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
zaxlct/imooc-django
daf1ced745d3d21989e8191b658c293a511b37fd
extra_apps/xadmin/plugins/actions.py
python
ActionPlugin.get_list_display_links
(self, list_display_links)
return list_display_links
[]
def get_list_display_links(self, list_display_links): if self.actions: if len(list_display_links) == 1 and list_display_links[0] == 'action_checkbox': return list(self.admin_view.list_display[1:2]) return list_display_links
[ "def", "get_list_display_links", "(", "self", ",", "list_display_links", ")", ":", "if", "self", ".", "actions", ":", "if", "len", "(", "list_display_links", ")", "==", "1", "and", "list_display_links", "[", "0", "]", "==", "'action_checkbox'", ":", "return", ...
https://github.com/zaxlct/imooc-django/blob/daf1ced745d3d21989e8191b658c293a511b37fd/extra_apps/xadmin/plugins/actions.py#L150-L154
getkeops/keops
fbe73a5de07dabc7c20df9cbb5a7e5e5ad360524
pykeops/common/lazy_tensor.py
python
GenericLazyTensor.norm2
(self)
return self.unary("Norm2", dimres=1)
r""" Euclidean norm - a unary operation. ``x.norm2()`` returns a :class:`LazyTensor` that encodes, symbolically, the Euclidean norm of a vector ``x``.
r""" Euclidean norm - a unary operation.
[ "r", "Euclidean", "norm", "-", "a", "unary", "operation", "." ]
def norm2(self): r""" Euclidean norm - a unary operation. ``x.norm2()`` returns a :class:`LazyTensor` that encodes, symbolically, the Euclidean norm of a vector ``x``. """ return self.unary("Norm2", dimres=1)
[ "def", "norm2", "(", "self", ")", ":", "return", "self", ".", "unary", "(", "\"Norm2\"", ",", "dimres", "=", "1", ")" ]
https://github.com/getkeops/keops/blob/fbe73a5de07dabc7c20df9cbb5a7e5e5ad360524/pykeops/common/lazy_tensor.py#L1436-L1443
abhisharma404/vault
0303cf425f028ce38cfaf40640d625861b7c805a
src/lib/scanner/port_scanner/port_scanner.py
python
PortScanner.port_name
(port)
return names[port]
[]
def port_name(port): with open('port_names.json', 'r') as f: names = json.loads(f) return names[port]
[ "def", "port_name", "(", "port", ")", ":", "with", "open", "(", "'port_names.json'", ",", "'r'", ")", "as", "f", ":", "names", "=", "json", ".", "loads", "(", "f", ")", "return", "names", "[", "port", "]" ]
https://github.com/abhisharma404/vault/blob/0303cf425f028ce38cfaf40640d625861b7c805a/src/lib/scanner/port_scanner/port_scanner.py#L43-L47
Yuliang-Liu/TIoU-metric
1da136386e2d25943d90182345def587fc5a1762
Word_Text-Line/script.py
python
evaluate_method
(gtFilePath, submFilePath, gtTextLineFilePath, evaluationParams)
return resDict
Method evaluate_method: evaluate method and returns the results Results. Dictionary with the following values: - method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 } - samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 }
Method evaluate_method: evaluate method and returns the results Results. Dictionary with the following values: - method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 } - samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 }
[ "Method", "evaluate_method", ":", "evaluate", "method", "and", "returns", "the", "results", "Results", ".", "Dictionary", "with", "the", "following", "values", ":", "-", "method", "(", "required", ")", "Global", "method", "metrics", ".", "Ex", ":", "{", "Pre...
def evaluate_method(gtFilePath, submFilePath, gtTextLineFilePath, evaluationParams): """ Method evaluate_method: evaluate method and returns the results Results. Dictionary with the following values: - method (required) Global method metrics. Ex: { 'Precision':0.8,'Recall':0.9 } - samples (optional) Per sample metrics. Ex: {'sample1' : { 'Precision':0.8,'Recall':0.9 } , 'sample2' : { 'Precision':0.8,'Recall':0.9 } """ for module,alias in evaluation_imports().iteritems(): globals()[alias] = importlib.import_module(module) def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes=np.empty([1,8],dtype='int32') resBoxes[0,0]=int(points[0]) resBoxes[0,4]=int(points[1]) resBoxes[0,1]=int(points[2]) resBoxes[0,5]=int(points[3]) resBoxes[0,2]=int(points[4]) resBoxes[0,6]=int(points[5]) resBoxes[0,3]=int(points[6]) resBoxes[0,7]=int(points[7]) pointMat = resBoxes[0].reshape([2,4]).T return plg.Polygon( pointMat) def rectangle_to_polygon(rect): resBoxes=np.empty([1,8],dtype='int32') resBoxes[0,0]=int(rect.xmin) resBoxes[0,4]=int(rect.ymax) resBoxes[0,1]=int(rect.xmin) resBoxes[0,5]=int(rect.ymin) resBoxes[0,2]=int(rect.xmax) resBoxes[0,6]=int(rect.ymin) resBoxes[0,3]=int(rect.xmax) resBoxes[0,7]=int(rect.ymax) pointMat = resBoxes[0].reshape([2,4]).T return plg.Polygon( pointMat) def rectangle_to_points(rect): points = [int(rect.xmin), int(rect.ymax), int(rect.xmax), int(rect.ymax), int(rect.xmax), int(rect.ymin), int(rect.xmin), int(rect.ymin)] return points def get_intersection_over_gtRegions(pD,pG): try: return get_intersection(pD, pG) / pG.area(); except: return 0 def get_union(pD,pG): areaA = pD.area(); areaB = pG.area(); return areaA + areaB - get_intersection(pD, pG); def get_intersection_over_union(pD,pG): try: return get_intersection(pD, pG) / get_union(pD, pG); except: return 0 def funcCt(x): if x<=0.01: return 1 else: return 1-x def get_text_intersection_over_Gt_area_recall(pD, pG): ''' Ct (cut): Area of ground truth that is not covered by detection bounding box. ''' try: Ct = pG.area() - get_intersection(pD, pG) assert(Ct>=0 and Ct<=pG.area()), 'Invalid Ct value' assert(pG.area()>0), 'Invalid Gt' return (get_intersection(pD, pG) * funcCt(Ct*1.0/pG.area())) / pG.area(); # except Exception as e: print(e) return 0 def get_text_intersection_over_union_recall(pD, pG): ''' Ct (cut): Area of ground truth that is not covered by detection bounding box. ''' try: Ct = pG.area() - get_intersection(pD, pG) assert(Ct>=0 and Ct<=pG.area()), 'Invalid Ct value' assert(pG.area()>0), 'Invalid Gt' return (get_intersection(pD, pG) * funcCt(Ct*1.0/pG.area())) / get_union(pD, pG); except Exception as e: print(e) return 0 def funcOt(x): if x<=0.01: return 1 else: return 1-x def get_text_intersection_over_union_precision(pD, pG, gtNum, gtPolys, gtDontCarePolsNum): ''' Ot (Outlier gt area) ''' Ot = 0 try: inside_pG = pD & pG gt_union_inside_pD = None gt_union_inside_pD_and_pG = None count_initial = 0 for i in xrange(len(gtPolys)): if i!= gtNum and gtNum not in gtDontCarePolsNum: # ignore don't care regions if not get_intersection(pD, gtPolys[i]) == 0: if count_initial == 0: # initial gt_union_inside_pD = gtPolys[i] gt_union_inside_pD_and_pG = inside_pG & gtPolys[i] count_initial = 1 continue gt_union_inside_pD = gt_union_inside_pD | gtPolys[i] inside_pG_i = inside_pG & gtPolys[i] gt_union_inside_pD_and_pG = gt_union_inside_pD_and_pG | inside_pG_i if not gt_union_inside_pD == None: pD_union_with_other_gt = pD & gt_union_inside_pD Ot = pD_union_with_other_gt.area() - gt_union_inside_pD_and_pG.area() if Ot <=1.0e-10: Ot = 0 else: Ot = 0 assert(Ot>=0 and Ot<=pD.area()+0.001), 'Invalid Ot value: '+str(Ot)+' '+str(pD.area()) assert(pD.area()>0), 'Invalid pD: '+str(pD.area()) return (get_intersection(pD, pG) * funcOt(Ot*1.0/pD.area())) / get_union(pD, pG); except Exception as e: print(Ot, pD.area()) print(e) return 0 def get_intersection(pD,pG): pInt = pD & pG if len(pInt) == 0: return 0 return pInt.area() def get_intersection_three(pD,pG,pGi): pInt = pD & pG pInt_3 = pInt & pGi if len(pInt_3) == 0: return 0 return pInt_3.area() def compute_ap(confList, matchList,numGtCare): correct = 0 AP = 0 if len(confList)>0: confList = np.array(confList) matchList = np.array(matchList) sorted_ind = np.argsort(-confList) confList = confList[sorted_ind] matchList = matchList[sorted_ind] for n in range(len(confList)): match = matchList[n] if match: correct += 1 AP += float(correct)/(n + 1) if numGtCare>0: AP /= numGtCare return AP perSampleMetrics = {} matchedSum = 0 matchedSum_iou = 0 matchedSum_tiouGt = 0 matchedSum_tiouDt = 0 matchedSum_cutGt = 0 matchedSum_coverOtherGt = 0 Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax') gt = rrc_evaluation_funcs.load_zip_file(gtFilePath,evaluationParams['GT_SAMPLE_NAME_2_ID']) subm = rrc_evaluation_funcs.load_zip_file(submFilePath,evaluationParams['DET_SAMPLE_NAME_2_ID'],True) gt_tl = rrc_evaluation_funcs.load_zip_file(gtTextLineFilePath,evaluationParams['GT_SAMPLE_NAME_2_ID']) numGlobalCareGt = 0; numGlobalCareDet = 0; arrGlobalConfidences = []; arrGlobalMatches = []; totalNumGtPols = 0 totalNumDetPols = 0 for index_gt, resFile in enumerate(gt): gtFile = rrc_evaluation_funcs.decode_utf8(gt[resFile]) gt_tlFile = rrc_evaluation_funcs.decode_utf8(gt_tl[resFile]) recall = 0 precision = 0 hmean = 0 detMatched = 0 detMatched_iou = 0 detMatched_tiouGt = 0 detMatched_tiouDt = 0 iouMat = np.empty([1,1]) gtPols = [] detPols = [] gt_tlPols = [] gtPolPoints = [] detPolPoints = [] gt_tlPolPoints = [] #Array of Ground Truth Polygons' keys marked as don't Care gtDontCarePolsNum = [] valid_gtDontCare = 0 #Array of Detected Polygons' matched with a don't Care GT detDontCarePolsNum = [] gt_tlDontCarePolsNum = [] pairs = [] detMatchedNums = [] tl_pairs = [] arrSampleConfidences = []; arrSampleMatch = []; sampleAP = 0; evaluationLog = "" pointsList,_,transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(gtFile,evaluationParams['CRLF'],evaluationParams['LTRB'],True,False) tl_pointsList,_,tl_transcriptionsList = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(gt_tlFile,evaluationParams['CRLF'],evaluationParams['LTRB'],True,False) for n in range(len(pointsList)): points = pointsList[n] transcription = transcriptionsList[n] dontCare = transcription == "###" if evaluationParams['LTRB']: gtRect = Rectangle(*points) gtPol = rectangle_to_polygon(gtRect) else: gtPol = polygon_from_points(points) gtPols.append(gtPol) gtPolPoints.append(points) if dontCare: gtDontCarePolsNum.append( len(gtPols)-1 ) for n in range(len(tl_pointsList)): tl_points = tl_pointsList[n] if evaluationParams['LTRB']: gt_tlRect = Rectangle(*tl_points) gt_tlPol = rectangle_to_polygon(gt_tlRect) else: gt_tlPol = polygon_from_points(tl_points) gt_tlPols.append(gt_tlPol) gt_tlPolPoints.append(tl_points) evaluationLog += "GT polygons: " + str(len(gtPols)) + " GT-Textline polygons: " + str(len(gt_tlPols)) + (" (" + str(len(gtDontCarePolsNum)) + " don't care)\n" if len(gtDontCarePolsNum)>0 else "\n") if resFile in subm: detFile = rrc_evaluation_funcs.decode_utf8(subm[resFile]) pointsList,confidencesList,_ = rrc_evaluation_funcs.get_tl_line_values_from_file_contents(detFile,evaluationParams['CRLF'],evaluationParams['LTRB'],False,evaluationParams['CONFIDENCES']) for n in range(len(pointsList)): points = pointsList[n] if evaluationParams['LTRB']: detRect = Rectangle(*points) detPol = rectangle_to_polygon(detRect) else: detPol = polygon_from_points(points) detPols.append(detPol) detPolPoints.append(points) if len(gtDontCarePolsNum)>0 : for dontCarePol in gtDontCarePolsNum: dontCarePol = gtPols[dontCarePol] intersected_area = get_intersection(dontCarePol,detPol) pdDimensions = detPol.area() precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT'] ): detDontCarePolsNum.append( len(detPols)-1 ) break evaluationLog += "DET polygons: " + str(len(detPols)) + (" (" + str(len(detDontCarePolsNum)) + " don't care)\n" if len(detDontCarePolsNum)>0 else "\n") if len(gtPols)>0 and len(detPols)>0: #Calculate IoU and precision matrixs outputShape=[len(gtPols),len(detPols)] iouMat = np.empty(outputShape) gtRectMat = np.zeros(len(gtPols),np.int8) gttlRectMat = np.zeros(len(gt_tlPols),np.int8) detRectMat = np.zeros(len(detPols),np.int8) tiouRecallMat = np.empty(outputShape) tiouPrecisionMat = np.empty(outputShape) tiouGtRectMat = np.zeros(len(gtPols),np.int8) tiouDetRectMat = np.zeros(len(detPols),np.int8) ioGt_Mat = np.zeros(outputShape) area_tiouRecallMat = np.zeros(outputShape) # text-line evaluation is calculated in advance. gt_and_gt_tl_outputShape=[len(gt_tlPols), len(gtPols)] gt_and_gt_tl_Mat = np.zeros(gt_and_gt_tl_outputShape) tl_outputShape=[len(gt_tlPols),len(detPols)] tl_iouMat = np.zeros(tl_outputShape) tl_tiouPrecisionMat = np.zeros(tl_outputShape) tl_tiouGtRectMat = np.zeros(len(gt_tlPols),np.int8) tl_tiouDetRectMat = np.zeros(len(detPols),np.int8) for gt_tlNum in range(len(gt_tlPols)): # for gt_Num in range(len(gtPols)): gt_and_gt_tl_Mat[gt_tlNum,gt_Num] = get_intersection_over_gtRegions(gt_tlPols[gt_tlNum],gtPols[gt_Num]) gt_gt_tl_Matching_index = np.where(gt_and_gt_tl_Mat >= 0.5) for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): pG = gtPols[gtNum] pD = detPols[detNum] iouMat[gtNum,detNum] = get_intersection_over_union(pD,pG) tiouRecallMat[gtNum,detNum] = get_text_intersection_over_union_recall(pD,pG) tiouPrecisionMat[gtNum,detNum] = get_text_intersection_over_union_precision(pD, pG, gtNum, gtPols, gtDontCarePolsNum) ioGt_Mat[gtNum,detNum] = get_intersection_over_gtRegions(pD,pG) area_tiouRecallMat[gtNum,detNum] = get_text_intersection_over_Gt_area_recall(pD,pG) for gt_tlNum in range(len(gt_tlPols)): for detNum in range(len(detPols)): pG = gt_tlPols[gt_tlNum] pD = detPols[detNum] tl_iouMat[gt_tlNum,detNum] = get_intersection_over_union(pD,pG) tl_tiouPrecisionMat[gt_tlNum,detNum] = get_text_intersection_over_union_precision(pD, pG, gt_tlNum, gtPols, []) if gttlRectMat[gt_tlNum] == 0 and detRectMat[detNum] == 0 and detNum not in detDontCarePolsNum: if tl_iouMat[gt_tlNum,detNum]>evaluationParams['IOU_CONSTRAINT']: detRectMat[detNum] = 1 gttlRectMat[gt_tlNum] = 1 detMatched += 1 detMatched_tiouDt += tl_tiouPrecisionMat[gt_tlNum,detNum] # ---- WordMatchTl wmtl = gt_gt_tl_Matching_index[1][np.where(gt_gt_tl_Matching_index[0] == gt_tlNum)[0]] for w2tl_index in wmtl: if ioGt_Mat[w2tl_index, detNum]>0.5: gtRectMat[w2tl_index] = 1 gtDontCarePolsNum.append(w2tl_index) valid_gtDontCare += 1 if len(wmtl)>=2: # Normally, each TL annotation should contain at least two gt from WL annotations. detMatched_tiouGt += area_tiouRecallMat[w2tl_index,detNum] else: detMatched_tiouGt += tiouRecallMat[w2tl_index,detNum] # same as OO match. tl_pairs.append({'gt_tl':gt_tlNum,'det':detNum}) detMatchedNums.append(detNum) evaluationLog += "Match GT #" + str(gt_tlNum) + " with Det #" + str(detNum) + "\n" if len(gtDontCarePolsNum)>0: # ---- redefined. for dontCarePolStage2 in gtDontCarePolsNum: for detNum in range(len(detPols)): if detRectMat[detNum] == 0 and detNum not in detDontCarePolsNum: detPol = detPols[detNum] plgStage2 = gtPols[dontCarePolStage2] intersected_area = get_intersection(plgStage2,detPol) pdDimensions = detPol.area() precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions if (precision > evaluationParams['AREA_PRECISION_CONSTRAINT']): detDontCarePolsNum.append(detNum) break for gtNum in range(len(gtPols)): for detNum in range(len(detPols)): if gtRectMat[gtNum] == 0 and detRectMat[detNum] == 0 and gtNum not in gtDontCarePolsNum and detNum not in detDontCarePolsNum: if iouMat[gtNum,detNum]>evaluationParams['IOU_CONSTRAINT']: gtRectMat[gtNum] = 1 detRectMat[detNum] = 1 detMatched += 1 detMatched_tiouGt += tiouRecallMat[gtNum,detNum] detMatched_tiouDt += tiouPrecisionMat[gtNum,detNum] pairs.append({'gt':gtNum,'det':detNum}) detMatchedNums.append(detNum) evaluationLog += "Match GT #" + str(gtNum) + " with Det #" + str(detNum) + "\n" if evaluationParams['CONFIDENCES']: for detNum in range(len(detPols)): if detNum not in detDontCarePolsNum : #we exclude the don't care detections match = detNum in detMatchedNums arrSampleConfidences.append(confidencesList[detNum]) arrSampleMatch.append(match) arrGlobalConfidences.append(confidencesList[detNum]); arrGlobalMatches.append(match); numGtCare = (len(gtPols) - len(gtDontCarePolsNum) + valid_gtDontCare) numDetCare = (len(detPols) - len(detDontCarePolsNum)) if numGtCare == 0: recall = float(1) precision = float(0) if numDetCare >0 else float(1) sampleAP = precision tiouRecall = float(1) tiouPrecision = float(0) if numDetCare >0 else float(1) else: recall = float(detMatched) / numGtCare precision = 0 if numDetCare==0 else float(detMatched) / numDetCare tiouRecall = float(detMatched_tiouGt) / numGtCare tiouPrecision = 0 if numDetCare==0 else float(detMatched_tiouDt) / numDetCare if evaluationParams['CONFIDENCES'] and evaluationParams['PER_SAMPLE_RESULTS']: sampleAP = compute_ap(arrSampleConfidences, arrSampleMatch, numGtCare ) hmean = 0 if (precision + recall)==0 else 2.0 * precision * recall / (precision + recall) tiouHmean = 0 if (tiouPrecision + tiouRecall)==0 else 2.0 * tiouPrecision * tiouRecall / (tiouPrecision + tiouRecall) matchedSum += detMatched matchedSum_tiouGt += detMatched_tiouGt matchedSum_tiouDt += detMatched_tiouDt numGlobalCareGt += numGtCare numGlobalCareDet += numDetCare if evaluationParams['PER_SAMPLE_RESULTS']: perSampleMetrics[resFile] = { 'precision':precision, 'recall':recall, 'hmean':hmean, 'tiouPrecision':tiouPrecision, 'tiouRecall':tiouRecall, 'tiouHmean':tiouHmean, 'pairs':pairs, 'AP':sampleAP, 'iouMat':[] if len(detPols)>100 else iouMat.tolist(), 'gtPolPoints':gtPolPoints, 'detPolPoints':detPolPoints, 'gtDontCare':gtDontCarePolsNum, 'detDontCare':detDontCarePolsNum, 'evaluationParams': evaluationParams, 'evaluationLog': evaluationLog } try: totalNumGtPols += len(gtPols) totalNumDetPols += len(detPols) except Exception as e: raise e AP = 0 if evaluationParams['CONFIDENCES']: AP = compute_ap(arrGlobalConfidences, arrGlobalMatches, numGlobalCareGt) print('num_gt, num_det: ', numGlobalCareGt, totalNumDetPols) methodRecall = 0 if numGlobalCareGt == 0 else float(matchedSum)/numGlobalCareGt methodPrecision = 0 if numGlobalCareDet == 0 else float(matchedSum)/numGlobalCareDet methodHmean = 0 if methodRecall + methodPrecision==0 else 2* methodRecall * methodPrecision / (methodRecall + methodPrecision) methodRecall_tiouGt = 0 if numGlobalCareGt == 0 else float(matchedSum_tiouGt)/numGlobalCareGt methodPrecision_tiouDt = 0 if numGlobalCareDet == 0 else float(matchedSum_tiouDt)/numGlobalCareDet tiouMethodHmean = 0 if methodRecall_tiouGt + methodPrecision_tiouDt==0 else 2* methodRecall_tiouGt * methodPrecision_tiouDt / (methodRecall_tiouGt + methodPrecision_tiouDt) methodMetrics = {'precision':methodPrecision, 'recall':methodRecall,'hmean': methodHmean} tiouMethodMetrics = {'tiouPrecision':methodPrecision_tiouDt, 'tiouRecall':methodRecall_tiouGt,'tiouHmean': tiouMethodHmean } print('Origin:') print("recall: ", round(methodRecall,3), "precision: ", round(methodPrecision,3), "hmean: ", round(methodHmean,3)) print('tiouNewMetric:') print("tiouRecall:", round(methodRecall_tiouGt,3), "tiouPrecision:", round(methodPrecision_tiouDt,3), "tiouHmean:", round(tiouMethodHmean,3)) resDict = {'calculated':True,'Message':'','method': methodMetrics,'per_sample': perSampleMetrics, 'tiouMethod': tiouMethodMetrics} return resDict;
[ "def", "evaluate_method", "(", "gtFilePath", ",", "submFilePath", ",", "gtTextLineFilePath", ",", "evaluationParams", ")", ":", "for", "module", ",", "alias", "in", "evaluation_imports", "(", ")", ".", "iteritems", "(", ")", ":", "globals", "(", ")", "[", "a...
https://github.com/Yuliang-Liu/TIoU-metric/blob/1da136386e2d25943d90182345def587fc5a1762/Word_Text-Line/script.py#L63-L536
SPFlow/SPFlow
68ce7dac0f41bd3cf86ccb56555a29ef1368fe69
src/spn/structure/leaves/piecewise/PiecewiseLinear.py
python
isotonic_unimodal_regression_R
(x, y)
return iso_x, iso_y
Perform unimodal isotonic regression via the Iso package in R
Perform unimodal isotonic regression via the Iso package in R
[ "Perform", "unimodal", "isotonic", "regression", "via", "the", "Iso", "package", "in", "R" ]
def isotonic_unimodal_regression_R(x, y): """ Perform unimodal isotonic regression via the Iso package in R """ from rpy2.robjects.packages import importr from rpy2 import robjects from rpy2.robjects import numpy2ri numpy2ri.activate() # n_instances = x.shape[0] # assert y.shape[0] == n_instances importr("Iso") z = robjects.r["ufit"](y, x=x, type="b") iso_x, iso_y = np.array(z.rx2("x")), np.array(z.rx2("y")) return iso_x, iso_y
[ "def", "isotonic_unimodal_regression_R", "(", "x", ",", "y", ")", ":", "from", "rpy2", ".", "robjects", ".", "packages", "import", "importr", "from", "rpy2", "import", "robjects", "from", "rpy2", ".", "robjects", "import", "numpy2ri", "numpy2ri", ".", "activat...
https://github.com/SPFlow/SPFlow/blob/68ce7dac0f41bd3cf86ccb56555a29ef1368fe69/src/spn/structure/leaves/piecewise/PiecewiseLinear.py#L62-L78
rlworkgroup/garage
b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507
src/garage/torch/algos/td3.py
python
TD3.networks
(self)
return [ self.policy, self._qf_1, self._qf_2, self._target_policy, self._target_qf_1, self._target_qf_2 ]
Return all the networks within the model. Returns: list: A list of networks.
Return all the networks within the model.
[ "Return", "all", "the", "networks", "within", "the", "model", "." ]
def networks(self): """Return all the networks within the model. Returns: list: A list of networks. """ return [ self.policy, self._qf_1, self._qf_2, self._target_policy, self._target_qf_1, self._target_qf_2 ]
[ "def", "networks", "(", "self", ")", ":", "return", "[", "self", ".", "policy", ",", "self", ".", "_qf_1", ",", "self", ".", "_qf_2", ",", "self", ".", "_target_policy", ",", "self", ".", "_target_qf_1", ",", "self", ".", "_target_qf_2", "]" ]
https://github.com/rlworkgroup/garage/blob/b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507/src/garage/torch/algos/td3.py#L379-L389
pytorchbearer/torchbearer
9d97c60ec4deb37a0627311ddecb9c6f1429cd82
torchbearer/metrics/wrappers.py
python
ToDict.process_train
(self, *args)
[]
def process_train(self, *args): val = self.metric.process(*args) if val is not None: return {self.metric.name: val}
[ "def", "process_train", "(", "self", ",", "*", "args", ")", ":", "val", "=", "self", ".", "metric", ".", "process", "(", "*", "args", ")", "if", "val", "is", "not", "None", ":", "return", "{", "self", ".", "metric", ".", "name", ":", "val", "}" ]
https://github.com/pytorchbearer/torchbearer/blob/9d97c60ec4deb37a0627311ddecb9c6f1429cd82/torchbearer/metrics/wrappers.py#L43-L46
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/data/owmelt.py
python
OWMelt.commit
(self)
[]
def commit(self): self.Error.clear() if self.data: output = self._reshape_to_long() self.Outputs.data.send(output) self._store_output_desc(output) else: self.Outputs.data.send(None) self._output_desc = None
[ "def", "commit", "(", "self", ")", ":", "self", ".", "Error", ".", "clear", "(", ")", "if", "self", ".", "data", ":", "output", "=", "self", ".", "_reshape_to_long", "(", ")", "self", ".", "Outputs", ".", "data", ".", "send", "(", "output", ")", ...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/data/owmelt.py#L167-L175
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/core/debugger.py
python
Pdb.do_pinfo2
(self, arg)
Provide extra detailed information about an object. The debugger interface to %pinfo2, i.e., obj??.
Provide extra detailed information about an object.
[ "Provide", "extra", "detailed", "information", "about", "an", "object", "." ]
def do_pinfo2(self, arg): """Provide extra detailed information about an object. The debugger interface to %pinfo2, i.e., obj??.""" namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces)
[ "def", "do_pinfo2", "(", "self", ",", "arg", ")", ":", "namespaces", "=", "[", "(", "\"Locals\"", ",", "self", ".", "curframe_locals", ")", ",", "(", "\"Globals\"", ",", "self", ".", "curframe", ".", "f_globals", ")", ",", "]", "self", ".", "shell", ...
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/core/debugger.py#L761-L769
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/guardian/__init__.py
python
PairedSensorEntity.async_added_to_hass
(self)
Perform tasks when the entity is added.
Perform tasks when the entity is added.
[ "Perform", "tasks", "when", "the", "entity", "is", "added", "." ]
async def async_added_to_hass(self) -> None: """Perform tasks when the entity is added.""" self._async_update_from_latest_data()
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":", "self", ".", "_async_update_from_latest_data", "(", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/guardian/__init__.py#L446-L448
plone/Products.CMFPlone
83137764e3e7e4fe60d03c36dfc6ba9c7c543324
Products/CMFPlone/interfaces/installable.py
python
INonInstallable.getNonInstallableProducts
()
Returns a list of products that should not be available for installation.
Returns a list of products that should not be available for installation.
[ "Returns", "a", "list", "of", "products", "that", "should", "not", "be", "available", "for", "installation", "." ]
def getNonInstallableProducts(): """Returns a list of products that should not be available for installation. """
[ "def", "getNonInstallableProducts", "(", ")", ":" ]
https://github.com/plone/Products.CMFPlone/blob/83137764e3e7e4fe60d03c36dfc6ba9c7c543324/Products/CMFPlone/interfaces/installable.py#L14-L17
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/utils/checksums.py
python
luhn
(candidate)
Checks a candidate number for validity according to the Luhn algorithm (used in validation of, for example, credit cards). Both numeric and string candidates are accepted.
Checks a candidate number for validity according to the Luhn algorithm (used in validation of, for example, credit cards). Both numeric and string candidates are accepted.
[ "Checks", "a", "candidate", "number", "for", "validity", "according", "to", "the", "Luhn", "algorithm", "(", "used", "in", "validation", "of", "for", "example", "credit", "cards", ")", ".", "Both", "numeric", "and", "string", "candidates", "are", "accepted", ...
def luhn(candidate): """ Checks a candidate number for validity according to the Luhn algorithm (used in validation of, for example, credit cards). Both numeric and string candidates are accepted. """ if not isinstance(candidate, six.string_types): candidate = str(candidate) try: evens = sum([int(c) for c in candidate[-1::-2]]) odds = sum([LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2]]) return ((evens + odds) % 10 == 0) except ValueError: # Raised if an int conversion fails return False
[ "def", "luhn", "(", "candidate", ")", ":", "if", "not", "isinstance", "(", "candidate", ",", "six", ".", "string_types", ")", ":", "candidate", "=", "str", "(", "candidate", ")", "try", ":", "evens", "=", "sum", "(", "[", "int", "(", "c", ")", "for...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/utils/checksums.py#L11-L24
mandiant/ioc_writer
712247f3a10bdc2584fa18ac909fc763f71df21a
ioc_writer/managers/downgrade_11.py
python
DowngradeManager.convert_branch
(self, old_node, new_node, ids_to_skip, comment_dict=None)
return True
Recursively walk a indicator logic tree, starting from a Indicator node. Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order. :param old_node: An Indicator node, which we walk down to convert :param new_node: An Indicator node, which we add new IndicatorItem and Indicator nodes too :param ids_to_skip: set of node @id values not to convert :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: returns True upon completion. :raises: DowngradeError if there is a problem during the conversion.
Recursively walk a indicator logic tree, starting from a Indicator node. Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order.
[ "Recursively", "walk", "a", "indicator", "logic", "tree", "starting", "from", "a", "Indicator", "node", ".", "Converts", "OpenIOC", "1", ".", "1", "Indicator", "/", "IndicatorItems", "to", "Openioc", "1", ".", "0", "and", "preserves", "order", "." ]
def convert_branch(self, old_node, new_node, ids_to_skip, comment_dict=None): """ Recursively walk a indicator logic tree, starting from a Indicator node. Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order. :param old_node: An Indicator node, which we walk down to convert :param new_node: An Indicator node, which we add new IndicatorItem and Indicator nodes too :param ids_to_skip: set of node @id values not to convert :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: returns True upon completion. :raises: DowngradeError if there is a problem during the conversion. """ expected_tag = 'Indicator' if old_node.tag != expected_tag: raise DowngradeError('old_node expected tag is [%s]' % expected_tag) if not comment_dict: comment_dict = {} for node in old_node.getchildren(): node_id = node.get('id') if node_id in ids_to_skip: continue if node.tag == 'IndicatorItem': negation = node.get('negate') condition = node.get('condition') if 'true' in negation.lower(): new_condition = condition + 'not' else: new_condition = condition document = node.xpath('Context/@document')[0] search = node.xpath('Context/@search')[0] content_type = node.xpath('Content/@type')[0] content = node.findtext('Content') context_type = node.xpath('Context/@type')[0] new_ii_node = ioc_api.make_indicatoritem_node(condition=condition, document=document, search=search, content_type=content_type, content=content, context_type=context_type, nid=node_id) # set condition new_ii_node.attrib['condition'] = new_condition # set comment if node_id in comment_dict: comment = comment_dict[node_id] comment_node = et.Element('Comment') comment_node.text = comment new_ii_node.append(comment_node) # remove preserver-case and negate del new_ii_node.attrib['negate'] del new_ii_node.attrib['preserve-case'] new_node.append(new_ii_node) elif node.tag == 'Indicator': operator = node.get('operator') if operator.upper() not in ['OR', 'AND']: raise DowngradeError('Indicator@operator is not AND/OR. [%s] has [%s]' % (node_id, operator)) new_i_node = ioc_api.make_indicator_node(operator, node_id) new_node.append(new_i_node) self.convert_branch(node, new_i_node, ids_to_skip, comment_dict) else: # should never get here raise DowngradeError('node is not a Indicator/IndicatorItem') return True
[ "def", "convert_branch", "(", "self", ",", "old_node", ",", "new_node", ",", "ids_to_skip", ",", "comment_dict", "=", "None", ")", ":", "expected_tag", "=", "'Indicator'", "if", "old_node", ".", "tag", "!=", "expected_tag", ":", "raise", "DowngradeError", "(",...
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/managers/downgrade_11.py#L228-L291
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/type_info.py
python
Bytes.ToString
(self, value: bytes)
return value.decode("utf-8")
[]
def ToString(self, value: bytes) -> Text: precondition.AssertType(value, bytes) return value.decode("utf-8")
[ "def", "ToString", "(", "self", ",", "value", ":", "bytes", ")", "->", "Text", ":", "precondition", ".", "AssertType", "(", "value", ",", "bytes", ")", "return", "value", ".", "decode", "(", "\"utf-8\"", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/type_info.py#L428-L430
wakatime/komodo-wakatime
8923c04ded9fa64d7374fadd8cde3a6fadfe053d
components/wakatime/packages/pygments/lexers/data.py
python
YamlLexer.reset_indent
(token_class)
return callback
Reset the indentation levels.
Reset the indentation levels.
[ "Reset", "the", "indentation", "levels", "." ]
def reset_indent(token_class): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), token_class, text context.pos = match.end() return callback
[ "def", "reset_indent", "(", "token_class", ")", ":", "def", "callback", "(", "lexer", ",", "match", ",", "context", ")", ":", "text", "=", "match", ".", "group", "(", ")", "context", ".", "indent_stack", "=", "[", "]", "context", ".", "indent", "=", ...
https://github.com/wakatime/komodo-wakatime/blob/8923c04ded9fa64d7374fadd8cde3a6fadfe053d/components/wakatime/packages/pygments/lexers/data.py#L56-L66
ducksboard/libsaas
615981a3336f65be9d51ae95a48aed9ad3bd1c3c
libsaas/services/desk/service.py
python
Desk.user
(self, user_id)
return users.User(self, user_id)
Return the resource corresponding to a single user.
Return the resource corresponding to a single user.
[ "Return", "the", "resource", "corresponding", "to", "a", "single", "user", "." ]
def user(self, user_id): """ Return the resource corresponding to a single user. """ return users.User(self, user_id)
[ "def", "user", "(", "self", ",", "user_id", ")", ":", "return", "users", ".", "User", "(", "self", ",", "user_id", ")" ]
https://github.com/ducksboard/libsaas/blob/615981a3336f65be9d51ae95a48aed9ad3bd1c3c/libsaas/services/desk/service.py#L138-L142
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/gtk_extras/WidgetSaver.py
python
WidgetPrefs.toggle_widget
(self, w, val)
Toggle the visibility of widget 'w
Toggle the visibility of widget 'w
[ "Toggle", "the", "visibility", "of", "widget", "w" ]
def toggle_widget (self, w, val): """Toggle the visibility of widget 'w'""" if val: method = 'hide' else: method = 'show' if isinstance(w, str): w = [w] for wn in w: widg = self.glade.get_widget(wn) if widg: getattr(widg,method)() else: debug('There is no widget %s'%wn,1)
[ "def", "toggle_widget", "(", "self", ",", "w", ",", "val", ")", ":", "if", "val", ":", "method", "=", "'hide'", "else", ":", "method", "=", "'show'", "if", "isinstance", "(", "w", ",", "str", ")", ":", "w", "=", "[", "w", "]", "for", "wn", "in"...
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/gtk_extras/WidgetSaver.py#L91-L102
bfirsh/loom
d3108aa495474c785c50d0e3537bfb5ba34aad06
loom/utils.py
python
upload_dir
(src, dest, use_sudo=False)
Fabric's rsync_project with some sane settings
Fabric's rsync_project with some sane settings
[ "Fabric", "s", "rsync_project", "with", "some", "sane", "settings" ]
def upload_dir(src, dest, use_sudo=False): """ Fabric's rsync_project with some sane settings """ extra_opts = ['--exclude=".git*"', '--copy-links'] if use_sudo: extra_opts.append('--rsync-path="sudo rsync"') rsync_project( local_dir=src, remote_dir=dest, delete=True, extra_opts=' '.join(extra_opts), ssh_opts='-oStrictHostKeyChecking=no' )
[ "def", "upload_dir", "(", "src", ",", "dest", ",", "use_sudo", "=", "False", ")", ":", "extra_opts", "=", "[", "'--exclude=\".git*\"'", ",", "'--copy-links'", "]", "if", "use_sudo", ":", "extra_opts", ".", "append", "(", "'--rsync-path=\"sudo rsync\"'", ")", "...
https://github.com/bfirsh/loom/blob/d3108aa495474c785c50d0e3537bfb5ba34aad06/loom/utils.py#L4-L17
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/platforms.py
python
_setuid
(uid, gid)
[]
def _setuid(uid, gid): # If GID isn't defined, get the primary GID of the user. if not gid and pwd: gid = pwd.getpwuid(uid).pw_gid # Must set the GID before initgroups(), as setgid() # is known to zap the group list on some platforms. # setgid must happen before setuid (otherwise the setgid operation # may fail because of insufficient privileges and possibly stay # in a privileged group). setgid(gid) initgroups(uid, gid) # at last: setuid(uid) # ... and make sure privileges cannot be restored: try: setuid(0) except OSError as exc: if exc.errno != errno.EPERM: raise # we should get here: cannot restore privileges, # everything was fine. else: raise SecurityError( 'non-root user able to restore privileges after setuid.')
[ "def", "_setuid", "(", "uid", ",", "gid", ")", ":", "# If GID isn't defined, get the primary GID of the user.", "if", "not", "gid", "and", "pwd", ":", "gid", "=", "pwd", ".", "getpwuid", "(", "uid", ")", ".", "pw_gid", "# Must set the GID before initgroups(), as set...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/platforms.py#L547-L572
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/events/events_client.py
python
EventsClient.change_rule_compartment
(self, rule_id, change_rule_compartment_details, **kwargs)
Moves a rule into a different compartment within the same tenancy. For information about moving resources between compartments, see `Moving Resources to a Different Compartment`__. __ https://docs.cloud.oracle.com/iaas/Content/Identity/Tasks/managingcompartments.htm#moveRes :param str rule_id: (required) The `OCID`__ of this rule. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param oci.events.models.ChangeRuleCompartmentDetails change_rule_compartment_details: (required) :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the if-match parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param str opc_request_id: (optional) The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/events/change_rule_compartment.py.html>`__ to see an example of how to use change_rule_compartment API.
Moves a rule into a different compartment within the same tenancy. For information about moving resources between compartments, see `Moving Resources to a Different Compartment`__.
[ "Moves", "a", "rule", "into", "a", "different", "compartment", "within", "the", "same", "tenancy", ".", "For", "information", "about", "moving", "resources", "between", "compartments", "see", "Moving", "Resources", "to", "a", "Different", "Compartment", "__", "....
def change_rule_compartment(self, rule_id, change_rule_compartment_details, **kwargs): """ Moves a rule into a different compartment within the same tenancy. For information about moving resources between compartments, see `Moving Resources to a Different Compartment`__. __ https://docs.cloud.oracle.com/iaas/Content/Identity/Tasks/managingcompartments.htm#moveRes :param str rule_id: (required) The `OCID`__ of this rule. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param oci.events.models.ChangeRuleCompartmentDetails change_rule_compartment_details: (required) :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the if-match parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param str opc_request_id: (optional) The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/events/change_rule_compartment.py.html>`__ to see an example of how to use change_rule_compartment API. """ resource_path = "/rules/{ruleId}/actions/changeCompartment" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "if_match", "opc_request_id", "opc_retry_token" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "change_rule_compartment got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "ruleId": rule_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "if-match": kwargs.get("if_match", missing), "opc-request-id": kwargs.get("opc_request_id", missing), "opc-retry-token": kwargs.get("opc_retry_token", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_retry_token_if_needed(header_params) self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=change_rule_compartment_details) else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=change_rule_compartment_details)
[ "def", "change_rule_compartment", "(", "self", ",", "rule_id", ",", "change_rule_compartment_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/rules/{ruleId}/actions/changeCompartment\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "expe...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/events/events_client.py#L102-L204
apple/swift-source-compat-suite
89d65bf2e6de29a11be61b3e67384c347faf5a53
builder.py
python
parse_args
()
return parser.parse_args()
Return parsed command line arguments.
Return parsed command line arguments.
[ "Return", "parsed", "command", "line", "arguments", "." ]
def parse_args(): """Return parsed command line arguments.""" parser = argparse.ArgumentParser() project.add_arguments(parser) return parser.parse_args()
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "project", ".", "add_arguments", "(", "parser", ")", "return", "parser", ".", "parse_args", "(", ")" ]
https://github.com/apple/swift-source-compat-suite/blob/89d65bf2e6de29a11be61b3e67384c347faf5a53/builder.py#L24-L28
yrq110/TinyGoogle
f92d7ce1e8a295c9e95c20c25a8dd3bcf1d6dab7
app.py
python
index
()
return render_template('index.html',name='index')
[]
def index(): return render_template('index.html',name='index')
[ "def", "index", "(", ")", ":", "return", "render_template", "(", "'index.html'", ",", "name", "=", "'index'", ")" ]
https://github.com/yrq110/TinyGoogle/blob/f92d7ce1e8a295c9e95c20c25a8dd3bcf1d6dab7/app.py#L11-L12
nschaetti/EchoTorch
cba209c49e0fda73172d2e853b85c747f9f5117e
echotorch/data/random_processes.py
python
ema
()
r"""Alias for :func:`echotorch.data.exponential_moving_average`.
r"""Alias for :func:`echotorch.data.exponential_moving_average`.
[ "r", "Alias", "for", ":", "func", ":", "echotorch", ".", "data", ".", "exponential_moving_average", "." ]
def ema() -> List[echotorch.TimeTensor]: r"""Alias for :func:`echotorch.data.exponential_moving_average`. """ pass
[ "def", "ema", "(", ")", "->", "List", "[", "echotorch", ".", "TimeTensor", "]", ":", "pass" ]
https://github.com/nschaetti/EchoTorch/blob/cba209c49e0fda73172d2e853b85c747f9f5117e/echotorch/data/random_processes.py#L398-L401
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/ticker.py
python
LinearLocator.__call__
(self)
return self.tick_values(vmin, vmax)
Return the locations of the ticks
Return the locations of the ticks
[ "Return", "the", "locations", "of", "the", "ticks" ]
def __call__(self): 'Return the locations of the ticks' vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax)
[ "def", "__call__", "(", "self", ")", ":", "vmin", ",", "vmax", "=", "self", ".", "axis", ".", "get_view_interval", "(", ")", "return", "self", ".", "tick_values", "(", "vmin", ",", "vmax", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/ticker.py#L1056-L1059
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/logging/handlers.py
python
SysLogHandler.close
(self)
Closes the socket.
Closes the socket.
[ "Closes", "the", "socket", "." ]
def close(self): """ Closes the socket. """ self.acquire() try: self.socket.close() logging.Handler.close(self) finally: self.release()
[ "def", "close", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "self", ".", "socket", ".", "close", "(", ")", "logging", ".", "Handler", ".", "close", "(", "self", ")", "finally", ":", "self", ".", "release", "(", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/logging/handlers.py#L886-L895
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/_erfa/erfa_generator.py
python
Variable.view_dtype
(self)
Name of dtype corresponding to the ctype for viewing back as array. E.g., dt_double for double, dt_double33 for double[3][3]. The types are defined in core.py, where they are used for view-casts of structured results as regular arrays.
Name of dtype corresponding to the ctype for viewing back as array.
[ "Name", "of", "dtype", "corresponding", "to", "the", "ctype", "for", "viewing", "back", "as", "array", "." ]
def view_dtype(self): """Name of dtype corresponding to the ctype for viewing back as array. E.g., dt_double for double, dt_double33 for double[3][3]. The types are defined in core.py, where they are used for view-casts of structured results as regular arrays. """ if self.ctype == 'const char': return 'dt_bytes12' elif self.ctype == 'char': return 'dt_bytes1' else: raise ValueError('Only char ctype should need view back!')
[ "def", "view_dtype", "(", "self", ")", ":", "if", "self", ".", "ctype", "==", "'const char'", ":", "return", "'dt_bytes12'", "elif", "self", ".", "ctype", "==", "'char'", ":", "return", "'dt_bytes1'", "else", ":", "raise", "ValueError", "(", "'Only char ctyp...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/_erfa/erfa_generator.py#L190-L203
isocpp/CppCoreGuidelines
171fda35972cb0678c26274547be3d5dfaf73156
scripts/python/cpplint.py
python
FileInfo.RepositoryName
(self)
return fullname
r"""FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors.
r"""FullName after removing the local path to the repository.
[ "r", "FullName", "after", "removing", "the", "local", "path", "to", "the", "repository", "." ]
def RepositoryName(self): r"""FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) # If the user specified a repository path, it exists, and the file is # contained in it, use the specified repository path if _repository: repo = FileInfo(_repository).FullName() root_dir = project_dir while os.path.exists(root_dir): # allow case insensitive compare on Windows if os.path.normcase(root_dir) == os.path.normcase(repo): return os.path.relpath(fullname, root_dir).replace('\\', '/') one_up_dir = os.path.dirname(root_dir) if one_up_dir == root_dir: break root_dir = one_up_dir if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = current_dir = os.path.dirname(fullname) while current_dir != os.path.dirname(current_dir): if (os.path.exists(os.path.join(current_dir, ".git")) or os.path.exists(os.path.join(current_dir, ".hg")) or os.path.exists(os.path.join(current_dir, ".svn"))): root_dir = current_dir current_dir = os.path.dirname(current_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname
[ "def", "RepositoryName", "(", "self", ")", ":", "fullname", "=", "self", ".", "FullName", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "project_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "# If ...
https://github.com/isocpp/CppCoreGuidelines/blob/171fda35972cb0678c26274547be3d5dfaf73156/scripts/python/cpplint.py#L1264-L1322
kupferlauncher/kupfer
1c1e9bcbce05a82f503f68f8b3955c20b02639b3
waflib/extras/compat15.py
python
apply_uselib_local
(self)
process the uselib_local attribute execute after apply_link because of the execution order set on 'link_task'
process the uselib_local attribute execute after apply_link because of the execution order set on 'link_task'
[ "process", "the", "uselib_local", "attribute", "execute", "after", "apply_link", "because", "of", "the", "execution", "order", "set", "on", "link_task" ]
def apply_uselib_local(self): """ process the uselib_local attribute execute after apply_link because of the execution order set on 'link_task' """ env = self.env from waflib.Tools.ccroot import stlink_task # 1. the case of the libs defined in the project (visit ancestors first) # the ancestors external libraries (uselib) will be prepended self.uselib = self.to_list(getattr(self, 'uselib', [])) self.includes = self.to_list(getattr(self, 'includes', [])) names = self.to_list(getattr(self, 'uselib_local', [])) get = self.bld.get_tgen_by_name seen = set() seen_uselib = set() tmp = Utils.deque(names) # consume a copy of the list of names if tmp: if Logs.verbose: Logs.warn('compat: "uselib_local" is deprecated, replace by "use"') while tmp: lib_name = tmp.popleft() # visit dependencies only once if lib_name in seen: continue y = get(lib_name) y.post() seen.add(lib_name) # object has ancestors to process (shared libraries): add them to the end of the list if getattr(y, 'uselib_local', None): for x in self.to_list(getattr(y, 'uselib_local', [])): obj = get(x) obj.post() if getattr(obj, 'link_task', None): if not isinstance(obj.link_task, stlink_task): tmp.append(x) # link task and flags if getattr(y, 'link_task', None): link_name = y.target[y.target.rfind(os.sep) + 1:] if isinstance(y.link_task, stlink_task): env.append_value('STLIB', [link_name]) else: # some linkers can link against programs env.append_value('LIB', [link_name]) # the order self.link_task.set_run_after(y.link_task) # for the recompilation self.link_task.dep_nodes += y.link_task.outputs # add the link path too tmp_path = y.link_task.outputs[0].parent.bldpath() if not tmp_path in env['LIBPATH']: env.prepend_value('LIBPATH', [tmp_path]) # add ancestors uselib too - but only propagate those that have no staticlib defined for v in self.to_list(getattr(y, 'uselib', [])): if v not in seen_uselib: seen_uselib.add(v) if not env['STLIB_' + v]: if not v in self.uselib: self.uselib.insert(0, v) # if the library task generator provides 'export_includes', add to the include path # the export_includes must be a list of paths relative to the other library if getattr(y, 'export_includes', None): self.includes.extend(y.to_incnodes(y.export_includes))
[ "def", "apply_uselib_local", "(", "self", ")", ":", "env", "=", "self", ".", "env", "from", "waflib", ".", "Tools", ".", "ccroot", "import", "stlink_task", "# 1. the case of the libs defined in the project (visit ancestors first)", "# the ancestors external libraries (uselib)...
https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/waflib/extras/compat15.py#L218-L289
graphbrain/graphbrain
96cb902d9e22d8dc8c2110ff3176b9aafdeba444
graphbrain/scripts/select-alpha-features.py
python
FeatureSelector.run
(self)
[]
def run(self): new_features = ALL_FEATURES cur_features = None i = 1 # ablation stage while new_features != cur_features: self._log('\n>>> ITERATION {} <<<'.format(i)) i += 1 cur_features = new_features new_features = self._ablate(cur_features) # regrowth stage cur_features = None while new_features != cur_features: self._log('\n>>> ITERATION {} <<<'.format(i)) i += 1 cur_features = new_features new_features = self._regrow(cur_features)
[ "def", "run", "(", "self", ")", ":", "new_features", "=", "ALL_FEATURES", "cur_features", "=", "None", "i", "=", "1", "# ablation stage", "while", "new_features", "!=", "cur_features", ":", "self", ".", "_log", "(", "'\\n>>> ITERATION {} <<<'", ".", "format", ...
https://github.com/graphbrain/graphbrain/blob/96cb902d9e22d8dc8c2110ff3176b9aafdeba444/graphbrain/scripts/select-alpha-features.py#L233-L251
stdcoutzyx/DeepID_FaceClassify
356d08fa364f7a75913e743aa1a7f5d5c02e0be2
src/conv_net/deepid_generate.py
python
DeepIDGenerator.build_layer_architecture
(self, n_hidden, acti_func=relu)
simple means the deepid layer input is only the layer4 output. layer1: convpool layer layer2: convpool layer layer3: convpool layer layer4: conv layer deepid: hidden layer
simple means the deepid layer input is only the layer4 output. layer1: convpool layer layer2: convpool layer layer3: convpool layer layer4: conv layer deepid: hidden layer
[ "simple", "means", "the", "deepid", "layer", "input", "is", "only", "the", "layer4", "output", ".", "layer1", ":", "convpool", "layer", "layer2", ":", "convpool", "layer", "layer3", ":", "convpool", "layer", "layer4", ":", "conv", "layer", "deepid", ":", "...
def build_layer_architecture(self, n_hidden, acti_func=relu): ''' simple means the deepid layer input is only the layer4 output. layer1: convpool layer layer2: convpool layer layer3: convpool layer layer4: conv layer deepid: hidden layer ''' x = T.matrix('x') print '\tbuilding the model ...' layer1_input = x.reshape(self.layer1_image_shape) self.layer1 = LeNetConvPoolLayer(self.rng, input = layer1_input, image_shape = self.layer1_image_shape, filter_shape = self.layer1_filter_shape, poolsize = (2,2), W = self.exist_params[5][0], b = self.exist_params[5][1], activation = acti_func) self.layer2 = LeNetConvPoolLayer(self.rng, input = self.layer1.output, image_shape = self.layer2_image_shape, filter_shape = self.layer2_filter_shape, poolsize = (2,2), W = self.exist_params[4][0], b = self.exist_params[4][1], activation = acti_func) self.layer3 = LeNetConvPoolLayer(self.rng, input = self.layer2.output, image_shape = self.layer3_image_shape, filter_shape = self.layer3_filter_shape, poolsize = (2,2), W = self.exist_params[3][0], b = self.exist_params[3][1], activation = acti_func) self.layer4 = LeNetConvLayer(self.rng, input = self.layer3.output, image_shape = self.layer4_image_shape, filter_shape = self.layer4_filter_shape, W = self.exist_params[2][0], b = self.exist_params[2][1], activation = acti_func) layer3_output_flatten = self.layer3.output.flatten(2) layer4_output_flatten = self.layer4.output.flatten(2) deepid_input = T.concatenate([layer3_output_flatten, layer4_output_flatten], axis=1) self.deepid_layer = HiddenLayer(self.rng, input = deepid_input, n_in = numpy.prod( self.result_image_shape[1:] ) + numpy.prod( self.layer4_image_shape[1:] ), n_out = n_hidden, W = self.exist_params[1][0], b = self.exist_params[1][1], activation = acti_func) self.generator = theano.function(inputs=[x], outputs=self.deepid_layer.output)
[ "def", "build_layer_architecture", "(", "self", ",", "n_hidden", ",", "acti_func", "=", "relu", ")", ":", "x", "=", "T", ".", "matrix", "(", "'x'", ")", "print", "'\\tbuilding the model ...'", "layer1_input", "=", "x", ".", "reshape", "(", "self", ".", "la...
https://github.com/stdcoutzyx/DeepID_FaceClassify/blob/356d08fa364f7a75913e743aa1a7f5d5c02e0be2/src/conv_net/deepid_generate.py#L32-L94
jobovy/galpy
8e6a230bbe24ce16938db10053f92eb17fe4bb52
galpy/potential/TwoPowerSphericalPotential.py
python
DehnenSphericalPotential._Rzderiv
(self,R,z,phi=0.,t=0.)
return ((R*z*numpy.power(r,-2.-alpha)*numpy.power(a+r,alpha-4.) *(3*r+a*alpha))/(alpha-3))
NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t- time OUTPUT: d2phi/dR/dz HISTORY: 2019-10-11 - Written - Starkman (UofT)
NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t- time OUTPUT: d2phi/dR/dz HISTORY: 2019-10-11 - Written - Starkman (UofT)
[ "NAME", ":", "_Rzderiv", "PURPOSE", ":", "evaluate", "the", "mixed", "R", "z", "derivative", "for", "this", "potential", "INPUT", ":", "R", "-", "Galactocentric", "cylindrical", "radius", "z", "-", "vertical", "height", "phi", "-", "azimuth", "t", "-", "ti...
def _Rzderiv(self,R,z,phi=0.,t=0.): """ NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t- time OUTPUT: d2phi/dR/dz HISTORY: 2019-10-11 - Written - Starkman (UofT) """ if self._specialSelf is not None: return self._specialSelf._Rzderiv(R, z, phi=phi, t=t) a, alpha= self.a, self.alpha r= numpy.sqrt(R**2.+z**2.) return ((R*z*numpy.power(r,-2.-alpha)*numpy.power(a+r,alpha-4.) *(3*r+a*alpha))/(alpha-3))
[ "def", "_Rzderiv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "self", ".", "_specialSelf", "is", "not", "None", ":", "return", "self", ".", "_specialSelf", ".", "_Rzderiv", "(", "R", ",", "z", "...
https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/potential/TwoPowerSphericalPotential.py#L528-L549
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
LFI vuln/panoptic.py
python
prepare_request
(payload)
return request_args
Prepares HTTP (GET or POST) request with proper payload
Prepares HTTP (GET or POST) request with proper payload
[ "Prepares", "HTTP", "(", "GET", "or", "POST", ")", "request", "with", "proper", "payload" ]
def prepare_request(payload): """ Prepares HTTP (GET or POST) request with proper payload """ _ = re.sub(r"(?P<param>%s)=(?P<value>[^=&]*)" % args.param, r"\1=%s" % (payload or ""), kb.request_params) request_args = {"url": "%s://%s%s" % (kb.parsed_target_url.scheme or "http", kb.parsed_target_url.netloc, kb.parsed_target_url.path)} if args.data: request_args["data"] = _ else: request_args["url"] += "?%s" % _ if args.header: request_args["header"] = args.header if args.cookie: request_args["cookie"] = args.cookie if args.user_agent: request_args["user_agent"] = args.user_agent request_args["verbose"] = args.verbose return request_args
[ "def", "prepare_request", "(", "payload", ")", ":", "_", "=", "re", ".", "sub", "(", "r\"(?P<param>%s)=(?P<value>[^=&]*)\"", "%", "args", ".", "param", ",", "r\"\\1=%s\"", "%", "(", "payload", "or", "\"\"", ")", ",", "kb", ".", "request_params", ")", "requ...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/LFI vuln/panoptic.py#L327-L353
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/thread/ttypes.py
python
_MutexFunction.try_lock
(self, fsm)
return self.mutex.try_lock(fsm)
[]
def try_lock(self, fsm): self._check_mutex(fsm) return self.mutex.try_lock(fsm)
[ "def", "try_lock", "(", "self", ",", "fsm", ")", ":", "self", ".", "_check_mutex", "(", "fsm", ")", "return", "self", ".", "mutex", ".", "try_lock", "(", "fsm", ")" ]
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/thread/ttypes.py#L239-L241
vispy/vispy
26256fdc2574259dd227022fbce0767cae4e244b
vispy/ext/fontconfig.py
python
_list_fonts
()
return vals
List system fonts
List system fonts
[ "List", "system", "fonts" ]
def _list_fonts(): """List system fonts""" stdout_, stderr = run_subprocess(['fc-list', ':scalable=true', 'family']) vals = [v.split(',')[0] for v in stdout_.strip().splitlines(False)] return vals
[ "def", "_list_fonts", "(", ")", ":", "stdout_", ",", "stderr", "=", "run_subprocess", "(", "[", "'fc-list'", ",", "':scalable=true'", ",", "'family'", "]", ")", "vals", "=", "[", "v", ".", "split", "(", "','", ")", "[", "0", "]", "for", "v", "in", ...
https://github.com/vispy/vispy/blob/26256fdc2574259dd227022fbce0767cae4e244b/vispy/ext/fontconfig.py#L114-L118
google/glazier
8a7f3dacb8be8a73a15d988d02a3c14e306d8f6e
glazier/lib/beyondcorp.py
python
BeyondCorp._GetHash
(self, file_path: str)
return base64.b64encode(hasher.digest())
Calculates the hash of the boot wim. Args: file_path: path to the file to be hashed Returns: hash of boot wim in hex
Calculates the hash of the boot wim.
[ "Calculates", "the", "hash", "of", "the", "boot", "wim", "." ]
def _GetHash(self, file_path: str) -> bytes: """Calculates the hash of the boot wim. Args: file_path: path to the file to be hashed Returns: hash of boot wim in hex """ block_size = 33554432 # define bytes to read at a time when hashing (32mb) hasher = hashlib.sha256() with open(file_path, 'rb') as f: fb = f.read(block_size) while fb: hasher.update(fb) fb = f.read(block_size) return base64.b64encode(hasher.digest())
[ "def", "_GetHash", "(", "self", ",", "file_path", ":", "str", ")", "->", "bytes", ":", "block_size", "=", "33554432", "# define bytes to read at a time when hashing (32mb)", "hasher", "=", "hashlib", ".", "sha256", "(", ")", "with", "open", "(", "file_path", ","...
https://github.com/google/glazier/blob/8a7f3dacb8be8a73a15d988d02a3c14e306d8f6e/glazier/lib/beyondcorp.py#L96-L113
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/sqlalchemy/orm/mapper.py
python
Mapper._set_concrete_base
(self, mapper)
Set the given :class:`.Mapper` as the 'inherits' for this :class:`.Mapper`, assuming this :class:`.Mapper` is concrete and does not already have an inherits.
Set the given :class:`.Mapper` as the 'inherits' for this :class:`.Mapper`, assuming this :class:`.Mapper` is concrete and does not already have an inherits.
[ "Set", "the", "given", ":", "class", ":", ".", "Mapper", "as", "the", "inherits", "for", "this", ":", "class", ":", ".", "Mapper", "assuming", "this", ":", "class", ":", ".", "Mapper", "is", "concrete", "and", "does", "not", "already", "have", "an", ...
def _set_concrete_base(self, mapper): """Set the given :class:`.Mapper` as the 'inherits' for this :class:`.Mapper`, assuming this :class:`.Mapper` is concrete and does not already have an inherits.""" assert self.concrete assert not self.inherits assert isinstance(mapper, Mapper) self.inherits = mapper self.inherits.polymorphic_map.update(self.polymorphic_map) self.polymorphic_map = self.inherits.polymorphic_map for mapper in self.iterate_to_root(): if mapper.polymorphic_on is not None: mapper._requires_row_aliasing = True self.batch = self.inherits.batch for mp in self.self_and_descendants: mp.base_mapper = self.inherits.base_mapper self.inherits._inheriting_mappers.add(self) self.passive_updates = self.inherits.passive_updates self._all_tables = self.inherits._all_tables
[ "def", "_set_concrete_base", "(", "self", ",", "mapper", ")", ":", "assert", "self", ".", "concrete", "assert", "not", "self", ".", "inherits", "assert", "isinstance", "(", "mapper", ",", "Mapper", ")", "self", ".", "inherits", "=", "mapper", "self", ".", ...
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/orm/mapper.py#L563-L582
dingjiansw101/AerialDetection
fbb7726bc0c6898fc00e50a418a3f5e0838b30d4
mmdet/core/anchor/guided_anchor_target.py
python
ga_shape_target_single
(flat_approxs, inside_flags, flat_squares, gt_bboxes, gt_bboxes_ignore, img_meta, approxs_per_octave, cfg, sampling=True, unmap_outputs=True)
return (bbox_anchors, bbox_gts, bbox_weights, pos_inds, neg_inds)
Compute guided anchoring targets. This function returns sampled anchors and gt bboxes directly rather than calculates regression targets. Args: flat_approxs (Tensor): flat approxs of a single image, shape (n, 4) inside_flags (Tensor): inside flags of a single image, shape (n, ). flat_squares (Tensor): flat squares of a single image, shape (approxs_per_octave * n, 4) gt_bboxes (Tensor): Ground truth bboxes of a single image. img_meta (dict): Meta info of a single image. approxs_per_octave (int): number of approxs per octave cfg (dict): RPN train configs. sampling (bool): sampling or not. unmap_outputs (bool): unmap outputs or not. Returns: tuple
Compute guided anchoring targets.
[ "Compute", "guided", "anchoring", "targets", "." ]
def ga_shape_target_single(flat_approxs, inside_flags, flat_squares, gt_bboxes, gt_bboxes_ignore, img_meta, approxs_per_octave, cfg, sampling=True, unmap_outputs=True): """Compute guided anchoring targets. This function returns sampled anchors and gt bboxes directly rather than calculates regression targets. Args: flat_approxs (Tensor): flat approxs of a single image, shape (n, 4) inside_flags (Tensor): inside flags of a single image, shape (n, ). flat_squares (Tensor): flat squares of a single image, shape (approxs_per_octave * n, 4) gt_bboxes (Tensor): Ground truth bboxes of a single image. img_meta (dict): Meta info of a single image. approxs_per_octave (int): number of approxs per octave cfg (dict): RPN train configs. sampling (bool): sampling or not. unmap_outputs (bool): unmap outputs or not. Returns: tuple """ if not inside_flags.any(): return (None, ) * 6 # assign gt and sample anchors expand_inside_flags = inside_flags[:, None].expand( -1, approxs_per_octave).reshape(-1) approxs = flat_approxs[expand_inside_flags, :] squares = flat_squares[inside_flags, :] bbox_assigner = build_assigner(cfg.ga_assigner) assign_result = bbox_assigner.assign(approxs, squares, approxs_per_octave, gt_bboxes, gt_bboxes_ignore) if sampling: bbox_sampler = build_sampler(cfg.ga_sampler) else: bbox_sampler = PseudoSampler() sampling_result = bbox_sampler.sample(assign_result, squares, gt_bboxes) bbox_anchors = torch.zeros_like(squares) bbox_gts = torch.zeros_like(squares) bbox_weights = torch.zeros_like(squares) pos_inds = sampling_result.pos_inds neg_inds = sampling_result.neg_inds if len(pos_inds) > 0: bbox_anchors[pos_inds, :] = sampling_result.pos_bboxes bbox_gts[pos_inds, :] = sampling_result.pos_gt_bboxes bbox_weights[pos_inds, :] = 1.0 # map up to original set of anchors if unmap_outputs: num_total_anchors = flat_squares.size(0) bbox_anchors = unmap(bbox_anchors, num_total_anchors, inside_flags) bbox_gts = unmap(bbox_gts, num_total_anchors, inside_flags) bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags) return (bbox_anchors, bbox_gts, bbox_weights, pos_inds, neg_inds)
[ "def", "ga_shape_target_single", "(", "flat_approxs", ",", "inside_flags", ",", "flat_squares", ",", "gt_bboxes", ",", "gt_bboxes_ignore", ",", "img_meta", ",", "approxs_per_octave", ",", "cfg", ",", "sampling", "=", "True", ",", "unmap_outputs", "=", "True", ")",...
https://github.com/dingjiansw101/AerialDetection/blob/fbb7726bc0c6898fc00e50a418a3f5e0838b30d4/mmdet/core/anchor/guided_anchor_target.py#L218-L285
laughingman7743/PyAthena
417749914247cabca2325368c6eda337b28b47f0
pyathena/common.py
python
BaseCursor._find_previous_query_id
( self, query: str, work_group: Optional[str], cache_size: int = 0, cache_expiration_time: int = 0, )
return query_id
[]
def _find_previous_query_id( self, query: str, work_group: Optional[str], cache_size: int = 0, cache_expiration_time: int = 0, ) -> Optional[str]: query_id = None if cache_size == 0 and cache_expiration_time > 0: cache_size = sys.maxsize if cache_expiration_time > 0: expiration_time = datetime.now(timezone.utc) - timedelta( seconds=cache_expiration_time ) else: expiration_time = datetime.now(timezone.utc) try: next_token = None while cache_size > 0: max_results = min(cache_size, 50) # 50 is max allowed by AWS API cache_size -= max_results next_token, query_executions = self._list_query_executions( max_results, work_group, next_token=next_token ) for execution in sorted( ( e for e in query_executions if e["Status"]["State"] == AthenaQueryExecution.STATE_SUCCEEDED and e["StatementType"] == AthenaQueryExecution.STATEMENT_TYPE_DML ), # https://github.com/python/mypy/issues/9656 key=lambda e: e["Status"]["CompletionDateTime"], # type: ignore reverse=True, ): if ( cache_expiration_time > 0 and execution["Status"]["CompletionDateTime"].astimezone( timezone.utc ) < expiration_time ): next_token = None break if execution["Query"] == query: query_id = execution["QueryExecutionId"] break if query_id or next_token is None: break except Exception: _logger.warning("Failed to check the cache. Moving on without cache.") return query_id
[ "def", "_find_previous_query_id", "(", "self", ",", "query", ":", "str", ",", "work_group", ":", "Optional", "[", "str", "]", ",", "cache_size", ":", "int", "=", "0", ",", "cache_expiration_time", ":", "int", "=", "0", ",", ")", "->", "Optional", "[", ...
https://github.com/laughingman7743/PyAthena/blob/417749914247cabca2325368c6eda337b28b47f0/pyathena/common.py#L230-L282
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/clc_server.py
python
main
()
The main function. Instantiates the module and calls process_request. :return: none
The main function. Instantiates the module and calls process_request. :return: none
[ "The", "main", "function", ".", "Instantiates", "the", "module", "and", "calls", "process_request", ".", ":", "return", ":", "none" ]
def main(): """ The main function. Instantiates the module and calls process_request. :return: none """ argument_dict = ClcServer._define_module_argument_spec() module = AnsibleModule(supports_check_mode=True, **argument_dict) clc_server = ClcServer(module) clc_server.process_request()
[ "def", "main", "(", ")", ":", "argument_dict", "=", "ClcServer", ".", "_define_module_argument_spec", "(", ")", "module", "=", "AnsibleModule", "(", "supports_check_mode", "=", "True", ",", "*", "*", "argument_dict", ")", "clc_server", "=", "ClcServer", "(", "...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/clc_server.py#L1551-L1559
onaio/onadata
89ad16744e8f247fb748219476f6ac295869a95f
onadata/apps/viewer/tasks.py
python
create_external_export
(username, id_string, export_id, **options)
XLSReport export task.
XLSReport export task.
[ "XLSReport", "export", "task", "." ]
def create_external_export(username, id_string, export_id, **options): """ XLSReport export task. """ try: export = _get_export_object(export_id) # though export is not available when for has 0 submissions, we # catch this since it potentially stops celery gen_export = generate_external_export( Export.EXTERNAL_EXPORT, username, id_string, export_id, options, xform=export.xform) except (Exception, NoRecordsFoundError, ConnectionError) as e: export.internal_status = Export.FAILED export.save() # mail admins details = _get_export_details(username, id_string, export_id) report_exception( "External Export Exception: Export ID - " "%(export_id)s, /%(username)s/%(id_string)s" % details, e, sys.exc_info()) raise else: return gen_export.id
[ "def", "create_external_export", "(", "username", ",", "id_string", ",", "export_id", ",", "*", "*", "options", ")", ":", "try", ":", "export", "=", "_get_export_object", "(", "export_id", ")", "# though export is not available when for has 0 submissions, we", "# catch ...
https://github.com/onaio/onadata/blob/89ad16744e8f247fb748219476f6ac295869a95f/onadata/apps/viewer/tasks.py#L350-L376
zedshaw/lamson
8a8ad546ea746b129fa5f069bf9278f87d01473a
lamson/routing.py
python
RoutingBase.call_safely
(self, func, message, kwargs)
Used by self to call a function and log exceptions rather than explode and crash.
Used by self to call a function and log exceptions rather than explode and crash.
[ "Used", "by", "self", "to", "call", "a", "function", "and", "log", "exceptions", "rather", "than", "explode", "and", "crash", "." ]
def call_safely(self, func, message, kwargs): """ Used by self to call a function and log exceptions rather than explode and crash. """ from lamson.server import SMTPError try: func(message, **kwargs) LOG.debug("Message to %s was handled by %s.%s", message.route_to, func.__module__, func.__name__) except SMTPError: raise except: if 'ERROR' in dir(sys.modules[func.__module__]): self.set_state(func.__module__, message, 'ERROR') if self.UNDELIVERABLE_QUEUE: self.UNDELIVERABLE_QUEUE.push(message) if self.LOG_EXCEPTIONS: LOG.exception("!!! ERROR handling %s.%s", func.__module__, func.__name__) else: raise
[ "def", "call_safely", "(", "self", ",", "func", ",", "message", ",", "kwargs", ")", ":", "from", "lamson", ".", "server", "import", "SMTPError", "try", ":", "func", "(", "message", ",", "*", "*", "kwargs", ")", "LOG", ".", "debug", "(", "\"Message to %...
https://github.com/zedshaw/lamson/blob/8a8ad546ea746b129fa5f069bf9278f87d01473a/lamson/routing.py#L367-L390
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/io/vasp/sets.py
python
MPNMRSet.incar
(self)
return incar
:return: Incar
:return: Incar
[ ":", "return", ":", "Incar" ]
def incar(self): """ :return: Incar """ incar = super().incar if self.mode.lower() == "cs": incar.update( { "LCHIMAG": True, "EDIFF": -1.0e-10, "ISYM": 0, "LCHARG": False, "LNMR_SYM_RED": True, "NELMIN": 10, "NSLPLINE": True, "PREC": "ACCURATE", "SIGMA": 0.01, } ) elif self.mode.lower() == "efg": isotopes = {ist.split("-")[0]: ist for ist in self.isotopes} quad_efg = [Species(p).get_nmr_quadrupole_moment(isotopes.get(p, None)) for p in self.poscar.site_symbols] incar.update( { "ALGO": "FAST", "EDIFF": -1.0e-10, "ISYM": 0, "LCHARG": False, "LEFG": True, "QUAD_EFG": quad_efg, "NELMIN": 10, "PREC": "ACCURATE", "SIGMA": 0.01, } ) incar.update(self.user_incar_settings) return incar
[ "def", "incar", "(", "self", ")", ":", "incar", "=", "super", "(", ")", ".", "incar", "if", "self", ".", "mode", ".", "lower", "(", ")", "==", "\"cs\"", ":", "incar", ".", "update", "(", "{", "\"LCHIMAG\"", ":", "True", ",", "\"EDIFF\"", ":", "-"...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/vasp/sets.py#L1943-L1984
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/micronumpy/ndarray.py
python
__extend__.descr_array_iface
(self, space)
Note: arr.__array__.data[0] is a pointer so arr must be kept alive while it is in use
Note: arr.__array__.data[0] is a pointer so arr must be kept alive while it is in use
[ "Note", ":", "arr", ".", "__array__", ".", "data", "[", "0", "]", "is", "a", "pointer", "so", "arr", "must", "be", "kept", "alive", "while", "it", "is", "in", "use" ]
def descr_array_iface(self, space): ''' Note: arr.__array__.data[0] is a pointer so arr must be kept alive while it is in use ''' with self.implementation as storage: addr = support.get_storage_as_int(storage, self.get_start()) # will explode if it can't w_d = space.newdict() space.setitem_str(w_d, 'data', space.newtuple([space.newint(addr), space.w_False])) space.setitem_str(w_d, 'shape', self.descr_get_shape(space)) space.setitem_str(w_d, 'typestr', self.get_dtype().descr_get_str(space)) if self.implementation.order == NPY.CORDER: # Array is contiguous, no strides in the interface. strides = space.w_None else: strides = self.descr_get_strides(space) space.setitem_str(w_d, 'strides', strides) space.setitem_str(w_d, 'version', space.newint(3)) return w_d
[ "def", "descr_array_iface", "(", "self", ",", "space", ")", ":", "with", "self", ".", "implementation", "as", "storage", ":", "addr", "=", "support", ".", "get_storage_as_int", "(", "storage", ",", "self", ".", "get_start", "(", ")", ")", "# will explode if ...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/micronumpy/ndarray.py#L668-L688
timonwong/OmniMarkupPreviewer
21921ac7a99d2b5924a2219b33679a5b53621392
OmniMarkupLib/Renderers/libs/python3/docutils/utils/math/math2html.py
python
Bracket.parsetext
(self, pos)
return self
Parse a text bracket
Parse a text bracket
[ "Parse", "a", "text", "bracket" ]
def parsetext(self, pos): "Parse a text bracket" self.parsecomplete(pos, self.innertext) return self
[ "def", "parsetext", "(", "self", ",", "pos", ")", ":", "self", ".", "parsecomplete", "(", "pos", ",", "self", ".", "innertext", ")", "return", "self" ]
https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/Renderers/libs/python3/docutils/utils/math/math2html.py#L2671-L2674
guxd/deep-code-search
92fcaa6b0f2e3143a46c9e8d3d55319d3c09a891
pytorch/models/jointemb.py
python
JointEmbeder.similarity
(self, code_vec, desc_vec)
https://arxiv.org/pdf/1508.01585.pdf
https://arxiv.org/pdf/1508.01585.pdf
[ "https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1508", ".", "01585", ".", "pdf" ]
def similarity(self, code_vec, desc_vec): """ https://arxiv.org/pdf/1508.01585.pdf """ assert self.conf['sim_measure'] in ['cos', 'poly', 'euc', 'sigmoid', 'gesd', 'aesd'], "invalid similarity measure" if self.conf['sim_measure']=='cos': return F.cosine_similarity(code_vec, desc_vec) elif self.conf['sim_measure']=='poly': return (0.5*torch.matmul(code_vec, desc_vec.t()).diag()+1)**2 elif self.conf['sim_measure']=='sigmoid': return torch.tanh(torch.matmul(code_vec, desc_vec.t()).diag()+1) elif self.conf['sim_measure'] in ['euc', 'gesd', 'aesd']: euc_dist = torch.dist(code_vec, desc_vec, 2) # or torch.norm(code_vec-desc_vec,2) euc_sim = 1 / (1 + euc_dist) if self.conf['sim_measure']=='euc': return euc_sim sigmoid_sim = torch.sigmoid(torch.matmul(code_vec, desc_vec.t()).diag()+1) if self.conf['sim_measure']=='gesd': return euc_sim * sigmoid_sim elif self.conf['sim_measure']=='aesd': return 0.5*(euc_sim+sigmoid_sim)
[ "def", "similarity", "(", "self", ",", "code_vec", ",", "desc_vec", ")", ":", "assert", "self", ".", "conf", "[", "'sim_measure'", "]", "in", "[", "'cos'", ",", "'poly'", ",", "'euc'", ",", "'sigmoid'", ",", "'gesd'", ",", "'aesd'", "]", ",", "\"invali...
https://github.com/guxd/deep-code-search/blob/92fcaa6b0f2e3143a46c9e8d3d55319d3c09a891/pytorch/models/jointemb.py#L65-L84
getsentry/sentry
83b1f25aac3e08075e0e2495bc29efaf35aca18a
src/sentry/api/endpoints/project_stats.py
python
ProjectStatsEndpoint.get
(self, request: Request, project)
return Response(data)
Retrieve Event Counts for a Project ``````````````````````````````````` .. caution:: This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. Query ranges are limited to Sentry's configured time-series resolutions. :pparam string organization_slug: the slug of the organization. :pparam string project_slug: the slug of the project. :qparam string stat: the name of the stat to query (``"received"``, ``"rejected"``, ``"blacklisted"``, ``generated``) :qparam timestamp since: a timestamp to set the start of the query in seconds since UNIX epoch. :qparam timestamp until: a timestamp to set the end of the query in seconds since UNIX epoch. :qparam string resolution: an explicit resolution to search for (one of ``10s``, ``1h``, and ``1d``) :auth: required
Retrieve Event Counts for a Project ```````````````````````````````````
[ "Retrieve", "Event", "Counts", "for", "a", "Project" ]
def get(self, request: Request, project) -> Response: """ Retrieve Event Counts for a Project ``````````````````````````````````` .. caution:: This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. Query ranges are limited to Sentry's configured time-series resolutions. :pparam string organization_slug: the slug of the organization. :pparam string project_slug: the slug of the project. :qparam string stat: the name of the stat to query (``"received"``, ``"rejected"``, ``"blacklisted"``, ``generated``) :qparam timestamp since: a timestamp to set the start of the query in seconds since UNIX epoch. :qparam timestamp until: a timestamp to set the end of the query in seconds since UNIX epoch. :qparam string resolution: an explicit resolution to search for (one of ``10s``, ``1h``, and ``1d``) :auth: required """ stat = request.GET.get("stat", "received") query_kwargs = {} if stat == "received": stat_model = tsdb.models.project_total_received elif stat == "rejected": stat_model = tsdb.models.project_total_rejected elif stat == "blacklisted": stat_model = tsdb.models.project_total_blacklisted elif stat == "generated": stat_model = tsdb.models.project try: query_kwargs["environment_id"] = self._get_environment_id_from_request( request, project.organization_id ) except Environment.DoesNotExist: raise ResourceDoesNotExist elif stat == "forwarded": stat_model = tsdb.models.project_total_forwarded else: try: stat_model = FILTER_STAT_KEYS_TO_VALUES[stat] except KeyError: raise ValueError("Invalid stat: %s" % stat) data = tsdb.get_range( model=stat_model, keys=[project.id], **self._parse_args(request, **query_kwargs) )[project.id] return Response(data)
[ "def", "get", "(", "self", ",", "request", ":", "Request", ",", "project", ")", "->", "Response", ":", "stat", "=", "request", ".", "GET", ".", "get", "(", "\"stat\"", ",", "\"received\"", ")", "query_kwargs", "=", "{", "}", "if", "stat", "==", "\"re...
https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/api/endpoints/project_stats.py#L13-L67
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
UI_Hooks.term
(self, *args)
return _idaapi.UI_Hooks_term(self, *args)
term(self) IDA is terminated and the database is already closed. The UI may close its windows in this callback.
term(self)
[ "term", "(", "self", ")" ]
def term(self, *args): """ term(self) IDA is terminated and the database is already closed. The UI may close its windows in this callback. """ return _idaapi.UI_Hooks_term(self, *args)
[ "def", "term", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "UI_Hooks_term", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L42126-L42134
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/data/owfeatureconstructor.py
python
selected_row
(view)
Return the index of selected row in a `view` (:class:`QListView`) The view's selection mode must be a QAbstractItemView.SingleSelction
Return the index of selected row in a `view` (:class:`QListView`)
[ "Return", "the", "index", "of", "selected", "row", "in", "a", "view", "(", ":", "class", ":", "QListView", ")" ]
def selected_row(view): """ Return the index of selected row in a `view` (:class:`QListView`) The view's selection mode must be a QAbstractItemView.SingleSelction """ if view.selectionMode() in [QAbstractItemView.MultiSelection, QAbstractItemView.ExtendedSelection]: raise ValueError("invalid 'selectionMode'") sel_model = view.selectionModel() indexes = sel_model.selectedRows() if indexes: assert len(indexes) == 1 return indexes[0].row() else: return None
[ "def", "selected_row", "(", "view", ")", ":", "if", "view", ".", "selectionMode", "(", ")", "in", "[", "QAbstractItemView", ".", "MultiSelection", ",", "QAbstractItemView", ".", "ExtendedSelection", "]", ":", "raise", "ValueError", "(", "\"invalid 'selectionMode'\...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/data/owfeatureconstructor.py#L84-L100
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/Theano/theano/sandbox/cuda/fftconv.py
python
bptrs
(a)
return pycuda.gpuarray.arange(a.ptr, a.ptr + a.shape[0] * a.strides[0], a.strides[0], dtype=cublas.ctypes.c_void_p)
Pointer array when input represents a batch of matrices. Taken from scikits.cuda tests/test_cublas.py.
Pointer array when input represents a batch of matrices.
[ "Pointer", "array", "when", "input", "represents", "a", "batch", "of", "matrices", "." ]
def bptrs(a): """ Pointer array when input represents a batch of matrices. Taken from scikits.cuda tests/test_cublas.py. """ return pycuda.gpuarray.arange(a.ptr, a.ptr + a.shape[0] * a.strides[0], a.strides[0], dtype=cublas.ctypes.c_void_p)
[ "def", "bptrs", "(", "a", ")", ":", "return", "pycuda", ".", "gpuarray", ".", "arange", "(", "a", ".", "ptr", ",", "a", ".", "ptr", "+", "a", ".", "shape", "[", "0", "]", "*", "a", ".", "strides", "[", "0", "]", ",", "a", ".", "strides", "[...
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/sandbox/cuda/fftconv.py#L213-L221
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/api/data/information/dns.py
python
DnsRegisterSRV.__init__
(self, target, priority, weight, port, **kwargs)
:param target: the target host name :type target: str :param priority: the priority :type priority: int :param weight: the weight :type weight: int :param port: the port of the service :type port: int
:param target: the target host name :type target: str
[ ":", "param", "target", ":", "the", "target", "host", "name", ":", "type", "target", ":", "str" ]
def __init__(self, target, priority, weight, port, **kwargs): """ :param target: the target host name :type target: str :param priority: the priority :type priority: int :param weight: the weight :type weight: int :param port: the port of the service :type port: int """ if not isinstance(target, basestring): raise TypeError("Expected basestring, got '%s'" % type(target)) if not isinstance(priority, int): raise TypeError("Expected int, got '%s'" % type(priority)) if not isinstance(weight, int): raise TypeError("Expected int, got '%s'" % type(weight)) if not isinstance(port, int): raise TypeError("Expected int, got '%s'" % type(port)) self.__target = target self.__priority = priority self.__weight = weight self.__port = port # Set type of register and the other options super(DnsRegisterSRV, self).__init__(type="SRV", **kwargs)
[ "def", "__init__", "(", "self", ",", "target", ",", "priority", ",", "weight", ",", "port", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "target", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"Expected basestring, got '%s...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/api/data/information/dns.py#L2053-L2083
phantomcyber/playbooks
9e850ecc44cb98c5dde53784744213a1ed5799bd
reinfected_endpoint_check.py
python
format_reinfected
(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs)
return
[]
def format_reinfected(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs): phantom.debug('format_reinfected() called') template = """The following infected endpoints are repeat offenders who have matched on the infected_endpoints custom list: {0}""" # parameter list for template variable replacement parameters = [ "filtered-data:filter_2:condition_1:artifact:*.cef.sourceAddress", ] phantom.format(container=container, template=template, parameters=parameters, name="format_reinfected") create_ticket_reinfected(container=container) return
[ "def", "format_reinfected", "(", "action", "=", "None", ",", "success", "=", "None", ",", "container", "=", "None", ",", "results", "=", "None", ",", "handle", "=", "None", ",", "filtered_artifacts", "=", "None", ",", "filtered_results", "=", "None", ",", ...
https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/reinfected_endpoint_check.py#L172-L187
nltk/nltk_contrib
c9da2c29777ca9df650740145f1f4a375ccac961
nltk_contrib/mit/six863/tagging/drawchart.py
python
ChartView.update
(self, chart=None)
Draw any edges that have not been drawn. This is typically called when a after modifies the canvas that a CanvasView is displaying. C{update} will cause any edges that have been added to the chart to be drawn. If update is given a C{chart} argument, then it will replace the current chart with the given chart.
Draw any edges that have not been drawn. This is typically called when a after modifies the canvas that a CanvasView is displaying. C{update} will cause any edges that have been added to the chart to be drawn.
[ "Draw", "any", "edges", "that", "have", "not", "been", "drawn", ".", "This", "is", "typically", "called", "when", "a", "after", "modifies", "the", "canvas", "that", "a", "CanvasView", "is", "displaying", ".", "C", "{", "update", "}", "will", "cause", "an...
def update(self, chart=None): """ Draw any edges that have not been drawn. This is typically called when a after modifies the canvas that a CanvasView is displaying. C{update} will cause any edges that have been added to the chart to be drawn. If update is given a C{chart} argument, then it will replace the current chart with the given chart. """ if chart is not None: self._chart = chart self._edgelevels = [] self._marks = {} self._analyze() self._grow() self.draw() self.erase_tree() self._resize() else: for edge in self._chart: if not self._edgetags.has_key(edge): self._add_edge(edge) self._resize()
[ "def", "update", "(", "self", ",", "chart", "=", "None", ")", ":", "if", "chart", "is", "not", "None", ":", "self", ".", "_chart", "=", "chart", "self", ".", "_edgelevels", "=", "[", "]", "self", ".", "_marks", "=", "{", "}", "self", ".", "_analy...
https://github.com/nltk/nltk_contrib/blob/c9da2c29777ca9df650740145f1f4a375ccac961/nltk_contrib/mit/six863/tagging/drawchart.py#L1061-L1084
mnemosyne-proj/mnemosyne
e39e364e56343437f2e485e0b06ca714de2f2d2e
mnemosyne/libmnemosyne/database.py
python
Database.release_connection
(self)
Release the connection, so that it may be recreated in a separate thread.
Release the connection, so that it may be recreated in a separate thread.
[ "Release", "the", "connection", "so", "that", "it", "may", "be", "recreated", "in", "a", "separate", "thread", "." ]
def release_connection(self): """Release the connection, so that it may be recreated in a separate thread. """ raise NotImplementedError
[ "def", "release_connection", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mnemosyne-proj/mnemosyne/blob/e39e364e56343437f2e485e0b06ca714de2f2d2e/mnemosyne/libmnemosyne/database.py#L62-L69
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/xmlrpc/server.py
python
SimpleXMLRPCDispatcher._dispatch
(self, method, params)
Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called.
Dispatches the XML-RPC method.
[ "Dispatches", "the", "XML", "-", "RPC", "method", "." ]
def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. """ try: # call the matching registered function func = self.funcs[method] except KeyError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method) if self.instance is not None: if hasattr(self.instance, '_dispatch'): # call the `_dispatch` method on the instance return self.instance._dispatch(method, params) # call the instance's method directly try: func = resolve_dotted_attribute( self.instance, method, self.allow_dotted_names ) except AttributeError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method)
[ "def", "_dispatch", "(", "self", ",", "method", ",", "params", ")", ":", "try", ":", "# call the matching registered function", "func", "=", "self", ".", "funcs", "[", "method", "]", "except", "KeyError", ":", "pass", "else", ":", "if", "func", "is", "not"...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/xmlrpc/server.py#L382-L431
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/distlib/wheel.py
python
Wheel.exists
(self)
return os.path.isfile(path)
[]
def exists(self): path = os.path.join(self.dirname, self.filename) return os.path.isfile(path)
[ "def", "exists", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirname", ",", "self", ".", "filename", ")", "return", "os", ".", "path", ".", "isfile", "(", "path", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/distlib/wheel.py#L204-L206
lorien/grab
21fcafeb63e2950e8c97b25e7b5b9a8a19d38410
grab/base.py
python
Grab.request
(self, **kwargs)
Perform network request. You can specify grab settings in ``**kwargs``. Any keyword argument will be passed to ``self.config``. Returns: ``Document`` objects.
Perform network request.
[ "Perform", "network", "request", "." ]
def request(self, **kwargs): """ Perform network request. You can specify grab settings in ``**kwargs``. Any keyword argument will be passed to ``self.config``. Returns: ``Document`` objects. """ self.prepare_request(**kwargs) refresh_count = 0 while True: self.log_request() try: self.transport.request() except error.GrabError as ex: self.exception = ex self.reset_temporary_options() if self.config['log_dir']: self.save_failed_dump() raise else: with self.transport.wrap_transport_error(): doc = self.process_request_result() if self.config['follow_location']: if doc.code in (301, 302, 303, 307, 308): if doc.headers.get('Location'): refresh_count += 1 if refresh_count > self.config['redirect_limit']: raise error.GrabTooManyRedirectsError() else: url = doc.headers.get('Location') self.prepare_request( url=self.make_url_absolute(url), referer=None) continue if self.config['follow_refresh']: refresh_url = self.doc.get_meta_refresh_url() if refresh_url is not None: refresh_count += 1 if refresh_count > self.config['redirect_limit']: raise error.GrabTooManyRedirectsError() else: self.prepare_request( url=self.make_url_absolute(refresh_url), referer=None) continue return doc
[ "def", "request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "prepare_request", "(", "*", "*", "kwargs", ")", "refresh_count", "=", "0", "while", "True", ":", "self", ".", "log_request", "(", ")", "try", ":", "self", ".", "transport...
https://github.com/lorien/grab/blob/21fcafeb63e2950e8c97b25e7b5b9a8a19d38410/grab/base.py#L447-L499
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/figure.py
python
FigureBase.get_edgecolor
(self)
return self.patch.get_edgecolor()
Get the edge color of the Figure rectangle.
Get the edge color of the Figure rectangle.
[ "Get", "the", "edge", "color", "of", "the", "Figure", "rectangle", "." ]
def get_edgecolor(self): """Get the edge color of the Figure rectangle.""" return self.patch.get_edgecolor()
[ "def", "get_edgecolor", "(", "self", ")", ":", "return", "self", ".", "patch", ".", "get_edgecolor", "(", ")" ]
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/figure.py#L433-L435
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
CodeComplice.py
python
logger
(view, ltype, msg=None, timeout=None, delay=0, lid='CodeIntel')
[]
def logger(view, ltype, msg=None, timeout=None, delay=0, lid='CodeIntel'): if msg is None: msg, ltype = ltype, 'info' set_status(view, ltype, msg, timeout=timeout, delay=delay, lid=lid + '-' + ltype, logger=getattr(log, ltype, None))
[ "def", "logger", "(", "view", ",", "ltype", ",", "msg", "=", "None", ",", "timeout", "=", "None", ",", "delay", "=", "0", ",", "lid", "=", "'CodeIntel'", ")", ":", "if", "msg", "is", "None", ":", "msg", ",", "ltype", "=", "ltype", ",", "'info'", ...
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/CodeComplice.py#L403-L406
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/yaml3/constructor.py
python
FullConstructor.construct_python_module
(self, suffix, node)
return self.find_python_module(suffix, node.start_mark)
[]
def construct_python_module(self, suffix, node): value = self.construct_scalar(node) if value: raise ConstructorError("while constructing a Python module", node.start_mark, "expected the empty value, but found %r" % value, node.start_mark) return self.find_python_module(suffix, node.start_mark)
[ "def", "construct_python_module", "(", "self", ",", "suffix", ",", "node", ")", ":", "value", "=", "self", ".", "construct_scalar", "(", "node", ")", "if", "value", ":", "raise", "ConstructorError", "(", "\"while constructing a Python module\"", ",", "node", "."...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/yaml3/constructor.py#L572-L577
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/smart_campaign_suggest_service/client.py
python
SmartCampaignSuggestServiceClient.common_organization_path
(organization: str,)
return "organizations/{organization}".format(organization=organization,)
Return a fully-qualified organization string.
Return a fully-qualified organization string.
[ "Return", "a", "fully", "-", "qualified", "organization", "string", "." ]
def common_organization_path(organization: str,) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,)
[ "def", "common_organization_path", "(", "organization", ":", "str", ",", ")", "->", "str", ":", "return", "\"organizations/{organization}\"", ".", "format", "(", "organization", "=", "organization", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/smart_campaign_suggest_service/client.py#L240-L242
xyuanmu/XX-Mini
5daf3a3d741566bfd18655ea9eb94f546bd0c70a
lib/hyper/http11/connection.py
python
HTTP11Connection.close
(self)
Closes the connection. This closes the socket and then abandons the reference to it. After calling this method, any outstanding :class:`Response <hyper.http11.response.Response>` objects will throw exceptions if attempts are made to read their bodies. In some cases this method will automatically be called. .. warning:: This method should absolutely only be called when you are certain the connection object is no longer needed.
Closes the connection. This closes the socket and then abandons the reference to it. After calling this method, any outstanding :class:`Response <hyper.http11.response.Response>` objects will throw exceptions if attempts are made to read their bodies.
[ "Closes", "the", "connection", ".", "This", "closes", "the", "socket", "and", "then", "abandons", "the", "reference", "to", "it", ".", "After", "calling", "this", "method", "any", "outstanding", ":", "class", ":", "Response", "<hyper", ".", "http11", ".", ...
def close(self): """ Closes the connection. This closes the socket and then abandons the reference to it. After calling this method, any outstanding :class:`Response <hyper.http11.response.Response>` objects will throw exceptions if attempts are made to read their bodies. In some cases this method will automatically be called. .. warning:: This method should absolutely only be called when you are certain the connection object is no longer needed. """ self._sock.close() self._sock = None
[ "def", "close", "(", "self", ")", ":", "self", ".", "_sock", ".", "close", "(", ")", "self", ".", "_sock", "=", "None" ]
https://github.com/xyuanmu/XX-Mini/blob/5daf3a3d741566bfd18655ea9eb94f546bd0c70a/lib/hyper/http11/connection.py#L327-L340
aziz/PlainNotes
6a2d343304b0c2ccd9a6e06c9692b89f83019778
note_headings.py
python
NoteSmartFoldingCommand.fold_or_unfold_headline_at_point
(self, from_point)
return True
Smart folding of the current headline. Unfold only when it's totally folded. Otherwise fold it.
Smart folding of the current headline.
[ "Smart", "folding", "of", "the", "current", "headline", "." ]
def fold_or_unfold_headline_at_point(self, from_point): """Smart folding of the current headline. Unfold only when it's totally folded. Otherwise fold it. """ _, level = headline.headline_and_level_at_point(self.view, from_point) # Not a headline, cancel if level is None or not headline.is_scope_headline(self.view, from_point): return False content_region = headline.region_of_content_of_headline_at_point(self.view, from_point) # If the content is empty, Nothing needs to be done. if content_region is None: # Return True because there is a headline anyway. return True # Check if content region is folded to decide the action. if self.is_region_totally_folded(content_region): self.unfold_yet_fold_subheads(content_region, level) else: self.view.fold(sublime.Region(content_region.a - 1, content_region.b)) return True
[ "def", "fold_or_unfold_headline_at_point", "(", "self", ",", "from_point", ")", ":", "_", ",", "level", "=", "headline", ".", "headline_and_level_at_point", "(", "self", ".", "view", ",", "from_point", ")", "# Not a headline, cancel", "if", "level", "is", "None", ...
https://github.com/aziz/PlainNotes/blob/6a2d343304b0c2ccd9a6e06c9692b89f83019778/note_headings.py#L62-L86
kakao/khaiii
328d5a8af456a5941130383354c07d1cd0e47cf5
rsc/bin/compile_model.py
python
_write_linear
(linear_data: dict, path: str)
write weight and bias with given layer name prefix Args: linear_data: pickled linear layer data path: output file path
write weight and bias with given layer name prefix Args: linear_data: pickled linear layer data path: output file path
[ "write", "weight", "and", "bias", "with", "given", "layer", "name", "prefix", "Args", ":", "linear_data", ":", "pickled", "linear", "layer", "data", "path", ":", "output", "file", "path" ]
def _write_linear(linear_data: dict, path: str): """ write weight and bias with given layer name prefix Args: linear_data: pickled linear layer data path: output file path """ with open(path, 'wb') as fout: for weight in linear_data['weight']: weight.tofile(fout) # output * input * 4 if 'bias' in linear_data: linear_data['bias'].tofile(fout)
[ "def", "_write_linear", "(", "linear_data", ":", "dict", ",", "path", ":", "str", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "fout", ":", "for", "weight", "in", "linear_data", "[", "'weight'", "]", ":", "weight", ".", "tofile", "(...
https://github.com/kakao/khaiii/blob/328d5a8af456a5941130383354c07d1cd0e47cf5/rsc/bin/compile_model.py#L84-L95
AndroBugs/AndroBugs_Framework
7fd3a2cb1cf65a9af10b7ed2129701d4451493fe
tools/modified/androguard/core/bytecodes/dvm.py
python
ProtoIdItem.get_return_type_idx_value
(self)
return self.return_type_idx_value
Return the string associated to the return_type_idx :rtype: string
Return the string associated to the return_type_idx
[ "Return", "the", "string", "associated", "to", "the", "return_type_idx" ]
def get_return_type_idx_value(self): """ Return the string associated to the return_type_idx :rtype: string """ return self.return_type_idx_value
[ "def", "get_return_type_idx_value", "(", "self", ")", ":", "return", "self", ".", "return_type_idx_value" ]
https://github.com/AndroBugs/AndroBugs_Framework/blob/7fd3a2cb1cf65a9af10b7ed2129701d4451493fe/tools/modified/androguard/core/bytecodes/dvm.py#L2023-L2029
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/mailbox.py
python
Maildir.get_folder
(self, folder)
return Maildir(os.path.join(self._path, '.' + folder), factory=self._factory, create=False)
Return a Maildir instance for the named folder.
Return a Maildir instance for the named folder.
[ "Return", "a", "Maildir", "instance", "for", "the", "named", "folder", "." ]
def get_folder(self, folder): """Return a Maildir instance for the named folder.""" return Maildir(os.path.join(self._path, '.' + folder), factory=self._factory, create=False)
[ "def", "get_folder", "(", "self", ",", "folder", ")", ":", "return", "Maildir", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "'.'", "+", "folder", ")", ",", "factory", "=", "self", ".", "_factory", ",", "create", "=", "False...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/mailbox.py#L428-L432
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/ui/tui/spokes/software_selection.py
python
SoftwareSpoke._selection
(self)
return self.payload.get_packages_selection()
The packages selection.
The packages selection.
[ "The", "packages", "selection", "." ]
def _selection(self): """The packages selection.""" return self.payload.get_packages_selection()
[ "def", "_selection", "(", "self", ")", ":", "return", "self", ".", "payload", ".", "get_packages_selection", "(", ")" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/ui/tui/spokes/software_selection.py#L83-L85
awslabs/autogluon
7309118f2ab1c9519f25acf61a283a95af95842b
core/src/autogluon/core/models/ensemble/fold_fitting_strategy.py
python
AbstractFoldFittingStrategy.after_all_folds_scheduled
(self)
Method is called when all the folds are scheduled. Local fitters will perform training here. Distributed fitters will handle job handles and results retrieval here.
Method is called when all the folds are scheduled. Local fitters will perform training here. Distributed fitters will handle job handles and results retrieval here.
[ "Method", "is", "called", "when", "all", "the", "folds", "are", "scheduled", ".", "Local", "fitters", "will", "perform", "training", "here", ".", "Distributed", "fitters", "will", "handle", "job", "handles", "and", "results", "retrieval", "here", "." ]
def after_all_folds_scheduled(self): """ Method is called when all the folds are scheduled. Local fitters will perform training here. Distributed fitters will handle job handles and results retrieval here. """
[ "def", "after_all_folds_scheduled", "(", "self", ")", ":" ]
https://github.com/awslabs/autogluon/blob/7309118f2ab1c9519f25acf61a283a95af95842b/core/src/autogluon/core/models/ensemble/fold_fitting_strategy.py#L40-L45
sqlalchemy/sqlalchemy
eb716884a4abcabae84a6aaba105568e925b7d27
lib/sqlalchemy/sql/base.py
python
ColumnCollection.keys
(self)
return [k for (k, col) in self._collection]
Return a sequence of string key names for all columns in this collection.
Return a sequence of string key names for all columns in this collection.
[ "Return", "a", "sequence", "of", "string", "key", "names", "for", "all", "columns", "in", "this", "collection", "." ]
def keys(self): """Return a sequence of string key names for all columns in this collection.""" return [k for (k, col) in self._collection]
[ "def", "keys", "(", "self", ")", ":", "return", "[", "k", "for", "(", "k", ",", "col", ")", "in", "self", ".", "_collection", "]" ]
https://github.com/sqlalchemy/sqlalchemy/blob/eb716884a4abcabae84a6aaba105568e925b7d27/lib/sqlalchemy/sql/base.py#L1204-L1207
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/ad_group_bid_modifier_service/client.py
python
AdGroupBidModifierServiceClient._get_default_mtls_endpoint
(api_endpoint)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint.
Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint.
[ "Convert", "api", "endpoint", "to", "mTLS", "endpoint", ".", "Convert", "*", ".", "sandbox", ".", "googleapis", ".", "com", "and", "*", ".", "googleapis", ".", "com", "to", "*", ".", "mtls", ".", "sandbox", ".", "googleapis", ".", "com", "and", "*", ...
def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
[ "def", "_get_default_mtls_endpoint", "(", "api_endpoint", ")", ":", "if", "not", "api_endpoint", ":", "return", "api_endpoint", "mtls_endpoint_re", "=", "re", ".", "compile", "(", "r\"(?P<name>[^.]+)(?P<mtls>\\.mtls)?(?P<sandbox>\\.sandbox)?(?P<googledomain>\\.googleapis\\.com)?\...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/ad_group_bid_modifier_service/client.py#L82-L108
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
ziplibs/werkzeug/http.py
python
is_resource_modified
(environ, etag=None, data=None, last_modified=None)
return not unmodified
Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :return: `True` if the resource was modified, otherwise `False`.
Convenience method for conditional requests.
[ "Convenience", "method", "for", "conditional", "requests", "." ]
def is_resource_modified(environ, etag=None, data=None, last_modified=None): """Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :param last_modified: an optional date of the last modification. :return: `True` if the resource was modified, otherwise `False`. """ if etag is None and data is not None: etag = generate_etag(data) elif data is not None: raise TypeError('both data and etag given') if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'): return False unmodified = False if isinstance(last_modified, basestring): last_modified = parse_date(last_modified) modified_since = parse_date(environ.get('HTTP_IF_MODIFIED_SINCE')) if modified_since and last_modified and last_modified <= modified_since: unmodified = True if etag: if_none_match = parse_etags(environ.get('HTTP_IF_NONE_MATCH')) if if_none_match: unmodified = if_none_match.contains_raw(etag) return not unmodified
[ "def", "is_resource_modified", "(", "environ", ",", "etag", "=", "None", ",", "data", "=", "None", ",", "last_modified", "=", "None", ")", ":", "if", "etag", "is", "None", "and", "data", "is", "not", "None", ":", "etag", "=", "generate_etag", "(", "dat...
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/ziplibs/werkzeug/http.py#L486-L515
moloch--/RootTheBox
097272332b9f9b7e2df31ca0823ed10c7b66ac81
libs/DatabaseConnection.py
python
DatabaseConnection._test_connection
(self, connection_string)
Test the connection string to see if we can connect to the database
Test the connection string to see if we can connect to the database
[ "Test", "the", "connection", "string", "to", "see", "if", "we", "can", "connect", "to", "the", "database" ]
def _test_connection(self, connection_string): """ Test the connection string to see if we can connect to the database """ try: engine = create_engine(connection_string) connection = engine.connect() connection.close() return True except Exception as e: if options.debug: logging.exception("Database connection failed: %s" % e) return False
[ "def", "_test_connection", "(", "self", ",", "connection_string", ")", ":", "try", ":", "engine", "=", "create_engine", "(", "connection_string", ")", "connection", "=", "engine", ".", "connect", "(", ")", "connection", ".", "close", "(", ")", "return", "Tru...
https://github.com/moloch--/RootTheBox/blob/097272332b9f9b7e2df31ca0823ed10c7b66ac81/libs/DatabaseConnection.py#L147-L159
david-abel/simple_rl
d8fe6007efb4840377f085a4e35ba89aaa2cdf6d
simple_rl/agents/bandits/LinUCBAgentClass.py
python
LinUCBAgent.get_parameters
(self)
return param_dict
Returns: (dict) key=param_name (str) --> val=param_val (object).
Returns: (dict) key=param_name (str) --> val=param_val (object).
[ "Returns", ":", "(", "dict", ")", "key", "=", "param_name", "(", "str", ")", "--", ">", "val", "=", "param_val", "(", "object", ")", "." ]
def get_parameters(self): ''' Returns: (dict) key=param_name (str) --> val=param_val (object). ''' param_dict = defaultdict(int) param_dict["rand_init"] = self.rand_init param_dict["context_size"] = self.context_size param_dict["alpha"] = self.alpha return param_dict
[ "def", "get_parameters", "(", "self", ")", ":", "param_dict", "=", "defaultdict", "(", "int", ")", "param_dict", "[", "\"rand_init\"", "]", "=", "self", ".", "rand_init", "param_dict", "[", "\"context_size\"", "]", "=", "self", ".", "context_size", "param_dict...
https://github.com/david-abel/simple_rl/blob/d8fe6007efb4840377f085a4e35ba89aaa2cdf6d/simple_rl/agents/bandits/LinUCBAgentClass.py#L37-L48
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/numbers.py
python
Integral.__long__
(self)
long(self)
long(self)
[ "long", "(", "self", ")" ]
def __long__(self): """long(self)""" raise NotImplementedError
[ "def", "__long__", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/numbers.py#L301-L303
MechanicalSoup/MechanicalSoup
72783b827b176bec8a3f9672a5222ce835b72a82
mechanicalsoup/browser.py
python
Browser._get_request_kwargs
(method, url, **kwargs)
return request_kwargs
This method exists to raise a TypeError when a method or url is specified in the kwargs.
This method exists to raise a TypeError when a method or url is specified in the kwargs.
[ "This", "method", "exists", "to", "raise", "a", "TypeError", "when", "a", "method", "or", "url", "is", "specified", "in", "the", "kwargs", "." ]
def _get_request_kwargs(method, url, **kwargs): """This method exists to raise a TypeError when a method or url is specified in the kwargs. """ request_kwargs = {"method": method, "url": url} request_kwargs.update(kwargs) return request_kwargs
[ "def", "_get_request_kwargs", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "request_kwargs", "=", "{", "\"method\"", ":", "method", ",", "\"url\"", ":", "url", "}", "request_kwargs", ".", "update", "(", "kwargs", ")", "return", "request_kw...
https://github.com/MechanicalSoup/MechanicalSoup/blob/72783b827b176bec8a3f9672a5222ce835b72a82/mechanicalsoup/browser.py#L179-L185
LabPy/lantz
3e878e3f765a4295b0089d04e241d4beb7b8a65b
lantz/drivers/ni/daqmx/base.py
python
Device.pci_device_number
(self)
return value
Return the PCI slot number of the device.
Return the PCI slot number of the device.
[ "Return", "the", "PCI", "slot", "number", "of", "the", "device", "." ]
def pci_device_number (self): """Return the PCI slot number of the device. """ err, value = self.lib.GetDevPCIDevNum(RetValue('i32')) return value
[ "def", "pci_device_number", "(", "self", ")", ":", "err", ",", "value", "=", "self", ".", "lib", ".", "GetDevPCIDevNum", "(", "RetValue", "(", "'i32'", ")", ")", "return", "value" ]
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/ni/daqmx/base.py#L315-L319
lululxvi/deepxde
730c97282636e86c845ce2ba3253482f2178469e
deepxde/data/data.py
python
Tuple.losses
(self, targets, outputs, loss, model)
return [loss(targets, outputs)]
Return a list of losses, i.e., constraints.
Return a list of losses, i.e., constraints.
[ "Return", "a", "list", "of", "losses", "i", ".", "e", ".", "constraints", "." ]
def losses(self, targets, outputs, loss, model): """Return a list of losses, i.e., constraints.""" return [loss(targets, outputs)]
[ "def", "losses", "(", "self", ",", "targets", ",", "outputs", ",", "loss", ",", "model", ")", ":", "return", "[", "loss", "(", "targets", ",", "outputs", ")", "]" ]
https://github.com/lululxvi/deepxde/blob/730c97282636e86c845ce2ba3253482f2178469e/deepxde/data/data.py#L35-L37
peterbe/tornado-utils
820f18fc4acce57f755ee5bde0bf26543429ae1a
tornado_utils/send_mail/backends/smtp.py
python
EmailBackend.close
(self)
Closes the connection to the email server.
Closes the connection to the email server.
[ "Closes", "the", "connection", "to", "the", "email", "server", "." ]
def close(self): """Closes the connection to the email server.""" try: try: self.connection.quit() except socket.sslerror: # This happens when calling quit() on a TLS connection # sometimes. self.connection.close() except: if self.fail_silently: return raise finally: self.connection = None
[ "def", "close", "(", "self", ")", ":", "try", ":", "try", ":", "self", ".", "connection", ".", "quit", "(", ")", "except", "socket", ".", "sslerror", ":", "# This happens when calling quit() on a TLS connection", "# sometimes.", "self", ".", "connection", ".", ...
https://github.com/peterbe/tornado-utils/blob/820f18fc4acce57f755ee5bde0bf26543429ae1a/tornado_utils/send_mail/backends/smtp.py#L62-L76
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_internal/commands/configuration.py
python
ConfigurationCommand.list_values
(self, options, args)
[]
def list_values(self, options, args): self._get_n_args(args, "list", n=0) for key, value in sorted(self.configuration.items()): logger.info("%s=%r", key, value)
[ "def", "list_values", "(", "self", ",", "options", ",", "args", ")", ":", "self", ".", "_get_n_args", "(", "args", ",", "\"list\"", ",", "n", "=", "0", ")", "for", "key", ",", "value", "in", "sorted", "(", "self", ".", "configuration", ".", "items", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_internal/commands/configuration.py#L153-L157
yingl/LintCodeInPython
ac11a31f414ebf1481109bdfa7757ef4c7d89df7
copy-list-with-random-pointer.py
python
Solution.copyRandomList
(self, head)
return new_head
思路如下,abcd...代表原链表,a'b'c'd'...代表新链表。()内代表random,'/'代表None。 初始状态:a(d)->b(/)->c(e)->d(a) 1. 插入并复制原来的random节点:a(d)->a'(d)->b(/)->b'(/)->c(e)->c'(e)->d(a)->d'(a) 2. 更新新节点的random(因为x指向x'):a(d)->a'(d')->b(/)->b'(/)->c(e)->c'(e')->d(a)->d'(a') 3. 拆成两条链表并返回
思路如下,abcd...代表原链表,a'b'c'd'...代表新链表。()内代表random,'/'代表None。 初始状态:a(d)->b(/)->c(e)->d(a) 1. 插入并复制原来的random节点:a(d)->a'(d)->b(/)->b'(/)->c(e)->c'(e)->d(a)->d'(a) 2. 更新新节点的random(因为x指向x'):a(d)->a'(d')->b(/)->b'(/)->c(e)->c'(e')->d(a)->d'(a') 3. 拆成两条链表并返回
[ "思路如下,abcd", "...", "代表原链表,a", "b", "c", "d", "...", "代表新链表。", "()", "内代表random,", "/", "代表None。", "初始状态:a", "(", "d", ")", "-", ">", "b", "(", "/", ")", "-", ">", "c", "(", "e", ")", "-", ">", "d", "(", "a", ")", "1", ".", "插入并复制原来的random节点:a"...
def copyRandomList(self, head): # write your code here ''' 思路如下,abcd...代表原链表,a'b'c'd'...代表新链表。()内代表random,'/'代表None。 初始状态:a(d)->b(/)->c(e)->d(a) 1. 插入并复制原来的random节点:a(d)->a'(d)->b(/)->b'(/)->c(e)->c'(e)->d(a)->d'(a) 2. 更新新节点的random(因为x指向x'):a(d)->a'(d')->b(/)->b'(/)->c(e)->c'(e')->d(a)->d'(a') 3. 拆成两条链表并返回 ''' if not head: return None node = head while node: new_node = RandomListNode(node.label) new_node.next, new_node.random = node.next, node.random node.next = new_node node = new_node.next node = head.next while node: node.random = node.random.next node = node.next # 向前两步 node = node.next new_head, new_tail = None, None node = head while node: prev = node node = node.next prev.next = node.next # prev.next保存下一个node的位置 if not new_head: new_node = node else: new_tail.next = node new_tail = node new_tail.next = None node = prev.next return new_head
[ "def", "copyRandomList", "(", "self", ",", "head", ")", ":", "# write your code here", "if", "not", "head", ":", "return", "None", "node", "=", "head", "while", "node", ":", "new_node", "=", "RandomListNode", "(", "node", ".", "label", ")", "new_node", "."...
https://github.com/yingl/LintCodeInPython/blob/ac11a31f414ebf1481109bdfa7757ef4c7d89df7/copy-list-with-random-pointer.py#L6-L41
arrayfire/arrayfire-python
96fa9768ee02e5fb5ffcaf3d1f744c898b141637
arrayfire/opencl.py
python
add_device_context
(dev, ctx, que)
Add a new device to arrayfire opencl device manager Parameters ---------- dev : cl_device_id ctx : cl_context que : cl_command_queue
Add a new device to arrayfire opencl device manager
[ "Add", "a", "new", "device", "to", "arrayfire", "opencl", "device", "manager" ]
def add_device_context(dev, ctx, que): """ Add a new device to arrayfire opencl device manager Parameters ---------- dev : cl_device_id ctx : cl_context que : cl_command_queue """ import ctypes as ct from .util import safe_call as safe_call from .library import backend if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") safe_call(backend.get().afcl_add_device_context(dev, ctx, que))
[ "def", "add_device_context", "(", "dev", ",", "ctx", ",", "que", ")", ":", "import", "ctypes", "as", "ct", "from", ".", "util", "import", "safe_call", "as", "safe_call", "from", ".", "library", "import", "backend", "if", "(", "backend", ".", "name", "(",...
https://github.com/arrayfire/arrayfire-python/blob/96fa9768ee02e5fb5ffcaf3d1f744c898b141637/arrayfire/opencl.py#L135-L156
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/contrib/gis/utils/srs.py
python
add_srs_entry
(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None, database=DEFAULT_DB_ALIAS)
This function takes a GDAL SpatialReference system and adds its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations for the backend. Thus, this utility is useful for adding spatial reference systems not included by default with the backend -- for example, the so-called "Google Maps Mercator Projection" is excluded in PostGIS 1.3 and below, and the following adds it to the `spatial_ref_sys` table: >>> from django.contrib.gis.utils import add_srs_entry >>> add_srs_entry(900913) Keyword Arguments: auth_name: This keyword may be customized with the value of the `auth_name` field. Defaults to 'EPSG'. auth_srid: This keyword may be customized with the value of the `auth_srid` field. Defaults to the SRID determined by GDAL. ref_sys_name: For SpatiaLite users only, sets the value of the the `ref_sys_name` field. Defaults to the name determined by GDAL. database: The name of the database connection to use; the default is the value of `django.db.DEFAULT_DB_ALIAS` (at the time of this writing, it's value is 'default').
This function takes a GDAL SpatialReference system and adds its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations for the backend. Thus, this utility is useful for adding spatial reference systems not included by default with the backend -- for example, the so-called "Google Maps Mercator Projection" is excluded in PostGIS 1.3 and below, and the following adds it to the `spatial_ref_sys` table:
[ "This", "function", "takes", "a", "GDAL", "SpatialReference", "system", "and", "adds", "its", "information", "to", "the", "spatial_ref_sys", "table", "of", "the", "spatial", "backend", ".", "Doing", "this", "enables", "database", "-", "level", "spatial", "transf...
def add_srs_entry(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None, database=DEFAULT_DB_ALIAS): """ This function takes a GDAL SpatialReference system and adds its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations for the backend. Thus, this utility is useful for adding spatial reference systems not included by default with the backend -- for example, the so-called "Google Maps Mercator Projection" is excluded in PostGIS 1.3 and below, and the following adds it to the `spatial_ref_sys` table: >>> from django.contrib.gis.utils import add_srs_entry >>> add_srs_entry(900913) Keyword Arguments: auth_name: This keyword may be customized with the value of the `auth_name` field. Defaults to 'EPSG'. auth_srid: This keyword may be customized with the value of the `auth_srid` field. Defaults to the SRID determined by GDAL. ref_sys_name: For SpatiaLite users only, sets the value of the the `ref_sys_name` field. Defaults to the name determined by GDAL. database: The name of the database connection to use; the default is the value of `django.db.DEFAULT_DB_ALIAS` (at the time of this writing, it's value is 'default'). """ connection = connections[database] if not hasattr(connection.ops, 'spatial_version'): raise Exception('The `add_srs_entry` utility only works ' 'with spatial backends.') if connection.ops.oracle or connection.ops.mysql: raise Exception('This utility does not support the ' 'Oracle or MySQL spatial backends.') SpatialRefSys = connection.ops.spatial_ref_sys() # If argument is not a `SpatialReference` instance, use it as parameter # to construct a `SpatialReference` instance. if not isinstance(srs, SpatialReference): srs = SpatialReference(srs) if srs.srid is None: raise Exception('Spatial reference requires an SRID to be ' 'compatible with the spatial backend.') # Initializing the keyword arguments dictionary for both PostGIS # and SpatiaLite. kwargs = {'srid' : srs.srid, 'auth_name' : auth_name, 'auth_srid' : auth_srid or srs.srid, 'proj4text' : srs.proj4, } # Backend-specific fields for the SpatialRefSys model. if connection.ops.postgis: kwargs['srtext'] = srs.wkt if connection.ops.spatialite: kwargs['ref_sys_name'] = ref_sys_name or srs.name # Creating the spatial_ref_sys model. try: # Try getting via SRID only, because using all kwargs may # differ from exact wkt/proj in database. sr = SpatialRefSys.objects.get(srid=srs.srid) except SpatialRefSys.DoesNotExist: sr = SpatialRefSys.objects.create(**kwargs)
[ "def", "add_srs_entry", "(", "srs", ",", "auth_name", "=", "'EPSG'", ",", "auth_srid", "=", "None", ",", "ref_sys_name", "=", "None", ",", "database", "=", "DEFAULT_DB_ALIAS", ")", ":", "connection", "=", "connections", "[", "database", "]", "if", "not", "...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/utils/srs.py#L4-L74
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/cryptography/hazmat/backends/openssl/decode_asn1.py
python
_decode_key_usage
(backend, bit_string)
return x509.KeyUsage( digital_signature, content_commitment, key_encipherment, data_encipherment, key_agreement, key_cert_sign, crl_sign, encipher_only, decipher_only )
[]
def _decode_key_usage(backend, bit_string): bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string) bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free) get_bit = backend._lib.ASN1_BIT_STRING_get_bit digital_signature = get_bit(bit_string, 0) == 1 content_commitment = get_bit(bit_string, 1) == 1 key_encipherment = get_bit(bit_string, 2) == 1 data_encipherment = get_bit(bit_string, 3) == 1 key_agreement = get_bit(bit_string, 4) == 1 key_cert_sign = get_bit(bit_string, 5) == 1 crl_sign = get_bit(bit_string, 6) == 1 encipher_only = get_bit(bit_string, 7) == 1 decipher_only = get_bit(bit_string, 8) == 1 return x509.KeyUsage( digital_signature, content_commitment, key_encipherment, data_encipherment, key_agreement, key_cert_sign, crl_sign, encipher_only, decipher_only )
[ "def", "_decode_key_usage", "(", "backend", ",", "bit_string", ")", ":", "bit_string", "=", "backend", ".", "_ffi", ".", "cast", "(", "\"ASN1_BIT_STRING *\"", ",", "bit_string", ")", "bit_string", "=", "backend", ".", "_ffi", ".", "gc", "(", "bit_string", ",...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/cryptography/hazmat/backends/openssl/decode_asn1.py#L403-L426
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/graphicsItems/InfiniteLine.py
python
InfiniteLine.viewTransformChanged
(self)
Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized)
Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized)
[ "Called", "whenever", "the", "transformation", "matrix", "of", "the", "view", "has", "changed", ".", "(", "eg", "the", "view", "range", "has", "changed", "or", "the", "view", "was", "resized", ")" ]
def viewTransformChanged(self): """ Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized) """ self._invalidateCache()
[ "def", "viewTransformChanged", "(", "self", ")", ":", "self", ".", "_invalidateCache", "(", ")" ]
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/graphicsItems/InfiniteLine.py#L427-L432
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/tensor/tensor.py
python
TensorSymmetry.fully_symmetric
(cls, rank)
return TensorSymmetry(bsgs)
Returns a fully symmetric (antisymmetric if ``rank``<0) TensorSymmetry object for ``abs(rank)`` indices.
Returns a fully symmetric (antisymmetric if ``rank``<0) TensorSymmetry object for ``abs(rank)`` indices.
[ "Returns", "a", "fully", "symmetric", "(", "antisymmetric", "if", "rank", "<0", ")", "TensorSymmetry", "object", "for", "abs", "(", "rank", ")", "indices", "." ]
def fully_symmetric(cls, rank): """ Returns a fully symmetric (antisymmetric if ``rank``<0) TensorSymmetry object for ``abs(rank)`` indices. """ if rank > 0: bsgs = get_symmetric_group_sgs(rank, False) elif rank < 0: bsgs = get_symmetric_group_sgs(-rank, True) elif rank == 0: bsgs = ([], [Permutation(1)]) return TensorSymmetry(bsgs)
[ "def", "fully_symmetric", "(", "cls", ",", "rank", ")", ":", "if", "rank", ">", "0", ":", "bsgs", "=", "get_symmetric_group_sgs", "(", "rank", ",", "False", ")", "elif", "rank", "<", "0", ":", "bsgs", "=", "get_symmetric_group_sgs", "(", "-", "rank", "...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/tensor/tensor.py#L1404-L1415
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/layers/basic.py
python
GatherLayer.get_out_data_from_opts
(cls, name, sources, position, axis, **kwargs)
return output_data
:param str name: :param list[LayerBase] sources: :param LayerBase|int position: :param Dim|str axis: :rtype: Data
:param str name: :param list[LayerBase] sources: :param LayerBase|int position: :param Dim|str axis: :rtype: Data
[ ":", "param", "str", "name", ":", ":", "param", "list", "[", "LayerBase", "]", "sources", ":", ":", "param", "LayerBase|int", "position", ":", ":", "param", "Dim|str", "axis", ":", ":", "rtype", ":", "Data" ]
def get_out_data_from_opts(cls, name, sources, position, axis, **kwargs): """ :param str name: :param list[LayerBase] sources: :param LayerBase|int position: :param Dim|str axis: :rtype: Data """ from returnn.tf.util.data import BatchInfo input_data = get_concat_sources_data_template(sources) old_gather_axis = input_data.get_axis_from_description(axis, allow_int=False) if isinstance(position, int): position_data = Data(name="constant_position", dtype="int32", shape=(), batch_dim_axis=None) else: position_data = position.output.copy_template() assert position_data.dtype in ["int32", "int64"] # determine all common axes of input_data and position_data common_axes_input, common_axes_position, input_axes, position_axes = ( cls._get_common_input_position_axes(input_data, position_data, old_gather_axis)) batch_dims = len(common_axes_input) # move gather axis back if necessary s.t. common axes are always in front gather_axis = max(batch_dims, old_gather_axis) # (BatchAxes.., InputAxesBeforeGatherAxis, PositionAxes.., InputAxesAfterGatherAxis..) dim_tags = ( [input_data.dim_tags[ax] for ax in common_axes_input] + [input_data.dim_tags[ax] for ax in input_axes[:gather_axis-batch_dims]] + [position_data.dim_tags[ax] for ax in position_axes] + [input_data.dim_tags[ax] for ax in input_axes[gather_axis-batch_dims:]]) out_type = input_data.get_kwargs(include_special_axes=False) out_type["name"] = "%s_output" % name out_type["dim_tags"] = dim_tags out_type["beam"] = SearchBeam.get_combined_beam(input_data.beam, position_data.beam) out_type["available_for_inference"] = input_data.available_for_inference and position_data.available_for_inference out_type["batch"] = BatchInfo.get_common_batch_info([src.batch for src in (input_data, position_data)]) # Take axes from input_data if they exist there, otherwise from position_data for axis_kind in Data.SpecialAxesNames: input_axis, position_axis = getattr(input_data, axis_kind), getattr(position_data, axis_kind) if input_axis is not None and input_axis != old_gather_axis: out_type[axis_kind] = cls._translate_input_axis( input_axis, old_gather_axis, common_axes_input, input_axes, position_axes) elif position_axis is not None: out_type[axis_kind] = cls._translate_position_axis( position_axis, old_gather_axis, common_axes_position, position_axes) else: out_type[axis_kind] = None # feature_dim_axis needs to be handled differently if it is NotSpecified if (input_data.feature_dim_axis_or_unspecified is NotSpecified and position_data.feature_dim_axis_or_unspecified is NotSpecified): out_type["feature_dim_axis"] = NotSpecified elif input_data.feature_dim_axis_or_unspecified is NotSpecified: assert position_data.feature_dim_axis_or_unspecified is not NotSpecified if position_data.feature_dim_axis is not None: out_type["feature_dim_axis"] = cls._translate_position_axis( position_data.feature_dim_axis, old_gather_axis, common_axes_position, position_axes) else: out_type["feature_dim_axis"] = NotSpecified elif position_data.feature_dim_axis_or_unspecified is NotSpecified: assert input_data.feature_dim_axis_or_unspecified is not NotSpecified if input_data.feature_dim_axis is not None: out_type["feature_dim_axis"] = cls._translate_input_axis( input_data.feature_dim_axis, old_gather_axis, common_axes_input, input_axes, position_axes) else: out_type["feature_dim_axis"] = NotSpecified else: assert input_data.feature_dim_axis_or_unspecified is not NotSpecified assert position_data.feature_dim_axis_or_unspecified is not NotSpecified pass # keep the logic as before # If not sparse, the feature dim axis could now originate from position, let Data figure this out if not out_type.get("sparse", False): out_type["dim"] = NotSpecified output_data = Data(**out_type) # Take size_placeholder from input_data if they exist there, otherwise from position_data size_placeholder = {} for input_axis, size in input_data.size_placeholder.items(): input_axis = input_data.get_batch_axis(input_axis) if input_axis == old_gather_axis: continue output_axis = output_data.get_batch_axis_excluding_batch( cls._translate_input_axis(input_axis, old_gather_axis, common_axes_input, input_axes, position_axes)) size_placeholder[output_axis] = size for position_axis, size in position_data.size_placeholder.items(): position_axis = position_data.get_batch_axis(position_axis) output_axis = output_data.get_batch_axis_excluding_batch(cls._translate_position_axis( position_axis, old_gather_axis, common_axes_position, position_axes)) size_placeholder.setdefault(output_axis, size) output_data.size_placeholder = size_placeholder return output_data
[ "def", "get_out_data_from_opts", "(", "cls", ",", "name", ",", "sources", ",", "position", ",", "axis", ",", "*", "*", "kwargs", ")", ":", "from", "returnn", ".", "tf", ".", "util", ".", "data", "import", "BatchInfo", "input_data", "=", "get_concat_sources...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/layers/basic.py#L1382-L1477
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractYoursiteCom.py
python
extractYoursiteCom
(item)
return False
Parser for 'yoursite.com' Note: Feed returns incorrect URLs! Actual site is pbsnovel.rocks
Parser for 'yoursite.com' Note: Feed returns incorrect URLs! Actual site is pbsnovel.rocks
[ "Parser", "for", "yoursite", ".", "com", "Note", ":", "Feed", "returns", "incorrect", "URLs!", "Actual", "site", "is", "pbsnovel", ".", "rocks" ]
def extractYoursiteCom(item): ''' Parser for 'yoursite.com' Note: Feed returns incorrect URLs! Actual site is pbsnovel.rocks ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None item['guid'] = item['guid'].replace('http://yoursite.com/', 'http://pbsnovel.rocks/') item['linkUrl'] = item['linkUrl'].replace('http://yoursite.com/', 'http://pbsnovel.rocks/') if not item['title'].startswith("Chapter"): return False if len(item['tags']) != 1: return False chp_tag = item['tags'][0] # The items right now have titles that start with "Chapter", and a single tag with the format "int-int" # Validate that structure before assuming it's a tag for PBS try: chp_1, chp_2 = chp_tag.split("-") int(chp_1) int(chp_2) return buildReleaseMessageWithType(item, "Peerless Battle Spirit", vol, chp, frag=frag, postfix=postfix, tl_type='translated') except: return False return False
[ "def", "extractYoursiteCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", "in", "ite...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractYoursiteCom.py#L1-L36
weinbe58/QuSpin
5bbc3204dbf5c227a87a44f0dacf39509cba580c
quspin/operators/quantum_operator_core.py
python
quantum_operator.matrix_ele
(self,Vl,Vr,pars={},diagonal=False,check=True)
Calculates matrix element of `quantum_operator` object for parameters `pars` in states `Vl` and `Vr`. .. math:: \\langle V_l|H(\\lambda)|V_r\\rangle Notes ----- Taking the conjugate or transpose of the state `Vl` is done automatically. Parameters ----------- Vl : numpy.ndarray Vector(s)/state(s) to multiple with on left side. Vl : numpy.ndarray Vector(s)/state(s) to multiple with on right side. pars : dict, optional Dictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys` are assumed to be set to unity. diagonal : bool, optional When set to `True`, returs only diagonal part of expectation value. Default is `diagonal = False`. check : bool, Returns -------- float Matrix element of `quantum_operator` quantum_operator between the states `Vl` and `Vr`. Examples --------- >>> H_lr = H.expt_value(Vl,Vr,pars=pars,diagonal=False,check=True) corresponds to :math:`H_{lr} = \\langle V_l|H(\\lambda=0)|V_r\\rangle`.
Calculates matrix element of `quantum_operator` object for parameters `pars` in states `Vl` and `Vr`.
[ "Calculates", "matrix", "element", "of", "quantum_operator", "object", "for", "parameters", "pars", "in", "states", "Vl", "and", "Vr", "." ]
def matrix_ele(self,Vl,Vr,pars={},diagonal=False,check=True): """Calculates matrix element of `quantum_operator` object for parameters `pars` in states `Vl` and `Vr`. .. math:: \\langle V_l|H(\\lambda)|V_r\\rangle Notes ----- Taking the conjugate or transpose of the state `Vl` is done automatically. Parameters ----------- Vl : numpy.ndarray Vector(s)/state(s) to multiple with on left side. Vl : numpy.ndarray Vector(s)/state(s) to multiple with on right side. pars : dict, optional Dictionary with same `keys` as `input_dict` and coupling strengths as `values`. Any missing `keys` are assumed to be set to unity. diagonal : bool, optional When set to `True`, returs only diagonal part of expectation value. Default is `diagonal = False`. check : bool, Returns -------- float Matrix element of `quantum_operator` quantum_operator between the states `Vl` and `Vr`. Examples --------- >>> H_lr = H.expt_value(Vl,Vr,pars=pars,diagonal=False,check=True) corresponds to :math:`H_{lr} = \\langle V_l|H(\\lambda=0)|V_r\\rangle`. """ Vr = self.dot(Vr,pars=pars,check=check) if check: try: shape = Vl.shape except AttributeError: Vl =_np.asanyarray(Vl) shape = Vl.shape if shape[0] != self._shape[1]: raise ValueError("matrix dimension mismatch with shapes: {0} and {1}.".format(V.shape,self._shape)) if Vl.ndim > 2: raise ValueError("Expecting 0< V.ndim < 3.") if _sp.issparse(Vl): if diagonal: return _np.asarray(Vl.conj().multiply(Vr).sum(axis=0)).squeeze() else: return Vl.H.dot(Vr) elif _sp.issparse(Vr): if diagonal: return _np.asarray(Vr.multiply(Vl.conj()).sum(axis=0)).squeeze() else: return Vr.T.dot(Vl.conj()) else: if diagonal: return _np.einsum("ij,ij->j",Vl.conj(),Vr) else: return Vl.T.conj().dot(Vr)
[ "def", "matrix_ele", "(", "self", ",", "Vl", ",", "Vr", ",", "pars", "=", "{", "}", ",", "diagonal", "=", "False", ",", "check", "=", "True", ")", ":", "Vr", "=", "self", ".", "dot", "(", "Vr", ",", "pars", "=", "pars", ",", "check", "=", "ch...
https://github.com/weinbe58/QuSpin/blob/5bbc3204dbf5c227a87a44f0dacf39509cba580c/quspin/operators/quantum_operator_core.py#L694-L758
quartiq/rayopt
3890c72b8f56253bdce309b0fe42beda91c6d3e0
rayopt/transformations.py
python
euler_matrix
(ai, aj, ak, axes='sxyz')
return M
Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> numpy.allclose(numpy.sum(R[0]), -1.34786452) True >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1)) >>> numpy.allclose(numpy.sum(R[0]), -0.383436184) True >>> ai, aj, ak = (4*math.pi) * (numpy.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R = euler_matrix(ai, aj, ak, axes) >>> for axes in _TUPLE2AXES.keys(): ... R = euler_matrix(ai, aj, ak, axes)
Return homogeneous rotation matrix from Euler angles and axis sequence.
[ "Return", "homogeneous", "rotation", "matrix", "from", "Euler", "angles", "and", "axis", "sequence", "." ]
def euler_matrix(ai, aj, ak, axes='sxyz'): """Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> numpy.allclose(numpy.sum(R[0]), -1.34786452) True >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1)) >>> numpy.allclose(numpy.sum(R[0]), -0.383436184) True >>> ai, aj, ak = (4*math.pi) * (numpy.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R = euler_matrix(ai, aj, ak, axes) >>> for axes in _TUPLE2AXES.keys(): ... R = euler_matrix(ai, aj, ak, axes) """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis j = _NEXT_AXIS[i+parity] k = _NEXT_AXIS[i-parity+1] if frame: ai, ak = ak, ai if parity: ai, aj, ak = -ai, -aj, -ak si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak) ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak) cc, cs = ci*ck, ci*sk sc, ss = si*ck, si*sk M = numpy.identity(4) if repetition: M[i, i] = cj M[i, j] = sj*si M[i, k] = sj*ci M[j, i] = sj*sk M[j, j] = -cj*ss+cc M[j, k] = -cj*cs-sc M[k, i] = -sj*ck M[k, j] = cj*sc+cs M[k, k] = cj*cc-ss else: M[i, i] = cj*ck M[i, j] = sj*sc-cs M[i, k] = sj*cc+ss M[j, i] = cj*sk M[j, j] = sj*ss+cc M[j, k] = sj*cs-sc M[k, i] = -sj M[k, j] = cj*si M[k, k] = cj*ci return M
[ "def", "euler_matrix", "(", "ai", ",", "aj", ",", "ak", ",", "axes", "=", "'sxyz'", ")", ":", "try", ":", "firstaxis", ",", "parity", ",", "repetition", ",", "frame", "=", "_AXES2TUPLE", "[", "axes", "]", "except", "(", "AttributeError", ",", "KeyError...
https://github.com/quartiq/rayopt/blob/3890c72b8f56253bdce309b0fe42beda91c6d3e0/rayopt/transformations.py#L1047-L1107
doorstop-dev/doorstop
03aa287e5069e29da6979274e1cb6714ee450d3a
doorstop/core/document.py
python
Document.prefix
(self, value)
Set the document's prefix.
Set the document's prefix.
[ "Set", "the", "document", "s", "prefix", "." ]
def prefix(self, value): """Set the document's prefix.""" self._data['prefix'] = Prefix(value)
[ "def", "prefix", "(", "self", ",", "value", ")", ":", "self", ".", "_data", "[", "'prefix'", "]", "=", "Prefix", "(", "value", ")" ]
https://github.com/doorstop-dev/doorstop/blob/03aa287e5069e29da6979274e1cb6714ee450d3a/doorstop/core/document.py#L327-L329
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3dashboard.py
python
S3DashboardAgent.__call__
(self, dashboard, context)
return output, error
Dispatch Ajax requests Args: dashboard: the calling S3Dashboard instance context: the current S3DashboardContext Returns: tuple (output, error), where: - "output" is the output of the command execution - "error" is a tuple (http_status, message), or None
Dispatch Ajax requests
[ "Dispatch", "Ajax", "requests" ]
def __call__(self, dashboard, context): """ Dispatch Ajax requests Args: dashboard: the calling S3Dashboard instance context: the current S3DashboardContext Returns: tuple (output, error), where: - "output" is the output of the command execution - "error" is a tuple (http_status, message), or None """ command = context.command representation = context.representation output = None error = None if command: if command == "config": if representation == "popup": output = self.configure(dashboard, context) else: error = (415, current.ERROR.BAD_FORMAT) elif command == "authorize": # Placeholder for agent command # @todo: implement authorize-action error = (501, current.ERROR.NOT_IMPLEMENTED) else: # Delegated command try: output = self.do(command, context) except NotImplementedError: error = (501, current.ERROR.NOT_IMPLEMENTED) else: if context.http == "GET": if representation in ("html", "iframe"): # Return the widget XML output = self.widget.widget(self.agent_id, self.config, context = context, ) else: error = (415, current.ERROR.BAD_FORMAT) else: error = (405, current.ERROR.BAD_METHOD) return output, error
[ "def", "__call__", "(", "self", ",", "dashboard", ",", "context", ")", ":", "command", "=", "context", ".", "command", "representation", "=", "context", ".", "representation", "output", "=", "None", "error", "=", "None", "if", "command", ":", "if", "comman...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3dashboard.py#L1096-L1145
danielfrg/copper
956e9ae607aec461d4fe4f6e7b0ccd9ed556fc79
dev/ml/gdbn/gdbn/gnumpy.py
python
negative
(x)
return _elementwise__base(x, operator.neg, operator.neg)
Like -x, except that a zero dimensional numpy array input results in a numpy array return value. This works on garrays, numpy arrays, and numbers, preserving type (though all numbers become floats).
Like -x, except that a zero dimensional numpy array input results in a numpy array return value. This works on garrays, numpy arrays, and numbers, preserving type (though all numbers become floats).
[ "Like", "-", "x", "except", "that", "a", "zero", "dimensional", "numpy", "array", "input", "results", "in", "a", "numpy", "array", "return", "value", ".", "This", "works", "on", "garrays", "numpy", "arrays", "and", "numbers", "preserving", "type", "(", "th...
def negative(x): """ Like -x, except that a zero dimensional numpy array input results in a numpy array return value. This works on garrays, numpy arrays, and numbers, preserving type (though all numbers become floats). """ return _elementwise__base(x, operator.neg, operator.neg)
[ "def", "negative", "(", "x", ")", ":", "return", "_elementwise__base", "(", "x", ",", "operator", ".", "neg", ",", "operator", ".", "neg", ")" ]
https://github.com/danielfrg/copper/blob/956e9ae607aec461d4fe4f6e7b0ccd9ed556fc79/dev/ml/gdbn/gdbn/gnumpy.py#L530-L535
liwanlei/FXTest
414a20024ae164035ec31982cda252eaa6b129b8
common/CollectionJenkins.py
python
Conlenct_jenkins.build_job
(self, jobname)
[]
def build_job(self, jobname): try: self.servir.build_job(jobname) return True except: return False
[ "def", "build_job", "(", "self", ",", "jobname", ")", ":", "try", ":", "self", ".", "servir", ".", "build_job", "(", "jobname", ")", "return", "True", "except", ":", "return", "False" ]
https://github.com/liwanlei/FXTest/blob/414a20024ae164035ec31982cda252eaa6b129b8/common/CollectionJenkins.py#L24-L29
orestis/pysmell
14382f377f7759a1b6505120990898dd51f175e6
pysmell/codefinder.py
python
CodeFinder.inClass
(self)
return (len(self.scope) > 0 and (isinstance(self.scope[-1], ast.Class) or self.inClassFunction))
[]
def inClass(self): return (len(self.scope) > 0 and (isinstance(self.scope[-1], ast.Class) or self.inClassFunction))
[ "def", "inClass", "(", "self", ")", ":", "return", "(", "len", "(", "self", ".", "scope", ")", ">", "0", "and", "(", "isinstance", "(", "self", ".", "scope", "[", "-", "1", "]", ",", "ast", ".", "Class", ")", "or", "self", ".", "inClassFunction",...
https://github.com/orestis/pysmell/blob/14382f377f7759a1b6505120990898dd51f175e6/pysmell/codefinder.py#L161-L163
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/optparse.py
python
OptionParser.get_option_group
(self, opt_str)
return None
[]
def get_option_group(self, opt_str): option = (self._short_opt.get(opt_str) or self._long_opt.get(opt_str)) if option and option.container is not self: return option.container return None
[ "def", "get_option_group", "(", "self", ",", "opt_str", ")", ":", "option", "=", "(", "self", ".", "_short_opt", ".", "get", "(", "opt_str", ")", "or", "self", ".", "_long_opt", ".", "get", "(", "opt_str", ")", ")", "if", "option", "and", "option", "...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/optparse.py#L1339-L1344
SirVer/ultisnips
2c83e40ce66814bf813457bb58ea96184ab9bb81
pythonx/UltiSnips/snippet_manager.py
python
SnippetManager.register_snippet_source
(self, name, snippet_source)
Registers a new 'snippet_source' with the given 'name'. The given class must be an instance of SnippetSource. This source will be queried for snippets.
Registers a new 'snippet_source' with the given 'name'.
[ "Registers", "a", "new", "snippet_source", "with", "the", "given", "name", "." ]
def register_snippet_source(self, name, snippet_source): """Registers a new 'snippet_source' with the given 'name'. The given class must be an instance of SnippetSource. This source will be queried for snippets. """ self._snippet_sources.append((name, snippet_source))
[ "def", "register_snippet_source", "(", "self", ",", "name", ",", "snippet_source", ")", ":", "self", ".", "_snippet_sources", ".", "append", "(", "(", "name", ",", "snippet_source", ")", ")" ]
https://github.com/SirVer/ultisnips/blob/2c83e40ce66814bf813457bb58ea96184ab9bb81/pythonx/UltiSnips/snippet_manager.py#L306-L313
weinbe58/QuSpin
5bbc3204dbf5c227a87a44f0dacf39509cba580c
quspin/operators/exp_op_core.py
python
exp_op.T
(self)
return self.transpose(copy = False)
:obj:`exp_op`: transposes the matrix exponential.
:obj:`exp_op`: transposes the matrix exponential.
[ ":", "obj", ":", "exp_op", ":", "transposes", "the", "matrix", "exponential", "." ]
def T(self): """:obj:`exp_op`: transposes the matrix exponential.""" return self.transpose(copy = False)
[ "def", "T", "(", "self", ")", ":", "return", "self", ".", "transpose", "(", "copy", "=", "False", ")" ]
https://github.com/weinbe58/QuSpin/blob/5bbc3204dbf5c227a87a44f0dacf39509cba580c/quspin/operators/exp_op_core.py#L167-L169
missionpinball/mpf
8e6b74cff4ba06d2fec9445742559c1068b88582
mpf/platforms/fast/fast_driver.py
python
FASTDriver.clear_autofire
(self, config_cmd, number)
Clear autofire.
Clear autofire.
[ "Clear", "autofire", "." ]
def clear_autofire(self, config_cmd, number): """Clear autofire.""" cmd = '{}{},81'.format(config_cmd, number) self.log.debug("Clearing hardware rule: %s", cmd) self.send(cmd) self.autofire = None self.config_state = None
[ "def", "clear_autofire", "(", "self", ",", "config_cmd", ",", "number", ")", ":", "cmd", "=", "'{}{},81'", ".", "format", "(", "config_cmd", ",", "number", ")", "self", ".", "log", ".", "debug", "(", "\"Clearing hardware rule: %s\"", ",", "cmd", ")", "self...
https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/platforms/fast/fast_driver.py#L140-L146
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/python-vsmclient/vsmclient/v1/vsms.py
python
VolumeManager.resource_info
(self, req=None)
return self.api.client.post(url, body=body)
Perform a vsm "action."
Perform a vsm "action."
[ "Perform", "a", "vsm", "action", "." ]
def resource_info(self, req=None): """ Perform a vsm "action." """ body = {'request': req} url = '/conductor/resource_info' return self.api.client.post(url, body=body)
[ "def", "resource_info", "(", "self", ",", "req", "=", "None", ")", ":", "body", "=", "{", "'request'", ":", "req", "}", "url", "=", "'/conductor/resource_info'", "return", "self", ".", "api", ".", "client", ".", "post", "(", "url", ",", "body", "=", ...
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/python-vsmclient/vsmclient/v1/vsms.py#L247-L253
VDIGPKU/CBNet_caffe
3bf4db9bfe5439f844f8f4e9188c7e6e83f6f769
detectron/core/config.py
python
cache_cfg_urls
()
Download URLs in the config, cache them locally, and rewrite cfg to make use of the locally cached file.
Download URLs in the config, cache them locally, and rewrite cfg to make use of the locally cached file.
[ "Download", "URLs", "in", "the", "config", "cache", "them", "locally", "and", "rewrite", "cfg", "to", "make", "use", "of", "the", "locally", "cached", "file", "." ]
def cache_cfg_urls(): """Download URLs in the config, cache them locally, and rewrite cfg to make use of the locally cached file. """ __C.TRAIN.WEIGHTS = cache_url(__C.TRAIN.WEIGHTS, __C.DOWNLOAD_CACHE) __C.TEST.WEIGHTS = cache_url(__C.TEST.WEIGHTS, __C.DOWNLOAD_CACHE) __C.TRAIN.PROPOSAL_FILES = tuple( cache_url(f, __C.DOWNLOAD_CACHE) for f in __C.TRAIN.PROPOSAL_FILES ) __C.TEST.PROPOSAL_FILES = tuple( cache_url(f, __C.DOWNLOAD_CACHE) for f in __C.TEST.PROPOSAL_FILES )
[ "def", "cache_cfg_urls", "(", ")", ":", "__C", ".", "TRAIN", ".", "WEIGHTS", "=", "cache_url", "(", "__C", ".", "TRAIN", ".", "WEIGHTS", ",", "__C", ".", "DOWNLOAD_CACHE", ")", "__C", ".", "TEST", ".", "WEIGHTS", "=", "cache_url", "(", "__C", ".", "T...
https://github.com/VDIGPKU/CBNet_caffe/blob/3bf4db9bfe5439f844f8f4e9188c7e6e83f6f769/detectron/core/config.py#L1132-L1143
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/_abcoll.py
python
Mapping.items
(self)
return [(key, self[key]) for key in self]
D.items() -> list of D's (key, value) pairs, as 2-tuples
D.items() -> list of D's (key, value) pairs, as 2-tuples
[ "D", ".", "items", "()", "-", ">", "list", "of", "D", "s", "(", "key", "value", ")", "pairs", "as", "2", "-", "tuples" ]
def items(self): "D.items() -> list of D's (key, value) pairs, as 2-tuples" return [(key, self[key]) for key in self]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "key", ",", "self", "[", "key", "]", ")", "for", "key", "in", "self", "]" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/_abcoll.py#L393-L395