nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_adm_router.py
python
SecretConfig.create_dict
(self)
assign the correct properties for a secret dict
assign the correct properties for a secret dict
[ "assign", "the", "correct", "properties", "for", "a", "secret", "dict" ]
def create_dict(self): ''' assign the correct properties for a secret dict ''' self.data['apiVersion'] = 'v1' self.data['kind'] = 'Secret' self.data['type'] = self.type self.data['metadata'] = {} self.data['metadata']['name'] = self.name self.data['metadata']['namespace'] = self.namespace self.data['data'] = {} if self.secrets: for key, value in self.secrets.items(): self.data['data'][key] = value if self.annotations: self.data['metadata']['annotations'] = self.annotations
[ "def", "create_dict", "(", "self", ")", ":", "self", ".", "data", "[", "'apiVersion'", "]", "=", "'v1'", "self", ".", "data", "[", "'kind'", "]", "=", "'Secret'", "self", ".", "data", "[", "'type'", "]", "=", "self", ".", "type", "self", ".", "data...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_adm_router.py#L2303-L2316
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/idlelib/CallTipWindow.py
python
_calltip_window
(parent)
[]
def _calltip_window(parent): # htest # from Tkinter import Toplevel, Text, LEFT, BOTH top = Toplevel(parent) top.title("Test calltips") top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200, parent.winfo_rooty() + 150)) text = Text(top) text.pack(side=LEFT, fill=BOTH, expand=1) text.insert("insert", "string.split") top.update() calltip = CallTip(text) def calltip_show(event): calltip.showtip("(s=Hello world)", "insert", "end") def calltip_hide(event): calltip.hidetip() text.event_add("<<calltip-show>>", "(") text.event_add("<<calltip-hide>>", ")") text.bind("<<calltip-show>>", calltip_show) text.bind("<<calltip-hide>>", calltip_hide) text.focus_set()
[ "def", "_calltip_window", "(", "parent", ")", ":", "# htest #", "from", "Tkinter", "import", "Toplevel", ",", "Text", ",", "LEFT", ",", "BOTH", "top", "=", "Toplevel", "(", "parent", ")", "top", ".", "title", "(", "\"Test calltips\"", ")", "top", ".", "g...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/idlelib/CallTipWindow.py#L136-L157
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/evaluation/metrics/classification_metric.py
python
BiClassPrecision.compute_metric_from_confusion_mat
(self, confusion_mat, formatted=True, impute_val=1.0)
[]
def compute_metric_from_confusion_mat(self, confusion_mat, formatted=True, impute_val=1.0): numerator = confusion_mat['tp'] denominator = (confusion_mat['tp'] + confusion_mat['fp']) zero_indexes = (denominator == 0) denominator[zero_indexes] = 1 precision_scores = numerator / denominator precision_scores[zero_indexes] = impute_val # impute_val is for prettifying when drawing pr curves if formatted: score_formatted = [[0, i] for i in precision_scores] return score_formatted else: return precision_scores
[ "def", "compute_metric_from_confusion_mat", "(", "self", ",", "confusion_mat", ",", "formatted", "=", "True", ",", "impute_val", "=", "1.0", ")", ":", "numerator", "=", "confusion_mat", "[", "'tp'", "]", "denominator", "=", "(", "confusion_mat", "[", "'tp'", "...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/evaluation/metrics/classification_metric.py#L304-L316
zopefoundation/Zope
ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb
src/Products/PageTemplates/ZopePageTemplate.py
python
ZopePageTemplate.ZScriptHTML_tryParams
(self)
return []
Parameters to test the script with.
Parameters to test the script with.
[ "Parameters", "to", "test", "the", "script", "with", "." ]
def ZScriptHTML_tryParams(self): """Parameters to test the script with.""" return []
[ "def", "ZScriptHTML_tryParams", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/Products/PageTemplates/ZopePageTemplate.py#L210-L212
XiaoMi/minos
164454a0804fb7eb7e14052327bdd4d5572c2697
client/deploy_utils.py
python
get_local_package_path_general
(path, artifact, version)
return ("%s/%s-%s.tar.gz" % (path, artifact, version))
Get the local tarball path of the package of specified artifact and version @param path the base path of the tarball @param artifact the artifact of the package @param version the version of the package @return string the full path of the tarball Note: This method is for internal use, users shouldn't call it directly. Users who want to obtain the local package path should call get_local_package_path().
Get the local tarball path of the package of specified artifact and version
[ "Get", "the", "local", "tarball", "path", "of", "the", "package", "of", "specified", "artifact", "and", "version" ]
def get_local_package_path_general(path, artifact, version): ''' Get the local tarball path of the package of specified artifact and version @param path the base path of the tarball @param artifact the artifact of the package @param version the version of the package @return string the full path of the tarball Note: This method is for internal use, users shouldn't call it directly. Users who want to obtain the local package path should call get_local_package_path(). ''' return ("%s/%s-%s.tar.gz" % (path, artifact, version))
[ "def", "get_local_package_path_general", "(", "path", ",", "artifact", ",", "version", ")", ":", "return", "(", "\"%s/%s-%s.tar.gz\"", "%", "(", "path", ",", "artifact", ",", "version", ")", ")" ]
https://github.com/XiaoMi/minos/blob/164454a0804fb7eb7e14052327bdd4d5572c2697/client/deploy_utils.py#L83-L96
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router_without_checks.py
python
ApiCallRouterWithoutChecks.GrantClientApproval
(self, args, context=None)
return api_user.ApiGrantClientApprovalHandler()
[]
def GrantClientApproval(self, args, context=None): return api_user.ApiGrantClientApprovalHandler()
[ "def", "GrantClientApproval", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "return", "api_user", ".", "ApiGrantClientApprovalHandler", "(", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router_without_checks.py#L397-L398
xiadingZ/video-caption.pytorch
0597647c9f1f756202ba7ff9898ad0a26847480f
coco-caption/pycocotools/cocoeval.py
python
COCOeval.accumulate
(self, p = None)
Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None
Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None
[ "Accumulate", "per", "image", "evaluation", "results", "and", "store", "the", "result", "in", "self", ".", "eval", ":", "param", "p", ":", "input", "params", "for", "evaluation", ":", "return", ":", "None" ]
def accumulate(self, p = None): ''' Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None ''' print('Accumulating evaluation results...') tic = time.time() if not self.evalImgs: print('Please run evaluate() first') # allows input customized parameters if p is None: p = self.params p.catIds = p.catIds if p.useCats == 1 else [-1] T = len(p.iouThrs) R = len(p.recThrs) K = len(p.catIds) if p.useCats else 1 A = len(p.areaRng) M = len(p.maxDets) precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories recall = -np.ones((T,K,A,M)) scores = -np.ones((T,R,K,A,M)) # create dictionary for future indexing _pe = self._paramsEval catIds = _pe.catIds if _pe.useCats else [-1] setK = set(catIds) setA = set(map(tuple, _pe.areaRng)) setM = set(_pe.maxDets) setI = set(_pe.imgIds) # get inds to evaluate k_list = [n for n, k in enumerate(p.catIds) if k in setK] m_list = [m for n, m in enumerate(p.maxDets) if m in setM] a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA] i_list = [n for n, i in enumerate(p.imgIds) if i in setI] I0 = len(_pe.imgIds) A0 = len(_pe.areaRng) # retrieve E at each category, area range, and max number of detections for k, k0 in enumerate(k_list): Nk = k0*A0*I0 for a, a0 in enumerate(a_list): Na = a0*I0 for m, maxDet in enumerate(m_list): E = [self.evalImgs[Nk + Na + i] for i in i_list] E = [e for e in E if not e is None] if len(E) == 0: continue dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E]) # different sorting method generates slightly different results. # mergesort is used to be consistent as Matlab implementation. inds = np.argsort(-dtScores, kind='mergesort') dtScoresSorted = dtScores[inds] dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds] dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds] gtIg = np.concatenate([e['gtIgnore'] for e in E]) npig = np.count_nonzero(gtIg==0 ) if npig == 0: continue tps = np.logical_and( dtm, np.logical_not(dtIg) ) fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) ) tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float) fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float) for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)): tp = np.array(tp) fp = np.array(fp) nd = len(tp) rc = tp / npig pr = tp / (fp+tp+np.spacing(1)) q = np.zeros((R,)) ss = np.zeros((R,)) if nd: recall[t,k,a,m] = rc[-1] else: recall[t,k,a,m] = 0 # numpy is slow without cython optimization for accessing elements # use python array gets significant speed improvement pr = pr.tolist(); q = q.tolist() for i in range(nd-1, 0, -1): if pr[i] > pr[i-1]: pr[i-1] = pr[i] inds = np.searchsorted(rc, p.recThrs, side='left') try: for ri, pi in enumerate(inds): q[ri] = pr[pi] ss[ri] = dtScoresSorted[pi] except: pass precision[t,:,k,a,m] = np.array(q) scores[t,:,k,a,m] = np.array(ss) self.eval = { 'params': p, 'counts': [T, R, K, A, M], 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'precision': precision, 'recall': recall, 'scores': scores, } toc = time.time() print('DONE (t={:0.2f}s).'.format( toc-tic))
[ "def", "accumulate", "(", "self", ",", "p", "=", "None", ")", ":", "print", "(", "'Accumulating evaluation results...'", ")", "tic", "=", "time", ".", "time", "(", ")", "if", "not", "self", ".", "evalImgs", ":", "print", "(", "'Please run evaluate() first'",...
https://github.com/xiadingZ/video-caption.pytorch/blob/0597647c9f1f756202ba7ff9898ad0a26847480f/coco-caption/pycocotools/cocoeval.py#L316-L421
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/core/task.py
python
Task.Integer
(self, name, width=None, dims=None, signed=False, value=None)
return t
[]
def Integer(self, name, width=None, dims=None, signed=False, value=None): t = vtypes.Integer(width, dims, signed, value, name=name) self.variable[name] = t return t
[ "def", "Integer", "(", "self", ",", "name", ",", "width", "=", "None", ",", "dims", "=", "None", ",", "signed", "=", "False", ",", "value", "=", "None", ")", ":", "t", "=", "vtypes", ".", "Integer", "(", "width", ",", "dims", ",", "signed", ",", ...
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/core/task.py#L29-L32
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_serviceaccount.py
python
Yedit.exists
(self, path, value)
return entry == value
check if value exists at path
check if value exists at path
[ "check", "if", "value", "exists", "at", "path" ]
def exists(self, path, value): ''' check if value exists at path''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if isinstance(entry, list): if value in entry: return True return False elif isinstance(entry, dict): if isinstance(value, dict): rval = False for key, val in value.items(): if entry[key] != val: rval = False break else: rval = True return rval return value in entry return entry == value
[ "def", "exists", "(", "self", ",", "path", ",", "value", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separator", ")", "except", "KeyError", ":", "entry", "=", "None", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_serviceaccount.py#L494-L519
binaryage/drydrop
2f27e15befd247255d89f9120eeee44851b82c4a
dryapp/jinja2/ext.py
python
Extension.preprocess
(self, source, name, filename=None)
return source
This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source.
This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source.
[ "This", "method", "is", "called", "before", "the", "actual", "lexing", "and", "can", "be", "used", "to", "preprocess", "the", "source", ".", "The", "filename", "is", "optional", ".", "The", "return", "value", "must", "be", "the", "preprocessed", "source", ...
def preprocess(self, source, name, filename=None): """This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source. """ return source
[ "def", "preprocess", "(", "self", ",", "source", ",", "name", ",", "filename", "=", "None", ")", ":", "return", "source" ]
https://github.com/binaryage/drydrop/blob/2f27e15befd247255d89f9120eeee44851b82c4a/dryapp/jinja2/ext.py#L70-L75
Borda/pyImSegm
7584b40a8d5bba04d3bf46f540f22b5d923e4b03
experiments_ovary_detect/run_ovary_egg-segmentation.py
python
segment_active_contour
(img, centers)
return segm, centers, None
segmentation using acive contours :param ndarray img: input image / segmentation :param list(tuple(int,int)) centers: position of centres / seeds :return tuple(ndarray, list(tuple(int,int))): resulting segmentation, updated centres
segmentation using acive contours
[ "segmentation", "using", "acive", "contours" ]
def segment_active_contour(img, centers): """ segmentation using acive contours :param ndarray img: input image / segmentation :param list(tuple(int,int)) centers: position of centres / seeds :return tuple(ndarray, list(tuple(int,int))): resulting segmentation, updated centres """ logging.debug('segment: active_contour...') # http://scikit-image.org/docs/dev/auto_examples/edges/plot_active_contours.html segm = np.zeros(img.shape[:2]) img_smooth = ndimage.filters.gaussian_filter(img, 5) center_circles, _, _ = create_circle_center(img.shape[:2], centers) for i, snake in enumerate(center_circles): snake = segmentation.active_contour( img_smooth, snake.astype(float), alpha=0.015, beta=10, gamma=0.001, w_line=0.0, w_edge=1.0, max_px_move=1.0, max_iterations=2500, convergence=0.2 ) seg = np.zeros(segm.shape, dtype=bool) x, y = np.array(snake).transpose().tolist() # rr, cc = draw.polygon(x, y) seg[map(int, x), map(int, y)] = True seg = morphology.binary_dilation(seg, selem=morphology.disk(3)) bb_area = int((max(x) - min(x)) * (max(y) - min(y))) logging.debug('bounding box area: %d', bb_area) seg = morphology.remove_small_holes(seg, min_size=bb_area) segm[seg] = i + 1 return segm, centers, None
[ "def", "segment_active_contour", "(", "img", ",", "centers", ")", ":", "logging", ".", "debug", "(", "'segment: active_contour...'", ")", "# http://scikit-image.org/docs/dev/auto_examples/edges/plot_active_contours.html", "segm", "=", "np", ".", "zeros", "(", "img", ".", ...
https://github.com/Borda/pyImSegm/blob/7584b40a8d5bba04d3bf46f540f22b5d923e4b03/experiments_ovary_detect/run_ovary_egg-segmentation.py#L298-L332
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/datastore/datastore_query.py
python
Batcher.next
(self)
return self.next_batch(self.AT_LEAST_ONE)
Get the next batch. See .next_batch().
Get the next batch. See .next_batch().
[ "Get", "the", "next", "batch", ".", "See", ".", "next_batch", "()", "." ]
def next(self): """Get the next batch. See .next_batch().""" return self.next_batch(self.AT_LEAST_ONE)
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "next_batch", "(", "self", ".", "AT_LEAST_ONE", ")" ]
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/datastore/datastore_query.py#L3168-L3170
zvtvz/zvt
054bf8a3e7a049df7087c324fa87e8effbaf5bdc
src/zvt/factors/algorithm.py
python
intersect_ranges
(range_list)
return result
[]
def intersect_ranges(range_list): if len(range_list) == 1: return range_list[0] result = intersect(range_list[0], range_list[1]) for range_i in range_list[2:]: result = intersect(result, range_i) return result
[ "def", "intersect_ranges", "(", "range_list", ")", ":", "if", "len", "(", "range_list", ")", "==", "1", ":", "return", "range_list", "[", "0", "]", "result", "=", "intersect", "(", "range_list", "[", "0", "]", ",", "range_list", "[", "1", "]", ")", "...
https://github.com/zvtvz/zvt/blob/054bf8a3e7a049df7087c324fa87e8effbaf5bdc/src/zvt/factors/algorithm.py#L85-L92
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/views/debug.py
python
default_urlconf
(request)
return HttpResponse(t.render(c), content_type='text/html')
Create an empty URLconf 404 error response.
Create an empty URLconf 404 error response.
[ "Create", "an", "empty", "URLconf", "404", "error", "response", "." ]
def default_urlconf(request): "Create an empty URLconf 404 error response." t = Template(DEFAULT_URLCONF_TEMPLATE, name='Default URLconf template') c = Context({}) return HttpResponse(t.render(c), content_type='text/html')
[ "def", "default_urlconf", "(", "request", ")", ":", "t", "=", "Template", "(", "DEFAULT_URLCONF_TEMPLATE", ",", "name", "=", "'Default URLconf template'", ")", "c", "=", "Context", "(", "{", "}", ")", "return", "HttpResponse", "(", "t", ".", "render", "(", ...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/views/debug.py#L490-L494
kovidgoyal/calibre
2b41671370f2a9eb1109b9ae901ccf915f1bd0c8
src/calibre/ebooks/conversion/utils.py
python
HeuristicProcessor.punctuation_unwrap
(self, length, content, format)
return content
Unwraps lines based on line length and punctuation supports a range of html markup and text files the lookahead regex below is meant look for any non-full stop characters - punctuation characters which can be used as a full stop should *not* be added below - e.g. ?!“”. etc the reason for this is to prevent false positive wrapping. False positives are more difficult to detect than false negatives during a manual review of the doc This function intentionally leaves hyphenated content alone as that is handled by the dehyphenate routine in a separate step
Unwraps lines based on line length and punctuation supports a range of html markup and text files
[ "Unwraps", "lines", "based", "on", "line", "length", "and", "punctuation", "supports", "a", "range", "of", "html", "markup", "and", "text", "files" ]
def punctuation_unwrap(self, length, content, format): ''' Unwraps lines based on line length and punctuation supports a range of html markup and text files the lookahead regex below is meant look for any non-full stop characters - punctuation characters which can be used as a full stop should *not* be added below - e.g. ?!“”. etc the reason for this is to prevent false positive wrapping. False positives are more difficult to detect than false negatives during a manual review of the doc This function intentionally leaves hyphenated content alone as that is handled by the dehyphenate routine in a separate step ''' def style_unwrap(match): style_close = match.group('style_close') style_open = match.group('style_open') if style_open and style_close: return style_close+' '+style_open elif style_open and not style_close: return ' '+style_open elif not style_open and style_close: return style_close+' ' else: return ' ' # define the pieces of the regex # (?<!\&\w{4});) is a semicolon not part of an entity lookahead = "(?<=.{"+str(length)+r"}([a-zა-ჰäëïöüàèìòùáćéíĺóŕńśúýâêîôûçąężıãõñæøþðßěľščťžňďřů,:)\\IAß]|(?<!\&\w{4});))" em_en_lookahead = "(?<=.{"+str(length)+"}[\u2013\u2014])" soft_hyphen = "\xad" line_ending = "\\s*(?P<style_close></(span|[iub])>)?\\s*(</(p|div)>)?" blanklines = "\\s*(?P<up2threeblanks><(p|span|div)[^>]*>\\s*(<(p|span|div)[^>]*>\\s*</(span|p|div)>\\s*)</(span|p|div)>\\s*){0,3}\\s*" line_opening = "<(p|div)[^>]*>\\s*(?P<style_open><(span|[iub])[^>]*>)?\\s*" txt_line_wrap = "((\u0020|\u0009)*\n){1,4}" if format == 'txt': unwrap_regex = lookahead+txt_line_wrap em_en_unwrap_regex = em_en_lookahead+txt_line_wrap shy_unwrap_regex = soft_hyphen+txt_line_wrap else: unwrap_regex = lookahead+line_ending+blanklines+line_opening em_en_unwrap_regex = em_en_lookahead+line_ending+blanklines+line_opening shy_unwrap_regex = soft_hyphen+line_ending+blanklines+line_opening unwrap = re.compile("%s" % unwrap_regex, re.UNICODE) em_en_unwrap = re.compile("%s" % em_en_unwrap_regex, re.UNICODE) shy_unwrap = re.compile("%s" % shy_unwrap_regex, re.UNICODE) if format == 'txt': content = unwrap.sub(' ', content) content = em_en_unwrap.sub('', content) content = shy_unwrap.sub('', content) else: content = unwrap.sub(style_unwrap, content) content = em_en_unwrap.sub(style_unwrap, content) content = shy_unwrap.sub(style_unwrap, content) return content
[ "def", "punctuation_unwrap", "(", "self", ",", "length", ",", "content", ",", "format", ")", ":", "def", "style_unwrap", "(", "match", ")", ":", "style_close", "=", "match", ".", "group", "(", "'style_close'", ")", "style_open", "=", "match", ".", "group",...
https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/ebooks/conversion/utils.py#L341-L398
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_pvc.py
python
Yedit.read
(self)
return contents
read from file
read from file
[ "read", "from", "file" ]
def read(self): ''' read from file ''' # check if it exists if self.filename is None or not self.file_exists(): return None contents = None with open(self.filename) as yfd: contents = yfd.read() return contents
[ "def", "read", "(", "self", ")", ":", "# check if it exists", "if", "self", ".", "filename", "is", "None", "or", "not", "self", ".", "file_exists", "(", ")", ":", "return", "None", "contents", "=", "None", "with", "open", "(", "self", ".", "filename", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_pvc.py#L389-L399
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/util/sgd/torch/worker_group.py
python
WorkerGroupInterface.load_state_dict
(self, state_dict, blocking=False)
See TorchTrainer.load_state_dict.
See TorchTrainer.load_state_dict.
[ "See", "TorchTrainer", ".", "load_state_dict", "." ]
def load_state_dict(self, state_dict, blocking=False): """See TorchTrainer.load_state_dict.""" raise NotImplementedError
[ "def", "load_state_dict", "(", "self", ",", "state_dict", ",", "blocking", "=", "False", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/util/sgd/torch/worker_group.py#L57-L59
huntfx/MouseTracks
4dfab6386f9461be77cb19b54c9c498d74fb4ef6
mousetracks/utils/os/placeholders.py
python
read_env_var
(text)
return None
Detect if text is an environment variable and read it. Returns: Value/None if successful or not.
Detect if text is an environment variable and read it. Returns: Value/None if successful or not.
[ "Detect", "if", "text", "is", "an", "environment", "variable", "and", "read", "it", ".", "Returns", ":", "Value", "/", "None", "if", "successful", "or", "not", "." ]
def read_env_var(text): """Detect if text is an environment variable and read it. Returns: Value/None if successful or not. """ return None
[ "def", "read_env_var", "(", "text", ")", ":", "return", "None" ]
https://github.com/huntfx/MouseTracks/blob/4dfab6386f9461be77cb19b54c9c498d74fb4ef6/mousetracks/utils/os/placeholders.py#L16-L21
zhanlaoban/Transformers_for_Text_Classification
5e12b21616b29e445e11fe307948e5c55084bb0e
transformers/data/processors/glue.py
python
QqpProcessor.get_dev_examples
(self, data_dir)
return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
[ "def", "get_dev_examples", "(", "self", ",", "data_dir", ")", ":", "return", "self", ".", "_create_examples", "(", "self", ".", "_read_tsv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"dev.tsv\"", ")", ")", ",", "\"dev\"", ")" ]
https://github.com/zhanlaoban/Transformers_for_Text_Classification/blob/5e12b21616b29e445e11fe307948e5c55084bb0e/transformers/data/processors/glue.py#L372-L375
F5Networks/f5-ansible
d61253b0980eb0feab448fcb977e3b089d49b79a
ansible_collections/f5networks/f5_modules/plugins/module_utils/common.py
python
fq_name
(partition, value, sub_path='')
return value
Returns a 'Fully Qualified' name A BIG-IP expects most names of resources to be in a fully-qualified form. This means that both the simple name, and the partition need to be combined. The Ansible modules, however, can accept (as names for several resources) their name in the FQ format. This becomes an issue when the FQ name and the partition are both specified as separate values. Consider the following examples. # Name not FQ name: foo partition: Common # Name FQ name: /Common/foo partition: Common This method will rectify the above situation and will, in both cases, return the following for name. /Common/foo Args: partition (string): The partition that you would want attached to the name if the name has no partition. value (string): The name that you want to attach a partition to. This value will be returned unchanged if it has a partition attached to it already. sub_path (string): The sub path element. If defined the sub_path will be inserted between partition and value. This will also work on FQ names. Returns: string: The fully qualified name, given the input parameters.
Returns a 'Fully Qualified' name
[ "Returns", "a", "Fully", "Qualified", "name" ]
def fq_name(partition, value, sub_path=''): """Returns a 'Fully Qualified' name A BIG-IP expects most names of resources to be in a fully-qualified form. This means that both the simple name, and the partition need to be combined. The Ansible modules, however, can accept (as names for several resources) their name in the FQ format. This becomes an issue when the FQ name and the partition are both specified as separate values. Consider the following examples. # Name not FQ name: foo partition: Common # Name FQ name: /Common/foo partition: Common This method will rectify the above situation and will, in both cases, return the following for name. /Common/foo Args: partition (string): The partition that you would want attached to the name if the name has no partition. value (string): The name that you want to attach a partition to. This value will be returned unchanged if it has a partition attached to it already. sub_path (string): The sub path element. If defined the sub_path will be inserted between partition and value. This will also work on FQ names. Returns: string: The fully qualified name, given the input parameters. """ if value is not None and sub_path == '': try: int(value) return '/{0}/{1}'.format(partition, value) except (ValueError, TypeError): if not value.startswith('/'): return '/{0}/{1}'.format(partition, value) if value is not None and sub_path != '': try: int(value) return '/{0}/{1}/{2}'.format(partition, sub_path, value) except (ValueError, TypeError): if value.startswith('/'): dummy, partition, name = value.split('/') return '/{0}/{1}/{2}'.format(partition, sub_path, name) if not value.startswith('/'): return '/{0}/{1}/{2}'.format(partition, sub_path, value) return value
[ "def", "fq_name", "(", "partition", ",", "value", ",", "sub_path", "=", "''", ")", ":", "if", "value", "is", "not", "None", "and", "sub_path", "==", "''", ":", "try", ":", "int", "(", "value", ")", "return", "'/{0}/{1}'", ".", "format", "(", "partiti...
https://github.com/F5Networks/f5-ansible/blob/d61253b0980eb0feab448fcb977e3b089d49b79a/ansible_collections/f5networks/f5_modules/plugins/module_utils/common.py#L95-L150
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/converter/subConverters.py
python
ConverterNoteworthy.parseData
(self, nwcData)
r'''Open Noteworthy data from a string or list >>> nwcData = ('!NoteWorthyComposer(2.0)\n|AddStaff\n|Clef|' + ... 'Type:Treble\n|Note|Dur:Whole|Pos:1^') >>> c = converter.subConverters.ConverterNoteworthy() >>> c.parseData(nwcData) >>> c.stream.show('text') {0.0} <music21.stream.Part ...> {0.0} <music21.stream.Measure 0 offset=0.0> {0.0} <music21.clef.TrebleClef> {0.0} <music21.note.Note C>
r'''Open Noteworthy data from a string or list
[ "r", "Open", "Noteworthy", "data", "from", "a", "string", "or", "list" ]
def parseData(self, nwcData): # noinspection PyShadowingNames r'''Open Noteworthy data from a string or list >>> nwcData = ('!NoteWorthyComposer(2.0)\n|AddStaff\n|Clef|' + ... 'Type:Treble\n|Note|Dur:Whole|Pos:1^') >>> c = converter.subConverters.ConverterNoteworthy() >>> c.parseData(nwcData) >>> c.stream.show('text') {0.0} <music21.stream.Part ...> {0.0} <music21.stream.Measure 0 offset=0.0> {0.0} <music21.clef.TrebleClef> {0.0} <music21.note.Note C> ''' from music21.noteworthy import translate as noteworthyTranslate self.stream = noteworthyTranslate.NoteworthyTranslator().parseString(nwcData)
[ "def", "parseData", "(", "self", ",", "nwcData", ")", ":", "# noinspection PyShadowingNames", "from", "music21", ".", "noteworthy", "import", "translate", "as", "noteworthyTranslate", "self", ".", "stream", "=", "noteworthyTranslate", ".", "NoteworthyTranslator", "(",...
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/converter/subConverters.py#L773-L788
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/parser/pattern/nodes/base.py
python
MultiValueDict.remove
(self, key, value)
[]
def remove(self, key, value): if key in self: if value in self[key]: self[key].remove(value) if len(self[key]) == 0: del self[key]
[ "def", "remove", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ":", "if", "value", "in", "self", "[", "key", "]", ":", "self", "[", "key", "]", ".", "remove", "(", "value", ")", "if", "len", "(", "self", "[", "ke...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/parser/pattern/nodes/base.py#L32-L38
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/lib2to3/fixer_util.py
python
ArgList
(args, lparen=LParen(), rparen=RParen())
return node
A parenthesised argument list, used by Call()
A parenthesised argument list, used by Call()
[ "A", "parenthesised", "argument", "list", "used", "by", "Call", "()" ]
def ArgList(args, lparen=LParen(), rparen=RParen()): """A parenthesised argument list, used by Call()""" node = Node(syms.trailer, [lparen.clone(), rparen.clone()]) if args: node.insert_child(1, Node(syms.arglist, args)) return node
[ "def", "ArgList", "(", "args", ",", "lparen", "=", "LParen", "(", ")", ",", "rparen", "=", "RParen", "(", ")", ")", ":", "node", "=", "Node", "(", "syms", ".", "trailer", ",", "[", "lparen", ".", "clone", "(", ")", ",", "rparen", ".", "clone", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/lib2to3/fixer_util.py#L54-L59
Blosc/bloscpack
5efdadf5b6f61e995df1817943afb9629ce28c89
bloscpack/append.py
python
append_fp
(original_fp, new_content_fp, new_size, blosc_args=None)
return nchunks
Append from a file pointer to a file pointer. Parameters ---------- original : file_like the original file_pointer new_content : str the file pointer for the data to be appended new_size : int the size of the new_content blosc_args : dict the blosc_args Returns ------- nchunks_written : int the total number of new chunks written to the file Notes ----- The blosc_args argument can be supplied if different blosc arguments are desired.
Append from a file pointer to a file pointer.
[ "Append", "from", "a", "file", "pointer", "to", "a", "file", "pointer", "." ]
def append_fp(original_fp, new_content_fp, new_size, blosc_args=None): """ Append from a file pointer to a file pointer. Parameters ---------- original : file_like the original file_pointer new_content : str the file pointer for the data to be appended new_size : int the size of the new_content blosc_args : dict the blosc_args Returns ------- nchunks_written : int the total number of new chunks written to the file Notes ----- The blosc_args argument can be supplied if different blosc arguments are desired. """ bloscpack_header, metadata, metadata_header, offsets = \ _read_beginning(original_fp) checksum_impl = bloscpack_header.checksum_impl if not offsets: raise RuntimeError('Appending to a file without offsets ' 'is not yet supported') if blosc_args is None: blosc_args = dict(zip(BLOSC_ARGS, [None] * len(BLOSC_ARGS))) # handle blosc_args if blosc_args['typesize'] is None: if bloscpack_header.typesize == -1: raise NonUniformTypesize('Non uniform type size, ' 'can not append to file.') else: # use the typesize from the bloscpack header blosc_args['typesize'] = bloscpack_header.typesize if blosc_args['clevel'] is None: # use the default blosc_args['clevel'] = DEFAULT_CLEVEL if blosc_args['shuffle'] is None: blosc_args['shuffle'] = DEFAULT_SHUFFLE if blosc_args['cname'] is None: blosc_args['cname'] = DEFAULT_CNAME _check_blosc_args(blosc_args) offsets_pos = (BLOSCPACK_HEADER_LENGTH + (METADATA_HEADER_LENGTH + metadata_header['max_meta_size'] + CHECKSUMS_LOOKUP[metadata_header['meta_checksum']].size if metadata is not None else 0)) # seek to the final offset original_fp.seek(offsets[-1], 0) # decompress the last chunk compressed, blosc_header, digest = _read_compressed_chunk_fp(original_fp, checksum_impl) # TODO check digest decompressed = blosc.decompress(compressed) # figure out how many bytes we need to read to rebuild the last chunk ultimo_length = len(decompressed) bytes_to_read = bloscpack_header.chunk_size - ultimo_length if new_size <= bytes_to_read: # special case # must squeeze data into last chunk fill_up = new_content_fp.read(new_size) # seek back to the position of the original last chunk original_fp.seek(offsets[-1], 0) # write the chunk that has been filled up compressed = _compress_chunk_str(decompressed + fill_up, blosc_args) digest = checksum_impl(compressed) _write_compressed_chunk(original_fp, compressed, digest) # return 0 to indicate that no new chunks have been written # build the new header bloscpack_header.last_chunk += new_size # create the new header raw_bloscpack_header = bloscpack_header.encode() original_fp.seek(0) original_fp.write(raw_bloscpack_header) return 0 # figure out what is left over new_new_size = new_size - bytes_to_read # read those bytes fill_up = new_content_fp.read(bytes_to_read) # figure out how many chunks we will need nchunks, chunk_size, last_chunk_size = \ calculate_nchunks(new_new_size, chunk_size=bloscpack_header.chunk_size) # make sure that we actually have that kind of space if nchunks > bloscpack_header.max_app_chunks: raise NotEnoughSpace('not enough space') # seek back to the position of the original last chunk original_fp.seek(offsets[-1], 0) # write the chunk that has been filled up compressed = _compress_chunk_str(decompressed + fill_up, blosc_args) digest = checksum_impl(compressed) _write_compressed_chunk(original_fp, compressed, digest) # append to the original file, again original_fp should be adequately # positioned sink = CompressedFPSink(original_fp) sink.configure(blosc_args, bloscpack_header) # allocate new offsets sink.offset_storage = list(itertools.repeat(-1, nchunks)) # read from the new input file, new_content_fp should be adequately # positioned source = PlainFPSource(new_content_fp) source.configure(chunk_size, last_chunk_size, nchunks) # read, compress, write loop for i, chunk in enumerate(source): log.debug("Handle chunk '%d' %s" % (i,'(last)' if i == nchunks -1 else '')) compressed = _compress_chunk_str(chunk, blosc_args) sink.put(i, compressed) # build the new header bloscpack_header.last_chunk = last_chunk_size bloscpack_header.nchunks += nchunks bloscpack_header.max_app_chunks -= nchunks # create the new header raw_bloscpack_header = bloscpack_header.encode() original_fp.seek(0) original_fp.write(raw_bloscpack_header) # write the new offsets, but only those that changed original_fp.seek(offsets_pos) # FIXME: write only those that changed _write_offsets(sink.output_fp, offsets + sink.offset_storage) return nchunks
[ "def", "append_fp", "(", "original_fp", ",", "new_content_fp", ",", "new_size", ",", "blosc_args", "=", "None", ")", ":", "bloscpack_header", ",", "metadata", ",", "metadata_header", ",", "offsets", "=", "_read_beginning", "(", "original_fp", ")", "checksum_impl",...
https://github.com/Blosc/bloscpack/blob/5efdadf5b6f61e995df1817943afb9629ce28c89/bloscpack/append.py#L62-L191
CheckPointSW/Karta
b845928487b50a5b41acd532ae0399177a4356aa
src/thumbs_up/analyzers/analyzer.py
python
Analyzer.cleanPtr
(self, ptr_ea)
return ptr_ea
Clean a pointer from the code type metadata. Args: ptr_ea (int): code type annotated effective address Return Value: dest address, stripped from the code type annotations
Clean a pointer from the code type metadata.
[ "Clean", "a", "pointer", "from", "the", "code", "type", "metadata", "." ]
def cleanPtr(self, ptr_ea): """Clean a pointer from the code type metadata. Args: ptr_ea (int): code type annotated effective address Return Value: dest address, stripped from the code type annotations """ # By default, there is only the default code type return ptr_ea
[ "def", "cleanPtr", "(", "self", ",", "ptr_ea", ")", ":", "# By default, there is only the default code type", "return", "ptr_ea" ]
https://github.com/CheckPointSW/Karta/blob/b845928487b50a5b41acd532ae0399177a4356aa/src/thumbs_up/analyzers/analyzer.py#L219-L229
yoyoyohamapi/mit-ml
bafefeec9a30b80bf0c29c246e517519d69b0f20
neural_network/nn.py
python
gradientDescent
(Thetas, X, y, alpha, theLambda)
return J, Thetas
梯度下降 Args: X 样本 y 标签 alpha 学习率 theLambda 正规化参数 Returns: J 预测代价 Thetas 更新后的各层权值矩阵
梯度下降
[ "梯度下降" ]
def gradientDescent(Thetas, X, y, alpha, theLambda): """梯度下降 Args: X 样本 y 标签 alpha 学习率 theLambda 正规化参数 Returns: J 预测代价 Thetas 更新后的各层权值矩阵 """ # 样本数,特征数 m, n = X.shape # 前向传播计算各个神经元的激活值 a = fp(Thetas, X) # 反向传播计算梯度增量 D = bp(Thetas, a, y, theLambda) # 计算预测代价 J = computeCost(Thetas,y,theLambda,a=a) # 更新权值 Thetas = updateThetas(m, Thetas, D, alpha, theLambda) if np.isnan(J): J = np.inf return J, Thetas
[ "def", "gradientDescent", "(", "Thetas", ",", "X", ",", "y", ",", "alpha", ",", "theLambda", ")", ":", "# 样本数,特征数", "m", ",", "n", "=", "X", ".", "shape", "# 前向传播计算各个神经元的激活值", "a", "=", "fp", "(", "Thetas", ",", "X", ")", "# 反向传播计算梯度增量", "D", "=", ...
https://github.com/yoyoyohamapi/mit-ml/blob/bafefeec9a30b80bf0c29c246e517519d69b0f20/neural_network/nn.py#L236-L260
ladybug-tools/honeybee-legacy
bd62af4862fe022801fb87dbc8794fdf1dff73a9
src/Honeybee_Honeybee.py
python
EPZone.getCurrentLoads
(self, returnDictionary = False, component = None)
[]
def getCurrentLoads(self, returnDictionary = False, component = None): # assign the default is there is no schedule assigned if not self.isLoadsAssigned: self.assignLoadsBasedOnProgram(component) if not returnDictionary: report = " Internal Loads [SI]:\n" + \ "EquipmentsLoadPerArea: " + "%.6f"%self.equipmentLoadPerArea + "\n" + \ "infiltrationRatePerArea: " + "%.6f"%self.infiltrationRatePerArea + "\n" + \ "lightingDensityPerArea: " + "%.6f"%self.lightingDensityPerArea + "\n" + \ "numOfPeoplePerArea: " + "%.6f"%self.numOfPeoplePerArea + "\n" + \ "ventilationPerPerson: " + "%.6f"%self.ventilationPerPerson + "\n" + \ "ventilationPerArea: " + "%.6f"%self.ventilationPerArea + "\n" + \ "recircAirPerArea: " + "%.6f"%self.recirculatedAirPerArea + "." return report else: loadsDict = {"EquipmentsLoadPerArea" : "%.4f"%self.equipmentLoadPerArea, "infiltrationRatePerArea" : "%.4f"%self.infiltrationRatePerArea, "lightingDensityPerArea" : "%.4f"%self.lightingDensityPerArea, "numOfPeoplePerArea" : "%.4f"%self.numOfPeoplePerArea, "ventilationPerArea" : "%.4f"%self.ventilationPerArea, "ventilationPerPerson" : "%.4f"%self.ventilationPerPerson} return loadsDict
[ "def", "getCurrentLoads", "(", "self", ",", "returnDictionary", "=", "False", ",", "component", "=", "None", ")", ":", "# assign the default is there is no schedule assigned", "if", "not", "self", ".", "isLoadsAssigned", ":", "self", ".", "assignLoadsBasedOnProgram", ...
https://github.com/ladybug-tools/honeybee-legacy/blob/bd62af4862fe022801fb87dbc8794fdf1dff73a9/src/Honeybee_Honeybee.py#L5245-L5272
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-0.96/django/core/handlers/wsgi.py
python
safe_copyfileobj
(fsrc, fdst, length=16*1024, size=0)
A version of shutil.copyfileobj that will not read more than 'size' bytes. This makes it safe from clients sending more than CONTENT_LENGTH bytes of data in the body.
A version of shutil.copyfileobj that will not read more than 'size' bytes. This makes it safe from clients sending more than CONTENT_LENGTH bytes of data in the body.
[ "A", "version", "of", "shutil", ".", "copyfileobj", "that", "will", "not", "read", "more", "than", "size", "bytes", ".", "This", "makes", "it", "safe", "from", "clients", "sending", "more", "than", "CONTENT_LENGTH", "bytes", "of", "data", "in", "the", "bod...
def safe_copyfileobj(fsrc, fdst, length=16*1024, size=0): """ A version of shutil.copyfileobj that will not read more than 'size' bytes. This makes it safe from clients sending more than CONTENT_LENGTH bytes of data in the body. """ if not size: return while size > 0: buf = fsrc.read(min(length, size)) if not buf: break fdst.write(buf) size -= len(buf)
[ "def", "safe_copyfileobj", "(", "fsrc", ",", "fdst", ",", "length", "=", "16", "*", "1024", ",", "size", "=", "0", ")", ":", "if", "not", "size", ":", "return", "while", "size", ">", "0", ":", "buf", "=", "fsrc", ".", "read", "(", "min", "(", "...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/core/handlers/wsgi.py#L58-L71
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/ldap3/strategy/mockBase.py
python
MockBaseStrategy.evaluate_filter_node
(self, node, candidates)
After evaluation each 2 sets are added to each MATCH node, one for the matched object and one for unmatched object. The unmatched object set is needed if a superior node is a NOT that reverts the evaluation. The BOOLEAN nodes mix the sets returned by the MATCH nodes
After evaluation each 2 sets are added to each MATCH node, one for the matched object and one for unmatched object. The unmatched object set is needed if a superior node is a NOT that reverts the evaluation. The BOOLEAN nodes mix the sets returned by the MATCH nodes
[ "After", "evaluation", "each", "2", "sets", "are", "added", "to", "each", "MATCH", "node", "one", "for", "the", "matched", "object", "and", "one", "for", "unmatched", "object", ".", "The", "unmatched", "object", "set", "is", "needed", "if", "a", "superior"...
def evaluate_filter_node(self, node, candidates): """After evaluation each 2 sets are added to each MATCH node, one for the matched object and one for unmatched object. The unmatched object set is needed if a superior node is a NOT that reverts the evaluation. The BOOLEAN nodes mix the sets returned by the MATCH nodes""" node.matched = set() node.unmatched = set() if node.elements: for element in node.elements: self.evaluate_filter_node(element, candidates) if node.tag == ROOT: return node.elements[0].matched elif node.tag == AND: first_element = node.elements[0] node.matched.update(first_element.matched) node.unmatched.update(first_element.unmatched) for element in node.elements[1:]: node.matched.intersection_update(element.matched) node.unmatched.intersection_update(element.unmatched) elif node.tag == OR: for element in node.elements: node.matched.update(element.matched) node.unmatched.update(element.unmatched) elif node.tag == NOT: node.matched = node.elements[0].unmatched node.unmatched = node.elements[0].matched elif node.tag == MATCH_GREATER_OR_EQUAL: attr_name = node.assertion['attr'] attr_value = node.assertion['value'] for candidate in candidates: if attr_name in self.connection.server.dit[candidate]: for value in self.connection.server.dit[candidate][attr_name]: if value.isdigit() and attr_value.isdigit(): # int comparison if int(value) >= int(attr_value): node.matched.add(candidate) else: node.unmatched.add(candidate) else: if to_unicode(value, SERVER_ENCODING).lower() >= to_unicode(attr_value, SERVER_ENCODING).lower(): # case insensitive string comparison node.matched.add(candidate) else: node.unmatched.add(candidate) elif node.tag == MATCH_LESS_OR_EQUAL: attr_name = node.assertion['attr'] attr_value = node.assertion['value'] for candidate in candidates: if attr_name in self.connection.server.dit[candidate]: for value in self.connection.server.dit[candidate][attr_name]: if value.isdigit() and attr_value.isdigit(): # int comparison if int(value) <= int(attr_value): node.matched.add(candidate) else: node.unmatched.add(candidate) else: if to_unicode(value, SERVER_ENCODING).lower() <= to_unicode(attr_value, SERVER_ENCODING).lower(): # case insentive string comparison node.matched.add(candidate) else: node.unmatched.add(candidate) elif node.tag == MATCH_EXTENSIBLE: self.connection.last_error = 'Extensible match not allowed in Mock strategy' if log_enabled(ERROR): log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection) raise LDAPDefinitionError(self.connection.last_error) elif node.tag == MATCH_PRESENT: attr_name = node.assertion['attr'] for candidate in candidates: if attr_name in self.connection.server.dit[candidate]: node.matched.add(candidate) else: node.unmatched.add(candidate) elif node.tag == MATCH_SUBSTRING: attr_name = node.assertion['attr'] # rebuild the original substring filter if 'initial' in node.assertion and node.assertion['initial'] is not None: substring_filter = re.escape(to_unicode(node.assertion['initial'], SERVER_ENCODING)) else: substring_filter = '' if 'any' in node.assertion and node.assertion['any'] is not None: for middle in node.assertion['any']: substring_filter += '.*' + re.escape(to_unicode(middle, SERVER_ENCODING)) if 'final' in node.assertion and node.assertion['final'] is not None: substring_filter += '.*' + re.escape(to_unicode(node.assertion['final'], SERVER_ENCODING)) if substring_filter and not node.assertion.get('any', None) and not node.assertion.get('final', None): # only initial, adds .* substring_filter += '.*' regex_filter = re.compile(substring_filter, flags=re.UNICODE | re.IGNORECASE) # unicode AND ignorecase for candidate in candidates: if attr_name in self.connection.server.dit[candidate]: for value in self.connection.server.dit[candidate][attr_name]: if regex_filter.match(to_unicode(value, SERVER_ENCODING)): node.matched.add(candidate) else: node.unmatched.add(candidate) else: node.unmatched.add(candidate) elif node.tag == MATCH_EQUAL or node.tag == MATCH_APPROX: attr_name = node.assertion['attr'] attr_value = node.assertion['value'] for candidate in candidates: # if attr_name in self.connection.server.dit[candidate] and attr_value in self.connection.server.dit[candidate][attr_name]: if attr_name in self.connection.server.dit[candidate] and self.equal(candidate, attr_name, attr_value): node.matched.add(candidate) else: node.unmatched.add(candidate)
[ "def", "evaluate_filter_node", "(", "self", ",", "node", ",", "candidates", ")", ":", "node", ".", "matched", "=", "set", "(", ")", "node", ".", "unmatched", "=", "set", "(", ")", "if", "node", ".", "elements", ":", "for", "element", "in", "node", "....
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/ldap3/strategy/mockBase.py#L744-L852
allenai/allennlp
a3d71254fcc0f3615910e9c3d48874515edf53e0
allennlp/confidence_checks/task_checklists/utils.py
python
toggle_punctuation
(data: str)
return ret
If `data` contains any punctuation, it is removed. Otherwise, a `.` is added to the string. Returns a list of strings. Eg. `data` = "This was great!" Returns ["This was great", "This was great."] `data` = "The movie was good" Returns ["The movie was good."]
If `data` contains any punctuation, it is removed. Otherwise, a `.` is added to the string. Returns a list of strings.
[ "If", "data", "contains", "any", "punctuation", "it", "is", "removed", ".", "Otherwise", "a", ".", "is", "added", "to", "the", "string", ".", "Returns", "a", "list", "of", "strings", "." ]
def toggle_punctuation(data: str) -> List[str]: """ If `data` contains any punctuation, it is removed. Otherwise, a `.` is added to the string. Returns a list of strings. Eg. `data` = "This was great!" Returns ["This was great", "This was great."] `data` = "The movie was good" Returns ["The movie was good."] """ s = strip_punctuation(data) ret = [] if s != data: ret.append(s) if s + "." != data: ret.append(s + ".") return ret
[ "def", "toggle_punctuation", "(", "data", ":", "str", ")", "->", "List", "[", "str", "]", ":", "s", "=", "strip_punctuation", "(", "data", ")", "ret", "=", "[", "]", "if", "s", "!=", "data", ":", "ret", ".", "append", "(", "s", ")", "if", "s", ...
https://github.com/allenai/allennlp/blob/a3d71254fcc0f3615910e9c3d48874515edf53e0/allennlp/confidence_checks/task_checklists/utils.py#L133-L152
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/totto/totto_parent_eval.py
python
_table_reader
(table_file)
Yields tables from the table file. Tables are parsed into a list of tuples with tokenized entries. Args: table_file: String filename.
Yields tables from the table file.
[ "Yields", "tables", "from", "the", "table", "file", "." ]
def _table_reader(table_file): """Yields tables from the table file. Tables are parsed into a list of tuples with tokenized entries. Args: table_file: String filename. """ with io.open(table_file, encoding="utf-8") as f: for line in f: entries = line.lower().split("\t") # pylint: disable=g-complex-comprehension table = [[ _normalize_text(member).split() for member in entry.split("|||") ] for entry in entries] yield table
[ "def", "_table_reader", "(", "table_file", ")", ":", "with", "io", ".", "open", "(", "table_file", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "entries", "=", "line", ".", "lower", "(", ")", ".", "split", ...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/totto/totto_parent_eval.py#L134-L149
aws/aws-cli
d697e0ed79fca0f853ce53efe1f83ee41a478134
awscli/customizations/s3/transferconfig.py
python
RuntimeConfig.build_config
(self, **kwargs)
return runtime_config
Create and convert a runtime config dictionary. This method will merge and convert S3 runtime configuration data into a single dictionary that can then be passed to classes that use this runtime config. :param kwargs: Any key in the ``DEFAULTS`` dict. :return: A dictionary of the merged and converted values.
Create and convert a runtime config dictionary.
[ "Create", "and", "convert", "a", "runtime", "config", "dictionary", "." ]
def build_config(self, **kwargs): """Create and convert a runtime config dictionary. This method will merge and convert S3 runtime configuration data into a single dictionary that can then be passed to classes that use this runtime config. :param kwargs: Any key in the ``DEFAULTS`` dict. :return: A dictionary of the merged and converted values. """ runtime_config = DEFAULTS.copy() if kwargs: runtime_config.update(kwargs) self._convert_human_readable_sizes(runtime_config) self._convert_human_readable_rates(runtime_config) self._validate_config(runtime_config) return runtime_config
[ "def", "build_config", "(", "self", ",", "*", "*", "kwargs", ")", ":", "runtime_config", "=", "DEFAULTS", ".", "copy", "(", ")", "if", "kwargs", ":", "runtime_config", ".", "update", "(", "kwargs", ")", "self", ".", "_convert_human_readable_sizes", "(", "r...
https://github.com/aws/aws-cli/blob/d697e0ed79fca0f853ce53efe1f83ee41a478134/awscli/customizations/s3/transferconfig.py#L45-L62
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/versioned_remote_process_group.py
python
VersionedRemoteProcessGroup.yield_duration
(self)
return self._yield_duration
Gets the yield_duration of this VersionedRemoteProcessGroup. When yielding, this amount of time must elapse before the remote process group is scheduled again. :return: The yield_duration of this VersionedRemoteProcessGroup. :rtype: str
Gets the yield_duration of this VersionedRemoteProcessGroup. When yielding, this amount of time must elapse before the remote process group is scheduled again.
[ "Gets", "the", "yield_duration", "of", "this", "VersionedRemoteProcessGroup", ".", "When", "yielding", "this", "amount", "of", "time", "must", "elapse", "before", "the", "remote", "process", "group", "is", "scheduled", "again", "." ]
def yield_duration(self): """ Gets the yield_duration of this VersionedRemoteProcessGroup. When yielding, this amount of time must elapse before the remote process group is scheduled again. :return: The yield_duration of this VersionedRemoteProcessGroup. :rtype: str """ return self._yield_duration
[ "def", "yield_duration", "(", "self", ")", ":", "return", "self", ".", "_yield_duration" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/versioned_remote_process_group.py#L293-L301
beeware/colosseum
cbf974be54fd7f6fddbe7285704cfaf7a866c5c5
src/colosseum/dimensions.py
python
Box.absolute_border_box_bottom
(self)
return ( self.__origin_top + self._content_top + self.content_height + self.padding_bottom + self.border_bottom_width )
[]
def absolute_border_box_bottom(self): return ( self.__origin_top + self._content_top + self.content_height + self.padding_bottom + self.border_bottom_width )
[ "def", "absolute_border_box_bottom", "(", "self", ")", ":", "return", "(", "self", ".", "__origin_top", "+", "self", ".", "_content_top", "+", "self", ".", "content_height", "+", "self", ".", "padding_bottom", "+", "self", ".", "border_bottom_width", ")" ]
https://github.com/beeware/colosseum/blob/cbf974be54fd7f6fddbe7285704cfaf7a866c5c5/src/colosseum/dimensions.py#L438-L444
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_cron_job_status.py
python
V1CronJobStatus.__init__
(self, active=None, last_schedule_time=None, last_successful_time=None, local_vars_configuration=None)
V1CronJobStatus - a model defined in OpenAPI
V1CronJobStatus - a model defined in OpenAPI
[ "V1CronJobStatus", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, active=None, last_schedule_time=None, last_successful_time=None, local_vars_configuration=None): # noqa: E501 """V1CronJobStatus - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._active = None self._last_schedule_time = None self._last_successful_time = None self.discriminator = None if active is not None: self.active = active if last_schedule_time is not None: self.last_schedule_time = last_schedule_time if last_successful_time is not None: self.last_successful_time = last_successful_time
[ "def", "__init__", "(", "self", ",", "active", "=", "None", ",", "last_schedule_time", "=", "None", ",", "last_successful_time", "=", "None", ",", "local_vars_configuration", "=", "None", ")", ":", "# noqa: E501", "# noqa: E501", "if", "local_vars_configuration", ...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_cron_job_status.py#L47-L63
MongoEngine/django-mongoengine
e8a75e8e5860545ecfbadaf1b1285495022bd7cb
django_mongoengine/mongo_auth/managers.py
python
get_user_document
()
return getattr(module, name[dot + 1:])
Get the user document class used for authentication. This is the class defined in settings.MONGOENGINE_USER_DOCUMENT, which defaults to `mongoengine.django.auth.User`.
Get the user document class used for authentication.
[ "Get", "the", "user", "document", "class", "used", "for", "authentication", "." ]
def get_user_document(): """Get the user document class used for authentication. This is the class defined in settings.MONGOENGINE_USER_DOCUMENT, which defaults to `mongoengine.django.auth.User`. """ name = MONGOENGINE_USER_DOCUMENT dot = name.rindex('.') module = import_module(name[:dot]) return getattr(module, name[dot + 1:])
[ "def", "get_user_document", "(", ")", ":", "name", "=", "MONGOENGINE_USER_DOCUMENT", "dot", "=", "name", ".", "rindex", "(", "'.'", ")", "module", "=", "import_module", "(", "name", "[", ":", "dot", "]", ")", "return", "getattr", "(", "module", ",", "nam...
https://github.com/MongoEngine/django-mongoengine/blob/e8a75e8e5860545ecfbadaf1b1285495022bd7cb/django_mongoengine/mongo_auth/managers.py#L15-L26
jkehler/awslambda-psycopg2
c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4
psycopg2-3.8/extras.py
python
ReplicationCursor.drop_replication_slot
(self, slot_name)
Drop streaming replication slot.
Drop streaming replication slot.
[ "Drop", "streaming", "replication", "slot", "." ]
def drop_replication_slot(self, slot_name): """Drop streaming replication slot.""" command = "DROP_REPLICATION_SLOT %s" % quote_ident(slot_name, self) self.execute(command)
[ "def", "drop_replication_slot", "(", "self", ",", "slot_name", ")", ":", "command", "=", "\"DROP_REPLICATION_SLOT %s\"", "%", "quote_ident", "(", "slot_name", ",", "self", ")", "self", ".", "execute", "(", "command", ")" ]
https://github.com/jkehler/awslambda-psycopg2/blob/c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4/psycopg2-3.8/extras.py#L571-L575
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/bdb.py
python
user_call
(self, frame, argument_list)
Called if we might stop in a function.
Called if we might stop in a function.
[ "Called", "if", "we", "might", "stop", "in", "a", "function", "." ]
def user_call(self, frame, argument_list): """Called if we might stop in a function.""" pass
[ "def", "user_call", "(", "self", ",", "frame", ",", "argument_list", ")", ":", "pass" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/bdb.py#L259-L261
ZhaoJ9014/High-Performance-Face-Recognition
aa8b240e34856d4a038198c8f73390d94ced2c6d
src/Pre-_and_post-processing/FaceAlign-Resize-w-Padding.PyTorch/box_utils.py
python
_preprocess
(img)
return img
Preprocessing step before feeding the network. Arguments: img: a float numpy array of shape [h, w, c]. Returns: a float numpy array of shape [1, c, h, w].
Preprocessing step before feeding the network.
[ "Preprocessing", "step", "before", "feeding", "the", "network", "." ]
def _preprocess(img): """Preprocessing step before feeding the network. Arguments: img: a float numpy array of shape [h, w, c]. Returns: a float numpy array of shape [1, c, h, w]. """ img = img.transpose((2, 0, 1)) img = np.expand_dims(img, 0) img = (img - 127.5)*0.0078125 return img
[ "def", "_preprocess", "(", "img", ")", ":", "img", "=", "img", ".", "transpose", "(", "(", "2", ",", "0", ",", "1", ")", ")", "img", "=", "np", ".", "expand_dims", "(", "img", ",", "0", ")", "img", "=", "(", "img", "-", "127.5", ")", "*", "...
https://github.com/ZhaoJ9014/High-Performance-Face-Recognition/blob/aa8b240e34856d4a038198c8f73390d94ced2c6d/src/Pre-_and_post-processing/FaceAlign-Resize-w-Padding.PyTorch/box_utils.py#L226-L238
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xl/metadata/_base.py
python
BaseFormat.load
(self)
Loads the tags from the file.
Loads the tags from the file.
[ "Loads", "the", "tags", "from", "the", "file", "." ]
def load(self): """ Loads the tags from the file. """ if self.MutagenType: try: self.mutagen = self.MutagenType(self.loc) except Exception: raise NotReadable
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "MutagenType", ":", "try", ":", "self", ".", "mutagen", "=", "self", ".", "MutagenType", "(", "self", ".", "loc", ")", "except", "Exception", ":", "raise", "NotReadable" ]
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xl/metadata/_base.py#L127-L135
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
option/ctp/ApiStruct.py
python
TransferQryDetailReq.__init__
(self, FutureAccount='')
[]
def __init__(self, FutureAccount=''): self.FutureAccount = 'AccountID'
[ "def", "__init__", "(", "self", ",", "FutureAccount", "=", "''", ")", ":", "self", ".", "FutureAccount", "=", "'AccountID'" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/option/ctp/ApiStruct.py#L2076-L2077
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
contrib/paramiko/paramiko/proxy.py
python
ProxyCommand.__init__
(self, command_line)
Create a new CommandProxy instance. The instance created by this class can be passed as an argument to the `.Transport` class. :param str command_line: the command that should be executed and used as the proxy.
Create a new CommandProxy instance. The instance created by this class can be passed as an argument to the `.Transport` class.
[ "Create", "a", "new", "CommandProxy", "instance", ".", "The", "instance", "created", "by", "this", "class", "can", "be", "passed", "as", "an", "argument", "to", "the", ".", "Transport", "class", "." ]
def __init__(self, command_line): """ Create a new CommandProxy instance. The instance created by this class can be passed as an argument to the `.Transport` class. :param str command_line: the command that should be executed and used as the proxy. """ self.cmd = shlsplit(command_line) self.process = Popen(self.cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0) self.timeout = None
[ "def", "__init__", "(", "self", ",", "command_line", ")", ":", "self", ".", "cmd", "=", "shlsplit", "(", "command_line", ")", "self", ".", "process", "=", "Popen", "(", "self", ".", "cmd", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", ...
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/contrib/paramiko/paramiko/proxy.py#L44-L55
nlpinaction/learning-nlp
d59fd75bdbbc0f4d1ef0d741065ab86639608924
chapter-10/seq2seq/main.py
python
Seq2seq.data_iter
(self, train_src, train_targets, batches, sample_num)
return {self.model.encoder_inputs: batch_inputs, self.model.encoder_inputs_length: batch_inputs_length, self.model.decoder_targets: batch_targets, self.model.decoder_targets_length: batch_targets_length, }
获取batch 最大长度为每个batch中句子的最大长度 并将数据作转换: [batch_size, time_steps] -> [time_steps, batch_size]
获取batch 最大长度为每个batch中句子的最大长度 并将数据作转换: [batch_size, time_steps] -> [time_steps, batch_size]
[ "获取batch", "最大长度为每个batch中句子的最大长度", "并将数据作转换", ":", "[", "batch_size", "time_steps", "]", "-", ">", "[", "time_steps", "batch_size", "]" ]
def data_iter(self, train_src, train_targets, batches, sample_num): ''' 获取batch 最大长度为每个batch中句子的最大长度 并将数据作转换: [batch_size, time_steps] -> [time_steps, batch_size] ''' batch_inputs = [] batch_targets = [] batch_inputs_length = [] batch_targets_length = [] # 随机样本 shuffle = np.random.randint(0, sample_num, batches) en_max_seq_length = max([len(train_src[i]) for i in shuffle]) de_max_seq_length = max([len(train_targets[i]) for i in shuffle]) for index in shuffle: _en = train_src[index] inputs_batch_major = np.zeros( shape=[en_max_seq_length], dtype=np.int32) # == PAD for seq in range(len(_en)): inputs_batch_major[seq] = _en[seq] batch_inputs.append(inputs_batch_major) batch_inputs_length.append(len(_en)) _de = train_targets[index] inputs_batch_major = np.zeros( shape=[de_max_seq_length], dtype=np.int32) # == PAD for seq in range(len(_de)): inputs_batch_major[seq] = _de[seq] batch_targets.append(inputs_batch_major) batch_targets_length.append(len(_de)) batch_inputs = np.array(batch_inputs).swapaxes(0, 1) batch_targets = np.array(batch_targets).swapaxes(0, 1) return {self.model.encoder_inputs: batch_inputs, self.model.encoder_inputs_length: batch_inputs_length, self.model.decoder_targets: batch_targets, self.model.decoder_targets_length: batch_targets_length, }
[ "def", "data_iter", "(", "self", ",", "train_src", ",", "train_targets", ",", "batches", ",", "sample_num", ")", ":", "batch_inputs", "=", "[", "]", "batch_targets", "=", "[", "]", "batch_inputs_length", "=", "[", "]", "batch_targets_length", "=", "[", "]", ...
https://github.com/nlpinaction/learning-nlp/blob/d59fd75bdbbc0f4d1ef0d741065ab86639608924/chapter-10/seq2seq/main.py#L71-L111
tensorflow/graphics
86997957324bfbdd85848daae989b4c02588faa0
tensorflow_graphics/rendering/opengl/rasterization_backend.py
python
rasterize
(vertices: type_alias.TensorLike, triangles: type_alias.TensorLike, view_projection_matrices: type_alias.TensorLike, image_size: Tuple[int, int], enable_cull_face: bool, num_layers: int, name: str = "rasterization_backend_rasterize")
Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[batch, num_vertices, 3]` containing batches vertices, each defined by a 3D point. triangles: A tensor of shape `[num_triangles, 3]` each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[batch, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. enable_cull_face: A boolean, which will enable BACK face culling when True and no face culling when False. Default is True. num_layers: Number of depth layers to render. Not supported by current backend yet, but exists for interface compatibility. name: A name for this op. Defaults to "rasterization_backend_rasterize". Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields.
Rasterizes the scene.
[ "Rasterizes", "the", "scene", "." ]
def rasterize(vertices: type_alias.TensorLike, triangles: type_alias.TensorLike, view_projection_matrices: type_alias.TensorLike, image_size: Tuple[int, int], enable_cull_face: bool, num_layers: int, name: str = "rasterization_backend_rasterize") -> fb.Framebuffer: """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[batch, num_vertices, 3]` containing batches vertices, each defined by a 3D point. triangles: A tensor of shape `[num_triangles, 3]` each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[batch, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. enable_cull_face: A boolean, which will enable BACK face culling when True and no face culling when False. Default is True. num_layers: Number of depth layers to render. Not supported by current backend yet, but exists for interface compatibility. name: A name for this op. Defaults to "rasterization_backend_rasterize". Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ with tf.name_scope(name): if num_layers != 1: raise ValueError("OpenGL rasterizer only supports single layer.") vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) view_projection_matrices = tf.convert_to_tensor( value=view_projection_matrices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank=3, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=view_projection_matrices, tensor_name="view_projection_matrices", has_rank=3, has_dim_equals=((-1, 4), (-2, 4))) shape.compare_batch_dimensions( tensors=(vertices, view_projection_matrices), tensor_names=("vertices", "view_projection_matrices"), last_axes=(-3, -3), broadcast_compatible=True) geometry = tf.gather(vertices, triangles, axis=-2) # Extract batch size in order to make sure it is preserved after `gather` # operation. batch_size = _dim_value(vertices.shape[0]) rasterized = render_ops.rasterize( num_points=geometry.shape[-3], alpha_clear=0.0, enable_cull_face=enable_cull_face, variable_names=("view_projection_matrix", "triangular_mesh"), variable_kinds=("mat", "buffer"), variable_values=(view_projection_matrices, tf.reshape(geometry, shape=[batch_size, -1])), output_resolution=image_size, vertex_shader=vertex_shader, geometry_shader=geometry_shader, fragment_shader=fragment_shader) triangle_index = tf.cast(rasterized[..., 0], tf.int32) # Slicing of the tensor will result in all batch dimensions being # `None` for tensorflow graph mode, therefore we have to fix it in order to # have explicit shape. width, height = image_size triangle_index = tf.reshape(triangle_index, [batch_size, num_layers, height, width, 1]) barycentric_coordinates = rasterized[..., 1:3] barycentric_coordinates = tf.concat( (barycentric_coordinates, 1.0 - barycentric_coordinates[..., 0:1] - barycentric_coordinates[..., 1:2]), axis=-1) barycentric_coordinates = tf.reshape( barycentric_coordinates, [batch_size, num_layers, height, width, 3]) mask = rasterized[..., 3] mask = tf.reshape(mask, [batch_size, num_layers, height, width, 1]) barycentric_coordinates = mask * barycentric_coordinates vertex_ids = tf.gather(triangles, triangle_index[..., 0]) # Stop gradient for tensors coming out of custom op in order to avoid # confusing Tensorflow that they are differentiable. barycentric_coordinates = tf.stop_gradient(barycentric_coordinates) mask = tf.stop_gradient(mask) return fb.Framebuffer( foreground_mask=mask, triangle_id=triangle_index, vertex_ids=vertex_ids, barycentrics=fb.RasterizedAttribute( value=barycentric_coordinates, d_dx=None, d_dy=None))
[ "def", "rasterize", "(", "vertices", ":", "type_alias", ".", "TensorLike", ",", "triangles", ":", "type_alias", ".", "TensorLike", ",", "view_projection_matrices", ":", "type_alias", ".", "TensorLike", ",", "image_size", ":", "Tuple", "[", "int", ",", "int", "...
https://github.com/tensorflow/graphics/blob/86997957324bfbdd85848daae989b4c02588faa0/tensorflow_graphics/rendering/opengl/rasterization_backend.py#L103-L225
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/xhtml2pdf/util.py
python
getSize
(value, relative=0, base=None, default=0.0)
Converts strings to standard sizes. That is the function taking a string of CSS size ('12pt', '1cm' and so on) and converts it into a float in a standard unit (in our case, points). >>> getSize('12pt') 12.0 >>> getSize('1cm') 28.346456692913385
Converts strings to standard sizes. That is the function taking a string of CSS size ('12pt', '1cm' and so on) and converts it into a float in a standard unit (in our case, points).
[ "Converts", "strings", "to", "standard", "sizes", ".", "That", "is", "the", "function", "taking", "a", "string", "of", "CSS", "size", "(", "12pt", "1cm", "and", "so", "on", ")", "and", "converts", "it", "into", "a", "float", "in", "a", "standard", "uni...
def getSize(value, relative=0, base=None, default=0.0): """ Converts strings to standard sizes. That is the function taking a string of CSS size ('12pt', '1cm' and so on) and converts it into a float in a standard unit (in our case, points). >>> getSize('12pt') 12.0 >>> getSize('1cm') 28.346456692913385 """ try: original = value if value is None: return relative elif type(value) is types.FloatType: return value elif isinstance(value, int): return float(value) elif type(value) in (types.TupleType, types.ListType): value = "".join(value) value = str(value).strip().lower().replace(",", ".") if value[-2:] == 'cm': return float(value[:-2].strip()) * cm elif value[-2:] == 'mm': return float(value[:-2].strip()) * mm # 1mm = 0.1cm elif value[-2:] == 'in': return float(value[:-2].strip()) * inch # 1pt == 1/72inch elif value[-2:] == 'inch': return float(value[:-4].strip()) * inch # 1pt == 1/72inch elif value[-2:] == 'pt': return float(value[:-2].strip()) elif value[-2:] == 'pc': return float(value[:-2].strip()) * 12.0 # 1pc == 12pt elif value[-2:] == 'px': # XXX W3C says, use 96pdi # http://www.w3.org/TR/CSS21/syndata.html#length-units return float(value[:-2].strip()) * dpi96 elif value[-1:] == 'i': # 1pt == 1/72inch return float(value[:-1].strip()) * inch elif value in ("none", "0", "auto"): return 0.0 elif relative: if value[-2:] == 'em': # XXX # 1em = 1 * fontSize return float(value[:-2].strip()) * relative elif value[-2:] == 'ex': # XXX # 1ex = 1/2 fontSize return float(value[:-2].strip()) * (relative / 2.0) elif value[-1:] == '%': # 1% = (fontSize * 1) / 100 return (relative * float(value[:-1].strip())) / 100.0 elif value in ("normal", "inherit"): return relative elif value in _relativeSizeTable: if base: return max(MIN_FONT_SIZE, base * _relativeSizeTable[value]) return max(MIN_FONT_SIZE, relative * _relativeSizeTable[value]) elif value in _absoluteSizeTable: if base: return max(MIN_FONT_SIZE, base * _absoluteSizeTable[value]) return max(MIN_FONT_SIZE, relative * _absoluteSizeTable[value]) else: return max(MIN_FONT_SIZE, relative * float(value)) try: value = float(value) except: log.warn("getSize: Not a float %r", value) return default # value = 0 return max(0, value) except Exception: log.warn("getSize %r %r", original, relative, exc_info=1) return default
[ "def", "getSize", "(", "value", ",", "relative", "=", "0", ",", "base", "=", "None", ",", "default", "=", "0.0", ")", ":", "try", ":", "original", "=", "value", "if", "value", "is", "None", ":", "return", "relative", "elif", "type", "(", "value", "...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/xhtml2pdf/util.py#L211-L283
hakril/PythonForWindows
61e027a678d5b87aa64fcf8a37a6661a86236589
windows/winproxy/apis/kernel32.py
python
FindNextChangeNotification
(hChangeHandle)
return FindNextChangeNotification.ctypes_function(hChangeHandle)
[]
def FindNextChangeNotification(hChangeHandle): return FindNextChangeNotification.ctypes_function(hChangeHandle)
[ "def", "FindNextChangeNotification", "(", "hChangeHandle", ")", ":", "return", "FindNextChangeNotification", ".", "ctypes_function", "(", "hChangeHandle", ")" ]
https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/windows/winproxy/apis/kernel32.py#L559-L560
GoogleCloudPlatform/cloudml-samples
efddc4a9898127e55edc0946557aca4bfaf59705
cloudml-template/examples/classification/census/trainer/model.py
python
_update_optimizer
(args)
return tf.train.AdamOptimizer(learning_rate=learning_rate)
Create an optimizer with an update learning rate. Arg: args: experiment parameters Returns: Optimizer
Create an optimizer with an update learning rate. Arg: args: experiment parameters Returns: Optimizer
[ "Create", "an", "optimizer", "with", "an", "update", "learning", "rate", ".", "Arg", ":", "args", ":", "experiment", "parameters", "Returns", ":", "Optimizer" ]
def _update_optimizer(args): """Create an optimizer with an update learning rate. Arg: args: experiment parameters Returns: Optimizer """ # decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps) # See: https://www.tensorflow.org/api_docs/python/tf/train/exponential_decay learning_rate = tf.train.exponential_decay( learning_rate=args.learning_rate, global_step=tf.train.get_global_step(), decay_steps=args.train_steps, decay_rate=args.learning_rate_decay_factor ) tf.summary.scalar('learning_rate', learning_rate) # By default, AdamOptimizer is used. You can change the type of the optimizer. return tf.train.AdamOptimizer(learning_rate=learning_rate)
[ "def", "_update_optimizer", "(", "args", ")", ":", "# decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps)", "# See: https://www.tensorflow.org/api_docs/python/tf/train/exponential_decay", "learning_rate", "=", "tf", ".", "train", ".", "exponential_decay", "...
https://github.com/GoogleCloudPlatform/cloudml-samples/blob/efddc4a9898127e55edc0946557aca4bfaf59705/cloudml-template/examples/classification/census/trainer/model.py#L110-L130
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/execution/code_generator.py
python
getGlobalizeStatement
(nodes, variables)
return "global " + ", ".join(socketNames)
[]
def getGlobalizeStatement(nodes, variables): socketNames = [variables[socket] for socket in iterUnlinkedSockets(nodes) if socket.dataType != "Node Control"] if len(socketNames) == 0: return "" return "global " + ", ".join(socketNames)
[ "def", "getGlobalizeStatement", "(", "nodes", ",", "variables", ")", ":", "socketNames", "=", "[", "variables", "[", "socket", "]", "for", "socket", "in", "iterUnlinkedSockets", "(", "nodes", ")", "if", "socket", ".", "dataType", "!=", "\"Node Control\"", "]",...
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/execution/code_generator.py#L92-L95
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/verify_student/utils.py
python
submit_request_to_ss
(user_verification, copy_id_photo_from)
Submit our verification attempt to Software Secure for validation. Submits the task to software secure and If the task creation fails, set the verification status to "must_retry".
Submit our verification attempt to Software Secure for validation.
[ "Submit", "our", "verification", "attempt", "to", "Software", "Secure", "for", "validation", "." ]
def submit_request_to_ss(user_verification, copy_id_photo_from): """ Submit our verification attempt to Software Secure for validation. Submits the task to software secure and If the task creation fails, set the verification status to "must_retry". """ try: send_request_to_ss_for_user.delay( user_verification_id=user_verification.id, copy_id_photo_from=copy_id_photo_from ) except Exception as error: # pylint: disable=broad-except log.error( "Software Secure submit request %r failed, result: %s", user_verification.user.username, str(error) ) user_verification.mark_must_retry()
[ "def", "submit_request_to_ss", "(", "user_verification", ",", "copy_id_photo_from", ")", ":", "try", ":", "send_request_to_ss_for_user", ".", "delay", "(", "user_verification_id", "=", "user_verification", ".", "id", ",", "copy_id_photo_from", "=", "copy_id_photo_from", ...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/verify_student/utils.py#L16-L31
princewen/leetcode_python
79e6e760e4d81824c96903e6c996630c24d01932
sort_by_myself/easy/其他/58_length_of_last_word.py
python
Solution.lengthOfLastWord
(self, s)
return length
:type s: str :rtype: int
:type s: str :rtype: int
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "int" ]
def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ s = s.strip() if not s: return 0 length = 0 for i in range(len(s) - 1, -1, -1): if s[i] != ' ': length = length + 1 else: break return length
[ "def", "lengthOfLastWord", "(", "self", ",", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "if", "not", "s", ":", "return", "0", "length", "=", "0", "for", "i", "in", "range", "(", "len", "(", "s", ")", "-", "1", ",", "-", "1", ",",...
https://github.com/princewen/leetcode_python/blob/79e6e760e4d81824c96903e6c996630c24d01932/sort_by_myself/easy/其他/58_length_of_last_word.py#L17-L33
openvinotoolkit/open_model_zoo
5a4232f6c35b4916eb6e8750141f4e45761237ef
tools/accuracy_checker/openvino/tools/accuracy_checker/launcher/tf_lite_launcher.py
python
TFLiteLauncher.predict
(self, inputs, metadata=None, **kwargs)
return results
Args: inputs: dictionary where keys are input layers names and values are data for them. metadata: metadata of input representations Returns: raw data from network.
Args: inputs: dictionary where keys are input layers names and values are data for them. metadata: metadata of input representations Returns: raw data from network.
[ "Args", ":", "inputs", ":", "dictionary", "where", "keys", "are", "input", "layers", "names", "and", "values", "are", "data", "for", "them", ".", "metadata", ":", "metadata", "of", "input", "representations", "Returns", ":", "raw", "data", "from", "network",...
def predict(self, inputs, metadata=None, **kwargs): """ Args: inputs: dictionary where keys are input layers names and values are data for them. metadata: metadata of input representations Returns: raw data from network. """ results = [] for dataset_input in inputs: self.set_tensors(dataset_input) self._interpreter.invoke() res = {output['name']: self._interpreter.get_tensor(output['index']) for output in self._output_details} results.append(res) if metadata is not None: for meta_ in metadata: meta_['input_shape'] = self.inputs_info_for_meta() return results
[ "def", "predict", "(", "self", ",", "inputs", ",", "metadata", "=", "None", ",", "*", "*", "kwargs", ")", ":", "results", "=", "[", "]", "for", "dataset_input", "in", "inputs", ":", "self", ".", "set_tensors", "(", "dataset_input", ")", "self", ".", ...
https://github.com/openvinotoolkit/open_model_zoo/blob/5a4232f6c35b4916eb6e8750141f4e45761237ef/tools/accuracy_checker/openvino/tools/accuracy_checker/launcher/tf_lite_launcher.py#L58-L79
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_job_condition.py
python
V1JobCondition.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "six", ".", "iteritems", "(", "self", ".", "openapi_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", ...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_job_condition.py#L220-L242
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/FreeBSD/i386/ucs2/cryptography/x509/base.py
python
CertificateBuilder.not_valid_after
(self, time)
return CertificateBuilder( self._issuer_name, self._subject_name, self._public_key, self._serial_number, self._not_valid_before, time, self._extensions )
Sets the certificate expiration time.
Sets the certificate expiration time.
[ "Sets", "the", "certificate", "expiration", "time", "." ]
def not_valid_after(self, time): """ Sets the certificate expiration time. """ if not isinstance(time, datetime.datetime): raise TypeError('Expecting datetime object.') if self._not_valid_after is not None: raise ValueError('The not valid after may only be set once.') time = _convert_to_naive_utc_time(time) if time <= _UNIX_EPOCH: raise ValueError('The not valid after date must be after the unix' ' epoch (1970 January 1).') if (self._not_valid_before is not None and time < self._not_valid_before): raise ValueError( 'The not valid after date must be after the not valid before ' 'date.' ) return CertificateBuilder( self._issuer_name, self._subject_name, self._public_key, self._serial_number, self._not_valid_before, time, self._extensions )
[ "def", "not_valid_after", "(", "self", ",", "time", ")", ":", "if", "not", "isinstance", "(", "time", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "'Expecting datetime object.'", ")", "if", "self", ".", "_not_valid_after", "is", "no...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/FreeBSD/i386/ucs2/cryptography/x509/base.py#L479-L501
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/lib/libgedcom.py
python
GedcomParser.__repo_email
(self, line, state)
@param line: The current line in GedLine format @type line: GedLine @param state: The current state @type state: CurrentState
[]
def __repo_email(self, line, state): """ @param line: The current line in GedLine format @type line: GedLine @param state: The current state @type state: CurrentState """ url = Url() url.set_path(line.data) url.set_type(UrlType(UrlType.EMAIL)) state.repo.add_url(url)
[ "def", "__repo_email", "(", "self", ",", "line", ",", "state", ")", ":", "url", "=", "Url", "(", ")", "url", ".", "set_path", "(", "line", ".", "data", ")", "url", ".", "set_type", "(", "UrlType", "(", "UrlType", ".", "EMAIL", ")", ")", "state", ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/lib/libgedcom.py#L7078-L7088
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/mailbox.py
python
_ProxyFile.__init__
(self, f, pos=None)
Initialize a _ProxyFile.
Initialize a _ProxyFile.
[ "Initialize", "a", "_ProxyFile", "." ]
def __init__(self, f, pos=None): """Initialize a _ProxyFile.""" self._file = f if pos is None: self._pos = f.tell() else: self._pos = pos
[ "def", "__init__", "(", "self", ",", "f", ",", "pos", "=", "None", ")", ":", "self", ".", "_file", "=", "f", "if", "pos", "is", "None", ":", "self", ".", "_pos", "=", "f", ".", "tell", "(", ")", "else", ":", "self", ".", "_pos", "=", "pos" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/mailbox.py#L1926-L1932
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/template/defaultfilters.py
python
center
(value, arg)
return value.center(int(arg))
Centers the value in a field of a given width.
Centers the value in a field of a given width.
[ "Centers", "the", "value", "in", "a", "field", "of", "a", "given", "width", "." ]
def center(value, arg): """Centers the value in a field of a given width.""" return value.center(int(arg))
[ "def", "center", "(", "value", ",", "arg", ")", ":", "return", "value", ".", "center", "(", "int", "(", "arg", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/template/defaultfilters.py#L361-L363
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/ftplib.py
python
ftpcp
(source, sourcename, target, targetname = '', type = 'I')
Copy file from one FTP-instance to another.
Copy file from one FTP-instance to another.
[ "Copy", "file", "from", "one", "FTP", "-", "instance", "to", "another", "." ]
def ftpcp(source, sourcename, target, targetname = '', type = 'I'): '''Copy file from one FTP-instance to another.''' if not targetname: targetname = sourcename type = 'TYPE ' + type source.voidcmd(type) target.voidcmd(type) sourcehost, sourceport = parse227(source.sendcmd('PASV')) target.sendport(sourcehost, sourceport) # RFC 959: the user must "listen" [...] BEFORE sending the # transfer request. # So: STOR before RETR, because here the target is a "user". treply = target.sendcmd('STOR ' + targetname) if treply[:3] not in {'125', '150'}: raise error_proto # RFC 959 sreply = source.sendcmd('RETR ' + sourcename) if sreply[:3] not in {'125', '150'}: raise error_proto # RFC 959 source.voidresp() target.voidresp()
[ "def", "ftpcp", "(", "source", ",", "sourcename", ",", "target", ",", "targetname", "=", "''", ",", "type", "=", "'I'", ")", ":", "if", "not", "targetname", ":", "targetname", "=", "sourcename", "type", "=", "'TYPE '", "+", "type", "source", ".", "void...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/ftplib.py#L909-L928
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/autopilot/v1/assistant/model_build.py
python
ModelBuildList.get
(self, sid)
return ModelBuildContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, )
Constructs a ModelBuildContext :param sid: The unique string that identifies the resource :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext
Constructs a ModelBuildContext
[ "Constructs", "a", "ModelBuildContext" ]
def get(self, sid): """ Constructs a ModelBuildContext :param sid: The unique string that identifies the resource :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext """ return ModelBuildContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, )
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "ModelBuildContext", "(", "self", ".", "_version", ",", "assistant_sid", "=", "self", ".", "_solution", "[", "'assistant_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/autopilot/v1/assistant/model_build.py#L131-L140
ruotianluo/Image_Captioning_AI_Challenger
ad230614efb8b964b4ced49a3622f4585d4de1cc
scripts/prepro_labels.py
python
encode_captions
(imgs, params, wtoi)
return L, label_start_ix, label_end_ix, label_length
encode all captions into one large array, which will be 1-indexed. also produces label_start_ix and label_end_ix which store 1-indexed and inclusive (Lua-style) pointers to the first and last caption for each image in the dataset.
encode all captions into one large array, which will be 1-indexed. also produces label_start_ix and label_end_ix which store 1-indexed and inclusive (Lua-style) pointers to the first and last caption for each image in the dataset.
[ "encode", "all", "captions", "into", "one", "large", "array", "which", "will", "be", "1", "-", "indexed", ".", "also", "produces", "label_start_ix", "and", "label_end_ix", "which", "store", "1", "-", "indexed", "and", "inclusive", "(", "Lua", "-", "style", ...
def encode_captions(imgs, params, wtoi): """ encode all captions into one large array, which will be 1-indexed. also produces label_start_ix and label_end_ix which store 1-indexed and inclusive (Lua-style) pointers to the first and last caption for each image in the dataset. """ max_length = params['max_length'] N = len(imgs) M = sum(len(img['final_captions']) for img in imgs) # total number of captions label_arrays = [] label_start_ix = np.zeros(N, dtype='uint32') # note: these will be one-indexed label_end_ix = np.zeros(N, dtype='uint32') label_length = np.zeros(M, dtype='uint32') caption_counter = 0 counter = 1 for i,img in enumerate(imgs): n = len(img['final_captions']) assert n > 0, 'error: some image has no captions' Li = np.zeros((n, max_length), dtype='uint32') for j,s in enumerate(img['final_captions']): label_length[caption_counter] = min(max_length, len(s)) # record the length of this sequence caption_counter += 1 for k,w in enumerate(s): if k < max_length: Li[j,k] = wtoi[w] # note: word indices are 1-indexed, and captions are padded with zeros label_arrays.append(Li) label_start_ix[i] = counter label_end_ix[i] = counter + n - 1 counter += n L = np.concatenate(label_arrays, axis=0) # put all the labels together assert L.shape[0] == M, 'lengths don\'t match? that\'s weird' assert np.all(label_length > 0), 'error: some caption had no words?' print('encoded captions to array of size ', L.shape) return L, label_start_ix, label_end_ix, label_length
[ "def", "encode_captions", "(", "imgs", ",", "params", ",", "wtoi", ")", ":", "max_length", "=", "params", "[", "'max_length'", "]", "N", "=", "len", "(", "imgs", ")", "M", "=", "sum", "(", "len", "(", "img", "[", "'final_captions'", "]", ")", "for", ...
https://github.com/ruotianluo/Image_Captioning_AI_Challenger/blob/ad230614efb8b964b4ced49a3622f4585d4de1cc/scripts/prepro_labels.py#L97-L139
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/python/ops/math_ops.py
python
reduce_all
(input_tensor, reduction_indices=None, keep_dims=False, name=None)
return gen_math_ops._all(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
Computes the "logical and" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[True, True] # [False, False]] tf.reduce_all(x) ==> False tf.reduce_all(x, 0) ==> [False, False] tf.reduce_all(x, 1) ==> [True, False] ``` Args: input_tensor: The boolean tensor to reduce. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor.
Computes the "logical and" of elements across dimensions of a tensor.
[ "Computes", "the", "logical", "and", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_all(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the "logical and" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[True, True] # [False, False]] tf.reduce_all(x) ==> False tf.reduce_all(x, 0) ==> [False, False] tf.reduce_all(x, 1) ==> [True, False] ``` Args: input_tensor: The boolean tensor to reduce. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._all(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
[ "def", "reduce_all", "(", "input_tensor", ",", "reduction_indices", "=", "None", ",", "keep_dims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "gen_math_ops", ".", "_all", "(", "input_tensor", ",", "_ReductionDims", "(", "input_tensor", ",", ...
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/math_ops.py#L1305-L1339
icometrix/dicom2nifti
60eca00a79c32a80e9c5909b56434db96c438b60
dicom2nifti/settings.py
python
enable_validate_instance_number
()
Enable the slice increment validation again (DEFAULT ENABLED)
Enable the slice increment validation again (DEFAULT ENABLED)
[ "Enable", "the", "slice", "increment", "validation", "again", "(", "DEFAULT", "ENABLED", ")" ]
def enable_validate_instance_number(): """ Enable the slice increment validation again (DEFAULT ENABLED) """ global validate_instance_number validate_instance_number = True
[ "def", "enable_validate_instance_number", "(", ")", ":", "global", "validate_instance_number", "validate_instance_number", "=", "True" ]
https://github.com/icometrix/dicom2nifti/blob/60eca00a79c32a80e9c5909b56434db96c438b60/dicom2nifti/settings.py#L84-L89
bigboNed3/bert_serving
44d33920da6888cf91cb72e6c7b27c7b0c7d8815
run_classifier.py
python
MrpcProcessor.get_dev_examples
(self, data_dir)
return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
[ "def", "get_dev_examples", "(", "self", ",", "data_dir", ")", ":", "return", "self", ".", "_create_examples", "(", "self", ".", "_read_tsv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"dev.tsv\"", ")", ")", ",", "\"dev\"", ")" ]
https://github.com/bigboNed3/bert_serving/blob/44d33920da6888cf91cb72e6c7b27c7b0c7d8815/run_classifier.py#L293-L296
LukeB42/Emissary
31629a8baedc91a9b60c551a01b2b45372b9a8c7
emissary/resources/feedgroups.py
python
FeedGroupArticles.get
(self, groupname)
return make_response(request.url, query)
Retrieve articles by feedgroup.
Retrieve articles by feedgroup.
[ "Retrieve", "articles", "by", "feedgroup", "." ]
def get(self, groupname): """ Retrieve articles by feedgroup. """ key = auth() # Summon the group or 404. fg = FeedGroup.query.filter(and_(FeedGroup.key == key, FeedGroup.name == groupname)).first() if not fg: restful.abort(404) parser = restful.reqparse.RequestParser() parser.add_argument("page", type=int, default=1) parser.add_argument("per_page", type=int, default=10) parser.add_argument("content", type=bool, default=None) args = parser.parse_args() if args.content == True: query = Article.query.filter( and_(Article.feed.has(group=fg), Article.content != None))\ .order_by(desc(Article.created)).paginate(args.page, args.per_page) response = make_response(request.url, query) # for doc in response['data']: # if not doc['content_available']: # response['data'].remove(doc) # return response if args.content == False: query = Article.query.filter( and_(Article.feed.has(group=fg), Article.content == None))\ .order_by(desc(Article.created)).paginate(args.page, args.per_page) return make_response(request.url, query) query = Article.query.filter( Article.feed.has(group=fg))\ .order_by(desc(Article.created)).paginate(args.page, args.per_page) return make_response(request.url, query)
[ "def", "get", "(", "self", ",", "groupname", ")", ":", "key", "=", "auth", "(", ")", "# Summon the group or 404.", "fg", "=", "FeedGroup", ".", "query", ".", "filter", "(", "and_", "(", "FeedGroup", ".", "key", "==", "key", ",", "FeedGroup", ".", "name...
https://github.com/LukeB42/Emissary/blob/31629a8baedc91a9b60c551a01b2b45372b9a8c7/emissary/resources/feedgroups.py#L184-L224
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/api/networking_v1_api.py
python
NetworkingV1Api.delete_collection_namespaced_ingress
(self, namespace, **kwargs)
return self.delete_collection_namespaced_ingress_with_http_info(namespace, **kwargs)
delete_collection_namespaced_ingress # noqa: E501 delete collection of Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_ingress(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread.
delete_collection_namespaced_ingress # noqa: E501
[ "delete_collection_namespaced_ingress", "#", "noqa", ":", "E501" ]
def delete_collection_namespaced_ingress(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_ingress # noqa: E501 delete collection of Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_ingress(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_ingress_with_http_info(namespace, **kwargs)
[ "def", "delete_collection_namespaced_ingress", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "delete_collection_namespaced_ingress_with_http_info", "(...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/networking_v1_api.py#L614-L650
hyperledger/fabric-sdk-py
8ee33a8981887e37950dc0f36a7ec63b3a5ba5c3
hfc/fabric_ca/caservice.py
python
ca_service
(target=DEFAULT_CA_ENDPOINT, ca_certs_path=None, crypto=ecies(), ca_name="")
return CAService(target, ca_certs_path, crypto, ca_name)
Create ca service :param target: url (Default value = DEFAULT_CA_ENDPOINT) :param ca_certs_path: certs path (Default value = None) :param crypto: crypto (Default value = ecies()) :param ca_name: CA name :return: ca service instance (Default value = "")
Create ca service
[ "Create", "ca", "service" ]
def ca_service(target=DEFAULT_CA_ENDPOINT, ca_certs_path=None, crypto=ecies(), ca_name=""): """Create ca service :param target: url (Default value = DEFAULT_CA_ENDPOINT) :param ca_certs_path: certs path (Default value = None) :param crypto: crypto (Default value = ecies()) :param ca_name: CA name :return: ca service instance (Default value = "") """ return CAService(target, ca_certs_path, crypto, ca_name)
[ "def", "ca_service", "(", "target", "=", "DEFAULT_CA_ENDPOINT", ",", "ca_certs_path", "=", "None", ",", "crypto", "=", "ecies", "(", ")", ",", "ca_name", "=", "\"\"", ")", ":", "return", "CAService", "(", "target", ",", "ca_certs_path", ",", "crypto", ",",...
https://github.com/hyperledger/fabric-sdk-py/blob/8ee33a8981887e37950dc0f36a7ec63b3a5ba5c3/hfc/fabric_ca/caservice.py#L667-L677
metabrainz/picard
535bf8c7d9363ffc7abb3f69418ec11823c38118
picard/file.py
python
File.can_edit_tags
(self)
return True
Return if this object supports tag editing.
Return if this object supports tag editing.
[ "Return", "if", "this", "object", "supports", "tag", "editing", "." ]
def can_edit_tags(self): """Return if this object supports tag editing.""" return True
[ "def", "can_edit_tags", "(", "self", ")", ":", "return", "True" ]
https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/file.py#L718-L720
seanbell/opensurfaces
7f3e987560faa62cd37f821760683ccd1e053c7c
server/common/geom.py
python
triangle_segment_intersects
(t0, t1, t2, p0, p1)
return True
Return whether line p0,p1 intersects triangle t0,t1,t2. Containment counts as intersection.
Return whether line p0,p1 intersects triangle t0,t1,t2. Containment counts as intersection.
[ "Return", "whether", "line", "p0", "p1", "intersects", "triangle", "t0", "t1", "t2", ".", "Containment", "counts", "as", "intersection", "." ]
def triangle_segment_intersects(t0, t1, t2, p0, p1): """ Return whether line p0,p1 intersects triangle t0,t1,t2. Containment counts as intersection. """ # if all 3 vertices are on the same side of the line, there is no # intersection s = line_ccw(p0, p1, t0) if s == line_ccw(p0, p1, t1) and s == line_ccw(p0, p1, t2): return False # if the line is outside one of the triangle half-planes, there is no # intersection for (a, b, c) in ((t0, t1, t2), (t1, t2, t0), (t2, t0, t1)): s = line_ccw(a, b, c) # find side of triangle if s != line_ccw(a, b, p0) and s != line_ccw(a, b, p1): return False # intersection return True
[ "def", "triangle_segment_intersects", "(", "t0", ",", "t1", ",", "t2", ",", "p0", ",", "p1", ")", ":", "# if all 3 vertices are on the same side of the line, there is no", "# intersection", "s", "=", "line_ccw", "(", "p0", ",", "p1", ",", "t0", ")", "if", "s", ...
https://github.com/seanbell/opensurfaces/blob/7f3e987560faa62cd37f821760683ccd1e053c7c/server/common/geom.py#L109-L126
rossant/galry
6201fa32fb5c9ef3cea700cc22caf52fb69ebe31
galry/scene.py
python
SceneCreator.__init__
(self, constrain_ratio=False,)
Initialize the scene.
Initialize the scene.
[ "Initialize", "the", "scene", "." ]
def __init__(self, constrain_ratio=False,): """Initialize the scene.""" # options self.constrain_ratio = constrain_ratio # create an empty scene self.scene = {'visuals': [], 'renderer_options': {}} self.visual_objects = {}
[ "def", "__init__", "(", "self", ",", "constrain_ratio", "=", "False", ",", ")", ":", "# options", "self", ".", "constrain_ratio", "=", "constrain_ratio", "# create an empty scene", "self", ".", "scene", "=", "{", "'visuals'", ":", "[", "]", ",", "'renderer_opt...
https://github.com/rossant/galry/blob/6201fa32fb5c9ef3cea700cc22caf52fb69ebe31/galry/scene.py#L14-L22
benedekrozemberczki/littleballoffur
dbfec92c0ead8c5da134c9aead7987c7a36234b4
littleballoffur/backend.py
python
NetworkXBackEnd.get_neighbors
(self, graph: NXGraph, node: int)
return [node for node in graph.neighbors(node)]
Given a graph and node return the neighbors.
Given a graph and node return the neighbors.
[ "Given", "a", "graph", "and", "node", "return", "the", "neighbors", "." ]
def get_neighbors(self, graph: NXGraph, node: int) -> List[int]: """ Given a graph and node return the neighbors. """ return [node for node in graph.neighbors(node)]
[ "def", "get_neighbors", "(", "self", ",", "graph", ":", "NXGraph", ",", "node", ":", "int", ")", "->", "List", "[", "int", "]", ":", "return", "[", "node", "for", "node", "in", "graph", ".", "neighbors", "(", "node", ")", "]" ]
https://github.com/benedekrozemberczki/littleballoffur/blob/dbfec92c0ead8c5da134c9aead7987c7a36234b4/littleballoffur/backend.py#L217-L221
minerllabs/minerl
0123527c334c96ebb3f0cf313df1552fa4302691
minerl/herobraine/hero/handlers/agent/observations/pov.py
python
POVObservation.to_string
(self)
return 'pov'
[]
def to_string(self): return 'pov'
[ "def", "to_string", "(", "self", ")", ":", "return", "'pov'" ]
https://github.com/minerllabs/minerl/blob/0123527c334c96ebb3f0cf313df1552fa4302691/minerl/herobraine/hero/handlers/agent/observations/pov.py#L16-L17
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/tvdbapiv2/models/user_ratings_data.py
python
UserRatingsData.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() else: result[attr] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "iteritems", "(", "self", ".", "swagger_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", "value", ","...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/tvdbapiv2/models/user_ratings_data.py#L99-L117
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/tools/customcompleter/customcompleter.py
python
TextEdit.setCompleter
(self, c)
[]
def setCompleter(self, c): if self._completer is not None: self._completer.activated.disconnect() self._completer = c c.setWidget(self) c.setCompletionMode(QCompleter.PopupCompletion) c.setCaseSensitivity(Qt.CaseInsensitive) c.activated.connect(self.insertCompletion)
[ "def", "setCompleter", "(", "self", ",", "c", ")", ":", "if", "self", ".", "_completer", "is", "not", "None", ":", "self", ".", "_completer", ".", "activated", ".", "disconnect", "(", ")", "self", ".", "_completer", "=", "c", "c", ".", "setWidget", "...
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/tools/customcompleter/customcompleter.py#L65-L74
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/inputters/corpus.py
python
build_sub_vocab
(corpora, transforms, opts, n_sample, stride, offset)
return sub_counter_src, sub_counter_tgt, sub_counter_src_feats
Build vocab on (strided) subpart of the data.
Build vocab on (strided) subpart of the data.
[ "Build", "vocab", "on", "(", "strided", ")", "subpart", "of", "the", "data", "." ]
def build_sub_vocab(corpora, transforms, opts, n_sample, stride, offset): """Build vocab on (strided) subpart of the data.""" sub_counter_src = Counter() sub_counter_tgt = Counter() sub_counter_src_feats = defaultdict(Counter) datasets_iterables = build_corpora_iters( corpora, transforms, opts.data, skip_empty_level=opts.skip_empty_level, stride=stride, offset=offset) for c_name, c_iter in datasets_iterables.items(): for i, item in enumerate(c_iter): maybe_example = DatasetAdapter._process(item, is_train=True) if maybe_example is None: if opts.dump_samples: build_sub_vocab.queues[c_name][offset].put("blank") continue src_line, tgt_line = (maybe_example['src']['src'], maybe_example['tgt']['tgt']) src_line_pretty = src_line for feat_name, feat_line in maybe_example["src"].items(): if feat_name not in ["src", "src_original"]: sub_counter_src_feats[feat_name].update( feat_line.split(' ')) if opts.dump_samples: src_line_pretty = append_features_to_example( src_line_pretty, feat_line) sub_counter_src.update(src_line.split(' ')) sub_counter_tgt.update(tgt_line.split(' ')) if opts.dump_samples: build_sub_vocab.queues[c_name][offset].put( (i, src_line_pretty, tgt_line)) if n_sample > 0 and ((i+1) * stride + offset) >= n_sample: if opts.dump_samples: build_sub_vocab.queues[c_name][offset].put("break") break if opts.dump_samples: build_sub_vocab.queues[c_name][offset].put("break") return sub_counter_src, sub_counter_tgt, sub_counter_src_feats
[ "def", "build_sub_vocab", "(", "corpora", ",", "transforms", ",", "opts", ",", "n_sample", ",", "stride", ",", "offset", ")", ":", "sub_counter_src", "=", "Counter", "(", ")", "sub_counter_tgt", "=", "Counter", "(", ")", "sub_counter_src_feats", "=", "defaultd...
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/inputters/corpus.py#L337-L374
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/integrations/vacuum/roborock/vacuum_cli.py
python
find
(vac: RoborockVacuum)
Find the robot.
Find the robot.
[ "Find", "the", "robot", "." ]
def find(vac: RoborockVacuum): """Find the robot.""" click.echo("Sending find the robot calls.") click.echo(vac.find())
[ "def", "find", "(", "vac", ":", "RoborockVacuum", ")", ":", "click", ".", "echo", "(", "\"Sending find the robot calls.\"", ")", "click", ".", "echo", "(", "vac", ".", "find", "(", ")", ")" ]
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/integrations/vacuum/roborock/vacuum_cli.py#L413-L416
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/jaraco/classes/properties.py
python
NonDataProperty.__get__
(self, obj, objtype=None)
return self.fget(obj)
[]
def __get__(self, obj, objtype=None): if obj is None: return self return self.fget(obj)
[ "def", "__get__", "(", "self", ",", "obj", ",", "objtype", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "self", "return", "self", ".", "fget", "(", "obj", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/jaraco/classes/properties.py#L29-L32
softlayer/softlayer-python
cdef7d63c66413197a9a97b0414de9f95887a82a
SoftLayer/CLI/image/detail.py
python
cli
(env, identifier)
Get details for an image.
Get details for an image.
[ "Get", "details", "for", "an", "image", "." ]
def cli(env, identifier): """Get details for an image.""" image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image') image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK) children_images = image.get('children') total_size = utils.lookup(image, 'firstChild', 'blockDevicesDiskSpaceTotal') or 0 table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', image['id']]) table.add_row(['global_identifier', image.get('globalIdentifier', formatting.blank())]) table.add_row(['name', image['name'].strip()]) table.add_row(['status', formatting.FormattedItem( utils.lookup(image, 'status', 'keyname'), utils.lookup(image, 'status', 'name'), )]) table.add_row([ 'active_transaction', formatting.listing(_get_transaction_groups(children_images), separator=','), ]) table.add_row(['account', image.get('accountId', formatting.blank())]) table.add_row(['visibility', image_mod.PUBLIC_TYPE if image['publicFlag'] else image_mod.PRIVATE_TYPE]) table.add_row(['type', formatting.FormattedItem( utils.lookup(image, 'imageType', 'keyName'), utils.lookup(image, 'imageType', 'name'), )]) table.add_row(['flex', image.get('flexImageFlag')]) table.add_row(['note', image.get('note')]) table.add_row(['created', image.get('createDate')]) table.add_row(['total_size', formatting.b_to_gb(total_size)]) table.add_row(['datacenters', _get_datacenter_table(children_images)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "image_mgr", "=", "SoftLayer", ".", "ImageManager", "(", "env", ".", "client", ")", "image_id", "=", "helpers", ".", "resolve_id", "(", "image_mgr", ".", "resolve_ids", ",", "identifier", ",", "'image'...
https://github.com/softlayer/softlayer-python/blob/cdef7d63c66413197a9a97b0414de9f95887a82a/SoftLayer/CLI/image/detail.py#L17-L59
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/prometheus_client/metrics.py
python
MetricWrapperBase.labels
(self, *labelvalues, **labelkwargs)
Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc() c.labels('post', '/submit').inc() Labels can also be provided as keyword arguments: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(method='get', endpoint='/').inc() c.labels(method='post', endpoint='/submit').inc() See the best practices on [naming](http://prometheus.io/docs/practices/naming/) and [labels](http://prometheus.io/docs/practices/instrumentation/#use-labels).
Return the child for the given labelset.
[ "Return", "the", "child", "for", "the", "given", "labelset", "." ]
def labels(self, *labelvalues, **labelkwargs): '''Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc() c.labels('post', '/submit').inc() Labels can also be provided as keyword arguments: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(method='get', endpoint='/').inc() c.labels(method='post', endpoint='/submit').inc() See the best practices on [naming](http://prometheus.io/docs/practices/naming/) and [labels](http://prometheus.io/docs/practices/instrumentation/#use-labels). ''' if not self._labelnames: raise ValueError('No label names were set when constructing %s' % self) if self._labelvalues: raise ValueError('%s already has labels set (%s); can not chain calls to .labels()' % ( self, dict(zip(self._labelnames, self._labelvalues)) )) if labelvalues and labelkwargs: raise ValueError("Can't pass both *args and **kwargs") if labelkwargs: if sorted(labelkwargs) != sorted(self._labelnames): raise ValueError('Incorrect label names') labelvalues = tuple(unicode(labelkwargs[l]) for l in self._labelnames) else: if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count') labelvalues = tuple(unicode(l) for l in labelvalues) with self._lock: if labelvalues not in self._metrics: self._metrics[labelvalues] = self.__class__( self._name, documentation=self._documentation, labelnames=self._labelnames, unit=self._unit, labelvalues=labelvalues, **self._kwargs ) return self._metrics[labelvalues]
[ "def", "labels", "(", "self", ",", "*", "labelvalues", ",", "*", "*", "labelkwargs", ")", ":", "if", "not", "self", ".", "_labelnames", ":", "raise", "ValueError", "(", "'No label names were set when constructing %s'", "%", "self", ")", "if", "self", ".", "_...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/prometheus_client/metrics.py#L105-L158
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/doc/ext/docscrape.py
python
NumpyDocString._parse_see_also
(self, content)
return items
func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3
func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3
[ "func_name", ":", "Descriptive", "text", "continued", "text", "another_func_name", ":", "Descriptive", "text", "func_name1", "func_name2", ":", "meth", ":", "func_name", "func_name3" ]
def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not a item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): if func.strip(): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items
[ "def", "_parse_see_also", "(", "self", ",", "content", ")", ":", "items", "=", "[", "]", "def", "parse_item_name", "(", "text", ")", ":", "\"\"\"Match ':role:`name`' or 'name'\"\"\"", "m", "=", "self", ".", "_name_rgx", ".", "match", "(", "text", ")", "if", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/doc/ext/docscrape.py#L193-L247
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/physics/vector/dyadic.py
python
Dyadic.__xor__
(self, other)
return ol
For a cross product in the form: Dyadic x Vector. Parameters ========== other : Vector The Vector that we are crossing this Dyadic with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, cross >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> cross(d, N.y) (N.x|N.z)
For a cross product in the form: Dyadic x Vector.
[ "For", "a", "cross", "product", "in", "the", "form", ":", "Dyadic", "x", "Vector", "." ]
def __xor__(self, other): """For a cross product in the form: Dyadic x Vector. Parameters ========== other : Vector The Vector that we are crossing this Dyadic with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, cross >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> cross(d, N.y) (N.x|N.z) """ from sympy.physics.vector.vector import _check_vector other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(self.args): ol += v[0] * (v[1] | (v[2] ^ other)) return ol
[ "def", "__xor__", "(", "self", ",", "other", ")", ":", "from", "sympy", ".", "physics", ".", "vector", ".", "vector", "import", "_check_vector", "other", "=", "_check_vector", "(", "other", ")", "ol", "=", "Dyadic", "(", "0", ")", "for", "i", ",", "v...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/physics/vector/dyadic.py#L349-L374
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/contrib/localflavor/is_/forms.py
python
ISIdNumberField._format
(self, value)
return smart_text(value[:6]+'-'+value[6:])
Takes in the value in canonical form and returns it in the common display format.
Takes in the value in canonical form and returns it in the common display format.
[ "Takes", "in", "the", "value", "in", "canonical", "form", "and", "returns", "it", "in", "the", "common", "display", "format", "." ]
def _format(self, value): """ Takes in the value in canonical form and returns it in the common display format. """ return smart_text(value[:6]+'-'+value[6:])
[ "def", "_format", "(", "self", ",", "value", ")", ":", "return", "smart_text", "(", "value", "[", ":", "6", "]", "+", "'-'", "+", "value", "[", "6", ":", "]", ")" ]
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/contrib/localflavor/is_/forms.py#L56-L61
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/dateutil/rrule.py
python
rruleset.rrule
(self, rrule)
Include the given :py:class:`rrule` instance in the recurrence set generation.
Include the given :py:class:`rrule` instance in the recurrence set generation.
[ "Include", "the", "given", ":", "py", ":", "class", ":", "rrule", "instance", "in", "the", "recurrence", "set", "generation", "." ]
def rrule(self, rrule): """ Include the given :py:class:`rrule` instance in the recurrence set generation. """ self._rrule.append(rrule)
[ "def", "rrule", "(", "self", ",", "rrule", ")", ":", "self", ".", "_rrule", ".", "append", "(", "rrule", ")" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/dateutil/rrule.py#L1331-L1334
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py
python
IPv4Address.__init__
(self, address)
Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address.
Args: address: A string or integer representing the IP
[ "Args", ":", "address", ":", "A", "string", "or", "integer", "representing", "the", "IP" ]
def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ # Efficient constructor from integer. if isinstance(address, _compat_int_types): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) bvs = _compat_bytes_to_byte_vals(address) self._ip = _compat_int_from_byte_vals(bvs, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = _compat_str(address) if '/' in addr_str: raise AddressValueError("Unexpected '/' in %r" % address) self._ip = self._ip_int_from_string(addr_str)
[ "def", "__init__", "(", "self", ",", "address", ")", ":", "# Efficient constructor from integer.", "if", "isinstance", "(", "address", ",", "_compat_int_types", ")", ":", "self", ".", "_check_int_address", "(", "address", ")", "self", ".", "_ip", "=", "address",...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py#L1375-L1409
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/contrib/gis/gdal/field.py
python
Field.as_double
(self)
return capi.get_field_as_double(self._feat, self._index)
Retrieves the Field's value as a double (float).
Retrieves the Field's value as a double (float).
[ "Retrieves", "the", "Field", "s", "value", "as", "a", "double", "(", "float", ")", "." ]
def as_double(self): "Retrieves the Field's value as a double (float)." return capi.get_field_as_double(self._feat, self._index)
[ "def", "as_double", "(", "self", ")", ":", "return", "capi", ".", "get_field_as_double", "(", "self", ".", "_feat", ",", "self", ".", "_index", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/gdal/field.py#L43-L45
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/compiler/transformer.py
python
Transformer.com_augassign
(self, node)
Return node suitable for lvalue of augmented assignment Names, slices, and attributes are the only allowable nodes.
Return node suitable for lvalue of augmented assignment Names, slices, and attributes are the only allowable nodes.
[ "Return", "node", "suitable", "for", "lvalue", "of", "augmented", "assignment", "Names", "slices", "and", "attributes", "are", "the", "only", "allowable", "nodes", "." ]
def com_augassign(self, node): """Return node suitable for lvalue of augmented assignment Names, slices, and attributes are the only allowable nodes. """ l = self.com_node(node) if l.__class__ in (Name, Slice, Subscript, Getattr): return l raise SyntaxError, "can't assign to %s" % l.__class__.__name__
[ "def", "com_augassign", "(", "self", ",", "node", ")", ":", "l", "=", "self", ".", "com_node", "(", "node", ")", "if", "l", ".", "__class__", "in", "(", "Name", ",", "Slice", ",", "Subscript", ",", "Getattr", ")", ":", "return", "l", "raise", "Synt...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/compiler/transformer.py#L811-L819
aio-libs/aiokafka
ccbcc25e9cd7dd5a980c175197f5315e0953e87c
aiokafka/producer/message_accumulator.py
python
MessageAccumulator.add_batch
(self, builder, tp, timeout)
Add BatchBuilder to queue by topic-partition. Arguments: builder (BatchBuilder): batch object to enqueue. tp (TopicPartition): topic and partition to enqueue this batch for. timeout (int): time in seconds to wait for a free slot in the batch queue. Returns: MessageBatch: delivery wrapper around the BatchBuilder object. Raises: aiokafka.errors.ProducerClosed: the accumulator has already been closed and flushed. aiokafka.errors.KafkaTimeoutError: the batch could not be added within the specified timeout.
Add BatchBuilder to queue by topic-partition.
[ "Add", "BatchBuilder", "to", "queue", "by", "topic", "-", "partition", "." ]
async def add_batch(self, builder, tp, timeout): """Add BatchBuilder to queue by topic-partition. Arguments: builder (BatchBuilder): batch object to enqueue. tp (TopicPartition): topic and partition to enqueue this batch for. timeout (int): time in seconds to wait for a free slot in the batch queue. Returns: MessageBatch: delivery wrapper around the BatchBuilder object. Raises: aiokafka.errors.ProducerClosed: the accumulator has already been closed and flushed. aiokafka.errors.KafkaTimeoutError: the batch could not be added within the specified timeout. """ if self._closed: raise ProducerClosed() if self._exception is not None: raise copy.copy(self._exception) start = time.monotonic() while timeout > 0: pending = self._batches.get(tp) if pending: await pending[-1].wait_drain(timeout=timeout) timeout -= time.monotonic() - start else: batch = self._append_batch(builder, tp) return asyncio.shield(batch.future) raise KafkaTimeoutError()
[ "async", "def", "add_batch", "(", "self", ",", "builder", ",", "tp", ",", "timeout", ")", ":", "if", "self", ".", "_closed", ":", "raise", "ProducerClosed", "(", ")", "if", "self", ".", "_exception", "is", "not", "None", ":", "raise", "copy", ".", "c...
https://github.com/aio-libs/aiokafka/blob/ccbcc25e9cd7dd5a980c175197f5315e0953e87c/aiokafka/producer/message_accumulator.py#L452-L484
youtify/youtify
82cbc4a4ca6283f14f7179d4aeba30ed1ee1fea8
dropbox/oauth.py
python
OAuthDataStore.lookup_consumer
(self, key)
-> OAuthConsumer.
-> OAuthConsumer.
[ "-", ">", "OAuthConsumer", "." ]
def lookup_consumer(self, key): """-> OAuthConsumer.""" raise NotImplementedError
[ "def", "lookup_consumer", "(", "self", ",", "key", ")", ":", "raise", "NotImplementedError" ]
https://github.com/youtify/youtify/blob/82cbc4a4ca6283f14f7179d4aeba30ed1ee1fea8/dropbox/oauth.py#L561-L563
python/mypy
17850b3bd77ae9efb5d21f656c4e4e05ac48d894
mypyc/build.py
python
group_name
(modules: List[str])
return h.hexdigest()[:20]
Produce a probably unique name for a group from a list of module names.
Produce a probably unique name for a group from a list of module names.
[ "Produce", "a", "probably", "unique", "name", "for", "a", "group", "from", "a", "list", "of", "module", "names", "." ]
def group_name(modules: List[str]) -> str: """Produce a probably unique name for a group from a list of module names.""" if len(modules) == 1: return modules[0] h = hashlib.sha1() h.update(','.join(modules).encode()) return h.hexdigest()[:20]
[ "def", "group_name", "(", "modules", ":", "List", "[", "str", "]", ")", "->", "str", ":", "if", "len", "(", "modules", ")", "==", "1", ":", "return", "modules", "[", "0", "]", "h", "=", "hashlib", ".", "sha1", "(", ")", "h", ".", "update", "(",...
https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypyc/build.py#L158-L165
Parsl/parsl
af2535341152b2640fdd1a3b73b891992bf1b3ea
parsl/providers/googlecloud/googlecloud.py
python
GoogleCloudProvider.cancel
(self, job_ids)
return statuses
Cancels the resources identified by the job_ids provided by the user. Args: - job_ids (list): A list of job identifiers Returns: - A list of status from cancelling the job which can be True, False Raises: - ExecutionProviderException or its subclasses
Cancels the resources identified by the job_ids provided by the user.
[ "Cancels", "the", "resources", "identified", "by", "the", "job_ids", "provided", "by", "the", "user", "." ]
def cancel(self, job_ids): ''' Cancels the resources identified by the job_ids provided by the user. Args: - job_ids (list): A list of job identifiers Returns: - A list of status from cancelling the job which can be True, False Raises: - ExecutionProviderException or its subclasses ''' statuses = [] for job_id in job_ids: try: self.delete_instance(job_id) statuses.append(True) except Exception: statuses.append(False) return statuses
[ "def", "cancel", "(", "self", ",", "job_ids", ")", ":", "statuses", "=", "[", "]", "for", "job_id", "in", "job_ids", ":", "try", ":", "self", ".", "delete_instance", "(", "job_id", ")", "statuses", ".", "append", "(", "True", ")", "except", "Exception"...
https://github.com/Parsl/parsl/blob/af2535341152b2640fdd1a3b73b891992bf1b3ea/parsl/providers/googlecloud/googlecloud.py#L143-L162
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/idsets.py
python
BitSet.intersection
(self, other)
return BitSet(source=(n for n in self if n in other))
[]
def intersection(self, other): if isinstance(other, BitSet): return self._logic(self.copy(), operator.__and__, other) return BitSet(source=(n for n in self if n in other))
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "BitSet", ")", ":", "return", "self", ".", "_logic", "(", "self", ".", "copy", "(", ")", ",", "operator", ".", "__and__", ",", "other", ")", "return", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/idsets.py#L431-L434
jacoxu/encoder_decoder
6829c3bc42105aedfd1b8a81c81be19df4326c0a
keras/layers/core.py
python
Layer.count_params
(self)
return sum([K.count_params(p) for p in self.trainable_weights])
Return the total number of floats (or ints) composing the weights of the layer.
Return the total number of floats (or ints) composing the weights of the layer.
[ "Return", "the", "total", "number", "of", "floats", "(", "or", "ints", ")", "composing", "the", "weights", "of", "the", "layer", "." ]
def count_params(self): '''Return the total number of floats (or ints) composing the weights of the layer. ''' return sum([K.count_params(p) for p in self.trainable_weights])
[ "def", "count_params", "(", "self", ")", ":", "return", "sum", "(", "[", "K", ".", "count_params", "(", "p", ")", "for", "p", "in", "self", ".", "trainable_weights", "]", ")" ]
https://github.com/jacoxu/encoder_decoder/blob/6829c3bc42105aedfd1b8a81c81be19df4326c0a/keras/layers/core.py#L353-L357
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/api/openstack/wsgi.py
python
ResponseObject.__setitem__
(self, key, value)
Sets a header with the given name to the given value.
Sets a header with the given name to the given value.
[ "Sets", "a", "header", "with", "the", "given", "name", "to", "the", "given", "value", "." ]
def __setitem__(self, key, value): """Sets a header with the given name to the given value.""" self._headers[key.lower()] = value
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "_headers", "[", "key", ".", "lower", "(", ")", "]", "=", "value" ]
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/api/openstack/wsgi.py#L413-L416
exodrifter/unity-python
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
Lib/mailbox.py
python
MH.iterkeys
(self)
return iter(sorted(int(entry) for entry in os.listdir(self._path) if entry.isdigit()))
Return an iterator over keys.
Return an iterator over keys.
[ "Return", "an", "iterator", "over", "keys", "." ]
def iterkeys(self): """Return an iterator over keys.""" return iter(sorted(int(entry) for entry in os.listdir(self._path) if entry.isdigit()))
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "sorted", "(", "int", "(", "entry", ")", "for", "entry", "in", "os", ".", "listdir", "(", "self", ".", "_path", ")", "if", "entry", ".", "isdigit", "(", ")", ")", ")" ]
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/mailbox.py#L1065-L1068
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/decimal.py
python
Decimal.__hash__
(self)
return -2 if ans == -1 else ans
x.__hash__() <==> hash(x)
x.__hash__() <==> hash(x)
[ "x", ".", "__hash__", "()", "<", "==", ">", "hash", "(", "x", ")" ]
def __hash__(self): """x.__hash__() <==> hash(x)""" # In order to make sure that the hash of a Decimal instance # agrees with the hash of a numerically equal integer, float # or Fraction, we follow the rules for numeric hashes outlined # in the documentation. (See library docs, 'Built-in Types'). if self._is_special: if self.is_snan(): raise TypeError('Cannot hash a signaling NaN value.') elif self.is_nan(): return _PyHASH_NAN else: if self._sign: return -_PyHASH_INF else: return _PyHASH_INF if self._exp >= 0: exp_hash = pow(10, self._exp, _PyHASH_MODULUS) else: exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS) hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS ans = hash_ if self >= 0 else -hash_ return -2 if ans == -1 else ans
[ "def", "__hash__", "(", "self", ")", ":", "# In order to make sure that the hash of a Decimal instance", "# agrees with the hash of a numerically equal integer, float", "# or Fraction, we follow the rules for numeric hashes outlined", "# in the documentation. (See library docs, 'Built-in Types')....
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/decimal.py#L982-L1006
axcore/tartube
36dd493642923fe8b9190a41db596c30c043ae90
tartube/config.py
python
SystemPrefWin.on_default_ffmpeg_button_clicked
(self, button, entry)
Called from callback in self.setup_downloader_ffmpeg_tab(). Sets the path to the ffmpeg binary to the default path. Args: button (Gtk.Button): The widget clicked entry (Gtk.Entry): Another widget to be modified by this function
Called from callback in self.setup_downloader_ffmpeg_tab().
[ "Called", "from", "callback", "in", "self", ".", "setup_downloader_ffmpeg_tab", "()", "." ]
def on_default_ffmpeg_button_clicked(self, button, entry): """Called from callback in self.setup_downloader_ffmpeg_tab(). Sets the path to the ffmpeg binary to the default path. Args: button (Gtk.Button): The widget clicked entry (Gtk.Entry): Another widget to be modified by this function """ self.app_obj.set_ffmpeg_path(self.app_obj.default_ffmpeg_path) entry.set_text(self.app_obj.ffmpeg_path)
[ "def", "on_default_ffmpeg_button_clicked", "(", "self", ",", "button", ",", "entry", ")", ":", "self", ".", "app_obj", ".", "set_ffmpeg_path", "(", "self", ".", "app_obj", ".", "default_ffmpeg_path", ")", "entry", ".", "set_text", "(", "self", ".", "app_obj", ...
https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/config.py#L24934-L24949
OneDrive/onedrive-sdk-python
e5642f8cad8eea37a4f653c1a23dfcfc06c37110
src/onedrivesdk/model/audio.py
python
Audio.album_artist
(self)
Gets and sets the albumArtist Returns: str: The albumArtist
Gets and sets the albumArtist Returns: str: The albumArtist
[ "Gets", "and", "sets", "the", "albumArtist", "Returns", ":", "str", ":", "The", "albumArtist" ]
def album_artist(self): """Gets and sets the albumArtist Returns: str: The albumArtist """ if "albumArtist" in self._prop_dict: return self._prop_dict["albumArtist"] else: return None
[ "def", "album_artist", "(", "self", ")", ":", "if", "\"albumArtist\"", "in", "self", ".", "_prop_dict", ":", "return", "self", ".", "_prop_dict", "[", "\"albumArtist\"", "]", "else", ":", "return", "None" ]
https://github.com/OneDrive/onedrive-sdk-python/blob/e5642f8cad8eea37a4f653c1a23dfcfc06c37110/src/onedrivesdk/model/audio.py#L35-L45
sunnyxiaohu/R-C3D.pytorch
e8731af7b95f1dc934f6604f9c09e3c4ead74db5
lib/tf_model_zoo/models/slim/preprocessing/cifarnet_preprocessing.py
python
preprocess_for_train
(image, output_height, output_width, padding=_PADDING)
return tf.image.per_image_whitening(distorted_image)
Preprocesses the given image for training. Note that the actual resizing scale is sampled from [`resize_size_min`, `resize_size_max`]. Args: image: A `Tensor` representing an image of arbitrary size. output_height: The height of the image after preprocessing. output_width: The width of the image after preprocessing. padding: The amound of padding before and after each dimension of the image. Returns: A preprocessed image.
Preprocesses the given image for training.
[ "Preprocesses", "the", "given", "image", "for", "training", "." ]
def preprocess_for_train(image, output_height, output_width, padding=_PADDING): """Preprocesses the given image for training. Note that the actual resizing scale is sampled from [`resize_size_min`, `resize_size_max`]. Args: image: A `Tensor` representing an image of arbitrary size. output_height: The height of the image after preprocessing. output_width: The width of the image after preprocessing. padding: The amound of padding before and after each dimension of the image. Returns: A preprocessed image. """ tf.image_summary('image', tf.expand_dims(image, 0)) # Transform the image to floats. image = tf.to_float(image) if padding > 0: image = tf.pad(image, [[padding, padding], [padding, padding], [0, 0]]) # Randomly crop a [height, width] section of the image. distorted_image = tf.random_crop(image, [output_height, output_width, 3]) # Randomly flip the image horizontally. distorted_image = tf.image.random_flip_left_right(distorted_image) tf.image_summary('distorted_image', tf.expand_dims(distorted_image, 0)) # Because these operations are not commutative, consider randomizing # the order their operation. distorted_image = tf.image.random_brightness(distorted_image, max_delta=63) distorted_image = tf.image.random_contrast(distorted_image, lower=0.2, upper=1.8) # Subtract off the mean and divide by the variance of the pixels. return tf.image.per_image_whitening(distorted_image)
[ "def", "preprocess_for_train", "(", "image", ",", "output_height", ",", "output_width", ",", "padding", "=", "_PADDING", ")", ":", "tf", ".", "image_summary", "(", "'image'", ",", "tf", ".", "expand_dims", "(", "image", ",", "0", ")", ")", "# Transform the i...
https://github.com/sunnyxiaohu/R-C3D.pytorch/blob/e8731af7b95f1dc934f6604f9c09e3c4ead74db5/lib/tf_model_zoo/models/slim/preprocessing/cifarnet_preprocessing.py#L30-L70
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/editors/editdate.py
python
EditDate.switch_dual_dated
(self, obj)
Changed whether this is a dual dated year, or not. Dual dated years are represented in the Julian calendar so that the day/months don't changed in the Text representation.
Changed whether this is a dual dated year, or not. Dual dated years are represented in the Julian calendar so that the day/months don't changed in the Text representation.
[ "Changed", "whether", "this", "is", "a", "dual", "dated", "year", "or", "not", ".", "Dual", "dated", "years", "are", "represented", "in", "the", "Julian", "calendar", "so", "that", "the", "day", "/", "months", "don", "t", "changed", "in", "the", "Text", ...
def switch_dual_dated(self, obj): """ Changed whether this is a dual dated year, or not. Dual dated years are represented in the Julian calendar so that the day/months don't changed in the Text representation. """ if self.dual_dated.get_active(): self.calendar_box.set_active(Date.CAL_JULIAN) self.calendar_box.set_sensitive(0) else: self.calendar_box.set_sensitive(1)
[ "def", "switch_dual_dated", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "dual_dated", ".", "get_active", "(", ")", ":", "self", ".", "calendar_box", ".", "set_active", "(", "Date", ".", "CAL_JULIAN", ")", "self", ".", "calendar_box", ".", "set_...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/editors/editdate.py#L349-L359
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/nodes/object/utility_nodes/transform_object.py
python
TransformObjectNode.execute
(self, object, matrix)
return object
[]
def execute(self, object, matrix): if object is None: return None evaluatedObject = getEvaluatedID(object) if self.useCenter: offset = Matrix.Translation(evaluatedObject.location) transformation = offset @ matrix @ offset.inverted() else: transformation = matrix object.matrix_world = transformation @ evaluatedObject.matrix_world return object
[ "def", "execute", "(", "self", ",", "object", ",", "matrix", ")", ":", "if", "object", "is", "None", ":", "return", "None", "evaluatedObject", "=", "getEvaluatedID", "(", "object", ")", "if", "self", ".", "useCenter", ":", "offset", "=", "Matrix", ".", ...
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/object/utility_nodes/transform_object.py#L23-L32
pseewald/fprettify
cb254022c2034ad3b8f744f4dad1bf5b7438815d
fprettify/__init__.py
python
F90Aligner.get_lines_indent
(self)
return self._line_indents
after processing, retrieve the indents of all line parts.
after processing, retrieve the indents of all line parts.
[ "after", "processing", "retrieve", "the", "indents", "of", "all", "line", "parts", "." ]
def get_lines_indent(self): """after processing, retrieve the indents of all line parts.""" return self._line_indents
[ "def", "get_lines_indent", "(", "self", ")", ":", "return", "self", ".", "_line_indents" ]
https://github.com/pseewald/fprettify/blob/cb254022c2034ad3b8f744f4dad1bf5b7438815d/fprettify/__init__.py#L739-L741
chibisov/drf-extensions
ecdf3a95d7f18ccf9cffa55809635c3715179605
rest_framework_extensions/bulk_operations/mixins.py
python
ListDestroyModelMixin.pre_delete_bulk
(self, queryset)
Placeholder method for calling before deleting an queryset.
Placeholder method for calling before deleting an queryset.
[ "Placeholder", "method", "for", "calling", "before", "deleting", "an", "queryset", "." ]
def pre_delete_bulk(self, queryset): """ Placeholder method for calling before deleting an queryset. """ pass
[ "def", "pre_delete_bulk", "(", "self", ",", "queryset", ")", ":", "pass" ]
https://github.com/chibisov/drf-extensions/blob/ecdf3a95d7f18ccf9cffa55809635c3715179605/rest_framework_extensions/bulk_operations/mixins.py#L47-L51