query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Parse atom block into atom objects | def atoms ( lines ) : # Convert sdf style charge to actual charge conv_charge_table = { 0 : 0 , 1 : 3 , 2 : 2 , 3 : 1 , 4 : 0 , 5 : - 1 , 6 : - 2 , 7 : - 3 } results = { } for i , line in enumerate ( lines ) : symbol = line [ 31 : 34 ] . rstrip ( ) try : atom = Atom ( symbol ) except KeyError : raise ValueError ( symbol ) xpos = float ( line [ 0 : 10 ] ) ypos = float ( line [ 10 : 20 ] ) zpos = float ( line [ 20 : 30 ] ) atom . coords = ( xpos , ypos , zpos ) atom . mass_diff = int ( line [ 34 : 37 ] ) old_sdf_charge = int ( line [ 37 : 40 ] ) atom . charge = conv_charge_table [ old_sdf_charge ] if old_sdf_charge == 4 : atom . radical = 1 # atom.stereo_flag = int(line[40:43]) # Not used # valence = int(line[46:49]) # if valence: # atom.valence = valence results [ i + 1 ] = { "atom" : atom } return results | 11,800 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L71-L100 | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
Parse bond block into bond objects | def bonds ( lines , atoms ) : # Convert sdf style stereobond (see chem.model.bond.Bond) conv_stereo_table = { 0 : 0 , 1 : 1 , 3 : 3 , 4 : 3 , 6 : 2 } results = { a : { } for a in atoms } for line in lines : bond = Bond ( ) first = int ( line [ 0 : 3 ] ) second = int ( line [ 3 : 6 ] ) if first > second : bond . is_lower_first = 0 order = int ( line [ 6 : 9 ] ) if order < 4 : bond . order = order bond . type = conv_stereo_table [ int ( line [ 9 : 12 ] ) ] results [ first ] [ second ] = { "bond" : bond } results [ second ] [ first ] = { "bond" : bond } return results | 11,801 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L103-L124 | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
Parse properties block | def properties ( lines ) : results = { } for i , line in enumerate ( lines ) : type_ = line [ 3 : 6 ] if type_ not in [ "CHG" , "RAD" , "ISO" ] : continue # Other properties are not supported yet count = int ( line [ 6 : 9 ] ) results [ type_ ] = [ ] for j in range ( count ) : idx = int ( line [ 10 + j * 8 : 13 + j * 8 ] ) val = int ( line [ 14 + j * 8 : 17 + j * 8 ] ) results [ type_ ] . append ( ( idx , val ) ) return results | 11,802 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L127-L144 | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
apply properties to the molecule object | def add_properties ( props , mol ) : if not props : return # The properties supersedes all charge and radical values in the atom block for _ , atom in mol . atoms_iter ( ) : atom . charge = 0 atom . multi = 1 atom . mass = None for prop in props . get ( "CHG" , [ ] ) : mol . atom ( prop [ 0 ] ) . charge = prop [ 1 ] for prop in props . get ( "RAD" , [ ] ) : mol . atom ( prop [ 0 ] ) . multi = prop [ 1 ] for prop in props . get ( "ISO" , [ ] ) : mol . atom ( prop [ 0 ] ) . mass = prop [ 1 ] | 11,803 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L147-L165 | [
"def",
"hurst",
"(",
"X",
")",
":",
"X",
"=",
"numpy",
".",
"array",
"(",
"X",
")",
"N",
"=",
"X",
".",
"size",
"T",
"=",
"numpy",
".",
"arange",
"(",
"1",
",",
"N",
"+",
"1",
")",
"Y",
"=",
"numpy",
".",
"cumsum",
"(",
"X",
")",
"Ave_T",
"=",
"Y",
"/",
"T",
"S_T",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"R_T",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"S_T",
"[",
"i",
"]",
"=",
"numpy",
".",
"std",
"(",
"X",
"[",
":",
"i",
"+",
"1",
"]",
")",
"X_T",
"=",
"Y",
"-",
"T",
"*",
"Ave_T",
"[",
"i",
"]",
"R_T",
"[",
"i",
"]",
"=",
"numpy",
".",
"ptp",
"(",
"X_T",
"[",
":",
"i",
"+",
"1",
"]",
")",
"R_S",
"=",
"R_T",
"/",
"S_T",
"R_S",
"=",
"numpy",
".",
"log",
"(",
"R_S",
")",
"[",
"1",
":",
"]",
"n",
"=",
"numpy",
".",
"log",
"(",
"T",
")",
"[",
"1",
":",
"]",
"A",
"=",
"numpy",
".",
"column_stack",
"(",
"(",
"n",
",",
"numpy",
".",
"ones",
"(",
"n",
".",
"size",
")",
")",
")",
"[",
"m",
",",
"c",
"]",
"=",
"numpy",
".",
"linalg",
".",
"lstsq",
"(",
"A",
",",
"R_S",
")",
"[",
"0",
"]",
"H",
"=",
"m",
"return",
"H"
] |
Parse molfile part into molecule object | def molecule ( lines ) : count_line = lines [ 3 ] num_atoms = int ( count_line [ 0 : 3 ] ) num_bonds = int ( count_line [ 3 : 6 ] ) # chiral_flag = int(count_line[12:15]) # Not used # num_prop = int(count_line[30:33]) # "No longer supported" compound = Compound ( ) compound . graph . _node = atoms ( lines [ 4 : num_atoms + 4 ] ) compound . graph . _adj = bonds ( lines [ num_atoms + 4 : num_atoms + num_bonds + 4 ] , compound . graph . _node . keys ( ) ) props = properties ( lines [ num_atoms + num_bonds + 4 : ] ) add_properties ( props , compound ) return compound | 11,804 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L168-L189 | [
"def",
"hurst",
"(",
"X",
")",
":",
"X",
"=",
"numpy",
".",
"array",
"(",
"X",
")",
"N",
"=",
"X",
".",
"size",
"T",
"=",
"numpy",
".",
"arange",
"(",
"1",
",",
"N",
"+",
"1",
")",
"Y",
"=",
"numpy",
".",
"cumsum",
"(",
"X",
")",
"Ave_T",
"=",
"Y",
"/",
"T",
"S_T",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"R_T",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"S_T",
"[",
"i",
"]",
"=",
"numpy",
".",
"std",
"(",
"X",
"[",
":",
"i",
"+",
"1",
"]",
")",
"X_T",
"=",
"Y",
"-",
"T",
"*",
"Ave_T",
"[",
"i",
"]",
"R_T",
"[",
"i",
"]",
"=",
"numpy",
".",
"ptp",
"(",
"X_T",
"[",
":",
"i",
"+",
"1",
"]",
")",
"R_S",
"=",
"R_T",
"/",
"S_T",
"R_S",
"=",
"numpy",
".",
"log",
"(",
"R_S",
")",
"[",
"1",
":",
"]",
"n",
"=",
"numpy",
".",
"log",
"(",
"T",
")",
"[",
"1",
":",
"]",
"A",
"=",
"numpy",
".",
"column_stack",
"(",
"(",
"n",
",",
"numpy",
".",
"ones",
"(",
"n",
".",
"size",
")",
")",
")",
"[",
"m",
",",
"c",
"]",
"=",
"numpy",
".",
"linalg",
".",
"lstsq",
"(",
"A",
",",
"R_S",
")",
"[",
"0",
"]",
"H",
"=",
"m",
"return",
"H"
] |
Yields molecules generated from CTAB text | def mol_supplier ( lines , no_halt , assign_descriptors ) : def sdf_block ( lns ) : mol = [ ] opt = [ ] is_mol = True for line in lns : if line . startswith ( "$$$$" ) : yield mol [ : ] , opt [ : ] is_mol = True mol . clear ( ) opt . clear ( ) elif line . startswith ( "M END" ) : is_mol = False elif is_mol : mol . append ( line . rstrip ( ) ) else : opt . append ( line . rstrip ( ) ) if mol : yield mol , opt for i , ( mol , opt ) in enumerate ( sdf_block ( lines ) ) : try : c = molecule ( mol ) if assign_descriptors : molutil . assign_descriptors ( c ) except ValueError as err : if no_halt : print ( "Unsupported symbol: {} (#{} in v2000reader)" . format ( err , i + 1 ) ) c = molutil . null_molecule ( assign_descriptors ) else : raise ValueError ( "Unsupported symbol: {}" . format ( err ) ) except RuntimeError as err : if no_halt : print ( "Failed to minimize ring: {} (#{} in v2000reader)" . format ( err , i + 1 ) ) else : raise RuntimeError ( "Failed to minimize ring: {}" . format ( err ) ) except : if no_halt : print ( "Unexpected error (#{} in v2000reader)" . format ( i + 1 ) ) c = molutil . null_molecule ( assign_descriptors ) c . data = optional_data ( opt ) yield c continue else : print ( traceback . format_exc ( ) ) raise Exception ( "Unsupported Error" ) c . data = optional_data ( opt ) yield c | 11,805 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L192-L253 | [
"def",
"get_valid_times_for_job_legacy",
"(",
"self",
",",
"num_job",
")",
":",
"# All of this should be integers, so no rounding factors needed.",
"shift_dur",
"=",
"self",
".",
"curr_seg",
"[",
"0",
"]",
"+",
"int",
"(",
"self",
".",
"job_time_shift",
"*",
"num_job",
")",
"job_valid_seg",
"=",
"self",
".",
"valid_chunk",
".",
"shift",
"(",
"shift_dur",
")",
"# If this is the last job, push the end back",
"if",
"num_job",
"==",
"(",
"self",
".",
"num_jobs",
"-",
"1",
")",
":",
"dataPushBack",
"=",
"self",
".",
"data_length",
"-",
"self",
".",
"valid_chunk",
"[",
"1",
"]",
"job_valid_seg",
"=",
"segments",
".",
"segment",
"(",
"job_valid_seg",
"[",
"0",
"]",
",",
"self",
".",
"curr_seg",
"[",
"1",
"]",
"-",
"dataPushBack",
")",
"return",
"job_valid_seg"
] |
Returns molecules generated from sdfile text | def mols_from_text ( text , no_halt = True , assign_descriptors = True ) : if isinstance ( text , bytes ) : t = tx . decode ( text ) else : t = text # Lazy line splitter. More efficient memory usage than str.split. exp = re . compile ( r"[^\n]*\n|." ) sp = ( x . group ( 0 ) for x in re . finditer ( exp , t ) ) for c in mol_supplier ( sp , no_halt , assign_descriptors ) : yield c | 11,806 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L256-L271 | [
"def",
"find_best_candidate",
"(",
"self",
")",
":",
"self",
".",
"fill_percent_done",
"(",
")",
"i_b",
"=",
"np",
".",
"argmax",
"(",
"self",
".",
"percent_done",
".",
"ravel",
"(",
")",
")",
"if",
"self",
".",
"percent_done",
".",
"ravel",
"(",
")",
"[",
"i_b",
"]",
"<=",
"0",
":",
"return",
"None",
"# check for ties",
"I",
"=",
"self",
".",
"percent_done",
".",
"ravel",
"(",
")",
"==",
"self",
".",
"percent_done",
".",
"ravel",
"(",
")",
"[",
"i_b",
"]",
"if",
"I",
".",
"sum",
"(",
")",
"==",
"1",
":",
"return",
"i_b",
"else",
":",
"I2",
"=",
"np",
".",
"argmax",
"(",
"self",
".",
"max_elev",
".",
"ravel",
"(",
")",
"[",
"I",
"]",
")",
"return",
"I",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"[",
"I2",
"]"
] |
Parse CTAB text and return first one as a Compound object . | def mol_from_text ( text , assign_descriptors = True ) : cg = mols_from_text ( text , False , assign_descriptors ) return next ( cg ) | 11,807 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L274-L282 | [
"def",
"streaming_init",
"(",
"self",
")",
":",
"system",
"=",
"self",
".",
"system",
"config",
"=",
"self",
".",
"config",
"if",
"system",
".",
"config",
".",
"dime_enable",
":",
"config",
".",
"compute_flows",
"=",
"True",
"system",
".",
"streaming",
".",
"send_init",
"(",
"recepient",
"=",
"'all'",
")",
"logger",
".",
"info",
"(",
"'Waiting for modules to send init info...'",
")",
"sleep",
"(",
"0.5",
")",
"system",
".",
"streaming",
".",
"sync_and_handle",
"(",
")"
] |
Parse CTAB file and return first one as a Compound object . | def mol_from_file ( path , assign_descriptors = True ) : cs = mols_from_file ( path , False , assign_descriptors ) return next ( cs ) | 11,808 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000reader.py#L293-L296 | [
"def",
"perturbParams",
"(",
"self",
",",
"pertSize",
"=",
"1e-3",
")",
":",
"params",
"=",
"self",
".",
"getParams",
"(",
")",
"self",
".",
"setParams",
"(",
"params",
"+",
"pertSize",
"*",
"sp",
".",
"randn",
"(",
"params",
".",
"shape",
"[",
"0",
"]",
")",
")"
] |
Returns the contents of a file resource . | def load_from_resource ( name ) : filepath = Path ( USER_DIR ) / name if filepath . exists ( ) : with filepath . open ( ) as fh : return fh . read ( ) else : return resource_string ( 'wdiffhtml' , 'data/' + name ) . decode ( 'utf-8' ) | 11,809 | https://github.com/brutus/wdiffhtml/blob/e97b524a7945f7a626e33ec141343120c524d9fa/wdiffhtml/settings.py#L40-L53 | [
"def",
"clearAndSetComboBoxes",
"(",
"self",
",",
"axesNames",
")",
":",
"logger",
".",
"debug",
"(",
"\"Collector clearAndSetComboBoxes: {}\"",
".",
"format",
"(",
"axesNames",
")",
")",
"check_is_a_sequence",
"(",
"axesNames",
")",
"row",
"=",
"0",
"self",
".",
"_deleteComboBoxes",
"(",
"row",
")",
"self",
".",
"clear",
"(",
")",
"self",
".",
"_setAxesNames",
"(",
"axesNames",
")",
"self",
".",
"_createComboBoxes",
"(",
"row",
")",
"self",
".",
"_updateWidgets",
"(",
")"
] |
Creates a new connection to the Slack Real - Time API . | def connect ( token , protocol = RtmProtocol , factory = WebSocketClientFactory , factory_kwargs = None , api_url = None , debug = False ) : if factory_kwargs is None : factory_kwargs = dict ( ) metadata = request_session ( token , api_url ) wsfactory = factory ( metadata . url , * * factory_kwargs ) if debug : warnings . warn ( 'debug=True has been deprecated in autobahn 0.14.0' ) wsfactory . protocol = lambda * a , * * k : protocol ( * a , * * k ) . _seedMetadata ( metadata ) connection = connectWS ( wsfactory ) return connection | 11,810 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/__init__.py#L26-L43 | [
"def",
"match_ancestor_bank_id",
"(",
"self",
",",
"bank_id",
",",
"match",
")",
":",
"# matches when the bank_id param is an ancestor of",
"# any bank",
"bank_descendants",
"=",
"self",
".",
"_get_descendant_catalog_ids",
"(",
"bank_id",
")",
"identifiers",
"=",
"[",
"ObjectId",
"(",
"i",
".",
"identifier",
")",
"for",
"i",
"in",
"bank_descendants",
"]",
"self",
".",
"_query_terms",
"[",
"'_id'",
"]",
"=",
"{",
"'$in'",
":",
"identifiers",
"}"
] |
This could probably be improved ; at the moment it starts by trying to overshoot the desired compressed block size then it reduces the input bytes one by one until it has met the required block size | def next_block ( self ) : assert self . pos <= self . input_len if self . pos == self . input_len : return None # Overshoot i = self . START_OVERSHOOT while True : try_size = int ( self . bs * i ) size = self . check_request_size ( try_size ) c , d = self . compress_next_chunk ( size ) if size != try_size : break if len ( d ) < self . bs : i += self . OVERSHOOT_INCREASE else : break # Reduce by one byte until we hit the target while True : if len ( d ) <= self . bs : self . c = c # self.c = self.factory() crc32 = zlib . crc32 ( self . get_input ( size ) , 0xffffffff ) & 0xffffffff self . pos += size self . compressed_bytes += len ( d ) return crc32 , size , d size -= 1 if size == 0 : return None c , d = self . compress_next_chunk ( size ) | 11,811 | https://github.com/xlfe/reticul8/blob/0f9503f7a0731ae09adfe4c9af9b57327a7f9d84/python/reticul8/block_compressor.py#L57-L101 | [
"def",
"_SeparateTypes",
"(",
"self",
",",
"metadata_value_pairs",
")",
":",
"registry_pairs",
"=",
"[",
"]",
"file_pairs",
"=",
"[",
"]",
"match_pairs",
"=",
"[",
"]",
"for",
"metadata",
",",
"result",
"in",
"metadata_value_pairs",
":",
"if",
"(",
"result",
".",
"stat_entry",
".",
"pathspec",
".",
"pathtype",
"==",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"REGISTRY",
")",
":",
"registry_pairs",
".",
"append",
"(",
"(",
"metadata",
",",
"result",
".",
"stat_entry",
")",
")",
"else",
":",
"file_pairs",
".",
"append",
"(",
"(",
"metadata",
",",
"result",
")",
")",
"match_pairs",
".",
"extend",
"(",
"[",
"(",
"metadata",
",",
"match",
")",
"for",
"match",
"in",
"result",
".",
"matches",
"]",
")",
"return",
"registry_pairs",
",",
"file_pairs",
",",
"match_pairs"
] |
Configure logging settings and return a logger object . | def set_up_logging ( log_file , console_log_level ) : logger = logging . getLogger ( ) logger . setLevel ( logging . DEBUG ) fh = logging . FileHandler ( str ( log_file ) ) fh . setLevel ( logging . DEBUG ) ch = logging . StreamHandler ( ) ch . setLevel ( console_log_level ) formatter = logging . Formatter ( "{asctime} {levelname} ({name}): {message}" , style = '{' ) fh . setFormatter ( formatter ) ch . setFormatter ( formatter ) logger . addHandler ( fh ) logger . addHandler ( ch ) return logger | 11,812 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/chronophore.py#L48-L64 | [
"def",
"trust_notebook",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"'.ipynb'",
")",
"or",
"path",
"not",
"in",
"self",
".",
"paired_notebooks",
":",
"super",
"(",
"TextFileContentsManager",
",",
"self",
")",
".",
"trust_notebook",
"(",
"path",
")",
"return",
"fmt",
",",
"formats",
"=",
"self",
".",
"paired_notebooks",
"[",
"path",
"]",
"for",
"alt_path",
",",
"alt_fmt",
"in",
"paired_paths",
"(",
"path",
",",
"fmt",
",",
"formats",
")",
":",
"if",
"alt_fmt",
"[",
"'extension'",
"]",
"==",
"'.ipynb'",
":",
"super",
"(",
"TextFileContentsManager",
",",
"self",
")",
".",
"trust_notebook",
"(",
"alt_path",
")"
] |
Run Chronophore based on the command line arguments . | def main ( ) : args = get_args ( ) # Make Chronophore's directories and files in $HOME DATA_DIR = pathlib . Path ( appdirs . user_data_dir ( __title__ ) ) LOG_FILE = pathlib . Path ( appdirs . user_log_dir ( __title__ ) , 'debug.log' ) os . makedirs ( str ( DATA_DIR ) , exist_ok = True ) os . makedirs ( str ( LOG_FILE . parent ) , exist_ok = True ) if args . version : print ( '{} {}' . format ( __title__ , __version__ ) ) raise SystemExit if args . debug : CONSOLE_LOG_LEVEL = logging . DEBUG elif args . verbose : CONSOLE_LOG_LEVEL = logging . INFO else : CONSOLE_LOG_LEVEL = logging . WARNING logger = set_up_logging ( LOG_FILE , CONSOLE_LOG_LEVEL ) logger . debug ( '-' * 80 ) logger . info ( '{} {}' . format ( __title__ , __version__ ) ) logger . debug ( 'Log File: {}' . format ( LOG_FILE ) ) logger . debug ( 'Data Directory: {}' . format ( DATA_DIR ) ) if args . testdb : DATABASE_FILE = DATA_DIR . joinpath ( 'test.sqlite' ) logger . info ( 'Using test database.' ) else : DATABASE_FILE = DATA_DIR . joinpath ( 'chronophore.sqlite' ) logger . debug ( 'Database File: {}' . format ( DATABASE_FILE ) ) engine = create_engine ( 'sqlite:///{}' . format ( str ( DATABASE_FILE ) ) ) Base . metadata . create_all ( engine ) Session . configure ( bind = engine ) if args . log_sql : logging . getLogger ( 'sqlalchemy.engine' ) . setLevel ( logging . INFO ) if args . testdb : add_test_users ( session = Session ( ) ) controller . flag_forgotten_entries ( session = Session ( ) ) if args . tk : from chronophore . tkview import TkChronophoreUI TkChronophoreUI ( ) else : try : from PyQt5 . QtWidgets import QApplication except ImportError : print ( 'Error: PyQt5, which chronophore uses for its' + ' graphical interface, is not installed.' + "\nInstall it with 'pip install PyQt5'" + " or use the old Tk ui with 'chronophore --tk'." ) raise SystemExit else : from chronophore . qtview import QtChronophoreUI app = QApplication ( sys . argv ) chrono_ui = QtChronophoreUI ( ) chrono_ui . show ( ) sys . exit ( app . exec_ ( ) ) logger . debug ( '{} stopping' . format ( __title__ ) ) | 11,813 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/chronophore.py#L67-L134 | [
"def",
"init_conv_weight",
"(",
"layer",
")",
":",
"n_filters",
"=",
"layer",
".",
"filters",
"filter_shape",
"=",
"(",
"layer",
".",
"kernel_size",
",",
")",
"*",
"get_n_dim",
"(",
"layer",
")",
"weight",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_filters",
",",
"n_filters",
")",
"+",
"filter_shape",
")",
"center",
"=",
"tuple",
"(",
"map",
"(",
"lambda",
"x",
":",
"int",
"(",
"(",
"x",
"-",
"1",
")",
"/",
"2",
")",
",",
"filter_shape",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n_filters",
")",
":",
"filter_weight",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_filters",
",",
")",
"+",
"filter_shape",
")",
"index",
"=",
"(",
"i",
",",
")",
"+",
"center",
"filter_weight",
"[",
"index",
"]",
"=",
"1",
"weight",
"[",
"i",
",",
"...",
"]",
"=",
"filter_weight",
"bias",
"=",
"np",
".",
"zeros",
"(",
"n_filters",
")",
"layer",
".",
"set_weights",
"(",
"(",
"add_noise",
"(",
"weight",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
",",
"add_noise",
"(",
"bias",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
")",
")",
")",
")"
] |
Determines if the record should be logged and injects context info into the record . Always returns True | def filter ( self , record ) : fmt = LogManager . spec . context_format if fmt : data = self . context . to_dict ( ) if data : record . context = fmt % "," . join ( "%s=%s" % ( key , val ) for key , val in sorted ( data . items ( ) ) if key and val ) else : record . context = "" return True | 11,814 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/logsetup.py#L142-L151 | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"alternative",
"in",
"self",
".",
"alternatives",
":",
"alternative",
".",
"reset",
"(",
")",
"self",
".",
"reset_winner",
"(",
")",
"self",
".",
"increment_version",
"(",
")"
] |
Enable dumping thread stack traces when specified signals are received similar to java s handling of SIGQUIT | def enable_faulthandler ( cls , signum = signal . SIGUSR1 ) : with cls . _lock : if not signum : cls . _disable_faulthandler ( ) return if not cls . file_handler or faulthandler is None : return cls . faulthandler_signum = signum dump_file = cls . file_handler . stream faulthandler . enable ( file = dump_file , all_threads = True ) faulthandler . register ( signum , file = dump_file , all_threads = True , chain = False ) | 11,815 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/logsetup.py#L383-L401 | [
"async",
"def",
"update_lease_async",
"(",
"self",
",",
"lease",
")",
":",
"if",
"lease",
"is",
"None",
":",
"return",
"False",
"if",
"not",
"lease",
".",
"token",
":",
"return",
"False",
"_logger",
".",
"debug",
"(",
"\"Updating lease %r %r\"",
",",
"self",
".",
"host",
".",
"guid",
",",
"lease",
".",
"partition_id",
")",
"# First, renew the lease to make sure the update will go through.",
"if",
"await",
"self",
".",
"renew_lease_async",
"(",
"lease",
")",
":",
"try",
":",
"await",
"self",
".",
"host",
".",
"loop",
".",
"run_in_executor",
"(",
"self",
".",
"executor",
",",
"functools",
".",
"partial",
"(",
"self",
".",
"storage_client",
".",
"create_blob_from_text",
",",
"self",
".",
"lease_container_name",
",",
"lease",
".",
"partition_id",
",",
"json",
".",
"dumps",
"(",
"lease",
".",
"serializable",
"(",
")",
")",
",",
"lease_id",
"=",
"lease",
".",
"token",
")",
")",
"except",
"Exception",
"as",
"err",
":",
"# pylint: disable=broad-except",
"_logger",
".",
"error",
"(",
"\"Failed to update lease %r %r %r\"",
",",
"self",
".",
"host",
".",
"guid",
",",
"lease",
".",
"partition_id",
",",
"err",
")",
"raise",
"err",
"else",
":",
"return",
"False",
"return",
"True"
] |
OVerride spec and _default_spec with given values | def override_spec ( cls , * * kwargs ) : cls . _default_spec . set ( * * kwargs ) cls . spec . set ( * * kwargs ) | 11,816 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/logsetup.py#L404-L407 | [
"def",
"_index_audio_cmu",
"(",
"self",
",",
"basename",
"=",
"None",
",",
"replace_already_indexed",
"=",
"False",
")",
":",
"self",
".",
"_prepare_audio",
"(",
"basename",
"=",
"basename",
",",
"replace_already_indexed",
"=",
"replace_already_indexed",
")",
"for",
"staging_audio_basename",
"in",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
":",
"original_audio_name",
"=",
"''",
".",
"join",
"(",
"staging_audio_basename",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"[",
":",
"-",
"3",
"]",
"pocketsphinx_command",
"=",
"''",
".",
"join",
"(",
"[",
"\"pocketsphinx_continuous\"",
",",
"\"-infile\"",
",",
"str",
"(",
"\"{}/staging/{}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"staging_audio_basename",
")",
")",
",",
"\"-time\"",
",",
"\"yes\"",
",",
"\"-logfn\"",
",",
"\"/dev/null\"",
"]",
")",
"try",
":",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Now indexing {}\"",
".",
"format",
"(",
"staging_audio_basename",
")",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"pocketsphinx_continuous\"",
",",
"\"-infile\"",
",",
"str",
"(",
"\"{}/staging/{}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"staging_audio_basename",
")",
")",
",",
"\"-time\"",
",",
"\"yes\"",
",",
"\"-logfn\"",
",",
"\"/dev/null\"",
"]",
",",
"universal_newlines",
"=",
"True",
")",
".",
"split",
"(",
"'\\n'",
")",
"str_timestamps_with_sil_conf",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"split",
"(",
"\" \"",
")",
",",
"filter",
"(",
"None",
",",
"output",
"[",
"1",
":",
"]",
")",
")",
")",
"# Timestamps are putted in a list of a single element. To match",
"# Watson's output.",
"self",
".",
"__timestamps_unregulated",
"[",
"original_audio_name",
"+",
"\".wav\"",
"]",
"=",
"[",
"(",
"self",
".",
"_timestamp_extractor_cmu",
"(",
"staging_audio_basename",
",",
"str_timestamps_with_sil_conf",
")",
")",
"]",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Done indexing {}\"",
".",
"format",
"(",
"staging_audio_basename",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"e",
",",
"\"The command was: {}\"",
".",
"format",
"(",
"pocketsphinx_command",
")",
")",
"self",
".",
"__errors",
"[",
"(",
"time",
"(",
")",
",",
"staging_audio_basename",
")",
"]",
"=",
"e",
"self",
".",
"_timestamp_regulator",
"(",
")",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Finished indexing procedure\"",
")"
] |
Fix standard logging shortcuts to correctly report logging module . | def _fix_logging_shortcuts ( cls ) : if cls . is_using_format ( "%(pathname)s %(filename)s %(funcName)s %(module)s" ) : logging . _srcfile = cls . _logging_snapshot . _srcfile else : logging . _srcfile = None logging . logProcesses = cls . is_using_format ( "%(process)d" ) logging . logThreads = cls . is_using_format ( "%(thread)d %(threadName)s" ) def getframe ( ) : return sys . _getframe ( 4 ) def log ( level , msg , * args , * * kwargs ) : """Wrapper to make logging.info() etc report the right module %(name)""" name = get_caller_name ( ) logger = logging . getLogger ( name ) try : logging . currentframe = getframe logger . log ( level , msg , * args , * * kwargs ) finally : logging . currentframe = ORIGINAL_CF def wrap ( level , * * kwargs ) : """Wrap corresponding logging shortcut function""" original = getattr ( logging , logging . getLevelName ( level ) . lower ( ) ) f = partial ( log , level , * * kwargs ) f . __doc__ = original . __doc__ return f logging . critical = wrap ( logging . CRITICAL ) logging . fatal = logging . critical logging . error = wrap ( logging . ERROR ) logging . exception = partial ( logging . error , exc_info = True ) logging . warning = wrap ( logging . WARNING ) logging . info = wrap ( logging . INFO ) logging . debug = wrap ( logging . DEBUG ) logging . log = log | 11,817 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/logsetup.py#L439-L491 | [
"def",
"fileupdate",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"add",
"=",
"self",
".",
"__additional",
"add",
"[",
"\"filetype\"",
"]",
"=",
"\"other\"",
"for",
"filetype",
"in",
"(",
"\"book\"",
",",
"\"image\"",
",",
"\"video\"",
",",
"\"audio\"",
",",
"\"archive\"",
")",
":",
"if",
"filetype",
"in",
"data",
":",
"add",
"[",
"\"filetype\"",
"]",
"=",
"filetype",
"break",
"if",
"add",
"[",
"\"filetype\"",
"]",
"in",
"(",
"\"image\"",
",",
"\"video\"",
",",
"\"audio\"",
")",
":",
"add",
"[",
"\"thumb\"",
"]",
"=",
"data",
".",
"get",
"(",
"\"thumb\"",
",",
"dict",
"(",
")",
")",
"# checksum is md5",
"add",
"[",
"\"checksum\"",
"]",
"=",
"data",
"[",
"\"checksum\"",
"]",
"add",
"[",
"\"expire_time\"",
"]",
"=",
"data",
"[",
"\"expires\"",
"]",
"/",
"1000",
"add",
"[",
"\"size\"",
"]",
"=",
"data",
"[",
"\"size\"",
"]",
"add",
"[",
"\"info\"",
"]",
"=",
"data",
".",
"get",
"(",
"add",
"[",
"\"filetype\"",
"]",
",",
"dict",
"(",
")",
")",
"add",
"[",
"\"uploader\"",
"]",
"=",
"data",
"[",
"\"user\"",
"]",
"if",
"self",
".",
"room",
".",
"admin",
":",
"add",
"[",
"\"info\"",
"]",
".",
"update",
"(",
"{",
"\"room\"",
":",
"data",
".",
"get",
"(",
"\"room\"",
")",
"}",
")",
"add",
"[",
"\"info\"",
"]",
".",
"update",
"(",
"{",
"\"uploader_ip\"",
":",
"data",
".",
"get",
"(",
"\"uploader_ip\"",
")",
"}",
")",
"self",
".",
"updated",
"=",
"True"
] |
A hack to get the content of the XML responses from the CAS server . | def _parse_single ( self , text , tagname ) : return minidom . parseString ( text ) . getElementsByTagName ( tagname ) [ 0 ] . firstChild . data | 11,818 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L93-L108 | [
"def",
"use_defaults",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"row",
",",
"cohort",
",",
"filter_fn",
"=",
"None",
",",
"normalized_per_mb",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filter_fn",
"=",
"first_not_none_param",
"(",
"[",
"filter_fn",
",",
"cohort",
".",
"filter_fn",
"]",
",",
"no_filter",
")",
"normalized_per_mb",
"=",
"first_not_none_param",
"(",
"[",
"normalized_per_mb",
",",
"cohort",
".",
"normalized_per_mb",
"]",
",",
"False",
")",
"return",
"func",
"(",
"row",
"=",
"row",
",",
"cohort",
"=",
"cohort",
",",
"filter_fn",
"=",
"filter_fn",
",",
"normalized_per_mb",
"=",
"normalized_per_mb",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Run a quick job . | def quick ( self , q , context = None , task_name = "quickie" , system = False ) : if not context : context = self . context params = { "qry" : q , "context" : context , "taskname" : task_name , "isSystem" : system } r = self . _send_request ( "ExecuteQuickJob" , params = params ) return self . _parse_single ( r . text , "string" ) | 11,819 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L110-L135 | [
"def",
"destroy_sns_event",
"(",
"app_name",
",",
"env",
",",
"region",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"sns_client",
"=",
"session",
".",
"client",
"(",
"'sns'",
")",
"lambda_subscriptions",
"=",
"get_sns_subscriptions",
"(",
"app_name",
"=",
"app_name",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
")",
"for",
"subscription_arn",
"in",
"lambda_subscriptions",
":",
"sns_client",
".",
"unsubscribe",
"(",
"SubscriptionArn",
"=",
"subscription_arn",
")",
"LOG",
".",
"debug",
"(",
"\"Lambda SNS event deleted\"",
")",
"return",
"True"
] |
Submit a job to CasJobs . | def submit ( self , q , context = None , task_name = "casjobs" , estimate = 30 ) : if not context : context = self . context params = { "qry" : q , "context" : context , "taskname" : task_name , "estimate" : estimate } r = self . _send_request ( "SubmitJob" , params = params ) job_id = int ( self . _parse_single ( r . text , "long" ) ) return job_id | 11,820 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L137-L162 | [
"def",
"from_string",
"(",
"contents",
")",
":",
"if",
"contents",
"[",
"-",
"1",
"]",
"!=",
"\"\\n\"",
":",
"contents",
"+=",
"\"\\n\"",
"white_space",
"=",
"r\"[ \\t\\r\\f\\v]\"",
"natoms_line",
"=",
"white_space",
"+",
"r\"*\\d+\"",
"+",
"white_space",
"+",
"r\"*\\n\"",
"comment_line",
"=",
"r\"[^\\n]*\\n\"",
"coord_lines",
"=",
"r\"(\\s*\\w+\\s+[0-9\\-\\+\\.eEdD]+\\s+[0-9\\-\\+\\.eEdD]+\\s+[0-9\\-\\+\\.eEdD]+\\s*\\n)+\"",
"frame_pattern_text",
"=",
"natoms_line",
"+",
"comment_line",
"+",
"coord_lines",
"pat",
"=",
"re",
".",
"compile",
"(",
"frame_pattern_text",
",",
"re",
".",
"MULTILINE",
")",
"mols",
"=",
"[",
"]",
"for",
"xyz_match",
"in",
"pat",
".",
"finditer",
"(",
"contents",
")",
":",
"xyz_text",
"=",
"xyz_match",
".",
"group",
"(",
"0",
")",
"mols",
".",
"append",
"(",
"XYZ",
".",
"_from_frame_string",
"(",
"xyz_text",
")",
")",
"return",
"XYZ",
"(",
"mols",
")"
] |
Check the status of a job . | def status ( self , job_id ) : params = { "jobid" : job_id } r = self . _send_request ( "GetJobStatus" , params = params ) status = int ( self . _parse_single ( r . text , "int" ) ) return status , self . status_codes [ status ] | 11,821 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L164-L181 | [
"def",
"removefromreadergroup",
"(",
"self",
",",
"groupname",
")",
":",
"hresult",
",",
"hcontext",
"=",
"SCardEstablishContext",
"(",
"SCARD_SCOPE_USER",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"EstablishContextException",
"(",
"hresult",
")",
"try",
":",
"hresult",
"=",
"SCardRemoveReaderFromGroup",
"(",
"hcontext",
",",
"self",
".",
"name",
",",
"groupname",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"RemoveReaderFromGroupException",
"(",
"hresult",
",",
"self",
".",
"name",
",",
"groupname",
")",
"finally",
":",
"hresult",
"=",
"SCardReleaseContext",
"(",
"hcontext",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"ReleaseContextException",
"(",
"hresult",
")"
] |
Monitor the status of a job . | def monitor ( self , job_id , timeout = 5 ) : while True : status = self . status ( job_id ) logging . info ( "Monitoring job: %d - Status: %d, %s" % ( job_id , status [ 0 ] , status [ 1 ] ) ) if status [ 0 ] in [ 3 , 4 , 5 ] : return status time . sleep ( timeout ) | 11,822 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L195-L216 | [
"def",
"removefromreadergroup",
"(",
"self",
",",
"groupname",
")",
":",
"hresult",
",",
"hcontext",
"=",
"SCardEstablishContext",
"(",
"SCARD_SCOPE_USER",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"EstablishContextException",
"(",
"hresult",
")",
"try",
":",
"hresult",
"=",
"SCardRemoveReaderFromGroup",
"(",
"hcontext",
",",
"self",
".",
"name",
",",
"groupname",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"RemoveReaderFromGroupException",
"(",
"hresult",
",",
"self",
".",
"name",
",",
"groupname",
")",
"finally",
":",
"hresult",
"=",
"SCardReleaseContext",
"(",
"hcontext",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"ReleaseContextException",
"(",
"hresult",
")"
] |
Request the output for a given table . | def request_output ( self , table , outtype ) : job_types = [ "CSV" , "DataSet" , "FITS" , "VOTable" ] assert outtype in job_types params = { "tableName" : table , "type" : outtype } r = self . _send_request ( "SubmitExtractJob" , params = params ) job_id = int ( self . _parse_single ( r . text , "long" ) ) return job_id | 11,823 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L238-L257 | [
"def",
"get_license_assignment_manager",
"(",
"service_instance",
")",
":",
"log",
".",
"debug",
"(",
"'Retrieving license assignment manager'",
")",
"try",
":",
"lic_assignment_manager",
"=",
"service_instance",
".",
"content",
".",
"licenseManager",
".",
"licenseAssignmentManager",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"if",
"not",
"lic_assignment_manager",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareObjectRetrievalError",
"(",
"'License assignment manager was not retrieved'",
")",
"return",
"lic_assignment_manager"
] |
Download an output file given the id of the output request job . | def get_output ( self , job_id , outfn ) : job_info = self . job_info ( jobid = job_id ) [ 0 ] # Make sure that the job is finished. status = int ( job_info [ "Status" ] ) if status != 5 : raise Exception ( "The status of job %d is %d (%s)" % ( job_id , status , self . status_codes [ status ] ) ) # Try to download the output file. remotefn = job_info [ "OutputLoc" ] r = requests . get ( remotefn ) # Make sure that the request went through. code = r . status_code if code != 200 : raise Exception ( "Getting file %s yielded status: %d" % ( remotefn , code ) ) # Save the data to a file. try : outfn . write ( r . content ) except AttributeError : f = open ( outfn , "wb" ) f . write ( r . content ) f . close ( ) | 11,824 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L259-L294 | [
"def",
"secret_file",
"(",
"filename",
")",
":",
"filestat",
"=",
"os",
".",
"stat",
"(",
"abspath",
"(",
"filename",
")",
")",
"if",
"stat",
".",
"S_ISREG",
"(",
"filestat",
".",
"st_mode",
")",
"==",
"0",
"and",
"stat",
".",
"S_ISLNK",
"(",
"filestat",
".",
"st_mode",
")",
"==",
"0",
":",
"e_msg",
"=",
"\"Secret file %s must be a real file or symlink\"",
"%",
"filename",
"raise",
"aomi",
".",
"exceptions",
".",
"AomiFile",
"(",
"e_msg",
")",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"\"Windows\"",
":",
"if",
"filestat",
".",
"st_mode",
"&",
"stat",
".",
"S_IROTH",
"or",
"filestat",
".",
"st_mode",
"&",
"stat",
".",
"S_IWOTH",
"or",
"filestat",
".",
"st_mode",
"&",
"stat",
".",
"S_IWGRP",
":",
"e_msg",
"=",
"\"Secret file %s has too loose permissions\"",
"%",
"filename",
"raise",
"aomi",
".",
"exceptions",
".",
"AomiFile",
"(",
"e_msg",
")"
] |
Shorthand for requesting an output file and then downloading it when ready . | def request_and_get_output ( self , table , outtype , outfn ) : job_id = self . request_output ( table , outtype ) status = self . monitor ( job_id ) if status [ 0 ] != 5 : raise Exception ( "Output request failed." ) self . get_output ( job_id , outfn ) | 11,825 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L296-L317 | [
"def",
"_options_dir",
"(",
"name",
")",
":",
"_check_portname",
"(",
"name",
")",
"_root",
"=",
"'/var/db/ports'",
"# New path: /var/db/ports/category_portname",
"new_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_root",
",",
"name",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
")",
"# Old path: /var/db/ports/portname",
"old_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_root",
",",
"name",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"old_dir",
")",
":",
"return",
"old_dir",
"return",
"new_dir"
] |
Drop a table from the MyDB context . | def drop_table ( self , table ) : job_id = self . submit ( "DROP TABLE %s" % table , context = "MYDB" ) status = self . monitor ( job_id ) if status [ 0 ] != 5 : raise Exception ( "Couldn't drop table %s" % table ) | 11,826 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L319-L331 | [
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid value type, should be bool.\"",
")",
"# Write value",
"try",
":",
"if",
"value",
":",
"os",
".",
"write",
"(",
"self",
".",
"_fd",
",",
"b\"1\\n\"",
")",
"else",
":",
"os",
".",
"write",
"(",
"self",
".",
"_fd",
",",
"b\"0\\n\"",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"GPIOError",
"(",
"e",
".",
"errno",
",",
"\"Writing GPIO: \"",
"+",
"e",
".",
"strerror",
")",
"# Rewind",
"try",
":",
"os",
".",
"lseek",
"(",
"self",
".",
"_fd",
",",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"GPIOError",
"(",
"e",
".",
"errno",
",",
"\"Rewinding GPIO: \"",
"+",
"e",
".",
"strerror",
")"
] |
Shorthand for counting the results of a specific query . | def count ( self , q ) : q = "SELECT COUNT(*) %s" % q return int ( self . quick ( q ) . split ( "\n" ) [ 1 ] ) | 11,827 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L333-L348 | [
"def",
"save",
"(",
"self",
",",
"create_multiple_renditions",
"=",
"True",
",",
"preserve_source_rendition",
"=",
"True",
",",
"encode_to",
"=",
"enums",
".",
"EncodeToEnum",
".",
"FLV",
")",
":",
"if",
"is_ftp_connection",
"(",
"self",
".",
"connection",
")",
"and",
"len",
"(",
"self",
".",
"assets",
")",
">",
"0",
":",
"self",
".",
"connection",
".",
"post",
"(",
"xml",
"=",
"self",
".",
"to_xml",
"(",
")",
",",
"assets",
"=",
"self",
".",
"assets",
")",
"elif",
"not",
"self",
".",
"id",
"and",
"self",
".",
"_filename",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_video'",
",",
"self",
".",
"_filename",
",",
"create_multiple_renditions",
"=",
"create_multiple_renditions",
",",
"preserve_source_rendition",
"=",
"preserve_source_rendition",
",",
"encode_to",
"=",
"encode_to",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"elif",
"not",
"self",
".",
"id",
"and",
"len",
"(",
"self",
".",
"renditions",
")",
">",
"0",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_video'",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"elif",
"self",
".",
"id",
":",
"data",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'update_video'",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"if",
"data",
":",
"self",
".",
"_load",
"(",
"data",
")"
] |
Lists the tables in mydb . | def list_tables ( self ) : q = 'SELECT Distinct TABLE_NAME FROM information_schema.TABLES' res = self . quick ( q , context = 'MYDB' , task_name = 'listtables' , system = True ) # the first line is a header and the last is always empty # also, the table names have " as the first and last characters return [ l [ 1 : - 1 ] for l in res . split ( '\n' ) [ 1 : - 1 ] ] | 11,828 | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L350-L362 | [
"def",
"aggregate_registry_timers",
"(",
")",
":",
"import",
"itertools",
"timers",
"=",
"sorted",
"(",
"shared_registry",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
".",
"desc",
")",
"aggregate_timers",
"=",
"[",
"]",
"for",
"k",
",",
"g",
"in",
"itertools",
".",
"groupby",
"(",
"timers",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
".",
"desc",
")",
":",
"group",
"=",
"list",
"(",
"g",
")",
"num_calls",
"=",
"len",
"(",
"group",
")",
"total_elapsed_ms",
"=",
"sum",
"(",
"t",
".",
"elapsed_time_ms",
"for",
"t",
"in",
"group",
")",
"first_start_time",
"=",
"min",
"(",
"t",
".",
"start_time",
"for",
"t",
"in",
"group",
")",
"# We'll use the first start time as a sort key.",
"aggregate_timers",
".",
"append",
"(",
"(",
"first_start_time",
",",
"(",
"k",
",",
"total_elapsed_ms",
",",
"num_calls",
")",
")",
")",
"aggregate_timers",
".",
"sort",
"(",
")",
"return",
"zip",
"(",
"*",
"aggregate_timers",
")",
"[",
"1",
"]"
] |
Multiply the given number n by some configured multiplier and then add a configured offset . | def multiply_and_add ( n ) : multiplier , offset = di . resolver . unpack ( multiply_and_add ) return ( multiplier * n ) + offset | 11,829 | https://github.com/ncraike/fang/blob/2d9e1216c866e450059017f83ab775f7716eda7a/examples/multiple_dependencies.py#L13-L17 | [
"def",
"delete_session_entity_type",
"(",
"project_id",
",",
"session_id",
",",
"entity_type_display_name",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"session_entity_types_client",
"=",
"dialogflow",
".",
"SessionEntityTypesClient",
"(",
")",
"session_entity_type_name",
"=",
"(",
"session_entity_types_client",
".",
"session_entity_type_path",
"(",
"project_id",
",",
"session_id",
",",
"entity_type_display_name",
")",
")",
"session_entity_types_client",
".",
"delete_session_entity_type",
"(",
"session_entity_type_name",
")"
] |
Flush the buffer of the tail | def flush_buffer ( self ) : if len ( self . buffer ) > 0 : return_value = '' . join ( self . buffer ) self . buffer . clear ( ) self . send_message ( return_value ) self . last_flush_date = datetime . datetime . now ( ) | 11,830 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputTailAction.py#L64-L70 | [
"def",
"get_community_names",
"(",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"# Look in GPO settings first",
"if",
"__utils__",
"[",
"'reg.key_exists'",
"]",
"(",
"_HKEY",
",",
"_COMMUNITIES_GPO_KEY",
")",
":",
"_LOG",
".",
"debug",
"(",
"'Loading communities from Group Policy settings'",
")",
"current_values",
"=",
"__utils__",
"[",
"'reg.list_values'",
"]",
"(",
"_HKEY",
",",
"_COMMUNITIES_GPO_KEY",
",",
"include_default",
"=",
"False",
")",
"# GPO settings are different in that they do not designate permissions",
"# They are a numbered list of communities like so:",
"#",
"# {1: \"community 1\",",
"# 2: \"community 2\"}",
"#",
"# Denote that it is being managed by Group Policy.",
"#",
"# community 1:",
"# Managed by GPO",
"# community 2:",
"# Managed by GPO",
"if",
"isinstance",
"(",
"current_values",
",",
"list",
")",
":",
"for",
"current_value",
"in",
"current_values",
":",
"# Ignore error values",
"if",
"not",
"isinstance",
"(",
"current_value",
",",
"dict",
")",
":",
"continue",
"ret",
"[",
"current_value",
"[",
"'vdata'",
"]",
"]",
"=",
"'Managed by GPO'",
"if",
"not",
"ret",
":",
"_LOG",
".",
"debug",
"(",
"'Loading communities from SNMP settings'",
")",
"current_values",
"=",
"__utils__",
"[",
"'reg.list_values'",
"]",
"(",
"_HKEY",
",",
"_COMMUNITIES_KEY",
",",
"include_default",
"=",
"False",
")",
"# The communities are stored as the community name with a numeric",
"# permission value. Like this (4 = Read Only):",
"#",
"# {\"community 1\": 4,",
"# \"community 2\": 4}",
"#",
"# Convert the numeric value to the text equivalent, as present in the",
"# Windows SNMP service GUI.",
"#",
"# community 1:",
"# Read Only",
"# community 2:",
"# Read Only",
"if",
"isinstance",
"(",
"current_values",
",",
"list",
")",
":",
"for",
"current_value",
"in",
"current_values",
":",
"# Ignore error values",
"if",
"not",
"isinstance",
"(",
"current_value",
",",
"dict",
")",
":",
"continue",
"permissions",
"=",
"six",
".",
"text_type",
"(",
")",
"for",
"permission_name",
"in",
"_PERMISSION_TYPES",
":",
"if",
"current_value",
"[",
"'vdata'",
"]",
"==",
"_PERMISSION_TYPES",
"[",
"permission_name",
"]",
":",
"permissions",
"=",
"permission_name",
"break",
"ret",
"[",
"current_value",
"[",
"'vname'",
"]",
"]",
"=",
"permissions",
"if",
"not",
"ret",
":",
"_LOG",
".",
"debug",
"(",
"'Unable to find existing communities.'",
")",
"return",
"ret"
] |
Conveniently set one or more fields at a time . | def set ( self , * args , * * kwargs ) : if args : for arg in args : if arg is not None : for name in self . __slots__ : self . _set ( name , getattr ( arg , name , UNSET ) ) for name in kwargs : self . _set ( name , kwargs . get ( name , UNSET ) ) | 11,831 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/base.py#L105-L118 | [
"def",
"get_kmgraph_meta",
"(",
"mapper_summary",
")",
":",
"d",
"=",
"mapper_summary",
"[",
"\"custom_meta\"",
"]",
"meta",
"=",
"(",
"\"<b>N_cubes:</b> \"",
"+",
"str",
"(",
"d",
"[",
"\"n_cubes\"",
"]",
")",
"+",
"\" <b>Perc_overlap:</b> \"",
"+",
"str",
"(",
"d",
"[",
"\"perc_overlap\"",
"]",
")",
")",
"meta",
"+=",
"(",
"\"<br><b>Nodes:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_nodes\"",
"]",
")",
"+",
"\" <b>Edges:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_edges\"",
"]",
")",
"+",
"\" <b>Total samples:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_total\"",
"]",
")",
"+",
"\" <b>Unique_samples:</b> \"",
"+",
"str",
"(",
"mapper_summary",
"[",
"\"n_unique\"",
"]",
")",
")",
"return",
"meta"
] |
Enable contextual logging | def enable ( self ) : with self . _lock : if self . filter is None : self . filter = self . _filter_type ( self ) | 11,832 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/base.py#L161-L165 | [
"def",
"main",
"(",
")",
":",
"fmt",
"=",
"'svg'",
"title",
"=",
"\"\"",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-f'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-f'",
")",
"file",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"X",
"=",
"numpy",
".",
"loadtxt",
"(",
"file",
")",
"file",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"2",
"]",
"X2",
"=",
"numpy",
".",
"loadtxt",
"(",
"file",
")",
"# else:",
"# X=numpy.loadtxt(sys.stdin,dtype=numpy.float)",
"else",
":",
"print",
"(",
"'-f option required'",
")",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-fmt'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-fmt'",
")",
"fmt",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"if",
"'-t'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-t'",
")",
"title",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"CDF",
"=",
"{",
"'X'",
":",
"1",
"}",
"pmagplotlib",
".",
"plot_init",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"5",
",",
"5",
")",
"pmagplotlib",
".",
"plot_cdf",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"X",
",",
"''",
",",
"'r'",
",",
"''",
")",
"pmagplotlib",
".",
"plot_cdf",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"X2",
",",
"title",
",",
"'b'",
",",
"''",
")",
"D",
",",
"p",
"=",
"scipy",
".",
"stats",
".",
"ks_2samp",
"(",
"X",
",",
"X2",
")",
"if",
"p",
">=",
".05",
":",
"print",
"(",
"D",
",",
"p",
",",
"' not rejected at 95%'",
")",
"else",
":",
"print",
"(",
"D",
",",
"p",
",",
"' rejected at 95%'",
")",
"pmagplotlib",
".",
"draw_figs",
"(",
"CDF",
")",
"ans",
"=",
"input",
"(",
"'S[a]ve plot, <Return> to quit '",
")",
"if",
"ans",
"==",
"'a'",
":",
"files",
"=",
"{",
"'X'",
":",
"'CDF_.'",
"+",
"fmt",
"}",
"pmagplotlib",
".",
"save_plots",
"(",
"CDF",
",",
"files",
")"
] |
Set current thread s logging context to specified values | def set_threadlocal ( self , * * values ) : with self . _lock : self . _ensure_threadlocal ( ) self . _tpayload . context = values | 11,833 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/base.py#L175-L179 | [
"def",
"is_ome",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
">",
"1",
"or",
"not",
"self",
".",
"description",
":",
"return",
"False",
"d",
"=",
"self",
".",
"description",
"return",
"d",
"[",
":",
"14",
"]",
"==",
"'<?xml version='",
"and",
"d",
"[",
"-",
"6",
":",
"]",
"==",
"'</OME>'"
] |
Add values to current thread s logging context | def add_threadlocal ( self , * * values ) : with self . _lock : self . _ensure_threadlocal ( ) self . _tpayload . context . update ( * * values ) | 11,834 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/base.py#L181-L185 | [
"def",
"parse_torrent_properties",
"(",
"table_datas",
")",
":",
"output",
"=",
"{",
"'category'",
":",
"table_datas",
"[",
"0",
"]",
".",
"text",
",",
"'subcategory'",
":",
"None",
",",
"'quality'",
":",
"None",
",",
"'language'",
":",
"None",
"}",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"table_datas",
")",
")",
":",
"td",
"=",
"table_datas",
"[",
"i",
"]",
"url",
"=",
"td",
".",
"get",
"(",
"'href'",
")",
"params",
"=",
"Parser",
".",
"get_params",
"(",
"url",
")",
"if",
"Parser",
".",
"is_subcategory",
"(",
"params",
")",
"and",
"not",
"output",
"[",
"'subcategory'",
"]",
":",
"output",
"[",
"'subcategory'",
"]",
"=",
"td",
".",
"text",
"elif",
"Parser",
".",
"is_quality",
"(",
"params",
")",
"and",
"not",
"output",
"[",
"'quality'",
"]",
":",
"output",
"[",
"'quality'",
"]",
"=",
"td",
".",
"text",
"elif",
"Parser",
".",
"is_language",
"(",
"params",
")",
"and",
"not",
"output",
"[",
"'language'",
"]",
":",
"output",
"[",
"'language'",
"]",
"=",
"td",
".",
"text",
"return",
"output"
] |
Add values to global logging context | def add_global ( self , * * values ) : with self . _lock : self . _ensure_global ( ) self . _gpayload . update ( * * values ) | 11,835 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/base.py#L209-L213 | [
"def",
"calc_actualremoterelieve_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"d_smoothpar",
"=",
"con",
".",
"remoterelievetolerance",
"*",
"flu",
".",
"allowedremoterelieve",
"flu",
".",
"actualremoterelieve",
"=",
"smoothutils",
".",
"smooth_min1",
"(",
"flu",
".",
"possibleremoterelieve",
",",
"flu",
".",
"allowedremoterelieve",
",",
"d_smoothpar",
")",
"for",
"dummy",
"in",
"range",
"(",
"5",
")",
":",
"d_smoothpar",
"/=",
"5.",
"flu",
".",
"actualremoterelieve",
"=",
"smoothutils",
".",
"smooth_max1",
"(",
"flu",
".",
"actualremoterelieve",
",",
"0.",
",",
"d_smoothpar",
")",
"d_smoothpar",
"/=",
"5.",
"flu",
".",
"actualremoterelieve",
"=",
"smoothutils",
".",
"smooth_min1",
"(",
"flu",
".",
"actualremoterelieve",
",",
"flu",
".",
"possibleremoterelieve",
",",
"d_smoothpar",
")",
"flu",
".",
"actualremoterelieve",
"=",
"min",
"(",
"flu",
".",
"actualremoterelieve",
",",
"flu",
".",
"possibleremoterelieve",
")",
"flu",
".",
"actualremoterelieve",
"=",
"min",
"(",
"flu",
".",
"actualremoterelieve",
",",
"flu",
".",
"allowedremoterelieve",
")",
"flu",
".",
"actualremoterelieve",
"=",
"max",
"(",
"flu",
".",
"actualremoterelieve",
",",
"0.",
")"
] |
Set visible = True to the terminal carbon atoms . | def display_terminal_carbon ( mol ) : for i , a in mol . atoms_iter ( ) : if mol . neighbor_count ( i ) == 1 : a . visible = True | 11,836 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/helper.py#L16-L21 | [
"def",
"_timestamp_regulator",
"(",
"self",
")",
":",
"unified_timestamps",
"=",
"_PrettyDefaultDict",
"(",
"list",
")",
"staged_files",
"=",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
"for",
"timestamp_basename",
"in",
"self",
".",
"__timestamps_unregulated",
":",
"if",
"len",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
">",
"1",
":",
"# File has been splitted",
"timestamp_name",
"=",
"''",
".",
"join",
"(",
"timestamp_basename",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"staged_splitted_files_of_timestamp",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"staged_file",
":",
"(",
"timestamp_name",
"==",
"staged_file",
"[",
":",
"-",
"3",
"]",
"and",
"all",
"(",
"[",
"(",
"x",
"in",
"set",
"(",
"map",
"(",
"str",
",",
"range",
"(",
"10",
")",
")",
")",
")",
"for",
"x",
"in",
"staged_file",
"[",
"-",
"3",
":",
"]",
"]",
")",
")",
",",
"staged_files",
")",
")",
"if",
"len",
"(",
"staged_splitted_files_of_timestamp",
")",
"==",
"0",
":",
"self",
".",
"__errors",
"[",
"(",
"time",
"(",
")",
",",
"timestamp_basename",
")",
"]",
"=",
"{",
"\"reason\"",
":",
"\"Missing staged file\"",
",",
"\"current_staged_files\"",
":",
"staged_files",
"}",
"continue",
"staged_splitted_files_of_timestamp",
".",
"sort",
"(",
")",
"unified_timestamp",
"=",
"list",
"(",
")",
"for",
"staging_digits",
",",
"splitted_file",
"in",
"enumerate",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
":",
"prev_splits_sec",
"=",
"0",
"if",
"int",
"(",
"staging_digits",
")",
"!=",
"0",
":",
"prev_splits_sec",
"=",
"self",
".",
"_get_audio_duration_seconds",
"(",
"\"{}/staging/{}{:03d}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"timestamp_name",
",",
"staging_digits",
"-",
"1",
")",
")",
"for",
"word_block",
"in",
"splitted_file",
":",
"unified_timestamp",
".",
"append",
"(",
"_WordBlock",
"(",
"word",
"=",
"word_block",
".",
"word",
",",
"start",
"=",
"round",
"(",
"word_block",
".",
"start",
"+",
"prev_splits_sec",
",",
"2",
")",
",",
"end",
"=",
"round",
"(",
"word_block",
".",
"end",
"+",
"prev_splits_sec",
",",
"2",
")",
")",
")",
"unified_timestamps",
"[",
"str",
"(",
"timestamp_basename",
")",
"]",
"+=",
"unified_timestamp",
"else",
":",
"unified_timestamps",
"[",
"timestamp_basename",
"]",
"+=",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
"[",
"0",
"]",
"self",
".",
"__timestamps",
".",
"update",
"(",
"unified_timestamps",
")",
"self",
".",
"__timestamps_unregulated",
"=",
"_PrettyDefaultDict",
"(",
"list",
")"
] |
Show equalized double bond if it is connected to terminal atom . | def equalize_terminal_double_bond ( mol ) : for i , a in mol . atoms_iter ( ) : if mol . neighbor_count ( i ) == 1 : nb = list ( mol . neighbors ( i ) . values ( ) ) [ 0 ] if nb . order == 2 : nb . type = 2 | 11,837 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/helper.py#L24-L31 | [
"def",
"table_to_gwf",
"(",
"table",
",",
"filename",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"LDAStools",
".",
"frameCPP",
"import",
"(",
"FrEvent",
",",
"GPSTime",
")",
"# create frame",
"write_kw",
"=",
"{",
"key",
":",
"kwargs",
".",
"pop",
"(",
"key",
")",
"for",
"key",
"in",
"(",
"'compression'",
",",
"'compression_level'",
")",
"if",
"key",
"in",
"kwargs",
"}",
"frame",
"=",
"io_gwf",
".",
"create_frame",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"kwargs",
")",
"# append row by row",
"names",
"=",
"table",
".",
"dtype",
".",
"names",
"for",
"row",
"in",
"table",
":",
"rowd",
"=",
"dict",
"(",
"(",
"n",
",",
"row",
"[",
"n",
"]",
")",
"for",
"n",
"in",
"names",
")",
"gps",
"=",
"LIGOTimeGPS",
"(",
"rowd",
".",
"pop",
"(",
"'time'",
",",
"0",
")",
")",
"frame",
".",
"AppendFrEvent",
"(",
"FrEvent",
"(",
"str",
"(",
"name",
")",
",",
"str",
"(",
"rowd",
".",
"pop",
"(",
"'comment'",
",",
"''",
")",
")",
",",
"str",
"(",
"rowd",
".",
"pop",
"(",
"'inputs'",
",",
"''",
")",
")",
",",
"GPSTime",
"(",
"gps",
".",
"gpsSeconds",
",",
"gps",
".",
"gpsNanoSeconds",
")",
",",
"float",
"(",
"rowd",
".",
"pop",
"(",
"'timeBefore'",
",",
"0",
")",
")",
",",
"float",
"(",
"rowd",
".",
"pop",
"(",
"'timeAfter'",
",",
"0",
")",
")",
",",
"int",
"(",
"rowd",
".",
"pop",
"(",
"'eventStatus'",
",",
"0",
")",
")",
",",
"float",
"(",
"rowd",
".",
"pop",
"(",
"'amplitude'",
",",
"0",
")",
")",
",",
"float",
"(",
"rowd",
".",
"pop",
"(",
"'probability'",
",",
"-",
"1",
")",
")",
",",
"str",
"(",
"rowd",
".",
"pop",
"(",
"'statistics'",
",",
"''",
")",
")",
",",
"list",
"(",
"rowd",
".",
"items",
"(",
")",
")",
",",
"# remaining params as tuple",
")",
")",
"# write frame to file",
"io_gwf",
".",
"write_frames",
"(",
"filename",
",",
"[",
"frame",
"]",
",",
"*",
"*",
"write_kw",
")"
] |
Arrange stereo wedge direction from spine to terminal atom | def spine_to_terminal_wedge ( mol ) : for i , a in mol . atoms_iter ( ) : if mol . neighbor_count ( i ) == 1 : ni , nb = list ( mol . neighbors ( i ) . items ( ) ) [ 0 ] if nb . order == 1 and nb . type in ( 1 , 2 ) and ni > i != nb . is_lower_first : nb . is_lower_first = not nb . is_lower_first nb . type = { 1 : 2 , 2 : 1 } [ nb . type ] | 11,838 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/helper.py#L34-L43 | [
"def",
"load_data",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"valid_dates",
"=",
"[",
"]",
"mrms_files",
"=",
"np",
".",
"array",
"(",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
"+",
"self",
".",
"variable",
"+",
"\"/\"",
")",
")",
")",
"mrms_file_dates",
"=",
"np",
".",
"array",
"(",
"[",
"m_file",
".",
"split",
"(",
"\"_\"",
")",
"[",
"-",
"2",
"]",
".",
"split",
"(",
"\"-\"",
")",
"[",
"0",
"]",
"for",
"m_file",
"in",
"mrms_files",
"]",
")",
"old_mrms_file",
"=",
"None",
"file_obj",
"=",
"None",
"for",
"t",
"in",
"range",
"(",
"self",
".",
"all_dates",
".",
"shape",
"[",
"0",
"]",
")",
":",
"file_index",
"=",
"np",
".",
"where",
"(",
"mrms_file_dates",
"==",
"self",
".",
"all_dates",
"[",
"t",
"]",
".",
"strftime",
"(",
"\"%Y%m%d\"",
")",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"file_index",
")",
">",
"0",
":",
"mrms_file",
"=",
"mrms_files",
"[",
"file_index",
"]",
"[",
"0",
"]",
"if",
"mrms_file",
"is",
"not",
"None",
":",
"if",
"file_obj",
"is",
"not",
"None",
":",
"file_obj",
".",
"close",
"(",
")",
"file_obj",
"=",
"Dataset",
"(",
"self",
".",
"path",
"+",
"self",
".",
"variable",
"+",
"\"/\"",
"+",
"mrms_file",
")",
"#old_mrms_file = mrms_file",
"if",
"\"time\"",
"in",
"file_obj",
".",
"variables",
".",
"keys",
"(",
")",
":",
"time_var",
"=",
"\"time\"",
"else",
":",
"time_var",
"=",
"\"date\"",
"file_valid_dates",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"num2date",
"(",
"file_obj",
".",
"variables",
"[",
"time_var",
"]",
"[",
":",
"]",
",",
"file_obj",
".",
"variables",
"[",
"time_var",
"]",
".",
"units",
")",
")",
"else",
":",
"file_valid_dates",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"[",
"]",
")",
"time_index",
"=",
"np",
".",
"where",
"(",
"file_valid_dates",
".",
"values",
"==",
"self",
".",
"all_dates",
".",
"values",
"[",
"t",
"]",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"time_index",
")",
">",
"0",
":",
"data",
".",
"append",
"(",
"file_obj",
".",
"variables",
"[",
"self",
".",
"variable",
"]",
"[",
"time_index",
"[",
"0",
"]",
"]",
")",
"valid_dates",
".",
"append",
"(",
"self",
".",
"all_dates",
"[",
"t",
"]",
")",
"if",
"file_obj",
"is",
"not",
"None",
":",
"file_obj",
".",
"close",
"(",
")",
"self",
".",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"self",
".",
"data",
"[",
"self",
".",
"data",
"<",
"0",
"]",
"=",
"0",
"self",
".",
"data",
"[",
"self",
".",
"data",
">",
"150",
"]",
"=",
"150",
"self",
".",
"valid_dates",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"valid_dates",
")"
] |
Set double bonds around the ring . | def format_ring_double_bond ( mol ) : mol . require ( "Topology" ) mol . require ( "ScaleAndCenter" ) for r in sorted ( mol . rings , key = len , reverse = True ) : vertices = [ mol . atom ( n ) . coords for n in r ] try : if geometry . is_clockwise ( vertices ) : cpath = iterator . consecutive ( itertools . cycle ( r ) , 2 ) else : cpath = iterator . consecutive ( itertools . cycle ( reversed ( r ) ) , 2 ) except ValueError : continue for _ in r : u , v = next ( cpath ) b = mol . bond ( u , v ) if b . order == 2 : b . type = int ( ( u > v ) == b . is_lower_first ) | 11,839 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/helper.py#L46-L64 | [
"def",
"load",
"(",
"self",
",",
"days",
"=",
"PRELOAD_DAYS",
",",
"only_cameras",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"videos",
"=",
"[",
"]",
"url",
"=",
"LIBRARY_ENDPOINT",
"if",
"not",
"(",
"date_from",
"and",
"date_to",
")",
":",
"now",
"=",
"datetime",
".",
"today",
"(",
")",
"date_from",
"=",
"(",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"days",
")",
")",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"date_to",
"=",
"now",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"params",
"=",
"{",
"'dateFrom'",
":",
"date_from",
",",
"'dateTo'",
":",
"date_to",
"}",
"data",
"=",
"self",
".",
"_session",
".",
"query",
"(",
"url",
",",
"method",
"=",
"'POST'",
",",
"extra_params",
"=",
"params",
")",
".",
"get",
"(",
"'data'",
")",
"# get all cameras to append to create ArloVideo object",
"all_cameras",
"=",
"self",
".",
"_session",
".",
"cameras",
"for",
"video",
"in",
"data",
":",
"# pylint: disable=cell-var-from-loop",
"srccam",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"cam",
":",
"cam",
".",
"device_id",
"==",
"video",
".",
"get",
"(",
"'deviceId'",
")",
",",
"all_cameras",
")",
")",
"[",
"0",
"]",
"# make sure only_cameras is a list",
"if",
"only_cameras",
"and",
"not",
"isinstance",
"(",
"only_cameras",
",",
"list",
")",
":",
"only_cameras",
"=",
"[",
"(",
"only_cameras",
")",
"]",
"# filter by camera only",
"if",
"only_cameras",
":",
"if",
"list",
"(",
"filter",
"(",
"lambda",
"cam",
":",
"cam",
".",
"device_id",
"==",
"srccam",
".",
"device_id",
",",
"list",
"(",
"only_cameras",
")",
")",
")",
":",
"videos",
".",
"append",
"(",
"ArloVideo",
"(",
"video",
",",
"srccam",
",",
"self",
".",
"_session",
")",
")",
"else",
":",
"videos",
".",
"append",
"(",
"ArloVideo",
"(",
"video",
",",
"srccam",
",",
"self",
".",
"_session",
")",
")",
"if",
"limit",
":",
"return",
"videos",
"[",
":",
"limit",
"]",
"return",
"videos"
] |
Shortcut function to prepare molecule to draw . Overwrite this function for customized appearance . It is recommended to clone the molecule before draw because all the methods above are destructive . | def ready_to_draw ( mol ) : copied = molutil . clone ( mol ) # display_terminal_carbon(mol) equalize_terminal_double_bond ( copied ) # spine_to_terminal_wedge(copied) scale_and_center ( copied ) format_ring_double_bond ( copied ) return copied | 11,840 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/helper.py#L113-L125 | [
"def",
"RunValidationOutputToConsole",
"(",
"feed",
",",
"options",
")",
":",
"accumulator",
"=",
"CountingConsoleProblemAccumulator",
"(",
"options",
".",
"error_types_ignore_list",
")",
"problems",
"=",
"transitfeed",
".",
"ProblemReporter",
"(",
"accumulator",
")",
"_",
",",
"exit_code",
"=",
"RunValidation",
"(",
"feed",
",",
"options",
",",
"problems",
")",
"return",
"exit_code"
] |
Update dict from the attributes of a module class or other object . | def update_from_object ( self , obj , criterion = lambda key : key . isupper ( ) ) : log . debug ( 'Loading config from {0}' . format ( obj ) ) if isinstance ( obj , basestring ) : if '.' in obj : path , name = obj . rsplit ( '.' , 1 ) mod = __import__ ( path , globals ( ) , locals ( ) , [ name ] , 0 ) obj = getattr ( mod , name ) else : obj = __import__ ( obj , globals ( ) , locals ( ) , [ ] , 0 ) self . update ( ( key , getattr ( obj , key ) ) for key in filter ( criterion , dir ( obj ) ) ) | 11,841 | https://github.com/adblair/configloader/blob/c56eb568a376243400bb72992ca927c35922c827/configloader/__init__.py#L46-L73 | [
"def",
"_process_pore_voxels",
"(",
"self",
")",
":",
"num_Ps",
"=",
"self",
".",
"num_pores",
"(",
")",
"pore_vox",
"=",
"sp",
".",
"zeros",
"(",
"num_Ps",
",",
"dtype",
"=",
"int",
")",
"fiber_vox",
"=",
"sp",
".",
"zeros",
"(",
"num_Ps",
",",
"dtype",
"=",
"int",
")",
"pore_space",
"=",
"self",
".",
"_hull_image",
".",
"copy",
"(",
")",
"fiber_space",
"=",
"self",
".",
"_hull_image",
".",
"copy",
"(",
")",
"pore_space",
"[",
"self",
".",
"_fiber_image",
"==",
"0",
"]",
"=",
"-",
"1",
"fiber_space",
"[",
"self",
".",
"_fiber_image",
"==",
"1",
"]",
"=",
"-",
"1",
"freq_pore_vox",
"=",
"itemfreq",
"(",
"pore_space",
")",
"freq_pore_vox",
"=",
"freq_pore_vox",
"[",
"freq_pore_vox",
"[",
":",
",",
"0",
"]",
">",
"-",
"1",
"]",
"freq_fiber_vox",
"=",
"itemfreq",
"(",
"fiber_space",
")",
"freq_fiber_vox",
"=",
"freq_fiber_vox",
"[",
"freq_fiber_vox",
"[",
":",
",",
"0",
"]",
">",
"-",
"1",
"]",
"pore_vox",
"[",
"freq_pore_vox",
"[",
":",
",",
"0",
"]",
"]",
"=",
"freq_pore_vox",
"[",
":",
",",
"1",
"]",
"fiber_vox",
"[",
"freq_fiber_vox",
"[",
":",
",",
"0",
"]",
"]",
"=",
"freq_fiber_vox",
"[",
":",
",",
"1",
"]",
"self",
"[",
"'pore.volume'",
"]",
"=",
"pore_vox",
"*",
"self",
".",
"network",
".",
"resolution",
"**",
"3",
"del",
"pore_space",
"del",
"fiber_space"
] |
Update dict from any environment variables that have a given prefix . | def update_from_env_namespace ( self , namespace ) : self . update ( ConfigLoader ( os . environ ) . namespace ( namespace ) ) | 11,842 | https://github.com/adblair/configloader/blob/c56eb568a376243400bb72992ca927c35922c827/configloader/__init__.py#L119-L137 | [
"def",
"get_joint_sections",
"(",
"section",
",",
"include_instructor_not_on_time_schedule",
"=",
"True",
")",
":",
"joint_sections",
"=",
"[",
"]",
"for",
"url",
"in",
"section",
".",
"joint_section_urls",
":",
"section",
"=",
"get_section_by_url",
"(",
"url",
",",
"include_instructor_not_on_time_schedule",
")",
"joint_sections",
".",
"append",
"(",
"section",
")",
"return",
"joint_sections"
] |
Update dict from several sources at once . | def update_from ( self , obj = None , yaml_env = None , yaml_file = None , json_env = None , json_file = None , env_namespace = None , ) : if obj : self . update_from_object ( obj ) if yaml_env : self . update_from_yaml_env ( yaml_env ) if yaml_file : self . update_from_yaml_file ( yaml_file ) if json_env : self . update_from_json_env ( json_env ) if json_file : self . update_from_json_file ( json_file ) if env_namespace : self . update_from_env_namespace ( env_namespace ) | 11,843 | https://github.com/adblair/configloader/blob/c56eb568a376243400bb72992ca927c35922c827/configloader/__init__.py#L139-L179 | [
"def",
"multivariate_neg_logposterior",
"(",
"self",
",",
"beta",
")",
":",
"post",
"=",
"self",
".",
"neg_loglik",
"(",
"beta",
")",
"for",
"k",
"in",
"range",
"(",
"0",
",",
"self",
".",
"z_no",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
".",
"covariance_prior",
"is",
"True",
":",
"post",
"+=",
"-",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
".",
"logpdf",
"(",
"self",
".",
"custom_covariance",
"(",
"beta",
")",
")",
"break",
"else",
":",
"post",
"+=",
"-",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
".",
"logpdf",
"(",
"beta",
"[",
"k",
"]",
")",
"return",
"post"
] |
Return a copy with only the keys from a given namespace . | def namespace ( self , namespace , key_transform = lambda key : key ) : namespace = namespace . rstrip ( '_' ) + '_' return ConfigLoader ( ( key_transform ( key [ len ( namespace ) : ] ) , value ) for key , value in self . items ( ) if key [ : len ( namespace ) ] == namespace ) | 11,844 | https://github.com/adblair/configloader/blob/c56eb568a376243400bb72992ca927c35922c827/configloader/__init__.py#L181-L208 | [
"def",
"find_best_frametype",
"(",
"channel",
",",
"start",
",",
"end",
",",
"frametype_match",
"=",
"None",
",",
"allow_tape",
"=",
"True",
",",
"connection",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"try",
":",
"return",
"find_frametype",
"(",
"channel",
",",
"gpstime",
"=",
"(",
"start",
",",
"end",
")",
",",
"frametype_match",
"=",
"frametype_match",
",",
"allow_tape",
"=",
"allow_tape",
",",
"on_gaps",
"=",
"'error'",
",",
"connection",
"=",
"connection",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")",
"except",
"RuntimeError",
":",
"# gaps (or something else went wrong)",
"ftout",
"=",
"find_frametype",
"(",
"channel",
",",
"gpstime",
"=",
"(",
"start",
",",
"end",
")",
",",
"frametype_match",
"=",
"frametype_match",
",",
"return_all",
"=",
"True",
",",
"allow_tape",
"=",
"allow_tape",
",",
"on_gaps",
"=",
"'ignore'",
",",
"connection",
"=",
"connection",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")",
"try",
":",
"if",
"isinstance",
"(",
"ftout",
",",
"dict",
")",
":",
"return",
"{",
"key",
":",
"ftout",
"[",
"key",
"]",
"[",
"0",
"]",
"for",
"key",
"in",
"ftout",
"}",
"return",
"ftout",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"\"Cannot find any valid frametypes for channel(s)\"",
")"
] |
Return a copy with only the keys from a given namespace lower - cased . | def namespace_lower ( self , namespace ) : return self . namespace ( namespace , key_transform = lambda key : key . lower ( ) ) | 11,845 | https://github.com/adblair/configloader/blob/c56eb568a376243400bb72992ca927c35922c827/configloader/__init__.py#L210-L236 | [
"def",
"remove_pickle_problems",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"doc_loader\"",
")",
":",
"obj",
".",
"doc_loader",
"=",
"None",
"if",
"hasattr",
"(",
"obj",
",",
"\"embedded_tool\"",
")",
":",
"obj",
".",
"embedded_tool",
"=",
"remove_pickle_problems",
"(",
"obj",
".",
"embedded_tool",
")",
"if",
"hasattr",
"(",
"obj",
",",
"\"steps\"",
")",
":",
"obj",
".",
"steps",
"=",
"[",
"remove_pickle_problems",
"(",
"s",
")",
"for",
"s",
"in",
"obj",
".",
"steps",
"]",
"return",
"obj"
] |
Render a diagram of the ETL pipeline | def render_diagram ( root_task , out_base , max_param_len = 20 , horizontal = False , colored = False ) : import re import codecs import subprocess from ozelot import config from ozelot . etl . tasks import get_task_name , get_task_param_string # the graph - lines in dot file lines = [ u"digraph G {" ] if horizontal : lines . append ( u"rankdir=LR;" ) # helper function: make unique task id from task name and parameters: # task name + parameter string, with spaces replaced with _ and all non-alphanumerical characters stripped def get_id ( task ) : s = get_task_name ( task ) + "_" + get_task_param_string ( task ) return re . sub ( r'\W+' , '' , re . sub ( ' ' , '_' , s ) ) # node names of tasks that have already been added to the graph existing_nodes = set ( ) # edge sets (tuples of two node names) that have already been added existing_edges = set ( ) # recursion function for generating the pipeline graph def _build ( task , parent_id = None ) : tid = get_id ( task ) # add node if it's not already there if tid not in existing_nodes : # build task label: task name plus dictionary of parameters as table params = task . to_str_params ( ) param_list = "" for k , v in params . items ( ) : # truncate param value if necessary, and add "..." if len ( v ) > max_param_len : v = v [ : max_param_len ] + "..." param_list += "<TR><TD ALIGN=\"LEFT\">" "<FONT POINT-SIZE=\"10\">{:s}</FONT>" "</TD><TD ALIGN=\"LEFT\">" "<FONT POINT-SIZE=\"10\">{:s}</FONT>" "</TD></TR>" . format ( k , v ) label = "<TABLE BORDER=\"0\" CELLSPACING=\"1\" CELLPADDING=\"1\">" "<TR><TD COLSPAN=\"2\" ALIGN=\"CENTER\">" "<FONT POINT-SIZE=\"12\">{:s}</FONT>" "</TD></TR>" "" . format ( get_task_name ( task ) ) + param_list + "</TABLE>" style = getattr ( task , 'diagram_style' , [ ] ) if colored : color = ', color="{:s}"' . format ( "green" if task . complete ( ) else "red" ) else : color = '' # add a node for the task lines . append ( u"{name:s} [label=< {label:s} >, shape=\"rect\" {color:s}, style=\"{style:s}\"];\n" u"" . format ( name = tid , label = label , color = color , style = ',' . join ( style ) ) ) existing_nodes . add ( tid ) # recurse over requirements for req in task . requires ( ) : _build ( req , parent_id = tid ) # add edge from current node to (upstream) parent, if it doesn't already exist if parent_id is not None and ( tid , parent_id ) not in existing_edges : lines . append ( u"{source:s} -> {target:s};\n" . format ( source = tid , target = parent_id ) ) # generate pipeline graph _build ( root_task ) # close the graph definition lines . append ( u"}" ) # write description in DOT format with codecs . open ( out_base + '.dot' , 'w' , encoding = 'utf-8' ) as f : f . write ( u"\n" . join ( lines ) ) # check existence of DOT_EXECUTABLE variable and file if not hasattr ( config , 'DOT_EXECUTABLE' ) : raise RuntimeError ( "Please configure the 'DOT_EXECUTABLE' variable in your 'project_config.py'" ) if not os . path . exists ( config . DOT_EXECUTABLE ) : raise IOError ( "Could not find file pointed to by 'DOT_EXECUTABLE': " + str ( config . DOT_EXECUTABLE ) ) # render to image using DOT # noinspection PyUnresolvedReferences subprocess . check_call ( [ config . DOT_EXECUTABLE , '-T' , 'png' , '-o' , out_base + '.png' , out_base + '.dot' ] ) | 11,846 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/util.py#L12-L127 | [
"def",
"_check_rest_version",
"(",
"self",
",",
"version",
")",
":",
"version",
"=",
"str",
"(",
"version",
")",
"if",
"version",
"not",
"in",
"self",
".",
"supported_rest_versions",
":",
"msg",
"=",
"\"Library is incompatible with REST API version {0}\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"version",
")",
")",
"array_rest_versions",
"=",
"self",
".",
"_list_available_rest_versions",
"(",
")",
"if",
"version",
"not",
"in",
"array_rest_versions",
":",
"msg",
"=",
"\"Array is incompatible with REST API version {0}\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"version",
")",
")",
"return",
"LooseVersion",
"(",
"version",
")"
] |
Normalize a string | def sanitize ( s , normalize_whitespace = True , normalize_unicode = True , form = 'NFKC' , enforce_encoding = True , encoding = 'utf-8' ) : if enforce_encoding : s = s . encode ( encoding , errors = 'ignore' ) . decode ( encoding , errors = 'ignore' ) if normalize_unicode : s = unicodedata . normalize ( form , s ) if normalize_whitespace : s = re . sub ( r'\s+' , ' ' , s ) . strip ( ) return s | 11,847 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/util.py#L130-L161 | [
"def",
"namer",
"(",
"cls",
",",
"imageUrl",
",",
"pageUrl",
")",
":",
"start",
"=",
"''",
"tsmatch",
"=",
"compile",
"(",
"r'/(\\d+)-'",
")",
".",
"search",
"(",
"imageUrl",
")",
"if",
"tsmatch",
":",
"start",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"int",
"(",
"tsmatch",
".",
"group",
"(",
"1",
")",
")",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"else",
":",
"# There were only chapter 1, page 4 and 5 not matching when writing",
"# this...",
"start",
"=",
"'2015-04-11x'",
"return",
"start",
"+",
"\"-\"",
"+",
"pageUrl",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"-",
"1",
"]"
] |
This is a shortcut for getting the sns_token as a post data of request body . | def get_ticket_for_sns_token ( self ) : self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return { "openid" : self . get_openid ( ) , "persistent_code" : self . get_persistent_code ( ) , } | 11,848 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/authority_request.py#L86-L93 | [
"def",
"exclude_types",
"(",
"self",
",",
"*",
"objs",
")",
":",
"for",
"o",
"in",
"objs",
":",
"for",
"t",
"in",
"_keytuple",
"(",
"o",
")",
":",
"if",
"t",
"and",
"t",
"not",
"in",
"self",
".",
"_excl_d",
":",
"self",
".",
"_excl_d",
"[",
"t",
"]",
"=",
"0"
] |
Drop all tables for all models then re - create them | def reinitialize ( ) : from ozelot import client # import all additional models needed in this project # noinspection PyUnresolvedReferences from ozelot . orm . target import ORMTargetMarker client = client . get_client ( ) base . Base . drop_all ( client ) base . Base . create_all ( client ) | 11,849 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/superheroes/superheroes/models.py#L130-L141 | [
"def",
"get_community_names",
"(",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"# Look in GPO settings first",
"if",
"__utils__",
"[",
"'reg.key_exists'",
"]",
"(",
"_HKEY",
",",
"_COMMUNITIES_GPO_KEY",
")",
":",
"_LOG",
".",
"debug",
"(",
"'Loading communities from Group Policy settings'",
")",
"current_values",
"=",
"__utils__",
"[",
"'reg.list_values'",
"]",
"(",
"_HKEY",
",",
"_COMMUNITIES_GPO_KEY",
",",
"include_default",
"=",
"False",
")",
"# GPO settings are different in that they do not designate permissions",
"# They are a numbered list of communities like so:",
"#",
"# {1: \"community 1\",",
"# 2: \"community 2\"}",
"#",
"# Denote that it is being managed by Group Policy.",
"#",
"# community 1:",
"# Managed by GPO",
"# community 2:",
"# Managed by GPO",
"if",
"isinstance",
"(",
"current_values",
",",
"list",
")",
":",
"for",
"current_value",
"in",
"current_values",
":",
"# Ignore error values",
"if",
"not",
"isinstance",
"(",
"current_value",
",",
"dict",
")",
":",
"continue",
"ret",
"[",
"current_value",
"[",
"'vdata'",
"]",
"]",
"=",
"'Managed by GPO'",
"if",
"not",
"ret",
":",
"_LOG",
".",
"debug",
"(",
"'Loading communities from SNMP settings'",
")",
"current_values",
"=",
"__utils__",
"[",
"'reg.list_values'",
"]",
"(",
"_HKEY",
",",
"_COMMUNITIES_KEY",
",",
"include_default",
"=",
"False",
")",
"# The communities are stored as the community name with a numeric",
"# permission value. Like this (4 = Read Only):",
"#",
"# {\"community 1\": 4,",
"# \"community 2\": 4}",
"#",
"# Convert the numeric value to the text equivalent, as present in the",
"# Windows SNMP service GUI.",
"#",
"# community 1:",
"# Read Only",
"# community 2:",
"# Read Only",
"if",
"isinstance",
"(",
"current_values",
",",
"list",
")",
":",
"for",
"current_value",
"in",
"current_values",
":",
"# Ignore error values",
"if",
"not",
"isinstance",
"(",
"current_value",
",",
"dict",
")",
":",
"continue",
"permissions",
"=",
"six",
".",
"text_type",
"(",
")",
"for",
"permission_name",
"in",
"_PERMISSION_TYPES",
":",
"if",
"current_value",
"[",
"'vdata'",
"]",
"==",
"_PERMISSION_TYPES",
"[",
"permission_name",
"]",
":",
"permissions",
"=",
"permission_name",
"break",
"ret",
"[",
"current_value",
"[",
"'vname'",
"]",
"]",
"=",
"permissions",
"if",
"not",
"ret",
":",
"_LOG",
".",
"debug",
"(",
"'Unable to find existing communities.'",
")",
"return",
"ret"
] |
This unwraps a decorated func returning the inner wrapped func . | def _unwrap_func ( cls , decorated_func ) : if click is not None : # Workaround for click.command() decorator not setting # __wrapped__ if isinstance ( decorated_func , click . Command ) : return cls . _unwrap_func ( decorated_func . callback ) if hasattr ( decorated_func , '__wrapped__' ) : # Recursion: unwrap more if needed return cls . _unwrap_func ( decorated_func . __wrapped__ ) else : # decorated_func isn't actually decorated, no more # unwrapping to do return decorated_func | 11,850 | https://github.com/ncraike/fang/blob/2d9e1216c866e450059017f83ab775f7716eda7a/fang/dependency_register.py#L21-L39 | [
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",
".",
"delete",
"(",
"0",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volume %s.\"",
",",
"vol_name",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volumes.\"",
")"
] |
Register a mapping of the dependent to resource name . | def _register_dependent ( self , dependent , resource_name ) : if dependent not in self . dependents : self . dependents [ dependent ] = [ ] self . dependents [ dependent ] . insert ( 0 , resource_name ) | 11,851 | https://github.com/ncraike/fang/blob/2d9e1216c866e450059017f83ab775f7716eda7a/fang/dependency_register.py#L50-L59 | [
"def",
"communityvisibilitystate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_communityvisibilitystate",
"==",
"None",
":",
"return",
"None",
"elif",
"self",
".",
"_communityvisibilitystate",
"in",
"self",
".",
"VisibilityState",
":",
"return",
"self",
".",
"VisibilityState",
"[",
"self",
".",
"_communityvisibilitystate",
"]",
"else",
":",
"#Invalid State",
"return",
"None"
] |
Register the given dependent as depending on the resource named by resource_name . | def register ( self , resource_name , dependent = None ) : if dependent is None : # Give a partial usable as a decorator return partial ( self . register , resource_name ) dependent = self . _unwrap_dependent ( dependent ) self . _register_dependent ( dependent , resource_name ) self . _register_resource_dependency ( resource_name , dependent ) # Return dependent to ease use as decorator return dependent | 11,852 | https://github.com/ncraike/fang/blob/2d9e1216c866e450059017f83ab775f7716eda7a/fang/dependency_register.py#L66-L80 | [
"def",
"_create_auth",
"(",
"team",
",",
"timeout",
"=",
"None",
")",
":",
"url",
"=",
"get_registry_url",
"(",
"team",
")",
"contents",
"=",
"_load_auth",
"(",
")",
"auth",
"=",
"contents",
".",
"get",
"(",
"url",
")",
"if",
"auth",
"is",
"not",
"None",
":",
"# If the access token expires within a minute, update it.",
"if",
"auth",
"[",
"'expires_at'",
"]",
"<",
"time",
".",
"time",
"(",
")",
"+",
"60",
":",
"try",
":",
"auth",
"=",
"_update_auth",
"(",
"team",
",",
"auth",
"[",
"'refresh_token'",
"]",
",",
"timeout",
")",
"except",
"CommandException",
"as",
"ex",
":",
"raise",
"CommandException",
"(",
"\"Failed to update the access token (%s). Run `quilt login%s` again.\"",
"%",
"(",
"ex",
",",
"' '",
"+",
"team",
"if",
"team",
"else",
"''",
")",
")",
"contents",
"[",
"url",
"]",
"=",
"auth",
"_save_auth",
"(",
"contents",
")",
"return",
"auth"
] |
Runs OCSP verification and returns error code - 0 means success | def verify_ocsp ( cls , certificate , issuer ) : return OCSPVerifier ( certificate , issuer , cls . get_ocsp_url ( ) , cls . get_ocsp_responder_certificate_path ( ) ) . verify ( ) | 11,853 | https://github.com/thorgate/django-esteid/blob/407ae513e357fedea0e3e42198df8eb9d9ff0646/esteid/middleware.py#L144-L150 | [
"def",
"set_bounds",
"(",
"self",
",",
"new_bounds",
")",
":",
"for",
"row",
",",
"key",
"in",
"enumerate",
"(",
"self",
".",
"keys",
")",
":",
"if",
"key",
"in",
"new_bounds",
":",
"self",
".",
"_bounds",
"[",
"row",
"]",
"=",
"new_bounds",
"[",
"key",
"]"
] |
Create a requests session that handles errors by retrying . | def requests_retry_session ( retries = 3 , backoff_factor = 0.3 , status_forcelist = ( 500 , 502 , 504 ) , session = None ) : session = session or requests . Session ( ) retry = Retry ( total = retries , read = retries , connect = retries , backoff_factor = backoff_factor , status_forcelist = status_forcelist , ) adapter = HTTPAdapter ( max_retries = retry ) session . mount ( 'http://' , adapter ) session . mount ( 'https://' , adapter ) return session | 11,854 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/requestsutils.py#L11-L52 | [
"def",
"set_current",
"(",
"self",
",",
"channel",
",",
"value",
",",
"unit",
"=",
"'A'",
")",
":",
"dac_offset",
"=",
"self",
".",
"_ch_cal",
"[",
"channel",
"]",
"[",
"'DAC'",
"]",
"[",
"'offset'",
"]",
"dac_gain",
"=",
"self",
".",
"_ch_cal",
"[",
"channel",
"]",
"[",
"'DAC'",
"]",
"[",
"'gain'",
"]",
"if",
"unit",
"==",
"'raw'",
":",
"value",
"=",
"value",
"elif",
"unit",
"==",
"'A'",
":",
"value",
"=",
"int",
"(",
"(",
"-",
"value",
"*",
"1000000",
"-",
"dac_offset",
")",
"/",
"dac_gain",
")",
"# fix sign of output",
"elif",
"unit",
"==",
"'mA'",
":",
"value",
"=",
"int",
"(",
"(",
"-",
"value",
"*",
"1000",
"-",
"dac_offset",
")",
"/",
"dac_gain",
")",
"# fix sign of output",
"elif",
"unit",
"==",
"'uA'",
":",
"value",
"=",
"int",
"(",
"(",
"-",
"value",
"-",
"dac_offset",
")",
"/",
"dac_gain",
")",
"# fix sign of output",
"else",
":",
"raise",
"TypeError",
"(",
"\"Invalid unit type.\"",
")",
"self",
".",
"_set_dac_value",
"(",
"channel",
"=",
"channel",
",",
"value",
"=",
"value",
")"
] |
Builds a dict of Sphinx configuration variables given a central configuration for LSST Design Documents and a metadata YAML file . | def configure_technote ( meta_stream ) : _metadata = yaml . load ( meta_stream ) confs = _build_confs ( _metadata ) return confs | 11,855 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/technoteconf.py#L17-L67 | [
"def",
"shutdown",
"(",
"self",
",",
"wait",
"=",
"True",
")",
":",
"if",
"self",
".",
"__running",
":",
"# Add a Non-entry for every worker thread we have.",
"for",
"thread",
"in",
"self",
".",
"__threads",
":",
"assert",
"thread",
".",
"isAlive",
"(",
")",
"self",
".",
"__queue",
".",
"append",
"(",
"None",
")",
"self",
".",
"__running",
"=",
"False",
"if",
"wait",
":",
"self",
".",
"__queue",
".",
"wait",
"(",
")",
"for",
"thread",
"in",
"self",
".",
"__threads",
":",
"thread",
".",
"join",
"(",
")"
] |
Get ocsp responder certificate path | def ocsp_responder_certificate_path ( ) : certificate_path = getattr ( settings , 'ESTEID_OCSP_RESPONDER_CERTIFICATE_PATH' , 'TEST_of_SK_OCSP_RESPONDER_2011.pem' ) if certificate_path in [ 'TEST_of_SK_OCSP_RESPONDER_2011.pem' , 'sk-ocsp-responder-certificates.pem' ] : return os . path . join ( os . path . dirname ( __file__ ) , 'certs' , certificate_path ) return certificate_path | 11,856 | https://github.com/thorgate/django-esteid/blob/407ae513e357fedea0e3e42198df8eb9d9ff0646/esteid/config.py#L40-L55 | [
"def",
"_subtractSky",
"(",
"image",
",",
"skyValue",
",",
"memmap",
"=",
"False",
")",
":",
"try",
":",
"np",
".",
"subtract",
"(",
"image",
".",
"data",
",",
"skyValue",
",",
"image",
".",
"data",
")",
"except",
"IOError",
":",
"print",
"(",
"\"Unable to perform sky subtraction on data array\"",
")",
"raise",
"IOError"
] |
Return a new Message instance . The arguments are passed to the marrow . mailer . Message constructor . | def new ( self , * * kwargs ) : app = self . app or current_app mailer = app . extensions [ 'marrowmailer' ] msg = mailer . new ( * * kwargs ) msg . __class__ = Message return msg | 11,857 | https://github.com/miguelgrinberg/Flask-MarrowMailer/blob/daf1ac0745fb31db2f43f4f7dc24c6f50ae96764/flask_marrowmailer.py#L62-L69 | [
"def",
"get_collision_state",
"(",
"self",
",",
"collision_name",
")",
":",
"return",
"self",
".",
"call_remote_api",
"(",
"'simxReadCollision'",
",",
"self",
".",
"get_collision_handle",
"(",
"collision_name",
")",
",",
"streaming",
"=",
"True",
")"
] |
Send the message . If message is an iterable then send all the messages . | def send ( self , msg ) : app = self . app or current_app mailer = app . extensions [ 'marrowmailer' ] mailer . start ( ) if not hasattr ( msg , '__iter__' ) : result = mailer . send ( msg ) else : result = map ( lambda message : mailer . send ( message ) , msg ) mailer . stop ( ) return result | 11,858 | https://github.com/miguelgrinberg/Flask-MarrowMailer/blob/daf1ac0745fb31db2f43f4f7dc24c6f50ae96764/flask_marrowmailer.py#L71-L82 | [
"def",
"generate_citation_counter",
"(",
"self",
")",
":",
"cite_counter",
"=",
"dict",
"(",
")",
"filename",
"=",
"'%s.aux'",
"%",
"self",
".",
"project_name",
"with",
"open",
"(",
"filename",
")",
"as",
"fobj",
":",
"main_aux",
"=",
"fobj",
".",
"read",
"(",
")",
"cite_counter",
"[",
"filename",
"]",
"=",
"_count_citations",
"(",
"filename",
")",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'\\\\@input\\{(.*.aux)\\}'",
",",
"main_aux",
")",
":",
"filename",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"try",
":",
"counter",
"=",
"_count_citations",
"(",
"filename",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"cite_counter",
"[",
"filename",
"]",
"=",
"counter",
"return",
"cite_counter"
] |
Returns the results of wdiff in a HTML compatible format . | def wdiff ( settings , wrap_with_html = False , fold_breaks = False , hard_breaks = False ) : diff = generate_wdiff ( settings . org_file , settings . new_file , fold_breaks ) if wrap_with_html : return wrap_content ( diff , settings , hard_breaks ) else : return diff | 11,859 | https://github.com/brutus/wdiffhtml/blob/e97b524a7945f7a626e33ec141343120c524d9fa/wdiffhtml/__init__.py#L62-L83 | [
"def",
"delete_persistent_data",
"(",
"role",
",",
"zk_node",
")",
":",
"if",
"role",
":",
"destroy_volumes",
"(",
"role",
")",
"unreserve_resources",
"(",
"role",
")",
"if",
"zk_node",
":",
"delete_zk_node",
"(",
"zk_node",
")"
] |
Load settings from config file and return them as a dict . If the config file is not found or if it is invalid create and use a default config file . | def _load_config ( config_file ) : logger . debug ( 'Config file: {}' . format ( config_file ) ) parser = configparser . ConfigParser ( ) try : with config_file . open ( 'r' ) as f : parser . read_file ( f ) except FileNotFoundError as e : logger . warning ( 'Config file not found' ) parser = _use_default ( config_file ) except configparser . ParsingError as e : logger . warning ( 'Error in config file: {}' . format ( e ) ) parser = _use_default ( config_file ) finally : try : config = _load_options ( parser ) except ( configparser . NoOptionError ) : parser = _use_default ( config_file ) config = _load_options ( parser ) logger . debug ( 'Config loaded: {}' . format ( config_file ) ) return config | 11,860 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/config.py#L13-L44 | [
"def",
"incrementSub",
"(",
"self",
",",
"amount",
"=",
"1",
")",
":",
"self",
".",
"_subProgressBar",
".",
"setValue",
"(",
"self",
".",
"subValue",
"(",
")",
"+",
"amount",
")",
"QApplication",
".",
"instance",
"(",
")",
".",
"processEvents",
"(",
")"
] |
Load config options from parser and return them as a dict . | def _load_options ( parser ) : config = dict ( MESSAGE_DURATION = parser . getint ( 'gui' , 'message_duration' ) , GUI_WELCOME_LABLE = parser . get ( 'gui' , 'gui_welcome_label' ) , FULL_USER_NAMES = parser . getboolean ( 'gui' , 'full_user_names' ) , LARGE_FONT_SIZE = parser . getint ( 'gui' , 'large_font_size' ) , MEDIUM_FONT_SIZE = parser . getint ( 'gui' , 'medium_font_size' ) , SMALL_FONT_SIZE = parser . getint ( 'gui' , 'small_font_size' ) , TINY_FONT_SIZE = parser . getint ( 'gui' , 'tiny_font_size' ) , MAX_INPUT_LENGTH = parser . getint ( 'gui' , 'max_input_length' ) , ) return config | 11,861 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/config.py#L47-L63 | [
"def",
"get_free_project_name",
"(",
"self",
",",
"base_name",
")",
":",
"names",
"=",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"_projects",
".",
"values",
"(",
")",
"]",
"if",
"base_name",
"not",
"in",
"names",
":",
"return",
"base_name",
"i",
"=",
"1",
"projects_path",
"=",
"self",
".",
"projects_directory",
"(",
")",
"while",
"True",
":",
"new_name",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"base_name",
",",
"i",
")",
"if",
"new_name",
"not",
"in",
"names",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"projects_path",
",",
"new_name",
")",
")",
":",
"break",
"i",
"+=",
"1",
"if",
"i",
">",
"1000000",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPConflict",
"(",
"text",
"=",
"\"A project name could not be allocated (node limit reached?)\"",
")",
"return",
"new_name"
] |
Write default values to a config file . If another config file already exists back it up before replacing it with the new file . | def _use_default ( config_file ) : default_config = OrderedDict ( ( ( 'gui' , OrderedDict ( ( ( 'message_duration' , 5 ) , ( 'gui_welcome_label' , 'Welcome to the STEM Learning Center!' ) , ( 'full_user_names' , True ) , ( 'large_font_size' , 30 ) , ( 'medium_font_size' , 18 ) , ( 'small_font_size' , 15 ) , ( 'tiny_font_size' , 10 ) , ( 'max_input_length' , 9 ) , ) ) , ) , ) ) parser = configparser . ConfigParser ( ) parser . read_dict ( default_config ) if config_file . exists ( ) : backup = config_file . with_suffix ( '.bak' ) os . rename ( str ( config_file ) , str ( backup ) ) logger . info ( '{} moved to {}.' . format ( config_file , backup ) ) with config_file . open ( 'w' ) as f : parser . write ( f ) logger . info ( 'Default config file created.' ) return parser | 11,862 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/config.py#L66-L104 | [
"async",
"def",
"on_raw_422",
"(",
"self",
",",
"message",
")",
":",
"await",
"self",
".",
"_registration_completed",
"(",
"message",
")",
"self",
".",
"motd",
"=",
"None",
"await",
"self",
".",
"on_connect",
"(",
")"
] |
Set an atom . Existing atom will be overwritten . | def add_atom ( self , key , atom ) : self . graph . add_node ( key , atom = atom ) | 11,863 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L79-L81 | [
"def",
"project_masks_on_boxes",
"(",
"segmentation_masks",
",",
"proposals",
",",
"discretization_size",
")",
":",
"masks",
"=",
"[",
"]",
"M",
"=",
"discretization_size",
"device",
"=",
"proposals",
".",
"bbox",
".",
"device",
"proposals",
"=",
"proposals",
".",
"convert",
"(",
"\"xyxy\"",
")",
"assert",
"segmentation_masks",
".",
"size",
"==",
"proposals",
".",
"size",
",",
"\"{}, {}\"",
".",
"format",
"(",
"segmentation_masks",
",",
"proposals",
")",
"# TODO put the proposals on the CPU, as the representation for the",
"# masks is not efficient GPU-wise (possibly several small tensors for",
"# representing a single instance mask)",
"proposals",
"=",
"proposals",
".",
"bbox",
".",
"to",
"(",
"torch",
".",
"device",
"(",
"\"cpu\"",
")",
")",
"for",
"segmentation_mask",
",",
"proposal",
"in",
"zip",
"(",
"segmentation_masks",
",",
"proposals",
")",
":",
"# crop the masks, resize them to the desired resolution and",
"# then convert them to the tensor representation,",
"# instead of the list representation that was used",
"cropped_mask",
"=",
"segmentation_mask",
".",
"crop",
"(",
"proposal",
")",
"scaled_mask",
"=",
"cropped_mask",
".",
"resize",
"(",
"(",
"M",
",",
"M",
")",
")",
"mask",
"=",
"scaled_mask",
".",
"convert",
"(",
"mode",
"=",
"\"mask\"",
")",
"masks",
".",
"append",
"(",
"mask",
")",
"if",
"len",
"(",
"masks",
")",
"==",
"0",
":",
"return",
"torch",
".",
"empty",
"(",
"0",
",",
"dtype",
"=",
"torch",
".",
"float32",
",",
"device",
"=",
"device",
")",
"return",
"torch",
".",
"stack",
"(",
"masks",
",",
"dim",
"=",
"0",
")",
".",
"to",
"(",
"device",
",",
"dtype",
"=",
"torch",
".",
"float32",
")"
] |
Iterate over atoms . | def atoms_iter ( self ) : for n , atom in self . graph . nodes . data ( "atom" ) : yield n , atom | 11,864 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L87-L90 | [
"def",
"delete_file",
"(",
"self",
",",
"fmfile",
")",
":",
"if",
"not",
"isinstance",
"(",
"fmfile",
",",
"dict",
")",
":",
"raise",
"FMFileError",
"(",
"'fmfile must be a <dict>'",
")",
"method",
",",
"url",
"=",
"get_URL",
"(",
"'file_delete'",
")",
"payload",
"=",
"{",
"'apikey'",
":",
"self",
".",
"config",
".",
"get",
"(",
"'apikey'",
")",
",",
"'logintoken'",
":",
"self",
".",
"session",
".",
"cookies",
".",
"get",
"(",
"'logintoken'",
")",
",",
"'fileid'",
":",
"fmfile",
".",
"get",
"(",
"'fileid'",
")",
"}",
"res",
"=",
"getattr",
"(",
"self",
".",
"session",
",",
"method",
")",
"(",
"url",
",",
"params",
"=",
"payload",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"self",
".",
"_complete",
"=",
"True",
"return",
"True",
"hellraiser",
"(",
"res",
")"
] |
Set a bond . Existing bond will be overwritten . | def add_bond ( self , key1 , key2 , bond ) : self . graph . add_edge ( key1 , key2 , bond = bond ) | 11,865 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L100-L102 | [
"def",
"FromEvent",
"(",
"cls",
",",
"service_event",
")",
":",
"_",
",",
"_",
",",
"name",
"=",
"service_event",
".",
"key_path",
".",
"rpartition",
"(",
"WindowsService",
".",
"_REGISTRY_KEY_PATH_SEPARATOR",
")",
"service_type",
"=",
"service_event",
".",
"regvalue",
".",
"get",
"(",
"'Type'",
",",
"''",
")",
"image_path",
"=",
"service_event",
".",
"regvalue",
".",
"get",
"(",
"'ImagePath'",
",",
"''",
")",
"start_type",
"=",
"service_event",
".",
"regvalue",
".",
"get",
"(",
"'Start'",
",",
"''",
")",
"service_dll",
"=",
"service_event",
".",
"regvalue",
".",
"get",
"(",
"'ServiceDll'",
",",
"''",
")",
"object_name",
"=",
"service_event",
".",
"regvalue",
".",
"get",
"(",
"'ObjectName'",
",",
"''",
")",
"if",
"service_event",
".",
"pathspec",
":",
"source",
"=",
"(",
"service_event",
".",
"pathspec",
".",
"location",
",",
"service_event",
".",
"key_path",
")",
"else",
":",
"source",
"=",
"(",
"'Unknown'",
",",
"'Unknown'",
")",
"return",
"cls",
"(",
"name",
"=",
"name",
",",
"service_type",
"=",
"service_type",
",",
"image_path",
"=",
"image_path",
",",
"start_type",
"=",
"start_type",
",",
"object_name",
"=",
"object_name",
",",
"source",
"=",
"source",
",",
"service_dll",
"=",
"service_dll",
")"
] |
Iterate over bonds . | def bonds_iter ( self ) : for u , v , bond in self . graph . edges . data ( "bond" ) : yield u , v , bond | 11,866 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L108-L111 | [
"def",
"upload",
"(",
"client",
",",
"source_dir",
")",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'upload images'",
")",
"print",
"(",
"'-------------'",
")",
"base_image_folders",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"'images'",
",",
"x",
")",
"for",
"x",
"in",
"image_types",
"]",
"for",
"type_folder",
"in",
"base_image_folders",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"type_folder",
")",
":",
"image_type",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"type_folder",
")",
"langfolders",
"=",
"filter",
"(",
"os",
".",
"path",
".",
"isdir",
",",
"list_dir_abspath",
"(",
"type_folder",
")",
")",
"for",
"language_dir",
"in",
"langfolders",
":",
"language",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"language_dir",
")",
"delete_and_upload_images",
"(",
"client",
",",
"image_type",
",",
"language",
",",
"type_folder",
")"
] |
Return dict of neighbor atom index and connecting bond . | def neighbors ( self , key ) : return { n : attr [ "bond" ] for n , attr in self . graph [ key ] . items ( ) } | 11,867 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L121-L123 | [
"def",
"calc_regenerated",
"(",
"self",
",",
"lastvotetime",
")",
":",
"delta",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"datetime",
".",
"strptime",
"(",
"lastvotetime",
",",
"'%Y-%m-%dT%H:%M:%S'",
")",
"td",
"=",
"delta",
".",
"days",
"ts",
"=",
"delta",
".",
"seconds",
"tt",
"=",
"(",
"td",
"*",
"86400",
")",
"+",
"ts",
"return",
"tt",
"*",
"10000",
"/",
"86400",
"/",
"5"
] |
Iterate over atoms and return its neighbors . | def neighbors_iter ( self ) : for n , adj in self . graph . adj . items ( ) : yield n , { n : attr [ "bond" ] for n , attr in adj . items ( ) } | 11,868 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L129-L132 | [
"def",
"delete_file",
"(",
"self",
",",
"fmfile",
")",
":",
"if",
"not",
"isinstance",
"(",
"fmfile",
",",
"dict",
")",
":",
"raise",
"FMFileError",
"(",
"'fmfile must be a <dict>'",
")",
"method",
",",
"url",
"=",
"get_URL",
"(",
"'file_delete'",
")",
"payload",
"=",
"{",
"'apikey'",
":",
"self",
".",
"config",
".",
"get",
"(",
"'apikey'",
")",
",",
"'logintoken'",
":",
"self",
".",
"session",
".",
"cookies",
".",
"get",
"(",
"'logintoken'",
")",
",",
"'fileid'",
":",
"fmfile",
".",
"get",
"(",
"'fileid'",
")",
"}",
"res",
"=",
"getattr",
"(",
"self",
".",
"session",
",",
"method",
")",
"(",
"url",
",",
"params",
"=",
"payload",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"self",
".",
"_complete",
"=",
"True",
"return",
"True",
"hellraiser",
"(",
"res",
")"
] |
Empty the instance | def clear ( self ) : # self.graph = nx.Graph() self . graph . clear ( ) self . data . clear ( ) self . descriptors . clear ( ) self . size2d = None self . rings = None self . scaffolds = None self . isolated = None | 11,869 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/graphmol.py#L134-L143 | [
"def",
"search_for_port",
"(",
"port_glob",
",",
"req",
",",
"expected_res",
")",
":",
"# Check that the USB port actually exists, based on the known vendor and",
"# product ID.",
"if",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"0x0403",
",",
"idProduct",
"=",
"0x6001",
")",
"is",
"None",
":",
"return",
"None",
"# Find ports matching the supplied glob.",
"ports",
"=",
"glob",
".",
"glob",
"(",
"port_glob",
")",
"if",
"len",
"(",
"ports",
")",
"==",
"0",
":",
"return",
"None",
"for",
"port",
"in",
"ports",
":",
"with",
"r12_serial_port",
"(",
"port",
")",
"as",
"ser",
":",
"if",
"not",
"ser",
".",
"isOpen",
"(",
")",
":",
"ser",
".",
"open",
"(",
")",
"# Write a request out.",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"ser",
".",
"write",
"(",
"str",
"(",
"req",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"else",
":",
"ser",
".",
"write",
"(",
"bytes",
"(",
"req",
",",
"'utf-8'",
")",
")",
"# Wait a short period to allow the connection to generate output.",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# Read output from the serial connection check if it's what we want.",
"res",
"=",
"ser",
".",
"read",
"(",
"ser",
".",
"in_waiting",
")",
".",
"decode",
"(",
"OUTPUT_ENCODING",
")",
"if",
"expected_res",
"in",
"res",
":",
"return",
"port",
"raise",
"ArmException",
"(",
"'ST Robotics connection found, but is not responsive.'",
"+",
"' Is the arm powered on?'",
")",
"return",
"None"
] |
For QPainter coordinate system reflect over X axis and translate from center to top - left | def _convert ( self , pos ) : px = pos [ 0 ] + self . logical_size . width ( ) / 2 py = self . logical_size . height ( ) / 2 - pos [ 1 ] return px , py | 11,870 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/qt.py#L181-L187 | [
"async",
"def",
"async_get_bridgeid",
"(",
"session",
",",
"host",
",",
"port",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"'http://{}:{}/api/{}/config'",
".",
"format",
"(",
"host",
",",
"str",
"(",
"port",
")",
",",
"api_key",
")",
"response",
"=",
"await",
"async_request",
"(",
"session",
".",
"get",
",",
"url",
")",
"bridgeid",
"=",
"response",
"[",
"'bridgeid'",
"]",
"_LOGGER",
".",
"info",
"(",
"\"Bridge id: %s\"",
",",
"bridgeid",
")",
"return",
"bridgeid"
] |
Run the Sphinx build process . | def run_sphinx ( root_dir ) : logger = logging . getLogger ( __name__ ) # This replicates what Sphinx's internal command line hander does in # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/cmd/build.py # build_main() # configuration root_dir = os . path . abspath ( root_dir ) srcdir = root_dir # root directory of Sphinx content confdir = root_dir # directory where conf.py is located outdir = os . path . join ( root_dir , '_build' , 'html' ) doctreedir = os . path . join ( root_dir , '_build' , 'doctree' ) builder = 'html' confoverrides = { } status = sys . stdout # set to None for 'quiet' mode warning = sys . stderr error = sys . stderr freshenv = False # attempt to re-use existing build artificats warningiserror = False tags = [ ] verbosity = 0 jobs = 1 # number of processes force_all = True filenames = [ ] logger . debug ( 'Sphinx config: srcdir={0}' . format ( srcdir ) ) logger . debug ( 'Sphinx config: confdir={0}' . format ( confdir ) ) logger . debug ( 'Sphinx config: outdir={0}' . format ( outdir ) ) logger . debug ( 'Sphinx config: doctreedir={0}' . format ( doctreedir ) ) logger . debug ( 'Sphinx config: builder={0}' . format ( builder ) ) logger . debug ( 'Sphinx config: freshenv={0:b}' . format ( freshenv ) ) logger . debug ( 'Sphinx config: warningiserror={0:b}' . format ( warningiserror ) ) logger . debug ( 'Sphinx config: verbosity={0:d}' . format ( verbosity ) ) logger . debug ( 'Sphinx config: jobs={0:d}' . format ( jobs ) ) logger . debug ( 'Sphinx config: force_all={0:b}' . format ( force_all ) ) app = None try : with patch_docutils ( ) , docutils_namespace ( ) : app = Sphinx ( srcdir , confdir , outdir , doctreedir , builder , confoverrides , status , warning , freshenv , warningiserror , tags , verbosity , jobs ) app . build ( force_all , filenames ) return app . statuscode except ( Exception , KeyboardInterrupt ) as exc : args = MockSphinxNamespace ( verbosity = verbosity , traceback = True ) handle_exception ( app , args , exc , error ) return 1 | 11,871 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxrunner.py#L19-L90 | [
"def",
"_ensure_file_path",
"(",
"self",
")",
":",
"storage_root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"file_path",
")",
"needs_storage_root",
"=",
"storage_root",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"storage_root",
")",
"if",
"needs_storage_root",
":",
"# pragma: no cover",
"os",
".",
"makedirs",
"(",
"storage_root",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"file_path",
")",
":",
"# create the file without group/world permissions",
"with",
"open",
"(",
"self",
".",
"file_path",
",",
"'w'",
")",
":",
"pass",
"user_read_write",
"=",
"0o600",
"os",
".",
"chmod",
"(",
"self",
".",
"file_path",
",",
"user_read_write",
")"
] |
Search and load a configuration file . | def get_settings ( config_file ) : default_settings = { 'general' : { 'endpoint' : 'http://guacamole.antojitos.io/files/' , 'shortener' : 'http://t.antojitos.io/api/v1/urls' , } } settings = configparser . ConfigParser ( ) try : settings . read_dict ( default_settings ) except AttributeError : # using python 2.7 for section , options in default_settings . items ( ) : settings . add_section ( section ) for option , value in options . items ( ) : settings . set ( section , option , value ) if config_file is not None and os . path . exists ( config_file ) : settings . read ( config_file ) return settings if os . path . exists ( CONFIG_FILE ) : settings . read ( CONFIG_FILE ) return settings return settings | 11,872 | https://github.com/Antojitos/guacamole-cli/blob/e3ae6b8eb08379ffb784978587bf24b168af73d0/src/guacamole_cli/__init__.py#L16-L41 | [
"def",
"delete_selection",
"(",
"self",
")",
":",
"selection",
"=",
"self",
".",
"selection",
"if",
"selection",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"selection",
",",
"ArrowWidget",
")",
":",
"self",
".",
"mainscreen",
".",
"boardview",
".",
"board",
".",
"rm_arrow",
"(",
"selection",
".",
"origin",
".",
"name",
",",
"selection",
".",
"destination",
".",
"name",
")",
"selection",
".",
"portal",
".",
"delete",
"(",
")",
"elif",
"isinstance",
"(",
"selection",
",",
"Spot",
")",
":",
"self",
".",
"mainscreen",
".",
"boardview",
".",
"board",
".",
"rm_spot",
"(",
"selection",
".",
"name",
")",
"selection",
".",
"proxy",
".",
"delete",
"(",
")",
"else",
":",
"assert",
"isinstance",
"(",
"selection",
",",
"Pawn",
")",
"self",
".",
"mainscreen",
".",
"boardview",
".",
"board",
".",
"rm_pawn",
"(",
"selection",
".",
"name",
")",
"selection",
".",
"proxy",
".",
"delete",
"(",
")",
"self",
".",
"selection",
"=",
"None"
] |
Encrypts a string using a given rsa . PublicKey object . If the message is larger than the key it will split it up into a list and encrypt each line in the list . | def encrypt ( self , message , public_key ) : # Get the maximum message length based on the key max_str_len = rsa . common . byte_size ( public_key . n ) - 11 # If the message is longer than the key size, split it into a list to # be encrypted if len ( message ) > max_str_len : message = textwrap . wrap ( message , width = max_str_len ) else : message = [ message ] # Create a list for the encrypted message to send enc_msg = [ ] # If we have a long message, loop through and encrypt each part of the # string for line in message : # Encrypt the line in the message into a bytestring enc_line = rsa . encrypt ( line , public_key ) # Convert the encrypted bytestring into ASCII, so we can send it # over the network enc_line_converted = binascii . b2a_base64 ( enc_line ) enc_msg . append ( enc_line_converted ) # Serialize the encrypted message again with json enc_msg = json . dumps ( enc_msg ) # Return the list of encrypted strings return enc_msg | 11,873 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/encryption.py#L43-L87 | [
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Decrypts a string using our own private key object . | def decrypt ( self , message ) : # Unserialize the encrypted message message = json . loads ( message ) # Set up a list for the unencrypted lines of the message unencrypted_msg = [ ] for line in message : # Convert from ascii back to bytestring enc_line = binascii . a2b_base64 ( line ) # Decrypt the line using our private key unencrypted_line = rsa . decrypt ( enc_line , self . private_key ) unencrypted_msg . append ( unencrypted_line ) # Convert the message from a list back into a string unencrypted_msg = "" . join ( unencrypted_msg ) return unencrypted_msg | 11,874 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/encryption.py#L90-L120 | [
"def",
"gumbel_sample",
"(",
"shape",
")",
":",
"uniform_samples",
"=",
"tf",
".",
"random_uniform",
"(",
"shape",
",",
"minval",
"=",
"0.00001",
",",
"maxval",
"=",
"0.99998",
")",
"return",
"-",
"tf",
".",
"log",
"(",
"-",
"tf",
".",
"log",
"(",
"uniform_samples",
")",
")"
] |
On any event method | def on_any_event ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_any_event" ) : delegate . on_any_event ( event ) | 11,875 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L28-L32 | [
"def",
"from_manifest",
"(",
"app",
",",
"filename",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not spend time here when testing",
"path",
"=",
"_manifests",
"[",
"app",
"]",
"[",
"filename",
"]",
"if",
"not",
"raw",
"and",
"cfg",
".",
"get",
"(",
"'CDN_DOMAIN'",
")",
"and",
"not",
"cfg",
".",
"get",
"(",
"'CDN_DEBUG'",
")",
":",
"scheme",
"=",
"'https'",
"if",
"cfg",
".",
"get",
"(",
"'CDN_HTTPS'",
")",
"else",
"request",
".",
"scheme",
"prefix",
"=",
"'{}://'",
".",
"format",
"(",
"scheme",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# CDN_DOMAIN has no trailing slash",
"path",
"=",
"'/'",
"+",
"path",
"return",
"''",
".",
"join",
"(",
"(",
"prefix",
",",
"cfg",
"[",
"'CDN_DOMAIN'",
"]",
",",
"path",
")",
")",
"elif",
"not",
"raw",
"and",
"kwargs",
".",
"get",
"(",
"'external'",
",",
"False",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# request.host_url has a trailing slash",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"return",
"''",
".",
"join",
"(",
"(",
"request",
".",
"host_url",
",",
"path",
")",
")",
"return",
"path"
] |
On created method | def on_created ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_created" ) : delegate . on_created ( event ) | 11,876 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L34-L38 | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"errors",
"=",
"0",
"return",
"resp",
"elif",
"resp",
".",
"status_code",
"==",
"401",
":",
"# Hack to retain the original exception, but augment it with",
"# additional context for the user to interpret it. In a Python",
"# 3 only future we can raise a new exception of the same type",
"# with a new message from the old error.",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"message",
"=",
"\"\\nThis is a protected or locked account, or\"",
"+",
"\" the credentials provided are no longer valid.\"",
"e",
".",
"args",
"=",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"+",
"message",
",",
")",
"+",
"e",
".",
"args",
"[",
"1",
":",
"]",
"log",
".",
"warning",
"(",
"\"401 Authentication required for %s\"",
",",
"resp",
".",
"url",
")",
"raise",
"elif",
"resp",
".",
"status_code",
"==",
"429",
":",
"reset",
"=",
"int",
"(",
"resp",
".",
"headers",
"[",
"'x-rate-limit-reset'",
"]",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"seconds",
"=",
"reset",
"-",
"now",
"+",
"10",
"if",
"seconds",
"<",
"1",
":",
"seconds",
"=",
"10",
"log",
".",
"warning",
"(",
"\"rate limit exceeded: sleeping %s secs\"",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"elif",
"resp",
".",
"status_code",
">=",
"500",
":",
"errors",
"+=",
"1",
"if",
"errors",
">",
"30",
":",
"log",
".",
"warning",
"(",
"\"too many errors from Twitter, giving up\"",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"seconds",
"=",
"60",
"*",
"errors",
"log",
".",
"warning",
"(",
"\"%s from Twitter API, sleeping %s\"",
",",
"resp",
".",
"status_code",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"else",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"new_f"
] |
On deleted method | def on_deleted ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_deleted" ) : delegate . on_deleted ( event ) | 11,877 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L40-L44 | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"errors",
"=",
"0",
"return",
"resp",
"elif",
"resp",
".",
"status_code",
"==",
"401",
":",
"# Hack to retain the original exception, but augment it with",
"# additional context for the user to interpret it. In a Python",
"# 3 only future we can raise a new exception of the same type",
"# with a new message from the old error.",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"message",
"=",
"\"\\nThis is a protected or locked account, or\"",
"+",
"\" the credentials provided are no longer valid.\"",
"e",
".",
"args",
"=",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"+",
"message",
",",
")",
"+",
"e",
".",
"args",
"[",
"1",
":",
"]",
"log",
".",
"warning",
"(",
"\"401 Authentication required for %s\"",
",",
"resp",
".",
"url",
")",
"raise",
"elif",
"resp",
".",
"status_code",
"==",
"429",
":",
"reset",
"=",
"int",
"(",
"resp",
".",
"headers",
"[",
"'x-rate-limit-reset'",
"]",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"seconds",
"=",
"reset",
"-",
"now",
"+",
"10",
"if",
"seconds",
"<",
"1",
":",
"seconds",
"=",
"10",
"log",
".",
"warning",
"(",
"\"rate limit exceeded: sleeping %s secs\"",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"elif",
"resp",
".",
"status_code",
">=",
"500",
":",
"errors",
"+=",
"1",
"if",
"errors",
">",
"30",
":",
"log",
".",
"warning",
"(",
"\"too many errors from Twitter, giving up\"",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"seconds",
"=",
"60",
"*",
"errors",
"log",
".",
"warning",
"(",
"\"%s from Twitter API, sleeping %s\"",
",",
"resp",
".",
"status_code",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"else",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"new_f"
] |
On modified method | def on_modified ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_modified" ) : delegate . on_modified ( event ) | 11,878 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L46-L50 | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"errors",
"=",
"0",
"return",
"resp",
"elif",
"resp",
".",
"status_code",
"==",
"401",
":",
"# Hack to retain the original exception, but augment it with",
"# additional context for the user to interpret it. In a Python",
"# 3 only future we can raise a new exception of the same type",
"# with a new message from the old error.",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"message",
"=",
"\"\\nThis is a protected or locked account, or\"",
"+",
"\" the credentials provided are no longer valid.\"",
"e",
".",
"args",
"=",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"+",
"message",
",",
")",
"+",
"e",
".",
"args",
"[",
"1",
":",
"]",
"log",
".",
"warning",
"(",
"\"401 Authentication required for %s\"",
",",
"resp",
".",
"url",
")",
"raise",
"elif",
"resp",
".",
"status_code",
"==",
"429",
":",
"reset",
"=",
"int",
"(",
"resp",
".",
"headers",
"[",
"'x-rate-limit-reset'",
"]",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"seconds",
"=",
"reset",
"-",
"now",
"+",
"10",
"if",
"seconds",
"<",
"1",
":",
"seconds",
"=",
"10",
"log",
".",
"warning",
"(",
"\"rate limit exceeded: sleeping %s secs\"",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"elif",
"resp",
".",
"status_code",
">=",
"500",
":",
"errors",
"+=",
"1",
"if",
"errors",
">",
"30",
":",
"log",
".",
"warning",
"(",
"\"too many errors from Twitter, giving up\"",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"seconds",
"=",
"60",
"*",
"errors",
"log",
".",
"warning",
"(",
"\"%s from Twitter API, sleeping %s\"",
",",
"resp",
".",
"status_code",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"else",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"new_f"
] |
On moved method | def on_moved ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_moved" ) : delegate . on_moved ( event ) | 11,879 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L52-L56 | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"errors",
"=",
"0",
"return",
"resp",
"elif",
"resp",
".",
"status_code",
"==",
"401",
":",
"# Hack to retain the original exception, but augment it with",
"# additional context for the user to interpret it. In a Python",
"# 3 only future we can raise a new exception of the same type",
"# with a new message from the old error.",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"message",
"=",
"\"\\nThis is a protected or locked account, or\"",
"+",
"\" the credentials provided are no longer valid.\"",
"e",
".",
"args",
"=",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"+",
"message",
",",
")",
"+",
"e",
".",
"args",
"[",
"1",
":",
"]",
"log",
".",
"warning",
"(",
"\"401 Authentication required for %s\"",
",",
"resp",
".",
"url",
")",
"raise",
"elif",
"resp",
".",
"status_code",
"==",
"429",
":",
"reset",
"=",
"int",
"(",
"resp",
".",
"headers",
"[",
"'x-rate-limit-reset'",
"]",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"seconds",
"=",
"reset",
"-",
"now",
"+",
"10",
"if",
"seconds",
"<",
"1",
":",
"seconds",
"=",
"10",
"log",
".",
"warning",
"(",
"\"rate limit exceeded: sleeping %s secs\"",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"elif",
"resp",
".",
"status_code",
">=",
"500",
":",
"errors",
"+=",
"1",
"if",
"errors",
">",
"30",
":",
"log",
".",
"warning",
"(",
"\"too many errors from Twitter, giving up\"",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"seconds",
"=",
"60",
"*",
"errors",
"log",
".",
"warning",
"(",
"\"%s from Twitter API, sleeping %s\"",
",",
"resp",
".",
"status_code",
",",
"seconds",
")",
"time",
".",
"sleep",
"(",
"seconds",
")",
"else",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"new_f"
] |
Fired when something s been created | def on_created ( self , event ) : if self . trigger != "create" : return action_input = ActionInput ( event , "" , self . name ) flows . Global . MESSAGE_DISPATCHER . send_message ( action_input ) | 11,880 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L118-L123 | [
"def",
"coordination_geometry_symmetry_measures_fallback_random",
"(",
"self",
",",
"coordination_geometry",
",",
"NRANDOM",
"=",
"10",
",",
"points_perfect",
"=",
"None",
")",
":",
"permutations_symmetry_measures",
"=",
"[",
"None",
"]",
"*",
"NRANDOM",
"permutations",
"=",
"list",
"(",
")",
"algos",
"=",
"list",
"(",
")",
"perfect2local_maps",
"=",
"list",
"(",
")",
"local2perfect_maps",
"=",
"list",
"(",
")",
"for",
"iperm",
"in",
"range",
"(",
"NRANDOM",
")",
":",
"perm",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"coordination_geometry",
".",
"coordination_number",
")",
"permutations",
".",
"append",
"(",
"perm",
")",
"p2l",
"=",
"{",
"}",
"l2p",
"=",
"{",
"}",
"for",
"i_p",
",",
"pp",
"in",
"enumerate",
"(",
"perm",
")",
":",
"p2l",
"[",
"i_p",
"]",
"=",
"pp",
"l2p",
"[",
"pp",
"]",
"=",
"i_p",
"perfect2local_maps",
".",
"append",
"(",
"p2l",
")",
"local2perfect_maps",
".",
"append",
"(",
"l2p",
")",
"points_distorted",
"=",
"self",
".",
"local_geometry",
".",
"points_wcs_ctwcc",
"(",
"permutation",
"=",
"perm",
")",
"sm_info",
"=",
"symmetry_measure",
"(",
"points_distorted",
"=",
"points_distorted",
",",
"points_perfect",
"=",
"points_perfect",
")",
"sm_info",
"[",
"'translation_vector'",
"]",
"=",
"self",
".",
"local_geometry",
".",
"centroid_with_centre",
"permutations_symmetry_measures",
"[",
"iperm",
"]",
"=",
"sm_info",
"algos",
".",
"append",
"(",
"'APPROXIMATE_FALLBACK'",
")",
"return",
"permutations_symmetry_measures",
",",
"permutations",
",",
"algos",
",",
"local2perfect_maps",
",",
"perfect2local_maps"
] |
Start background thread if not already started | def start ( cls ) : if cls . _thread is None : cls . _thread = threading . Thread ( target = cls . _run , name = "Heartbeat" ) cls . _thread . daemon = True cls . _thread . start ( ) | 11,881 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/heartbeat.py#L82-L87 | [
"def",
"GetAttachmentIdFromMediaId",
"(",
"media_id",
")",
":",
"altchars",
"=",
"'+-'",
"if",
"not",
"six",
".",
"PY2",
":",
"altchars",
"=",
"altchars",
".",
"encode",
"(",
"'utf-8'",
")",
"# altchars for '+' and '/'. We keep '+' but replace '/' with '-'",
"buffer",
"=",
"base64",
".",
"b64decode",
"(",
"str",
"(",
"media_id",
")",
",",
"altchars",
")",
"resoure_id_length",
"=",
"20",
"attachment_id",
"=",
"''",
"if",
"len",
"(",
"buffer",
")",
">",
"resoure_id_length",
":",
"# We are cutting off the storage index.",
"attachment_id",
"=",
"base64",
".",
"b64encode",
"(",
"buffer",
"[",
"0",
":",
"resoure_id_length",
"]",
",",
"altchars",
")",
"if",
"not",
"six",
".",
"PY2",
":",
"attachment_id",
"=",
"attachment_id",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"attachment_id",
"=",
"media_id",
"return",
"attachment_id"
] |
Task instance representing task if any | def resolved_task ( cls , task ) : for t in cls . tasks : if t is task or t . execute is task : return t | 11,882 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/heartbeat.py#L118-L122 | [
"def",
"load_from_package",
"(",
")",
":",
"try",
":",
"import",
"pkg_resources",
"f",
"=",
"pkg_resources",
".",
"resource_stream",
"(",
"meta",
".",
"__app__",
",",
"'cache/unicategories.cache'",
")",
"dversion",
",",
"mversion",
",",
"data",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"if",
"dversion",
"==",
"data_version",
"and",
"mversion",
"==",
"module_version",
":",
"return",
"data",
"warnings",
".",
"warn",
"(",
"'Unicode unicategories database is outdated. '",
"'Please reinstall unicategories module to regenerate it.'",
"if",
"dversion",
"<",
"data_version",
"else",
"'Incompatible unicategories database. '",
"'Please reinstall unicategories module to regenerate it.'",
")",
"except",
"(",
"ValueError",
",",
"EOFError",
")",
":",
"warnings",
".",
"warn",
"(",
"'Incompatible unicategories database. '",
"'Please reinstall unicategories module to regenerate it.'",
")",
"except",
"(",
"ImportError",
",",
"FileNotFoundError",
")",
":",
"pass"
] |
Background thread s main function execute registered tasks accordingly to their frequencies | def _run ( cls ) : if cls . _thread : with cls . _lock : # First run: execute each task once to get it started for task in cls . tasks : cls . _execute_task ( task ) cls . tasks . sort ( ) cls . _last_execution = time . time ( ) while cls . _thread : with cls . _lock : if cls . tasks : for task in cls . tasks : if task . next_execution - cls . _last_execution < 0.5 : cls . _execute_task ( task ) else : break cls . tasks . sort ( ) cls . _last_execution = time . time ( ) cls . _sleep_delay = cls . tasks [ 0 ] . next_execution - cls . _last_execution else : cls . _sleep_delay = 1 sleep_delay = max ( 0.1 , cls . _sleep_delay ) # Don't hold cls._lock while sleeping, sleep delay should be 1 second when no tasks are present time . sleep ( sleep_delay ) | 11,883 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/heartbeat.py#L149-L177 | [
"def",
"accept_record",
"(",
"self",
",",
"record",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"req",
"=",
"InclusionRequest",
".",
"get",
"(",
"self",
".",
"id",
",",
"record",
".",
"id",
")",
"if",
"req",
"is",
"None",
":",
"raise",
"InclusionRequestMissingError",
"(",
"community",
"=",
"self",
",",
"record",
"=",
"record",
")",
"req",
".",
"delete",
"(",
")",
"self",
".",
"add_record",
"(",
"record",
")",
"self",
".",
"last_record_accepted",
"=",
"datetime",
".",
"utcnow",
"(",
")"
] |
A standard method of creating parity plots between predicted and experimental values for trained models . | def parity_plot ( X , Y , model , devmodel , axes_labels = None ) : model_outputs = Y . shape [ 1 ] with plt . style . context ( 'seaborn-whitegrid' ) : fig = plt . figure ( figsize = ( 2.5 * model_outputs , 2.5 ) , dpi = 300 ) for i in range ( model_outputs ) : ax = fig . add_subplot ( 1 , model_outputs , i + 1 ) minval = np . min ( [ np . exp ( model . predict ( X ) [ : , i ] ) , np . exp ( Y ) [ : , i ] ] ) maxval = np . max ( [ np . exp ( model . predict ( X ) [ : , i ] ) , np . exp ( Y ) [ : , i ] ] ) buffer = ( maxval - minval ) / 100 * 2 minval = minval - buffer maxval = maxval + buffer ax . plot ( [ minval , maxval ] , [ minval , maxval ] , linestyle = "-" , label = None , c = "black" , linewidth = 1 ) ax . plot ( np . exp ( Y ) [ : , i ] , np . exp ( model . predict ( X ) ) [ : , i ] , marker = "*" , linestyle = "" , alpha = 0.4 ) if axes_labels : ax . set_ylabel ( "Predicted {}" . format ( axes_labels [ '{}' . format ( i ) ] ) ) ax . set_xlabel ( "Actual {}" . format ( axes_labels [ '{}' . format ( i ) ] ) ) else : ax . set_ylabel ( "Predicted {}" . format ( devmodel . Data . columns [ - ( 6 - i ) ] . split ( "<" ) [ 0 ] ) , wrap = True , fontsize = 5 ) ax . set_xlabel ( "Actual {}" . format ( devmodel . Data . columns [ - ( 6 - i ) ] . split ( "<" ) [ 0 ] ) , wrap = True , fontsize = 5 ) plt . xlim ( minval , maxval ) plt . ylim ( minval , maxval ) ax . grid ( ) plt . tight_layout ( ) return plt | 11,884 | https://github.com/wesleybeckner/salty/blob/ef17a97aea3e4f81fcd0359ce85b3438c0e6499b/salty/visualization.py#L6-L60 | [
"def",
"getADSLInfo",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getADSLInfo\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetInfo\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"ADSLInfo",
"(",
"results",
")"
] |
generate year month day features from specified date features | def expand_dates ( df , columns = [ ] ) : columns = df . columns . intersection ( columns ) df2 = df . reindex ( columns = set ( df . columns ) . difference ( columns ) ) for column in columns : df2 [ column + '_year' ] = df [ column ] . apply ( lambda x : x . year ) df2 [ column + '_month' ] = df [ column ] . apply ( lambda x : x . month ) df2 [ column + '_day' ] = df [ column ] . apply ( lambda x : x . day ) return df2 | 11,885 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/data.py#L203-L213 | [
"def",
"get_connection_details",
"(",
"session",
",",
"vcenter_resource_model",
",",
"resource_context",
")",
":",
"session",
"=",
"session",
"resource_context",
"=",
"resource_context",
"# get vCenter connection details from vCenter resource",
"user",
"=",
"vcenter_resource_model",
".",
"user",
"vcenter_url",
"=",
"resource_context",
".",
"address",
"password",
"=",
"session",
".",
"DecryptPassword",
"(",
"vcenter_resource_model",
".",
"password",
")",
".",
"Value",
"return",
"VCenterConnectionDetails",
"(",
"vcenter_url",
",",
"user",
",",
"password",
")"
] |
Binarize specified categoricals . Works inplace! | def binarize ( df , category_classes , all_classes = True , drop = True , astype = None , inplace = True , min_freq = None ) : if type ( category_classes ) is not dict : columns = set ( category_classes ) category_classes = { column : df [ column ] . unique ( ) for column in columns } else : columns = category_classes . keys ( ) df_new = df if inplace else df . drop ( columns , axis = 1 ) for category in columns : classes = category_classes [ category ] for i in range ( len ( classes ) - 1 if not all_classes else len ( classes ) ) : c = df [ category ] == classes [ i ] if not min_freq or c . sum ( ) >= min_freq : if astype is not None : c = c . astype ( astype ) df_new [ '%s_%s' % ( category , str ( classes [ i ] ) . replace ( ' ' , '_' ) ) ] = c if drop and inplace : df_new . drop ( columns , axis = 1 , inplace = True ) return df_new | 11,886 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/data.py#L216-L255 | [
"async",
"def",
"_get_subscriptions",
"(",
"self",
")",
"->",
"Tuple",
"[",
"Set",
"[",
"Text",
"]",
",",
"Text",
"]",
":",
"url",
",",
"params",
"=",
"self",
".",
"_get_subscriptions_endpoint",
"(",
")",
"get",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"async",
"with",
"get",
"as",
"r",
":",
"await",
"self",
".",
"_handle_fb_response",
"(",
"r",
")",
"data",
"=",
"await",
"r",
".",
"json",
"(",
")",
"for",
"scope",
"in",
"data",
"[",
"'data'",
"]",
":",
"if",
"scope",
"[",
"'object'",
"]",
"==",
"'page'",
":",
"return",
"(",
"set",
"(",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"scope",
"[",
"'fields'",
"]",
")",
",",
"scope",
"[",
"'callback_url'",
"]",
",",
")",
"return",
"set",
"(",
")",
",",
"''"
] |
select subset of strings matching a regex treats strings as a set | def select_regexes ( strings , regexes ) : strings = set ( strings ) select = set ( ) if isinstance ( strings , collections . Iterable ) : for r in regexes : s = set ( filter ( re . compile ( '^' + r + '$' ) . search , strings ) ) strings -= s select |= s return select else : raise ValueError ( "exclude should be iterable" ) | 11,887 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/data.py#L399-L413 | [
"def",
"get_status",
"(",
"self",
")",
":",
"status",
"=",
"ctypes",
".",
"c_int32",
"(",
")",
"result",
"=",
"self",
".",
"library",
".",
"Par_GetStatus",
"(",
"self",
".",
"pointer",
",",
"ctypes",
".",
"byref",
"(",
"status",
")",
")",
"check_error",
"(",
"result",
",",
"\"partner\"",
")",
"return",
"status"
] |
parse a string to a delta all is represented by None | def parse_delta ( s ) : if s == 'all' : return None else : ls = delta_regex . findall ( s ) if len ( ls ) == 1 : return relativedelta ( * * { delta_chars [ ls [ 0 ] [ 1 ] ] : int ( ls [ 0 ] [ 0 ] ) } ) else : raise ValueError ( 'Invalid delta string: %s' % s ) | 11,888 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/data.py#L623-L635 | [
"def",
"get_listing",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'listing'",
")",
":",
"allEvents",
"=",
"self",
".",
"get_allEvents",
"(",
")",
"openEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
"closedEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
"publicEvents",
"=",
"allEvents",
".",
"instance_of",
"(",
"PublicEvent",
")",
"allSeries",
"=",
"allEvents",
".",
"instance_of",
"(",
"Series",
")",
"self",
".",
"listing",
"=",
"{",
"'allEvents'",
":",
"allEvents",
",",
"'openEvents'",
":",
"openEvents",
",",
"'closedEvents'",
":",
"closedEvents",
",",
"'publicEvents'",
":",
"publicEvents",
",",
"'allSeries'",
":",
"allSeries",
",",
"'regOpenEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'publicevent__category'",
")",
",",
"'regOpenSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateSeries'",
":",
"allSeries",
".",
"filter",
"(",
"series__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'series__category'",
")",
",",
"}",
"return",
"self",
".",
"listing"
] |
Takes a pd . DataFrame and returns the newly defined column i . e . a pd . Series that has the same index as df . | def apply ( self , df ) : if hasattr ( self . definition , '__call__' ) : r = self . definition ( df ) elif self . definition in df . columns : r = df [ self . definition ] elif not isinstance ( self . definition , string_types ) : r = pd . Series ( self . definition , index = df . index ) else : raise ValueError ( "Invalid column definition: %s" % str ( self . definition ) ) return r . astype ( self . astype ) if self . astype else r | 11,889 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/data.py#L44-L56 | [
"def",
"delete_all_volumes",
"(",
"self",
")",
":",
"# Raise an exception if we are not a manager",
"if",
"not",
"self",
".",
"_manager",
":",
"raise",
"RuntimeError",
"(",
"'Volumes can only be deleted '",
"'on swarm manager nodes'",
")",
"volume_list",
"=",
"self",
".",
"get_volume_list",
"(",
")",
"for",
"volumes",
"in",
"volume_list",
":",
"# Remove all the services",
"self",
".",
"_api_client",
".",
"remove_volume",
"(",
"volumes",
",",
"force",
"=",
"True",
")"
] |
Convert ip address to a network byte order 32 - bit integer . | def ip_to_long ( ip ) : quad = ip . split ( '.' ) if len ( quad ) == 1 : quad = quad + [ 0 , 0 , 0 ] elif len ( quad ) < 4 : host = quad [ - 1 : ] quad = quad [ : - 1 ] + [ 0 , ] * ( 4 - len ( quad ) ) + host lip = 0 for q in quad : lip = ( lip << 8 ) | int ( q ) return lip | 11,890 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/iputils.py#L1-L15 | [
"def",
"snapshot_agents",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"for",
"agent",
"in",
"self",
".",
"_agents",
":",
"agent",
".",
"check_if_should_snapshot",
"(",
"force",
")"
] |
Link to LSST documents given their handle using LSST s ls . st link shortener . | def lsst_doc_shortlink_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : options = options or { } content = content or [ ] node = nodes . reference ( text = '{0}-{1}' . format ( name . upper ( ) , text ) , refuri = 'https://ls.st/{0}-{1}' . format ( name , text ) , * * options ) return [ node ] , [ ] | 11,891 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lsstdocushare.py#L6-L21 | [
"def",
"update_config",
"(",
"self",
",",
"config_dict",
",",
"config_file",
")",
":",
"config_path",
"=",
"path",
".",
"dirname",
"(",
"config_file",
")",
"self",
".",
"config",
".",
"config_file_path",
"=",
"config_file",
"self",
".",
"config",
".",
"path",
"=",
"config_path",
"for",
"config_key",
",",
"config_value",
"in",
"config_dict",
".",
"items",
"(",
")",
":",
"if",
"config_value",
"!=",
"self",
".",
"config",
".",
"get_config_value",
"(",
"config_key",
")",
":",
"self",
".",
"set_preliminary_config_value",
"(",
"config_key",
",",
"config_value",
")"
] |
Link to LSST documents given their handle using LSST s ls . st link shortener with the document handle displayed in title case . | def lsst_doc_shortlink_titlecase_display_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : options = options or { } content = content or [ ] node = nodes . reference ( text = '{0}-{1}' . format ( name . title ( ) , text ) , refuri = 'https://ls.st/{0}-{1}' . format ( name , text ) , * * options ) return [ node ] , [ ] | 11,892 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lsstdocushare.py#L24-L42 | [
"def",
"config_delete",
"(",
"args",
")",
":",
"r",
"=",
"fapi",
".",
"delete_workspace_config",
"(",
"args",
".",
"project",
",",
"args",
".",
"workspace",
",",
"args",
".",
"namespace",
",",
"args",
".",
"config",
")",
"fapi",
".",
"_check_response_code",
"(",
"r",
",",
"[",
"200",
",",
"204",
"]",
")",
"return",
"r",
".",
"text",
"if",
"r",
".",
"text",
"else",
"None"
] |
Command line entrypoint for the refresh - lsst - bib program . | def run ( ) : args = parse_args ( ) if args . verbose : log_level = logging . DEBUG else : log_level = logging . INFO logging . basicConfig ( level = log_level , format = '%(asctime)s %(levelname)s %(name)s: %(message)s' ) if not args . verbose : # Manage third-party loggers req_logger = logging . getLogger ( 'requests' ) req_logger . setLevel ( logging . WARNING ) logger = logging . getLogger ( __name__ ) logger . info ( 'refresh-lsst-bib version {}' . format ( __version__ ) ) error_count = process_bib_files ( args . dir ) sys . exit ( error_count ) | 11,893 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/bin/refreshlsstbib.py#L20-L43 | [
"def",
"_parse_directory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_parser",
".",
"has_option",
"(",
"'storage'",
",",
"'directory'",
")",
":",
"directory",
"=",
"self",
".",
"_parser",
".",
"get",
"(",
"'storage'",
",",
"'directory'",
")",
"# Don't allow CUSTOM_APPS_DIR as a storage directory",
"if",
"directory",
"==",
"CUSTOM_APPS_DIR",
":",
"raise",
"ConfigError",
"(",
"\"{} cannot be used as a storage directory.\"",
".",
"format",
"(",
"CUSTOM_APPS_DIR",
")",
")",
"else",
":",
"directory",
"=",
"MACKUP_BACKUP_PATH",
"return",
"str",
"(",
"directory",
")"
] |
Command line entrypoint for the build - stack - docs program . | def run_build_cli ( ) : args = parse_args ( ) if args . verbose : log_level = logging . DEBUG else : log_level = logging . INFO logging . basicConfig ( level = log_level , format = '%(asctime)s %(levelname)s %(name)s: %(message)s' ) logger = logging . getLogger ( __name__ ) logger . info ( 'build-stack-docs version {0}' . format ( __version__ ) ) return_code = build_stack_docs ( args . root_project_dir ) if return_code == 0 : logger . info ( 'build-stack-docs succeeded' ) sys . exit ( 0 ) else : logger . error ( 'Sphinx errored: code {0:d}' . format ( return_code ) ) sys . exit ( 1 ) | 11,894 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L25-L48 | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"update_ttl",
"(",
"other",
".",
"ttl",
")",
"super",
"(",
"Rdataset",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] |
Create an argument parser for the build - stack - docs program . | def parse_args ( ) : parser = argparse . ArgumentParser ( description = "Build a Sphinx documentation site for an EUPS stack, " "such as pipelines.lsst.io." , epilog = "Version {0}" . format ( __version__ ) ) parser . add_argument ( '-d' , '--dir' , dest = 'root_project_dir' , help = "Root Sphinx project directory" ) parser . add_argument ( '-v' , '--verbose' , dest = 'verbose' , action = 'store_true' , default = False , help = 'Enable Verbose output (debug level logging)' ) return parser . parse_args ( ) | 11,895 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L133-L156 | [
"def",
"getVATAmount",
"(",
"self",
")",
":",
"price",
",",
"vat",
"=",
"self",
".",
"getPrice",
"(",
")",
",",
"self",
".",
"getVAT",
"(",
")",
"return",
"float",
"(",
"price",
")",
"*",
"(",
"float",
"(",
"vat",
")",
"/",
"100",
")"
] |
Summarize packages currently set up by EUPS listing their set up directories and EUPS version names . | def discover_setup_packages ( ) : logger = logging . getLogger ( __name__ ) # Not a PyPI dependency; assumed to be available in the build environment. import eups eups_client = eups . Eups ( ) products = eups_client . getSetupProducts ( ) packages = { } for package in products : name = package . name info = { 'dir' : package . dir , 'version' : package . version } packages [ name ] = info logger . debug ( 'Found setup package: {name} {version} {dir}' . format ( name = name , * * info ) ) return packages | 11,896 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L159-L198 | [
"def",
"removeAll",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"_removeAll",
"(",
"self",
".",
"_reads",
",",
"self",
".",
"_writes",
")",
"return",
"rv"
] |
Find the EUPS table file for a project . | def find_table_file ( root_project_dir ) : ups_dir_path = os . path . join ( root_project_dir , 'ups' ) table_path = None for name in os . listdir ( ups_dir_path ) : if name . endswith ( '.table' ) : table_path = os . path . join ( ups_dir_path , name ) break if not os . path . exists ( table_path ) : raise RuntimeError ( 'Could not find the EUPS table file at {}' . format ( table_path ) ) return table_path | 11,897 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L201-L225 | [
"def",
"delete",
"(",
"request",
",",
"obj_id",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"DELETE",
"or",
"json",
".",
"loads",
"(",
"request",
".",
"body",
")",
"guids",
"=",
"data",
".",
"get",
"(",
"'guids'",
")",
".",
"split",
"(",
"','",
")",
"objects",
"=",
"getObjectsFromGuids",
"(",
"guids",
")",
"gallery",
"=",
"Gallery",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"obj_id",
")",
"LOGGER",
".",
"info",
"(",
"'{} removed {} from {}'",
".",
"format",
"(",
"request",
".",
"user",
".",
"email",
",",
"guids",
",",
"gallery",
")",
")",
"for",
"o",
"in",
"objects",
":",
"if",
"isinstance",
"(",
"o",
",",
"Image",
")",
":",
"gallery",
".",
"images",
".",
"remove",
"(",
"o",
")",
"elif",
"isinstance",
"(",
"o",
",",
"Video",
")",
":",
"gallery",
".",
"videos",
".",
"remove",
"(",
"o",
")",
"res",
"=",
"Result",
"(",
")",
"return",
"JsonResponse",
"(",
"res",
".",
"asDict",
"(",
")",
")"
] |
List the names of packages that are required by an EUPS table file . | def list_packages_in_eups_table ( table_text ) : logger = logging . getLogger ( __name__ ) # This pattern matches required product names in EUPS table files. pattern = re . compile ( r'setupRequired\((?P<name>\w+)\)' ) listed_packages = [ m . group ( 'name' ) for m in pattern . finditer ( table_text ) ] logger . debug ( 'Packages listed in the table file: %r' , listed_packages ) return listed_packages | 11,898 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L228-L246 | [
"def",
"_iter_grouped_shortcut",
"(",
"self",
")",
":",
"var",
"=",
"self",
".",
"_obj",
".",
"variable",
"for",
"indices",
"in",
"self",
".",
"_group_indices",
":",
"yield",
"var",
"[",
"{",
"self",
".",
"_group_dim",
":",
"indices",
"}",
"]"
] |
Find documentation directories in a package using manifest . yaml . | def find_package_docs ( package_dir , skippedNames = None ) : logger = logging . getLogger ( __name__ ) if skippedNames is None : skippedNames = [ ] doc_dir = os . path . join ( package_dir , 'doc' ) modules_yaml_path = os . path . join ( doc_dir , 'manifest.yaml' ) if not os . path . exists ( modules_yaml_path ) : raise NoPackageDocs ( 'Manifest YAML not found: {0}' . format ( modules_yaml_path ) ) with open ( modules_yaml_path ) as f : manifest_data = yaml . safe_load ( f ) module_dirs = { } package_dirs = { } static_dirs = { } if 'modules' in manifest_data : for module_name in manifest_data [ 'modules' ] : if module_name in skippedNames : logger . debug ( 'Skipping module {0}' . format ( module_name ) ) continue module_dir = os . path . join ( doc_dir , module_name ) # validate that the module's documentation directory does exist if not os . path . isdir ( module_dir ) : message = 'module doc dir not found: {0}' . format ( module_dir ) logger . warning ( message ) continue module_dirs [ module_name ] = module_dir logger . debug ( 'Found module doc dir {0}' . format ( module_dir ) ) if 'package' in manifest_data : package_name = manifest_data [ 'package' ] full_package_dir = os . path . join ( doc_dir , package_name ) # validate the directory exists if os . path . isdir ( full_package_dir ) and package_name not in skippedNames : package_dirs [ package_name ] = full_package_dir logger . debug ( 'Found package doc dir {0}' . format ( full_package_dir ) ) else : logger . warning ( 'package doc dir excluded or not found: {0}' . format ( full_package_dir ) ) if 'statics' in manifest_data : for static_dirname in manifest_data [ 'statics' ] : full_static_dir = os . path . join ( doc_dir , static_dirname ) # validate the directory exists if not os . path . isdir ( full_static_dir ) : message = '_static doc dir not found: {0}' . format ( full_static_dir ) logger . warning ( message ) continue # Make a relative path to `_static` that's used as the # link source in the root docproject's _static/ directory relative_static_dir = os . path . relpath ( full_static_dir , os . path . join ( doc_dir , '_static' ) ) static_dirs [ relative_static_dir ] = full_static_dir logger . debug ( 'Found _static doc dir: {0}' . format ( full_static_dir ) ) Dirs = namedtuple ( 'Dirs' , [ 'module_dirs' , 'package_dirs' , 'static_dirs' ] ) return Dirs ( module_dirs = module_dirs , package_dirs = package_dirs , static_dirs = static_dirs ) | 11,899 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/build.py#L249-L395 | [
"def",
"_get_site_amplification_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"s_b",
",",
"s_c",
",",
"s_d",
"=",
"self",
".",
"_get_site_dummy_variables",
"(",
"vs30",
")",
"return",
"(",
"C",
"[",
"\"sB\"",
"]",
"*",
"s_b",
")",
"+",
"(",
"C",
"[",
"\"sC\"",
"]",
"*",
"s_c",
")",
"+",
"(",
"C",
"[",
"\"sD\"",
"]",
"*",
"s_d",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.