code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def convert_rgb_to_rgba(self, row, result): """ Convert an RGB image to RGBA. This method assumes the alpha channel in result is already correctly initialized. """ for i in range(len(row) // 3): for j in range(3): result[(4 * i) + j] = row[(3 * i) + j]
def function[convert_rgb_to_rgba, parameter[self, row, result]]: constant[ Convert an RGB image to RGBA. This method assumes the alpha channel in result is already correctly initialized. ] for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[row]]] <ast.FloorDiv object at 0x7da2590d6bc0> constant[3]]]]] begin[:] for taget[name[j]] in starred[call[name[range], parameter[constant[3]]]] begin[:] call[name[result]][binary_operation[binary_operation[constant[4] * name[i]] + name[j]]] assign[=] call[name[row]][binary_operation[binary_operation[constant[3] * name[i]] + name[j]]]
keyword[def] identifier[convert_rgb_to_rgba] ( identifier[self] , identifier[row] , identifier[result] ): literal[string] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[row] )// literal[int] ): keyword[for] identifier[j] keyword[in] identifier[range] ( literal[int] ): identifier[result] [( literal[int] * identifier[i] )+ identifier[j] ]= identifier[row] [( literal[int] * identifier[i] )+ identifier[j] ]
def convert_rgb_to_rgba(self, row, result): """ Convert an RGB image to RGBA. This method assumes the alpha channel in result is already correctly initialized. """ for i in range(len(row) // 3): for j in range(3): result[4 * i + j] = row[3 * i + j] # depends on [control=['for'], data=['j']] # depends on [control=['for'], data=['i']]
def combine_sj_out( fns, external_db, total_jxn_cov_cutoff=20, define_sample_name=None, verbose=False, ): """Combine SJ.out.tab files from STAR by filtering based on coverage and comparing to an external annotation to discover novel junctions. Parameters ---------- fns : list of strings Filenames of SJ.out.tab files to combine. external_db : str Filename of splice junction information from external database. The file should have a header and contained the following columns 'gene', 'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'. total_jxn_cov_cutoff : int Discard junctions with less than this many reads summed over all samples. define_sample_name : function A function mapping the SJ.out.tab filenames to sample names. Returns ------- countDF : pandas.DataFrame Number of unique junction spanning reads for each junction that passed filtering criteria. annotDF : pandas.DataFrame Annotation information for junctions that passed filtering criteria. stats : list of strings Human readable statistics. """ if verbose: import sys # I'll start by figuring out which junctions we will keep. counts = _total_jxn_counts(fns) jxns = set(counts[counts >= total_jxn_cov_cutoff].index) if verbose: sys.stderr.write('Counting done\n') stats = [] sj_outD = _make_sj_out_dict(fns, jxns=jxns, define_sample_name=define_sample_name) stats.append('Number of junctions in SJ.out file per sample') for k in sj_outD.keys(): stats.append('{0}\t{1:,}'.format(k, sj_outD[k].shape[0])) stats.append('') if verbose: sys.stderr.write('Dict done\n') sj_outP, annotDF = _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff) stats.append('SJ.out panel size\t{0}'.format(sj_outP.shape)) stats.append('') if verbose: sys.stderr.write('Panel done\n') extDF, ext_stats = read_external_annotation(external_db) stats += ext_stats stats.append('') if verbose: sys.stderr.write('DB read done\n') countsDF, annotDF, filter_stats = _filter_jxns_donor_acceptor(sj_outP, annotDF, extDF) if verbose: sys.stderr.write('Filter done\n') annotDF = _find_novel_donor_acceptor_dist(annotDF, extDF) if verbose: sys.stderr.write('Dist done\n') stats += filter_stats return countsDF, annotDF, stats
def function[combine_sj_out, parameter[fns, external_db, total_jxn_cov_cutoff, define_sample_name, verbose]]: constant[Combine SJ.out.tab files from STAR by filtering based on coverage and comparing to an external annotation to discover novel junctions. Parameters ---------- fns : list of strings Filenames of SJ.out.tab files to combine. external_db : str Filename of splice junction information from external database. The file should have a header and contained the following columns 'gene', 'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'. total_jxn_cov_cutoff : int Discard junctions with less than this many reads summed over all samples. define_sample_name : function A function mapping the SJ.out.tab filenames to sample names. Returns ------- countDF : pandas.DataFrame Number of unique junction spanning reads for each junction that passed filtering criteria. annotDF : pandas.DataFrame Annotation information for junctions that passed filtering criteria. stats : list of strings Human readable statistics. ] if name[verbose] begin[:] import module[sys] variable[counts] assign[=] call[name[_total_jxn_counts], parameter[name[fns]]] variable[jxns] assign[=] call[name[set], parameter[call[name[counts]][compare[name[counts] greater_or_equal[>=] name[total_jxn_cov_cutoff]]].index]] if name[verbose] begin[:] call[name[sys].stderr.write, parameter[constant[Counting done ]]] variable[stats] assign[=] list[[]] variable[sj_outD] assign[=] call[name[_make_sj_out_dict], parameter[name[fns]]] call[name[stats].append, parameter[constant[Number of junctions in SJ.out file per sample]]] for taget[name[k]] in starred[call[name[sj_outD].keys, parameter[]]] begin[:] call[name[stats].append, parameter[call[constant[{0} {1:,}].format, parameter[name[k], call[call[name[sj_outD]][name[k]].shape][constant[0]]]]]] call[name[stats].append, parameter[constant[]]] if name[verbose] begin[:] call[name[sys].stderr.write, parameter[constant[Dict done ]]] <ast.Tuple object at 0x7da1b1602050> assign[=] call[name[_make_sj_out_panel], parameter[name[sj_outD], name[total_jxn_cov_cutoff]]] call[name[stats].append, parameter[call[constant[SJ.out panel size {0}].format, parameter[name[sj_outP].shape]]]] call[name[stats].append, parameter[constant[]]] if name[verbose] begin[:] call[name[sys].stderr.write, parameter[constant[Panel done ]]] <ast.Tuple object at 0x7da1b16e3460> assign[=] call[name[read_external_annotation], parameter[name[external_db]]] <ast.AugAssign object at 0x7da1b16e2800> call[name[stats].append, parameter[constant[]]] if name[verbose] begin[:] call[name[sys].stderr.write, parameter[constant[DB read done ]]] <ast.Tuple object at 0x7da1b16e2500> assign[=] call[name[_filter_jxns_donor_acceptor], parameter[name[sj_outP], name[annotDF], name[extDF]]] if name[verbose] begin[:] call[name[sys].stderr.write, parameter[constant[Filter done ]]] variable[annotDF] assign[=] call[name[_find_novel_donor_acceptor_dist], parameter[name[annotDF], name[extDF]]] if name[verbose] begin[:] call[name[sys].stderr.write, parameter[constant[Dist done ]]] <ast.AugAssign object at 0x7da1b16e07c0> return[tuple[[<ast.Name object at 0x7da1b16e3e80>, <ast.Name object at 0x7da1b16e2ec0>, <ast.Name object at 0x7da1b16e1c90>]]]
keyword[def] identifier[combine_sj_out] ( identifier[fns] , identifier[external_db] , identifier[total_jxn_cov_cutoff] = literal[int] , identifier[define_sample_name] = keyword[None] , identifier[verbose] = keyword[False] , ): literal[string] keyword[if] identifier[verbose] : keyword[import] identifier[sys] identifier[counts] = identifier[_total_jxn_counts] ( identifier[fns] ) identifier[jxns] = identifier[set] ( identifier[counts] [ identifier[counts] >= identifier[total_jxn_cov_cutoff] ]. identifier[index] ) keyword[if] identifier[verbose] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[stats] =[] identifier[sj_outD] = identifier[_make_sj_out_dict] ( identifier[fns] , identifier[jxns] = identifier[jxns] , identifier[define_sample_name] = identifier[define_sample_name] ) identifier[stats] . identifier[append] ( literal[string] ) keyword[for] identifier[k] keyword[in] identifier[sj_outD] . identifier[keys] (): identifier[stats] . identifier[append] ( literal[string] . identifier[format] ( identifier[k] , identifier[sj_outD] [ identifier[k] ]. identifier[shape] [ literal[int] ])) identifier[stats] . identifier[append] ( literal[string] ) keyword[if] identifier[verbose] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[sj_outP] , identifier[annotDF] = identifier[_make_sj_out_panel] ( identifier[sj_outD] , identifier[total_jxn_cov_cutoff] ) identifier[stats] . identifier[append] ( literal[string] . identifier[format] ( identifier[sj_outP] . identifier[shape] )) identifier[stats] . identifier[append] ( literal[string] ) keyword[if] identifier[verbose] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[extDF] , identifier[ext_stats] = identifier[read_external_annotation] ( identifier[external_db] ) identifier[stats] += identifier[ext_stats] identifier[stats] . identifier[append] ( literal[string] ) keyword[if] identifier[verbose] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[countsDF] , identifier[annotDF] , identifier[filter_stats] = identifier[_filter_jxns_donor_acceptor] ( identifier[sj_outP] , identifier[annotDF] , identifier[extDF] ) keyword[if] identifier[verbose] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[annotDF] = identifier[_find_novel_donor_acceptor_dist] ( identifier[annotDF] , identifier[extDF] ) keyword[if] identifier[verbose] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[stats] += identifier[filter_stats] keyword[return] identifier[countsDF] , identifier[annotDF] , identifier[stats]
def combine_sj_out(fns, external_db, total_jxn_cov_cutoff=20, define_sample_name=None, verbose=False): """Combine SJ.out.tab files from STAR by filtering based on coverage and comparing to an external annotation to discover novel junctions. Parameters ---------- fns : list of strings Filenames of SJ.out.tab files to combine. external_db : str Filename of splice junction information from external database. The file should have a header and contained the following columns 'gene', 'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'. total_jxn_cov_cutoff : int Discard junctions with less than this many reads summed over all samples. define_sample_name : function A function mapping the SJ.out.tab filenames to sample names. Returns ------- countDF : pandas.DataFrame Number of unique junction spanning reads for each junction that passed filtering criteria. annotDF : pandas.DataFrame Annotation information for junctions that passed filtering criteria. stats : list of strings Human readable statistics. """ if verbose: import sys # depends on [control=['if'], data=[]] # I'll start by figuring out which junctions we will keep. counts = _total_jxn_counts(fns) jxns = set(counts[counts >= total_jxn_cov_cutoff].index) if verbose: sys.stderr.write('Counting done\n') # depends on [control=['if'], data=[]] stats = [] sj_outD = _make_sj_out_dict(fns, jxns=jxns, define_sample_name=define_sample_name) stats.append('Number of junctions in SJ.out file per sample') for k in sj_outD.keys(): stats.append('{0}\t{1:,}'.format(k, sj_outD[k].shape[0])) # depends on [control=['for'], data=['k']] stats.append('') if verbose: sys.stderr.write('Dict done\n') # depends on [control=['if'], data=[]] (sj_outP, annotDF) = _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff) stats.append('SJ.out panel size\t{0}'.format(sj_outP.shape)) stats.append('') if verbose: sys.stderr.write('Panel done\n') # depends on [control=['if'], data=[]] (extDF, ext_stats) = read_external_annotation(external_db) stats += ext_stats stats.append('') if verbose: sys.stderr.write('DB read done\n') # depends on [control=['if'], data=[]] (countsDF, annotDF, filter_stats) = _filter_jxns_donor_acceptor(sj_outP, annotDF, extDF) if verbose: sys.stderr.write('Filter done\n') # depends on [control=['if'], data=[]] annotDF = _find_novel_donor_acceptor_dist(annotDF, extDF) if verbose: sys.stderr.write('Dist done\n') # depends on [control=['if'], data=[]] stats += filter_stats return (countsDF, annotDF, stats)
def ren(i): """ Input: { data_uoa - repo UOA (new_data_uoa) or xcids[0] - {'data_uoa'} - new data UOA } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ o=i.get('out','') duoa=i.get('data_uoa','') if duoa=='': return {'return':1, 'error':'repo is not defined'} r=ck.access({'action':'load', 'module_uoa':work['self_module_uid'], 'data_uoa':duoa}) if r['return']>0: return r dd=r['dict'] dp=r['path'] duoa_real=r['data_uoa'] dname=r['data_name'] nduoa=i.get('new_data_uoa','') if nduoa=='': xcids=i.get('xcids',[]) if len(xcids)>0: xcid=xcids[0] nduoa=xcid.get('data_uoa','') if nduoa=='': xcids=i.get('cids',[]) if len(xcids)>0: nduoa=xcids[0] if nduoa=='': return {'return':1, 'error':'new repo name is not defined'} if nduoa=='': return {'return':1, 'error':'new repo name is not defined'} if nduoa=='local' or nduoa=='default': return {'return':1, 'error':'new repo name already exists'} # Check if such repo doesn't exist r=ck.access({'action':'load', 'module_uoa':work['self_module_uid'], 'data_uoa':nduoa}) if r['return']==0: return {'return':1, 'error':'repo already exists'} # Update .ckr.json dpp=dd.get('path','') if dpp!='': pckr=os.path.join(dpp,ck.cfg['repo_file']) r=ck.load_json_file({'json_file':pckr}) if r['return']>0: return r dckr=r['dict'] x=dckr.get('data_uoa','') if x!='' and x==duoa_real: dckr['data_uoa']=nduoa x=dckr.get('data_alias','') if x!='' and x==duoa_real: dckr['data_alias']=nduoa x=dckr.get('data_name','') if x!='' and x==duoa_real: dckr['data_name']=nduoa r=ck.save_json_to_file({'json_file':pckr, 'dict':dckr}) if r['return']>0: return r # Rename repo entry using internal command r=ck.access({'action':'ren', 'module_uoa':work['self_module_uid'], 'data_uoa':duoa, 'new_data_uoa':nduoa, 'common_func':'yes'}) if r['return']>0: return r # Recache repos r1=recache({'out':o}) if r1['return']>0: return r1 return r
def function[ren, parameter[i]]: constant[ Input: { data_uoa - repo UOA (new_data_uoa) or xcids[0] - {'data_uoa'} - new data UOA } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } ] variable[o] assign[=] call[name[i].get, parameter[constant[out], constant[]]] variable[duoa] assign[=] call[name[i].get, parameter[constant[data_uoa], constant[]]] if compare[name[duoa] equal[==] constant[]] begin[:] return[dictionary[[<ast.Constant object at 0x7da1b236e8f0>, <ast.Constant object at 0x7da1b236dba0>], [<ast.Constant object at 0x7da1b236d660>, <ast.Constant object at 0x7da1b236dc00>]]] variable[r] assign[=] call[name[ck].access, parameter[dictionary[[<ast.Constant object at 0x7da1b236f070>, <ast.Constant object at 0x7da1b236fc40>, <ast.Constant object at 0x7da1b236fe50>], [<ast.Constant object at 0x7da1b236e740>, <ast.Subscript object at 0x7da1b236f310>, <ast.Name object at 0x7da1b236e410>]]]] if compare[call[name[r]][constant[return]] greater[>] constant[0]] begin[:] return[name[r]] variable[dd] assign[=] call[name[r]][constant[dict]] variable[dp] assign[=] call[name[r]][constant[path]] variable[duoa_real] assign[=] call[name[r]][constant[data_uoa]] variable[dname] assign[=] call[name[r]][constant[data_name]] variable[nduoa] assign[=] call[name[i].get, parameter[constant[new_data_uoa], constant[]]] if compare[name[nduoa] equal[==] constant[]] begin[:] variable[xcids] assign[=] call[name[i].get, parameter[constant[xcids], list[[]]]] if compare[call[name[len], parameter[name[xcids]]] greater[>] constant[0]] begin[:] variable[xcid] assign[=] call[name[xcids]][constant[0]] variable[nduoa] assign[=] call[name[xcid].get, parameter[constant[data_uoa], constant[]]] if compare[name[nduoa] equal[==] constant[]] begin[:] variable[xcids] assign[=] call[name[i].get, parameter[constant[cids], list[[]]]] if compare[call[name[len], parameter[name[xcids]]] greater[>] constant[0]] begin[:] variable[nduoa] assign[=] call[name[xcids]][constant[0]] if compare[name[nduoa] equal[==] constant[]] begin[:] return[dictionary[[<ast.Constant object at 0x7da1b222bcd0>, <ast.Constant object at 0x7da1b222bfd0>], [<ast.Constant object at 0x7da1b222bca0>, <ast.Constant object at 0x7da1b222bfa0>]]] if compare[name[nduoa] equal[==] constant[]] begin[:] return[dictionary[[<ast.Constant object at 0x7da1b222b340>, <ast.Constant object at 0x7da1b222be80>], [<ast.Constant object at 0x7da1b222bd60>, <ast.Constant object at 0x7da1b222bb20>]]] if <ast.BoolOp object at 0x7da1b222beb0> begin[:] return[dictionary[[<ast.Constant object at 0x7da1b22167a0>, <ast.Constant object at 0x7da1b2217760>], [<ast.Constant object at 0x7da1b2217790>, <ast.Constant object at 0x7da1b2216ce0>]]] variable[r] assign[=] call[name[ck].access, parameter[dictionary[[<ast.Constant object at 0x7da1b2214220>, <ast.Constant object at 0x7da1b22141c0>, <ast.Constant object at 0x7da1b2214250>], [<ast.Constant object at 0x7da1b22143a0>, <ast.Subscript object at 0x7da1b2214520>, <ast.Name object at 0x7da1b2214760>]]]] if compare[call[name[r]][constant[return]] equal[==] constant[0]] begin[:] return[dictionary[[<ast.Constant object at 0x7da1b2215c60>, <ast.Constant object at 0x7da1b2215cc0>], [<ast.Constant object at 0x7da1b2215c90>, <ast.Constant object at 0x7da1b2215f90>]]] variable[dpp] assign[=] call[name[dd].get, parameter[constant[path], constant[]]] if compare[name[dpp] not_equal[!=] constant[]] begin[:] variable[pckr] assign[=] call[name[os].path.join, parameter[name[dpp], call[name[ck].cfg][constant[repo_file]]]] variable[r] assign[=] call[name[ck].load_json_file, parameter[dictionary[[<ast.Constant object at 0x7da1b2214970>], [<ast.Name object at 0x7da1b2214910>]]]] if compare[call[name[r]][constant[return]] greater[>] constant[0]] begin[:] return[name[r]] variable[dckr] assign[=] call[name[r]][constant[dict]] variable[x] assign[=] call[name[dckr].get, parameter[constant[data_uoa], constant[]]] if <ast.BoolOp object at 0x7da1b22142b0> begin[:] call[name[dckr]][constant[data_uoa]] assign[=] name[nduoa] variable[x] assign[=] call[name[dckr].get, parameter[constant[data_alias], constant[]]] if <ast.BoolOp object at 0x7da1b22174f0> begin[:] call[name[dckr]][constant[data_alias]] assign[=] name[nduoa] variable[x] assign[=] call[name[dckr].get, parameter[constant[data_name], constant[]]] if <ast.BoolOp object at 0x7da1b2215f30> begin[:] call[name[dckr]][constant[data_name]] assign[=] name[nduoa] variable[r] assign[=] call[name[ck].save_json_to_file, parameter[dictionary[[<ast.Constant object at 0x7da1b2216560>, <ast.Constant object at 0x7da1b22164a0>], [<ast.Name object at 0x7da1b22163b0>, <ast.Name object at 0x7da1b2216230>]]]] if compare[call[name[r]][constant[return]] greater[>] constant[0]] begin[:] return[name[r]] variable[r] assign[=] call[name[ck].access, parameter[dictionary[[<ast.Constant object at 0x7da1b2216c20>, <ast.Constant object at 0x7da1b2216a70>, <ast.Constant object at 0x7da1b2216950>, <ast.Constant object at 0x7da1b2216b60>, <ast.Constant object at 0x7da1b22169b0>], [<ast.Constant object at 0x7da1b2216ad0>, <ast.Subscript object at 0x7da1b2216bf0>, <ast.Name object at 0x7da1b2216b00>, <ast.Name object at 0x7da1b2216b30>, <ast.Constant object at 0x7da1b22168f0>]]]] if compare[call[name[r]][constant[return]] greater[>] constant[0]] begin[:] return[name[r]] variable[r1] assign[=] call[name[recache], parameter[dictionary[[<ast.Constant object at 0x7da1b22171f0>], [<ast.Name object at 0x7da1b2217130>]]]] if compare[call[name[r1]][constant[return]] greater[>] constant[0]] begin[:] return[name[r1]] return[name[r]]
keyword[def] identifier[ren] ( identifier[i] ): literal[string] identifier[o] = identifier[i] . identifier[get] ( literal[string] , literal[string] ) identifier[duoa] = identifier[i] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[duoa] == literal[string] : keyword[return] { literal[string] : literal[int] , literal[string] : literal[string] } identifier[r] = identifier[ck] . identifier[access] ({ literal[string] : literal[string] , literal[string] : identifier[work] [ literal[string] ], literal[string] : identifier[duoa] }) keyword[if] identifier[r] [ literal[string] ]> literal[int] : keyword[return] identifier[r] identifier[dd] = identifier[r] [ literal[string] ] identifier[dp] = identifier[r] [ literal[string] ] identifier[duoa_real] = identifier[r] [ literal[string] ] identifier[dname] = identifier[r] [ literal[string] ] identifier[nduoa] = identifier[i] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[nduoa] == literal[string] : identifier[xcids] = identifier[i] . identifier[get] ( literal[string] ,[]) keyword[if] identifier[len] ( identifier[xcids] )> literal[int] : identifier[xcid] = identifier[xcids] [ literal[int] ] identifier[nduoa] = identifier[xcid] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[nduoa] == literal[string] : identifier[xcids] = identifier[i] . identifier[get] ( literal[string] ,[]) keyword[if] identifier[len] ( identifier[xcids] )> literal[int] : identifier[nduoa] = identifier[xcids] [ literal[int] ] keyword[if] identifier[nduoa] == literal[string] : keyword[return] { literal[string] : literal[int] , literal[string] : literal[string] } keyword[if] identifier[nduoa] == literal[string] : keyword[return] { literal[string] : literal[int] , literal[string] : literal[string] } keyword[if] identifier[nduoa] == literal[string] keyword[or] identifier[nduoa] == literal[string] : keyword[return] { literal[string] : literal[int] , literal[string] : literal[string] } identifier[r] = identifier[ck] . identifier[access] ({ literal[string] : literal[string] , literal[string] : identifier[work] [ literal[string] ], literal[string] : identifier[nduoa] }) keyword[if] identifier[r] [ literal[string] ]== literal[int] : keyword[return] { literal[string] : literal[int] , literal[string] : literal[string] } identifier[dpp] = identifier[dd] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[dpp] != literal[string] : identifier[pckr] = identifier[os] . identifier[path] . identifier[join] ( identifier[dpp] , identifier[ck] . identifier[cfg] [ literal[string] ]) identifier[r] = identifier[ck] . identifier[load_json_file] ({ literal[string] : identifier[pckr] }) keyword[if] identifier[r] [ literal[string] ]> literal[int] : keyword[return] identifier[r] identifier[dckr] = identifier[r] [ literal[string] ] identifier[x] = identifier[dckr] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[x] != literal[string] keyword[and] identifier[x] == identifier[duoa_real] : identifier[dckr] [ literal[string] ]= identifier[nduoa] identifier[x] = identifier[dckr] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[x] != literal[string] keyword[and] identifier[x] == identifier[duoa_real] : identifier[dckr] [ literal[string] ]= identifier[nduoa] identifier[x] = identifier[dckr] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[x] != literal[string] keyword[and] identifier[x] == identifier[duoa_real] : identifier[dckr] [ literal[string] ]= identifier[nduoa] identifier[r] = identifier[ck] . identifier[save_json_to_file] ({ literal[string] : identifier[pckr] , literal[string] : identifier[dckr] }) keyword[if] identifier[r] [ literal[string] ]> literal[int] : keyword[return] identifier[r] identifier[r] = identifier[ck] . identifier[access] ({ literal[string] : literal[string] , literal[string] : identifier[work] [ literal[string] ], literal[string] : identifier[duoa] , literal[string] : identifier[nduoa] , literal[string] : literal[string] }) keyword[if] identifier[r] [ literal[string] ]> literal[int] : keyword[return] identifier[r] identifier[r1] = identifier[recache] ({ literal[string] : identifier[o] }) keyword[if] identifier[r1] [ literal[string] ]> literal[int] : keyword[return] identifier[r1] keyword[return] identifier[r]
def ren(i): """ Input: { data_uoa - repo UOA (new_data_uoa) or xcids[0] - {'data_uoa'} - new data UOA } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ o = i.get('out', '') duoa = i.get('data_uoa', '') if duoa == '': return {'return': 1, 'error': 'repo is not defined'} # depends on [control=['if'], data=[]] r = ck.access({'action': 'load', 'module_uoa': work['self_module_uid'], 'data_uoa': duoa}) if r['return'] > 0: return r # depends on [control=['if'], data=[]] dd = r['dict'] dp = r['path'] duoa_real = r['data_uoa'] dname = r['data_name'] nduoa = i.get('new_data_uoa', '') if nduoa == '': xcids = i.get('xcids', []) if len(xcids) > 0: xcid = xcids[0] nduoa = xcid.get('data_uoa', '') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['nduoa']] if nduoa == '': xcids = i.get('cids', []) if len(xcids) > 0: nduoa = xcids[0] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['nduoa']] if nduoa == '': return {'return': 1, 'error': 'new repo name is not defined'} # depends on [control=['if'], data=[]] if nduoa == '': return {'return': 1, 'error': 'new repo name is not defined'} # depends on [control=['if'], data=[]] if nduoa == 'local' or nduoa == 'default': return {'return': 1, 'error': 'new repo name already exists'} # depends on [control=['if'], data=[]] # Check if such repo doesn't exist r = ck.access({'action': 'load', 'module_uoa': work['self_module_uid'], 'data_uoa': nduoa}) if r['return'] == 0: return {'return': 1, 'error': 'repo already exists'} # depends on [control=['if'], data=[]] # Update .ckr.json dpp = dd.get('path', '') if dpp != '': pckr = os.path.join(dpp, ck.cfg['repo_file']) r = ck.load_json_file({'json_file': pckr}) if r['return'] > 0: return r # depends on [control=['if'], data=[]] dckr = r['dict'] x = dckr.get('data_uoa', '') if x != '' and x == duoa_real: dckr['data_uoa'] = nduoa # depends on [control=['if'], data=[]] x = dckr.get('data_alias', '') if x != '' and x == duoa_real: dckr['data_alias'] = nduoa # depends on [control=['if'], data=[]] x = dckr.get('data_name', '') if x != '' and x == duoa_real: dckr['data_name'] = nduoa # depends on [control=['if'], data=[]] r = ck.save_json_to_file({'json_file': pckr, 'dict': dckr}) if r['return'] > 0: return r # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['dpp']] # Rename repo entry using internal command r = ck.access({'action': 'ren', 'module_uoa': work['self_module_uid'], 'data_uoa': duoa, 'new_data_uoa': nduoa, 'common_func': 'yes'}) if r['return'] > 0: return r # depends on [control=['if'], data=[]] # Recache repos r1 = recache({'out': o}) if r1['return'] > 0: return r1 # depends on [control=['if'], data=[]] return r
def parse(self, argument): """Determine validity of argument and return the correct element of enum. If self.enum_values is empty, then all arguments are valid and argument will be returned. Otherwise, if argument matches an element in enum, then the first matching element will be returned. Args: argument: The supplied flag value. Returns: The matching element from enum_values, or argument if enum_values is empty. Raises: ValueError: enum_values was non-empty, but argument didn't match anything in enum. """ if not self.enum_values: return argument elif self.case_sensitive: if argument not in self.enum_values: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return argument else: if argument.upper() not in [value.upper() for value in self.enum_values]: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) else: return [value for value in self.enum_values if value.upper() == argument.upper()][0]
def function[parse, parameter[self, argument]]: constant[Determine validity of argument and return the correct element of enum. If self.enum_values is empty, then all arguments are valid and argument will be returned. Otherwise, if argument matches an element in enum, then the first matching element will be returned. Args: argument: The supplied flag value. Returns: The matching element from enum_values, or argument if enum_values is empty. Raises: ValueError: enum_values was non-empty, but argument didn't match anything in enum. ] if <ast.UnaryOp object at 0x7da1b26ae5c0> begin[:] return[name[argument]]
keyword[def] identifier[parse] ( identifier[self] , identifier[argument] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[enum_values] : keyword[return] identifier[argument] keyword[elif] identifier[self] . identifier[case_sensitive] : keyword[if] identifier[argument] keyword[not] keyword[in] identifier[self] . identifier[enum_values] : keyword[raise] identifier[ValueError] ( literal[string] % literal[string] . identifier[join] ( identifier[self] . identifier[enum_values] )) keyword[else] : keyword[return] identifier[argument] keyword[else] : keyword[if] identifier[argument] . identifier[upper] () keyword[not] keyword[in] [ identifier[value] . identifier[upper] () keyword[for] identifier[value] keyword[in] identifier[self] . identifier[enum_values] ]: keyword[raise] identifier[ValueError] ( literal[string] % literal[string] . identifier[join] ( identifier[self] . identifier[enum_values] )) keyword[else] : keyword[return] [ identifier[value] keyword[for] identifier[value] keyword[in] identifier[self] . identifier[enum_values] keyword[if] identifier[value] . identifier[upper] ()== identifier[argument] . identifier[upper] ()][ literal[int] ]
def parse(self, argument): """Determine validity of argument and return the correct element of enum. If self.enum_values is empty, then all arguments are valid and argument will be returned. Otherwise, if argument matches an element in enum, then the first matching element will be returned. Args: argument: The supplied flag value. Returns: The matching element from enum_values, or argument if enum_values is empty. Raises: ValueError: enum_values was non-empty, but argument didn't match anything in enum. """ if not self.enum_values: return argument # depends on [control=['if'], data=[]] elif self.case_sensitive: if argument not in self.enum_values: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) # depends on [control=['if'], data=[]] else: return argument # depends on [control=['if'], data=[]] elif argument.upper() not in [value.upper() for value in self.enum_values]: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_values)) # depends on [control=['if'], data=[]] else: return [value for value in self.enum_values if value.upper() == argument.upper()][0]
def run(self): """ loops until exit command given """ while self.status != 'EXIT': print(self.process_input(self.get_input())) print('Bye')
def function[run, parameter[self]]: constant[ loops until exit command given ] while compare[name[self].status not_equal[!=] constant[EXIT]] begin[:] call[name[print], parameter[call[name[self].process_input, parameter[call[name[self].get_input, parameter[]]]]]] call[name[print], parameter[constant[Bye]]]
keyword[def] identifier[run] ( identifier[self] ): literal[string] keyword[while] identifier[self] . identifier[status] != literal[string] : identifier[print] ( identifier[self] . identifier[process_input] ( identifier[self] . identifier[get_input] ())) identifier[print] ( literal[string] )
def run(self): """ loops until exit command given """ while self.status != 'EXIT': print(self.process_input(self.get_input())) # depends on [control=['while'], data=[]] print('Bye')
def leaders(self, current_page, **options): ''' Retrieve a page of leaders from the leaderboard. @param current_page [int] Page to retrieve from the leaderboard. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard. ''' return self.leaders_in(self.leaderboard_name, current_page, **options)
def function[leaders, parameter[self, current_page]]: constant[ Retrieve a page of leaders from the leaderboard. @param current_page [int] Page to retrieve from the leaderboard. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard. ] return[call[name[self].leaders_in, parameter[name[self].leaderboard_name, name[current_page]]]]
keyword[def] identifier[leaders] ( identifier[self] , identifier[current_page] ,** identifier[options] ): literal[string] keyword[return] identifier[self] . identifier[leaders_in] ( identifier[self] . identifier[leaderboard_name] , identifier[current_page] ,** identifier[options] )
def leaders(self, current_page, **options): """ Retrieve a page of leaders from the leaderboard. @param current_page [int] Page to retrieve from the leaderboard. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard. """ return self.leaders_in(self.leaderboard_name, current_page, **options)
def _set_lsp_secpath_autobw_template(self, v, load=False): """ Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_secpath_autobw_template is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_secpath_autobw_template() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ReferenceType(referenced_path='../../../../autobw-template/autobw-template-name', caller=self._path() + ['lsp-secpath-autobw-template'], path_helper=self._path_helper, require_instance=True), is_leaf=True, yang_name="lsp-secpath-autobw-template", rest_name="template", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Inherit Auto-bandwidth parameters from a template', u'alt-name': u'template'}}, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='leafref', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """lsp_secpath_autobw_template must be of a type compatible with leafref""", 'defined-type': "leafref", 'generated-type': """YANGDynClass(base=ReferenceType(referenced_path='../../../../autobw-template/autobw-template-name', caller=self._path() + ['lsp-secpath-autobw-template'], path_helper=self._path_helper, require_instance=True), is_leaf=True, yang_name="lsp-secpath-autobw-template", rest_name="template", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Inherit Auto-bandwidth parameters from a template', u'alt-name': u'template'}}, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='leafref', is_config=True)""", }) self.__lsp_secpath_autobw_template = t if hasattr(self, '_set'): self._set()
def function[_set_lsp_secpath_autobw_template, parameter[self, v, load]]: constant[ Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_secpath_autobw_template is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_secpath_autobw_template() directly. ] if call[name[hasattr], parameter[name[v], constant[_utype]]] begin[:] variable[v] assign[=] call[name[v]._utype, parameter[name[v]]] <ast.Try object at 0x7da1b256f040> name[self].__lsp_secpath_autobw_template assign[=] name[t] if call[name[hasattr], parameter[name[self], constant[_set]]] begin[:] call[name[self]._set, parameter[]]
keyword[def] identifier[_set_lsp_secpath_autobw_template] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ): literal[string] keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ): identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] ) keyword[try] : identifier[t] = identifier[YANGDynClass] ( identifier[v] , identifier[base] = identifier[ReferenceType] ( identifier[referenced_path] = literal[string] , identifier[caller] = identifier[self] . identifier[_path] ()+[ literal[string] ], identifier[path_helper] = identifier[self] . identifier[_path_helper] , identifier[require_instance] = keyword[True] ), identifier[is_leaf] = keyword[True] , identifier[yang_name] = literal[string] , identifier[rest_name] = literal[string] , identifier[parent] = identifier[self] , identifier[path_helper] = identifier[self] . identifier[_path_helper] , identifier[extmethods] = identifier[self] . identifier[_extmethods] , identifier[register_paths] = keyword[True] , identifier[extensions] ={ literal[string] :{ literal[string] : keyword[None] , literal[string] : literal[string] , literal[string] : literal[string] }}, identifier[namespace] = literal[string] , identifier[defining_module] = literal[string] , identifier[yang_type] = literal[string] , identifier[is_config] = keyword[True] ) keyword[except] ( identifier[TypeError] , identifier[ValueError] ): keyword[raise] identifier[ValueError] ({ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , }) identifier[self] . identifier[__lsp_secpath_autobw_template] = identifier[t] keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[self] . identifier[_set] ()
def _set_lsp_secpath_autobw_template(self, v, load=False): """ Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_secpath_autobw_template is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lsp_secpath_autobw_template() directly. """ if hasattr(v, '_utype'): v = v._utype(v) # depends on [control=['if'], data=[]] try: t = YANGDynClass(v, base=ReferenceType(referenced_path='../../../../autobw-template/autobw-template-name', caller=self._path() + ['lsp-secpath-autobw-template'], path_helper=self._path_helper, require_instance=True), is_leaf=True, yang_name='lsp-secpath-autobw-template', rest_name='template', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Inherit Auto-bandwidth parameters from a template', u'alt-name': u'template'}}, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='leafref', is_config=True) # depends on [control=['try'], data=[]] except (TypeError, ValueError): raise ValueError({'error-string': 'lsp_secpath_autobw_template must be of a type compatible with leafref', 'defined-type': 'leafref', 'generated-type': 'YANGDynClass(base=ReferenceType(referenced_path=\'../../../../autobw-template/autobw-template-name\', caller=self._path() + [\'lsp-secpath-autobw-template\'], path_helper=self._path_helper, require_instance=True), is_leaf=True, yang_name="lsp-secpath-autobw-template", rest_name="template", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u\'tailf-common\': {u\'cli-full-command\': None, u\'info\': u\'Inherit Auto-bandwidth parameters from a template\', u\'alt-name\': u\'template\'}}, namespace=\'urn:brocade.com:mgmt:brocade-mpls\', defining_module=\'brocade-mpls\', yang_type=\'leafref\', is_config=True)'}) # depends on [control=['except'], data=[]] self.__lsp_secpath_autobw_template = t if hasattr(self, '_set'): self._set() # depends on [control=['if'], data=[]]
def copy_shell(self): """ Copy the group properties EXCEPT the members. Members need to be filled after manually :return: Itemgroup object :rtype: alignak.objects.itemgroup.Itemgroup :return: None """ cls = self.__class__ new_i = cls() # create a new group new_i.uuid = self.uuid # with the same id # Copy all properties for prop in cls.properties: if hasattr(self, prop): if prop in ['members', 'unknown_members']: setattr(new_i, prop, []) else: setattr(new_i, prop, getattr(self, prop)) return new_i
def function[copy_shell, parameter[self]]: constant[ Copy the group properties EXCEPT the members. Members need to be filled after manually :return: Itemgroup object :rtype: alignak.objects.itemgroup.Itemgroup :return: None ] variable[cls] assign[=] name[self].__class__ variable[new_i] assign[=] call[name[cls], parameter[]] name[new_i].uuid assign[=] name[self].uuid for taget[name[prop]] in starred[name[cls].properties] begin[:] if call[name[hasattr], parameter[name[self], name[prop]]] begin[:] if compare[name[prop] in list[[<ast.Constant object at 0x7da18f7202e0>, <ast.Constant object at 0x7da18f7228f0>]]] begin[:] call[name[setattr], parameter[name[new_i], name[prop], list[[]]]] return[name[new_i]]
keyword[def] identifier[copy_shell] ( identifier[self] ): literal[string] identifier[cls] = identifier[self] . identifier[__class__] identifier[new_i] = identifier[cls] () identifier[new_i] . identifier[uuid] = identifier[self] . identifier[uuid] keyword[for] identifier[prop] keyword[in] identifier[cls] . identifier[properties] : keyword[if] identifier[hasattr] ( identifier[self] , identifier[prop] ): keyword[if] identifier[prop] keyword[in] [ literal[string] , literal[string] ]: identifier[setattr] ( identifier[new_i] , identifier[prop] ,[]) keyword[else] : identifier[setattr] ( identifier[new_i] , identifier[prop] , identifier[getattr] ( identifier[self] , identifier[prop] )) keyword[return] identifier[new_i]
def copy_shell(self): """ Copy the group properties EXCEPT the members. Members need to be filled after manually :return: Itemgroup object :rtype: alignak.objects.itemgroup.Itemgroup :return: None """ cls = self.__class__ new_i = cls() # create a new group new_i.uuid = self.uuid # with the same id # Copy all properties for prop in cls.properties: if hasattr(self, prop): if prop in ['members', 'unknown_members']: setattr(new_i, prop, []) # depends on [control=['if'], data=['prop']] else: setattr(new_i, prop, getattr(self, prop)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['prop']] return new_i
def get_git_postversion(addon_dir): """ return the addon version number, with a developmental version increment if there were git commits in the addon_dir after the last version change. If the last change to the addon correspond to the version number in the manifest it is used as is for the python package version. Otherwise a counter is incremented for each commit and resulting version number has the following form: [8|9].0.x.y.z.1devN, N being the number of git commits since the version change. Note: we use .99.devN because: * pip ignores .postN by design (https://github.com/pypa/pip/issues/2872) * x.y.z.devN is anterior to x.y.z Note: we don't put the sha1 of the commit in the version number because this is not PEP 440 compliant and is therefore misinterpreted by pip. """ addon_dir = os.path.realpath(addon_dir) last_version = read_manifest(addon_dir).get('version', '0.0.0') last_version_parsed = parse_version(last_version) if not is_git_controlled(addon_dir): return last_version if get_git_uncommitted(addon_dir): uncommitted = True count = 1 else: uncommitted = False count = 0 last_sha = None git_root = get_git_root(addon_dir) for sha in git_log_iterator(addon_dir): try: manifest = read_manifest_from_sha(sha, addon_dir, git_root) except NoManifestFound: break version = manifest.get('version', '0.0.0') version_parsed = parse_version(version) if version_parsed != last_version_parsed: break if last_sha is None: last_sha = sha else: count += 1 if not count: return last_version if last_sha: return last_version + ".99.dev%s" % count if uncommitted: return last_version + ".dev1" # if everything is committed, the last commit # must have the same version as current, # so last_sha must be set and we'll never reach this branch return last_version
def function[get_git_postversion, parameter[addon_dir]]: constant[ return the addon version number, with a developmental version increment if there were git commits in the addon_dir after the last version change. If the last change to the addon correspond to the version number in the manifest it is used as is for the python package version. Otherwise a counter is incremented for each commit and resulting version number has the following form: [8|9].0.x.y.z.1devN, N being the number of git commits since the version change. Note: we use .99.devN because: * pip ignores .postN by design (https://github.com/pypa/pip/issues/2872) * x.y.z.devN is anterior to x.y.z Note: we don't put the sha1 of the commit in the version number because this is not PEP 440 compliant and is therefore misinterpreted by pip. ] variable[addon_dir] assign[=] call[name[os].path.realpath, parameter[name[addon_dir]]] variable[last_version] assign[=] call[call[name[read_manifest], parameter[name[addon_dir]]].get, parameter[constant[version], constant[0.0.0]]] variable[last_version_parsed] assign[=] call[name[parse_version], parameter[name[last_version]]] if <ast.UnaryOp object at 0x7da1b2609000> begin[:] return[name[last_version]] if call[name[get_git_uncommitted], parameter[name[addon_dir]]] begin[:] variable[uncommitted] assign[=] constant[True] variable[count] assign[=] constant[1] variable[last_sha] assign[=] constant[None] variable[git_root] assign[=] call[name[get_git_root], parameter[name[addon_dir]]] for taget[name[sha]] in starred[call[name[git_log_iterator], parameter[name[addon_dir]]]] begin[:] <ast.Try object at 0x7da1b260b760> variable[version] assign[=] call[name[manifest].get, parameter[constant[version], constant[0.0.0]]] variable[version_parsed] assign[=] call[name[parse_version], parameter[name[version]]] if compare[name[version_parsed] not_equal[!=] name[last_version_parsed]] begin[:] break if compare[name[last_sha] is constant[None]] begin[:] variable[last_sha] assign[=] name[sha] if <ast.UnaryOp object at 0x7da1b260ba60> begin[:] return[name[last_version]] if name[last_sha] begin[:] return[binary_operation[name[last_version] + binary_operation[constant[.99.dev%s] <ast.Mod object at 0x7da2590d6920> name[count]]]] if name[uncommitted] begin[:] return[binary_operation[name[last_version] + constant[.dev1]]] return[name[last_version]]
keyword[def] identifier[get_git_postversion] ( identifier[addon_dir] ): literal[string] identifier[addon_dir] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[addon_dir] ) identifier[last_version] = identifier[read_manifest] ( identifier[addon_dir] ). identifier[get] ( literal[string] , literal[string] ) identifier[last_version_parsed] = identifier[parse_version] ( identifier[last_version] ) keyword[if] keyword[not] identifier[is_git_controlled] ( identifier[addon_dir] ): keyword[return] identifier[last_version] keyword[if] identifier[get_git_uncommitted] ( identifier[addon_dir] ): identifier[uncommitted] = keyword[True] identifier[count] = literal[int] keyword[else] : identifier[uncommitted] = keyword[False] identifier[count] = literal[int] identifier[last_sha] = keyword[None] identifier[git_root] = identifier[get_git_root] ( identifier[addon_dir] ) keyword[for] identifier[sha] keyword[in] identifier[git_log_iterator] ( identifier[addon_dir] ): keyword[try] : identifier[manifest] = identifier[read_manifest_from_sha] ( identifier[sha] , identifier[addon_dir] , identifier[git_root] ) keyword[except] identifier[NoManifestFound] : keyword[break] identifier[version] = identifier[manifest] . identifier[get] ( literal[string] , literal[string] ) identifier[version_parsed] = identifier[parse_version] ( identifier[version] ) keyword[if] identifier[version_parsed] != identifier[last_version_parsed] : keyword[break] keyword[if] identifier[last_sha] keyword[is] keyword[None] : identifier[last_sha] = identifier[sha] keyword[else] : identifier[count] += literal[int] keyword[if] keyword[not] identifier[count] : keyword[return] identifier[last_version] keyword[if] identifier[last_sha] : keyword[return] identifier[last_version] + literal[string] % identifier[count] keyword[if] identifier[uncommitted] : keyword[return] identifier[last_version] + literal[string] keyword[return] identifier[last_version]
def get_git_postversion(addon_dir): """ return the addon version number, with a developmental version increment if there were git commits in the addon_dir after the last version change. If the last change to the addon correspond to the version number in the manifest it is used as is for the python package version. Otherwise a counter is incremented for each commit and resulting version number has the following form: [8|9].0.x.y.z.1devN, N being the number of git commits since the version change. Note: we use .99.devN because: * pip ignores .postN by design (https://github.com/pypa/pip/issues/2872) * x.y.z.devN is anterior to x.y.z Note: we don't put the sha1 of the commit in the version number because this is not PEP 440 compliant and is therefore misinterpreted by pip. """ addon_dir = os.path.realpath(addon_dir) last_version = read_manifest(addon_dir).get('version', '0.0.0') last_version_parsed = parse_version(last_version) if not is_git_controlled(addon_dir): return last_version # depends on [control=['if'], data=[]] if get_git_uncommitted(addon_dir): uncommitted = True count = 1 # depends on [control=['if'], data=[]] else: uncommitted = False count = 0 last_sha = None git_root = get_git_root(addon_dir) for sha in git_log_iterator(addon_dir): try: manifest = read_manifest_from_sha(sha, addon_dir, git_root) # depends on [control=['try'], data=[]] except NoManifestFound: break # depends on [control=['except'], data=[]] version = manifest.get('version', '0.0.0') version_parsed = parse_version(version) if version_parsed != last_version_parsed: break # depends on [control=['if'], data=[]] if last_sha is None: last_sha = sha # depends on [control=['if'], data=['last_sha']] else: count += 1 # depends on [control=['for'], data=['sha']] if not count: return last_version # depends on [control=['if'], data=[]] if last_sha: return last_version + '.99.dev%s' % count # depends on [control=['if'], data=[]] if uncommitted: return last_version + '.dev1' # depends on [control=['if'], data=[]] # if everything is committed, the last commit # must have the same version as current, # so last_sha must be set and we'll never reach this branch return last_version
def tilequeue_load_tiles_of_interest(cfg, peripherals): """ Given a newline-delimited file containing tile coordinates in `zoom/column/row` format, load those tiles into the tiles of interest. """ logger = make_logger(cfg, 'load_tiles_of_interest') toi_filename = "toi.txt" logger.info('Loading tiles of interest from %s ... ', toi_filename) with open(toi_filename, 'r') as f: new_toi = load_set_from_fp(f) logger.info('Loading tiles of interest from %s ... done', toi_filename) logger.info('Setting new TOI (with %s tiles) ... ', len(new_toi)) peripherals.toi.set_tiles_of_interest(new_toi) emit_toi_stats(new_toi, peripherals) logger.info('Setting new TOI (with %s tiles) ... done', len(new_toi)) logger.info('Loading tiles of interest ... done')
def function[tilequeue_load_tiles_of_interest, parameter[cfg, peripherals]]: constant[ Given a newline-delimited file containing tile coordinates in `zoom/column/row` format, load those tiles into the tiles of interest. ] variable[logger] assign[=] call[name[make_logger], parameter[name[cfg], constant[load_tiles_of_interest]]] variable[toi_filename] assign[=] constant[toi.txt] call[name[logger].info, parameter[constant[Loading tiles of interest from %s ... ], name[toi_filename]]] with call[name[open], parameter[name[toi_filename], constant[r]]] begin[:] variable[new_toi] assign[=] call[name[load_set_from_fp], parameter[name[f]]] call[name[logger].info, parameter[constant[Loading tiles of interest from %s ... done], name[toi_filename]]] call[name[logger].info, parameter[constant[Setting new TOI (with %s tiles) ... ], call[name[len], parameter[name[new_toi]]]]] call[name[peripherals].toi.set_tiles_of_interest, parameter[name[new_toi]]] call[name[emit_toi_stats], parameter[name[new_toi], name[peripherals]]] call[name[logger].info, parameter[constant[Setting new TOI (with %s tiles) ... done], call[name[len], parameter[name[new_toi]]]]] call[name[logger].info, parameter[constant[Loading tiles of interest ... done]]]
keyword[def] identifier[tilequeue_load_tiles_of_interest] ( identifier[cfg] , identifier[peripherals] ): literal[string] identifier[logger] = identifier[make_logger] ( identifier[cfg] , literal[string] ) identifier[toi_filename] = literal[string] identifier[logger] . identifier[info] ( literal[string] , identifier[toi_filename] ) keyword[with] identifier[open] ( identifier[toi_filename] , literal[string] ) keyword[as] identifier[f] : identifier[new_toi] = identifier[load_set_from_fp] ( identifier[f] ) identifier[logger] . identifier[info] ( literal[string] , identifier[toi_filename] ) identifier[logger] . identifier[info] ( literal[string] , identifier[len] ( identifier[new_toi] )) identifier[peripherals] . identifier[toi] . identifier[set_tiles_of_interest] ( identifier[new_toi] ) identifier[emit_toi_stats] ( identifier[new_toi] , identifier[peripherals] ) identifier[logger] . identifier[info] ( literal[string] , identifier[len] ( identifier[new_toi] )) identifier[logger] . identifier[info] ( literal[string] )
def tilequeue_load_tiles_of_interest(cfg, peripherals): """ Given a newline-delimited file containing tile coordinates in `zoom/column/row` format, load those tiles into the tiles of interest. """ logger = make_logger(cfg, 'load_tiles_of_interest') toi_filename = 'toi.txt' logger.info('Loading tiles of interest from %s ... ', toi_filename) with open(toi_filename, 'r') as f: new_toi = load_set_from_fp(f) # depends on [control=['with'], data=['f']] logger.info('Loading tiles of interest from %s ... done', toi_filename) logger.info('Setting new TOI (with %s tiles) ... ', len(new_toi)) peripherals.toi.set_tiles_of_interest(new_toi) emit_toi_stats(new_toi, peripherals) logger.info('Setting new TOI (with %s tiles) ... done', len(new_toi)) logger.info('Loading tiles of interest ... done')
def add_env(parser): """Add an `env` flag to the _parser_.""" parser.add_argument( '-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV')
def function[add_env, parameter[parser]]: constant[Add an `env` flag to the _parser_.] call[name[parser].add_argument, parameter[constant[-e], constant[--env]]]
keyword[def] identifier[add_env] ( identifier[parser] ): literal[string] identifier[parser] . identifier[add_argument] ( literal[string] , literal[string] , identifier[choices] = identifier[ENVS] , identifier[default] = identifier[os] . identifier[getenv] ( literal[string] , identifier[default] = literal[string] ), identifier[help] = literal[string] )
def add_env(parser): """Add an `env` flag to the _parser_.""" parser.add_argument('-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV')
def initdict2(self, dictfile): """initdict2""" dt = {} dtls = [] adict = dictfile for element in adict: dt[element[0].upper()] = [] # dict keys for objects always in caps dtls.append(element[0].upper()) return dt, dtls
def function[initdict2, parameter[self, dictfile]]: constant[initdict2] variable[dt] assign[=] dictionary[[], []] variable[dtls] assign[=] list[[]] variable[adict] assign[=] name[dictfile] for taget[name[element]] in starred[name[adict]] begin[:] call[name[dt]][call[call[name[element]][constant[0]].upper, parameter[]]] assign[=] list[[]] call[name[dtls].append, parameter[call[call[name[element]][constant[0]].upper, parameter[]]]] return[tuple[[<ast.Name object at 0x7da2041d8eb0>, <ast.Name object at 0x7da2041da980>]]]
keyword[def] identifier[initdict2] ( identifier[self] , identifier[dictfile] ): literal[string] identifier[dt] ={} identifier[dtls] =[] identifier[adict] = identifier[dictfile] keyword[for] identifier[element] keyword[in] identifier[adict] : identifier[dt] [ identifier[element] [ literal[int] ]. identifier[upper] ()]=[] identifier[dtls] . identifier[append] ( identifier[element] [ literal[int] ]. identifier[upper] ()) keyword[return] identifier[dt] , identifier[dtls]
def initdict2(self, dictfile): """initdict2""" dt = {} dtls = [] adict = dictfile for element in adict: dt[element[0].upper()] = [] # dict keys for objects always in caps dtls.append(element[0].upper()) # depends on [control=['for'], data=['element']] return (dt, dtls)
def is_bridge(self): """bool: Is this zone a bridge?""" # Since this does not change over time (?) check whether we already # know the answer. If so, there is no need to go further if self._is_bridge is not None: return self._is_bridge # if not, we have to get it from the zone topology. This will set # self._is_bridge for us for next time, so we won't have to do this # again self._parse_zone_group_state() return self._is_bridge
def function[is_bridge, parameter[self]]: constant[bool: Is this zone a bridge?] if compare[name[self]._is_bridge is_not constant[None]] begin[:] return[name[self]._is_bridge] call[name[self]._parse_zone_group_state, parameter[]] return[name[self]._is_bridge]
keyword[def] identifier[is_bridge] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_is_bridge] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[self] . identifier[_is_bridge] identifier[self] . identifier[_parse_zone_group_state] () keyword[return] identifier[self] . identifier[_is_bridge]
def is_bridge(self): """bool: Is this zone a bridge?""" # Since this does not change over time (?) check whether we already # know the answer. If so, there is no need to go further if self._is_bridge is not None: return self._is_bridge # depends on [control=['if'], data=[]] # if not, we have to get it from the zone topology. This will set # self._is_bridge for us for next time, so we won't have to do this # again self._parse_zone_group_state() return self._is_bridge
def bind(cls, ns, location=None): """ Bind a namespace to a schema location (URI). This is used for imports that don't specify a schemaLocation. @param ns: A namespace-uri. @type ns: str @param location: The (optional) schema location for the namespace. (default=ns). @type location: str """ if location is None: location = ns cls.locations[ns] = location
def function[bind, parameter[cls, ns, location]]: constant[ Bind a namespace to a schema location (URI). This is used for imports that don't specify a schemaLocation. @param ns: A namespace-uri. @type ns: str @param location: The (optional) schema location for the namespace. (default=ns). @type location: str ] if compare[name[location] is constant[None]] begin[:] variable[location] assign[=] name[ns] call[name[cls].locations][name[ns]] assign[=] name[location]
keyword[def] identifier[bind] ( identifier[cls] , identifier[ns] , identifier[location] = keyword[None] ): literal[string] keyword[if] identifier[location] keyword[is] keyword[None] : identifier[location] = identifier[ns] identifier[cls] . identifier[locations] [ identifier[ns] ]= identifier[location]
def bind(cls, ns, location=None): """ Bind a namespace to a schema location (URI). This is used for imports that don't specify a schemaLocation. @param ns: A namespace-uri. @type ns: str @param location: The (optional) schema location for the namespace. (default=ns). @type location: str """ if location is None: location = ns # depends on [control=['if'], data=['location']] cls.locations[ns] = location
def add_trial(self, trial): """Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue. """ trial.set_verbose(self._verbose) self._trials.append(trial) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial) self.trial_executor.try_checkpoint_metadata(trial)
def function[add_trial, parameter[self, trial]]: constant[Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue. ] call[name[trial].set_verbose, parameter[name[self]._verbose]] call[name[self]._trials.append, parameter[name[trial]]] with call[name[warn_if_slow], parameter[constant[scheduler.on_trial_add]]] begin[:] call[name[self]._scheduler_alg.on_trial_add, parameter[name[self], name[trial]]] call[name[self].trial_executor.try_checkpoint_metadata, parameter[name[trial]]]
keyword[def] identifier[add_trial] ( identifier[self] , identifier[trial] ): literal[string] identifier[trial] . identifier[set_verbose] ( identifier[self] . identifier[_verbose] ) identifier[self] . identifier[_trials] . identifier[append] ( identifier[trial] ) keyword[with] identifier[warn_if_slow] ( literal[string] ): identifier[self] . identifier[_scheduler_alg] . identifier[on_trial_add] ( identifier[self] , identifier[trial] ) identifier[self] . identifier[trial_executor] . identifier[try_checkpoint_metadata] ( identifier[trial] )
def add_trial(self, trial): """Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue. """ trial.set_verbose(self._verbose) self._trials.append(trial) with warn_if_slow('scheduler.on_trial_add'): self._scheduler_alg.on_trial_add(self, trial) # depends on [control=['with'], data=[]] self.trial_executor.try_checkpoint_metadata(trial)
def infer_location( self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ): """In-place location inferring of segments Returns: This track """ self.segments = [ segment.infer_location( location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ) for segment in self.segments ] return self
def function[infer_location, parameter[self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit]]: constant[In-place location inferring of segments Returns: This track ] name[self].segments assign[=] <ast.ListComp object at 0x7da1b0539e40> return[name[self]]
keyword[def] identifier[infer_location] ( identifier[self] , identifier[location_query] , identifier[max_distance] , identifier[google_key] , identifier[foursquare_client_id] , identifier[foursquare_client_secret] , identifier[limit] ): literal[string] identifier[self] . identifier[segments] =[ identifier[segment] . identifier[infer_location] ( identifier[location_query] , identifier[max_distance] , identifier[google_key] , identifier[foursquare_client_id] , identifier[foursquare_client_secret] , identifier[limit] ) keyword[for] identifier[segment] keyword[in] identifier[self] . identifier[segments] ] keyword[return] identifier[self]
def infer_location(self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit): """In-place location inferring of segments Returns: This track """ self.segments = [segment.infer_location(location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit) for segment in self.segments] return self
def fromxml(node): """Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = ElementTree.parse(StringIO(node)).getroot() if node.tag in globals(): id = '' paramflag = '' name = '' description = '' kwargs = {} error = None for attrib, value in node.attrib.items(): if attrib == 'id': id = value elif attrib == 'paramflag': paramflag = value elif attrib == 'name': name = value elif attrib == 'description': description = value elif attrib == 'error': error = value else: kwargs[attrib] = value #extra parsing for choice parameter (TODO: put in a better spot) if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'): kwargs['value'] = [] for subtag in node: #parse possible subtags if subtag.tag == 'choice': #extra parsing for choice parameter (TODO: put in a better spot) if 'choices' not in kwargs: kwargs['choices'] = {} kwargs['choices'][subtag.attrib['id']] = subtag.text if 'selected' in subtag.attrib and (subtag.attrib['selected'] == '1' or subtag.attrib['selected'] == 'yes'): if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'): kwargs['value'].append(subtag.attrib['id']) else: kwargs['value'] = subtag.attrib['id'] parameter = globals()[node.tag](id, name, description, **kwargs) #return parameter instance if error: parameter.error = error #prevent error from getting reset return parameter else: raise Exception("No such parameter exists: " + node.tag)
def function[fromxml, parameter[node]]: constant[Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element] if <ast.UnaryOp object at 0x7da20e9b1d20> begin[:] variable[node] assign[=] call[call[name[ElementTree].parse, parameter[call[name[StringIO], parameter[name[node]]]]].getroot, parameter[]] if compare[name[node].tag in call[name[globals], parameter[]]] begin[:] variable[id] assign[=] constant[] variable[paramflag] assign[=] constant[] variable[name] assign[=] constant[] variable[description] assign[=] constant[] variable[kwargs] assign[=] dictionary[[], []] variable[error] assign[=] constant[None] for taget[tuple[[<ast.Name object at 0x7da20e9b1180>, <ast.Name object at 0x7da20e9b3f70>]]] in starred[call[name[node].attrib.items, parameter[]]] begin[:] if compare[name[attrib] equal[==] constant[id]] begin[:] variable[id] assign[=] name[value] if <ast.BoolOp object at 0x7da20e9b2080> begin[:] call[name[kwargs]][constant[value]] assign[=] list[[]] for taget[name[subtag]] in starred[name[node]] begin[:] if compare[name[subtag].tag equal[==] constant[choice]] begin[:] if compare[constant[choices] <ast.NotIn object at 0x7da2590d7190> name[kwargs]] begin[:] call[name[kwargs]][constant[choices]] assign[=] dictionary[[], []] call[call[name[kwargs]][constant[choices]]][call[name[subtag].attrib][constant[id]]] assign[=] name[subtag].text if <ast.BoolOp object at 0x7da20e9b1c60> begin[:] if <ast.BoolOp object at 0x7da20c6c7520> begin[:] call[call[name[kwargs]][constant[value]].append, parameter[call[name[subtag].attrib][constant[id]]]] variable[parameter] assign[=] call[call[call[name[globals], parameter[]]][name[node].tag], parameter[name[id], name[name], name[description]]] if name[error] begin[:] name[parameter].error assign[=] name[error] return[name[parameter]]
keyword[def] identifier[fromxml] ( identifier[node] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[node] , identifier[ElementTree] . identifier[_Element] ): identifier[node] = identifier[ElementTree] . identifier[parse] ( identifier[StringIO] ( identifier[node] )). identifier[getroot] () keyword[if] identifier[node] . identifier[tag] keyword[in] identifier[globals] (): identifier[id] = literal[string] identifier[paramflag] = literal[string] identifier[name] = literal[string] identifier[description] = literal[string] identifier[kwargs] ={} identifier[error] = keyword[None] keyword[for] identifier[attrib] , identifier[value] keyword[in] identifier[node] . identifier[attrib] . identifier[items] (): keyword[if] identifier[attrib] == literal[string] : identifier[id] = identifier[value] keyword[elif] identifier[attrib] == literal[string] : identifier[paramflag] = identifier[value] keyword[elif] identifier[attrib] == literal[string] : identifier[name] = identifier[value] keyword[elif] identifier[attrib] == literal[string] : identifier[description] = identifier[value] keyword[elif] identifier[attrib] == literal[string] : identifier[error] = identifier[value] keyword[else] : identifier[kwargs] [ identifier[attrib] ]= identifier[value] keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[and] ( identifier[kwargs] [ literal[string] ]== literal[string] keyword[or] identifier[kwargs] [ literal[string] ]== literal[string] keyword[or] identifier[kwargs] [ literal[string] ]== literal[string] ): identifier[kwargs] [ literal[string] ]=[] keyword[for] identifier[subtag] keyword[in] identifier[node] : keyword[if] identifier[subtag] . identifier[tag] == literal[string] : keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] : identifier[kwargs] [ literal[string] ]={} identifier[kwargs] [ literal[string] ][ identifier[subtag] . identifier[attrib] [ literal[string] ]]= identifier[subtag] . identifier[text] keyword[if] literal[string] keyword[in] identifier[subtag] . identifier[attrib] keyword[and] ( identifier[subtag] . identifier[attrib] [ literal[string] ]== literal[string] keyword[or] identifier[subtag] . identifier[attrib] [ literal[string] ]== literal[string] ): keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[and] ( identifier[kwargs] [ literal[string] ]== literal[string] keyword[or] identifier[kwargs] [ literal[string] ]== literal[string] keyword[or] identifier[kwargs] [ literal[string] ]== literal[string] ): identifier[kwargs] [ literal[string] ]. identifier[append] ( identifier[subtag] . identifier[attrib] [ literal[string] ]) keyword[else] : identifier[kwargs] [ literal[string] ]= identifier[subtag] . identifier[attrib] [ literal[string] ] identifier[parameter] = identifier[globals] ()[ identifier[node] . identifier[tag] ]( identifier[id] , identifier[name] , identifier[description] ,** identifier[kwargs] ) keyword[if] identifier[error] : identifier[parameter] . identifier[error] = identifier[error] keyword[return] identifier[parameter] keyword[else] : keyword[raise] identifier[Exception] ( literal[string] + identifier[node] . identifier[tag] )
def fromxml(node): """Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element""" if not isinstance(node, ElementTree._Element): #pylint: disable=protected-access node = ElementTree.parse(StringIO(node)).getroot() # depends on [control=['if'], data=[]] if node.tag in globals(): id = '' paramflag = '' name = '' description = '' kwargs = {} error = None for (attrib, value) in node.attrib.items(): if attrib == 'id': id = value # depends on [control=['if'], data=[]] elif attrib == 'paramflag': paramflag = value # depends on [control=['if'], data=[]] elif attrib == 'name': name = value # depends on [control=['if'], data=[]] elif attrib == 'description': description = value # depends on [control=['if'], data=[]] elif attrib == 'error': error = value # depends on [control=['if'], data=[]] else: kwargs[attrib] = value # depends on [control=['for'], data=[]] #extra parsing for choice parameter (TODO: put in a better spot) if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'): kwargs['value'] = [] # depends on [control=['if'], data=[]] for subtag in node: #parse possible subtags if subtag.tag == 'choice': #extra parsing for choice parameter (TODO: put in a better spot) if 'choices' not in kwargs: kwargs['choices'] = {} # depends on [control=['if'], data=['kwargs']] kwargs['choices'][subtag.attrib['id']] = subtag.text if 'selected' in subtag.attrib and (subtag.attrib['selected'] == '1' or subtag.attrib['selected'] == 'yes'): if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'): kwargs['value'].append(subtag.attrib['id']) # depends on [control=['if'], data=[]] else: kwargs['value'] = subtag.attrib['id'] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['subtag']] parameter = globals()[node.tag](id, name, description, **kwargs) #return parameter instance if error: parameter.error = error #prevent error from getting reset # depends on [control=['if'], data=[]] return parameter # depends on [control=['if'], data=[]] else: raise Exception('No such parameter exists: ' + node.tag)
def getPriorities(self, projectarea_id=None, projectarea_name=None): """Get all :class:`rtcclient.models.Priority` objects by project area id or name At least either of `projectarea_id` and `projectarea_name` is given. If no :class:`rtcclient.models.Priority` is retrieved, `None` is returned. :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea` id :param projectarea_name: the project area name :return: a :class:`list` contains all the :class:`rtcclient.models.Priority` objects :rtype: list """ return self._getPriorities(projectarea_id=projectarea_id, projectarea_name=projectarea_name)
def function[getPriorities, parameter[self, projectarea_id, projectarea_name]]: constant[Get all :class:`rtcclient.models.Priority` objects by project area id or name At least either of `projectarea_id` and `projectarea_name` is given. If no :class:`rtcclient.models.Priority` is retrieved, `None` is returned. :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea` id :param projectarea_name: the project area name :return: a :class:`list` contains all the :class:`rtcclient.models.Priority` objects :rtype: list ] return[call[name[self]._getPriorities, parameter[]]]
keyword[def] identifier[getPriorities] ( identifier[self] , identifier[projectarea_id] = keyword[None] , identifier[projectarea_name] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[_getPriorities] ( identifier[projectarea_id] = identifier[projectarea_id] , identifier[projectarea_name] = identifier[projectarea_name] )
def getPriorities(self, projectarea_id=None, projectarea_name=None): """Get all :class:`rtcclient.models.Priority` objects by project area id or name At least either of `projectarea_id` and `projectarea_name` is given. If no :class:`rtcclient.models.Priority` is retrieved, `None` is returned. :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea` id :param projectarea_name: the project area name :return: a :class:`list` contains all the :class:`rtcclient.models.Priority` objects :rtype: list """ return self._getPriorities(projectarea_id=projectarea_id, projectarea_name=projectarea_name)
def created(self): """Return creation date :rtype: datetime :raises ResourceNotFound: resource not found on the API """ if 'id_perms' not in self: self.fetch() created = self['id_perms']['created'] return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.%f')
def function[created, parameter[self]]: constant[Return creation date :rtype: datetime :raises ResourceNotFound: resource not found on the API ] if compare[constant[id_perms] <ast.NotIn object at 0x7da2590d7190> name[self]] begin[:] call[name[self].fetch, parameter[]] variable[created] assign[=] call[call[name[self]][constant[id_perms]]][constant[created]] return[call[name[datetime].strptime, parameter[name[created], constant[%Y-%m-%dT%H:%M:%S.%f]]]]
keyword[def] identifier[created] ( identifier[self] ): literal[string] keyword[if] literal[string] keyword[not] keyword[in] identifier[self] : identifier[self] . identifier[fetch] () identifier[created] = identifier[self] [ literal[string] ][ literal[string] ] keyword[return] identifier[datetime] . identifier[strptime] ( identifier[created] , literal[string] )
def created(self): """Return creation date :rtype: datetime :raises ResourceNotFound: resource not found on the API """ if 'id_perms' not in self: self.fetch() # depends on [control=['if'], data=['self']] created = self['id_perms']['created'] return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.%f')
def _first(self, **spec): """ Get the earliest entry in this category, optionally including subcategories """ for record in self._entries(spec).order_by(model.Entry.local_date, model.Entry.id)[:1]: return entry.Entry(record) return None
def function[_first, parameter[self]]: constant[ Get the earliest entry in this category, optionally including subcategories ] for taget[name[record]] in starred[call[call[call[name[self]._entries, parameter[name[spec]]].order_by, parameter[name[model].Entry.local_date, name[model].Entry.id]]][<ast.Slice object at 0x7da1b2345d20>]] begin[:] return[call[name[entry].Entry, parameter[name[record]]]] return[constant[None]]
keyword[def] identifier[_first] ( identifier[self] ,** identifier[spec] ): literal[string] keyword[for] identifier[record] keyword[in] identifier[self] . identifier[_entries] ( identifier[spec] ). identifier[order_by] ( identifier[model] . identifier[Entry] . identifier[local_date] , identifier[model] . identifier[Entry] . identifier[id] )[: literal[int] ]: keyword[return] identifier[entry] . identifier[Entry] ( identifier[record] ) keyword[return] keyword[None]
def _first(self, **spec): """ Get the earliest entry in this category, optionally including subcategories """ for record in self._entries(spec).order_by(model.Entry.local_date, model.Entry.id)[:1]: return entry.Entry(record) # depends on [control=['for'], data=['record']] return None
def _platform_name(): """ Returns information about the current operating system and version :return: A unicode string containing the OS name and version """ if sys.platform == 'darwin': version = _plat.mac_ver()[0] _plat_ver_info = tuple(map(int, version.split('.'))) if _plat_ver_info < (10, 12): name = 'OS X' else: name = 'macOS' return '%s %s' % (name, version) elif sys.platform == 'win32': _win_ver = sys.getwindowsversion() _plat_ver_info = (_win_ver[0], _win_ver[1]) return 'Windows %s' % _plat.win32_ver()[0] elif sys.platform in ['linux', 'linux2']: if os.path.exists('/etc/os-release'): with open('/etc/os-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'NAME' in pairs and 'VERSION_ID' in pairs: return '%s %s' % (pairs['NAME'], pairs['VERSION_ID']) version = pairs['VERSION_ID'] elif 'PRETTY_NAME' in pairs: return pairs['PRETTY_NAME'] elif 'NAME' in pairs: return pairs['NAME'] else: raise ValueError('No suitable version info found in /etc/os-release') elif os.path.exists('/etc/lsb-release'): with open('/etc/lsb-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'DISTRIB_DESCRIPTION' in pairs: return pairs['DISTRIB_DESCRIPTION'] else: raise ValueError('No suitable version info found in /etc/lsb-release') else: return 'Linux' else: return '%s %s' % (_plat.system(), _plat.release())
def function[_platform_name, parameter[]]: constant[ Returns information about the current operating system and version :return: A unicode string containing the OS name and version ] if compare[name[sys].platform equal[==] constant[darwin]] begin[:] variable[version] assign[=] call[call[name[_plat].mac_ver, parameter[]]][constant[0]] variable[_plat_ver_info] assign[=] call[name[tuple], parameter[call[name[map], parameter[name[int], call[name[version].split, parameter[constant[.]]]]]]] if compare[name[_plat_ver_info] less[<] tuple[[<ast.Constant object at 0x7da20cabea40>, <ast.Constant object at 0x7da20cabff70>]]] begin[:] variable[name] assign[=] constant[OS X] return[binary_operation[constant[%s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da20cabe2c0>, <ast.Name object at 0x7da20cabef50>]]]]
keyword[def] identifier[_platform_name] (): literal[string] keyword[if] identifier[sys] . identifier[platform] == literal[string] : identifier[version] = identifier[_plat] . identifier[mac_ver] ()[ literal[int] ] identifier[_plat_ver_info] = identifier[tuple] ( identifier[map] ( identifier[int] , identifier[version] . identifier[split] ( literal[string] ))) keyword[if] identifier[_plat_ver_info] <( literal[int] , literal[int] ): identifier[name] = literal[string] keyword[else] : identifier[name] = literal[string] keyword[return] literal[string] %( identifier[name] , identifier[version] ) keyword[elif] identifier[sys] . identifier[platform] == literal[string] : identifier[_win_ver] = identifier[sys] . identifier[getwindowsversion] () identifier[_plat_ver_info] =( identifier[_win_ver] [ literal[int] ], identifier[_win_ver] [ literal[int] ]) keyword[return] literal[string] % identifier[_plat] . identifier[win32_ver] ()[ literal[int] ] keyword[elif] identifier[sys] . identifier[platform] keyword[in] [ literal[string] , literal[string] ]: keyword[if] identifier[os] . identifier[path] . identifier[exists] ( literal[string] ): keyword[with] identifier[open] ( literal[string] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[f] : identifier[pairs] = identifier[_parse_env_var_file] ( identifier[f] . identifier[read] ()) keyword[if] literal[string] keyword[in] identifier[pairs] keyword[and] literal[string] keyword[in] identifier[pairs] : keyword[return] literal[string] %( identifier[pairs] [ literal[string] ], identifier[pairs] [ literal[string] ]) identifier[version] = identifier[pairs] [ literal[string] ] keyword[elif] literal[string] keyword[in] identifier[pairs] : keyword[return] identifier[pairs] [ literal[string] ] keyword[elif] literal[string] keyword[in] identifier[pairs] : keyword[return] identifier[pairs] [ literal[string] ] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[elif] identifier[os] . identifier[path] . identifier[exists] ( literal[string] ): keyword[with] identifier[open] ( literal[string] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[f] : identifier[pairs] = identifier[_parse_env_var_file] ( identifier[f] . identifier[read] ()) keyword[if] literal[string] keyword[in] identifier[pairs] : keyword[return] identifier[pairs] [ literal[string] ] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[else] : keyword[return] literal[string] keyword[else] : keyword[return] literal[string] %( identifier[_plat] . identifier[system] (), identifier[_plat] . identifier[release] ())
def _platform_name(): """ Returns information about the current operating system and version :return: A unicode string containing the OS name and version """ if sys.platform == 'darwin': version = _plat.mac_ver()[0] _plat_ver_info = tuple(map(int, version.split('.'))) if _plat_ver_info < (10, 12): name = 'OS X' # depends on [control=['if'], data=[]] else: name = 'macOS' return '%s %s' % (name, version) # depends on [control=['if'], data=[]] elif sys.platform == 'win32': _win_ver = sys.getwindowsversion() _plat_ver_info = (_win_ver[0], _win_ver[1]) return 'Windows %s' % _plat.win32_ver()[0] # depends on [control=['if'], data=[]] elif sys.platform in ['linux', 'linux2']: if os.path.exists('/etc/os-release'): with open('/etc/os-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'NAME' in pairs and 'VERSION_ID' in pairs: return '%s %s' % (pairs['NAME'], pairs['VERSION_ID']) version = pairs['VERSION_ID'] # depends on [control=['if'], data=[]] elif 'PRETTY_NAME' in pairs: return pairs['PRETTY_NAME'] # depends on [control=['if'], data=['pairs']] elif 'NAME' in pairs: return pairs['NAME'] # depends on [control=['if'], data=['pairs']] else: raise ValueError('No suitable version info found in /etc/os-release') # depends on [control=['with'], data=['f']] # depends on [control=['if'], data=[]] elif os.path.exists('/etc/lsb-release'): with open('/etc/lsb-release', 'r', encoding='utf-8') as f: pairs = _parse_env_var_file(f.read()) if 'DISTRIB_DESCRIPTION' in pairs: return pairs['DISTRIB_DESCRIPTION'] # depends on [control=['if'], data=['pairs']] else: raise ValueError('No suitable version info found in /etc/lsb-release') # depends on [control=['with'], data=['f']] # depends on [control=['if'], data=[]] else: return 'Linux' # depends on [control=['if'], data=[]] else: return '%s %s' % (_plat.system(), _plat.release())
def generate_password(): """Returns a 23 character random string, with 3 special characters at the end""" if sys.version_info > (3, 6): import secrets # pylint: disable=import-error alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(20)) special = ''.join(secrets.choice(string.punctuation) for i in range(3)) return password + special else: raise ImportError("Generating passwords require python 3.6 or higher")
def function[generate_password, parameter[]]: constant[Returns a 23 character random string, with 3 special characters at the end] if compare[name[sys].version_info greater[>] tuple[[<ast.Constant object at 0x7da204621510>, <ast.Constant object at 0x7da204620e50>]]] begin[:] import module[secrets] variable[alphabet] assign[=] binary_operation[name[string].ascii_letters + name[string].digits] variable[password] assign[=] call[constant[].join, parameter[<ast.GeneratorExp object at 0x7da204621e40>]] variable[special] assign[=] call[constant[].join, parameter[<ast.GeneratorExp object at 0x7da204622170>]] return[binary_operation[name[password] + name[special]]]
keyword[def] identifier[generate_password] (): literal[string] keyword[if] identifier[sys] . identifier[version_info] >( literal[int] , literal[int] ): keyword[import] identifier[secrets] identifier[alphabet] = identifier[string] . identifier[ascii_letters] + identifier[string] . identifier[digits] identifier[password] = literal[string] . identifier[join] ( identifier[secrets] . identifier[choice] ( identifier[alphabet] ) keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] )) identifier[special] = literal[string] . identifier[join] ( identifier[secrets] . identifier[choice] ( identifier[string] . identifier[punctuation] ) keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] )) keyword[return] identifier[password] + identifier[special] keyword[else] : keyword[raise] identifier[ImportError] ( literal[string] )
def generate_password(): """Returns a 23 character random string, with 3 special characters at the end""" if sys.version_info > (3, 6): import secrets # pylint: disable=import-error alphabet = string.ascii_letters + string.digits password = ''.join((secrets.choice(alphabet) for i in range(20))) special = ''.join((secrets.choice(string.punctuation) for i in range(3))) return password + special # depends on [control=['if'], data=[]] else: raise ImportError('Generating passwords require python 3.6 or higher')
def _parseBoundImportDirectory(self, rva, size, magic = consts.PE32): """ Parses the bound import directory. @type rva: int @param rva: The RVA where the bound import directory starts. @type size: int @param size: The size of the bound import directory. @type magic: int @param magic: (Optional) The type of PE. This value could be L{consts.PE32} or L{consts.PE64}. @rtype: L{ImageBoundImportDescriptor} @return: A new L{ImageBoundImportDescriptor} object. """ data = self.getDataAtRva(rva, size) rd = utils.ReadData(data) boundImportDirectory = directories.ImageBoundImportDescriptor.parse(rd) # parse the name of every bounded import. for i in range(len(boundImportDirectory) - 1): if hasattr(boundImportDirectory[i], "forwarderRefsList"): if boundImportDirectory[i].forwarderRefsList: for forwarderRefEntry in boundImportDirectory[i].forwarderRefsList: offset = forwarderRefEntry.offsetModuleName.value forwarderRefEntry.moduleName = self.readStringAtRva(offset + rva) offset = boundImportDirectory[i].offsetModuleName.value boundImportDirectory[i].moduleName = self.readStringAtRva(offset + rva) return boundImportDirectory
def function[_parseBoundImportDirectory, parameter[self, rva, size, magic]]: constant[ Parses the bound import directory. @type rva: int @param rva: The RVA where the bound import directory starts. @type size: int @param size: The size of the bound import directory. @type magic: int @param magic: (Optional) The type of PE. This value could be L{consts.PE32} or L{consts.PE64}. @rtype: L{ImageBoundImportDescriptor} @return: A new L{ImageBoundImportDescriptor} object. ] variable[data] assign[=] call[name[self].getDataAtRva, parameter[name[rva], name[size]]] variable[rd] assign[=] call[name[utils].ReadData, parameter[name[data]]] variable[boundImportDirectory] assign[=] call[name[directories].ImageBoundImportDescriptor.parse, parameter[name[rd]]] for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[boundImportDirectory]]] - constant[1]]]]] begin[:] if call[name[hasattr], parameter[call[name[boundImportDirectory]][name[i]], constant[forwarderRefsList]]] begin[:] if call[name[boundImportDirectory]][name[i]].forwarderRefsList begin[:] for taget[name[forwarderRefEntry]] in starred[call[name[boundImportDirectory]][name[i]].forwarderRefsList] begin[:] variable[offset] assign[=] name[forwarderRefEntry].offsetModuleName.value name[forwarderRefEntry].moduleName assign[=] call[name[self].readStringAtRva, parameter[binary_operation[name[offset] + name[rva]]]] variable[offset] assign[=] call[name[boundImportDirectory]][name[i]].offsetModuleName.value call[name[boundImportDirectory]][name[i]].moduleName assign[=] call[name[self].readStringAtRva, parameter[binary_operation[name[offset] + name[rva]]]] return[name[boundImportDirectory]]
keyword[def] identifier[_parseBoundImportDirectory] ( identifier[self] , identifier[rva] , identifier[size] , identifier[magic] = identifier[consts] . identifier[PE32] ): literal[string] identifier[data] = identifier[self] . identifier[getDataAtRva] ( identifier[rva] , identifier[size] ) identifier[rd] = identifier[utils] . identifier[ReadData] ( identifier[data] ) identifier[boundImportDirectory] = identifier[directories] . identifier[ImageBoundImportDescriptor] . identifier[parse] ( identifier[rd] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[boundImportDirectory] )- literal[int] ): keyword[if] identifier[hasattr] ( identifier[boundImportDirectory] [ identifier[i] ], literal[string] ): keyword[if] identifier[boundImportDirectory] [ identifier[i] ]. identifier[forwarderRefsList] : keyword[for] identifier[forwarderRefEntry] keyword[in] identifier[boundImportDirectory] [ identifier[i] ]. identifier[forwarderRefsList] : identifier[offset] = identifier[forwarderRefEntry] . identifier[offsetModuleName] . identifier[value] identifier[forwarderRefEntry] . identifier[moduleName] = identifier[self] . identifier[readStringAtRva] ( identifier[offset] + identifier[rva] ) identifier[offset] = identifier[boundImportDirectory] [ identifier[i] ]. identifier[offsetModuleName] . identifier[value] identifier[boundImportDirectory] [ identifier[i] ]. identifier[moduleName] = identifier[self] . identifier[readStringAtRva] ( identifier[offset] + identifier[rva] ) keyword[return] identifier[boundImportDirectory]
def _parseBoundImportDirectory(self, rva, size, magic=consts.PE32): """ Parses the bound import directory. @type rva: int @param rva: The RVA where the bound import directory starts. @type size: int @param size: The size of the bound import directory. @type magic: int @param magic: (Optional) The type of PE. This value could be L{consts.PE32} or L{consts.PE64}. @rtype: L{ImageBoundImportDescriptor} @return: A new L{ImageBoundImportDescriptor} object. """ data = self.getDataAtRva(rva, size) rd = utils.ReadData(data) boundImportDirectory = directories.ImageBoundImportDescriptor.parse(rd) # parse the name of every bounded import. for i in range(len(boundImportDirectory) - 1): if hasattr(boundImportDirectory[i], 'forwarderRefsList'): if boundImportDirectory[i].forwarderRefsList: for forwarderRefEntry in boundImportDirectory[i].forwarderRefsList: offset = forwarderRefEntry.offsetModuleName.value forwarderRefEntry.moduleName = self.readStringAtRva(offset + rva) # depends on [control=['for'], data=['forwarderRefEntry']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] offset = boundImportDirectory[i].offsetModuleName.value boundImportDirectory[i].moduleName = self.readStringAtRva(offset + rva) # depends on [control=['for'], data=['i']] return boundImportDirectory
def preferred_jvm_distribution(cls, platforms, strict=False): """Returns a jvm Distribution with a version that should work for all the platforms. Any one of those distributions whose version is >= all requested platforms' versions can be returned unless strict flag is set. :param iterable platforms: An iterable of platform settings. :param bool strict: If true, only distribution whose version matches the minimum required version can be returned, i.e, the max target_level of all the requested platforms. :returns: Distribution one of the selected distributions. """ if not platforms: return DistributionLocator.cached() min_version = max(platform.target_level for platform in platforms) max_version = Revision(*(min_version.components + [9999])) if strict else None return DistributionLocator.cached(minimum_version=min_version, maximum_version=max_version)
def function[preferred_jvm_distribution, parameter[cls, platforms, strict]]: constant[Returns a jvm Distribution with a version that should work for all the platforms. Any one of those distributions whose version is >= all requested platforms' versions can be returned unless strict flag is set. :param iterable platforms: An iterable of platform settings. :param bool strict: If true, only distribution whose version matches the minimum required version can be returned, i.e, the max target_level of all the requested platforms. :returns: Distribution one of the selected distributions. ] if <ast.UnaryOp object at 0x7da1b1e6a710> begin[:] return[call[name[DistributionLocator].cached, parameter[]]] variable[min_version] assign[=] call[name[max], parameter[<ast.GeneratorExp object at 0x7da1b1e6bca0>]] variable[max_version] assign[=] <ast.IfExp object at 0x7da1b1e687c0> return[call[name[DistributionLocator].cached, parameter[]]]
keyword[def] identifier[preferred_jvm_distribution] ( identifier[cls] , identifier[platforms] , identifier[strict] = keyword[False] ): literal[string] keyword[if] keyword[not] identifier[platforms] : keyword[return] identifier[DistributionLocator] . identifier[cached] () identifier[min_version] = identifier[max] ( identifier[platform] . identifier[target_level] keyword[for] identifier[platform] keyword[in] identifier[platforms] ) identifier[max_version] = identifier[Revision] (*( identifier[min_version] . identifier[components] +[ literal[int] ])) keyword[if] identifier[strict] keyword[else] keyword[None] keyword[return] identifier[DistributionLocator] . identifier[cached] ( identifier[minimum_version] = identifier[min_version] , identifier[maximum_version] = identifier[max_version] )
def preferred_jvm_distribution(cls, platforms, strict=False): """Returns a jvm Distribution with a version that should work for all the platforms. Any one of those distributions whose version is >= all requested platforms' versions can be returned unless strict flag is set. :param iterable platforms: An iterable of platform settings. :param bool strict: If true, only distribution whose version matches the minimum required version can be returned, i.e, the max target_level of all the requested platforms. :returns: Distribution one of the selected distributions. """ if not platforms: return DistributionLocator.cached() # depends on [control=['if'], data=[]] min_version = max((platform.target_level for platform in platforms)) max_version = Revision(*min_version.components + [9999]) if strict else None return DistributionLocator.cached(minimum_version=min_version, maximum_version=max_version)
def end_episode(self, agent_indices): """Add episodes to the memory and perform update steps if memory is full. During training, add the collected episodes of the batch indices that finished their episode to the memory. If the memory is full, train on it, and then clear the memory. A summary string is returned if requested at this step. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor. """ with tf.name_scope('end_episode/'): return tf.cond( self._is_training, lambda: self._define_end_episode(agent_indices), str)
def function[end_episode, parameter[self, agent_indices]]: constant[Add episodes to the memory and perform update steps if memory is full. During training, add the collected episodes of the batch indices that finished their episode to the memory. If the memory is full, train on it, and then clear the memory. A summary string is returned if requested at this step. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor. ] with call[name[tf].name_scope, parameter[constant[end_episode/]]] begin[:] return[call[name[tf].cond, parameter[name[self]._is_training, <ast.Lambda object at 0x7da18c4cd870>, name[str]]]]
keyword[def] identifier[end_episode] ( identifier[self] , identifier[agent_indices] ): literal[string] keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ): keyword[return] identifier[tf] . identifier[cond] ( identifier[self] . identifier[_is_training] , keyword[lambda] : identifier[self] . identifier[_define_end_episode] ( identifier[agent_indices] ), identifier[str] )
def end_episode(self, agent_indices): """Add episodes to the memory and perform update steps if memory is full. During training, add the collected episodes of the batch indices that finished their episode to the memory. If the memory is full, train on it, and then clear the memory. A summary string is returned if requested at this step. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor. """ with tf.name_scope('end_episode/'): return tf.cond(self._is_training, lambda : self._define_end_episode(agent_indices), str) # depends on [control=['with'], data=[]]
def _distance_squared(self, p2: "Point2") -> Union[int, float]: """ Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """ return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2
def function[_distance_squared, parameter[self, p2]]: constant[ Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. ] return[binary_operation[binary_operation[binary_operation[call[name[self]][constant[0]] - call[name[p2]][constant[0]]] ** constant[2]] + binary_operation[binary_operation[call[name[self]][constant[1]] - call[name[p2]][constant[1]]] ** constant[2]]]]
keyword[def] identifier[_distance_squared] ( identifier[self] , identifier[p2] : literal[string] )-> identifier[Union] [ identifier[int] , identifier[float] ]: literal[string] keyword[return] ( identifier[self] [ literal[int] ]- identifier[p2] [ literal[int] ])** literal[int] +( identifier[self] [ literal[int] ]- identifier[p2] [ literal[int] ])** literal[int]
def _distance_squared(self, p2: 'Point2') -> Union[int, float]: """ Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """ return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2
def set_attribute_xsi_type(self, el, **kw): '''if typed, set the xsi:type attribute Paramters: el -- MessageInterface representing the element ''' if kw.get('typed', self.typed): namespaceURI,typeName = kw.get('type', _get_xsitype(self)) if namespaceURI and typeName: self.logger.debug("attribute: (%s, %s)", namespaceURI, typeName) el.setAttributeType(namespaceURI, typeName)
def function[set_attribute_xsi_type, parameter[self, el]]: constant[if typed, set the xsi:type attribute Paramters: el -- MessageInterface representing the element ] if call[name[kw].get, parameter[constant[typed], name[self].typed]] begin[:] <ast.Tuple object at 0x7da18f00c700> assign[=] call[name[kw].get, parameter[constant[type], call[name[_get_xsitype], parameter[name[self]]]]] if <ast.BoolOp object at 0x7da18f00f280> begin[:] call[name[self].logger.debug, parameter[constant[attribute: (%s, %s)], name[namespaceURI], name[typeName]]] call[name[el].setAttributeType, parameter[name[namespaceURI], name[typeName]]]
keyword[def] identifier[set_attribute_xsi_type] ( identifier[self] , identifier[el] ,** identifier[kw] ): literal[string] keyword[if] identifier[kw] . identifier[get] ( literal[string] , identifier[self] . identifier[typed] ): identifier[namespaceURI] , identifier[typeName] = identifier[kw] . identifier[get] ( literal[string] , identifier[_get_xsitype] ( identifier[self] )) keyword[if] identifier[namespaceURI] keyword[and] identifier[typeName] : identifier[self] . identifier[logger] . identifier[debug] ( literal[string] , identifier[namespaceURI] , identifier[typeName] ) identifier[el] . identifier[setAttributeType] ( identifier[namespaceURI] , identifier[typeName] )
def set_attribute_xsi_type(self, el, **kw): """if typed, set the xsi:type attribute Paramters: el -- MessageInterface representing the element """ if kw.get('typed', self.typed): (namespaceURI, typeName) = kw.get('type', _get_xsitype(self)) if namespaceURI and typeName: self.logger.debug('attribute: (%s, %s)', namespaceURI, typeName) el.setAttributeType(namespaceURI, typeName) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
def _parseRelocsDirectory(self, rva, size, magic = consts.PE32): """ Parses the relocation directory. @type rva: int @param rva: The RVA where the relocation directory starts. @type size: int @param size: The size of the relocation directory. @type magic: int @param magic: (Optional) The type of PE. This value could be L{consts.PE32} or L{consts.PE64}. @rtype: L{ImageBaseRelocation} @return: A new L{ImageBaseRelocation} object. """ data = self.getDataAtRva(rva, size) #print "Length Relocation data: %x" % len(data) rd = utils.ReadData(data) relocsArray = directories.ImageBaseRelocation() while rd.offset < size: relocEntry = directories.ImageBaseRelocationEntry.parse(rd) relocsArray.append(relocEntry) return relocsArray
def function[_parseRelocsDirectory, parameter[self, rva, size, magic]]: constant[ Parses the relocation directory. @type rva: int @param rva: The RVA where the relocation directory starts. @type size: int @param size: The size of the relocation directory. @type magic: int @param magic: (Optional) The type of PE. This value could be L{consts.PE32} or L{consts.PE64}. @rtype: L{ImageBaseRelocation} @return: A new L{ImageBaseRelocation} object. ] variable[data] assign[=] call[name[self].getDataAtRva, parameter[name[rva], name[size]]] variable[rd] assign[=] call[name[utils].ReadData, parameter[name[data]]] variable[relocsArray] assign[=] call[name[directories].ImageBaseRelocation, parameter[]] while compare[name[rd].offset less[<] name[size]] begin[:] variable[relocEntry] assign[=] call[name[directories].ImageBaseRelocationEntry.parse, parameter[name[rd]]] call[name[relocsArray].append, parameter[name[relocEntry]]] return[name[relocsArray]]
keyword[def] identifier[_parseRelocsDirectory] ( identifier[self] , identifier[rva] , identifier[size] , identifier[magic] = identifier[consts] . identifier[PE32] ): literal[string] identifier[data] = identifier[self] . identifier[getDataAtRva] ( identifier[rva] , identifier[size] ) identifier[rd] = identifier[utils] . identifier[ReadData] ( identifier[data] ) identifier[relocsArray] = identifier[directories] . identifier[ImageBaseRelocation] () keyword[while] identifier[rd] . identifier[offset] < identifier[size] : identifier[relocEntry] = identifier[directories] . identifier[ImageBaseRelocationEntry] . identifier[parse] ( identifier[rd] ) identifier[relocsArray] . identifier[append] ( identifier[relocEntry] ) keyword[return] identifier[relocsArray]
def _parseRelocsDirectory(self, rva, size, magic=consts.PE32): """ Parses the relocation directory. @type rva: int @param rva: The RVA where the relocation directory starts. @type size: int @param size: The size of the relocation directory. @type magic: int @param magic: (Optional) The type of PE. This value could be L{consts.PE32} or L{consts.PE64}. @rtype: L{ImageBaseRelocation} @return: A new L{ImageBaseRelocation} object. """ data = self.getDataAtRva(rva, size) #print "Length Relocation data: %x" % len(data) rd = utils.ReadData(data) relocsArray = directories.ImageBaseRelocation() while rd.offset < size: relocEntry = directories.ImageBaseRelocationEntry.parse(rd) relocsArray.append(relocEntry) # depends on [control=['while'], data=[]] return relocsArray
def nextversion(current_version): """Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned. """ norm_ver = verlib.suggest_normalized_version(current_version) if norm_ver is None: return None norm_ver = verlib.NormalizedVersion(norm_ver) # increment last version figure parts = norm_ver.parts # see comments of `verlib.py` to get the idea of `parts` assert(len(parts) == 3) if len(parts[2]) > 1: # postdev if parts[2][-1] == 'f': # when `post` exists but `dev` doesn't parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-2, incval=1) else: # when both `post` and `dev` exist parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-1, incval=1) elif len(parts[1]) > 1: # prerel parts = _mk_incremented_parts(parts, part_idx=1, in_part_idx=-1, incval=1) else: # version & extraversion parts = _mk_incremented_parts(parts, part_idx=0, in_part_idx=-1, incval=1) norm_ver.parts = parts return str(norm_ver)
def function[nextversion, parameter[current_version]]: constant[Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned. ] variable[norm_ver] assign[=] call[name[verlib].suggest_normalized_version, parameter[name[current_version]]] if compare[name[norm_ver] is constant[None]] begin[:] return[constant[None]] variable[norm_ver] assign[=] call[name[verlib].NormalizedVersion, parameter[name[norm_ver]]] variable[parts] assign[=] name[norm_ver].parts assert[compare[call[name[len], parameter[name[parts]]] equal[==] constant[3]]] if compare[call[name[len], parameter[call[name[parts]][constant[2]]]] greater[>] constant[1]] begin[:] if compare[call[call[name[parts]][constant[2]]][<ast.UnaryOp object at 0x7da18f00fd60>] equal[==] constant[f]] begin[:] variable[parts] assign[=] call[name[_mk_incremented_parts], parameter[name[parts]]] name[norm_ver].parts assign[=] name[parts] return[call[name[str], parameter[name[norm_ver]]]]
keyword[def] identifier[nextversion] ( identifier[current_version] ): literal[string] identifier[norm_ver] = identifier[verlib] . identifier[suggest_normalized_version] ( identifier[current_version] ) keyword[if] identifier[norm_ver] keyword[is] keyword[None] : keyword[return] keyword[None] identifier[norm_ver] = identifier[verlib] . identifier[NormalizedVersion] ( identifier[norm_ver] ) identifier[parts] = identifier[norm_ver] . identifier[parts] keyword[assert] ( identifier[len] ( identifier[parts] )== literal[int] ) keyword[if] identifier[len] ( identifier[parts] [ literal[int] ])> literal[int] : keyword[if] identifier[parts] [ literal[int] ][- literal[int] ]== literal[string] : identifier[parts] = identifier[_mk_incremented_parts] ( identifier[parts] , identifier[part_idx] = literal[int] , identifier[in_part_idx] =- literal[int] , identifier[incval] = literal[int] ) keyword[else] : identifier[parts] = identifier[_mk_incremented_parts] ( identifier[parts] , identifier[part_idx] = literal[int] , identifier[in_part_idx] =- literal[int] , identifier[incval] = literal[int] ) keyword[elif] identifier[len] ( identifier[parts] [ literal[int] ])> literal[int] : identifier[parts] = identifier[_mk_incremented_parts] ( identifier[parts] , identifier[part_idx] = literal[int] , identifier[in_part_idx] =- literal[int] , identifier[incval] = literal[int] ) keyword[else] : identifier[parts] = identifier[_mk_incremented_parts] ( identifier[parts] , identifier[part_idx] = literal[int] , identifier[in_part_idx] =- literal[int] , identifier[incval] = literal[int] ) identifier[norm_ver] . identifier[parts] = identifier[parts] keyword[return] identifier[str] ( identifier[norm_ver] )
def nextversion(current_version): """Returns incremented module version number. :param current_version: version string to increment :returns: Next version string (PEP 386 compatible) if possible. If impossible (since `current_version` is too far from PEP 386), `None` is returned. """ norm_ver = verlib.suggest_normalized_version(current_version) if norm_ver is None: return None # depends on [control=['if'], data=[]] norm_ver = verlib.NormalizedVersion(norm_ver) # increment last version figure parts = norm_ver.parts # see comments of `verlib.py` to get the idea of `parts` assert len(parts) == 3 if len(parts[2]) > 1: # postdev if parts[2][-1] == 'f': # when `post` exists but `dev` doesn't parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-2, incval=1) # depends on [control=['if'], data=[]] else: # when both `post` and `dev` exist parts = _mk_incremented_parts(parts, part_idx=2, in_part_idx=-1, incval=1) # depends on [control=['if'], data=[]] elif len(parts[1]) > 1: # prerel parts = _mk_incremented_parts(parts, part_idx=1, in_part_idx=-1, incval=1) # depends on [control=['if'], data=[]] else: # version & extraversion parts = _mk_incremented_parts(parts, part_idx=0, in_part_idx=-1, incval=1) norm_ver.parts = parts return str(norm_ver)
def rational_limit(f, g, t0): """Computes the limit of the rational function (f/g)(t) as t approaches t0.""" assert isinstance(f, np.poly1d) and isinstance(g, np.poly1d) assert g != np.poly1d([0]) if g(t0) != 0: return f(t0)/g(t0) elif f(t0) == 0: return rational_limit(f.deriv(), g.deriv(), t0) else: raise ValueError("Limit does not exist.")
def function[rational_limit, parameter[f, g, t0]]: constant[Computes the limit of the rational function (f/g)(t) as t approaches t0.] assert[<ast.BoolOp object at 0x7da1b2344a00>] assert[compare[name[g] not_equal[!=] call[name[np].poly1d, parameter[list[[<ast.Constant object at 0x7da20cabf190>]]]]]] if compare[call[name[g], parameter[name[t0]]] not_equal[!=] constant[0]] begin[:] return[binary_operation[call[name[f], parameter[name[t0]]] / call[name[g], parameter[name[t0]]]]]
keyword[def] identifier[rational_limit] ( identifier[f] , identifier[g] , identifier[t0] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[f] , identifier[np] . identifier[poly1d] ) keyword[and] identifier[isinstance] ( identifier[g] , identifier[np] . identifier[poly1d] ) keyword[assert] identifier[g] != identifier[np] . identifier[poly1d] ([ literal[int] ]) keyword[if] identifier[g] ( identifier[t0] )!= literal[int] : keyword[return] identifier[f] ( identifier[t0] )/ identifier[g] ( identifier[t0] ) keyword[elif] identifier[f] ( identifier[t0] )== literal[int] : keyword[return] identifier[rational_limit] ( identifier[f] . identifier[deriv] (), identifier[g] . identifier[deriv] (), identifier[t0] ) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] )
def rational_limit(f, g, t0): """Computes the limit of the rational function (f/g)(t) as t approaches t0.""" assert isinstance(f, np.poly1d) and isinstance(g, np.poly1d) assert g != np.poly1d([0]) if g(t0) != 0: return f(t0) / g(t0) # depends on [control=['if'], data=[]] elif f(t0) == 0: return rational_limit(f.deriv(), g.deriv(), t0) # depends on [control=['if'], data=[]] else: raise ValueError('Limit does not exist.')
def render(self, context, instance, placeholder): ''' Add the cart-specific context to this form ''' context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder) context.update({ 'squareApplicationId': getattr(settings,'SQUARE_APPLICATION_ID',''), }) return context
def function[render, parameter[self, context, instance, placeholder]]: constant[ Add the cart-specific context to this form ] variable[context] assign[=] call[call[name[super], parameter[name[SquareCheckoutFormPlugin], name[self]]].render, parameter[name[context], name[instance], name[placeholder]]] call[name[context].update, parameter[dictionary[[<ast.Constant object at 0x7da1b13b4820>], [<ast.Call object at 0x7da1b13b4850>]]]] return[name[context]]
keyword[def] identifier[render] ( identifier[self] , identifier[context] , identifier[instance] , identifier[placeholder] ): literal[string] identifier[context] = identifier[super] ( identifier[SquareCheckoutFormPlugin] , identifier[self] ). identifier[render] ( identifier[context] , identifier[instance] , identifier[placeholder] ) identifier[context] . identifier[update] ({ literal[string] : identifier[getattr] ( identifier[settings] , literal[string] , literal[string] ), }) keyword[return] identifier[context]
def render(self, context, instance, placeholder): """ Add the cart-specific context to this form """ context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder) context.update({'squareApplicationId': getattr(settings, 'SQUARE_APPLICATION_ID', '')}) return context
def fetch_events(cursor, config, account_name): """Generator that returns the events""" query = config['indexer'].get('query', 'select * from events where user_agent glob \'*CloudCustodian*\'') for event in cursor.execute(query): event['account'] = account_name event['_index'] = config['indexer']['idx_name'] event['_type'] = config['indexer'].get('idx_type', 'traildb') yield event
def function[fetch_events, parameter[cursor, config, account_name]]: constant[Generator that returns the events] variable[query] assign[=] call[call[name[config]][constant[indexer]].get, parameter[constant[query], constant[select * from events where user_agent glob '*CloudCustodian*']]] for taget[name[event]] in starred[call[name[cursor].execute, parameter[name[query]]]] begin[:] call[name[event]][constant[account]] assign[=] name[account_name] call[name[event]][constant[_index]] assign[=] call[call[name[config]][constant[indexer]]][constant[idx_name]] call[name[event]][constant[_type]] assign[=] call[call[name[config]][constant[indexer]].get, parameter[constant[idx_type], constant[traildb]]] <ast.Yield object at 0x7da1b1f38490>
keyword[def] identifier[fetch_events] ( identifier[cursor] , identifier[config] , identifier[account_name] ): literal[string] identifier[query] = identifier[config] [ literal[string] ]. identifier[get] ( literal[string] , literal[string] ) keyword[for] identifier[event] keyword[in] identifier[cursor] . identifier[execute] ( identifier[query] ): identifier[event] [ literal[string] ]= identifier[account_name] identifier[event] [ literal[string] ]= identifier[config] [ literal[string] ][ literal[string] ] identifier[event] [ literal[string] ]= identifier[config] [ literal[string] ]. identifier[get] ( literal[string] , literal[string] ) keyword[yield] identifier[event]
def fetch_events(cursor, config, account_name): """Generator that returns the events""" query = config['indexer'].get('query', "select * from events where user_agent glob '*CloudCustodian*'") for event in cursor.execute(query): event['account'] = account_name event['_index'] = config['indexer']['idx_name'] event['_type'] = config['indexer'].get('idx_type', 'traildb') yield event # depends on [control=['for'], data=['event']]
def init_config(self, app): """Initialize configuration.""" for k in dir(config): if k.startswith('JSONSCHEMAS_'): app.config.setdefault(k, getattr(config, k)) host_setting = app.config['JSONSCHEMAS_HOST'] if not host_setting or host_setting == 'localhost': app.logger.warning('JSONSCHEMAS_HOST is set to {0}'.format( host_setting))
def function[init_config, parameter[self, app]]: constant[Initialize configuration.] for taget[name[k]] in starred[call[name[dir], parameter[name[config]]]] begin[:] if call[name[k].startswith, parameter[constant[JSONSCHEMAS_]]] begin[:] call[name[app].config.setdefault, parameter[name[k], call[name[getattr], parameter[name[config], name[k]]]]] variable[host_setting] assign[=] call[name[app].config][constant[JSONSCHEMAS_HOST]] if <ast.BoolOp object at 0x7da20c796740> begin[:] call[name[app].logger.warning, parameter[call[constant[JSONSCHEMAS_HOST is set to {0}].format, parameter[name[host_setting]]]]]
keyword[def] identifier[init_config] ( identifier[self] , identifier[app] ): literal[string] keyword[for] identifier[k] keyword[in] identifier[dir] ( identifier[config] ): keyword[if] identifier[k] . identifier[startswith] ( literal[string] ): identifier[app] . identifier[config] . identifier[setdefault] ( identifier[k] , identifier[getattr] ( identifier[config] , identifier[k] )) identifier[host_setting] = identifier[app] . identifier[config] [ literal[string] ] keyword[if] keyword[not] identifier[host_setting] keyword[or] identifier[host_setting] == literal[string] : identifier[app] . identifier[logger] . identifier[warning] ( literal[string] . identifier[format] ( identifier[host_setting] ))
def init_config(self, app): """Initialize configuration.""" for k in dir(config): if k.startswith('JSONSCHEMAS_'): app.config.setdefault(k, getattr(config, k)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['k']] host_setting = app.config['JSONSCHEMAS_HOST'] if not host_setting or host_setting == 'localhost': app.logger.warning('JSONSCHEMAS_HOST is set to {0}'.format(host_setting)) # depends on [control=['if'], data=[]]
def add_custom_fields(cls, *args, **kw): """ Add any custom fields defined in the configuration. """ for factory in config.custom_field_factories: for field in factory(): setattr(cls, field.name, field)
def function[add_custom_fields, parameter[cls]]: constant[ Add any custom fields defined in the configuration. ] for taget[name[factory]] in starred[name[config].custom_field_factories] begin[:] for taget[name[field]] in starred[call[name[factory], parameter[]]] begin[:] call[name[setattr], parameter[name[cls], name[field].name, name[field]]]
keyword[def] identifier[add_custom_fields] ( identifier[cls] ,* identifier[args] ,** identifier[kw] ): literal[string] keyword[for] identifier[factory] keyword[in] identifier[config] . identifier[custom_field_factories] : keyword[for] identifier[field] keyword[in] identifier[factory] (): identifier[setattr] ( identifier[cls] , identifier[field] . identifier[name] , identifier[field] )
def add_custom_fields(cls, *args, **kw): """ Add any custom fields defined in the configuration. """ for factory in config.custom_field_factories: for field in factory(): setattr(cls, field.name, field) # depends on [control=['for'], data=['field']] # depends on [control=['for'], data=['factory']]
def extract_url_query_parameter(url, parameter): """Given a URL (ex: "http://www.test.com/path?query=3") and a parameter (ex: "query"), return the value as a list :param url: a `str` URL :param parameter: the URL query we went to extract :return: a `list` of values for the given query name in the given URL or an empty string if the query is not in the URL """ query_string = urlparse(url).query return parse_qs(query_string).get(parameter, [])
def function[extract_url_query_parameter, parameter[url, parameter]]: constant[Given a URL (ex: "http://www.test.com/path?query=3") and a parameter (ex: "query"), return the value as a list :param url: a `str` URL :param parameter: the URL query we went to extract :return: a `list` of values for the given query name in the given URL or an empty string if the query is not in the URL ] variable[query_string] assign[=] call[name[urlparse], parameter[name[url]]].query return[call[call[name[parse_qs], parameter[name[query_string]]].get, parameter[name[parameter], list[[]]]]]
keyword[def] identifier[extract_url_query_parameter] ( identifier[url] , identifier[parameter] ): literal[string] identifier[query_string] = identifier[urlparse] ( identifier[url] ). identifier[query] keyword[return] identifier[parse_qs] ( identifier[query_string] ). identifier[get] ( identifier[parameter] ,[])
def extract_url_query_parameter(url, parameter): """Given a URL (ex: "http://www.test.com/path?query=3") and a parameter (ex: "query"), return the value as a list :param url: a `str` URL :param parameter: the URL query we went to extract :return: a `list` of values for the given query name in the given URL or an empty string if the query is not in the URL """ query_string = urlparse(url).query return parse_qs(query_string).get(parameter, [])
def parse_prototype(prototype): '''Returns a :attr:`FunctionSpec` instance from the input. ''' val = ' '.join(prototype.splitlines()) f = match(func_pat, val) # match the whole function if f is None: raise Exception('Cannot parse function prototype "{}"'.format(val)) ftp, pointer, name, arg = [v.strip() for v in f.groups()] args = [] if arg.strip(): # split each arg into type, zero or more *, and name for item in split(arg_split_pat, arg): m = match(variable_pat, item.strip()) if m is None: raise Exception('Cannot parse function prototype "{}"'.format(val)) tp, star, nm, count = [v.strip() if v else '' for v in m.groups()] args.append(VariableSpec(tp, star, nm, count)) return FunctionSpec('FLYCAPTURE2_C_API', ftp, pointer, name, args)
def function[parse_prototype, parameter[prototype]]: constant[Returns a :attr:`FunctionSpec` instance from the input. ] variable[val] assign[=] call[constant[ ].join, parameter[call[name[prototype].splitlines, parameter[]]]] variable[f] assign[=] call[name[match], parameter[name[func_pat], name[val]]] if compare[name[f] is constant[None]] begin[:] <ast.Raise object at 0x7da20e957ee0> <ast.Tuple object at 0x7da20e9551e0> assign[=] <ast.ListComp object at 0x7da20c7cacb0> variable[args] assign[=] list[[]] if call[name[arg].strip, parameter[]] begin[:] for taget[name[item]] in starred[call[name[split], parameter[name[arg_split_pat], name[arg]]]] begin[:] variable[m] assign[=] call[name[match], parameter[name[variable_pat], call[name[item].strip, parameter[]]]] if compare[name[m] is constant[None]] begin[:] <ast.Raise object at 0x7da20c7cb010> <ast.Tuple object at 0x7da20c7c9690> assign[=] <ast.ListComp object at 0x7da20c7ca5c0> call[name[args].append, parameter[call[name[VariableSpec], parameter[name[tp], name[star], name[nm], name[count]]]]] return[call[name[FunctionSpec], parameter[constant[FLYCAPTURE2_C_API], name[ftp], name[pointer], name[name], name[args]]]]
keyword[def] identifier[parse_prototype] ( identifier[prototype] ): literal[string] identifier[val] = literal[string] . identifier[join] ( identifier[prototype] . identifier[splitlines] ()) identifier[f] = identifier[match] ( identifier[func_pat] , identifier[val] ) keyword[if] identifier[f] keyword[is] keyword[None] : keyword[raise] identifier[Exception] ( literal[string] . identifier[format] ( identifier[val] )) identifier[ftp] , identifier[pointer] , identifier[name] , identifier[arg] =[ identifier[v] . identifier[strip] () keyword[for] identifier[v] keyword[in] identifier[f] . identifier[groups] ()] identifier[args] =[] keyword[if] identifier[arg] . identifier[strip] (): keyword[for] identifier[item] keyword[in] identifier[split] ( identifier[arg_split_pat] , identifier[arg] ): identifier[m] = identifier[match] ( identifier[variable_pat] , identifier[item] . identifier[strip] ()) keyword[if] identifier[m] keyword[is] keyword[None] : keyword[raise] identifier[Exception] ( literal[string] . identifier[format] ( identifier[val] )) identifier[tp] , identifier[star] , identifier[nm] , identifier[count] =[ identifier[v] . identifier[strip] () keyword[if] identifier[v] keyword[else] literal[string] keyword[for] identifier[v] keyword[in] identifier[m] . identifier[groups] ()] identifier[args] . identifier[append] ( identifier[VariableSpec] ( identifier[tp] , identifier[star] , identifier[nm] , identifier[count] )) keyword[return] identifier[FunctionSpec] ( literal[string] , identifier[ftp] , identifier[pointer] , identifier[name] , identifier[args] )
def parse_prototype(prototype): """Returns a :attr:`FunctionSpec` instance from the input. """ val = ' '.join(prototype.splitlines()) f = match(func_pat, val) # match the whole function if f is None: raise Exception('Cannot parse function prototype "{}"'.format(val)) # depends on [control=['if'], data=[]] (ftp, pointer, name, arg) = [v.strip() for v in f.groups()] args = [] if arg.strip(): # split each arg into type, zero or more *, and name for item in split(arg_split_pat, arg): m = match(variable_pat, item.strip()) if m is None: raise Exception('Cannot parse function prototype "{}"'.format(val)) # depends on [control=['if'], data=[]] (tp, star, nm, count) = [v.strip() if v else '' for v in m.groups()] args.append(VariableSpec(tp, star, nm, count)) # depends on [control=['for'], data=['item']] # depends on [control=['if'], data=[]] return FunctionSpec('FLYCAPTURE2_C_API', ftp, pointer, name, args)
def set_nested(self, klist, value): """D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v""" keys = list(klist) if len(keys) > 0: curr_dict = self last_key = keys.pop() for key in keys: if not curr_dict.has_key(key) or not isinstance(curr_dict[key], NestedDict): curr_dict[key] = type(self)() curr_dict = curr_dict[key] curr_dict[last_key] = value
def function[set_nested, parameter[self, klist, value]]: constant[D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v] variable[keys] assign[=] call[name[list], parameter[name[klist]]] if compare[call[name[len], parameter[name[keys]]] greater[>] constant[0]] begin[:] variable[curr_dict] assign[=] name[self] variable[last_key] assign[=] call[name[keys].pop, parameter[]] for taget[name[key]] in starred[name[keys]] begin[:] if <ast.BoolOp object at 0x7da2044c16c0> begin[:] call[name[curr_dict]][name[key]] assign[=] call[call[name[type], parameter[name[self]]], parameter[]] variable[curr_dict] assign[=] call[name[curr_dict]][name[key]] call[name[curr_dict]][name[last_key]] assign[=] name[value]
keyword[def] identifier[set_nested] ( identifier[self] , identifier[klist] , identifier[value] ): literal[string] identifier[keys] = identifier[list] ( identifier[klist] ) keyword[if] identifier[len] ( identifier[keys] )> literal[int] : identifier[curr_dict] = identifier[self] identifier[last_key] = identifier[keys] . identifier[pop] () keyword[for] identifier[key] keyword[in] identifier[keys] : keyword[if] keyword[not] identifier[curr_dict] . identifier[has_key] ( identifier[key] ) keyword[or] keyword[not] identifier[isinstance] ( identifier[curr_dict] [ identifier[key] ], identifier[NestedDict] ): identifier[curr_dict] [ identifier[key] ]= identifier[type] ( identifier[self] )() identifier[curr_dict] = identifier[curr_dict] [ identifier[key] ] identifier[curr_dict] [ identifier[last_key] ]= identifier[value]
def set_nested(self, klist, value): """D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v""" keys = list(klist) if len(keys) > 0: curr_dict = self last_key = keys.pop() for key in keys: if not curr_dict.has_key(key) or not isinstance(curr_dict[key], NestedDict): curr_dict[key] = type(self)() # depends on [control=['if'], data=[]] curr_dict = curr_dict[key] # depends on [control=['for'], data=['key']] curr_dict[last_key] = value # depends on [control=['if'], data=[]]
def _run_dir(self, run): """Helper that maps a frontend run name to a profile "run" directory. The frontend run name consists of the TensorBoard run name (aka the relative path from the logdir root to the directory containing the data) path-joined to the Profile plugin's "run" concept (which is a subdirectory of the plugins/profile directory representing an individual run of the tool), with the special case that TensorBoard run is the logdir root (which is the run named '.') then only the Profile plugin "run" name is used, for backwards compatibility. To convert back to the actual run directory, we apply the following transformation: - If the run name doesn't contain '/', prepend './' - Split on the rightmost instance of '/' - Assume the left side is a TensorBoard run name and map it to a directory path using EventMultiplexer.RunPaths(), then map that to the profile plugin directory via PluginDirectory() - Assume the right side is a Profile plugin "run" and path-join it to the preceding path to get the final directory Args: run: the frontend run name, as described above, e.g. train/run1. Returns: The resolved directory path, e.g. /logdir/train/plugins/profile/run1. """ run = run.rstrip('/') if '/' not in run: run = './' + run tb_run_name, _, profile_run_name = run.rpartition('/') tb_run_directory = self.multiplexer.RunPaths().get(tb_run_name) if tb_run_directory is None: # Check if logdir is a directory to handle case where it's actually a # multipart directory spec, which this plugin does not support. if tb_run_name == '.' and tf.io.gfile.isdir(self.logdir): tb_run_directory = self.logdir else: raise RuntimeError("No matching run directory for run %s" % run) plugin_directory = plugin_asset_util.PluginDirectory( tb_run_directory, PLUGIN_NAME) return os.path.join(plugin_directory, profile_run_name)
def function[_run_dir, parameter[self, run]]: constant[Helper that maps a frontend run name to a profile "run" directory. The frontend run name consists of the TensorBoard run name (aka the relative path from the logdir root to the directory containing the data) path-joined to the Profile plugin's "run" concept (which is a subdirectory of the plugins/profile directory representing an individual run of the tool), with the special case that TensorBoard run is the logdir root (which is the run named '.') then only the Profile plugin "run" name is used, for backwards compatibility. To convert back to the actual run directory, we apply the following transformation: - If the run name doesn't contain '/', prepend './' - Split on the rightmost instance of '/' - Assume the left side is a TensorBoard run name and map it to a directory path using EventMultiplexer.RunPaths(), then map that to the profile plugin directory via PluginDirectory() - Assume the right side is a Profile plugin "run" and path-join it to the preceding path to get the final directory Args: run: the frontend run name, as described above, e.g. train/run1. Returns: The resolved directory path, e.g. /logdir/train/plugins/profile/run1. ] variable[run] assign[=] call[name[run].rstrip, parameter[constant[/]]] if compare[constant[/] <ast.NotIn object at 0x7da2590d7190> name[run]] begin[:] variable[run] assign[=] binary_operation[constant[./] + name[run]] <ast.Tuple object at 0x7da1b21ce5f0> assign[=] call[name[run].rpartition, parameter[constant[/]]] variable[tb_run_directory] assign[=] call[call[name[self].multiplexer.RunPaths, parameter[]].get, parameter[name[tb_run_name]]] if compare[name[tb_run_directory] is constant[None]] begin[:] if <ast.BoolOp object at 0x7da1b21cd630> begin[:] variable[tb_run_directory] assign[=] name[self].logdir variable[plugin_directory] assign[=] call[name[plugin_asset_util].PluginDirectory, parameter[name[tb_run_directory], name[PLUGIN_NAME]]] return[call[name[os].path.join, parameter[name[plugin_directory], name[profile_run_name]]]]
keyword[def] identifier[_run_dir] ( identifier[self] , identifier[run] ): literal[string] identifier[run] = identifier[run] . identifier[rstrip] ( literal[string] ) keyword[if] literal[string] keyword[not] keyword[in] identifier[run] : identifier[run] = literal[string] + identifier[run] identifier[tb_run_name] , identifier[_] , identifier[profile_run_name] = identifier[run] . identifier[rpartition] ( literal[string] ) identifier[tb_run_directory] = identifier[self] . identifier[multiplexer] . identifier[RunPaths] (). identifier[get] ( identifier[tb_run_name] ) keyword[if] identifier[tb_run_directory] keyword[is] keyword[None] : keyword[if] identifier[tb_run_name] == literal[string] keyword[and] identifier[tf] . identifier[io] . identifier[gfile] . identifier[isdir] ( identifier[self] . identifier[logdir] ): identifier[tb_run_directory] = identifier[self] . identifier[logdir] keyword[else] : keyword[raise] identifier[RuntimeError] ( literal[string] % identifier[run] ) identifier[plugin_directory] = identifier[plugin_asset_util] . identifier[PluginDirectory] ( identifier[tb_run_directory] , identifier[PLUGIN_NAME] ) keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[plugin_directory] , identifier[profile_run_name] )
def _run_dir(self, run): """Helper that maps a frontend run name to a profile "run" directory. The frontend run name consists of the TensorBoard run name (aka the relative path from the logdir root to the directory containing the data) path-joined to the Profile plugin's "run" concept (which is a subdirectory of the plugins/profile directory representing an individual run of the tool), with the special case that TensorBoard run is the logdir root (which is the run named '.') then only the Profile plugin "run" name is used, for backwards compatibility. To convert back to the actual run directory, we apply the following transformation: - If the run name doesn't contain '/', prepend './' - Split on the rightmost instance of '/' - Assume the left side is a TensorBoard run name and map it to a directory path using EventMultiplexer.RunPaths(), then map that to the profile plugin directory via PluginDirectory() - Assume the right side is a Profile plugin "run" and path-join it to the preceding path to get the final directory Args: run: the frontend run name, as described above, e.g. train/run1. Returns: The resolved directory path, e.g. /logdir/train/plugins/profile/run1. """ run = run.rstrip('/') if '/' not in run: run = './' + run # depends on [control=['if'], data=['run']] (tb_run_name, _, profile_run_name) = run.rpartition('/') tb_run_directory = self.multiplexer.RunPaths().get(tb_run_name) if tb_run_directory is None: # Check if logdir is a directory to handle case where it's actually a # multipart directory spec, which this plugin does not support. if tb_run_name == '.' and tf.io.gfile.isdir(self.logdir): tb_run_directory = self.logdir # depends on [control=['if'], data=[]] else: raise RuntimeError('No matching run directory for run %s' % run) # depends on [control=['if'], data=['tb_run_directory']] plugin_directory = plugin_asset_util.PluginDirectory(tb_run_directory, PLUGIN_NAME) return os.path.join(plugin_directory, profile_run_name)
def array(self, name): """ Returns the array of tables with the given name. """ if name in self._navigable: if isinstance(self._navigable[name], (list, tuple)): return self[name] else: raise NoArrayFoundError else: return ArrayOfTables(toml_file=self, name=name)
def function[array, parameter[self, name]]: constant[ Returns the array of tables with the given name. ] if compare[name[name] in name[self]._navigable] begin[:] if call[name[isinstance], parameter[call[name[self]._navigable][name[name]], tuple[[<ast.Name object at 0x7da20c7c9270>, <ast.Name object at 0x7da20c7c8370>]]]] begin[:] return[call[name[self]][name[name]]]
keyword[def] identifier[array] ( identifier[self] , identifier[name] ): literal[string] keyword[if] identifier[name] keyword[in] identifier[self] . identifier[_navigable] : keyword[if] identifier[isinstance] ( identifier[self] . identifier[_navigable] [ identifier[name] ],( identifier[list] , identifier[tuple] )): keyword[return] identifier[self] [ identifier[name] ] keyword[else] : keyword[raise] identifier[NoArrayFoundError] keyword[else] : keyword[return] identifier[ArrayOfTables] ( identifier[toml_file] = identifier[self] , identifier[name] = identifier[name] )
def array(self, name): """ Returns the array of tables with the given name. """ if name in self._navigable: if isinstance(self._navigable[name], (list, tuple)): return self[name] # depends on [control=['if'], data=[]] else: raise NoArrayFoundError # depends on [control=['if'], data=['name']] else: return ArrayOfTables(toml_file=self, name=name)
def _get_limits_instances(self): """ Return a dict of limits for EC2 instances only. This method should only be used internally by :py:meth:~.get_limits`. :rtype: dict """ # from: http://aws.amazon.com/ec2/faqs/ # (On-Demand, Reserved, Spot) default_limits = (20, 20, 5) special_limits = { 'c4.4xlarge': (10, 20, 5), 'c4.8xlarge': (5, 20, 5), 'c5.4xlarge': (10, 20, 5), 'c5.9xlarge': (5, 20, 5), 'c5.18xlarge': (5, 20, 5), 'cg1.4xlarge': (2, 20, 5), 'cr1.8xlarge': (2, 20, 5), 'd2.4xlarge': (10, 20, 5), 'd2.8xlarge': (5, 20, 5), 'g2.2xlarge': (5, 20, 5), 'g2.8xlarge': (2, 20, 5), 'g3.4xlarge': (1, 20, 5), 'g3.8xlarge': (1, 20, 5), 'g3.16xlarge': (1, 20, 5), 'h1.8xlarge': (10, 20, 5), 'h1.16xlarge': (5, 20, 5), 'hi1.4xlarge': (2, 20, 5), 'hs1.8xlarge': (2, 20, 0), 'i2.2xlarge': (8, 20, 0), 'i2.4xlarge': (4, 20, 0), 'i2.8xlarge': (2, 20, 0), 'i2.xlarge': (8, 20, 0), 'i3.2xlarge': (2, 20, 0), 'i3.4xlarge': (2, 20, 0), 'i3.8xlarge': (2, 20, 0), 'i3.16xlarge': (2, 20, 0), 'i3.large': (2, 20, 0), 'i3.xlarge': (2, 20, 0), 'm4.4xlarge': (10, 20, 5), 'm4.10xlarge': (5, 20, 5), 'm4.16xlarge': (5, 20, 5), 'm5.4xlarge': (10, 20, 5), 'm5.12xlarge': (5, 20, 5), 'm5.24xlarge': (5, 20, 5), 'p2.8xlarge': (1, 20, 5), 'p2.16xlarge': (1, 20, 5), 'p2.xlarge': (1, 20, 5), 'p3.2xlarge': (1, 20, 5), 'p3.8xlarge': (1, 20, 5), 'p3.16xlarge': (1, 20, 5), 'p3dn.24xlarge': (1, 20, 5), 'r3.4xlarge': (10, 20, 5), 'r3.8xlarge': (5, 20, 5), 'r4.4xlarge': (10, 20, 5), 'r4.8xlarge': (5, 20, 5), 'r4.16xlarge': (1, 20, 5), } limits = {} for i_type in self._instance_types(): key = 'Running On-Demand {t} instances'.format( t=i_type) lim = default_limits[0] if i_type in special_limits: lim = special_limits[i_type][0] limits[key] = AwsLimit( key, self, lim, self.warning_threshold, self.critical_threshold, limit_type='On-Demand instances', limit_subtype=i_type, ta_limit_name='On-Demand instances - %s' % i_type ) # limit for ALL running On-Demand instances key = 'Running On-Demand EC2 instances' limits[key] = AwsLimit( key, self, default_limits[0], self.warning_threshold, self.critical_threshold, limit_type='On-Demand instances', ) return limits
def function[_get_limits_instances, parameter[self]]: constant[ Return a dict of limits for EC2 instances only. This method should only be used internally by :py:meth:~.get_limits`. :rtype: dict ] variable[default_limits] assign[=] tuple[[<ast.Constant object at 0x7da20e961e70>, <ast.Constant object at 0x7da20e961f00>, <ast.Constant object at 0x7da20e9638e0>]] variable[special_limits] assign[=] dictionary[[<ast.Constant object at 0x7da20e961660>, <ast.Constant object at 0x7da20e962830>, <ast.Constant object at 0x7da20e962980>, <ast.Constant object at 0x7da20e960df0>, <ast.Constant object at 0x7da20e960f40>, <ast.Constant object at 0x7da20e960b80>, <ast.Constant object at 0x7da20e9610f0>, <ast.Constant object at 0x7da20e9605b0>, <ast.Constant object at 0x7da20e963430>, <ast.Constant object at 0x7da20e961840>, <ast.Constant object at 0x7da20e9601c0>, <ast.Constant object at 0x7da20e962770>, <ast.Constant object at 0x7da20e960fd0>, <ast.Constant object at 0x7da20e962860>, <ast.Constant object at 0x7da20e961c30>, <ast.Constant object at 0x7da20e960d00>, <ast.Constant object at 0x7da20e9639a0>, <ast.Constant object at 0x7da20e960070>, <ast.Constant object at 0x7da20e9621d0>, <ast.Constant object at 0x7da20e9627d0>, <ast.Constant object at 0x7da20e963250>, <ast.Constant object at 0x7da20e9634c0>, <ast.Constant object at 0x7da20e961150>, <ast.Constant object at 0x7da20e960be0>, <ast.Constant object at 0x7da20e9637f0>, <ast.Constant object at 0x7da20e9637c0>, <ast.Constant object at 0x7da20e960ee0>, <ast.Constant object at 0x7da20e9620e0>, <ast.Constant object at 0x7da20e9633a0>, <ast.Constant object at 0x7da20e9600a0>, <ast.Constant object at 0x7da20e962230>, <ast.Constant object at 0x7da20e960af0>, <ast.Constant object at 0x7da20e962fe0>, <ast.Constant object at 0x7da20e963550>, <ast.Constant object at 0x7da20e963a30>, <ast.Constant object at 0x7da20e9619f0>, <ast.Constant object at 0x7da20e960640>, <ast.Constant object at 0x7da20e960760>, <ast.Constant object at 0x7da20e963fa0>, <ast.Constant object at 0x7da20e9604c0>, <ast.Constant object at 0x7da20e960880>, <ast.Constant object at 0x7da20e963b80>, <ast.Constant object at 0x7da20e9606a0>, <ast.Constant object at 0x7da20e962590>, <ast.Constant object at 0x7da20e961d80>, <ast.Constant object at 0x7da20e962530>], [<ast.Tuple object at 0x7da20e963ac0>, <ast.Tuple object at 0x7da20e961b70>, <ast.Tuple object at 0x7da20e961690>, <ast.Tuple object at 0x7da20e961d20>, <ast.Tuple object at 0x7da20e961390>, <ast.Tuple object at 0x7da20c6a8c10>, <ast.Tuple object at 0x7da20c6ab6d0>, <ast.Tuple object at 0x7da20c6a8430>, <ast.Tuple object at 0x7da20c6a81f0>, <ast.Tuple object at 0x7da20c6abe50>, <ast.Tuple object at 0x7da20c6aa590>, <ast.Tuple object at 0x7da20c6aab30>, <ast.Tuple object at 0x7da20e9623e0>, <ast.Tuple object at 0x7da20e9630d0>, <ast.Tuple object at 0x7da20e9608b0>, <ast.Tuple object at 0x7da20e960d90>, <ast.Tuple object at 0x7da20e9612d0>, <ast.Tuple object at 0x7da20e9619c0>, <ast.Tuple object at 0x7da20e963cd0>, <ast.Tuple object at 0x7da20e961ed0>, <ast.Tuple object at 0x7da20e961e40>, <ast.Tuple object at 0x7da20e960580>, <ast.Tuple object at 0x7da20e9602e0>, <ast.Tuple object at 0x7da20e963d60>, <ast.Tuple object at 0x7da20e962110>, <ast.Tuple object at 0x7da20e961750>, <ast.Tuple object at 0x7da20e963d90>, <ast.Tuple object at 0x7da20e962470>, <ast.Tuple object at 0x7da20e962ce0>, <ast.Tuple object at 0x7da20e963df0>, <ast.Tuple object at 0x7da20e960610>, <ast.Tuple object at 0x7da20e962dd0>, <ast.Tuple object at 0x7da20e963580>, <ast.Tuple object at 0x7da20e961a50>, <ast.Tuple object at 0x7da20e960280>, <ast.Tuple object at 0x7da20e962da0>, <ast.Tuple object at 0x7da18f09ecb0>, <ast.Tuple object at 0x7da18f09ca00>, <ast.Tuple object at 0x7da18f09e110>, <ast.Tuple object at 0x7da18f09cdf0>, <ast.Tuple object at 0x7da18f09ff70>, <ast.Tuple object at 0x7da18f09c430>, <ast.Tuple object at 0x7da18f09ce50>, <ast.Tuple object at 0x7da18f09f940>, <ast.Tuple object at 0x7da18f09d5a0>, <ast.Tuple object at 0x7da18f09da80>]] variable[limits] assign[=] dictionary[[], []] for taget[name[i_type]] in starred[call[name[self]._instance_types, parameter[]]] begin[:] variable[key] assign[=] call[constant[Running On-Demand {t} instances].format, parameter[]] variable[lim] assign[=] call[name[default_limits]][constant[0]] if compare[name[i_type] in name[special_limits]] begin[:] variable[lim] assign[=] call[call[name[special_limits]][name[i_type]]][constant[0]] call[name[limits]][name[key]] assign[=] call[name[AwsLimit], parameter[name[key], name[self], name[lim], name[self].warning_threshold, name[self].critical_threshold]] variable[key] assign[=] constant[Running On-Demand EC2 instances] call[name[limits]][name[key]] assign[=] call[name[AwsLimit], parameter[name[key], name[self], call[name[default_limits]][constant[0]], name[self].warning_threshold, name[self].critical_threshold]] return[name[limits]]
keyword[def] identifier[_get_limits_instances] ( identifier[self] ): literal[string] identifier[default_limits] =( literal[int] , literal[int] , literal[int] ) identifier[special_limits] ={ literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), literal[string] :( literal[int] , literal[int] , literal[int] ), } identifier[limits] ={} keyword[for] identifier[i_type] keyword[in] identifier[self] . identifier[_instance_types] (): identifier[key] = literal[string] . identifier[format] ( identifier[t] = identifier[i_type] ) identifier[lim] = identifier[default_limits] [ literal[int] ] keyword[if] identifier[i_type] keyword[in] identifier[special_limits] : identifier[lim] = identifier[special_limits] [ identifier[i_type] ][ literal[int] ] identifier[limits] [ identifier[key] ]= identifier[AwsLimit] ( identifier[key] , identifier[self] , identifier[lim] , identifier[self] . identifier[warning_threshold] , identifier[self] . identifier[critical_threshold] , identifier[limit_type] = literal[string] , identifier[limit_subtype] = identifier[i_type] , identifier[ta_limit_name] = literal[string] % identifier[i_type] ) identifier[key] = literal[string] identifier[limits] [ identifier[key] ]= identifier[AwsLimit] ( identifier[key] , identifier[self] , identifier[default_limits] [ literal[int] ], identifier[self] . identifier[warning_threshold] , identifier[self] . identifier[critical_threshold] , identifier[limit_type] = literal[string] , ) keyword[return] identifier[limits]
def _get_limits_instances(self): """ Return a dict of limits for EC2 instances only. This method should only be used internally by :py:meth:~.get_limits`. :rtype: dict """ # from: http://aws.amazon.com/ec2/faqs/ # (On-Demand, Reserved, Spot) default_limits = (20, 20, 5) special_limits = {'c4.4xlarge': (10, 20, 5), 'c4.8xlarge': (5, 20, 5), 'c5.4xlarge': (10, 20, 5), 'c5.9xlarge': (5, 20, 5), 'c5.18xlarge': (5, 20, 5), 'cg1.4xlarge': (2, 20, 5), 'cr1.8xlarge': (2, 20, 5), 'd2.4xlarge': (10, 20, 5), 'd2.8xlarge': (5, 20, 5), 'g2.2xlarge': (5, 20, 5), 'g2.8xlarge': (2, 20, 5), 'g3.4xlarge': (1, 20, 5), 'g3.8xlarge': (1, 20, 5), 'g3.16xlarge': (1, 20, 5), 'h1.8xlarge': (10, 20, 5), 'h1.16xlarge': (5, 20, 5), 'hi1.4xlarge': (2, 20, 5), 'hs1.8xlarge': (2, 20, 0), 'i2.2xlarge': (8, 20, 0), 'i2.4xlarge': (4, 20, 0), 'i2.8xlarge': (2, 20, 0), 'i2.xlarge': (8, 20, 0), 'i3.2xlarge': (2, 20, 0), 'i3.4xlarge': (2, 20, 0), 'i3.8xlarge': (2, 20, 0), 'i3.16xlarge': (2, 20, 0), 'i3.large': (2, 20, 0), 'i3.xlarge': (2, 20, 0), 'm4.4xlarge': (10, 20, 5), 'm4.10xlarge': (5, 20, 5), 'm4.16xlarge': (5, 20, 5), 'm5.4xlarge': (10, 20, 5), 'm5.12xlarge': (5, 20, 5), 'm5.24xlarge': (5, 20, 5), 'p2.8xlarge': (1, 20, 5), 'p2.16xlarge': (1, 20, 5), 'p2.xlarge': (1, 20, 5), 'p3.2xlarge': (1, 20, 5), 'p3.8xlarge': (1, 20, 5), 'p3.16xlarge': (1, 20, 5), 'p3dn.24xlarge': (1, 20, 5), 'r3.4xlarge': (10, 20, 5), 'r3.8xlarge': (5, 20, 5), 'r4.4xlarge': (10, 20, 5), 'r4.8xlarge': (5, 20, 5), 'r4.16xlarge': (1, 20, 5)} limits = {} for i_type in self._instance_types(): key = 'Running On-Demand {t} instances'.format(t=i_type) lim = default_limits[0] if i_type in special_limits: lim = special_limits[i_type][0] # depends on [control=['if'], data=['i_type', 'special_limits']] limits[key] = AwsLimit(key, self, lim, self.warning_threshold, self.critical_threshold, limit_type='On-Demand instances', limit_subtype=i_type, ta_limit_name='On-Demand instances - %s' % i_type) # depends on [control=['for'], data=['i_type']] # limit for ALL running On-Demand instances key = 'Running On-Demand EC2 instances' limits[key] = AwsLimit(key, self, default_limits[0], self.warning_threshold, self.critical_threshold, limit_type='On-Demand instances') return limits
def add_attachment_viewer_widget(self, attachment_property, custom_title=False, height=None): """ Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization. The widget will be saved to KE-chain. :param attachment_property: The Attachment Property to which the Viewer will be connected to. :type attachment_property: :class:`Property` or UUID :param custom_title: A custom title for the attachment viewer widget * False (default): Notebook name * String value: Custom title * None: No title :type custom_title: bool or basestring or None :param height: The height of the Notebook in pixels :type height: int or None :raises IllegalArgumentError: When unknown or illegal arguments are passed. """ # Check whether the attachment property is uuid type or class `Property` if isinstance(attachment_property, Property): attachment_property_id = attachment_property.id elif isinstance(attachment_property, text_type) and is_uuid(attachment_property): attachment_property_id = attachment_property attachment_property = self._client.property(id=attachment_property_id) else: raise IllegalArgumentError("When using the add_attachment_viewer_widget, attachment_property must be a " "Property or Property id. Type is: {}".format(type(attachment_property))) # Check whether the `Property` has type `Attachment` property_type = attachment_property.type if property_type != PropertyType.ATTACHMENT_VALUE: raise IllegalArgumentError("When using the add_attachment_viewer_widget, attachment_property must have " "type {}. Type found: {}".format(PropertyType.ATTACHMENT_VALUE, property_type)) # Check also whether `Property` has category `Instance` property_category = attachment_property._json_data['category'] if property_category != Category.INSTANCE: raise IllegalArgumentError("When using the add_attachment_viewer_widget, attachment_property must have " "category {}. Category found: {}".format(Category.INSTANCE, property_category)) # Add custom title if custom_title is False: show_title_value = "Default" title = attachment_property.name elif custom_title is None: show_title_value = "No title" title = '' else: show_title_value = "Custom title" title = str(custom_title) # Declare attachment viewer widget config config = { 'propertyId': attachment_property_id, 'showTitleValue': show_title_value, 'xtype': ComponentXType.PROPERTYATTACHMENTPREVIEWER, 'title': title, 'filter': { 'activity_id': str(self.activity.id) }, 'height': height if height else 500 } # Declare attachment viewer widget meta meta = { 'propertyInstanceId': attachment_property_id, 'activityId': str(self.activity.id), 'customHeight': height if height else 500, 'showTitleValue': show_title_value, 'customTitle': title } self._add_widget(dict(config=config, meta=meta, name=WidgetNames.ATTACHMENTVIEWERWIDGET))
def function[add_attachment_viewer_widget, parameter[self, attachment_property, custom_title, height]]: constant[ Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization. The widget will be saved to KE-chain. :param attachment_property: The Attachment Property to which the Viewer will be connected to. :type attachment_property: :class:`Property` or UUID :param custom_title: A custom title for the attachment viewer widget * False (default): Notebook name * String value: Custom title * None: No title :type custom_title: bool or basestring or None :param height: The height of the Notebook in pixels :type height: int or None :raises IllegalArgumentError: When unknown or illegal arguments are passed. ] if call[name[isinstance], parameter[name[attachment_property], name[Property]]] begin[:] variable[attachment_property_id] assign[=] name[attachment_property].id variable[property_type] assign[=] name[attachment_property].type if compare[name[property_type] not_equal[!=] name[PropertyType].ATTACHMENT_VALUE] begin[:] <ast.Raise object at 0x7da20c6c7430> variable[property_category] assign[=] call[name[attachment_property]._json_data][constant[category]] if compare[name[property_category] not_equal[!=] name[Category].INSTANCE] begin[:] <ast.Raise object at 0x7da20c6c6a10> if compare[name[custom_title] is constant[False]] begin[:] variable[show_title_value] assign[=] constant[Default] variable[title] assign[=] name[attachment_property].name variable[config] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c6d10>, <ast.Constant object at 0x7da20c6c6260>, <ast.Constant object at 0x7da20c6c71c0>, <ast.Constant object at 0x7da20c6c6fe0>, <ast.Constant object at 0x7da20c6c4be0>, <ast.Constant object at 0x7da20c6c7340>], [<ast.Name object at 0x7da20c6c42e0>, <ast.Name object at 0x7da20c6c69b0>, <ast.Attribute object at 0x7da20c6c7d30>, <ast.Name object at 0x7da20c6c60b0>, <ast.Dict object at 0x7da20c6c6f50>, <ast.IfExp object at 0x7da20c6c45b0>]] variable[meta] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c67d0>, <ast.Constant object at 0x7da20c6c6e60>, <ast.Constant object at 0x7da20c6c5cc0>, <ast.Constant object at 0x7da20c6c7490>, <ast.Constant object at 0x7da20c6c7eb0>], [<ast.Name object at 0x7da20c6c6e90>, <ast.Call object at 0x7da20c6c6080>, <ast.IfExp object at 0x7da1b24afa90>, <ast.Name object at 0x7da204621c90>, <ast.Name object at 0x7da2046232e0>]] call[name[self]._add_widget, parameter[call[name[dict], parameter[]]]]
keyword[def] identifier[add_attachment_viewer_widget] ( identifier[self] , identifier[attachment_property] , identifier[custom_title] = keyword[False] , identifier[height] = keyword[None] ): literal[string] keyword[if] identifier[isinstance] ( identifier[attachment_property] , identifier[Property] ): identifier[attachment_property_id] = identifier[attachment_property] . identifier[id] keyword[elif] identifier[isinstance] ( identifier[attachment_property] , identifier[text_type] ) keyword[and] identifier[is_uuid] ( identifier[attachment_property] ): identifier[attachment_property_id] = identifier[attachment_property] identifier[attachment_property] = identifier[self] . identifier[_client] . identifier[property] ( identifier[id] = identifier[attachment_property_id] ) keyword[else] : keyword[raise] identifier[IllegalArgumentError] ( literal[string] literal[string] . identifier[format] ( identifier[type] ( identifier[attachment_property] ))) identifier[property_type] = identifier[attachment_property] . identifier[type] keyword[if] identifier[property_type] != identifier[PropertyType] . identifier[ATTACHMENT_VALUE] : keyword[raise] identifier[IllegalArgumentError] ( literal[string] literal[string] . identifier[format] ( identifier[PropertyType] . identifier[ATTACHMENT_VALUE] , identifier[property_type] )) identifier[property_category] = identifier[attachment_property] . identifier[_json_data] [ literal[string] ] keyword[if] identifier[property_category] != identifier[Category] . identifier[INSTANCE] : keyword[raise] identifier[IllegalArgumentError] ( literal[string] literal[string] . identifier[format] ( identifier[Category] . identifier[INSTANCE] , identifier[property_category] )) keyword[if] identifier[custom_title] keyword[is] keyword[False] : identifier[show_title_value] = literal[string] identifier[title] = identifier[attachment_property] . identifier[name] keyword[elif] identifier[custom_title] keyword[is] keyword[None] : identifier[show_title_value] = literal[string] identifier[title] = literal[string] keyword[else] : identifier[show_title_value] = literal[string] identifier[title] = identifier[str] ( identifier[custom_title] ) identifier[config] ={ literal[string] : identifier[attachment_property_id] , literal[string] : identifier[show_title_value] , literal[string] : identifier[ComponentXType] . identifier[PROPERTYATTACHMENTPREVIEWER] , literal[string] : identifier[title] , literal[string] :{ literal[string] : identifier[str] ( identifier[self] . identifier[activity] . identifier[id] ) }, literal[string] : identifier[height] keyword[if] identifier[height] keyword[else] literal[int] } identifier[meta] ={ literal[string] : identifier[attachment_property_id] , literal[string] : identifier[str] ( identifier[self] . identifier[activity] . identifier[id] ), literal[string] : identifier[height] keyword[if] identifier[height] keyword[else] literal[int] , literal[string] : identifier[show_title_value] , literal[string] : identifier[title] } identifier[self] . identifier[_add_widget] ( identifier[dict] ( identifier[config] = identifier[config] , identifier[meta] = identifier[meta] , identifier[name] = identifier[WidgetNames] . identifier[ATTACHMENTVIEWERWIDGET] ))
def add_attachment_viewer_widget(self, attachment_property, custom_title=False, height=None): """ Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization. The widget will be saved to KE-chain. :param attachment_property: The Attachment Property to which the Viewer will be connected to. :type attachment_property: :class:`Property` or UUID :param custom_title: A custom title for the attachment viewer widget * False (default): Notebook name * String value: Custom title * None: No title :type custom_title: bool or basestring or None :param height: The height of the Notebook in pixels :type height: int or None :raises IllegalArgumentError: When unknown or illegal arguments are passed. """ # Check whether the attachment property is uuid type or class `Property` if isinstance(attachment_property, Property): attachment_property_id = attachment_property.id # depends on [control=['if'], data=[]] elif isinstance(attachment_property, text_type) and is_uuid(attachment_property): attachment_property_id = attachment_property attachment_property = self._client.property(id=attachment_property_id) # depends on [control=['if'], data=[]] else: raise IllegalArgumentError('When using the add_attachment_viewer_widget, attachment_property must be a Property or Property id. Type is: {}'.format(type(attachment_property))) # Check whether the `Property` has type `Attachment` property_type = attachment_property.type if property_type != PropertyType.ATTACHMENT_VALUE: raise IllegalArgumentError('When using the add_attachment_viewer_widget, attachment_property must have type {}. Type found: {}'.format(PropertyType.ATTACHMENT_VALUE, property_type)) # depends on [control=['if'], data=['property_type']] # Check also whether `Property` has category `Instance` property_category = attachment_property._json_data['category'] if property_category != Category.INSTANCE: raise IllegalArgumentError('When using the add_attachment_viewer_widget, attachment_property must have category {}. Category found: {}'.format(Category.INSTANCE, property_category)) # depends on [control=['if'], data=['property_category']] # Add custom title if custom_title is False: show_title_value = 'Default' title = attachment_property.name # depends on [control=['if'], data=[]] elif custom_title is None: show_title_value = 'No title' title = '' # depends on [control=['if'], data=[]] else: show_title_value = 'Custom title' title = str(custom_title) # Declare attachment viewer widget config config = {'propertyId': attachment_property_id, 'showTitleValue': show_title_value, 'xtype': ComponentXType.PROPERTYATTACHMENTPREVIEWER, 'title': title, 'filter': {'activity_id': str(self.activity.id)}, 'height': height if height else 500} # Declare attachment viewer widget meta meta = {'propertyInstanceId': attachment_property_id, 'activityId': str(self.activity.id), 'customHeight': height if height else 500, 'showTitleValue': show_title_value, 'customTitle': title} self._add_widget(dict(config=config, meta=meta, name=WidgetNames.ATTACHMENTVIEWERWIDGET))
def has_sources(self, extension=None): """Return `True` if this target owns sources; optionally of the given `extension`. :API: public :param string extension: Optional suffix of filenames to test for. :return: `True` if the target contains sources that match the optional extension suffix. :rtype: bool """ source_paths = self._sources_field.source_paths if not source_paths: return False if not extension: return True return any(source.endswith(extension) for source in source_paths)
def function[has_sources, parameter[self, extension]]: constant[Return `True` if this target owns sources; optionally of the given `extension`. :API: public :param string extension: Optional suffix of filenames to test for. :return: `True` if the target contains sources that match the optional extension suffix. :rtype: bool ] variable[source_paths] assign[=] name[self]._sources_field.source_paths if <ast.UnaryOp object at 0x7da1b227b700> begin[:] return[constant[False]] if <ast.UnaryOp object at 0x7da1b2279060> begin[:] return[constant[True]] return[call[name[any], parameter[<ast.GeneratorExp object at 0x7da1b227a920>]]]
keyword[def] identifier[has_sources] ( identifier[self] , identifier[extension] = keyword[None] ): literal[string] identifier[source_paths] = identifier[self] . identifier[_sources_field] . identifier[source_paths] keyword[if] keyword[not] identifier[source_paths] : keyword[return] keyword[False] keyword[if] keyword[not] identifier[extension] : keyword[return] keyword[True] keyword[return] identifier[any] ( identifier[source] . identifier[endswith] ( identifier[extension] ) keyword[for] identifier[source] keyword[in] identifier[source_paths] )
def has_sources(self, extension=None): """Return `True` if this target owns sources; optionally of the given `extension`. :API: public :param string extension: Optional suffix of filenames to test for. :return: `True` if the target contains sources that match the optional extension suffix. :rtype: bool """ source_paths = self._sources_field.source_paths if not source_paths: return False # depends on [control=['if'], data=[]] if not extension: return True # depends on [control=['if'], data=[]] return any((source.endswith(extension) for source in source_paths))
def binary(self): """Load and return the path to the native engine binary.""" lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE) lib_path = os.path.join(safe_mkdtemp(), lib_name) try: with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp: # NB: The header stripping code here must be coordinated with header insertion code in # build-support/bin/native/bootstrap_code.sh engine_version = input_fp.readline().decode('utf-8').strip() repo_version = input_fp.readline().decode('utf-8').strip() logger.debug('using {} built at {}'.format(engine_version, repo_version)) with open(lib_path, 'wb') as output_fp: output_fp.write(input_fp.read()) except (IOError, OSError) as e: raise self.BinaryLocationError( "Error unpacking the native engine binary to path {}: {}".format(lib_path, e), e) return lib_path
def function[binary, parameter[self]]: constant[Load and return the path to the native engine binary.] variable[lib_name] assign[=] call[constant[{}.so].format, parameter[name[NATIVE_ENGINE_MODULE]]] variable[lib_path] assign[=] call[name[os].path.join, parameter[call[name[safe_mkdtemp], parameter[]], name[lib_name]]] <ast.Try object at 0x7da1b2279660> return[name[lib_path]]
keyword[def] identifier[binary] ( identifier[self] ): literal[string] identifier[lib_name] = literal[string] . identifier[format] ( identifier[NATIVE_ENGINE_MODULE] ) identifier[lib_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[safe_mkdtemp] (), identifier[lib_name] ) keyword[try] : keyword[with] identifier[closing] ( identifier[pkg_resources] . identifier[resource_stream] ( identifier[__name__] , identifier[lib_name] )) keyword[as] identifier[input_fp] : identifier[engine_version] = identifier[input_fp] . identifier[readline] (). identifier[decode] ( literal[string] ). identifier[strip] () identifier[repo_version] = identifier[input_fp] . identifier[readline] (). identifier[decode] ( literal[string] ). identifier[strip] () identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[engine_version] , identifier[repo_version] )) keyword[with] identifier[open] ( identifier[lib_path] , literal[string] ) keyword[as] identifier[output_fp] : identifier[output_fp] . identifier[write] ( identifier[input_fp] . identifier[read] ()) keyword[except] ( identifier[IOError] , identifier[OSError] ) keyword[as] identifier[e] : keyword[raise] identifier[self] . identifier[BinaryLocationError] ( literal[string] . identifier[format] ( identifier[lib_path] , identifier[e] ), identifier[e] ) keyword[return] identifier[lib_path]
def binary(self): """Load and return the path to the native engine binary.""" lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE) lib_path = os.path.join(safe_mkdtemp(), lib_name) try: with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp: # NB: The header stripping code here must be coordinated with header insertion code in # build-support/bin/native/bootstrap_code.sh engine_version = input_fp.readline().decode('utf-8').strip() repo_version = input_fp.readline().decode('utf-8').strip() logger.debug('using {} built at {}'.format(engine_version, repo_version)) with open(lib_path, 'wb') as output_fp: output_fp.write(input_fp.read()) # depends on [control=['with'], data=['output_fp']] # depends on [control=['with'], data=['input_fp']] # depends on [control=['try'], data=[]] except (IOError, OSError) as e: raise self.BinaryLocationError('Error unpacking the native engine binary to path {}: {}'.format(lib_path, e), e) # depends on [control=['except'], data=['e']] return lib_path
def shippingaddress_update(self, tid, session, **kwargs): '''taobao.trade.shippingaddress.update 更改交易的收货地址''' request = TOPRequest('taobao.trade.shippingaddress.update') request['tid'] = tid for k, v in kwargs.iteritems(): if k not in ('receiver_name','receiver_phone','receiver_mobile','receiver_state','receiver_city','receiver_district','receiver_address','receiver_zip') or v==None: continue request[k] = v self.create(self.execute(request, session)['trade']) return self
def function[shippingaddress_update, parameter[self, tid, session]]: constant[taobao.trade.shippingaddress.update 更改交易的收货地址] variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.trade.shippingaddress.update]]] call[name[request]][constant[tid]] assign[=] name[tid] for taget[tuple[[<ast.Name object at 0x7da1b2616170>, <ast.Name object at 0x7da1b2615600>]]] in starred[call[name[kwargs].iteritems, parameter[]]] begin[:] if <ast.BoolOp object at 0x7da1b2617460> begin[:] continue call[name[request]][name[k]] assign[=] name[v] call[name[self].create, parameter[call[call[name[self].execute, parameter[name[request], name[session]]]][constant[trade]]]] return[name[self]]
keyword[def] identifier[shippingaddress_update] ( identifier[self] , identifier[tid] , identifier[session] ,** identifier[kwargs] ): literal[string] identifier[request] = identifier[TOPRequest] ( literal[string] ) identifier[request] [ literal[string] ]= identifier[tid] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[kwargs] . identifier[iteritems] (): keyword[if] identifier[k] keyword[not] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ) keyword[or] identifier[v] == keyword[None] : keyword[continue] identifier[request] [ identifier[k] ]= identifier[v] identifier[self] . identifier[create] ( identifier[self] . identifier[execute] ( identifier[request] , identifier[session] )[ literal[string] ]) keyword[return] identifier[self]
def shippingaddress_update(self, tid, session, **kwargs): """taobao.trade.shippingaddress.update 更改交易的收货地址""" request = TOPRequest('taobao.trade.shippingaddress.update') request['tid'] = tid for (k, v) in kwargs.iteritems(): if k not in ('receiver_name', 'receiver_phone', 'receiver_mobile', 'receiver_state', 'receiver_city', 'receiver_district', 'receiver_address', 'receiver_zip') or v == None: continue # depends on [control=['if'], data=[]] request[k] = v # depends on [control=['for'], data=[]] self.create(self.execute(request, session)['trade']) return self
def read_line(self, line): """ Match a line of input according to the format specified and return a tuple of the resulting values """ if not self._read_line_init: self.init_read_line() match = self._re.match(line) assert match is not None, f"Format mismatch (line = {line})" matched_values = [] for i in range(self._re.groups): cvt_re = self._match_exps[i] cvt_div = self._divisors[i] cvt_fn = self._in_cvt_fns[i] match_str = match.group(i + 1) match0 = re.match(cvt_re, match_str) if match0 is not None: if cvt_fn == "float": if "." in match_str: val = float(match_str) else: val = int(match_str) / cvt_div elif cvt_fn == "int": val = int(match_str) else: sys.stderr.write( f"Unrecognized conversion function: {cvt_fn}\n" ) else: sys.stderr.write( f"Format conversion failed: {match_str}\n" ) matched_values.append(val) return tuple(matched_values)
def function[read_line, parameter[self, line]]: constant[ Match a line of input according to the format specified and return a tuple of the resulting values ] if <ast.UnaryOp object at 0x7da18f721750> begin[:] call[name[self].init_read_line, parameter[]] variable[match] assign[=] call[name[self]._re.match, parameter[name[line]]] assert[compare[name[match] is_not constant[None]]] variable[matched_values] assign[=] list[[]] for taget[name[i]] in starred[call[name[range], parameter[name[self]._re.groups]]] begin[:] variable[cvt_re] assign[=] call[name[self]._match_exps][name[i]] variable[cvt_div] assign[=] call[name[self]._divisors][name[i]] variable[cvt_fn] assign[=] call[name[self]._in_cvt_fns][name[i]] variable[match_str] assign[=] call[name[match].group, parameter[binary_operation[name[i] + constant[1]]]] variable[match0] assign[=] call[name[re].match, parameter[name[cvt_re], name[match_str]]] if compare[name[match0] is_not constant[None]] begin[:] if compare[name[cvt_fn] equal[==] constant[float]] begin[:] if compare[constant[.] in name[match_str]] begin[:] variable[val] assign[=] call[name[float], parameter[name[match_str]]] call[name[matched_values].append, parameter[name[val]]] return[call[name[tuple], parameter[name[matched_values]]]]
keyword[def] identifier[read_line] ( identifier[self] , identifier[line] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[_read_line_init] : identifier[self] . identifier[init_read_line] () identifier[match] = identifier[self] . identifier[_re] . identifier[match] ( identifier[line] ) keyword[assert] identifier[match] keyword[is] keyword[not] keyword[None] , literal[string] identifier[matched_values] =[] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[_re] . identifier[groups] ): identifier[cvt_re] = identifier[self] . identifier[_match_exps] [ identifier[i] ] identifier[cvt_div] = identifier[self] . identifier[_divisors] [ identifier[i] ] identifier[cvt_fn] = identifier[self] . identifier[_in_cvt_fns] [ identifier[i] ] identifier[match_str] = identifier[match] . identifier[group] ( identifier[i] + literal[int] ) identifier[match0] = identifier[re] . identifier[match] ( identifier[cvt_re] , identifier[match_str] ) keyword[if] identifier[match0] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[cvt_fn] == literal[string] : keyword[if] literal[string] keyword[in] identifier[match_str] : identifier[val] = identifier[float] ( identifier[match_str] ) keyword[else] : identifier[val] = identifier[int] ( identifier[match_str] )/ identifier[cvt_div] keyword[elif] identifier[cvt_fn] == literal[string] : identifier[val] = identifier[int] ( identifier[match_str] ) keyword[else] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) keyword[else] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[matched_values] . identifier[append] ( identifier[val] ) keyword[return] identifier[tuple] ( identifier[matched_values] )
def read_line(self, line): """ Match a line of input according to the format specified and return a tuple of the resulting values """ if not self._read_line_init: self.init_read_line() # depends on [control=['if'], data=[]] match = self._re.match(line) assert match is not None, f'Format mismatch (line = {line})' matched_values = [] for i in range(self._re.groups): cvt_re = self._match_exps[i] cvt_div = self._divisors[i] cvt_fn = self._in_cvt_fns[i] match_str = match.group(i + 1) match0 = re.match(cvt_re, match_str) if match0 is not None: if cvt_fn == 'float': if '.' in match_str: val = float(match_str) # depends on [control=['if'], data=['match_str']] else: val = int(match_str) / cvt_div # depends on [control=['if'], data=[]] elif cvt_fn == 'int': val = int(match_str) # depends on [control=['if'], data=[]] else: sys.stderr.write(f'Unrecognized conversion function: {cvt_fn}\n') # depends on [control=['if'], data=[]] else: sys.stderr.write(f'Format conversion failed: {match_str}\n') matched_values.append(val) # depends on [control=['for'], data=['i']] return tuple(matched_values)
def copy(self, name=None, prefix=None): """Copy this :class:`SettingBase`""" setting = self.__class__.__new__(self.__class__) setting.__dict__.update(self.__dict__) # Keep the modified flag? # setting.modified = False if prefix and not setting.is_global: flags = setting.flags # Prefix a setting setting.orig_name = setting.name setting.name = '%s_%s' % (prefix, setting.name) if flags and flags[-1].startswith('--'): setting.flags = ['--%s-%s' % (prefix, flags[-1][2:])] if name and not setting.is_global: setting.short = '%s application. %s' % (name, setting.short) return setting
def function[copy, parameter[self, name, prefix]]: constant[Copy this :class:`SettingBase`] variable[setting] assign[=] call[name[self].__class__.__new__, parameter[name[self].__class__]] call[name[setting].__dict__.update, parameter[name[self].__dict__]] if <ast.BoolOp object at 0x7da18eb551b0> begin[:] variable[flags] assign[=] name[setting].flags name[setting].orig_name assign[=] name[setting].name name[setting].name assign[=] binary_operation[constant[%s_%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18eb57b20>, <ast.Attribute object at 0x7da18eb55d50>]]] if <ast.BoolOp object at 0x7da18eb57970> begin[:] name[setting].flags assign[=] list[[<ast.BinOp object at 0x7da18eb56200>]] if <ast.BoolOp object at 0x7da18eb56ce0> begin[:] name[setting].short assign[=] binary_operation[constant[%s application. %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18eb56290>, <ast.Attribute object at 0x7da18eb57be0>]]] return[name[setting]]
keyword[def] identifier[copy] ( identifier[self] , identifier[name] = keyword[None] , identifier[prefix] = keyword[None] ): literal[string] identifier[setting] = identifier[self] . identifier[__class__] . identifier[__new__] ( identifier[self] . identifier[__class__] ) identifier[setting] . identifier[__dict__] . identifier[update] ( identifier[self] . identifier[__dict__] ) keyword[if] identifier[prefix] keyword[and] keyword[not] identifier[setting] . identifier[is_global] : identifier[flags] = identifier[setting] . identifier[flags] identifier[setting] . identifier[orig_name] = identifier[setting] . identifier[name] identifier[setting] . identifier[name] = literal[string] %( identifier[prefix] , identifier[setting] . identifier[name] ) keyword[if] identifier[flags] keyword[and] identifier[flags] [- literal[int] ]. identifier[startswith] ( literal[string] ): identifier[setting] . identifier[flags] =[ literal[string] %( identifier[prefix] , identifier[flags] [- literal[int] ][ literal[int] :])] keyword[if] identifier[name] keyword[and] keyword[not] identifier[setting] . identifier[is_global] : identifier[setting] . identifier[short] = literal[string] %( identifier[name] , identifier[setting] . identifier[short] ) keyword[return] identifier[setting]
def copy(self, name=None, prefix=None): """Copy this :class:`SettingBase`""" setting = self.__class__.__new__(self.__class__) setting.__dict__.update(self.__dict__) # Keep the modified flag? # setting.modified = False if prefix and (not setting.is_global): flags = setting.flags # Prefix a setting setting.orig_name = setting.name setting.name = '%s_%s' % (prefix, setting.name) if flags and flags[-1].startswith('--'): setting.flags = ['--%s-%s' % (prefix, flags[-1][2:])] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if name and (not setting.is_global): setting.short = '%s application. %s' % (name, setting.short) # depends on [control=['if'], data=[]] return setting
def SetHighlight( self, node, point=None, propagate=True ): """Set the currently-highlighted node""" if node == self.highlightedNode: return self.highlightedNode = node # TODO: restrict refresh to the squares for previous node and new node... self.UpdateDrawing() if node and propagate: wx.PostEvent( self, SquareHighlightEvent( node=node, point=point, map=self ) )
def function[SetHighlight, parameter[self, node, point, propagate]]: constant[Set the currently-highlighted node] if compare[name[node] equal[==] name[self].highlightedNode] begin[:] return[None] name[self].highlightedNode assign[=] name[node] call[name[self].UpdateDrawing, parameter[]] if <ast.BoolOp object at 0x7da18f00d870> begin[:] call[name[wx].PostEvent, parameter[name[self], call[name[SquareHighlightEvent], parameter[]]]]
keyword[def] identifier[SetHighlight] ( identifier[self] , identifier[node] , identifier[point] = keyword[None] , identifier[propagate] = keyword[True] ): literal[string] keyword[if] identifier[node] == identifier[self] . identifier[highlightedNode] : keyword[return] identifier[self] . identifier[highlightedNode] = identifier[node] identifier[self] . identifier[UpdateDrawing] () keyword[if] identifier[node] keyword[and] identifier[propagate] : identifier[wx] . identifier[PostEvent] ( identifier[self] , identifier[SquareHighlightEvent] ( identifier[node] = identifier[node] , identifier[point] = identifier[point] , identifier[map] = identifier[self] ))
def SetHighlight(self, node, point=None, propagate=True): """Set the currently-highlighted node""" if node == self.highlightedNode: return # depends on [control=['if'], data=[]] self.highlightedNode = node # TODO: restrict refresh to the squares for previous node and new node... self.UpdateDrawing() if node and propagate: wx.PostEvent(self, SquareHighlightEvent(node=node, point=point, map=self)) # depends on [control=['if'], data=[]]
def display_html(*objs, **kwargs): """Display the HTML representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw HTML data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [default: False] """ raw = kwargs.pop('raw',False) if raw: for obj in objs: publish_html(obj) else: display(*objs, include=['text/plain','text/html'])
def function[display_html, parameter[]]: constant[Display the HTML representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw HTML data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [default: False] ] variable[raw] assign[=] call[name[kwargs].pop, parameter[constant[raw], constant[False]]] if name[raw] begin[:] for taget[name[obj]] in starred[name[objs]] begin[:] call[name[publish_html], parameter[name[obj]]]
keyword[def] identifier[display_html] (* identifier[objs] ,** identifier[kwargs] ): literal[string] identifier[raw] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] ) keyword[if] identifier[raw] : keyword[for] identifier[obj] keyword[in] identifier[objs] : identifier[publish_html] ( identifier[obj] ) keyword[else] : identifier[display] (* identifier[objs] , identifier[include] =[ literal[string] , literal[string] ])
def display_html(*objs, **kwargs): """Display the HTML representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw HTML data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [default: False] """ raw = kwargs.pop('raw', False) if raw: for obj in objs: publish_html(obj) # depends on [control=['for'], data=['obj']] # depends on [control=['if'], data=[]] else: display(*objs, include=['text/plain', 'text/html'])
def replace_tax_class_by_id(cls, tax_class_id, tax_class, **kwargs): """Replace TaxClass Replace all attributes of TaxClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_class_by_id(tax_class_id, tax_class, async=True) >>> result = thread.get() :param async bool :param str tax_class_id: ID of taxClass to replace (required) :param TaxClass tax_class: Attributes of taxClass to replace (required) :return: TaxClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_tax_class_by_id_with_http_info(tax_class_id, tax_class, **kwargs) else: (data) = cls._replace_tax_class_by_id_with_http_info(tax_class_id, tax_class, **kwargs) return data
def function[replace_tax_class_by_id, parameter[cls, tax_class_id, tax_class]]: constant[Replace TaxClass Replace all attributes of TaxClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_class_by_id(tax_class_id, tax_class, async=True) >>> result = thread.get() :param async bool :param str tax_class_id: ID of taxClass to replace (required) :param TaxClass tax_class: Attributes of taxClass to replace (required) :return: TaxClass If the method is called asynchronously, returns the request thread. ] call[name[kwargs]][constant[_return_http_data_only]] assign[=] constant[True] if call[name[kwargs].get, parameter[constant[async]]] begin[:] return[call[name[cls]._replace_tax_class_by_id_with_http_info, parameter[name[tax_class_id], name[tax_class]]]]
keyword[def] identifier[replace_tax_class_by_id] ( identifier[cls] , identifier[tax_class_id] , identifier[tax_class] ,** identifier[kwargs] ): literal[string] identifier[kwargs] [ literal[string] ]= keyword[True] keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ): keyword[return] identifier[cls] . identifier[_replace_tax_class_by_id_with_http_info] ( identifier[tax_class_id] , identifier[tax_class] ,** identifier[kwargs] ) keyword[else] : ( identifier[data] )= identifier[cls] . identifier[_replace_tax_class_by_id_with_http_info] ( identifier[tax_class_id] , identifier[tax_class] ,** identifier[kwargs] ) keyword[return] identifier[data]
def replace_tax_class_by_id(cls, tax_class_id, tax_class, **kwargs): """Replace TaxClass Replace all attributes of TaxClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_class_by_id(tax_class_id, tax_class, async=True) >>> result = thread.get() :param async bool :param str tax_class_id: ID of taxClass to replace (required) :param TaxClass tax_class: Attributes of taxClass to replace (required) :return: TaxClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_tax_class_by_id_with_http_info(tax_class_id, tax_class, **kwargs) # depends on [control=['if'], data=[]] else: data = cls._replace_tax_class_by_id_with_http_info(tax_class_id, tax_class, **kwargs) return data
def getExpressionLevelById(self, expressionId): """ :param expressionId: the ExpressionLevel ID :return: dictionary representing an ExpressionLevel object, or None if no match is found. """ sql = ("SELECT * FROM Expression WHERE id = ?") query = self._dbconn.execute(sql, (expressionId,)) try: return sqlite_backend.fetchOne(query) except AttributeError: raise exceptions.ExpressionLevelNotFoundException( expressionId)
def function[getExpressionLevelById, parameter[self, expressionId]]: constant[ :param expressionId: the ExpressionLevel ID :return: dictionary representing an ExpressionLevel object, or None if no match is found. ] variable[sql] assign[=] constant[SELECT * FROM Expression WHERE id = ?] variable[query] assign[=] call[name[self]._dbconn.execute, parameter[name[sql], tuple[[<ast.Name object at 0x7da18f00f5e0>]]]] <ast.Try object at 0x7da18f00e020>
keyword[def] identifier[getExpressionLevelById] ( identifier[self] , identifier[expressionId] ): literal[string] identifier[sql] =( literal[string] ) identifier[query] = identifier[self] . identifier[_dbconn] . identifier[execute] ( identifier[sql] ,( identifier[expressionId] ,)) keyword[try] : keyword[return] identifier[sqlite_backend] . identifier[fetchOne] ( identifier[query] ) keyword[except] identifier[AttributeError] : keyword[raise] identifier[exceptions] . identifier[ExpressionLevelNotFoundException] ( identifier[expressionId] )
def getExpressionLevelById(self, expressionId): """ :param expressionId: the ExpressionLevel ID :return: dictionary representing an ExpressionLevel object, or None if no match is found. """ sql = 'SELECT * FROM Expression WHERE id = ?' query = self._dbconn.execute(sql, (expressionId,)) try: return sqlite_backend.fetchOne(query) # depends on [control=['try'], data=[]] except AttributeError: raise exceptions.ExpressionLevelNotFoundException(expressionId) # depends on [control=['except'], data=[]]
def combine_first(self, other): """ Combine Series values, choosing the calling Series's values first. Parameters ---------- other : Series The value(s) to be combined with the `Series`. Returns ------- Series The result of combining the Series with the other object. See Also -------- Series.combine : Perform elementwise operation on two Series using a given function. Notes ----- Result index will be the union of the two indexes. Examples -------- >>> s1 = pd.Series([1, np.nan]) >>> s2 = pd.Series([3, 4]) >>> s1.combine_first(s2) 0 1.0 1 4.0 dtype: float64 """ new_index = self.index.union(other.index) this = self.reindex(new_index, copy=False) other = other.reindex(new_index, copy=False) if is_datetimelike(this) and not is_datetimelike(other): other = to_datetime(other) return this.where(notna(this), other)
def function[combine_first, parameter[self, other]]: constant[ Combine Series values, choosing the calling Series's values first. Parameters ---------- other : Series The value(s) to be combined with the `Series`. Returns ------- Series The result of combining the Series with the other object. See Also -------- Series.combine : Perform elementwise operation on two Series using a given function. Notes ----- Result index will be the union of the two indexes. Examples -------- >>> s1 = pd.Series([1, np.nan]) >>> s2 = pd.Series([3, 4]) >>> s1.combine_first(s2) 0 1.0 1 4.0 dtype: float64 ] variable[new_index] assign[=] call[name[self].index.union, parameter[name[other].index]] variable[this] assign[=] call[name[self].reindex, parameter[name[new_index]]] variable[other] assign[=] call[name[other].reindex, parameter[name[new_index]]] if <ast.BoolOp object at 0x7da1b1eb49d0> begin[:] variable[other] assign[=] call[name[to_datetime], parameter[name[other]]] return[call[name[this].where, parameter[call[name[notna], parameter[name[this]]], name[other]]]]
keyword[def] identifier[combine_first] ( identifier[self] , identifier[other] ): literal[string] identifier[new_index] = identifier[self] . identifier[index] . identifier[union] ( identifier[other] . identifier[index] ) identifier[this] = identifier[self] . identifier[reindex] ( identifier[new_index] , identifier[copy] = keyword[False] ) identifier[other] = identifier[other] . identifier[reindex] ( identifier[new_index] , identifier[copy] = keyword[False] ) keyword[if] identifier[is_datetimelike] ( identifier[this] ) keyword[and] keyword[not] identifier[is_datetimelike] ( identifier[other] ): identifier[other] = identifier[to_datetime] ( identifier[other] ) keyword[return] identifier[this] . identifier[where] ( identifier[notna] ( identifier[this] ), identifier[other] )
def combine_first(self, other): """ Combine Series values, choosing the calling Series's values first. Parameters ---------- other : Series The value(s) to be combined with the `Series`. Returns ------- Series The result of combining the Series with the other object. See Also -------- Series.combine : Perform elementwise operation on two Series using a given function. Notes ----- Result index will be the union of the two indexes. Examples -------- >>> s1 = pd.Series([1, np.nan]) >>> s2 = pd.Series([3, 4]) >>> s1.combine_first(s2) 0 1.0 1 4.0 dtype: float64 """ new_index = self.index.union(other.index) this = self.reindex(new_index, copy=False) other = other.reindex(new_index, copy=False) if is_datetimelike(this) and (not is_datetimelike(other)): other = to_datetime(other) # depends on [control=['if'], data=[]] return this.where(notna(this), other)
def source_roots(self, document_path): """Return the source roots for the given document.""" files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or [] return [os.path.dirname(setup_py) for setup_py in files]
def function[source_roots, parameter[self, document_path]]: constant[Return the source roots for the given document.] variable[files] assign[=] <ast.BoolOp object at 0x7da18f723f40> return[<ast.ListComp object at 0x7da18f721990>]
keyword[def] identifier[source_roots] ( identifier[self] , identifier[document_path] ): literal[string] identifier[files] = identifier[_utils] . identifier[find_parents] ( identifier[self] . identifier[_root_path] , identifier[document_path] ,[ literal[string] ]) keyword[or] [] keyword[return] [ identifier[os] . identifier[path] . identifier[dirname] ( identifier[setup_py] ) keyword[for] identifier[setup_py] keyword[in] identifier[files] ]
def source_roots(self, document_path): """Return the source roots for the given document.""" files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or [] return [os.path.dirname(setup_py) for setup_py in files]
def sleep(self, delay): """ Inline sleep for use in co-routines. :param delay: Time to sleep in seconds. :type delay: float """ d = Deferred() self._get_loop().callLater(delay, d.callback, None) return d
def function[sleep, parameter[self, delay]]: constant[ Inline sleep for use in co-routines. :param delay: Time to sleep in seconds. :type delay: float ] variable[d] assign[=] call[name[Deferred], parameter[]] call[call[name[self]._get_loop, parameter[]].callLater, parameter[name[delay], name[d].callback, constant[None]]] return[name[d]]
keyword[def] identifier[sleep] ( identifier[self] , identifier[delay] ): literal[string] identifier[d] = identifier[Deferred] () identifier[self] . identifier[_get_loop] (). identifier[callLater] ( identifier[delay] , identifier[d] . identifier[callback] , keyword[None] ) keyword[return] identifier[d]
def sleep(self, delay): """ Inline sleep for use in co-routines. :param delay: Time to sleep in seconds. :type delay: float """ d = Deferred() self._get_loop().callLater(delay, d.callback, None) return d
def angle_to_name(angle, segments=8, abbr=False): """Convert angle in to direction name. Args: angle (float): Angle in degrees to convert to direction name segments (int): Number of segments to split compass in to abbr (bool): Whether to return abbreviated direction string Returns: str: Direction name for ``angle`` """ if segments == 4: string = COMPASS_NAMES[int((angle + 45) / 90) % 4 * 2] elif segments == 8: string = COMPASS_NAMES[int((angle + 22.5) / 45) % 8 * 2] elif segments == 16: string = COMPASS_NAMES[int((angle + 11.25) / 22.5) % 16] else: raise ValueError('Segments parameter must be 4, 8 or 16 not %r' % segments) if abbr: return ''.join(i[0].capitalize() for i in string.split('-')) else: return string
def function[angle_to_name, parameter[angle, segments, abbr]]: constant[Convert angle in to direction name. Args: angle (float): Angle in degrees to convert to direction name segments (int): Number of segments to split compass in to abbr (bool): Whether to return abbreviated direction string Returns: str: Direction name for ``angle`` ] if compare[name[segments] equal[==] constant[4]] begin[:] variable[string] assign[=] call[name[COMPASS_NAMES]][binary_operation[binary_operation[call[name[int], parameter[binary_operation[binary_operation[name[angle] + constant[45]] / constant[90]]]] <ast.Mod object at 0x7da2590d6920> constant[4]] * constant[2]]] if name[abbr] begin[:] return[call[constant[].join, parameter[<ast.GeneratorExp object at 0x7da18dc05a50>]]]
keyword[def] identifier[angle_to_name] ( identifier[angle] , identifier[segments] = literal[int] , identifier[abbr] = keyword[False] ): literal[string] keyword[if] identifier[segments] == literal[int] : identifier[string] = identifier[COMPASS_NAMES] [ identifier[int] (( identifier[angle] + literal[int] )/ literal[int] )% literal[int] * literal[int] ] keyword[elif] identifier[segments] == literal[int] : identifier[string] = identifier[COMPASS_NAMES] [ identifier[int] (( identifier[angle] + literal[int] )/ literal[int] )% literal[int] * literal[int] ] keyword[elif] identifier[segments] == literal[int] : identifier[string] = identifier[COMPASS_NAMES] [ identifier[int] (( identifier[angle] + literal[int] )/ literal[int] )% literal[int] ] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] % identifier[segments] ) keyword[if] identifier[abbr] : keyword[return] literal[string] . identifier[join] ( identifier[i] [ literal[int] ]. identifier[capitalize] () keyword[for] identifier[i] keyword[in] identifier[string] . identifier[split] ( literal[string] )) keyword[else] : keyword[return] identifier[string]
def angle_to_name(angle, segments=8, abbr=False): """Convert angle in to direction name. Args: angle (float): Angle in degrees to convert to direction name segments (int): Number of segments to split compass in to abbr (bool): Whether to return abbreviated direction string Returns: str: Direction name for ``angle`` """ if segments == 4: string = COMPASS_NAMES[int((angle + 45) / 90) % 4 * 2] # depends on [control=['if'], data=[]] elif segments == 8: string = COMPASS_NAMES[int((angle + 22.5) / 45) % 8 * 2] # depends on [control=['if'], data=[]] elif segments == 16: string = COMPASS_NAMES[int((angle + 11.25) / 22.5) % 16] # depends on [control=['if'], data=[]] else: raise ValueError('Segments parameter must be 4, 8 or 16 not %r' % segments) if abbr: return ''.join((i[0].capitalize() for i in string.split('-'))) # depends on [control=['if'], data=[]] else: return string
def table_api_get(self, *paths, **kparams): """ helper to make GET /api/now/v1/table requests """ url = self.flattened_params_url("/api/now/v1/table", *paths, **kparams) rjson = self.req("get", url).text return json.loads(rjson)
def function[table_api_get, parameter[self]]: constant[ helper to make GET /api/now/v1/table requests ] variable[url] assign[=] call[name[self].flattened_params_url, parameter[constant[/api/now/v1/table], <ast.Starred object at 0x7da18dc99300>]] variable[rjson] assign[=] call[name[self].req, parameter[constant[get], name[url]]].text return[call[name[json].loads, parameter[name[rjson]]]]
keyword[def] identifier[table_api_get] ( identifier[self] ,* identifier[paths] ,** identifier[kparams] ): literal[string] identifier[url] = identifier[self] . identifier[flattened_params_url] ( literal[string] ,* identifier[paths] ,** identifier[kparams] ) identifier[rjson] = identifier[self] . identifier[req] ( literal[string] , identifier[url] ). identifier[text] keyword[return] identifier[json] . identifier[loads] ( identifier[rjson] )
def table_api_get(self, *paths, **kparams): """ helper to make GET /api/now/v1/table requests """ url = self.flattened_params_url('/api/now/v1/table', *paths, **kparams) rjson = self.req('get', url).text return json.loads(rjson)
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z, phi INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z,phi) HISTORY: 2011-04-10 - Started - Bovy (NYU) 2018-10-18 - Updated for general object potential - James Lane (UofT) """ #Cylindrical distance Rdist = _cylR(R,phi,self._orb.R(t),self._orb.phi(t)) #Evaluate potential return evaluatePotentials( self._pot, Rdist, self._orb.z(t)-z, use_physical=False)
def function[_evaluate, parameter[self, R, z, phi, t]]: constant[ NAME: _evaluate PURPOSE: evaluate the potential at R,z, phi INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z,phi) HISTORY: 2011-04-10 - Started - Bovy (NYU) 2018-10-18 - Updated for general object potential - James Lane (UofT) ] variable[Rdist] assign[=] call[name[_cylR], parameter[name[R], name[phi], call[name[self]._orb.R, parameter[name[t]]], call[name[self]._orb.phi, parameter[name[t]]]]] return[call[name[evaluatePotentials], parameter[name[self]._pot, name[Rdist], binary_operation[call[name[self]._orb.z, parameter[name[t]]] - name[z]]]]]
keyword[def] identifier[_evaluate] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ): literal[string] identifier[Rdist] = identifier[_cylR] ( identifier[R] , identifier[phi] , identifier[self] . identifier[_orb] . identifier[R] ( identifier[t] ), identifier[self] . identifier[_orb] . identifier[phi] ( identifier[t] )) keyword[return] identifier[evaluatePotentials] ( identifier[self] . identifier[_pot] , identifier[Rdist] , identifier[self] . identifier[_orb] . identifier[z] ( identifier[t] )- identifier[z] , identifier[use_physical] = keyword[False] )
def _evaluate(self, R, z, phi=0.0, t=0.0): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z, phi INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z,phi) HISTORY: 2011-04-10 - Started - Bovy (NYU) 2018-10-18 - Updated for general object potential - James Lane (UofT) """ #Cylindrical distance Rdist = _cylR(R, phi, self._orb.R(t), self._orb.phi(t)) #Evaluate potential return evaluatePotentials(self._pot, Rdist, self._orb.z(t) - z, use_physical=False)
def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool: """Extract the variable substitution for the given pattern and subject. This assumes that subject and pattern already match when being considered as linear. Also, they both must be :term:`syntactic`, as sequence variables cannot be handled here. All that this method does is checking whether all the substitutions for the variables can be unified. So, in case it returns ``False``, the substitution is invalid for the match. ..warning:: This method mutates the substitution and will even do so in case the extraction fails. Create a copy before using this method if you need to preserve the original substitution. Example: With an empty initial substitution and a linear pattern, the extraction will always succeed: >>> subst = Substitution() >>> subst.extract_substitution(f(a, b), f(x_, y_)) True >>> print(subst) {x ↦ a, y ↦ b} Clashing values for existing variables will fail: >>> subst.extract_substitution(b, x_) False For non-linear patterns, the extraction can also fail with an empty substitution: >>> subst = Substitution() >>> subst.extract_substitution(f(a, b), f(x_, x_)) False >>> print(subst) {x ↦ a} Note that the initial substitution got mutated even though the extraction failed! Args: subject: A :term:`syntactic` subject that matches the pattern. pattern: A :term:`syntactic` pattern that matches the subject. Returns: ``True`` iff the substitution could be extracted successfully. """ if getattr(pattern, 'variable_name', False): try: self.try_add_variable(pattern.variable_name, subject) except ValueError: return False return True elif isinstance(pattern, expressions.Operation): assert isinstance(subject, type(pattern)) assert op_len(subject) == op_len(pattern) op_expression = cast(expressions.Operation, subject) for subj, patt in zip(op_iter(op_expression), op_iter(pattern)): if not self.extract_substitution(subj, patt): return False return True
def function[extract_substitution, parameter[self, subject, pattern]]: constant[Extract the variable substitution for the given pattern and subject. This assumes that subject and pattern already match when being considered as linear. Also, they both must be :term:`syntactic`, as sequence variables cannot be handled here. All that this method does is checking whether all the substitutions for the variables can be unified. So, in case it returns ``False``, the substitution is invalid for the match. ..warning:: This method mutates the substitution and will even do so in case the extraction fails. Create a copy before using this method if you need to preserve the original substitution. Example: With an empty initial substitution and a linear pattern, the extraction will always succeed: >>> subst = Substitution() >>> subst.extract_substitution(f(a, b), f(x_, y_)) True >>> print(subst) {x ↦ a, y ↦ b} Clashing values for existing variables will fail: >>> subst.extract_substitution(b, x_) False For non-linear patterns, the extraction can also fail with an empty substitution: >>> subst = Substitution() >>> subst.extract_substitution(f(a, b), f(x_, x_)) False >>> print(subst) {x ↦ a} Note that the initial substitution got mutated even though the extraction failed! Args: subject: A :term:`syntactic` subject that matches the pattern. pattern: A :term:`syntactic` pattern that matches the subject. Returns: ``True`` iff the substitution could be extracted successfully. ] if call[name[getattr], parameter[name[pattern], constant[variable_name], constant[False]]] begin[:] <ast.Try object at 0x7da1b06be3e0> return[constant[True]] return[constant[True]]
keyword[def] identifier[extract_substitution] ( identifier[self] , identifier[subject] : literal[string] , identifier[pattern] : literal[string] )-> identifier[bool] : literal[string] keyword[if] identifier[getattr] ( identifier[pattern] , literal[string] , keyword[False] ): keyword[try] : identifier[self] . identifier[try_add_variable] ( identifier[pattern] . identifier[variable_name] , identifier[subject] ) keyword[except] identifier[ValueError] : keyword[return] keyword[False] keyword[return] keyword[True] keyword[elif] identifier[isinstance] ( identifier[pattern] , identifier[expressions] . identifier[Operation] ): keyword[assert] identifier[isinstance] ( identifier[subject] , identifier[type] ( identifier[pattern] )) keyword[assert] identifier[op_len] ( identifier[subject] )== identifier[op_len] ( identifier[pattern] ) identifier[op_expression] = identifier[cast] ( identifier[expressions] . identifier[Operation] , identifier[subject] ) keyword[for] identifier[subj] , identifier[patt] keyword[in] identifier[zip] ( identifier[op_iter] ( identifier[op_expression] ), identifier[op_iter] ( identifier[pattern] )): keyword[if] keyword[not] identifier[self] . identifier[extract_substitution] ( identifier[subj] , identifier[patt] ): keyword[return] keyword[False] keyword[return] keyword[True]
def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool: """Extract the variable substitution for the given pattern and subject. This assumes that subject and pattern already match when being considered as linear. Also, they both must be :term:`syntactic`, as sequence variables cannot be handled here. All that this method does is checking whether all the substitutions for the variables can be unified. So, in case it returns ``False``, the substitution is invalid for the match. ..warning:: This method mutates the substitution and will even do so in case the extraction fails. Create a copy before using this method if you need to preserve the original substitution. Example: With an empty initial substitution and a linear pattern, the extraction will always succeed: >>> subst = Substitution() >>> subst.extract_substitution(f(a, b), f(x_, y_)) True >>> print(subst) {x ↦ a, y ↦ b} Clashing values for existing variables will fail: >>> subst.extract_substitution(b, x_) False For non-linear patterns, the extraction can also fail with an empty substitution: >>> subst = Substitution() >>> subst.extract_substitution(f(a, b), f(x_, x_)) False >>> print(subst) {x ↦ a} Note that the initial substitution got mutated even though the extraction failed! Args: subject: A :term:`syntactic` subject that matches the pattern. pattern: A :term:`syntactic` pattern that matches the subject. Returns: ``True`` iff the substitution could be extracted successfully. """ if getattr(pattern, 'variable_name', False): try: self.try_add_variable(pattern.variable_name, subject) # depends on [control=['try'], data=[]] except ValueError: return False # depends on [control=['except'], data=[]] return True # depends on [control=['if'], data=[]] elif isinstance(pattern, expressions.Operation): assert isinstance(subject, type(pattern)) assert op_len(subject) == op_len(pattern) op_expression = cast(expressions.Operation, subject) for (subj, patt) in zip(op_iter(op_expression), op_iter(pattern)): if not self.extract_substitution(subj, patt): return False # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]] return True
def encode(self, envelope, session, aes_cipher=None, **kwargs): """ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation. :param envelope: original envelope :param session: original session :param aes_cipher: cipher to use :param kwargs: additional arguments :return: WMessengerBytesEnvelope """ return WMessengerBytesEnvelope(aes_cipher.encrypt(envelope.message()), meta=envelope)
def function[encode, parameter[self, envelope, session, aes_cipher]]: constant[ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation. :param envelope: original envelope :param session: original session :param aes_cipher: cipher to use :param kwargs: additional arguments :return: WMessengerBytesEnvelope ] return[call[name[WMessengerBytesEnvelope], parameter[call[name[aes_cipher].encrypt, parameter[call[name[envelope].message, parameter[]]]]]]]
keyword[def] identifier[encode] ( identifier[self] , identifier[envelope] , identifier[session] , identifier[aes_cipher] = keyword[None] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[WMessengerBytesEnvelope] ( identifier[aes_cipher] . identifier[encrypt] ( identifier[envelope] . identifier[message] ()), identifier[meta] = identifier[envelope] )
def encode(self, envelope, session, aes_cipher=None, **kwargs): """ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation. :param envelope: original envelope :param session: original session :param aes_cipher: cipher to use :param kwargs: additional arguments :return: WMessengerBytesEnvelope """ return WMessengerBytesEnvelope(aes_cipher.encrypt(envelope.message()), meta=envelope)
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0): '''Return list N+1 points representing N line segments on bezier curve defined by control points P. ''' assert isinstance(P, list) assert len(P) > 0 for p in P: assert isinstance(p, tuple) for i in p: assert len(p) > 1 assert isinstance(i, float) assert isinstance(n_seg, int) assert n_seg >= 0 return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]
def function[pts_on_bezier_curve, parameter[P, n_seg]]: constant[Return list N+1 points representing N line segments on bezier curve defined by control points P. ] assert[call[name[isinstance], parameter[name[P], name[list]]]] assert[compare[call[name[len], parameter[name[P]]] greater[>] constant[0]]] for taget[name[p]] in starred[name[P]] begin[:] assert[call[name[isinstance], parameter[name[p], name[tuple]]]] for taget[name[i]] in starred[name[p]] begin[:] assert[compare[call[name[len], parameter[name[p]]] greater[>] constant[1]]] assert[call[name[isinstance], parameter[name[i], name[float]]]] assert[call[name[isinstance], parameter[name[n_seg], name[int]]]] assert[compare[name[n_seg] greater_or_equal[>=] constant[0]]] return[binary_operation[<ast.ListComp object at 0x7da18ede68c0> + list[[<ast.Subscript object at 0x7da2044c27d0>]]]]
keyword[def] identifier[pts_on_bezier_curve] ( identifier[P] =[( literal[int] , literal[int] )], identifier[n_seg] = literal[int] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[P] , identifier[list] ) keyword[assert] identifier[len] ( identifier[P] )> literal[int] keyword[for] identifier[p] keyword[in] identifier[P] : keyword[assert] identifier[isinstance] ( identifier[p] , identifier[tuple] ) keyword[for] identifier[i] keyword[in] identifier[p] : keyword[assert] identifier[len] ( identifier[p] )> literal[int] keyword[assert] identifier[isinstance] ( identifier[i] , identifier[float] ) keyword[assert] identifier[isinstance] ( identifier[n_seg] , identifier[int] ) keyword[assert] identifier[n_seg] >= literal[int] keyword[return] [ identifier[pt_on_bezier_curve] ( identifier[P] , identifier[float] ( identifier[i] )/ identifier[n_seg] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[n_seg] )]+[ identifier[P] [- literal[int] ]]
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0): """Return list N+1 points representing N line segments on bezier curve defined by control points P. """ assert isinstance(P, list) assert len(P) > 0 for p in P: assert isinstance(p, tuple) for i in p: assert len(p) > 1 assert isinstance(i, float) # depends on [control=['for'], data=['i']] # depends on [control=['for'], data=['p']] assert isinstance(n_seg, int) assert n_seg >= 0 return [pt_on_bezier_curve(P, float(i) / n_seg) for i in range(n_seg)] + [P[-1]]
def _normalize_date_SQL(self, field_name, field_kwargs, symbol): """ allow extracting information from date http://www.sqlite.org/lang_datefunc.html """ fstrs = [] k_opts = { 'day': "CAST(strftime('%d', {}) AS integer)", 'hour': "CAST(strftime('%H', {}) AS integer)", 'doy': "CAST(strftime('%j', {}) AS integer)", # day of year 'julian_day': "strftime('%J', {})", # YYYY-MM-DD 'month': "CAST(strftime('%m', {}) AS integer)", 'minute': "CAST(strftime('%M', {}) AS integer)", 'dow': "CAST(strftime('%w', {}) AS integer)", # day of week 0 = sunday 'week': "CAST(strftime('%W', {}) AS integer)", 'year': "CAST(strftime('%Y', {}) AS integer)" } for k, v in field_kwargs.items(): fstrs.append([k_opts[k].format(self._normalize_name(field_name)), self.val_placeholder, v]) return fstrs
def function[_normalize_date_SQL, parameter[self, field_name, field_kwargs, symbol]]: constant[ allow extracting information from date http://www.sqlite.org/lang_datefunc.html ] variable[fstrs] assign[=] list[[]] variable[k_opts] assign[=] dictionary[[<ast.Constant object at 0x7da18ede6c20>, <ast.Constant object at 0x7da18ede5240>, <ast.Constant object at 0x7da18ede61a0>, <ast.Constant object at 0x7da18ede5780>, <ast.Constant object at 0x7da18ede4f10>, <ast.Constant object at 0x7da18ede6c50>, <ast.Constant object at 0x7da18ede6590>, <ast.Constant object at 0x7da18ede43a0>, <ast.Constant object at 0x7da18ede7220>], [<ast.Constant object at 0x7da18ede7340>, <ast.Constant object at 0x7da18ede6a70>, <ast.Constant object at 0x7da18ede4970>, <ast.Constant object at 0x7da18ede7610>, <ast.Constant object at 0x7da18ede5510>, <ast.Constant object at 0x7da18ede7a00>, <ast.Constant object at 0x7da18ede4700>, <ast.Constant object at 0x7da18ede4f70>, <ast.Constant object at 0x7da18ede5de0>]] for taget[tuple[[<ast.Name object at 0x7da18ede5330>, <ast.Name object at 0x7da18ede68c0>]]] in starred[call[name[field_kwargs].items, parameter[]]] begin[:] call[name[fstrs].append, parameter[list[[<ast.Call object at 0x7da18ede6bf0>, <ast.Attribute object at 0x7da18ede6e00>, <ast.Name object at 0x7da18ede4be0>]]]] return[name[fstrs]]
keyword[def] identifier[_normalize_date_SQL] ( identifier[self] , identifier[field_name] , identifier[field_kwargs] , identifier[symbol] ): literal[string] identifier[fstrs] =[] identifier[k_opts] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] } keyword[for] identifier[k] , identifier[v] keyword[in] identifier[field_kwargs] . identifier[items] (): identifier[fstrs] . identifier[append] ([ identifier[k_opts] [ identifier[k] ]. identifier[format] ( identifier[self] . identifier[_normalize_name] ( identifier[field_name] )), identifier[self] . identifier[val_placeholder] , identifier[v] ]) keyword[return] identifier[fstrs]
def _normalize_date_SQL(self, field_name, field_kwargs, symbol): """ allow extracting information from date http://www.sqlite.org/lang_datefunc.html """ fstrs = [] # day of year # YYYY-MM-DD # day of week 0 = sunday k_opts = {'day': "CAST(strftime('%d', {}) AS integer)", 'hour': "CAST(strftime('%H', {}) AS integer)", 'doy': "CAST(strftime('%j', {}) AS integer)", 'julian_day': "strftime('%J', {})", 'month': "CAST(strftime('%m', {}) AS integer)", 'minute': "CAST(strftime('%M', {}) AS integer)", 'dow': "CAST(strftime('%w', {}) AS integer)", 'week': "CAST(strftime('%W', {}) AS integer)", 'year': "CAST(strftime('%Y', {}) AS integer)"} for (k, v) in field_kwargs.items(): fstrs.append([k_opts[k].format(self._normalize_name(field_name)), self.val_placeholder, v]) # depends on [control=['for'], data=[]] return fstrs
def getcoordinates(self, tree, location): """Gets coordinates from a specific element in PLIP XML""" return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))
def function[getcoordinates, parameter[self, tree, location]]: constant[Gets coordinates from a specific element in PLIP XML] return[call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da18f09e0e0>]]]
keyword[def] identifier[getcoordinates] ( identifier[self] , identifier[tree] , identifier[location] ): literal[string] keyword[return] identifier[tuple] ( identifier[float] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[tree] . identifier[xpath] ( literal[string] % identifier[location] ))
def getcoordinates(self, tree, location): """Gets coordinates from a specific element in PLIP XML""" return tuple((float(x) for x in tree.xpath('.//%s/*/text()' % location)))
def class_result(classname): """Errcheck function. Returns a function that creates the specified class. """ def wrap_errcheck(result, func, arguments): if result is None: return None return classname(result) return wrap_errcheck
def function[class_result, parameter[classname]]: constant[Errcheck function. Returns a function that creates the specified class. ] def function[wrap_errcheck, parameter[result, func, arguments]]: if compare[name[result] is constant[None]] begin[:] return[constant[None]] return[call[name[classname], parameter[name[result]]]] return[name[wrap_errcheck]]
keyword[def] identifier[class_result] ( identifier[classname] ): literal[string] keyword[def] identifier[wrap_errcheck] ( identifier[result] , identifier[func] , identifier[arguments] ): keyword[if] identifier[result] keyword[is] keyword[None] : keyword[return] keyword[None] keyword[return] identifier[classname] ( identifier[result] ) keyword[return] identifier[wrap_errcheck]
def class_result(classname): """Errcheck function. Returns a function that creates the specified class. """ def wrap_errcheck(result, func, arguments): if result is None: return None # depends on [control=['if'], data=[]] return classname(result) return wrap_errcheck
def clear_file(self, label): """stub""" rm = self.my_osid_object_form._get_provider_manager('REPOSITORY') catalog_id_str = '' if 'assignedBankIds' in self.my_osid_object_form._my_map: catalog_id_str = self.my_osid_object_form._my_map['assignedBankIds'][0] elif 'assignedRepositoryIds' in self.my_osid_object_form._my_map: catalog_id_str = self.my_osid_object_form._my_map['assignedRepositoryIds'][0] try: try: aas = rm.get_asset_admin_session_for_repository( Id(catalog_id_str), self.my_osid_object_form._proxy) except NullArgument: aas = rm.get_asset_admin_session_for_repository( Id(catalog_id_str)) except AttributeError: # for update forms try: aas = rm.get_asset_admin_session_for_repository( Id(catalog_id_str), self.my_osid_object_form._proxy) except NullArgument: aas = rm.get_asset_admin_session_for_repository( Id(catalog_id_str)) if label not in self.my_osid_object_form._my_map['fileIds']: raise NotFound() aas.delete_asset(Id(self.my_osid_object_form._my_map['fileIds'][label]['assetId'])) del self.my_osid_object_form._my_map['fileIds'][label]
def function[clear_file, parameter[self, label]]: constant[stub] variable[rm] assign[=] call[name[self].my_osid_object_form._get_provider_manager, parameter[constant[REPOSITORY]]] variable[catalog_id_str] assign[=] constant[] if compare[constant[assignedBankIds] in name[self].my_osid_object_form._my_map] begin[:] variable[catalog_id_str] assign[=] call[call[name[self].my_osid_object_form._my_map][constant[assignedBankIds]]][constant[0]] <ast.Try object at 0x7da20c993e20> if compare[name[label] <ast.NotIn object at 0x7da2590d7190> call[name[self].my_osid_object_form._my_map][constant[fileIds]]] begin[:] <ast.Raise object at 0x7da204623040> call[name[aas].delete_asset, parameter[call[name[Id], parameter[call[call[call[name[self].my_osid_object_form._my_map][constant[fileIds]]][name[label]]][constant[assetId]]]]]] <ast.Delete object at 0x7da204623820>
keyword[def] identifier[clear_file] ( identifier[self] , identifier[label] ): literal[string] identifier[rm] = identifier[self] . identifier[my_osid_object_form] . identifier[_get_provider_manager] ( literal[string] ) identifier[catalog_id_str] = literal[string] keyword[if] literal[string] keyword[in] identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] : identifier[catalog_id_str] = identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ][ literal[int] ] keyword[elif] literal[string] keyword[in] identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] : identifier[catalog_id_str] = identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ][ literal[int] ] keyword[try] : keyword[try] : identifier[aas] = identifier[rm] . identifier[get_asset_admin_session_for_repository] ( identifier[Id] ( identifier[catalog_id_str] ), identifier[self] . identifier[my_osid_object_form] . identifier[_proxy] ) keyword[except] identifier[NullArgument] : identifier[aas] = identifier[rm] . identifier[get_asset_admin_session_for_repository] ( identifier[Id] ( identifier[catalog_id_str] )) keyword[except] identifier[AttributeError] : keyword[try] : identifier[aas] = identifier[rm] . identifier[get_asset_admin_session_for_repository] ( identifier[Id] ( identifier[catalog_id_str] ), identifier[self] . identifier[my_osid_object_form] . identifier[_proxy] ) keyword[except] identifier[NullArgument] : identifier[aas] = identifier[rm] . identifier[get_asset_admin_session_for_repository] ( identifier[Id] ( identifier[catalog_id_str] )) keyword[if] identifier[label] keyword[not] keyword[in] identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ]: keyword[raise] identifier[NotFound] () identifier[aas] . identifier[delete_asset] ( identifier[Id] ( identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ][ identifier[label] ][ literal[string] ])) keyword[del] identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ][ identifier[label] ]
def clear_file(self, label): """stub""" rm = self.my_osid_object_form._get_provider_manager('REPOSITORY') catalog_id_str = '' if 'assignedBankIds' in self.my_osid_object_form._my_map: catalog_id_str = self.my_osid_object_form._my_map['assignedBankIds'][0] # depends on [control=['if'], data=[]] elif 'assignedRepositoryIds' in self.my_osid_object_form._my_map: catalog_id_str = self.my_osid_object_form._my_map['assignedRepositoryIds'][0] # depends on [control=['if'], data=[]] try: try: aas = rm.get_asset_admin_session_for_repository(Id(catalog_id_str), self.my_osid_object_form._proxy) # depends on [control=['try'], data=[]] except NullArgument: aas = rm.get_asset_admin_session_for_repository(Id(catalog_id_str)) # depends on [control=['except'], data=[]] # depends on [control=['try'], data=[]] except AttributeError: # for update forms try: aas = rm.get_asset_admin_session_for_repository(Id(catalog_id_str), self.my_osid_object_form._proxy) # depends on [control=['try'], data=[]] except NullArgument: aas = rm.get_asset_admin_session_for_repository(Id(catalog_id_str)) # depends on [control=['except'], data=[]] # depends on [control=['except'], data=[]] if label not in self.my_osid_object_form._my_map['fileIds']: raise NotFound() # depends on [control=['if'], data=[]] aas.delete_asset(Id(self.my_osid_object_form._my_map['fileIds'][label]['assetId'])) del self.my_osid_object_form._my_map['fileIds'][label]
def Reynolds_factor(FL, C, d, Rev, full_trim=True): r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery factor `FL`, and with either full or reduced trim, all according to IEC 60534 calculations. If full trim: .. math:: F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1) .. math:: n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2} .. math:: F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2}) Otherwise : .. math:: F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v} .. math:: n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3} .. math:: F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4}) Parameters ---------- FL : float Liquid pressure recovery factor of a control valve without attached fittings [] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] d : float Diameter of the valve [m] Rev : float Valve reynolds number [-] full_trim : bool Whether or not the valve has full trim Returns ------- FR : float Reynolds number factor for laminar or transitional flow [] Examples -------- In Example 4, compressible flow with small flow trim sized for gas flow (Cv in the problem was converted to Kv here to make FR match with N32, N2): >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False) 0.7148753122302025 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if full_trim: n1 = N2/(min(C/d**2, 0.04))**2 # C/d**2 must not exceed 0.04 FR_1a = 1 + (0.33*FL**0.5)/n1**0.25*log10(Rev/10000.) FR_2 = 0.026/FL*(n1*Rev)**0.5 if Rev < 10: FR = FR_2 else: FR = min(FR_2, FR_1a) else: n2 = 1 + N32*(C/d**2)**(2/3.) FR_3a = 1 + (0.33*FL**0.5)/n2**0.25*log10(Rev/10000.) FR_4 = min(0.026/FL*(n2*Rev)**0.5, 1) if Rev < 10: FR = FR_4 else: FR = min(FR_3a, FR_4) return FR
def function[Reynolds_factor, parameter[FL, C, d, Rev, full_trim]]: constant[Calculates the Reynolds number factor `FR` for a valve with a Reynolds number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery factor `FL`, and with either full or reduced trim, all according to IEC 60534 calculations. If full trim: .. math:: F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1) .. math:: n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2} .. math:: F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2}) Otherwise : .. math:: F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v} .. math:: n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3} .. math:: F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4}) Parameters ---------- FL : float Liquid pressure recovery factor of a control valve without attached fittings [] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] d : float Diameter of the valve [m] Rev : float Valve reynolds number [-] full_trim : bool Whether or not the valve has full trim Returns ------- FR : float Reynolds number factor for laminar or transitional flow [] Examples -------- In Example 4, compressible flow with small flow trim sized for gas flow (Cv in the problem was converted to Kv here to make FR match with N32, N2): >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False) 0.7148753122302025 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ] if name[full_trim] begin[:] variable[n1] assign[=] binary_operation[name[N2] / binary_operation[call[name[min], parameter[binary_operation[name[C] / binary_operation[name[d] ** constant[2]]], constant[0.04]]] ** constant[2]]] variable[FR_1a] assign[=] binary_operation[constant[1] + binary_operation[binary_operation[binary_operation[constant[0.33] * binary_operation[name[FL] ** constant[0.5]]] / binary_operation[name[n1] ** constant[0.25]]] * call[name[log10], parameter[binary_operation[name[Rev] / constant[10000.0]]]]]] variable[FR_2] assign[=] binary_operation[binary_operation[constant[0.026] / name[FL]] * binary_operation[binary_operation[name[n1] * name[Rev]] ** constant[0.5]]] if compare[name[Rev] less[<] constant[10]] begin[:] variable[FR] assign[=] name[FR_2] return[name[FR]]
keyword[def] identifier[Reynolds_factor] ( identifier[FL] , identifier[C] , identifier[d] , identifier[Rev] , identifier[full_trim] = keyword[True] ): literal[string] keyword[if] identifier[full_trim] : identifier[n1] = identifier[N2] /( identifier[min] ( identifier[C] / identifier[d] ** literal[int] , literal[int] ))** literal[int] identifier[FR_1a] = literal[int] +( literal[int] * identifier[FL] ** literal[int] )/ identifier[n1] ** literal[int] * identifier[log10] ( identifier[Rev] / literal[int] ) identifier[FR_2] = literal[int] / identifier[FL] *( identifier[n1] * identifier[Rev] )** literal[int] keyword[if] identifier[Rev] < literal[int] : identifier[FR] = identifier[FR_2] keyword[else] : identifier[FR] = identifier[min] ( identifier[FR_2] , identifier[FR_1a] ) keyword[else] : identifier[n2] = literal[int] + identifier[N32] *( identifier[C] / identifier[d] ** literal[int] )**( literal[int] / literal[int] ) identifier[FR_3a] = literal[int] +( literal[int] * identifier[FL] ** literal[int] )/ identifier[n2] ** literal[int] * identifier[log10] ( identifier[Rev] / literal[int] ) identifier[FR_4] = identifier[min] ( literal[int] / identifier[FL] *( identifier[n2] * identifier[Rev] )** literal[int] , literal[int] ) keyword[if] identifier[Rev] < literal[int] : identifier[FR] = identifier[FR_4] keyword[else] : identifier[FR] = identifier[min] ( identifier[FR_3a] , identifier[FR_4] ) keyword[return] identifier[FR]
def Reynolds_factor(FL, C, d, Rev, full_trim=True): """Calculates the Reynolds number factor `FR` for a valve with a Reynolds number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery factor `FL`, and with either full or reduced trim, all according to IEC 60534 calculations. If full trim: .. math:: F_{R,1a} = 1 + \\left(\\frac{0.33F_L^{0.5}}{n_1^{0.25}}\\right)\\log_{10} \\left(\\frac{Re_v}{10000}\\right) .. math:: F_{R,2} = \\min(\\frac{0.026}{F_L}\\sqrt{n_1 Re_v},\\; 1) .. math:: n_1 = \\frac{N_2}{\\left(\\frac{C}{d^2}\\right)^2} .. math:: F_R = F_{R,2} \\text{ if Rev < 10 else } \\min(F_{R,1a}, F_{R,2}) Otherwise : .. math:: F_{R,3a} = 1 + \\left(\\frac{0.33F_L^{0.5}}{n_2^{0.25}}\\right)\\log_{10} \\left(\\frac{Re_v}{10000}\\right) .. math:: F_{R,4} = \\frac{0.026}{F_L}\\sqrt{n_2 Re_v} .. math:: n_2 = 1 + N_{32}\\left(\\frac{C}{d}\\right)^{2/3} .. math:: F_R = F_{R,4} \\text{ if Rev < 10 else } \\min(F_{R,3a}, F_{R,4}) Parameters ---------- FL : float Liquid pressure recovery factor of a control valve without attached fittings [] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] d : float Diameter of the valve [m] Rev : float Valve reynolds number [-] full_trim : bool Whether or not the valve has full trim Returns ------- FR : float Reynolds number factor for laminar or transitional flow [] Examples -------- In Example 4, compressible flow with small flow trim sized for gas flow (Cv in the problem was converted to Kv here to make FR match with N32, N2): >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False) 0.7148753122302025 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 """ if full_trim: n1 = N2 / min(C / d ** 2, 0.04) ** 2 # C/d**2 must not exceed 0.04 FR_1a = 1 + 0.33 * FL ** 0.5 / n1 ** 0.25 * log10(Rev / 10000.0) FR_2 = 0.026 / FL * (n1 * Rev) ** 0.5 if Rev < 10: FR = FR_2 # depends on [control=['if'], data=[]] else: FR = min(FR_2, FR_1a) # depends on [control=['if'], data=[]] else: n2 = 1 + N32 * (C / d ** 2) ** (2 / 3.0) FR_3a = 1 + 0.33 * FL ** 0.5 / n2 ** 0.25 * log10(Rev / 10000.0) FR_4 = min(0.026 / FL * (n2 * Rev) ** 0.5, 1) if Rev < 10: FR = FR_4 # depends on [control=['if'], data=[]] else: FR = min(FR_3a, FR_4) return FR
def _set_value(self, entity, value): """Internal helper to set a value in an entity for a Property. This performs validation first. For a repeated Property the value should be a list. """ if entity._projection: raise ReadonlyPropertyError( 'You cannot set property values of a projection entity') if self._repeated: if not isinstance(value, (list, tuple, set, frozenset)): raise datastore_errors.BadValueError('Expected list or tuple, got %r' % (value,)) value = [self._do_validate(v) for v in value] else: if value is not None: value = self._do_validate(value) self._store_value(entity, value)
def function[_set_value, parameter[self, entity, value]]: constant[Internal helper to set a value in an entity for a Property. This performs validation first. For a repeated Property the value should be a list. ] if name[entity]._projection begin[:] <ast.Raise object at 0x7da20c6a8400> if name[self]._repeated begin[:] if <ast.UnaryOp object at 0x7da20c6a9060> begin[:] <ast.Raise object at 0x7da20c6a8040> variable[value] assign[=] <ast.ListComp object at 0x7da20c6a9600> call[name[self]._store_value, parameter[name[entity], name[value]]]
keyword[def] identifier[_set_value] ( identifier[self] , identifier[entity] , identifier[value] ): literal[string] keyword[if] identifier[entity] . identifier[_projection] : keyword[raise] identifier[ReadonlyPropertyError] ( literal[string] ) keyword[if] identifier[self] . identifier[_repeated] : keyword[if] keyword[not] identifier[isinstance] ( identifier[value] ,( identifier[list] , identifier[tuple] , identifier[set] , identifier[frozenset] )): keyword[raise] identifier[datastore_errors] . identifier[BadValueError] ( literal[string] % ( identifier[value] ,)) identifier[value] =[ identifier[self] . identifier[_do_validate] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[value] ] keyword[else] : keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] : identifier[value] = identifier[self] . identifier[_do_validate] ( identifier[value] ) identifier[self] . identifier[_store_value] ( identifier[entity] , identifier[value] )
def _set_value(self, entity, value): """Internal helper to set a value in an entity for a Property. This performs validation first. For a repeated Property the value should be a list. """ if entity._projection: raise ReadonlyPropertyError('You cannot set property values of a projection entity') # depends on [control=['if'], data=[]] if self._repeated: if not isinstance(value, (list, tuple, set, frozenset)): raise datastore_errors.BadValueError('Expected list or tuple, got %r' % (value,)) # depends on [control=['if'], data=[]] value = [self._do_validate(v) for v in value] # depends on [control=['if'], data=[]] elif value is not None: value = self._do_validate(value) # depends on [control=['if'], data=['value']] self._store_value(entity, value)
def generate_search_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate search results for a set of n-grams.""" parser = subparsers.add_parser( 'search', description=constants.SEARCH_DESCRIPTION, epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter, help=constants.SEARCH_HELP) parser.set_defaults(func=search_texts) utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser) parser.add_argument('ngrams', help=constants.SEARCH_NGRAMS_HELP, nargs='*', metavar='NGRAMS')
def function[generate_search_subparser, parameter[subparsers]]: constant[Adds a sub-command parser to `subparsers` to generate search results for a set of n-grams.] variable[parser] assign[=] call[name[subparsers].add_parser, parameter[constant[search]]] call[name[parser].set_defaults, parameter[]] call[name[utils].add_common_arguments, parameter[name[parser]]] call[name[utils].add_db_arguments, parameter[name[parser]]] call[name[utils].add_corpus_arguments, parameter[name[parser]]] call[name[utils].add_query_arguments, parameter[name[parser]]] call[name[parser].add_argument, parameter[constant[ngrams]]]
keyword[def] identifier[generate_search_subparser] ( identifier[subparsers] ): literal[string] identifier[parser] = identifier[subparsers] . identifier[add_parser] ( literal[string] , identifier[description] = identifier[constants] . identifier[SEARCH_DESCRIPTION] , identifier[epilog] = identifier[constants] . identifier[SEARCH_EPILOG] , identifier[formatter_class] = identifier[ParagraphFormatter] , identifier[help] = identifier[constants] . identifier[SEARCH_HELP] ) identifier[parser] . identifier[set_defaults] ( identifier[func] = identifier[search_texts] ) identifier[utils] . identifier[add_common_arguments] ( identifier[parser] ) identifier[utils] . identifier[add_db_arguments] ( identifier[parser] ) identifier[utils] . identifier[add_corpus_arguments] ( identifier[parser] ) identifier[utils] . identifier[add_query_arguments] ( identifier[parser] ) identifier[parser] . identifier[add_argument] ( literal[string] , identifier[help] = identifier[constants] . identifier[SEARCH_NGRAMS_HELP] , identifier[nargs] = literal[string] , identifier[metavar] = literal[string] )
def generate_search_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate search results for a set of n-grams.""" parser = subparsers.add_parser('search', description=constants.SEARCH_DESCRIPTION, epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter, help=constants.SEARCH_HELP) parser.set_defaults(func=search_texts) utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser) parser.add_argument('ngrams', help=constants.SEARCH_NGRAMS_HELP, nargs='*', metavar='NGRAMS')
def emitCurrentRecordEdited(self): """ Emits the current record edited signal for this combobox, provided the signals aren't blocked and the record has changed since the last time. """ if self._changedRecord == -1: return if self.signalsBlocked(): return record = self._changedRecord self._changedRecord = -1 self.currentRecordEdited.emit(record)
def function[emitCurrentRecordEdited, parameter[self]]: constant[ Emits the current record edited signal for this combobox, provided the signals aren't blocked and the record has changed since the last time. ] if compare[name[self]._changedRecord equal[==] <ast.UnaryOp object at 0x7da18f09eb30>] begin[:] return[None] if call[name[self].signalsBlocked, parameter[]] begin[:] return[None] variable[record] assign[=] name[self]._changedRecord name[self]._changedRecord assign[=] <ast.UnaryOp object at 0x7da18f09df00> call[name[self].currentRecordEdited.emit, parameter[name[record]]]
keyword[def] identifier[emitCurrentRecordEdited] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_changedRecord] ==- literal[int] : keyword[return] keyword[if] identifier[self] . identifier[signalsBlocked] (): keyword[return] identifier[record] = identifier[self] . identifier[_changedRecord] identifier[self] . identifier[_changedRecord] =- literal[int] identifier[self] . identifier[currentRecordEdited] . identifier[emit] ( identifier[record] )
def emitCurrentRecordEdited(self): """ Emits the current record edited signal for this combobox, provided the signals aren't blocked and the record has changed since the last time. """ if self._changedRecord == -1: return # depends on [control=['if'], data=[]] if self.signalsBlocked(): return # depends on [control=['if'], data=[]] record = self._changedRecord self._changedRecord = -1 self.currentRecordEdited.emit(record)
def fork(self, **args): ''' fork any gist by providing gistID or gistname(for authenticated user) ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Either provide authenticated user\'s Unambigious Gistname or any unique Gistid to be forked') r = requests.post( '%s'%BASE_URL+'/gists/%s/forks' % self.gist_id, headers=self.gist.header ) if (r.status_code == 201): response = { 'id': self.gist_id, 'description': r.json()['description'], 'public': r.json()['public'], 'comments': r.json()['comments'] } return response raise Exception('Gist can\'t be forked')
def function[fork, parameter[self]]: constant[ fork any gist by providing gistID or gistname(for authenticated user) ] if compare[constant[name] in name[args]] begin[:] name[self].gist_name assign[=] call[name[args]][constant[name]] name[self].gist_id assign[=] call[name[self].getMyID, parameter[name[self].gist_name]] variable[r] assign[=] call[name[requests].post, parameter[binary_operation[binary_operation[constant[%s] <ast.Mod object at 0x7da2590d6920> name[BASE_URL]] + binary_operation[constant[/gists/%s/forks] <ast.Mod object at 0x7da2590d6920> name[self].gist_id]]]] if compare[name[r].status_code equal[==] constant[201]] begin[:] variable[response] assign[=] dictionary[[<ast.Constant object at 0x7da204961360>, <ast.Constant object at 0x7da204962a70>, <ast.Constant object at 0x7da204963ca0>, <ast.Constant object at 0x7da204962ef0>], [<ast.Attribute object at 0x7da204963520>, <ast.Subscript object at 0x7da2049634c0>, <ast.Subscript object at 0x7da204961030>, <ast.Subscript object at 0x7da204960df0>]] return[name[response]] <ast.Raise object at 0x7da204960670>
keyword[def] identifier[fork] ( identifier[self] ,** identifier[args] ): literal[string] keyword[if] literal[string] keyword[in] identifier[args] : identifier[self] . identifier[gist_name] = identifier[args] [ literal[string] ] identifier[self] . identifier[gist_id] = identifier[self] . identifier[getMyID] ( identifier[self] . identifier[gist_name] ) keyword[elif] literal[string] keyword[in] identifier[args] : identifier[self] . identifier[gist_id] = identifier[args] [ literal[string] ] keyword[else] : keyword[raise] identifier[Exception] ( literal[string] ) identifier[r] = identifier[requests] . identifier[post] ( literal[string] % identifier[BASE_URL] + literal[string] % identifier[self] . identifier[gist_id] , identifier[headers] = identifier[self] . identifier[gist] . identifier[header] ) keyword[if] ( identifier[r] . identifier[status_code] == literal[int] ): identifier[response] ={ literal[string] : identifier[self] . identifier[gist_id] , literal[string] : identifier[r] . identifier[json] ()[ literal[string] ], literal[string] : identifier[r] . identifier[json] ()[ literal[string] ], literal[string] : identifier[r] . identifier[json] ()[ literal[string] ] } keyword[return] identifier[response] keyword[raise] identifier[Exception] ( literal[string] )
def fork(self, **args): """ fork any gist by providing gistID or gistname(for authenticated user) """ if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) # depends on [control=['if'], data=['args']] elif 'id' in args: self.gist_id = args['id'] # depends on [control=['if'], data=['args']] else: raise Exception("Either provide authenticated user's Unambigious Gistname or any unique Gistid to be forked") r = requests.post('%s' % BASE_URL + '/gists/%s/forks' % self.gist_id, headers=self.gist.header) if r.status_code == 201: response = {'id': self.gist_id, 'description': r.json()['description'], 'public': r.json()['public'], 'comments': r.json()['comments']} return response # depends on [control=['if'], data=[]] raise Exception("Gist can't be forked")
def artist_to_qfont(artist): """Convert a :class:`matplotlib.text.Text` artist to a QFont object Parameters ---------- artist: matplotlib.text.Text The text artist, e.g. an axes title Returns ------- PyQt5.QtGui.QFont The QFont object""" size = int(artist.get_size()) weight = mpl_weight2qt(artist.get_weight()) italic = artist.get_style() == 'italic' for family in artist.get_family(): if family in ['sans-serif', 'cursive', 'monospace', 'serif']: for name in mpl.rcParams['font.' + family]: font = QtGui.QFont(name, size, weight, italic) if font.exactMatch(): break else: font = QtGui.QFont(family, size, weight, italic) return font
def function[artist_to_qfont, parameter[artist]]: constant[Convert a :class:`matplotlib.text.Text` artist to a QFont object Parameters ---------- artist: matplotlib.text.Text The text artist, e.g. an axes title Returns ------- PyQt5.QtGui.QFont The QFont object] variable[size] assign[=] call[name[int], parameter[call[name[artist].get_size, parameter[]]]] variable[weight] assign[=] call[name[mpl_weight2qt], parameter[call[name[artist].get_weight, parameter[]]]] variable[italic] assign[=] compare[call[name[artist].get_style, parameter[]] equal[==] constant[italic]] for taget[name[family]] in starred[call[name[artist].get_family, parameter[]]] begin[:] if compare[name[family] in list[[<ast.Constant object at 0x7da18dc98d30>, <ast.Constant object at 0x7da18dc98220>, <ast.Constant object at 0x7da18dc99930>, <ast.Constant object at 0x7da18dc983a0>]]] begin[:] for taget[name[name]] in starred[call[name[mpl].rcParams][binary_operation[constant[font.] + name[family]]]] begin[:] variable[font] assign[=] call[name[QtGui].QFont, parameter[name[name], name[size], name[weight], name[italic]]] if call[name[font].exactMatch, parameter[]] begin[:] break return[name[font]]
keyword[def] identifier[artist_to_qfont] ( identifier[artist] ): literal[string] identifier[size] = identifier[int] ( identifier[artist] . identifier[get_size] ()) identifier[weight] = identifier[mpl_weight2qt] ( identifier[artist] . identifier[get_weight] ()) identifier[italic] = identifier[artist] . identifier[get_style] ()== literal[string] keyword[for] identifier[family] keyword[in] identifier[artist] . identifier[get_family] (): keyword[if] identifier[family] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] ]: keyword[for] identifier[name] keyword[in] identifier[mpl] . identifier[rcParams] [ literal[string] + identifier[family] ]: identifier[font] = identifier[QtGui] . identifier[QFont] ( identifier[name] , identifier[size] , identifier[weight] , identifier[italic] ) keyword[if] identifier[font] . identifier[exactMatch] (): keyword[break] keyword[else] : identifier[font] = identifier[QtGui] . identifier[QFont] ( identifier[family] , identifier[size] , identifier[weight] , identifier[italic] ) keyword[return] identifier[font]
def artist_to_qfont(artist): """Convert a :class:`matplotlib.text.Text` artist to a QFont object Parameters ---------- artist: matplotlib.text.Text The text artist, e.g. an axes title Returns ------- PyQt5.QtGui.QFont The QFont object""" size = int(artist.get_size()) weight = mpl_weight2qt(artist.get_weight()) italic = artist.get_style() == 'italic' for family in artist.get_family(): if family in ['sans-serif', 'cursive', 'monospace', 'serif']: for name in mpl.rcParams['font.' + family]: font = QtGui.QFont(name, size, weight, italic) if font.exactMatch(): break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['name']] # depends on [control=['if'], data=['family']] else: font = QtGui.QFont(family, size, weight, italic) # depends on [control=['for'], data=['family']] return font
def update_access_key(self, access_key_id, status, user_name=None): """ Changes the status of the specified access key from Active to Inactive or vice versa. This action can be used to disable a user's key as part of a key rotation workflow. If the user_name is not specified, the user_name is determined implicitly based on the AWS Access Key ID used to sign the request. :type access_key_id: string :param access_key_id: The ID of the access key. :type status: string :param status: Either Active or Inactive. :type user_name: string :param user_name: The username of user (optional). """ params = {'AccessKeyId' : access_key_id, 'Status' : status} if user_name: params['UserName'] = user_name return self.get_response('UpdateAccessKey', params)
def function[update_access_key, parameter[self, access_key_id, status, user_name]]: constant[ Changes the status of the specified access key from Active to Inactive or vice versa. This action can be used to disable a user's key as part of a key rotation workflow. If the user_name is not specified, the user_name is determined implicitly based on the AWS Access Key ID used to sign the request. :type access_key_id: string :param access_key_id: The ID of the access key. :type status: string :param status: Either Active or Inactive. :type user_name: string :param user_name: The username of user (optional). ] variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b2615bd0>, <ast.Constant object at 0x7da1b2615c90>], [<ast.Name object at 0x7da1b2614490>, <ast.Name object at 0x7da1b2614700>]] if name[user_name] begin[:] call[name[params]][constant[UserName]] assign[=] name[user_name] return[call[name[self].get_response, parameter[constant[UpdateAccessKey], name[params]]]]
keyword[def] identifier[update_access_key] ( identifier[self] , identifier[access_key_id] , identifier[status] , identifier[user_name] = keyword[None] ): literal[string] identifier[params] ={ literal[string] : identifier[access_key_id] , literal[string] : identifier[status] } keyword[if] identifier[user_name] : identifier[params] [ literal[string] ]= identifier[user_name] keyword[return] identifier[self] . identifier[get_response] ( literal[string] , identifier[params] )
def update_access_key(self, access_key_id, status, user_name=None): """ Changes the status of the specified access key from Active to Inactive or vice versa. This action can be used to disable a user's key as part of a key rotation workflow. If the user_name is not specified, the user_name is determined implicitly based on the AWS Access Key ID used to sign the request. :type access_key_id: string :param access_key_id: The ID of the access key. :type status: string :param status: Either Active or Inactive. :type user_name: string :param user_name: The username of user (optional). """ params = {'AccessKeyId': access_key_id, 'Status': status} if user_name: params['UserName'] = user_name # depends on [control=['if'], data=[]] return self.get_response('UpdateAccessKey', params)
def _are_safety_checks_disabled(self, caller=u"unknown_function"): """ Return ``True`` if safety checks are disabled. :param string caller: the name of the caller function :rtype: bool """ if self.rconf.safety_checks: return False self.log_warn([u"Safety checks disabled => %s passed", caller]) return True
def function[_are_safety_checks_disabled, parameter[self, caller]]: constant[ Return ``True`` if safety checks are disabled. :param string caller: the name of the caller function :rtype: bool ] if name[self].rconf.safety_checks begin[:] return[constant[False]] call[name[self].log_warn, parameter[list[[<ast.Constant object at 0x7da18c4cd450>, <ast.Name object at 0x7da18c4cc370>]]]] return[constant[True]]
keyword[def] identifier[_are_safety_checks_disabled] ( identifier[self] , identifier[caller] = literal[string] ): literal[string] keyword[if] identifier[self] . identifier[rconf] . identifier[safety_checks] : keyword[return] keyword[False] identifier[self] . identifier[log_warn] ([ literal[string] , identifier[caller] ]) keyword[return] keyword[True]
def _are_safety_checks_disabled(self, caller=u'unknown_function'): """ Return ``True`` if safety checks are disabled. :param string caller: the name of the caller function :rtype: bool """ if self.rconf.safety_checks: return False # depends on [control=['if'], data=[]] self.log_warn([u'Safety checks disabled => %s passed', caller]) return True
def map(self, func): """ A lazy way to apply the given function to each element in the stream. Useful for type casting, like: >>> from audiolazy import count >>> count().take(5) [0, 1, 2, 3, 4] >>> my_stream = count().map(float) >>> my_stream.take(5) # A float counter [0.0, 1.0, 2.0, 3.0, 4.0] """ self._data = xmap(func, self._data) return self
def function[map, parameter[self, func]]: constant[ A lazy way to apply the given function to each element in the stream. Useful for type casting, like: >>> from audiolazy import count >>> count().take(5) [0, 1, 2, 3, 4] >>> my_stream = count().map(float) >>> my_stream.take(5) # A float counter [0.0, 1.0, 2.0, 3.0, 4.0] ] name[self]._data assign[=] call[name[xmap], parameter[name[func], name[self]._data]] return[name[self]]
keyword[def] identifier[map] ( identifier[self] , identifier[func] ): literal[string] identifier[self] . identifier[_data] = identifier[xmap] ( identifier[func] , identifier[self] . identifier[_data] ) keyword[return] identifier[self]
def map(self, func): """ A lazy way to apply the given function to each element in the stream. Useful for type casting, like: >>> from audiolazy import count >>> count().take(5) [0, 1, 2, 3, 4] >>> my_stream = count().map(float) >>> my_stream.take(5) # A float counter [0.0, 1.0, 2.0, 3.0, 4.0] """ self._data = xmap(func, self._data) return self
def custom_token(spacy_token) -> Token: """ Function for token attributes extension, methods extension Use set_extension method. Reference: https://spacy.io/api/token, https://spacy.io/usage/processing-pipelines#custom-components-attributes """ """Add custom attributes""" """Add full_shape attribute. Eg. 21.33 => dd.dd, esadDeweD23 => xxxxXxxxXdd""" def get_shape(token): full_shape = "" for i in token.text: if i.isdigit(): full_shape += "d" elif i.islower(): full_shape += "x" elif i.isupper(): full_shape += "X" else: full_shape += i return full_shape spacy_token.set_extension("full_shape", getter=get_shape, force=True) def is_integer(token): pattern = re.compile('^[-+]?[0-9]+$') return bool(pattern.match(token.text)) spacy_token.set_extension("is_integer", getter=is_integer, force=True) def is_decimal(token): pattern = re.compile('^[-+]?[0-9]+\.[0-9]+$') return bool(pattern.match(token.text)) spacy_token.set_extension("is_decimal", getter=is_decimal, force=True) def is_ordinal(token): return token.orth_[-2:] in ['rd', 'st', 'th', 'nd'] spacy_token.set_extension("is_ordinal", getter=is_ordinal, force=True) def is_mixed(token): if not token.is_title and not token.is_lower and not token.is_upper: return True else: return False spacy_token.set_extension("is_mixed", getter=is_mixed, force=True) """Add custom methods""" """Add get_prefix method. RETURN length N prefix""" def n_prefix(token, n): return token.text[:n] spacy_token.set_extension("n_prefix", method=n_prefix, force=True) """Add get_suffix method. RETURN length N suffix""" def n_suffix(token, n): return token.text[-n:] spacy_token.set_extension("n_suffix", method=n_suffix, force=True) return spacy_token
def function[custom_token, parameter[spacy_token]]: constant[ Function for token attributes extension, methods extension Use set_extension method. Reference: https://spacy.io/api/token, https://spacy.io/usage/processing-pipelines#custom-components-attributes ] constant[Add custom attributes] constant[Add full_shape attribute. Eg. 21.33 => dd.dd, esadDeweD23 => xxxxXxxxXdd] def function[get_shape, parameter[token]]: variable[full_shape] assign[=] constant[] for taget[name[i]] in starred[name[token].text] begin[:] if call[name[i].isdigit, parameter[]] begin[:] <ast.AugAssign object at 0x7da1b0bdb7c0> return[name[full_shape]] call[name[spacy_token].set_extension, parameter[constant[full_shape]]] def function[is_integer, parameter[token]]: variable[pattern] assign[=] call[name[re].compile, parameter[constant[^[-+]?[0-9]+$]]] return[call[name[bool], parameter[call[name[pattern].match, parameter[name[token].text]]]]] call[name[spacy_token].set_extension, parameter[constant[is_integer]]] def function[is_decimal, parameter[token]]: variable[pattern] assign[=] call[name[re].compile, parameter[constant[^[-+]?[0-9]+\.[0-9]+$]]] return[call[name[bool], parameter[call[name[pattern].match, parameter[name[token].text]]]]] call[name[spacy_token].set_extension, parameter[constant[is_decimal]]] def function[is_ordinal, parameter[token]]: return[compare[call[name[token].orth_][<ast.Slice object at 0x7da1b0bd9f30>] in list[[<ast.Constant object at 0x7da1b0bda710>, <ast.Constant object at 0x7da1b0bd8b50>, <ast.Constant object at 0x7da1b0bd9930>, <ast.Constant object at 0x7da1b0bdb940>]]]] call[name[spacy_token].set_extension, parameter[constant[is_ordinal]]] def function[is_mixed, parameter[token]]: if <ast.BoolOp object at 0x7da1b0bd9c30> begin[:] return[constant[True]] call[name[spacy_token].set_extension, parameter[constant[is_mixed]]] constant[Add custom methods] constant[Add get_prefix method. RETURN length N prefix] def function[n_prefix, parameter[token, n]]: return[call[name[token].text][<ast.Slice object at 0x7da1b0bdb700>]] call[name[spacy_token].set_extension, parameter[constant[n_prefix]]] constant[Add get_suffix method. RETURN length N suffix] def function[n_suffix, parameter[token, n]]: return[call[name[token].text][<ast.Slice object at 0x7da1b0bd9360>]] call[name[spacy_token].set_extension, parameter[constant[n_suffix]]] return[name[spacy_token]]
keyword[def] identifier[custom_token] ( identifier[spacy_token] )-> identifier[Token] : literal[string] literal[string] literal[string] keyword[def] identifier[get_shape] ( identifier[token] ): identifier[full_shape] = literal[string] keyword[for] identifier[i] keyword[in] identifier[token] . identifier[text] : keyword[if] identifier[i] . identifier[isdigit] (): identifier[full_shape] += literal[string] keyword[elif] identifier[i] . identifier[islower] (): identifier[full_shape] += literal[string] keyword[elif] identifier[i] . identifier[isupper] (): identifier[full_shape] += literal[string] keyword[else] : identifier[full_shape] += identifier[i] keyword[return] identifier[full_shape] identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[getter] = identifier[get_shape] , identifier[force] = keyword[True] ) keyword[def] identifier[is_integer] ( identifier[token] ): identifier[pattern] = identifier[re] . identifier[compile] ( literal[string] ) keyword[return] identifier[bool] ( identifier[pattern] . identifier[match] ( identifier[token] . identifier[text] )) identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[getter] = identifier[is_integer] , identifier[force] = keyword[True] ) keyword[def] identifier[is_decimal] ( identifier[token] ): identifier[pattern] = identifier[re] . identifier[compile] ( literal[string] ) keyword[return] identifier[bool] ( identifier[pattern] . identifier[match] ( identifier[token] . identifier[text] )) identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[getter] = identifier[is_decimal] , identifier[force] = keyword[True] ) keyword[def] identifier[is_ordinal] ( identifier[token] ): keyword[return] identifier[token] . identifier[orth_] [- literal[int] :] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] ] identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[getter] = identifier[is_ordinal] , identifier[force] = keyword[True] ) keyword[def] identifier[is_mixed] ( identifier[token] ): keyword[if] keyword[not] identifier[token] . identifier[is_title] keyword[and] keyword[not] identifier[token] . identifier[is_lower] keyword[and] keyword[not] identifier[token] . identifier[is_upper] : keyword[return] keyword[True] keyword[else] : keyword[return] keyword[False] identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[getter] = identifier[is_mixed] , identifier[force] = keyword[True] ) literal[string] literal[string] keyword[def] identifier[n_prefix] ( identifier[token] , identifier[n] ): keyword[return] identifier[token] . identifier[text] [: identifier[n] ] identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[method] = identifier[n_prefix] , identifier[force] = keyword[True] ) literal[string] keyword[def] identifier[n_suffix] ( identifier[token] , identifier[n] ): keyword[return] identifier[token] . identifier[text] [- identifier[n] :] identifier[spacy_token] . identifier[set_extension] ( literal[string] , identifier[method] = identifier[n_suffix] , identifier[force] = keyword[True] ) keyword[return] identifier[spacy_token]
def custom_token(spacy_token) -> Token: """ Function for token attributes extension, methods extension Use set_extension method. Reference: https://spacy.io/api/token, https://spacy.io/usage/processing-pipelines#custom-components-attributes """ 'Add custom attributes' 'Add full_shape attribute. Eg. 21.33 => dd.dd, esadDeweD23 => xxxxXxxxXdd' def get_shape(token): full_shape = '' for i in token.text: if i.isdigit(): full_shape += 'd' # depends on [control=['if'], data=[]] elif i.islower(): full_shape += 'x' # depends on [control=['if'], data=[]] elif i.isupper(): full_shape += 'X' # depends on [control=['if'], data=[]] else: full_shape += i # depends on [control=['for'], data=['i']] return full_shape spacy_token.set_extension('full_shape', getter=get_shape, force=True) def is_integer(token): pattern = re.compile('^[-+]?[0-9]+$') return bool(pattern.match(token.text)) spacy_token.set_extension('is_integer', getter=is_integer, force=True) def is_decimal(token): pattern = re.compile('^[-+]?[0-9]+\\.[0-9]+$') return bool(pattern.match(token.text)) spacy_token.set_extension('is_decimal', getter=is_decimal, force=True) def is_ordinal(token): return token.orth_[-2:] in ['rd', 'st', 'th', 'nd'] spacy_token.set_extension('is_ordinal', getter=is_ordinal, force=True) def is_mixed(token): if not token.is_title and (not token.is_lower) and (not token.is_upper): return True # depends on [control=['if'], data=[]] else: return False spacy_token.set_extension('is_mixed', getter=is_mixed, force=True) 'Add custom methods' 'Add get_prefix method. RETURN length N prefix' def n_prefix(token, n): return token.text[:n] spacy_token.set_extension('n_prefix', method=n_prefix, force=True) 'Add get_suffix method. RETURN length N suffix' def n_suffix(token, n): return token.text[-n:] spacy_token.set_extension('n_suffix', method=n_suffix, force=True) return spacy_token
def new_media_status(self, media_status): """Handle reception of a new MediaStatus.""" casts = self._casts group_members = self._mz.members for member_uuid in group_members: if member_uuid not in casts: continue for listener in list(casts[member_uuid]['listeners']): listener.multizone_new_media_status( self._group_uuid, media_status)
def function[new_media_status, parameter[self, media_status]]: constant[Handle reception of a new MediaStatus.] variable[casts] assign[=] name[self]._casts variable[group_members] assign[=] name[self]._mz.members for taget[name[member_uuid]] in starred[name[group_members]] begin[:] if compare[name[member_uuid] <ast.NotIn object at 0x7da2590d7190> name[casts]] begin[:] continue for taget[name[listener]] in starred[call[name[list], parameter[call[call[name[casts]][name[member_uuid]]][constant[listeners]]]]] begin[:] call[name[listener].multizone_new_media_status, parameter[name[self]._group_uuid, name[media_status]]]
keyword[def] identifier[new_media_status] ( identifier[self] , identifier[media_status] ): literal[string] identifier[casts] = identifier[self] . identifier[_casts] identifier[group_members] = identifier[self] . identifier[_mz] . identifier[members] keyword[for] identifier[member_uuid] keyword[in] identifier[group_members] : keyword[if] identifier[member_uuid] keyword[not] keyword[in] identifier[casts] : keyword[continue] keyword[for] identifier[listener] keyword[in] identifier[list] ( identifier[casts] [ identifier[member_uuid] ][ literal[string] ]): identifier[listener] . identifier[multizone_new_media_status] ( identifier[self] . identifier[_group_uuid] , identifier[media_status] )
def new_media_status(self, media_status): """Handle reception of a new MediaStatus.""" casts = self._casts group_members = self._mz.members for member_uuid in group_members: if member_uuid not in casts: continue # depends on [control=['if'], data=[]] for listener in list(casts[member_uuid]['listeners']): listener.multizone_new_media_status(self._group_uuid, media_status) # depends on [control=['for'], data=['listener']] # depends on [control=['for'], data=['member_uuid']]
def cli(ctx): """Saves a new command""" cmd = click.prompt('Command') desc = click.prompt('Description ') alias = click.prompt('Alias (optional)', default='') utils.save_command(cmd, desc, alias) utils.log(ctx, 'Saved the new command - {} - with the description - {}.'.format(cmd, desc))
def function[cli, parameter[ctx]]: constant[Saves a new command] variable[cmd] assign[=] call[name[click].prompt, parameter[constant[Command]]] variable[desc] assign[=] call[name[click].prompt, parameter[constant[Description ]]] variable[alias] assign[=] call[name[click].prompt, parameter[constant[Alias (optional)]]] call[name[utils].save_command, parameter[name[cmd], name[desc], name[alias]]] call[name[utils].log, parameter[name[ctx], call[constant[Saved the new command - {} - with the description - {}.].format, parameter[name[cmd], name[desc]]]]]
keyword[def] identifier[cli] ( identifier[ctx] ): literal[string] identifier[cmd] = identifier[click] . identifier[prompt] ( literal[string] ) identifier[desc] = identifier[click] . identifier[prompt] ( literal[string] ) identifier[alias] = identifier[click] . identifier[prompt] ( literal[string] , identifier[default] = literal[string] ) identifier[utils] . identifier[save_command] ( identifier[cmd] , identifier[desc] , identifier[alias] ) identifier[utils] . identifier[log] ( identifier[ctx] , literal[string] . identifier[format] ( identifier[cmd] , identifier[desc] ))
def cli(ctx): """Saves a new command""" cmd = click.prompt('Command') desc = click.prompt('Description ') alias = click.prompt('Alias (optional)', default='') utils.save_command(cmd, desc, alias) utils.log(ctx, 'Saved the new command - {} - with the description - {}.'.format(cmd, desc))
def hidden_basic_auth(user="user", passwd="passwd"): """Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json responses: 200: description: Sucessful authentication. 404: description: Unsuccessful authentication. """ if not check_basic_auth(user, passwd): return status_code(404) return jsonify(authenticated=True, user=user)
def function[hidden_basic_auth, parameter[user, passwd]]: constant[Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json responses: 200: description: Sucessful authentication. 404: description: Unsuccessful authentication. ] if <ast.UnaryOp object at 0x7da1b21d62f0> begin[:] return[call[name[status_code], parameter[constant[404]]]] return[call[name[jsonify], parameter[]]]
keyword[def] identifier[hidden_basic_auth] ( identifier[user] = literal[string] , identifier[passwd] = literal[string] ): literal[string] keyword[if] keyword[not] identifier[check_basic_auth] ( identifier[user] , identifier[passwd] ): keyword[return] identifier[status_code] ( literal[int] ) keyword[return] identifier[jsonify] ( identifier[authenticated] = keyword[True] , identifier[user] = identifier[user] )
def hidden_basic_auth(user='user', passwd='passwd'): """Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json responses: 200: description: Sucessful authentication. 404: description: Unsuccessful authentication. """ if not check_basic_auth(user, passwd): return status_code(404) # depends on [control=['if'], data=[]] return jsonify(authenticated=True, user=user)
def get_field_name_for(cls, field_name, dynamic_part): """ Given the name of a dynamic field, and a dynamic part, return the name of the final dynamic field to use. It will then be used with get_field. """ field = cls.get_field(field_name) return field.get_name_for(dynamic_part)
def function[get_field_name_for, parameter[cls, field_name, dynamic_part]]: constant[ Given the name of a dynamic field, and a dynamic part, return the name of the final dynamic field to use. It will then be used with get_field. ] variable[field] assign[=] call[name[cls].get_field, parameter[name[field_name]]] return[call[name[field].get_name_for, parameter[name[dynamic_part]]]]
keyword[def] identifier[get_field_name_for] ( identifier[cls] , identifier[field_name] , identifier[dynamic_part] ): literal[string] identifier[field] = identifier[cls] . identifier[get_field] ( identifier[field_name] ) keyword[return] identifier[field] . identifier[get_name_for] ( identifier[dynamic_part] )
def get_field_name_for(cls, field_name, dynamic_part): """ Given the name of a dynamic field, and a dynamic part, return the name of the final dynamic field to use. It will then be used with get_field. """ field = cls.get_field(field_name) return field.get_name_for(dynamic_part)
def add_line(self, moves: Iterable[chess.Move], *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode": """ Creates a sequence of child nodes for the given list of moves. Adds *comment* and *nags* to the last node of the line and returns it. """ node = self # Add line. for move in moves: node = node.add_variation(move, starting_comment=starting_comment) starting_comment = "" # Merge comment and NAGs. if node.comment: node.comment += " " + comment else: node.comment = comment node.nags.update(nags) return node
def function[add_line, parameter[self, moves]]: constant[ Creates a sequence of child nodes for the given list of moves. Adds *comment* and *nags* to the last node of the line and returns it. ] variable[node] assign[=] name[self] for taget[name[move]] in starred[name[moves]] begin[:] variable[node] assign[=] call[name[node].add_variation, parameter[name[move]]] variable[starting_comment] assign[=] constant[] if name[node].comment begin[:] <ast.AugAssign object at 0x7da1b18bd630> call[name[node].nags.update, parameter[name[nags]]] return[name[node]]
keyword[def] identifier[add_line] ( identifier[self] , identifier[moves] : identifier[Iterable] [ identifier[chess] . identifier[Move] ],*, identifier[comment] : identifier[str] = literal[string] , identifier[starting_comment] : identifier[str] = literal[string] , identifier[nags] : identifier[Iterable] [ identifier[int] ]=())-> literal[string] : literal[string] identifier[node] = identifier[self] keyword[for] identifier[move] keyword[in] identifier[moves] : identifier[node] = identifier[node] . identifier[add_variation] ( identifier[move] , identifier[starting_comment] = identifier[starting_comment] ) identifier[starting_comment] = literal[string] keyword[if] identifier[node] . identifier[comment] : identifier[node] . identifier[comment] += literal[string] + identifier[comment] keyword[else] : identifier[node] . identifier[comment] = identifier[comment] identifier[node] . identifier[nags] . identifier[update] ( identifier[nags] ) keyword[return] identifier[node]
def add_line(self, moves: Iterable[chess.Move], *, comment: str='', starting_comment: str='', nags: Iterable[int]=()) -> 'GameNode': """ Creates a sequence of child nodes for the given list of moves. Adds *comment* and *nags* to the last node of the line and returns it. """ node = self # Add line. for move in moves: node = node.add_variation(move, starting_comment=starting_comment) starting_comment = '' # depends on [control=['for'], data=['move']] # Merge comment and NAGs. if node.comment: node.comment += ' ' + comment # depends on [control=['if'], data=[]] else: node.comment = comment node.nags.update(nags) return node
def read_fastas(input_files): """ Read the tumor and normal fastas into a joint dict. :param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files. :return: The read fastas in a dictionary of tuples :rtype: dict """ tumor_file = [y for x, y in input_files.items() if x.startswith('T')][0] normal_file = [y for x, y in input_files.items() if x.startswith('N')][0] output_files = defaultdict(list) output_files = _read_fasta(tumor_file, output_files) num_entries = len(output_files) output_files = _read_fasta(normal_file, output_files) assert len(output_files) == num_entries return output_files
def function[read_fastas, parameter[input_files]]: constant[ Read the tumor and normal fastas into a joint dict. :param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files. :return: The read fastas in a dictionary of tuples :rtype: dict ] variable[tumor_file] assign[=] call[<ast.ListComp object at 0x7da1b25d9f00>][constant[0]] variable[normal_file] assign[=] call[<ast.ListComp object at 0x7da1b25d99f0>][constant[0]] variable[output_files] assign[=] call[name[defaultdict], parameter[name[list]]] variable[output_files] assign[=] call[name[_read_fasta], parameter[name[tumor_file], name[output_files]]] variable[num_entries] assign[=] call[name[len], parameter[name[output_files]]] variable[output_files] assign[=] call[name[_read_fasta], parameter[name[normal_file], name[output_files]]] assert[compare[call[name[len], parameter[name[output_files]]] equal[==] name[num_entries]]] return[name[output_files]]
keyword[def] identifier[read_fastas] ( identifier[input_files] ): literal[string] identifier[tumor_file] =[ identifier[y] keyword[for] identifier[x] , identifier[y] keyword[in] identifier[input_files] . identifier[items] () keyword[if] identifier[x] . identifier[startswith] ( literal[string] )][ literal[int] ] identifier[normal_file] =[ identifier[y] keyword[for] identifier[x] , identifier[y] keyword[in] identifier[input_files] . identifier[items] () keyword[if] identifier[x] . identifier[startswith] ( literal[string] )][ literal[int] ] identifier[output_files] = identifier[defaultdict] ( identifier[list] ) identifier[output_files] = identifier[_read_fasta] ( identifier[tumor_file] , identifier[output_files] ) identifier[num_entries] = identifier[len] ( identifier[output_files] ) identifier[output_files] = identifier[_read_fasta] ( identifier[normal_file] , identifier[output_files] ) keyword[assert] identifier[len] ( identifier[output_files] )== identifier[num_entries] keyword[return] identifier[output_files]
def read_fastas(input_files): """ Read the tumor and normal fastas into a joint dict. :param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files. :return: The read fastas in a dictionary of tuples :rtype: dict """ tumor_file = [y for (x, y) in input_files.items() if x.startswith('T')][0] normal_file = [y for (x, y) in input_files.items() if x.startswith('N')][0] output_files = defaultdict(list) output_files = _read_fasta(tumor_file, output_files) num_entries = len(output_files) output_files = _read_fasta(normal_file, output_files) assert len(output_files) == num_entries return output_files
def GetCustomJsonFieldMapping(message_type, python_name=None, json_name=None): """Return the appropriate remapping for the given field, or None.""" return _FetchRemapping(message_type, 'field', python_name=python_name, json_name=json_name, mappings=_JSON_FIELD_MAPPINGS)
def function[GetCustomJsonFieldMapping, parameter[message_type, python_name, json_name]]: constant[Return the appropriate remapping for the given field, or None.] return[call[name[_FetchRemapping], parameter[name[message_type], constant[field]]]]
keyword[def] identifier[GetCustomJsonFieldMapping] ( identifier[message_type] , identifier[python_name] = keyword[None] , identifier[json_name] = keyword[None] ): literal[string] keyword[return] identifier[_FetchRemapping] ( identifier[message_type] , literal[string] , identifier[python_name] = identifier[python_name] , identifier[json_name] = identifier[json_name] , identifier[mappings] = identifier[_JSON_FIELD_MAPPINGS] )
def GetCustomJsonFieldMapping(message_type, python_name=None, json_name=None): """Return the appropriate remapping for the given field, or None.""" return _FetchRemapping(message_type, 'field', python_name=python_name, json_name=json_name, mappings=_JSON_FIELD_MAPPINGS)
def post_comment(self, message): """ Comments on an issue, not on a particular line. """ report_url = ( 'https://api.github.com/repos/%s/issues/%s/comments' % (self.repo_name, self.pr_number) ) result = self.requester.post(report_url, {'body': message}) if result.status_code >= 400: log.error("Error posting comment to github. %s", result.json()) return result
def function[post_comment, parameter[self, message]]: constant[ Comments on an issue, not on a particular line. ] variable[report_url] assign[=] binary_operation[constant[https://api.github.com/repos/%s/issues/%s/comments] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da20c6a9e40>, <ast.Attribute object at 0x7da20c6aa560>]]] variable[result] assign[=] call[name[self].requester.post, parameter[name[report_url], dictionary[[<ast.Constant object at 0x7da20c6aa4a0>], [<ast.Name object at 0x7da20c6a84c0>]]]] if compare[name[result].status_code greater_or_equal[>=] constant[400]] begin[:] call[name[log].error, parameter[constant[Error posting comment to github. %s], call[name[result].json, parameter[]]]] return[name[result]]
keyword[def] identifier[post_comment] ( identifier[self] , identifier[message] ): literal[string] identifier[report_url] =( literal[string] %( identifier[self] . identifier[repo_name] , identifier[self] . identifier[pr_number] ) ) identifier[result] = identifier[self] . identifier[requester] . identifier[post] ( identifier[report_url] ,{ literal[string] : identifier[message] }) keyword[if] identifier[result] . identifier[status_code] >= literal[int] : identifier[log] . identifier[error] ( literal[string] , identifier[result] . identifier[json] ()) keyword[return] identifier[result]
def post_comment(self, message): """ Comments on an issue, not on a particular line. """ report_url = 'https://api.github.com/repos/%s/issues/%s/comments' % (self.repo_name, self.pr_number) result = self.requester.post(report_url, {'body': message}) if result.status_code >= 400: log.error('Error posting comment to github. %s', result.json()) # depends on [control=['if'], data=[]] return result
def __set_formulas(self, formulas): """ Sets formulas in this cell range from an iterable. Any cell values can be set using this method. Actual formulas must start with an equal sign. """ array = tuple((self._clean_formula(v),) for v in formulas) self._get_target().setFormulaArray(array)
def function[__set_formulas, parameter[self, formulas]]: constant[ Sets formulas in this cell range from an iterable. Any cell values can be set using this method. Actual formulas must start with an equal sign. ] variable[array] assign[=] call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da1b0c53010>]] call[call[name[self]._get_target, parameter[]].setFormulaArray, parameter[name[array]]]
keyword[def] identifier[__set_formulas] ( identifier[self] , identifier[formulas] ): literal[string] identifier[array] = identifier[tuple] (( identifier[self] . identifier[_clean_formula] ( identifier[v] ),) keyword[for] identifier[v] keyword[in] identifier[formulas] ) identifier[self] . identifier[_get_target] (). identifier[setFormulaArray] ( identifier[array] )
def __set_formulas(self, formulas): """ Sets formulas in this cell range from an iterable. Any cell values can be set using this method. Actual formulas must start with an equal sign. """ array = tuple(((self._clean_formula(v),) for v in formulas)) self._get_target().setFormulaArray(array)
def _get_call_summary(self, call, index=0, inspect_packages=True): ''' get a call summary a call summary is a nicely formatted string synopsis of the call handy for backtraces since -- 7-6-12 call_info -- dict -- the dict returned from _get_call_info() index -- integer -- set to something above 0 if you would like the summary to be numbered inspect_packages -- boolean -- set to True to get the full format even for system frames return -- string ''' call_info = call.info inspect_regex = re.compile(r'[\\\\/]python\d(?:\.\d+)?', re.I) # truncate the filepath if it is super long f = call_info['file'] if len(f) > 75: f = "{}...{}".format(f[0:30], f[-45:]) if inspect_packages or not inspect_regex.search(call_info['file']): s = "{}:{}\n\n{}\n\n".format( f, call_info['line'], String(call_info['call']).indent(1) ) else: s = "{}:{}\n".format( f, call_info['line'] ) if index > 0: s = "{:02d} - {}".format(index, s) return s
def function[_get_call_summary, parameter[self, call, index, inspect_packages]]: constant[ get a call summary a call summary is a nicely formatted string synopsis of the call handy for backtraces since -- 7-6-12 call_info -- dict -- the dict returned from _get_call_info() index -- integer -- set to something above 0 if you would like the summary to be numbered inspect_packages -- boolean -- set to True to get the full format even for system frames return -- string ] variable[call_info] assign[=] name[call].info variable[inspect_regex] assign[=] call[name[re].compile, parameter[constant[[\\\\/]python\d(?:\.\d+)?], name[re].I]] variable[f] assign[=] call[name[call_info]][constant[file]] if compare[call[name[len], parameter[name[f]]] greater[>] constant[75]] begin[:] variable[f] assign[=] call[constant[{}...{}].format, parameter[call[name[f]][<ast.Slice object at 0x7da18f58c760>], call[name[f]][<ast.Slice object at 0x7da18f58f670>]]] if <ast.BoolOp object at 0x7da18f58d2a0> begin[:] variable[s] assign[=] call[constant[{}:{} {} ].format, parameter[name[f], call[name[call_info]][constant[line]], call[call[name[String], parameter[call[name[call_info]][constant[call]]]].indent, parameter[constant[1]]]]] if compare[name[index] greater[>] constant[0]] begin[:] variable[s] assign[=] call[constant[{:02d} - {}].format, parameter[name[index], name[s]]] return[name[s]]
keyword[def] identifier[_get_call_summary] ( identifier[self] , identifier[call] , identifier[index] = literal[int] , identifier[inspect_packages] = keyword[True] ): literal[string] identifier[call_info] = identifier[call] . identifier[info] identifier[inspect_regex] = identifier[re] . identifier[compile] ( literal[string] , identifier[re] . identifier[I] ) identifier[f] = identifier[call_info] [ literal[string] ] keyword[if] identifier[len] ( identifier[f] )> literal[int] : identifier[f] = literal[string] . identifier[format] ( identifier[f] [ literal[int] : literal[int] ], identifier[f] [- literal[int] :]) keyword[if] identifier[inspect_packages] keyword[or] keyword[not] identifier[inspect_regex] . identifier[search] ( identifier[call_info] [ literal[string] ]): identifier[s] = literal[string] . identifier[format] ( identifier[f] , identifier[call_info] [ literal[string] ], identifier[String] ( identifier[call_info] [ literal[string] ]). identifier[indent] ( literal[int] ) ) keyword[else] : identifier[s] = literal[string] . identifier[format] ( identifier[f] , identifier[call_info] [ literal[string] ] ) keyword[if] identifier[index] > literal[int] : identifier[s] = literal[string] . identifier[format] ( identifier[index] , identifier[s] ) keyword[return] identifier[s]
def _get_call_summary(self, call, index=0, inspect_packages=True): """ get a call summary a call summary is a nicely formatted string synopsis of the call handy for backtraces since -- 7-6-12 call_info -- dict -- the dict returned from _get_call_info() index -- integer -- set to something above 0 if you would like the summary to be numbered inspect_packages -- boolean -- set to True to get the full format even for system frames return -- string """ call_info = call.info inspect_regex = re.compile('[\\\\\\\\/]python\\d(?:\\.\\d+)?', re.I) # truncate the filepath if it is super long f = call_info['file'] if len(f) > 75: f = '{}...{}'.format(f[0:30], f[-45:]) # depends on [control=['if'], data=[]] if inspect_packages or not inspect_regex.search(call_info['file']): s = '{}:{}\n\n{}\n\n'.format(f, call_info['line'], String(call_info['call']).indent(1)) # depends on [control=['if'], data=[]] else: s = '{}:{}\n'.format(f, call_info['line']) if index > 0: s = '{:02d} - {}'.format(index, s) # depends on [control=['if'], data=['index']] return s
def covariance_lagged(data=None, c00=True, c0t=True, ctt=False, remove_constant_mean=None, remove_data_mean=False, reversible=False, bessel=True, lag=0, weights="empirical", stride=1, skip=0, chunksize=None, ncov_max=float('inf'), column_selection=None, diag_only=False): r"""Compute lagged covariances between time series. If data is available as an array of size (TxN), where T is the number of time steps and N the number of dimensions, this function can compute lagged covariances like .. math:: C_00 &= X^T X \\ C_{0t} &= X^T Y \\ C_{tt} &= Y^T Y, where X comprises the first T-lag time steps and Y the last T-lag time steps. It is also possible to use more than one time series, the number of time steps in each time series can also vary. Parameters ---------- data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by source function array with the data, if available. When given, the covariances are immediately computed. c00 : bool, optional, default=True compute instantaneous correlations over the first part of the data. If lag==0, use all of the data. c0t : bool, optional, default=False compute lagged correlations. Does not work with lag==0. ctt : bool, optional, default=False compute instantaneous correlations over the second part of the data. Does not work with lag==0. remove_constant_mean : ndarray(N,), optional, default=None substract a constant vector of mean values from time series. remove_data_mean : bool, optional, default=False substract the sample mean from the time series (mean-free correlations). reversible : bool, optional, default=False symmetrize correlations. bessel : bool, optional, default=True use Bessel's correction for correlations in order to use an unbiased estimator lag : int, optional, default=0 lag time. Does not work with xy=True or yy=True. weights : optional, default="empirical" Re-weighting strategy to be used in order to compute equilibrium covariances from non-equilibrium data. * "empirical": no re-weighting * "koopman": use re-weighting procedure from [1]_ * weights: An object that allows to compute re-weighting factors. It must possess a method weights(X) that accepts a trajectory X (np.ndarray(T, n)) and returns a vector of re-weighting factors (np.ndarray(T,)). stride: int, optional, default = 1 Use only every stride-th time step. By default, every time step is used. skip : int, optional, default=0 skip the first initial n frames per trajectory. chunksize: int, default=None Number of data frames to process at once. Choose a higher value here, to optimize thread usage and gain processing speed. If None is passed, use the default value of the underlying reader/data source. Choose zero to disable chunking at all. ncov_max : int, default=infinity limit the memory usage of the algorithm from [2]_ to an amount that corresponds to ncov_max additional copies of each correlation matrix column_selection: ndarray(k, dtype=int) or None Indices of those columns that are to be computed. If None, all columns are computed. diag_only: bool If True, the computation is restricted to the diagonal entries (autocorrelations) only. Returns ------- lc : a :class:`LaggedCovariance <pyemma.coordinates.estimation.covariance.LaggedCovariance>` object. .. [1] Wu, H., Nueske, F., Paul, F., Klus, S., Koltai, P., and Noe, F. 2016. Bias reduced variational approximation of molecular kinetics from short off-equilibrium simulations. J. Chem. Phys. (submitted) .. [2] Chan, T. F., Golub G. H., LeVeque R. J. 1979. Updating formulae and pairwiese algorithms for computing sample variances. Technical Report STAN-CS-79-773, Department of Computer Science, Stanford University. """ from pyemma.coordinates.estimation.covariance import LaggedCovariance from pyemma.coordinates.estimation.koopman import _KoopmanEstimator import types if isinstance(weights, _string_types): if weights== "koopman": if data is None: raise ValueError("Data must be supplied for reweighting='koopman'") koop = _KoopmanEstimator(lag=lag, stride=stride, skip=skip, ncov_max=ncov_max) koop.estimate(data, chunksize=chunksize) weights = koop.weights elif weights == "empirical": weights = None else: raise ValueError("reweighting must be either 'empirical', 'koopman' " "or an object with a weights(data) method.") elif hasattr(weights, 'weights') and type(getattr(weights, 'weights')) == types.MethodType: pass elif isinstance(weights, (list, tuple, _np.ndarray)): pass else: raise ValueError("reweighting must be either 'empirical', 'koopman' or an object with a weights(data) method.") # chunksize is an estimation parameter for now. lc = LaggedCovariance(c00=c00, c0t=c0t, ctt=ctt, remove_constant_mean=remove_constant_mean, remove_data_mean=remove_data_mean, reversible=reversible, bessel=bessel, lag=lag, weights=weights, stride=stride, skip=skip, ncov_max=ncov_max, column_selection=column_selection, diag_only=diag_only) if data is not None: lc.estimate(data, chunksize=chunksize) else: lc.chunksize = chunksize return lc
def function[covariance_lagged, parameter[data, c00, c0t, ctt, remove_constant_mean, remove_data_mean, reversible, bessel, lag, weights, stride, skip, chunksize, ncov_max, column_selection, diag_only]]: constant[Compute lagged covariances between time series. If data is available as an array of size (TxN), where T is the number of time steps and N the number of dimensions, this function can compute lagged covariances like .. math:: C_00 &= X^T X \\ C_{0t} &= X^T Y \\ C_{tt} &= Y^T Y, where X comprises the first T-lag time steps and Y the last T-lag time steps. It is also possible to use more than one time series, the number of time steps in each time series can also vary. Parameters ---------- data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by source function array with the data, if available. When given, the covariances are immediately computed. c00 : bool, optional, default=True compute instantaneous correlations over the first part of the data. If lag==0, use all of the data. c0t : bool, optional, default=False compute lagged correlations. Does not work with lag==0. ctt : bool, optional, default=False compute instantaneous correlations over the second part of the data. Does not work with lag==0. remove_constant_mean : ndarray(N,), optional, default=None substract a constant vector of mean values from time series. remove_data_mean : bool, optional, default=False substract the sample mean from the time series (mean-free correlations). reversible : bool, optional, default=False symmetrize correlations. bessel : bool, optional, default=True use Bessel's correction for correlations in order to use an unbiased estimator lag : int, optional, default=0 lag time. Does not work with xy=True or yy=True. weights : optional, default="empirical" Re-weighting strategy to be used in order to compute equilibrium covariances from non-equilibrium data. * "empirical": no re-weighting * "koopman": use re-weighting procedure from [1]_ * weights: An object that allows to compute re-weighting factors. It must possess a method weights(X) that accepts a trajectory X (np.ndarray(T, n)) and returns a vector of re-weighting factors (np.ndarray(T,)). stride: int, optional, default = 1 Use only every stride-th time step. By default, every time step is used. skip : int, optional, default=0 skip the first initial n frames per trajectory. chunksize: int, default=None Number of data frames to process at once. Choose a higher value here, to optimize thread usage and gain processing speed. If None is passed, use the default value of the underlying reader/data source. Choose zero to disable chunking at all. ncov_max : int, default=infinity limit the memory usage of the algorithm from [2]_ to an amount that corresponds to ncov_max additional copies of each correlation matrix column_selection: ndarray(k, dtype=int) or None Indices of those columns that are to be computed. If None, all columns are computed. diag_only: bool If True, the computation is restricted to the diagonal entries (autocorrelations) only. Returns ------- lc : a :class:`LaggedCovariance <pyemma.coordinates.estimation.covariance.LaggedCovariance>` object. .. [1] Wu, H., Nueske, F., Paul, F., Klus, S., Koltai, P., and Noe, F. 2016. Bias reduced variational approximation of molecular kinetics from short off-equilibrium simulations. J. Chem. Phys. (submitted) .. [2] Chan, T. F., Golub G. H., LeVeque R. J. 1979. Updating formulae and pairwiese algorithms for computing sample variances. Technical Report STAN-CS-79-773, Department of Computer Science, Stanford University. ] from relative_module[pyemma.coordinates.estimation.covariance] import module[LaggedCovariance] from relative_module[pyemma.coordinates.estimation.koopman] import module[_KoopmanEstimator] import module[types] if call[name[isinstance], parameter[name[weights], name[_string_types]]] begin[:] if compare[name[weights] equal[==] constant[koopman]] begin[:] if compare[name[data] is constant[None]] begin[:] <ast.Raise object at 0x7da20c6aa770> variable[koop] assign[=] call[name[_KoopmanEstimator], parameter[]] call[name[koop].estimate, parameter[name[data]]] variable[weights] assign[=] name[koop].weights variable[lc] assign[=] call[name[LaggedCovariance], parameter[]] if compare[name[data] is_not constant[None]] begin[:] call[name[lc].estimate, parameter[name[data]]] return[name[lc]]
keyword[def] identifier[covariance_lagged] ( identifier[data] = keyword[None] , identifier[c00] = keyword[True] , identifier[c0t] = keyword[True] , identifier[ctt] = keyword[False] , identifier[remove_constant_mean] = keyword[None] , identifier[remove_data_mean] = keyword[False] , identifier[reversible] = keyword[False] , identifier[bessel] = keyword[True] , identifier[lag] = literal[int] , identifier[weights] = literal[string] , identifier[stride] = literal[int] , identifier[skip] = literal[int] , identifier[chunksize] = keyword[None] , identifier[ncov_max] = identifier[float] ( literal[string] ), identifier[column_selection] = keyword[None] , identifier[diag_only] = keyword[False] ): literal[string] keyword[from] identifier[pyemma] . identifier[coordinates] . identifier[estimation] . identifier[covariance] keyword[import] identifier[LaggedCovariance] keyword[from] identifier[pyemma] . identifier[coordinates] . identifier[estimation] . identifier[koopman] keyword[import] identifier[_KoopmanEstimator] keyword[import] identifier[types] keyword[if] identifier[isinstance] ( identifier[weights] , identifier[_string_types] ): keyword[if] identifier[weights] == literal[string] : keyword[if] identifier[data] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[koop] = identifier[_KoopmanEstimator] ( identifier[lag] = identifier[lag] , identifier[stride] = identifier[stride] , identifier[skip] = identifier[skip] , identifier[ncov_max] = identifier[ncov_max] ) identifier[koop] . identifier[estimate] ( identifier[data] , identifier[chunksize] = identifier[chunksize] ) identifier[weights] = identifier[koop] . identifier[weights] keyword[elif] identifier[weights] == literal[string] : identifier[weights] = keyword[None] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[elif] identifier[hasattr] ( identifier[weights] , literal[string] ) keyword[and] identifier[type] ( identifier[getattr] ( identifier[weights] , literal[string] ))== identifier[types] . identifier[MethodType] : keyword[pass] keyword[elif] identifier[isinstance] ( identifier[weights] ,( identifier[list] , identifier[tuple] , identifier[_np] . identifier[ndarray] )): keyword[pass] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[lc] = identifier[LaggedCovariance] ( identifier[c00] = identifier[c00] , identifier[c0t] = identifier[c0t] , identifier[ctt] = identifier[ctt] , identifier[remove_constant_mean] = identifier[remove_constant_mean] , identifier[remove_data_mean] = identifier[remove_data_mean] , identifier[reversible] = identifier[reversible] , identifier[bessel] = identifier[bessel] , identifier[lag] = identifier[lag] , identifier[weights] = identifier[weights] , identifier[stride] = identifier[stride] , identifier[skip] = identifier[skip] , identifier[ncov_max] = identifier[ncov_max] , identifier[column_selection] = identifier[column_selection] , identifier[diag_only] = identifier[diag_only] ) keyword[if] identifier[data] keyword[is] keyword[not] keyword[None] : identifier[lc] . identifier[estimate] ( identifier[data] , identifier[chunksize] = identifier[chunksize] ) keyword[else] : identifier[lc] . identifier[chunksize] = identifier[chunksize] keyword[return] identifier[lc]
def covariance_lagged(data=None, c00=True, c0t=True, ctt=False, remove_constant_mean=None, remove_data_mean=False, reversible=False, bessel=True, lag=0, weights='empirical', stride=1, skip=0, chunksize=None, ncov_max=float('inf'), column_selection=None, diag_only=False): """Compute lagged covariances between time series. If data is available as an array of size (TxN), where T is the number of time steps and N the number of dimensions, this function can compute lagged covariances like .. math:: C_00 &= X^T X \\\\ C_{0t} &= X^T Y \\\\ C_{tt} &= Y^T Y, where X comprises the first T-lag time steps and Y the last T-lag time steps. It is also possible to use more than one time series, the number of time steps in each time series can also vary. Parameters ---------- data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by source function array with the data, if available. When given, the covariances are immediately computed. c00 : bool, optional, default=True compute instantaneous correlations over the first part of the data. If lag==0, use all of the data. c0t : bool, optional, default=False compute lagged correlations. Does not work with lag==0. ctt : bool, optional, default=False compute instantaneous correlations over the second part of the data. Does not work with lag==0. remove_constant_mean : ndarray(N,), optional, default=None substract a constant vector of mean values from time series. remove_data_mean : bool, optional, default=False substract the sample mean from the time series (mean-free correlations). reversible : bool, optional, default=False symmetrize correlations. bessel : bool, optional, default=True use Bessel's correction for correlations in order to use an unbiased estimator lag : int, optional, default=0 lag time. Does not work with xy=True or yy=True. weights : optional, default="empirical" Re-weighting strategy to be used in order to compute equilibrium covariances from non-equilibrium data. * "empirical": no re-weighting * "koopman": use re-weighting procedure from [1]_ * weights: An object that allows to compute re-weighting factors. It must possess a method weights(X) that accepts a trajectory X (np.ndarray(T, n)) and returns a vector of re-weighting factors (np.ndarray(T,)). stride: int, optional, default = 1 Use only every stride-th time step. By default, every time step is used. skip : int, optional, default=0 skip the first initial n frames per trajectory. chunksize: int, default=None Number of data frames to process at once. Choose a higher value here, to optimize thread usage and gain processing speed. If None is passed, use the default value of the underlying reader/data source. Choose zero to disable chunking at all. ncov_max : int, default=infinity limit the memory usage of the algorithm from [2]_ to an amount that corresponds to ncov_max additional copies of each correlation matrix column_selection: ndarray(k, dtype=int) or None Indices of those columns that are to be computed. If None, all columns are computed. diag_only: bool If True, the computation is restricted to the diagonal entries (autocorrelations) only. Returns ------- lc : a :class:`LaggedCovariance <pyemma.coordinates.estimation.covariance.LaggedCovariance>` object. .. [1] Wu, H., Nueske, F., Paul, F., Klus, S., Koltai, P., and Noe, F. 2016. Bias reduced variational approximation of molecular kinetics from short off-equilibrium simulations. J. Chem. Phys. (submitted) .. [2] Chan, T. F., Golub G. H., LeVeque R. J. 1979. Updating formulae and pairwiese algorithms for computing sample variances. Technical Report STAN-CS-79-773, Department of Computer Science, Stanford University. """ from pyemma.coordinates.estimation.covariance import LaggedCovariance from pyemma.coordinates.estimation.koopman import _KoopmanEstimator import types if isinstance(weights, _string_types): if weights == 'koopman': if data is None: raise ValueError("Data must be supplied for reweighting='koopman'") # depends on [control=['if'], data=[]] koop = _KoopmanEstimator(lag=lag, stride=stride, skip=skip, ncov_max=ncov_max) koop.estimate(data, chunksize=chunksize) weights = koop.weights # depends on [control=['if'], data=['weights']] elif weights == 'empirical': weights = None # depends on [control=['if'], data=['weights']] else: raise ValueError("reweighting must be either 'empirical', 'koopman' or an object with a weights(data) method.") # depends on [control=['if'], data=[]] elif hasattr(weights, 'weights') and type(getattr(weights, 'weights')) == types.MethodType: pass # depends on [control=['if'], data=[]] elif isinstance(weights, (list, tuple, _np.ndarray)): pass # depends on [control=['if'], data=[]] else: raise ValueError("reweighting must be either 'empirical', 'koopman' or an object with a weights(data) method.") # chunksize is an estimation parameter for now. lc = LaggedCovariance(c00=c00, c0t=c0t, ctt=ctt, remove_constant_mean=remove_constant_mean, remove_data_mean=remove_data_mean, reversible=reversible, bessel=bessel, lag=lag, weights=weights, stride=stride, skip=skip, ncov_max=ncov_max, column_selection=column_selection, diag_only=diag_only) if data is not None: lc.estimate(data, chunksize=chunksize) # depends on [control=['if'], data=['data']] else: lc.chunksize = chunksize return lc
def remove_done_callback(self, func): """Remove a callback from the long running operation. :param callable func: The function to be removed from the callbacks. :raises: ValueError if the long running operation has already completed. """ if self._done is None or self._done.is_set(): raise ValueError("Process is complete.") self._callbacks = [c for c in self._callbacks if c != func]
def function[remove_done_callback, parameter[self, func]]: constant[Remove a callback from the long running operation. :param callable func: The function to be removed from the callbacks. :raises: ValueError if the long running operation has already completed. ] if <ast.BoolOp object at 0x7da2054a54e0> begin[:] <ast.Raise object at 0x7da2054a7e50> name[self]._callbacks assign[=] <ast.ListComp object at 0x7da2054a61d0>
keyword[def] identifier[remove_done_callback] ( identifier[self] , identifier[func] ): literal[string] keyword[if] identifier[self] . identifier[_done] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[_done] . identifier[is_set] (): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[self] . identifier[_callbacks] =[ identifier[c] keyword[for] identifier[c] keyword[in] identifier[self] . identifier[_callbacks] keyword[if] identifier[c] != identifier[func] ]
def remove_done_callback(self, func): """Remove a callback from the long running operation. :param callable func: The function to be removed from the callbacks. :raises: ValueError if the long running operation has already completed. """ if self._done is None or self._done.is_set(): raise ValueError('Process is complete.') # depends on [control=['if'], data=[]] self._callbacks = [c for c in self._callbacks if c != func]
def render(self, context, instance, placeholder): ''' Allows this plugin to use templates designed for a list of locations. ''' context = super(StatsGraphPlugin,self).render(context,instance,placeholder) # Javascript makes it difficult to calculate date/time differences, so instead # pass the most useful ones to the template context in a dictionary. These are used # to show stats over different time ranges. limitMonthDates = {} for m in range(0,25): limitMonthDates[m] = (timezone.now() - relativedelta(months=m)).strftime('%Y-%m-%d') # The same for graphs that allow one to choose different years. recentYears = [timezone.now().year + x for x in range(-5,1)] series_by_year = Series.objects.order_by('year') if series_by_year.count() > 0: first_year = series_by_year.first().year allYears = [x for x in range(first_year,timezone.now().year + 1)] else: allYears = [] context.update({ 'limitMonthDates': limitMonthDates, 'recentYears': recentYears, 'allYears': allYears, }) return context
def function[render, parameter[self, context, instance, placeholder]]: constant[ Allows this plugin to use templates designed for a list of locations. ] variable[context] assign[=] call[call[name[super], parameter[name[StatsGraphPlugin], name[self]]].render, parameter[name[context], name[instance], name[placeholder]]] variable[limitMonthDates] assign[=] dictionary[[], []] for taget[name[m]] in starred[call[name[range], parameter[constant[0], constant[25]]]] begin[:] call[name[limitMonthDates]][name[m]] assign[=] call[binary_operation[call[name[timezone].now, parameter[]] - call[name[relativedelta], parameter[]]].strftime, parameter[constant[%Y-%m-%d]]] variable[recentYears] assign[=] <ast.ListComp object at 0x7da1b15eb130> variable[series_by_year] assign[=] call[name[Series].objects.order_by, parameter[constant[year]]] if compare[call[name[series_by_year].count, parameter[]] greater[>] constant[0]] begin[:] variable[first_year] assign[=] call[name[series_by_year].first, parameter[]].year variable[allYears] assign[=] <ast.ListComp object at 0x7da1b15ea6b0> call[name[context].update, parameter[dictionary[[<ast.Constant object at 0x7da1b15ebd00>, <ast.Constant object at 0x7da1b15eb340>, <ast.Constant object at 0x7da1b15ea3b0>], [<ast.Name object at 0x7da1b15e8430>, <ast.Name object at 0x7da1b15e9750>, <ast.Name object at 0x7da1b15e8490>]]]] return[name[context]]
keyword[def] identifier[render] ( identifier[self] , identifier[context] , identifier[instance] , identifier[placeholder] ): literal[string] identifier[context] = identifier[super] ( identifier[StatsGraphPlugin] , identifier[self] ). identifier[render] ( identifier[context] , identifier[instance] , identifier[placeholder] ) identifier[limitMonthDates] ={} keyword[for] identifier[m] keyword[in] identifier[range] ( literal[int] , literal[int] ): identifier[limitMonthDates] [ identifier[m] ]=( identifier[timezone] . identifier[now] ()- identifier[relativedelta] ( identifier[months] = identifier[m] )). identifier[strftime] ( literal[string] ) identifier[recentYears] =[ identifier[timezone] . identifier[now] (). identifier[year] + identifier[x] keyword[for] identifier[x] keyword[in] identifier[range] (- literal[int] , literal[int] )] identifier[series_by_year] = identifier[Series] . identifier[objects] . identifier[order_by] ( literal[string] ) keyword[if] identifier[series_by_year] . identifier[count] ()> literal[int] : identifier[first_year] = identifier[series_by_year] . identifier[first] (). identifier[year] identifier[allYears] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[range] ( identifier[first_year] , identifier[timezone] . identifier[now] (). identifier[year] + literal[int] )] keyword[else] : identifier[allYears] =[] identifier[context] . identifier[update] ({ literal[string] : identifier[limitMonthDates] , literal[string] : identifier[recentYears] , literal[string] : identifier[allYears] , }) keyword[return] identifier[context]
def render(self, context, instance, placeholder): """ Allows this plugin to use templates designed for a list of locations. """ context = super(StatsGraphPlugin, self).render(context, instance, placeholder) # Javascript makes it difficult to calculate date/time differences, so instead # pass the most useful ones to the template context in a dictionary. These are used # to show stats over different time ranges. limitMonthDates = {} for m in range(0, 25): limitMonthDates[m] = (timezone.now() - relativedelta(months=m)).strftime('%Y-%m-%d') # depends on [control=['for'], data=['m']] # The same for graphs that allow one to choose different years. recentYears = [timezone.now().year + x for x in range(-5, 1)] series_by_year = Series.objects.order_by('year') if series_by_year.count() > 0: first_year = series_by_year.first().year allYears = [x for x in range(first_year, timezone.now().year + 1)] # depends on [control=['if'], data=[]] else: allYears = [] context.update({'limitMonthDates': limitMonthDates, 'recentYears': recentYears, 'allYears': allYears}) return context
def identify_core(core): """Identify the polynomial argument.""" for datatype, identifier in { int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, float: _identify_scaler, numpy.float16: _identify_scaler, numpy.float32: _identify_scaler, numpy.float64: _identify_scaler, chaospy.poly.base.Poly: _identify_poly, dict: _identify_dict, numpy.ndarray: _identify_iterable, list: _identify_iterable, tuple: _identify_iterable, }.items(): if isinstance(core, datatype): return identifier(core) raise TypeError( "Poly arg: 'core' is not a valid type " + repr(core))
def function[identify_core, parameter[core]]: constant[Identify the polynomial argument.] for taget[tuple[[<ast.Name object at 0x7da18ede5960>, <ast.Name object at 0x7da18ede67a0>]]] in starred[call[dictionary[[<ast.Name object at 0x7da18ede5180>, <ast.Attribute object at 0x7da18ede5540>, <ast.Attribute object at 0x7da18ede4790>, <ast.Attribute object at 0x7da18ede4ee0>, <ast.Attribute object at 0x7da18ede6500>, <ast.Name object at 0x7da18ede46a0>, <ast.Attribute object at 0x7da18ede44f0>, <ast.Attribute object at 0x7da18ede4d00>, <ast.Attribute object at 0x7da18ede6b90>, <ast.Attribute object at 0x7da18ede49d0>, <ast.Name object at 0x7da18ede7370>, <ast.Attribute object at 0x7da18ede6ec0>, <ast.Name object at 0x7da18ede4250>, <ast.Name object at 0x7da18ede5cf0>], [<ast.Name object at 0x7da18ede58d0>, <ast.Name object at 0x7da18ede50f0>, <ast.Name object at 0x7da18ede7280>, <ast.Name object at 0x7da2054a6a10>, <ast.Name object at 0x7da2054a4880>, <ast.Name object at 0x7da2054a7370>, <ast.Name object at 0x7da2054a59f0>, <ast.Name object at 0x7da2054a40a0>, <ast.Name object at 0x7da2054a79a0>, <ast.Name object at 0x7da2054a5ba0>, <ast.Name object at 0x7da2054a6ef0>, <ast.Name object at 0x7da2054a4550>, <ast.Name object at 0x7da2054a7ac0>, <ast.Name object at 0x7da2054a7d90>]].items, parameter[]]] begin[:] if call[name[isinstance], parameter[name[core], name[datatype]]] begin[:] return[call[name[identifier], parameter[name[core]]]] <ast.Raise object at 0x7da2054a7bb0>
keyword[def] identifier[identify_core] ( identifier[core] ): literal[string] keyword[for] identifier[datatype] , identifier[identifier] keyword[in] { identifier[int] : identifier[_identify_scaler] , identifier[numpy] . identifier[int8] : identifier[_identify_scaler] , identifier[numpy] . identifier[int16] : identifier[_identify_scaler] , identifier[numpy] . identifier[int32] : identifier[_identify_scaler] , identifier[numpy] . identifier[int64] : identifier[_identify_scaler] , identifier[float] : identifier[_identify_scaler] , identifier[numpy] . identifier[float16] : identifier[_identify_scaler] , identifier[numpy] . identifier[float32] : identifier[_identify_scaler] , identifier[numpy] . identifier[float64] : identifier[_identify_scaler] , identifier[chaospy] . identifier[poly] . identifier[base] . identifier[Poly] : identifier[_identify_poly] , identifier[dict] : identifier[_identify_dict] , identifier[numpy] . identifier[ndarray] : identifier[_identify_iterable] , identifier[list] : identifier[_identify_iterable] , identifier[tuple] : identifier[_identify_iterable] , }. identifier[items] (): keyword[if] identifier[isinstance] ( identifier[core] , identifier[datatype] ): keyword[return] identifier[identifier] ( identifier[core] ) keyword[raise] identifier[TypeError] ( literal[string] + identifier[repr] ( identifier[core] ))
def identify_core(core): """Identify the polynomial argument.""" for (datatype, identifier) in {int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, float: _identify_scaler, numpy.float16: _identify_scaler, numpy.float32: _identify_scaler, numpy.float64: _identify_scaler, chaospy.poly.base.Poly: _identify_poly, dict: _identify_dict, numpy.ndarray: _identify_iterable, list: _identify_iterable, tuple: _identify_iterable}.items(): if isinstance(core, datatype): return identifier(core) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] raise TypeError("Poly arg: 'core' is not a valid type " + repr(core))
def create_sqs_policy(self, topic_name, topic_arn, topic_subs): """ This method creates the SQS policy needed for an SNS subscription. It also takes the ARN of the SQS queue and converts it to the URL needed for the subscription, as that takes a URL rather than the ARN. """ t = self.template arn_endpoints = [] url_endpoints = [] for sub in topic_subs: arn_endpoints.append(sub["Endpoint"]) split_endpoint = sub["Endpoint"].split(":") queue_url = "https://%s.%s.amazonaws.com/%s/%s" % ( split_endpoint[2], # literally "sqs" split_endpoint[3], # AWS region split_endpoint[4], # AWS ID split_endpoint[5], # Queue name ) url_endpoints.append(queue_url) policy_doc = queue_policy(topic_arn, arn_endpoints) t.add_resource( sqs.QueuePolicy( topic_name + "SubPolicy", PolicyDocument=policy_doc, Queues=url_endpoints, ) )
def function[create_sqs_policy, parameter[self, topic_name, topic_arn, topic_subs]]: constant[ This method creates the SQS policy needed for an SNS subscription. It also takes the ARN of the SQS queue and converts it to the URL needed for the subscription, as that takes a URL rather than the ARN. ] variable[t] assign[=] name[self].template variable[arn_endpoints] assign[=] list[[]] variable[url_endpoints] assign[=] list[[]] for taget[name[sub]] in starred[name[topic_subs]] begin[:] call[name[arn_endpoints].append, parameter[call[name[sub]][constant[Endpoint]]]] variable[split_endpoint] assign[=] call[call[name[sub]][constant[Endpoint]].split, parameter[constant[:]]] variable[queue_url] assign[=] binary_operation[constant[https://%s.%s.amazonaws.com/%s/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Subscript object at 0x7da1b061bee0>, <ast.Subscript object at 0x7da1b061b910>, <ast.Subscript object at 0x7da1b0619b10>, <ast.Subscript object at 0x7da1b061a290>]]] call[name[url_endpoints].append, parameter[name[queue_url]]] variable[policy_doc] assign[=] call[name[queue_policy], parameter[name[topic_arn], name[arn_endpoints]]] call[name[t].add_resource, parameter[call[name[sqs].QueuePolicy, parameter[binary_operation[name[topic_name] + constant[SubPolicy]]]]]]
keyword[def] identifier[create_sqs_policy] ( identifier[self] , identifier[topic_name] , identifier[topic_arn] , identifier[topic_subs] ): literal[string] identifier[t] = identifier[self] . identifier[template] identifier[arn_endpoints] =[] identifier[url_endpoints] =[] keyword[for] identifier[sub] keyword[in] identifier[topic_subs] : identifier[arn_endpoints] . identifier[append] ( identifier[sub] [ literal[string] ]) identifier[split_endpoint] = identifier[sub] [ literal[string] ]. identifier[split] ( literal[string] ) identifier[queue_url] = literal[string] %( identifier[split_endpoint] [ literal[int] ], identifier[split_endpoint] [ literal[int] ], identifier[split_endpoint] [ literal[int] ], identifier[split_endpoint] [ literal[int] ], ) identifier[url_endpoints] . identifier[append] ( identifier[queue_url] ) identifier[policy_doc] = identifier[queue_policy] ( identifier[topic_arn] , identifier[arn_endpoints] ) identifier[t] . identifier[add_resource] ( identifier[sqs] . identifier[QueuePolicy] ( identifier[topic_name] + literal[string] , identifier[PolicyDocument] = identifier[policy_doc] , identifier[Queues] = identifier[url_endpoints] , ) )
def create_sqs_policy(self, topic_name, topic_arn, topic_subs): """ This method creates the SQS policy needed for an SNS subscription. It also takes the ARN of the SQS queue and converts it to the URL needed for the subscription, as that takes a URL rather than the ARN. """ t = self.template arn_endpoints = [] url_endpoints = [] for sub in topic_subs: arn_endpoints.append(sub['Endpoint']) split_endpoint = sub['Endpoint'].split(':') # literally "sqs" # AWS region # AWS ID # Queue name queue_url = 'https://%s.%s.amazonaws.com/%s/%s' % (split_endpoint[2], split_endpoint[3], split_endpoint[4], split_endpoint[5]) url_endpoints.append(queue_url) # depends on [control=['for'], data=['sub']] policy_doc = queue_policy(topic_arn, arn_endpoints) t.add_resource(sqs.QueuePolicy(topic_name + 'SubPolicy', PolicyDocument=policy_doc, Queues=url_endpoints))
def publish_extensions(self, handler): """Publish the Media RSS Feed elements as XML.""" if isinstance(self.media_content, list): [PyRSS2Gen._opt_element(handler, "media:content", mc_element) for mc_element in self.media_content] else: PyRSS2Gen._opt_element(handler, "media:content", self.media_content) if hasattr(self, 'media_title'): PyRSS2Gen._opt_element(handler, "media:title", self.media_title) if hasattr(self, 'media_text'): PyRSS2Gen._opt_element(handler, "media:text", self.media_text)
def function[publish_extensions, parameter[self, handler]]: constant[Publish the Media RSS Feed elements as XML.] if call[name[isinstance], parameter[name[self].media_content, name[list]]] begin[:] <ast.ListComp object at 0x7da18fe92a10> if call[name[hasattr], parameter[name[self], constant[media_title]]] begin[:] call[name[PyRSS2Gen]._opt_element, parameter[name[handler], constant[media:title], name[self].media_title]] if call[name[hasattr], parameter[name[self], constant[media_text]]] begin[:] call[name[PyRSS2Gen]._opt_element, parameter[name[handler], constant[media:text], name[self].media_text]]
keyword[def] identifier[publish_extensions] ( identifier[self] , identifier[handler] ): literal[string] keyword[if] identifier[isinstance] ( identifier[self] . identifier[media_content] , identifier[list] ): [ identifier[PyRSS2Gen] . identifier[_opt_element] ( identifier[handler] , literal[string] , identifier[mc_element] ) keyword[for] identifier[mc_element] keyword[in] identifier[self] . identifier[media_content] ] keyword[else] : identifier[PyRSS2Gen] . identifier[_opt_element] ( identifier[handler] , literal[string] , identifier[self] . identifier[media_content] ) keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[PyRSS2Gen] . identifier[_opt_element] ( identifier[handler] , literal[string] , identifier[self] . identifier[media_title] ) keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[PyRSS2Gen] . identifier[_opt_element] ( identifier[handler] , literal[string] , identifier[self] . identifier[media_text] )
def publish_extensions(self, handler): """Publish the Media RSS Feed elements as XML.""" if isinstance(self.media_content, list): [PyRSS2Gen._opt_element(handler, 'media:content', mc_element) for mc_element in self.media_content] # depends on [control=['if'], data=[]] else: PyRSS2Gen._opt_element(handler, 'media:content', self.media_content) if hasattr(self, 'media_title'): PyRSS2Gen._opt_element(handler, 'media:title', self.media_title) # depends on [control=['if'], data=[]] if hasattr(self, 'media_text'): PyRSS2Gen._opt_element(handler, 'media:text', self.media_text) # depends on [control=['if'], data=[]]
def use_comparative_assessment_part_bank_view(self): """Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view""" self._bank_view = COMPARATIVE # self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_comparative_bank_view() except AttributeError: pass
def function[use_comparative_assessment_part_bank_view, parameter[self]]: constant[Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view] name[self]._bank_view assign[=] name[COMPARATIVE] for taget[name[session]] in starred[call[name[self]._get_provider_sessions, parameter[]]] begin[:] <ast.Try object at 0x7da18f58d030>
keyword[def] identifier[use_comparative_assessment_part_bank_view] ( identifier[self] ): literal[string] identifier[self] . identifier[_bank_view] = identifier[COMPARATIVE] keyword[for] identifier[session] keyword[in] identifier[self] . identifier[_get_provider_sessions] (): keyword[try] : identifier[session] . identifier[use_comparative_bank_view] () keyword[except] identifier[AttributeError] : keyword[pass]
def use_comparative_assessment_part_bank_view(self): """Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view""" self._bank_view = COMPARATIVE # self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_comparative_bank_view() # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['session']]
def operations(nsteps): '''Returns the number of operations needed for nsteps of GMRES''' return {'A': 1 + nsteps, 'M': 2 + nsteps, 'Ml': 2 + nsteps, 'Mr': 1 + nsteps, 'ip_B': 2 + nsteps + nsteps*(nsteps+1)/2, 'axpy': 4 + 2*nsteps + nsteps*(nsteps+1)/2 }
def function[operations, parameter[nsteps]]: constant[Returns the number of operations needed for nsteps of GMRES] return[dictionary[[<ast.Constant object at 0x7da1b26e3490>, <ast.Constant object at 0x7da1b26f0520>, <ast.Constant object at 0x7da1b26f0550>, <ast.Constant object at 0x7da1b26f0580>, <ast.Constant object at 0x7da1b26f05b0>, <ast.Constant object at 0x7da1b26f05e0>], [<ast.BinOp object at 0x7da1b26f0640>, <ast.BinOp object at 0x7da1b26f06d0>, <ast.BinOp object at 0x7da1b26f0760>, <ast.BinOp object at 0x7da1b26f07f0>, <ast.BinOp object at 0x7da1b26f0880>, <ast.BinOp object at 0x7da1b26f0a90>]]]
keyword[def] identifier[operations] ( identifier[nsteps] ): literal[string] keyword[return] { literal[string] : literal[int] + identifier[nsteps] , literal[string] : literal[int] + identifier[nsteps] , literal[string] : literal[int] + identifier[nsteps] , literal[string] : literal[int] + identifier[nsteps] , literal[string] : literal[int] + identifier[nsteps] + identifier[nsteps] *( identifier[nsteps] + literal[int] )/ literal[int] , literal[string] : literal[int] + literal[int] * identifier[nsteps] + identifier[nsteps] *( identifier[nsteps] + literal[int] )/ literal[int] }
def operations(nsteps): """Returns the number of operations needed for nsteps of GMRES""" return {'A': 1 + nsteps, 'M': 2 + nsteps, 'Ml': 2 + nsteps, 'Mr': 1 + nsteps, 'ip_B': 2 + nsteps + nsteps * (nsteps + 1) / 2, 'axpy': 4 + 2 * nsteps + nsteps * (nsteps + 1) / 2}
def compile_attribute(line, in_key, foreign_key_sql): """ Convert attribute definition from DataJoint format to SQL :param line: attribution line :param in_key: set to True if attribute is in primary key set :param foreign_key_sql: :returns: (name, sql, is_external) -- attribute name and sql code for its declaration """ try: match = attribute_parser.parseString(line+'#', parseAll=True) except pp.ParseException as err: raise DataJointError('Declaration error in position {pos} in line:\n {line}\n{msg}'.format( line=err.args[0], pos=err.args[1], msg=err.args[2])) match['comment'] = match['comment'].rstrip('#') if 'default' not in match: match['default'] = '' match = {k: v.strip() for k, v in match.items()} match['nullable'] = match['default'].lower() == 'null' accepted_datatype = r'time|date|year|enum|(var)?char|float|real|double|decimal|numeric|' \ r'(tiny|small|medium|big)?int|bool|' \ r'(tiny|small|medium|long)?blob|external|attach' if re.match(accepted_datatype, match['type'], re.I) is None: raise DataJointError('DataJoint does not support datatype "{type}"'.format(**match)) literals = ['CURRENT_TIMESTAMP'] # not to be enclosed in quotes if match['nullable']: if in_key: raise DataJointError('Primary key attributes cannot be nullable in line %s' % line) match['default'] = 'DEFAULT NULL' # nullable attributes default to null else: if match['default']: quote = match['default'].upper() not in literals and match['default'][0] not in '"\'' match['default'] = ('NOT NULL DEFAULT ' + ('"%s"' if quote else "%s") % match['default']) else: match['default'] = 'NOT NULL' match['comment'] = match['comment'].replace('"', '\\"') # escape double quotes in comment is_external = match['type'].startswith('external') is_attachment = match['type'].startswith('attachment') if not is_external: sql = ('`{name}` {type} {default}' + (' COMMENT "{comment}"' if match['comment'] else '')).format(**match) else: # process externally stored attribute if in_key: raise DataJointError('External attributes cannot be primary in:\n%s' % line) store_name = match['type'].split('-') if store_name[0] != 'external': raise DataJointError('External store types must be specified as "external" or "external-<name>"') store_name = '-'.join(store_name[1:]) if store_name != '' and not store_name.isidentifier(): raise DataJointError( 'The external store name `{type}` is invalid. Make like a python identifier.'.format(**match)) if len(store_name) > STORE_NAME_LENGTH: raise DataJointError( 'The external store name `{type}` is too long. Must be <={max_len} characters.'.format( max_len=STORE_NAME_LENGTH, **match)) if not match['default'] in ('DEFAULT NULL', 'NOT NULL'): raise DataJointError('The only acceptable default value for an external field is null in:\n%s' % line) if match['type'] not in config: raise DataJointError('The external store `{type}` is not configured.'.format(**match)) # append external configuration name to the end of the comment sql = '`{name}` {hash_type} {default} COMMENT ":{type}:{comment}"'.format( hash_type=HASH_DATA_TYPE, **match) foreign_key_sql.append( "FOREIGN KEY (`{name}`) REFERENCES {{external_table}} (`hash`) " "ON UPDATE RESTRICT ON DELETE RESTRICT".format(**match)) return match['name'], sql, is_external
def function[compile_attribute, parameter[line, in_key, foreign_key_sql]]: constant[ Convert attribute definition from DataJoint format to SQL :param line: attribution line :param in_key: set to True if attribute is in primary key set :param foreign_key_sql: :returns: (name, sql, is_external) -- attribute name and sql code for its declaration ] <ast.Try object at 0x7da2054a64d0> call[name[match]][constant[comment]] assign[=] call[call[name[match]][constant[comment]].rstrip, parameter[constant[#]]] if compare[constant[default] <ast.NotIn object at 0x7da2590d7190> name[match]] begin[:] call[name[match]][constant[default]] assign[=] constant[] variable[match] assign[=] <ast.DictComp object at 0x7da2054a7e50> call[name[match]][constant[nullable]] assign[=] compare[call[call[name[match]][constant[default]].lower, parameter[]] equal[==] constant[null]] variable[accepted_datatype] assign[=] constant[time|date|year|enum|(var)?char|float|real|double|decimal|numeric|(tiny|small|medium|big)?int|bool|(tiny|small|medium|long)?blob|external|attach] if compare[call[name[re].match, parameter[name[accepted_datatype], call[name[match]][constant[type]], name[re].I]] is constant[None]] begin[:] <ast.Raise object at 0x7da2054a7430> variable[literals] assign[=] list[[<ast.Constant object at 0x7da2054a4df0>]] if call[name[match]][constant[nullable]] begin[:] if name[in_key] begin[:] <ast.Raise object at 0x7da2054a6500> call[name[match]][constant[default]] assign[=] constant[DEFAULT NULL] call[name[match]][constant[comment]] assign[=] call[call[name[match]][constant[comment]].replace, parameter[constant["], constant[\"]]] variable[is_external] assign[=] call[call[name[match]][constant[type]].startswith, parameter[constant[external]]] variable[is_attachment] assign[=] call[call[name[match]][constant[type]].startswith, parameter[constant[attachment]]] if <ast.UnaryOp object at 0x7da2054a60b0> begin[:] variable[sql] assign[=] call[binary_operation[constant[`{name}` {type} {default}] + <ast.IfExp object at 0x7da2054a7250>].format, parameter[]] return[tuple[[<ast.Subscript object at 0x7da20e9542e0>, <ast.Name object at 0x7da20e954dc0>, <ast.Name object at 0x7da20e956380>]]]
keyword[def] identifier[compile_attribute] ( identifier[line] , identifier[in_key] , identifier[foreign_key_sql] ): literal[string] keyword[try] : identifier[match] = identifier[attribute_parser] . identifier[parseString] ( identifier[line] + literal[string] , identifier[parseAll] = keyword[True] ) keyword[except] identifier[pp] . identifier[ParseException] keyword[as] identifier[err] : keyword[raise] identifier[DataJointError] ( literal[string] . identifier[format] ( identifier[line] = identifier[err] . identifier[args] [ literal[int] ], identifier[pos] = identifier[err] . identifier[args] [ literal[int] ], identifier[msg] = identifier[err] . identifier[args] [ literal[int] ])) identifier[match] [ literal[string] ]= identifier[match] [ literal[string] ]. identifier[rstrip] ( literal[string] ) keyword[if] literal[string] keyword[not] keyword[in] identifier[match] : identifier[match] [ literal[string] ]= literal[string] identifier[match] ={ identifier[k] : identifier[v] . identifier[strip] () keyword[for] identifier[k] , identifier[v] keyword[in] identifier[match] . identifier[items] ()} identifier[match] [ literal[string] ]= identifier[match] [ literal[string] ]. identifier[lower] ()== literal[string] identifier[accepted_datatype] = literal[string] literal[string] literal[string] keyword[if] identifier[re] . identifier[match] ( identifier[accepted_datatype] , identifier[match] [ literal[string] ], identifier[re] . identifier[I] ) keyword[is] keyword[None] : keyword[raise] identifier[DataJointError] ( literal[string] . identifier[format] (** identifier[match] )) identifier[literals] =[ literal[string] ] keyword[if] identifier[match] [ literal[string] ]: keyword[if] identifier[in_key] : keyword[raise] identifier[DataJointError] ( literal[string] % identifier[line] ) identifier[match] [ literal[string] ]= literal[string] keyword[else] : keyword[if] identifier[match] [ literal[string] ]: identifier[quote] = identifier[match] [ literal[string] ]. identifier[upper] () keyword[not] keyword[in] identifier[literals] keyword[and] identifier[match] [ literal[string] ][ literal[int] ] keyword[not] keyword[in] literal[string] identifier[match] [ literal[string] ]=( literal[string] + ( literal[string] keyword[if] identifier[quote] keyword[else] literal[string] )% identifier[match] [ literal[string] ]) keyword[else] : identifier[match] [ literal[string] ]= literal[string] identifier[match] [ literal[string] ]= identifier[match] [ literal[string] ]. identifier[replace] ( literal[string] , literal[string] ) identifier[is_external] = identifier[match] [ literal[string] ]. identifier[startswith] ( literal[string] ) identifier[is_attachment] = identifier[match] [ literal[string] ]. identifier[startswith] ( literal[string] ) keyword[if] keyword[not] identifier[is_external] : identifier[sql] =( literal[string] +( literal[string] keyword[if] identifier[match] [ literal[string] ] keyword[else] literal[string] )). identifier[format] (** identifier[match] ) keyword[else] : keyword[if] identifier[in_key] : keyword[raise] identifier[DataJointError] ( literal[string] % identifier[line] ) identifier[store_name] = identifier[match] [ literal[string] ]. identifier[split] ( literal[string] ) keyword[if] identifier[store_name] [ literal[int] ]!= literal[string] : keyword[raise] identifier[DataJointError] ( literal[string] ) identifier[store_name] = literal[string] . identifier[join] ( identifier[store_name] [ literal[int] :]) keyword[if] identifier[store_name] != literal[string] keyword[and] keyword[not] identifier[store_name] . identifier[isidentifier] (): keyword[raise] identifier[DataJointError] ( literal[string] . identifier[format] (** identifier[match] )) keyword[if] identifier[len] ( identifier[store_name] )> identifier[STORE_NAME_LENGTH] : keyword[raise] identifier[DataJointError] ( literal[string] . identifier[format] ( identifier[max_len] = identifier[STORE_NAME_LENGTH] ,** identifier[match] )) keyword[if] keyword[not] identifier[match] [ literal[string] ] keyword[in] ( literal[string] , literal[string] ): keyword[raise] identifier[DataJointError] ( literal[string] % identifier[line] ) keyword[if] identifier[match] [ literal[string] ] keyword[not] keyword[in] identifier[config] : keyword[raise] identifier[DataJointError] ( literal[string] . identifier[format] (** identifier[match] )) identifier[sql] = literal[string] . identifier[format] ( identifier[hash_type] = identifier[HASH_DATA_TYPE] ,** identifier[match] ) identifier[foreign_key_sql] . identifier[append] ( literal[string] literal[string] . identifier[format] (** identifier[match] )) keyword[return] identifier[match] [ literal[string] ], identifier[sql] , identifier[is_external]
def compile_attribute(line, in_key, foreign_key_sql): """ Convert attribute definition from DataJoint format to SQL :param line: attribution line :param in_key: set to True if attribute is in primary key set :param foreign_key_sql: :returns: (name, sql, is_external) -- attribute name and sql code for its declaration """ try: match = attribute_parser.parseString(line + '#', parseAll=True) # depends on [control=['try'], data=[]] except pp.ParseException as err: raise DataJointError('Declaration error in position {pos} in line:\n {line}\n{msg}'.format(line=err.args[0], pos=err.args[1], msg=err.args[2])) # depends on [control=['except'], data=['err']] match['comment'] = match['comment'].rstrip('#') if 'default' not in match: match['default'] = '' # depends on [control=['if'], data=['match']] match = {k: v.strip() for (k, v) in match.items()} match['nullable'] = match['default'].lower() == 'null' accepted_datatype = 'time|date|year|enum|(var)?char|float|real|double|decimal|numeric|(tiny|small|medium|big)?int|bool|(tiny|small|medium|long)?blob|external|attach' if re.match(accepted_datatype, match['type'], re.I) is None: raise DataJointError('DataJoint does not support datatype "{type}"'.format(**match)) # depends on [control=['if'], data=[]] literals = ['CURRENT_TIMESTAMP'] # not to be enclosed in quotes if match['nullable']: if in_key: raise DataJointError('Primary key attributes cannot be nullable in line %s' % line) # depends on [control=['if'], data=[]] match['default'] = 'DEFAULT NULL' # nullable attributes default to null # depends on [control=['if'], data=[]] elif match['default']: quote = match['default'].upper() not in literals and match['default'][0] not in '"\'' match['default'] = 'NOT NULL DEFAULT ' + ('"%s"' if quote else '%s') % match['default'] # depends on [control=['if'], data=[]] else: match['default'] = 'NOT NULL' match['comment'] = match['comment'].replace('"', '\\"') # escape double quotes in comment is_external = match['type'].startswith('external') is_attachment = match['type'].startswith('attachment') if not is_external: sql = ('`{name}` {type} {default}' + (' COMMENT "{comment}"' if match['comment'] else '')).format(**match) # depends on [control=['if'], data=[]] else: # process externally stored attribute if in_key: raise DataJointError('External attributes cannot be primary in:\n%s' % line) # depends on [control=['if'], data=[]] store_name = match['type'].split('-') if store_name[0] != 'external': raise DataJointError('External store types must be specified as "external" or "external-<name>"') # depends on [control=['if'], data=[]] store_name = '-'.join(store_name[1:]) if store_name != '' and (not store_name.isidentifier()): raise DataJointError('The external store name `{type}` is invalid. Make like a python identifier.'.format(**match)) # depends on [control=['if'], data=[]] if len(store_name) > STORE_NAME_LENGTH: raise DataJointError('The external store name `{type}` is too long. Must be <={max_len} characters.'.format(max_len=STORE_NAME_LENGTH, **match)) # depends on [control=['if'], data=['STORE_NAME_LENGTH']] if not match['default'] in ('DEFAULT NULL', 'NOT NULL'): raise DataJointError('The only acceptable default value for an external field is null in:\n%s' % line) # depends on [control=['if'], data=[]] if match['type'] not in config: raise DataJointError('The external store `{type}` is not configured.'.format(**match)) # depends on [control=['if'], data=[]] # append external configuration name to the end of the comment sql = '`{name}` {hash_type} {default} COMMENT ":{type}:{comment}"'.format(hash_type=HASH_DATA_TYPE, **match) foreign_key_sql.append('FOREIGN KEY (`{name}`) REFERENCES {{external_table}} (`hash`) ON UPDATE RESTRICT ON DELETE RESTRICT'.format(**match)) return (match['name'], sql, is_external)
def show_tabulated(self, begin, middle, end): """Shows a tabulated message.""" internal_assert(len(begin) < info_tabulation, "info message too long", begin) self.show(begin + " " * (info_tabulation - len(begin)) + middle + " " + end)
def function[show_tabulated, parameter[self, begin, middle, end]]: constant[Shows a tabulated message.] call[name[internal_assert], parameter[compare[call[name[len], parameter[name[begin]]] less[<] name[info_tabulation]], constant[info message too long], name[begin]]] call[name[self].show, parameter[binary_operation[binary_operation[binary_operation[binary_operation[name[begin] + binary_operation[constant[ ] * binary_operation[name[info_tabulation] - call[name[len], parameter[name[begin]]]]]] + name[middle]] + constant[ ]] + name[end]]]]
keyword[def] identifier[show_tabulated] ( identifier[self] , identifier[begin] , identifier[middle] , identifier[end] ): literal[string] identifier[internal_assert] ( identifier[len] ( identifier[begin] )< identifier[info_tabulation] , literal[string] , identifier[begin] ) identifier[self] . identifier[show] ( identifier[begin] + literal[string] *( identifier[info_tabulation] - identifier[len] ( identifier[begin] ))+ identifier[middle] + literal[string] + identifier[end] )
def show_tabulated(self, begin, middle, end): """Shows a tabulated message.""" internal_assert(len(begin) < info_tabulation, 'info message too long', begin) self.show(begin + ' ' * (info_tabulation - len(begin)) + middle + ' ' + end)
def create_stream(self, stream_id, sandbox=None): """ Must be overridden by deriving classes, must create the stream according to the tool and return its unique identifier stream_id """ if stream_id in self.streams: raise StreamAlreadyExistsError("Stream with id '{}' already exists".format(stream_id)) if sandbox is not None: raise ValueError("Cannot use sandboxes with memory streams") stream = Stream(channel=self, stream_id=stream_id, calculated_intervals=None, sandbox=None) self.streams[stream_id] = stream self.data[stream_id] = StreamInstanceCollection() return stream
def function[create_stream, parameter[self, stream_id, sandbox]]: constant[ Must be overridden by deriving classes, must create the stream according to the tool and return its unique identifier stream_id ] if compare[name[stream_id] in name[self].streams] begin[:] <ast.Raise object at 0x7da18ede68f0> if compare[name[sandbox] is_not constant[None]] begin[:] <ast.Raise object at 0x7da18ede49a0> variable[stream] assign[=] call[name[Stream], parameter[]] call[name[self].streams][name[stream_id]] assign[=] name[stream] call[name[self].data][name[stream_id]] assign[=] call[name[StreamInstanceCollection], parameter[]] return[name[stream]]
keyword[def] identifier[create_stream] ( identifier[self] , identifier[stream_id] , identifier[sandbox] = keyword[None] ): literal[string] keyword[if] identifier[stream_id] keyword[in] identifier[self] . identifier[streams] : keyword[raise] identifier[StreamAlreadyExistsError] ( literal[string] . identifier[format] ( identifier[stream_id] )) keyword[if] identifier[sandbox] keyword[is] keyword[not] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[stream] = identifier[Stream] ( identifier[channel] = identifier[self] , identifier[stream_id] = identifier[stream_id] , identifier[calculated_intervals] = keyword[None] , identifier[sandbox] = keyword[None] ) identifier[self] . identifier[streams] [ identifier[stream_id] ]= identifier[stream] identifier[self] . identifier[data] [ identifier[stream_id] ]= identifier[StreamInstanceCollection] () keyword[return] identifier[stream]
def create_stream(self, stream_id, sandbox=None): """ Must be overridden by deriving classes, must create the stream according to the tool and return its unique identifier stream_id """ if stream_id in self.streams: raise StreamAlreadyExistsError("Stream with id '{}' already exists".format(stream_id)) # depends on [control=['if'], data=['stream_id']] if sandbox is not None: raise ValueError('Cannot use sandboxes with memory streams') # depends on [control=['if'], data=[]] stream = Stream(channel=self, stream_id=stream_id, calculated_intervals=None, sandbox=None) self.streams[stream_id] = stream self.data[stream_id] = StreamInstanceCollection() return stream
def iter(context, sequence, limit=10): """Iter to list all the jobs events.""" params = {'limit': limit, 'offset': 0} uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence) while True: j = context.session.get(uri, params=params).json() if len(j['jobs_events']): for i in j['jobs_events']: yield i else: break params['offset'] += params['limit']
def function[iter, parameter[context, sequence, limit]]: constant[Iter to list all the jobs events.] variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b2429630>, <ast.Constant object at 0x7da1b242ab30>], [<ast.Name object at 0x7da1b242a9b0>, <ast.Constant object at 0x7da1b242b5e0>]] variable[uri] assign[=] binary_operation[constant[%s/%s/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b242aa70>, <ast.Name object at 0x7da1b2429c90>, <ast.Name object at 0x7da1b24285e0>]]] while constant[True] begin[:] variable[j] assign[=] call[call[name[context].session.get, parameter[name[uri]]].json, parameter[]] if call[name[len], parameter[call[name[j]][constant[jobs_events]]]] begin[:] for taget[name[i]] in starred[call[name[j]][constant[jobs_events]]] begin[:] <ast.Yield object at 0x7da1b242ad70> <ast.AugAssign object at 0x7da1b242a020>
keyword[def] identifier[iter] ( identifier[context] , identifier[sequence] , identifier[limit] = literal[int] ): literal[string] identifier[params] ={ literal[string] : identifier[limit] , literal[string] : literal[int] } identifier[uri] = literal[string] %( identifier[context] . identifier[dci_cs_api] , identifier[RESOURCE] , identifier[sequence] ) keyword[while] keyword[True] : identifier[j] = identifier[context] . identifier[session] . identifier[get] ( identifier[uri] , identifier[params] = identifier[params] ). identifier[json] () keyword[if] identifier[len] ( identifier[j] [ literal[string] ]): keyword[for] identifier[i] keyword[in] identifier[j] [ literal[string] ]: keyword[yield] identifier[i] keyword[else] : keyword[break] identifier[params] [ literal[string] ]+= identifier[params] [ literal[string] ]
def iter(context, sequence, limit=10): """Iter to list all the jobs events.""" params = {'limit': limit, 'offset': 0} uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence) while True: j = context.session.get(uri, params=params).json() if len(j['jobs_events']): for i in j['jobs_events']: yield i # depends on [control=['for'], data=['i']] # depends on [control=['if'], data=[]] else: break params['offset'] += params['limit'] # depends on [control=['while'], data=[]]
def make_related_protein_fasta_from_dataframe(self, input_df): ''' DataFrame should have ''' dirname = './group_fastas' if not os.path.exists(dirname): os.makedirs(dirname) unique_hit_queries = set(input_df.hit_query) for hq in unique_hit_queries: fasta = [] subdf = input_df[input_df.hit_query==hq].reset_index() for i in range(0, len(subdf)): fasta.append('>' + subdf.ix[i].org_name.replace(" ", "-") + "," + subdf.ix[i].hit_query + "," + subdf.ix[i].prot_acc + '\n' + subdf.ix[i].prot_translation + '\n') faastring = "".join(fasta) filename = './group_fastas/' + hq + '.fasta' write_fasta = open(filename, 'w') write_fasta.write(faastring) write_fasta.close()
def function[make_related_protein_fasta_from_dataframe, parameter[self, input_df]]: constant[ DataFrame should have ] variable[dirname] assign[=] constant[./group_fastas] if <ast.UnaryOp object at 0x7da1b09d0280> begin[:] call[name[os].makedirs, parameter[name[dirname]]] variable[unique_hit_queries] assign[=] call[name[set], parameter[name[input_df].hit_query]] for taget[name[hq]] in starred[name[unique_hit_queries]] begin[:] variable[fasta] assign[=] list[[]] variable[subdf] assign[=] call[call[name[input_df]][compare[name[input_df].hit_query equal[==] name[hq]]].reset_index, parameter[]] for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[subdf]]]]]] begin[:] call[name[fasta].append, parameter[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[constant[>] + call[call[name[subdf].ix][name[i]].org_name.replace, parameter[constant[ ], constant[-]]]] + constant[,]] + call[name[subdf].ix][name[i]].hit_query] + constant[,]] + call[name[subdf].ix][name[i]].prot_acc] + constant[ ]] + call[name[subdf].ix][name[i]].prot_translation] + constant[ ]]]] variable[faastring] assign[=] call[constant[].join, parameter[name[fasta]]] variable[filename] assign[=] binary_operation[binary_operation[constant[./group_fastas/] + name[hq]] + constant[.fasta]] variable[write_fasta] assign[=] call[name[open], parameter[name[filename], constant[w]]] call[name[write_fasta].write, parameter[name[faastring]]] call[name[write_fasta].close, parameter[]]
keyword[def] identifier[make_related_protein_fasta_from_dataframe] ( identifier[self] , identifier[input_df] ): literal[string] identifier[dirname] = literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[dirname] ): identifier[os] . identifier[makedirs] ( identifier[dirname] ) identifier[unique_hit_queries] = identifier[set] ( identifier[input_df] . identifier[hit_query] ) keyword[for] identifier[hq] keyword[in] identifier[unique_hit_queries] : identifier[fasta] =[] identifier[subdf] = identifier[input_df] [ identifier[input_df] . identifier[hit_query] == identifier[hq] ]. identifier[reset_index] () keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[subdf] )): identifier[fasta] . identifier[append] ( literal[string] + identifier[subdf] . identifier[ix] [ identifier[i] ]. identifier[org_name] . identifier[replace] ( literal[string] , literal[string] )+ literal[string] + identifier[subdf] . identifier[ix] [ identifier[i] ]. identifier[hit_query] + literal[string] + identifier[subdf] . identifier[ix] [ identifier[i] ]. identifier[prot_acc] + literal[string] + identifier[subdf] . identifier[ix] [ identifier[i] ]. identifier[prot_translation] + literal[string] ) identifier[faastring] = literal[string] . identifier[join] ( identifier[fasta] ) identifier[filename] = literal[string] + identifier[hq] + literal[string] identifier[write_fasta] = identifier[open] ( identifier[filename] , literal[string] ) identifier[write_fasta] . identifier[write] ( identifier[faastring] ) identifier[write_fasta] . identifier[close] ()
def make_related_protein_fasta_from_dataframe(self, input_df): """ DataFrame should have """ dirname = './group_fastas' if not os.path.exists(dirname): os.makedirs(dirname) # depends on [control=['if'], data=[]] unique_hit_queries = set(input_df.hit_query) for hq in unique_hit_queries: fasta = [] subdf = input_df[input_df.hit_query == hq].reset_index() for i in range(0, len(subdf)): fasta.append('>' + subdf.ix[i].org_name.replace(' ', '-') + ',' + subdf.ix[i].hit_query + ',' + subdf.ix[i].prot_acc + '\n' + subdf.ix[i].prot_translation + '\n') # depends on [control=['for'], data=['i']] faastring = ''.join(fasta) filename = './group_fastas/' + hq + '.fasta' write_fasta = open(filename, 'w') write_fasta.write(faastring) write_fasta.close() # depends on [control=['for'], data=['hq']]
def _add_install(self, context): """ generates install.sh and adds it to included files """ contents = self._render_template('install.sh', context) self.config.setdefault('files', []) # file list might be empty # add install.sh to list of included files self._add_unique_file({ "path": "/install.sh", "contents": contents, "mode": "755" })
def function[_add_install, parameter[self, context]]: constant[ generates install.sh and adds it to included files ] variable[contents] assign[=] call[name[self]._render_template, parameter[constant[install.sh], name[context]]] call[name[self].config.setdefault, parameter[constant[files], list[[]]]] call[name[self]._add_unique_file, parameter[dictionary[[<ast.Constant object at 0x7da1b009f880>, <ast.Constant object at 0x7da1b009fb20>, <ast.Constant object at 0x7da1b009f910>], [<ast.Constant object at 0x7da1b009f790>, <ast.Name object at 0x7da1b009f940>, <ast.Constant object at 0x7da1b009f760>]]]]
keyword[def] identifier[_add_install] ( identifier[self] , identifier[context] ): literal[string] identifier[contents] = identifier[self] . identifier[_render_template] ( literal[string] , identifier[context] ) identifier[self] . identifier[config] . identifier[setdefault] ( literal[string] ,[]) identifier[self] . identifier[_add_unique_file] ({ literal[string] : literal[string] , literal[string] : identifier[contents] , literal[string] : literal[string] })
def _add_install(self, context): """ generates install.sh and adds it to included files """ contents = self._render_template('install.sh', context) self.config.setdefault('files', []) # file list might be empty # add install.sh to list of included files self._add_unique_file({'path': '/install.sh', 'contents': contents, 'mode': '755'})
def boolean(_object): """ Validates a given input is of type boolean. Example usage:: data = {'a' : True} schema = ('a', boolean) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decorating behavior will be triggered, otherwise it will act as a normal function. """ if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, bool), "not of type boolean") return _validator(value) return decorated ensure(isinstance(_object, bool), "not of type boolean")
def function[boolean, parameter[_object]]: constant[ Validates a given input is of type boolean. Example usage:: data = {'a' : True} schema = ('a', boolean) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decorating behavior will be triggered, otherwise it will act as a normal function. ] if call[name[is_callable], parameter[name[_object]]] begin[:] variable[_validator] assign[=] name[_object] def function[decorated, parameter[value]]: call[name[ensure], parameter[call[name[isinstance], parameter[name[value], name[bool]]], constant[not of type boolean]]] return[call[name[_validator], parameter[name[value]]]] return[name[decorated]] call[name[ensure], parameter[call[name[isinstance], parameter[name[_object], name[bool]]], constant[not of type boolean]]]
keyword[def] identifier[boolean] ( identifier[_object] ): literal[string] keyword[if] identifier[is_callable] ( identifier[_object] ): identifier[_validator] = identifier[_object] @ identifier[wraps] ( identifier[_validator] ) keyword[def] identifier[decorated] ( identifier[value] ): identifier[ensure] ( identifier[isinstance] ( identifier[value] , identifier[bool] ), literal[string] ) keyword[return] identifier[_validator] ( identifier[value] ) keyword[return] identifier[decorated] identifier[ensure] ( identifier[isinstance] ( identifier[_object] , identifier[bool] ), literal[string] )
def boolean(_object): """ Validates a given input is of type boolean. Example usage:: data = {'a' : True} schema = ('a', boolean) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable, the decorating behavior will be triggered, otherwise it will act as a normal function. """ if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, bool), 'not of type boolean') return _validator(value) return decorated # depends on [control=['if'], data=[]] ensure(isinstance(_object, bool), 'not of type boolean')
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False): '''These should also be in the config section, but some here for overrides ''' if self.config['api_key'] is None: raise ValueError('config api_key is undefined') if offset or self.config.get('offset', None): self.offset = offset or self.config.get('offset', None) self._start() while True: try: response = self.get_updates(poll_timeout, self.offset) if response.get('ok', False) is False: raise ValueError(response['error']) else: self.process_updates(response) except Exception as e: print('Error: Unknown Exception') print(e) if debug: raise e else: time.sleep(cooldown)
def function[poll, parameter[self, offset, poll_timeout, cooldown, debug]]: constant[These should also be in the config section, but some here for overrides ] if compare[call[name[self].config][constant[api_key]] is constant[None]] begin[:] <ast.Raise object at 0x7da18dc05480> if <ast.BoolOp object at 0x7da18dc07e20> begin[:] name[self].offset assign[=] <ast.BoolOp object at 0x7da18dc07520> call[name[self]._start, parameter[]] while constant[True] begin[:] <ast.Try object at 0x7da18dc04970>
keyword[def] identifier[poll] ( identifier[self] , identifier[offset] = keyword[None] , identifier[poll_timeout] = literal[int] , identifier[cooldown] = literal[int] , identifier[debug] = keyword[False] ): literal[string] keyword[if] identifier[self] . identifier[config] [ literal[string] ] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[offset] keyword[or] identifier[self] . identifier[config] . identifier[get] ( literal[string] , keyword[None] ): identifier[self] . identifier[offset] = identifier[offset] keyword[or] identifier[self] . identifier[config] . identifier[get] ( literal[string] , keyword[None] ) identifier[self] . identifier[_start] () keyword[while] keyword[True] : keyword[try] : identifier[response] = identifier[self] . identifier[get_updates] ( identifier[poll_timeout] , identifier[self] . identifier[offset] ) keyword[if] identifier[response] . identifier[get] ( literal[string] , keyword[False] ) keyword[is] keyword[False] : keyword[raise] identifier[ValueError] ( identifier[response] [ literal[string] ]) keyword[else] : identifier[self] . identifier[process_updates] ( identifier[response] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[print] ( literal[string] ) identifier[print] ( identifier[e] ) keyword[if] identifier[debug] : keyword[raise] identifier[e] keyword[else] : identifier[time] . identifier[sleep] ( identifier[cooldown] )
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False): """These should also be in the config section, but some here for overrides """ if self.config['api_key'] is None: raise ValueError('config api_key is undefined') # depends on [control=['if'], data=[]] if offset or self.config.get('offset', None): self.offset = offset or self.config.get('offset', None) # depends on [control=['if'], data=[]] self._start() while True: try: response = self.get_updates(poll_timeout, self.offset) if response.get('ok', False) is False: raise ValueError(response['error']) # depends on [control=['if'], data=[]] else: self.process_updates(response) # depends on [control=['try'], data=[]] except Exception as e: print('Error: Unknown Exception') print(e) if debug: raise e # depends on [control=['if'], data=[]] else: time.sleep(cooldown) # depends on [control=['except'], data=['e']] # depends on [control=['while'], data=[]]
def load(self): """(Re)Load config file.""" try: with open(self.config_file) as configfile: self.config = yaml.load(configfile) except TypeError: # no config file (use environment variables) pass if self.config: self.prefix = self.config.get('config_prefix', None) if not self.prefix: if os.getenv(self.config_prefix): self.prefix = os.getenv(self.config_prefix) else: for path in [ os.path.join(self.basepath, self.default_file), os.path.join(self.config_root, self.default_file) ]: if os.path.exists(path): with open(path) as conf: config = yaml.load(conf) prefix = config.get( self.config_prefix.lower(), None ) if prefix: self.prefix = prefix break
def function[load, parameter[self]]: constant[(Re)Load config file.] <ast.Try object at 0x7da1b1b6b400> if name[self].config begin[:] name[self].prefix assign[=] call[name[self].config.get, parameter[constant[config_prefix], constant[None]]] if <ast.UnaryOp object at 0x7da18c4cea70> begin[:] if call[name[os].getenv, parameter[name[self].config_prefix]] begin[:] name[self].prefix assign[=] call[name[os].getenv, parameter[name[self].config_prefix]]
keyword[def] identifier[load] ( identifier[self] ): literal[string] keyword[try] : keyword[with] identifier[open] ( identifier[self] . identifier[config_file] ) keyword[as] identifier[configfile] : identifier[self] . identifier[config] = identifier[yaml] . identifier[load] ( identifier[configfile] ) keyword[except] identifier[TypeError] : keyword[pass] keyword[if] identifier[self] . identifier[config] : identifier[self] . identifier[prefix] = identifier[self] . identifier[config] . identifier[get] ( literal[string] , keyword[None] ) keyword[if] keyword[not] identifier[self] . identifier[prefix] : keyword[if] identifier[os] . identifier[getenv] ( identifier[self] . identifier[config_prefix] ): identifier[self] . identifier[prefix] = identifier[os] . identifier[getenv] ( identifier[self] . identifier[config_prefix] ) keyword[else] : keyword[for] identifier[path] keyword[in] [ identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[basepath] , identifier[self] . identifier[default_file] ), identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[config_root] , identifier[self] . identifier[default_file] ) ]: keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ): keyword[with] identifier[open] ( identifier[path] ) keyword[as] identifier[conf] : identifier[config] = identifier[yaml] . identifier[load] ( identifier[conf] ) identifier[prefix] = identifier[config] . identifier[get] ( identifier[self] . identifier[config_prefix] . identifier[lower] (), keyword[None] ) keyword[if] identifier[prefix] : identifier[self] . identifier[prefix] = identifier[prefix] keyword[break]
def load(self): """(Re)Load config file.""" try: with open(self.config_file) as configfile: self.config = yaml.load(configfile) # depends on [control=['with'], data=['configfile']] # depends on [control=['try'], data=[]] except TypeError: # no config file (use environment variables) pass # depends on [control=['except'], data=[]] if self.config: self.prefix = self.config.get('config_prefix', None) # depends on [control=['if'], data=[]] if not self.prefix: if os.getenv(self.config_prefix): self.prefix = os.getenv(self.config_prefix) # depends on [control=['if'], data=[]] else: for path in [os.path.join(self.basepath, self.default_file), os.path.join(self.config_root, self.default_file)]: if os.path.exists(path): with open(path) as conf: config = yaml.load(conf) prefix = config.get(self.config_prefix.lower(), None) if prefix: self.prefix = prefix break # depends on [control=['if'], data=[]] # depends on [control=['with'], data=['conf']] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['path']] # depends on [control=['if'], data=[]]