query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
sequencelengths 20
553
|
---|---|---|---|---|
Format value to string with SI prefix using the specified precision . | def si_format ( value , precision = 1 , format_str = u'{value} {prefix}' , exp_format_str = u'{value}e{expof10}' ) : svalue , expof10 = split ( value , precision ) value_format = u'%%.%df' % precision value_str = value_format % svalue try : return format_str . format ( value = value_str , prefix = prefix ( expof10 ) . strip ( ) ) except ValueError : sign = '' if expof10 > 0 : sign = "+" return exp_format_str . format ( value = value_str , expof10 = '' . join ( [ sign , str ( expof10 ) ] ) ) | 1,000 | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L128-L221 | [
"def",
"_handle_run",
"(",
"self",
",",
"relpath",
",",
"params",
")",
":",
"args",
"=",
"self",
".",
"_default_template_args",
"(",
"'run.html'",
")",
"run_id",
"=",
"relpath",
"run_info",
"=",
"self",
".",
"_get_run_info_dict",
"(",
"run_id",
")",
"if",
"run_info",
"is",
"None",
":",
"args",
"[",
"'no_such_run'",
"]",
"=",
"relpath",
"if",
"run_id",
"==",
"'latest'",
":",
"args",
"[",
"'is_latest'",
"]",
"=",
"'none'",
"else",
":",
"report_abspath",
"=",
"run_info",
"[",
"'default_report'",
"]",
"report_relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"report_abspath",
",",
"self",
".",
"_root",
")",
"report_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"report_relpath",
")",
"self_timings_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"report_dir",
",",
"'self_timings'",
")",
"cumulative_timings_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"report_dir",
",",
"'cumulative_timings'",
")",
"artifact_cache_stats_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"report_dir",
",",
"'artifact_cache_stats'",
")",
"run_info",
"[",
"'timestamp_text'",
"]",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",
"run_info",
"[",
"'timestamp'",
"]",
")",
")",
".",
"strftime",
"(",
"'%H:%M:%S on %A, %B %d %Y'",
")",
"timings_and_stats",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"self",
".",
"_collapsible_fmt_string",
".",
"format",
"(",
"id",
"=",
"'cumulative-timings-collapsible'",
",",
"title",
"=",
"'Cumulative timings'",
",",
"class_prefix",
"=",
"'aggregated-timings'",
")",
",",
"self",
".",
"_collapsible_fmt_string",
".",
"format",
"(",
"id",
"=",
"'self-timings-collapsible'",
",",
"title",
"=",
"'Self timings'",
",",
"class_prefix",
"=",
"'aggregated-timings'",
")",
",",
"self",
".",
"_collapsible_fmt_string",
".",
"format",
"(",
"id",
"=",
"'artifact-cache-stats-collapsible'",
",",
"title",
"=",
"'Artifact cache stats'",
",",
"class_prefix",
"=",
"'artifact-cache-stats'",
")",
"]",
")",
"args",
".",
"update",
"(",
"{",
"'run_info'",
":",
"run_info",
",",
"'report_path'",
":",
"report_relpath",
",",
"'self_timings_path'",
":",
"self_timings_path",
",",
"'cumulative_timings_path'",
":",
"cumulative_timings_path",
",",
"'artifact_cache_stats_path'",
":",
"artifact_cache_stats_path",
",",
"'timings_and_stats'",
":",
"timings_and_stats",
"}",
")",
"if",
"run_id",
"==",
"'latest'",
":",
"args",
"[",
"'is_latest'",
"]",
"=",
"run_info",
"[",
"'id'",
"]",
"content",
"=",
"self",
".",
"_renderer",
".",
"render_name",
"(",
"'base.html'",
",",
"args",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
"self",
".",
"_send_content",
"(",
"content",
",",
"'text/html'",
")"
] |
Parse a value expressed using SI prefix units to a floating point number . | def si_parse ( value ) : CRE_10E_NUMBER = re . compile ( r'^\s*(?P<integer>[\+\-]?\d+)?' r'(?P<fraction>.\d+)?\s*([eE]\s*' r'(?P<expof10>[\+\-]?\d+))?$' ) CRE_SI_NUMBER = re . compile ( r'^\s*(?P<number>(?P<integer>[\+\-]?\d+)?' r'(?P<fraction>.\d+)?)\s*' u'(?P<si_unit>[%s])?\s*$' % SI_PREFIX_UNITS ) match = CRE_10E_NUMBER . match ( value ) if match : # Can be parse using `float`. assert ( match . group ( 'integer' ) is not None or match . group ( 'fraction' ) is not None ) return float ( value ) match = CRE_SI_NUMBER . match ( value ) assert ( match . group ( 'integer' ) is not None or match . group ( 'fraction' ) is not None ) d = match . groupdict ( ) si_unit = d [ 'si_unit' ] if d [ 'si_unit' ] else ' ' prefix_levels = ( len ( SI_PREFIX_UNITS ) - 1 ) // 2 scale = 10 ** ( 3 * ( SI_PREFIX_UNITS . index ( si_unit ) - prefix_levels ) ) return float ( d [ 'number' ] ) * scale | 1,001 | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L224-L263 | [
"def",
"_update_simulation_end_from_lsm",
"(",
"self",
")",
":",
"te",
"=",
"self",
".",
"l2g",
".",
"xd",
".",
"lsm",
".",
"datetime",
"[",
"-",
"1",
"]",
"simulation_end",
"=",
"te",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
".",
"astimezone",
"(",
"tz",
"=",
"self",
".",
"tz",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"if",
"self",
".",
"simulation_end",
"is",
"None",
":",
"self",
".",
"simulation_end",
"=",
"simulation_end",
"elif",
"self",
".",
"simulation_end",
">",
"simulation_end",
":",
"self",
".",
"simulation_end",
"=",
"simulation_end",
"self",
".",
"_update_card",
"(",
"\"END_TIME\"",
",",
"self",
".",
"simulation_end",
".",
"strftime",
"(",
"\"%Y %m %d %H %M\"",
")",
")"
] |
Set sensor name status to status . | def set_status ( self , name , status ) : getattr ( self . system , name ) . status = status return True | 1,002 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L31-L36 | [
"def",
"_generate_noise_system",
"(",
"dimensions_tr",
",",
"spatial_sd",
",",
"temporal_sd",
",",
"spatial_noise_type",
"=",
"'gaussian'",
",",
"temporal_noise_type",
"=",
"'gaussian'",
",",
")",
":",
"def",
"noise_volume",
"(",
"dimensions",
",",
"noise_type",
",",
")",
":",
"if",
"noise_type",
"==",
"'rician'",
":",
"# Generate the Rician noise (has an SD of 1)",
"noise",
"=",
"stats",
".",
"rice",
".",
"rvs",
"(",
"b",
"=",
"0",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1.527",
",",
"size",
"=",
"dimensions",
")",
"elif",
"noise_type",
"==",
"'exponential'",
":",
"# Make an exponential distribution (has an SD of 1)",
"noise",
"=",
"stats",
".",
"expon",
".",
"rvs",
"(",
"0",
",",
"scale",
"=",
"1",
",",
"size",
"=",
"dimensions",
")",
"elif",
"noise_type",
"==",
"'gaussian'",
":",
"noise",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"np",
".",
"prod",
"(",
"dimensions",
")",
")",
".",
"reshape",
"(",
"dimensions",
")",
"# Return the noise",
"return",
"noise",
"# Get just the xyz coordinates",
"dimensions",
"=",
"np",
".",
"asarray",
"(",
"[",
"dimensions_tr",
"[",
"0",
"]",
",",
"dimensions_tr",
"[",
"1",
"]",
",",
"dimensions_tr",
"[",
"2",
"]",
",",
"1",
"]",
")",
"# Generate noise",
"spatial_noise",
"=",
"noise_volume",
"(",
"dimensions",
",",
"spatial_noise_type",
")",
"temporal_noise",
"=",
"noise_volume",
"(",
"dimensions_tr",
",",
"temporal_noise_type",
")",
"# Make the system noise have a specific spatial variability",
"spatial_noise",
"*=",
"spatial_sd",
"# Set the size of the noise",
"temporal_noise",
"*=",
"temporal_sd",
"# The mean in time of system noise needs to be zero, so subtract the",
"# means of the temporal noise in time",
"temporal_noise_mean",
"=",
"np",
".",
"mean",
"(",
"temporal_noise",
",",
"3",
")",
".",
"reshape",
"(",
"dimensions",
"[",
"0",
"]",
",",
"dimensions",
"[",
"1",
"]",
",",
"dimensions",
"[",
"2",
"]",
",",
"1",
")",
"temporal_noise",
"=",
"temporal_noise",
"-",
"temporal_noise_mean",
"# Save the combination",
"system_noise",
"=",
"spatial_noise",
"+",
"temporal_noise",
"return",
"system_noise"
] |
Toggle boolean - valued sensor status between True and False . | def toggle_object_status ( self , objname ) : o = getattr ( self . system , objname ) o . status = not o . status self . system . flush ( ) return o . status | 1,003 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L52-L59 | [
"def",
"NewFromContent",
"(",
"cls",
",",
"content",
",",
"urn",
",",
"chunk_size",
"=",
"1024",
",",
"token",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"public_key",
"=",
"None",
")",
":",
"aff4",
".",
"FACTORY",
".",
"Delete",
"(",
"urn",
",",
"token",
"=",
"token",
")",
"with",
"data_store",
".",
"DB",
".",
"GetMutationPool",
"(",
")",
"as",
"pool",
":",
"with",
"aff4",
".",
"FACTORY",
".",
"Create",
"(",
"urn",
",",
"cls",
",",
"mode",
"=",
"\"w\"",
",",
"mutation_pool",
"=",
"pool",
",",
"token",
"=",
"token",
")",
"as",
"fd",
":",
"for",
"start_of_chunk",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"content",
")",
",",
"chunk_size",
")",
":",
"chunk",
"=",
"content",
"[",
"start_of_chunk",
":",
"start_of_chunk",
"+",
"chunk_size",
"]",
"blob_rdf",
"=",
"rdf_crypto",
".",
"SignedBlob",
"(",
")",
"blob_rdf",
".",
"Sign",
"(",
"chunk",
",",
"private_key",
",",
"public_key",
")",
"fd",
".",
"Add",
"(",
"blob_rdf",
",",
"mutation_pool",
"=",
"pool",
")",
"return",
"urn"
] |
Return recent log entries as a string . | def log ( self ) : logserv = self . system . request_service ( 'LogStoreService' ) return logserv . lastlog ( html = False ) | 1,004 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L93-L98 | [
"def",
"_proc_accept_header",
"(",
"self",
",",
"request",
",",
"result",
")",
":",
"if",
"result",
":",
"# Result has already been fully determined",
"return",
"try",
":",
"accept",
"=",
"request",
".",
"headers",
"[",
"'accept'",
"]",
"except",
"KeyError",
":",
"# No Accept header to examine",
"return",
"# Obtain the best-match content type and its parameters",
"ctype",
",",
"params",
"=",
"best_match",
"(",
"accept",
",",
"self",
".",
"types",
".",
"keys",
"(",
")",
")",
"# Is it a recognized content type?",
"if",
"ctype",
"not",
"in",
"self",
".",
"types",
":",
"return",
"# Get the mapped ctype and version",
"mapped_ctype",
",",
"mapped_version",
"=",
"self",
".",
"types",
"[",
"ctype",
"]",
"(",
"params",
")",
"# Set the content type and version",
"if",
"mapped_ctype",
":",
"result",
".",
"set_ctype",
"(",
"mapped_ctype",
",",
"ctype",
")",
"if",
"mapped_version",
":",
"result",
".",
"set_version",
"(",
"mapped_version",
")"
] |
Load system from a dump if dump file exists or create a new system if it does not exist . | def load_or_create ( cls , filename = None , no_input = False , create_new = False , * * kwargs ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( '--no_input' , action = 'store_true' ) parser . add_argument ( '--create_new' , action = 'store_true' ) args = parser . parse_args ( ) if args . no_input : print ( 'Parameter --no_input was given' ) no_input = True if args . create_new : print ( 'Parameter --create_new was given' ) create_new = True no_input = True def savefile_more_recent ( ) : time_savefile = os . path . getmtime ( filename ) time_program = os . path . getmtime ( sys . argv [ 0 ] ) return time_savefile > time_program def load_pickle ( ) : with open ( filename , 'rb' ) as of : statefile_version , data = pickle . load ( of ) if statefile_version != STATEFILE_VERSION : raise RuntimeError ( f'Wrong statefile version, please remove state file {filename}' ) return data def load ( ) : print ( 'Loading %s' % filename ) obj_list , config = load_pickle ( ) system = System ( load_state = obj_list , filename = filename , * * kwargs ) return system def create ( ) : print ( 'Creating new system' ) config = None if filename : try : obj_list , config = load_pickle ( ) except FileNotFoundError : config = None return cls ( filename = filename , load_config = config , * * kwargs ) if filename and os . path . isfile ( filename ) : if savefile_more_recent ( ) and not create_new : return load ( ) else : if no_input : print ( 'Program file more recent. Loading that instead.' ) return create ( ) while True : answer = input ( 'Program file more recent. Do you want to load it? (y/n) ' ) if answer == 'y' : return create ( ) elif answer == 'n' : return load ( ) else : return create ( ) | 1,005 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L200-L261 | [
"def",
"unbind",
"(",
"self",
")",
":",
"for",
"variable",
"in",
"self",
".",
"variables",
":",
"self",
".",
"__unbind_variable",
"(",
"variable",
")",
"for",
"result",
"in",
"self",
".",
"results",
":",
"self",
".",
"__unbind_result",
"(",
"result",
")"
] |
A read - only property that gives the namespace of the system for evaluating commands . | def cmd_namespace ( self ) : import automate ns = dict ( list ( automate . __dict__ . items ( ) ) + list ( self . namespace . items ( ) ) ) return ns | 1,006 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L287-L293 | [
"def",
"online_merge_medium",
"(",
"self",
",",
"medium_attachment",
",",
"source_idx",
",",
"target_idx",
",",
"progress",
")",
":",
"if",
"not",
"isinstance",
"(",
"medium_attachment",
",",
"IMediumAttachment",
")",
":",
"raise",
"TypeError",
"(",
"\"medium_attachment can only be an instance of type IMediumAttachment\"",
")",
"if",
"not",
"isinstance",
"(",
"source_idx",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"source_idx can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
"target_idx",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"target_idx can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
"progress",
",",
"IProgress",
")",
":",
"raise",
"TypeError",
"(",
"\"progress can only be an instance of type IProgress\"",
")",
"self",
".",
"_call",
"(",
"\"onlineMergeMedium\"",
",",
"in_p",
"=",
"[",
"medium_attachment",
",",
"source_idx",
",",
"target_idx",
",",
"progress",
"]",
")"
] |
A property that gives a dictionary that contains services as values and their names as keys . | def services_by_name ( self ) : srvs = defaultdict ( list ) for i in self . services : srvs [ i . __class__ . __name__ ] . append ( i ) return srvs | 1,007 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L323-L330 | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_md",
".",
"update",
"(",
"data",
")",
"bufpos",
"=",
"self",
".",
"_nbytes",
"&",
"63",
"self",
".",
"_nbytes",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_rarbug",
"and",
"len",
"(",
"data",
")",
">",
"64",
":",
"dpos",
"=",
"self",
".",
"block_size",
"-",
"bufpos",
"while",
"dpos",
"+",
"self",
".",
"block_size",
"<=",
"len",
"(",
"data",
")",
":",
"self",
".",
"_corrupt",
"(",
"data",
",",
"dpos",
")",
"dpos",
"+=",
"self",
".",
"block_size"
] |
Give SystemObject instance corresponding to the name | def name_to_system_object ( self , name ) : if isinstance ( name , str ) : if self . allow_name_referencing : name = name else : raise NameError ( 'System.allow_name_referencing is set to False, cannot convert string to name' ) elif isinstance ( name , Object ) : name = str ( name ) return self . namespace . get ( name , None ) | 1,008 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L345-L356 | [
"def",
"get_params",
"(",
"self",
")",
":",
"return",
"self",
".",
"timeout",
",",
"self",
".",
"xonxoff",
",",
"self",
".",
"rtscts",
",",
"self",
".",
"baudrate"
] |
Register function in the system namespace . Called by Services . | def register_service_functions ( self , * funcs ) : for func in funcs : self . namespace [ func . __name__ ] = func | 1,009 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L369-L374 | [
"def",
"get_time_to_merge_request_response",
"(",
"self",
",",
"item",
")",
":",
"review_dates",
"=",
"[",
"str_to_datetime",
"(",
"review",
"[",
"'created_at'",
"]",
")",
"for",
"review",
"in",
"item",
"[",
"'review_comments_data'",
"]",
"if",
"item",
"[",
"'user'",
"]",
"[",
"'login'",
"]",
"!=",
"review",
"[",
"'user'",
"]",
"[",
"'login'",
"]",
"]",
"if",
"review_dates",
":",
"return",
"min",
"(",
"review_dates",
")",
"return",
"None"
] |
Register service into the system . Called by Services . | def register_service ( self , service ) : if service not in self . services : self . services . append ( service ) | 1,010 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L376-L381 | [
"def",
"set_default_headers",
"(",
"self",
")",
":",
"mod_opts",
"=",
"self",
".",
"application",
".",
"mod_opts",
"if",
"mod_opts",
".",
"get",
"(",
"'cors_origin'",
")",
":",
"origin",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Origin'",
")",
"allowed_origin",
"=",
"_check_cors_origin",
"(",
"origin",
",",
"mod_opts",
"[",
"'cors_origin'",
"]",
")",
"if",
"allowed_origin",
":",
"self",
".",
"set_header",
"(",
"\"Access-Control-Allow-Origin\"",
",",
"allowed_origin",
")"
] |
Clean up before quitting | def cleanup ( self ) : self . pre_exit_trigger = True self . logger . info ( "Shutting down %s, please wait a moment." , self . name ) for t in threading . enumerate ( ) : if isinstance ( t , TimerClass ) : t . cancel ( ) self . logger . debug ( 'Timers cancelled' ) for i in self . objects : i . cleanup ( ) self . logger . debug ( 'Sensors etc cleanups done' ) for ser in ( i for i in self . services if isinstance ( i , AbstractUserService ) ) : ser . cleanup_system ( ) self . logger . debug ( 'User services cleaned up' ) if self . worker_thread . is_alive ( ) : self . worker_thread . stop ( ) self . logger . debug ( 'Worker thread really stopped' ) for ser in ( i for i in self . services if isinstance ( i , AbstractSystemService ) ) : ser . cleanup_system ( ) self . logger . debug ( 'System services cleaned up' ) threads = list ( t . name for t in threading . enumerate ( ) if t . is_alive ( ) and not t . daemon ) if threads : self . logger . info ( 'After cleanup, we have still the following threads ' 'running: %s' , ', ' . join ( threads ) ) | 1,011 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L398-L429 | [
"def",
"archive",
"(",
"base_dir",
":",
"str",
")",
"->",
"int",
":",
"LOGGER",
".",
"debug",
"(",
"'archive >>> base_dir: %s'",
",",
"base_dir",
")",
"rv",
"=",
"int",
"(",
"time",
"(",
")",
")",
"timestamp_dir",
"=",
"join",
"(",
"base_dir",
",",
"str",
"(",
"rv",
")",
")",
"makedirs",
"(",
"timestamp_dir",
",",
"exist_ok",
"=",
"True",
")",
"with",
"SCHEMA_CACHE",
".",
"lock",
":",
"with",
"open",
"(",
"join",
"(",
"timestamp_dir",
",",
"'schema'",
")",
",",
"'w'",
")",
"as",
"archive",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"SCHEMA_CACHE",
".",
"schemata",
"(",
")",
")",
",",
"file",
"=",
"archive",
")",
"with",
"CRED_DEF_CACHE",
".",
"lock",
":",
"with",
"open",
"(",
"join",
"(",
"timestamp_dir",
",",
"'cred_def'",
")",
",",
"'w'",
")",
"as",
"archive",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"CRED_DEF_CACHE",
")",
",",
"file",
"=",
"archive",
")",
"with",
"REVO_CACHE",
".",
"lock",
":",
"with",
"open",
"(",
"join",
"(",
"timestamp_dir",
",",
"'revocation'",
")",
",",
"'w'",
")",
"as",
"archive",
":",
"revo_cache_dict",
"=",
"{",
"}",
"for",
"rr_id",
"in",
"REVO_CACHE",
":",
"revo_cache_dict",
"[",
"rr_id",
"]",
"=",
"{",
"'rev_reg_def'",
":",
"REVO_CACHE",
"[",
"rr_id",
"]",
".",
"rev_reg_def",
",",
"'rr_delta_frames'",
":",
"[",
"vars",
"(",
"f",
")",
"for",
"f",
"in",
"REVO_CACHE",
"[",
"rr_id",
"]",
".",
"rr_delta_frames",
"]",
",",
"'rr_state_frames'",
":",
"[",
"vars",
"(",
"f",
")",
"for",
"f",
"in",
"REVO_CACHE",
"[",
"rr_id",
"]",
".",
"rr_state_frames",
"]",
"}",
"print",
"(",
"json",
".",
"dumps",
"(",
"revo_cache_dict",
")",
",",
"file",
"=",
"archive",
")",
"LOGGER",
".",
"debug",
"(",
"'archive <<< %s'",
",",
"rv",
")",
"return",
"rv"
] |
Execute commands in automate namespace | def cmd_exec ( self , cmd ) : if not cmd : return ns = self . cmd_namespace import copy rval = True nscopy = copy . copy ( ns ) try : r = eval ( cmd , ns ) if isinstance ( r , SystemObject ) and not r . system : r . setup_system ( self ) if callable ( r ) : r = r ( ) cmd += "()" self . logger . info ( "Eval: %s" , cmd ) self . logger . info ( "Result: %s" , r ) except SyntaxError : r = { } try : exec ( cmd , ns ) self . logger . info ( "Exec: %s" , cmd ) except ExitException : raise except Exception as e : self . logger . info ( "Failed to exec cmd %s: %s." , cmd , e ) rval = False for key , value in list ( ns . items ( ) ) : if key not in nscopy or not value is nscopy [ key ] : if key in self . namespace : del self . namespace [ key ] self . namespace [ key ] = value r [ key ] = value self . logger . info ( "Set items in namespace: %s" , r ) except ExitException : raise except Exception as e : self . logger . info ( "Failed to eval cmd %s: %s" , cmd , e ) return False return rval | 1,012 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L431-L474 | [
"def",
"query_cat_random",
"(",
"catid",
",",
"*",
"*",
"kwargs",
")",
":",
"num",
"=",
"kwargs",
".",
"get",
"(",
"'limit'",
",",
"8",
")",
"if",
"catid",
"==",
"''",
":",
"rand_recs",
"=",
"TabPost",
".",
"select",
"(",
")",
".",
"order_by",
"(",
"peewee",
".",
"fn",
".",
"Random",
"(",
")",
")",
".",
"limit",
"(",
"num",
")",
"else",
":",
"rand_recs",
"=",
"TabPost",
".",
"select",
"(",
")",
".",
"join",
"(",
"TabPost2Tag",
",",
"on",
"=",
"(",
"TabPost",
".",
"uid",
"==",
"TabPost2Tag",
".",
"post_id",
")",
")",
".",
"where",
"(",
"(",
"TabPost",
".",
"valid",
"==",
"1",
")",
"&",
"(",
"TabPost2Tag",
".",
"tag_id",
"==",
"catid",
")",
")",
".",
"order_by",
"(",
"peewee",
".",
"fn",
".",
"Random",
"(",
")",
")",
".",
"limit",
"(",
"num",
")",
"return",
"rand_recs"
] |
Writes PUML from the system . If filename is given stores result in the file . Otherwise returns result as a string . | def write_puml ( self , filename = '' ) : def get_type ( o ) : type = 'program' if isinstance ( o , AbstractSensor ) : type = 'sensor' elif isinstance ( o , AbstractActuator ) : type = 'actuator' return type if filename : s = open ( filename , 'w' ) else : s = io . StringIO ( ) s . write ( '@startuml\n' ) s . write ( 'skinparam state {\n' ) for k , v in list ( self . background_colors . items ( ) ) : s . write ( 'BackGroundColor<<%s>> %s\n' % ( k , v ) ) s . write ( '}\n' ) for o in self . system . objects : if isinstance ( o , DefaultProgram ) or o . hide_in_uml : continue if isinstance ( o , ProgrammableSystemObject ) : s . write ( 'state "%s" as %s <<%s>>\n' % ( o , o , get_type ( o ) ) ) s . write ( '%s: %s\n' % ( o , o . class_name ) ) if isinstance ( o , AbstractActuator ) : for p in reversed ( o . program_stack ) : s . write ( '%s: %s :: %s\n' % ( o , p , o . program_status . get ( p , '-' ) ) ) elif hasattr ( o , 'status' ) : s . write ( '%s: Status: %s\n' % ( o , o . status ) ) if getattr ( o , 'is_program' , False ) : s . write ( '%s: Priority: %s\n' % ( o , o . priority ) ) for t in o . actual_triggers : if isinstance ( t , DefaultProgram ) or t . hide_in_uml : continue s . write ( '%s -[%s]-> %s\n' % ( t , self . arrow_colors [ 'trigger' ] , o ) ) for t in o . actual_targets : if t . hide_in_uml : continue if o . active : color = 'active_target' else : color = 'inactive_target' if getattr ( t , 'program' , None ) == o : color = 'controlled_target' s . write ( '%s -[%s]-> %s\n' % ( o , self . arrow_colors [ color ] , t ) ) s . write ( '@enduml\n' ) if filename : s . close ( ) else : return s . getvalue ( ) | 1,013 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/services/plantumlserv.py#L54-L112 | [
"def",
"color_group",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"test_color",
"=",
"None",
")",
":",
"group",
"=",
"self",
".",
"tabs",
".",
"currentWidget",
"(",
")",
"if",
"test_color",
"is",
"None",
":",
"newcolor",
"=",
"QColorDialog",
".",
"getColor",
"(",
"group",
".",
"idx_color",
")",
"else",
":",
"newcolor",
"=",
"test_color",
"group",
".",
"idx_color",
"=",
"newcolor",
"self",
".",
"apply",
"(",
")"
] |
Returns PUML from the system as a SVG image . Requires plantuml library . | def write_svg ( self ) : import plantuml puml = self . write_puml ( ) server = plantuml . PlantUML ( url = self . url ) svg = server . processes ( puml ) return svg | 1,014 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/services/plantumlserv.py#L114-L122 | [
"def",
"client_connected",
"(",
"self",
",",
"reader",
":",
"asyncio",
".",
"StreamReader",
",",
"writer",
":",
"asyncio",
".",
"StreamWriter",
")",
"->",
"None",
":",
"self",
".",
"reader",
"=",
"reader",
"self",
".",
"writer",
"=",
"writer"
] |
Calculate the median kneighbor distance . | def median_kneighbour_distance ( X , k = 5 ) : N_all = X . shape [ 0 ] k = min ( k , N_all ) N_subset = min ( N_all , 2000 ) sample_idx_train = np . random . permutation ( N_all ) [ : N_subset ] nn = neighbors . NearestNeighbors ( k ) nn . fit ( X [ sample_idx_train , : ] ) d , idx = nn . kneighbors ( X [ sample_idx_train , : ] ) return np . median ( d [ : , - 1 ] ) | 1,015 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L12-L27 | [
"def",
"main",
"(",
"api_endpoint",
",",
"credentials",
",",
"device_model_id",
",",
"device_id",
",",
"lang",
",",
"verbose",
",",
"input_audio_file",
",",
"output_audio_file",
",",
"block_size",
",",
"grpc_deadline",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Setup logging.",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"verbose",
"else",
"logging",
".",
"INFO",
")",
"# Load OAuth 2.0 credentials.",
"try",
":",
"with",
"open",
"(",
"credentials",
",",
"'r'",
")",
"as",
"f",
":",
"credentials",
"=",
"google",
".",
"oauth2",
".",
"credentials",
".",
"Credentials",
"(",
"token",
"=",
"None",
",",
"*",
"*",
"json",
".",
"load",
"(",
"f",
")",
")",
"http_request",
"=",
"google",
".",
"auth",
".",
"transport",
".",
"requests",
".",
"Request",
"(",
")",
"credentials",
".",
"refresh",
"(",
"http_request",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"'Error loading credentials: %s'",
",",
"e",
")",
"logging",
".",
"error",
"(",
"'Run google-oauthlib-tool to initialize '",
"'new OAuth 2.0 credentials.'",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"# Create an authorized gRPC channel.",
"grpc_channel",
"=",
"google",
".",
"auth",
".",
"transport",
".",
"grpc",
".",
"secure_authorized_channel",
"(",
"credentials",
",",
"http_request",
",",
"api_endpoint",
")",
"logging",
".",
"info",
"(",
"'Connecting to %s'",
",",
"api_endpoint",
")",
"# Create gRPC stubs",
"assistant",
"=",
"embedded_assistant_pb2_grpc",
".",
"EmbeddedAssistantStub",
"(",
"grpc_channel",
")",
"# Generate gRPC requests.",
"def",
"gen_assist_requests",
"(",
"input_stream",
")",
":",
"dialog_state_in",
"=",
"embedded_assistant_pb2",
".",
"DialogStateIn",
"(",
"language_code",
"=",
"lang",
",",
"conversation_state",
"=",
"b''",
")",
"config",
"=",
"embedded_assistant_pb2",
".",
"AssistConfig",
"(",
"audio_in_config",
"=",
"embedded_assistant_pb2",
".",
"AudioInConfig",
"(",
"encoding",
"=",
"'LINEAR16'",
",",
"sample_rate_hertz",
"=",
"16000",
",",
")",
",",
"audio_out_config",
"=",
"embedded_assistant_pb2",
".",
"AudioOutConfig",
"(",
"encoding",
"=",
"'LINEAR16'",
",",
"sample_rate_hertz",
"=",
"16000",
",",
"volume_percentage",
"=",
"100",
",",
")",
",",
"dialog_state_in",
"=",
"dialog_state_in",
",",
"device_config",
"=",
"embedded_assistant_pb2",
".",
"DeviceConfig",
"(",
"device_id",
"=",
"device_id",
",",
"device_model_id",
"=",
"device_model_id",
",",
")",
")",
"# Send first AssistRequest message with configuration.",
"yield",
"embedded_assistant_pb2",
".",
"AssistRequest",
"(",
"config",
"=",
"config",
")",
"while",
"True",
":",
"# Read user request from file.",
"data",
"=",
"input_stream",
".",
"read",
"(",
"block_size",
")",
"if",
"not",
"data",
":",
"break",
"# Send following AssitRequest message with audio chunks.",
"yield",
"embedded_assistant_pb2",
".",
"AssistRequest",
"(",
"audio_in",
"=",
"data",
")",
"for",
"resp",
"in",
"assistant",
".",
"Assist",
"(",
"gen_assist_requests",
"(",
"input_audio_file",
")",
",",
"grpc_deadline",
")",
":",
"# Iterate on AssistResponse messages.",
"if",
"resp",
".",
"event_type",
"==",
"END_OF_UTTERANCE",
":",
"logging",
".",
"info",
"(",
"'End of audio request detected'",
")",
"if",
"resp",
".",
"speech_results",
":",
"logging",
".",
"info",
"(",
"'Transcript of user request: \"%s\".'",
",",
"' '",
".",
"join",
"(",
"r",
".",
"transcript",
"for",
"r",
"in",
"resp",
".",
"speech_results",
")",
")",
"if",
"len",
"(",
"resp",
".",
"audio_out",
".",
"audio_data",
")",
">",
"0",
":",
"# Write assistant response to supplied file.",
"output_audio_file",
".",
"write",
"(",
"resp",
".",
"audio_out",
".",
"audio_data",
")",
"if",
"resp",
".",
"dialog_state_out",
".",
"supplemental_display_text",
":",
"logging",
".",
"info",
"(",
"'Assistant display text: \"%s\"'",
",",
"resp",
".",
"dialog_state_out",
".",
"supplemental_display_text",
")",
"if",
"resp",
".",
"device_action",
".",
"device_request_json",
":",
"device_request",
"=",
"json",
".",
"loads",
"(",
"resp",
".",
"device_action",
".",
"device_request_json",
")",
"logging",
".",
"info",
"(",
"'Device request: %s'",
",",
"device_request",
")"
] |
Calculate centiles of distances between random pairs in a dataset . | def pair_distance_centile ( X , centile , max_pairs = 5000 ) : N = X . shape [ 0 ] n_pairs = min ( max_pairs , N ** 2 ) # randorder1 = np.random.permutation(N) # randorder2 = np.random.permutation(N) dists = np . zeros ( n_pairs ) for i in range ( n_pairs ) : pair = np . random . randint ( 0 , N , 2 ) pairdiff = X [ pair [ 0 ] , : ] - X [ pair [ 1 ] , : ] dists [ i ] = np . dot ( pairdiff , pairdiff . T ) dists . sort ( ) out = dists [ int ( n_pairs * centile / 100. ) ] return np . sqrt ( out ) | 1,016 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L30-L51 | [
"async",
"def",
"issuer_create_credential",
"(",
"wallet_handle",
":",
"int",
",",
"cred_offer_json",
":",
"str",
",",
"cred_req_json",
":",
"str",
",",
"cred_values_json",
":",
"str",
",",
"rev_reg_id",
":",
"Optional",
"[",
"str",
"]",
",",
"blob_storage_reader_handle",
":",
"Optional",
"[",
"int",
"]",
")",
"->",
"(",
"str",
",",
"Optional",
"[",
"str",
"]",
",",
"Optional",
"[",
"str",
"]",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"issuer_create_credential: >>> wallet_handle: %r, cred_offer_json: %r, cred_req_json: %r,\"",
"\" cred_values_json: %r, rev_reg_id: %r, blob_storage_reader_handle: %r\"",
",",
"wallet_handle",
",",
"cred_offer_json",
",",
"cred_req_json",
",",
"cred_values_json",
",",
"rev_reg_id",
",",
"blob_storage_reader_handle",
")",
"if",
"not",
"hasattr",
"(",
"issuer_create_credential",
",",
"\"cb\"",
")",
":",
"logger",
".",
"debug",
"(",
"\"issuer_create_credential: Creating callback\"",
")",
"issuer_create_credential",
".",
"cb",
"=",
"create_cb",
"(",
"CFUNCTYPE",
"(",
"None",
",",
"c_int32",
",",
"c_int32",
",",
"c_char_p",
",",
"c_char_p",
",",
"c_char_p",
")",
")",
"c_wallet_handle",
"=",
"c_int32",
"(",
"wallet_handle",
")",
"c_cred_offer_json",
"=",
"c_char_p",
"(",
"cred_offer_json",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_cred_req_json",
"=",
"c_char_p",
"(",
"cred_req_json",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_cred_values_json",
"=",
"c_char_p",
"(",
"cred_values_json",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_rev_reg_id",
"=",
"c_char_p",
"(",
"rev_reg_id",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"rev_reg_id",
"is",
"not",
"None",
"else",
"None",
"c_blob_storage_reader_handle",
"=",
"c_int32",
"(",
"blob_storage_reader_handle",
")",
"if",
"blob_storage_reader_handle",
"else",
"-",
"1",
"(",
"cred_json",
",",
"cred_revoc_id",
",",
"revoc_reg_delta_json",
")",
"=",
"await",
"do_call",
"(",
"'indy_issuer_create_credential'",
",",
"c_wallet_handle",
",",
"c_cred_offer_json",
",",
"c_cred_req_json",
",",
"c_cred_values_json",
",",
"c_rev_reg_id",
",",
"c_blob_storage_reader_handle",
",",
"issuer_create_credential",
".",
"cb",
")",
"cred_json",
"=",
"cred_json",
".",
"decode",
"(",
")",
"cred_revoc_id",
"=",
"cred_revoc_id",
".",
"decode",
"(",
")",
"if",
"cred_revoc_id",
"else",
"None",
"revoc_reg_delta_json",
"=",
"revoc_reg_delta_json",
".",
"decode",
"(",
")",
"if",
"revoc_reg_delta_json",
"else",
"None",
"res",
"=",
"(",
"cred_json",
",",
"cred_revoc_id",
",",
"revoc_reg_delta_json",
")",
"logger",
".",
"debug",
"(",
"\"issuer_create_credential: <<< res: %r\"",
",",
"res",
")",
"return",
"res"
] |
Fit the inlier model given training data . | def fit ( self , X , y = None ) : N = X . shape [ 0 ] if y is None : y = np . zeros ( N ) self . classes = list ( set ( y ) ) self . classes . sort ( ) self . n_classes = len ( self . classes ) # If no kernel parameters specified, try to choose some defaults if not self . sigma : self . sigma = median_kneighbour_distance ( X ) self . gamma = self . sigma ** - 2 if not self . gamma : self . gamma = self . sigma ** - 2 if not self . rho : self . rho = 0.1 # choose kernel basis centres if self . kernel_pos is None : B = min ( self . n_kernels_max , N ) kernel_idx = np . random . permutation ( N ) self . kernel_pos = X [ kernel_idx [ : B ] ] else : B = self . kernel_pos . shape [ 0 ] # fit coefficients Phi = metrics . pairwise . rbf_kernel ( X , self . kernel_pos , self . gamma ) theta = { } Phi_PhiT = np . dot ( Phi . T , Phi ) inverse_term = np . linalg . inv ( Phi_PhiT + self . rho * np . eye ( B ) ) for c in self . classes : m = ( y == c ) . astype ( int ) theta [ c ] = np . dot ( inverse_term , np . dot ( Phi . T , m ) ) self . theta = theta | 1,017 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L108-L164 | [
"def",
"monitor",
"(",
"self",
",",
"name",
",",
"handler",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"chan",
"=",
"self",
".",
"_channel",
"(",
"name",
")",
"return",
"Subscription",
"(",
"context",
"=",
"self",
",",
"nt",
"=",
"self",
".",
"_nt",
",",
"channel",
"=",
"chan",
",",
"handler",
"=",
"monHandler",
"(",
"handler",
")",
",",
"pvRequest",
"=",
"wrapRequest",
"(",
"request",
")",
",",
"*",
"*",
"kws",
")"
] |
Assign classes to test data . | def predict ( self , X ) : predictions_proba = self . predict_proba ( X ) predictions = [ ] allclasses = copy . copy ( self . classes ) allclasses . append ( 'anomaly' ) for i in range ( X . shape [ 0 ] ) : predictions . append ( allclasses [ predictions_proba [ i , : ] . argmax ( ) ] ) return predictions | 1,018 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L166-L192 | [
"def",
"memory_allocation",
"(",
"library",
",",
"session",
",",
"size",
",",
"extended",
"=",
"False",
")",
":",
"offset",
"=",
"ViBusAddress",
"(",
")",
"if",
"extended",
":",
"ret",
"=",
"library",
".",
"viMemAllocEx",
"(",
"session",
",",
"size",
",",
"byref",
"(",
"offset",
")",
")",
"else",
":",
"ret",
"=",
"library",
".",
"viMemAlloc",
"(",
"session",
",",
"size",
",",
"byref",
"(",
"offset",
")",
")",
"return",
"offset",
",",
"ret"
] |
Calculate posterior probabilities of test data . | def predict_proba ( self , X ) : Phi = metrics . pairwise . rbf_kernel ( X , self . kernel_pos , self . gamma ) N = X . shape [ 0 ] predictions = np . zeros ( ( N , self . n_classes + 1 ) ) for i in range ( N ) : post = np . zeros ( self . n_classes ) for c in range ( self . n_classes ) : post [ c ] = max ( 0 , np . dot ( self . theta [ self . classes [ c ] ] . T , Phi [ i , : ] ) ) post [ c ] = min ( post [ c ] , 1. ) predictions [ i , : - 1 ] = post predictions [ i , - 1 ] = max ( 0 , 1 - sum ( post ) ) return predictions | 1,019 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L194-L223 | [
"def",
"write",
"(",
"self",
",",
"symbol",
",",
"data",
")",
":",
"# get the full set of date ranges that we have",
"cursor",
"=",
"self",
".",
"_collection",
".",
"find",
"(",
")",
"for",
"res",
"in",
"cursor",
":",
"library",
"=",
"self",
".",
"_arctic_lib",
".",
"arctic",
"[",
"res",
"[",
"'library_name'",
"]",
"]",
"dslice",
"=",
"self",
".",
"_slice",
"(",
"data",
",",
"to_dt",
"(",
"res",
"[",
"'start'",
"]",
",",
"mktz",
"(",
"'UTC'",
")",
")",
",",
"to_dt",
"(",
"res",
"[",
"'end'",
"]",
",",
"mktz",
"(",
"'UTC'",
")",
")",
")",
"if",
"len",
"(",
"dslice",
")",
"!=",
"0",
":",
"library",
".",
"write",
"(",
"symbol",
",",
"dslice",
")"
] |
Generate an inlier score for each test data example . | def decision_function ( self , X ) : predictions = self . predict_proba ( X ) out = np . zeros ( ( predictions . shape [ 0 ] , 1 ) ) out [ : , 0 ] = 1 - predictions [ : , - 1 ] return out | 1,020 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L225-L245 | [
"def",
"is_vimball",
"(",
"fd",
")",
":",
"fd",
".",
"seek",
"(",
"0",
")",
"try",
":",
"header",
"=",
"fd",
".",
"readline",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"# binary files will raise exceptions when trying to decode raw bytes to",
"# str objects in our readline() wrapper",
"return",
"False",
"if",
"re",
".",
"match",
"(",
"'^\" Vimball Archiver'",
",",
"header",
")",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"False"
] |
Calculate accuracy score . | def score ( self , X , y ) : predictions = self . predict ( X ) true = 0.0 total = 0.0 for i in range ( len ( predictions ) ) : total += 1 if predictions [ i ] == y [ i ] : true += 1 return true / total | 1,021 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L247-L261 | [
"def",
"keep_sources",
"(",
"self",
",",
"keep",
")",
":",
"if",
"self",
".",
"unmixing_",
"is",
"None",
"or",
"self",
".",
"mixing_",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"No sources available (run do_mvarica first)\"",
")",
"n_sources",
"=",
"self",
".",
"mixing_",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"remove_sources",
"(",
"np",
".",
"setdiff1d",
"(",
"np",
".",
"arange",
"(",
"n_sources",
")",
",",
"np",
".",
"array",
"(",
"keep",
")",
")",
")",
"return",
"self"
] |
Calculate class probabilities for a sequence of data . | def predict_sequence ( self , X , A , pi , inference = 'smoothing' ) : obsll = self . predict_proba ( X ) T , S = obsll . shape alpha = np . zeros ( ( T , S ) ) alpha [ 0 , : ] = pi for t in range ( 1 , T ) : alpha [ t , : ] = np . dot ( alpha [ t - 1 , : ] , A ) for s in range ( S ) : alpha [ t , s ] *= obsll [ t , s ] alpha [ t , : ] = alpha [ t , : ] / sum ( alpha [ t , : ] ) if inference == 'filtering' : return alpha else : beta = np . zeros ( ( T , S ) ) gamma = np . zeros ( ( T , S ) ) beta [ T - 1 , : ] = np . ones ( S ) for t in range ( T - 2 , - 1 , - 1 ) : for i in range ( S ) : for j in range ( S ) : beta [ t , i ] += A [ i , j ] * obsll [ t + 1 , j ] * beta [ t + 1 , j ] beta [ t , : ] = beta [ t , : ] / sum ( beta [ t , : ] ) for t in range ( T ) : gamma [ t , : ] = alpha [ t , : ] * beta [ t , : ] gamma [ t , : ] = gamma [ t , : ] / sum ( gamma [ t , : ] ) return gamma | 1,022 | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L263-L310 | [
"def",
"clear_intersection",
"(",
"self",
",",
"other_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"other_dict",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"globals",
"and",
"self",
".",
"globals",
"[",
"key",
"]",
"is",
"value",
":",
"del",
"self",
".",
"globals",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"locals",
"and",
"self",
".",
"locals",
"[",
"key",
"]",
"is",
"value",
":",
"del",
"self",
".",
"locals",
"[",
"key",
"]",
"return",
"self"
] |
This is used only if websocket fails | def toggle_sensor ( request , sensorname ) : if service . read_only : service . logger . warning ( "Could not perform operation: read only mode enabled" ) raise Http404 source = request . GET . get ( 'source' , 'main' ) sensor = service . system . namespace [ sensorname ] sensor . status = not sensor . status service . system . flush ( ) return HttpResponseRedirect ( reverse ( source ) ) | 1,023 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/webui/djangoapp/views.py#L279-L290 | [
"def",
"ParseFileObject",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"regf_file",
"=",
"pyregf",
".",
"file",
"(",
")",
"# pylint: disable=no-member",
"try",
":",
"regf_file",
".",
"open_file_object",
"(",
"file_object",
")",
"except",
"IOError",
":",
"# The error is currently ignored -> see TODO above related to the",
"# fixing of handling multiple parsers for the same file format.",
"return",
"root_key",
"=",
"regf_file",
".",
"get_root_key",
"(",
")",
"if",
"root_key",
"is",
"None",
":",
"regf_file",
".",
"close",
"(",
")",
"return",
"root_file_key",
"=",
"root_key",
".",
"get_sub_key_by_path",
"(",
"self",
".",
"_AMCACHE_ROOT_FILE_KEY",
")",
"if",
"root_file_key",
"is",
"None",
":",
"regf_file",
".",
"close",
"(",
")",
"return",
"for",
"volume_key",
"in",
"root_file_key",
".",
"sub_keys",
":",
"for",
"am_entry",
"in",
"volume_key",
".",
"sub_keys",
":",
"self",
".",
"_ProcessAMCacheFileKey",
"(",
"am_entry",
",",
"parser_mediator",
")",
"root_program_key",
"=",
"root_key",
".",
"get_sub_key_by_path",
"(",
"self",
".",
"_AMCACHE_ROOT_PROGRAM_KEY",
")",
"if",
"root_program_key",
"is",
"None",
":",
"regf_file",
".",
"close",
"(",
")",
"return",
"for",
"am_entry",
"in",
"root_program_key",
".",
"sub_keys",
":",
"self",
".",
"_ProcessAMCacheProgramKey",
"(",
"am_entry",
",",
"parser_mediator",
")",
"regf_file",
".",
"close",
"(",
")"
] |
For manual shortcut links to perform toggle actions | def toggle_value ( request , name ) : obj = service . system . namespace . get ( name , None ) if not obj or service . read_only : raise Http404 new_status = obj . status = not obj . status if service . redirect_from_setters : return HttpResponseRedirect ( reverse ( 'set_ready' , args = ( name , new_status ) ) ) else : return set_ready ( request , name , new_status ) | 1,024 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/webui/djangoapp/views.py#L294-L305 | [
"def",
"_read_footer",
"(",
"file_obj",
")",
":",
"footer_size",
"=",
"_get_footer_size",
"(",
"file_obj",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"debug",
"(",
"\"Footer size in bytes: %s\"",
",",
"footer_size",
")",
"file_obj",
".",
"seek",
"(",
"-",
"(",
"8",
"+",
"footer_size",
")",
",",
"2",
")",
"# seek to beginning of footer",
"tin",
"=",
"TFileTransport",
"(",
"file_obj",
")",
"pin",
"=",
"TCompactProtocolFactory",
"(",
")",
".",
"get_protocol",
"(",
"tin",
")",
"fmd",
"=",
"parquet_thrift",
".",
"FileMetaData",
"(",
")",
"fmd",
".",
"read",
"(",
"pin",
")",
"return",
"fmd"
] |
For manual shortcut links to perform set value actions | def set_value ( request , name , value ) : obj = service . system . namespace . get ( name , None ) if not obj or service . read_only : raise Http404 obj . status = value if service . redirect_from_setters : return HttpResponseRedirect ( reverse ( 'set_ready' , args = ( name , value ) ) ) else : return set_ready ( request , name , value ) | 1,025 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/webui/djangoapp/views.py#L309-L320 | [
"def",
"_read_footer",
"(",
"file_obj",
")",
":",
"footer_size",
"=",
"_get_footer_size",
"(",
"file_obj",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"debug",
"(",
"\"Footer size in bytes: %s\"",
",",
"footer_size",
")",
"file_obj",
".",
"seek",
"(",
"-",
"(",
"8",
"+",
"footer_size",
")",
",",
"2",
")",
"# seek to beginning of footer",
"tin",
"=",
"TFileTransport",
"(",
"file_obj",
")",
"pin",
"=",
"TCompactProtocolFactory",
"(",
")",
".",
"get_protocol",
"(",
"tin",
")",
"fmd",
"=",
"parquet_thrift",
".",
"FileMetaData",
"(",
")",
"fmd",
".",
"read",
"(",
"pin",
")",
"return",
"fmd"
] |
A read - only property that gives the object type as string ; sensor actuator program other . Used by WEB interface templates . | def object_type ( self ) : from . statusobject import AbstractSensor , AbstractActuator from . program import Program if isinstance ( self , AbstractSensor ) : return 'sensor' elif isinstance ( self , AbstractActuator ) : return 'actuator' elif isinstance ( self , Program ) : return 'program' else : return 'other' | 1,026 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L115-L130 | [
"async",
"def",
"get_checkpoint_async",
"(",
"self",
",",
"partition_id",
")",
":",
"lease",
"=",
"await",
"self",
".",
"get_lease_async",
"(",
"partition_id",
")",
"checkpoint",
"=",
"None",
"if",
"lease",
":",
"if",
"lease",
".",
"offset",
":",
"checkpoint",
"=",
"Checkpoint",
"(",
"partition_id",
",",
"lease",
".",
"offset",
",",
"lease",
".",
"sequence_number",
")",
"return",
"checkpoint"
] |
Get information about this object as a dictionary . Used by WebSocket interface to pass some relevant information to client applications . | def get_as_datadict ( self ) : return dict ( type = self . __class__ . __name__ , tags = list ( self . tags ) ) | 1,027 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L156-L161 | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"hosted_zone",
"=",
"route53_backend",
".",
"get_hosted_zone_by_name",
"(",
"self",
".",
"hosted_zone_name",
")",
"if",
"not",
"hosted_zone",
":",
"hosted_zone",
"=",
"route53_backend",
".",
"get_hosted_zone",
"(",
"self",
".",
"hosted_zone_id",
")",
"hosted_zone",
".",
"delete_rrset_by_name",
"(",
"self",
".",
"name",
")"
] |
Set system attribute and do some initialization . Used by System . | def setup_system ( self , system , name_from_system = '' , * * kwargs ) : if not self . system : self . system = system name , traits = self . _passed_arguments new_name = self . system . get_unique_name ( self , name , name_from_system ) if not self in self . system . reverse : self . name = new_name self . logger = self . system . logger . getChild ( '%s.%s' % ( self . __class__ . __name__ , self . name ) ) self . logger . setLevel ( self . log_level ) if name is None and 'name' in traits : # Only __setstate__ sets name to None. Default is ''. del traits [ 'name' ] for cname in self . callables : if cname in traits : c = self . _postponed_callables [ cname ] = traits . pop ( cname ) c . setup_callable_system ( self . system ) getattr ( self , cname ) . setup_callable_system ( self . system ) if not self . traits_inited ( ) : super ( ) . __init__ ( * * traits ) self . name_changed_event = True self . setup ( ) | 1,028 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L169-L194 | [
"def",
"_bsecurate_cli_compare_basis_files",
"(",
"args",
")",
":",
"ret",
"=",
"curate",
".",
"compare_basis_files",
"(",
"args",
".",
"file1",
",",
"args",
".",
"file2",
",",
"args",
".",
"readfmt1",
",",
"args",
".",
"readfmt2",
",",
"args",
".",
"uncontract_general",
")",
"if",
"ret",
":",
"return",
"\"No difference found\"",
"else",
":",
"return",
"\"DIFFERENCES FOUND. SEE ABOVE\""
] |
Setup Callable attributes that belong to this object . | def setup_callables ( self ) : defaults = self . get_default_callables ( ) for key , value in list ( defaults . items ( ) ) : self . _postponed_callables . setdefault ( key , value ) for key in self . callables : value = self . _postponed_callables . pop ( key ) value . setup_callable_system ( self . system , init = True ) setattr ( self , key , value ) | 1,029 | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L196-L206 | [
"def",
"update_thumbnail",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"position",
"=",
"7.0",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
"\"Updating video thumbnail.\"",
")",
"try",
":",
"response",
"=",
"jwplatform_client",
".",
"videos",
".",
"thumbnails",
".",
"update",
"(",
"video_key",
"=",
"video_key",
",",
"position",
"=",
"position",
",",
"# Parameter which specifies seconds into video to extract thumbnail from.",
"*",
"*",
"kwargs",
")",
"except",
"jwplatform",
".",
"errors",
".",
"JWPlatformError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Encountered an error updating thumbnail.\\n{}\"",
".",
"format",
"(",
"e",
")",
")",
"sys",
".",
"exit",
"(",
"e",
".",
"message",
")",
"return",
"response"
] |
Function to acqure the keyfile | def grab_keyfile ( cert_url ) : key_cache = caches [ getattr ( settings , 'BOUNCY_KEY_CACHE' , 'default' ) ] pemfile = key_cache . get ( cert_url ) if not pemfile : response = urlopen ( cert_url ) pemfile = response . read ( ) # Extract the first certificate in the file and confirm it's a valid # PEM certificate certificates = pem . parse ( smart_bytes ( pemfile ) ) # A proper certificate file will contain 1 certificate if len ( certificates ) != 1 : logger . error ( 'Invalid Certificate File: URL %s' , cert_url ) raise ValueError ( 'Invalid Certificate File' ) key_cache . set ( cert_url , pemfile ) return pemfile | 1,030 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L67-L91 | [
"def",
"block",
"(",
"seed",
")",
":",
"num",
"=",
"SAMPLE_RATE",
"*",
"BLOCK_SIZE",
"rng",
"=",
"RandomState",
"(",
"seed",
"%",
"2",
"**",
"32",
")",
"variance",
"=",
"SAMPLE_RATE",
"/",
"2",
"return",
"rng",
".",
"normal",
"(",
"size",
"=",
"num",
",",
"scale",
"=",
"variance",
"**",
"0.5",
")"
] |
Function to verify notification came from a trusted source | def verify_notification ( data ) : pemfile = grab_keyfile ( data [ 'SigningCertURL' ] ) cert = crypto . load_certificate ( crypto . FILETYPE_PEM , pemfile ) signature = base64 . decodestring ( six . b ( data [ 'Signature' ] ) ) if data [ 'Type' ] == "Notification" : hash_format = NOTIFICATION_HASH_FORMAT else : hash_format = SUBSCRIPTION_HASH_FORMAT try : crypto . verify ( cert , signature , six . b ( hash_format . format ( * * data ) ) , 'sha1' ) except crypto . Error : return False return True | 1,031 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L94-L114 | [
"def",
"pop",
"(",
"self",
",",
"symbol",
")",
":",
"last_metadata",
"=",
"self",
".",
"find_one",
"(",
"{",
"'symbol'",
":",
"symbol",
"}",
",",
"sort",
"=",
"[",
"(",
"'start_time'",
",",
"pymongo",
".",
"DESCENDING",
")",
"]",
")",
"if",
"last_metadata",
"is",
"None",
":",
"raise",
"NoDataFoundException",
"(",
"'No metadata found for symbol {}'",
".",
"format",
"(",
"symbol",
")",
")",
"self",
".",
"find_one_and_delete",
"(",
"{",
"'symbol'",
":",
"symbol",
"}",
",",
"sort",
"=",
"[",
"(",
"'start_time'",
",",
"pymongo",
".",
"DESCENDING",
")",
"]",
")",
"mongo_retry",
"(",
"self",
".",
"find_one_and_update",
")",
"(",
"{",
"'symbol'",
":",
"symbol",
"}",
",",
"{",
"'$unset'",
":",
"{",
"'end_time'",
":",
"''",
"}",
"}",
",",
"sort",
"=",
"[",
"(",
"'start_time'",
",",
"pymongo",
".",
"DESCENDING",
")",
"]",
")",
"return",
"last_metadata"
] |
Function to approve a SNS subscription with Amazon | def approve_subscription ( data ) : url = data [ 'SubscribeURL' ] domain = urlparse ( url ) . netloc pattern = getattr ( settings , 'BOUNCY_SUBSCRIBE_DOMAIN_REGEX' , r"sns.[a-z0-9\-]+.amazonaws.com$" ) if not re . search ( pattern , domain ) : logger . error ( 'Invalid Subscription Domain %s' , url ) return HttpResponseBadRequest ( 'Improper Subscription Domain' ) try : result = urlopen ( url ) . read ( ) logger . info ( 'Subscription Request Sent %s' , url ) except urllib . HTTPError as error : result = error . read ( ) logger . warning ( 'HTTP Error Creating Subscription %s' , str ( result ) ) signals . subscription . send ( sender = 'bouncy_approve_subscription' , result = result , notification = data ) # Return a 200 Status Code return HttpResponse ( six . u ( result ) ) | 1,032 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L117-L150 | [
"def",
"connect",
"(",
"self",
",",
"port",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"self",
".",
"_driver",
".",
"connect",
"(",
"port",
"=",
"port",
")",
"self",
".",
"fw_version",
"=",
"self",
".",
"_driver",
".",
"get_fw_version",
"(",
")",
"# the below call to `cache_instrument_models` is relied upon by",
"# `Session._simulate()`, which calls `robot.connect()` after exec'ing a",
"# protocol. That protocol could very well have different pipettes than",
"# what are physically attached to the robot",
"self",
".",
"cache_instrument_models",
"(",
")"
] |
Return a datetime from the Amazon - provided datetime string | def clean_time ( time_string ) : # Get a timezone-aware datetime object from the string time = dateutil . parser . parse ( time_string ) if not settings . USE_TZ : # If timezone support is not active, convert the time to UTC and # remove the timezone field time = time . astimezone ( timezone . utc ) . replace ( tzinfo = None ) return time | 1,033 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L153-L161 | [
"def",
"remove",
"(",
"self",
")",
":",
"for",
"cgroup",
"in",
"self",
".",
"paths",
":",
"remove_cgroup",
"(",
"cgroup",
")",
"del",
"self",
".",
"paths",
"del",
"self",
".",
"per_subsystem"
] |
Validates fields are valid and maps pseudo - fields to actual fields for a given model class . | def parse_selectors ( model , fields = None , exclude = None , key_map = None , * * options ) : fields = fields or DEFAULT_SELECTORS exclude = exclude or ( ) key_map = key_map or { } validated = [ ] for alias in fields : # Map the output key name to the actual field/accessor name for # the model actual = key_map . get ( alias , alias ) # Validate the field exists cleaned = resolver . get_field ( model , actual ) if cleaned is None : raise AttributeError ( 'The "{0}" attribute could not be found ' 'on the model "{1}"' . format ( actual , model ) ) # Mapped value, so use the original name listed in `fields` if type ( cleaned ) is list : validated . extend ( cleaned ) elif alias != actual : validated . append ( alias ) else : validated . append ( cleaned ) return tuple ( [ x for x in validated if x not in exclude ] ) | 1,034 | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/utils.py#L96-L125 | [
"def",
"output_best_scores",
"(",
"self",
",",
"best_epoch_str",
":",
"str",
")",
"->",
"None",
":",
"BEST_SCORES_FILENAME",
"=",
"\"best_scores.txt\"",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"exp_dir",
",",
"BEST_SCORES_FILENAME",
")",
",",
"\"w\"",
",",
"encoding",
"=",
"ENCODING",
")",
"as",
"best_f",
":",
"print",
"(",
"best_epoch_str",
",",
"file",
"=",
"best_f",
",",
"flush",
"=",
"True",
")"
] |
Return the names of all locally defined fields on the model class . | def _get_local_fields ( self , model ) : local = [ f for f in model . _meta . fields ] m2m = [ f for f in model . _meta . many_to_many ] fields = local + m2m names = tuple ( [ x . name for x in fields ] ) return { ':local' : dict ( list ( zip ( names , fields ) ) ) , } | 1,035 | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/utils.py#L42-L51 | [
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Returns the names of all related fields for model class . | def _get_related_fields ( self , model ) : reverse_fk = self . _get_all_related_objects ( model ) reverse_m2m = self . _get_all_related_many_to_many_objects ( model ) fields = tuple ( reverse_fk + reverse_m2m ) names = tuple ( [ x . get_accessor_name ( ) for x in fields ] ) return { ':related' : dict ( list ( zip ( names , fields ) ) ) , } | 1,036 | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/utils.py#L53-L63 | [
"def",
"_augment_exception",
"(",
"exc",
",",
"version",
",",
"arch",
"=",
"''",
")",
":",
"# Error if MSVC++ directory not found or environment not set",
"message",
"=",
"exc",
".",
"args",
"[",
"0",
"]",
"if",
"\"vcvarsall\"",
"in",
"message",
".",
"lower",
"(",
")",
"or",
"\"visual c\"",
"in",
"message",
".",
"lower",
"(",
")",
":",
"# Special error message if MSVC++ not installed",
"tmpl",
"=",
"'Microsoft Visual C++ {version:0.1f} is required.'",
"message",
"=",
"tmpl",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"msdownload",
"=",
"'www.microsoft.com/download/details.aspx?id=%d'",
"if",
"version",
"==",
"9.0",
":",
"if",
"arch",
".",
"lower",
"(",
")",
".",
"find",
"(",
"'ia64'",
")",
">",
"-",
"1",
":",
"# For VC++ 9.0, if IA64 support is needed, redirect user",
"# to Windows SDK 7.0",
"message",
"+=",
"' Get it with \"Microsoft Windows SDK 7.0\": '",
"message",
"+=",
"msdownload",
"%",
"3138",
"else",
":",
"# For VC++ 9.0 redirect user to Vc++ for Python 2.7 :",
"# This redirection link is maintained by Microsoft.",
"# Contact [email protected] if it needs updating.",
"message",
"+=",
"' Get it from http://aka.ms/vcpython27'",
"elif",
"version",
"==",
"10.0",
":",
"# For VC++ 10.0 Redirect user to Windows SDK 7.1",
"message",
"+=",
"' Get it with \"Microsoft Windows SDK 7.1\": '",
"message",
"+=",
"msdownload",
"%",
"8279",
"elif",
"version",
">=",
"14.0",
":",
"# For VC++ 14.0 Redirect user to Visual C++ Build Tools",
"message",
"+=",
"(",
"' Get it with \"Microsoft Visual C++ Build Tools\": '",
"r'https://visualstudio.microsoft.com/downloads/'",
")",
"exc",
".",
"args",
"=",
"(",
"message",
",",
")"
] |
Return HTML version of the table | def to_html ( self , index = False , escape = False , header = True , collapse_table = True , class_outer = "table_outer" , * * kargs ) : _buffer = { } for k , v in self . pd_options . items ( ) : # save the current option _buffer [ k ] = pd . get_option ( k ) # set with user value pd . set_option ( k , v ) # class sortable is to use the sorttable javascript # note that the class has one t and the javascript library has 2 # as in the original version of sorttable.js table = self . df . to_html ( escape = escape , header = header , index = index , classes = 'sortable' , * * kargs ) # get back to default options for k , v in _buffer . items ( ) : pd . set_option ( k , v ) # We wrap the table in a dedicated class/div nammed table_scroller # that users must define. return '<div class="%s">' % class_outer + table + "</div>" | 1,037 | https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/htmltable.py#L75-L108 | [
"def",
"Find",
"(",
"cls",
",",
"setting_matcher",
",",
"port_path",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"timeout_ms",
"=",
"None",
")",
":",
"if",
"port_path",
":",
"device_matcher",
"=",
"cls",
".",
"PortPathMatcher",
"(",
"port_path",
")",
"usb_info",
"=",
"port_path",
"elif",
"serial",
":",
"device_matcher",
"=",
"cls",
".",
"SerialMatcher",
"(",
"serial",
")",
"usb_info",
"=",
"serial",
"else",
":",
"device_matcher",
"=",
"None",
"usb_info",
"=",
"'first'",
"return",
"cls",
".",
"FindFirst",
"(",
"setting_matcher",
",",
"device_matcher",
",",
"usb_info",
"=",
"usb_info",
",",
"timeout_ms",
"=",
"timeout_ms",
")"
] |
Change column content into HTML paragraph with background color | def add_bgcolor ( self , colname , cmap = 'copper' , mode = 'absmax' , threshold = 2 ) : try : # if a cmap is provided, it may be just a known cmap name cmap = cmap_builder ( cmap ) except : pass data = self . df [ colname ] . values if len ( data ) == 0 : return if mode == 'clip' : data = [ min ( x , threshold ) / float ( threshold ) for x in data ] elif mode == 'absmax' : m = abs ( data . min ( ) ) M = abs ( data . max ( ) ) M = max ( [ m , M ] ) if M != 0 : data = ( data / M + 1 ) / 2. elif mode == 'max' : if data . max ( ) != 0 : data = data / float ( data . max ( ) ) # the expected RGB values for a given data point rgbcolors = [ cmap ( x ) [ 0 : 3 ] for x in data ] hexcolors = [ rgb2hex ( * x , normalised = True ) for x in rgbcolors ] # need to read original data again data = self . df [ colname ] . values # need to set precision since this is going to be a text not a number # so pandas will not use the precision for those cases: def prec ( x ) : try : # this may fail if for instance x is nan or inf x = easydev . precision ( x , self . pd_options [ 'precision' ] ) return x except : return x data = [ prec ( x ) for x in data ] html_formatter = '<p style="background-color:{0}">{1}</p>' self . df [ colname ] = [ html_formatter . format ( x , y ) for x , y in zip ( hexcolors , data ) ] | 1,038 | https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/htmltable.py#L110-L180 | [
"def",
"_count_devices",
"(",
"self",
")",
":",
"number_of_devices",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetRawInputDeviceList",
"(",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_int",
")",
"(",
")",
",",
"ctypes",
".",
"byref",
"(",
"number_of_devices",
")",
",",
"ctypes",
".",
"sizeof",
"(",
"RawInputDeviceList",
")",
")",
"==",
"-",
"1",
":",
"warn",
"(",
"\"Call to GetRawInputDeviceList was unsuccessful.\"",
"\"We have no idea if a mouse or keyboard is attached.\"",
",",
"RuntimeWarning",
")",
"return",
"devices_found",
"=",
"(",
"RawInputDeviceList",
"*",
"number_of_devices",
".",
"value",
")",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetRawInputDeviceList",
"(",
"devices_found",
",",
"ctypes",
".",
"byref",
"(",
"number_of_devices",
")",
",",
"ctypes",
".",
"sizeof",
"(",
"RawInputDeviceList",
")",
")",
"==",
"-",
"1",
":",
"warn",
"(",
"\"Call to GetRawInputDeviceList was unsuccessful.\"",
"\"We have no idea if a mouse or keyboard is attached.\"",
",",
"RuntimeWarning",
")",
"return",
"for",
"device",
"in",
"devices_found",
":",
"if",
"device",
".",
"dwType",
"==",
"0",
":",
"self",
".",
"_raw_device_counts",
"[",
"'mice'",
"]",
"+=",
"1",
"elif",
"device",
".",
"dwType",
"==",
"1",
":",
"self",
".",
"_raw_device_counts",
"[",
"'keyboards'",
"]",
"+=",
"1",
"elif",
"device",
".",
"dwType",
"==",
"2",
":",
"self",
".",
"_raw_device_counts",
"[",
"'otherhid'",
"]",
"+=",
"1",
"else",
":",
"self",
".",
"_raw_device_counts",
"[",
"'unknown'",
"]",
"+=",
"1"
] |
Get object currently tracked and add a button to get back to it | def changelist_view ( self , request , extra_context = None ) : extra_context = extra_context or { } if 'object' in request . GET . keys ( ) : value = request . GET [ 'object' ] . split ( ':' ) content_type = get_object_or_404 ( ContentType , id = value [ 0 ] , ) tracked_object = get_object_or_404 ( content_type . model_class ( ) , id = value [ 1 ] , ) extra_context [ 'tracked_object' ] = tracked_object extra_context [ 'tracked_object_opts' ] = tracked_object . _meta return super ( TrackingEventAdmin , self ) . changelist_view ( request , extra_context ) | 1,039 | https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/admin.py#L118-L134 | [
"def",
"_validate_slices_form_uniform_grid",
"(",
"slice_datasets",
")",
":",
"invariant_properties",
"=",
"[",
"'Modality'",
",",
"'SOPClassUID'",
",",
"'SeriesInstanceUID'",
",",
"'Rows'",
",",
"'Columns'",
",",
"'PixelSpacing'",
",",
"'PixelRepresentation'",
",",
"'BitsAllocated'",
",",
"'BitsStored'",
",",
"'HighBit'",
",",
"]",
"for",
"property_name",
"in",
"invariant_properties",
":",
"_slice_attribute_equal",
"(",
"slice_datasets",
",",
"property_name",
")",
"_validate_image_orientation",
"(",
"slice_datasets",
"[",
"0",
"]",
".",
"ImageOrientationPatient",
")",
"_slice_ndarray_attribute_almost_equal",
"(",
"slice_datasets",
",",
"'ImageOrientationPatient'",
",",
"1e-5",
")",
"slice_positions",
"=",
"_slice_positions",
"(",
"slice_datasets",
")",
"_check_for_missing_slices",
"(",
"slice_positions",
")"
] |
Get a list of configs . | def list ( self , filter = None , type = None , sort = None , limit = None , page = None ) : # pylint: disable=redefined-builtin schema = self . LIST_SCHEMA resp = self . service . list ( self . base , filter , type , sort , limit , page ) cs , l = self . service . decode ( schema , resp , many = True , links = True ) return Page ( cs , l ) | 1,040 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L187-L200 | [
"def",
"start",
"(",
"self",
",",
"driver",
"=",
"None",
",",
"device",
"=",
"None",
",",
"midi_driver",
"=",
"None",
")",
":",
"if",
"driver",
"is",
"not",
"None",
":",
"assert",
"(",
"driver",
"in",
"[",
"'alsa'",
",",
"'oss'",
",",
"'jack'",
",",
"'portaudio'",
",",
"'sndmgr'",
",",
"'coreaudio'",
",",
"'Direct Sound'",
",",
"'pulseaudio'",
"]",
")",
"fluid_settings_setstr",
"(",
"self",
".",
"settings",
",",
"b'audio.driver'",
",",
"driver",
".",
"encode",
"(",
")",
")",
"if",
"device",
"is",
"not",
"None",
":",
"fluid_settings_setstr",
"(",
"self",
".",
"settings",
",",
"str",
"(",
"'audio.%s.device'",
"%",
"(",
"driver",
")",
")",
".",
"encode",
"(",
")",
",",
"device",
".",
"encode",
"(",
")",
")",
"self",
".",
"audio_driver",
"=",
"new_fluid_audio_driver",
"(",
"self",
".",
"settings",
",",
"self",
".",
"synth",
")",
"if",
"midi_driver",
"is",
"not",
"None",
":",
"assert",
"(",
"midi_driver",
"in",
"[",
"'alsa_seq'",
",",
"'alsa_raw'",
",",
"'oss'",
",",
"'winmidi'",
",",
"'midishare'",
",",
"'coremidi'",
"]",
")",
"fluid_settings_setstr",
"(",
"self",
".",
"settings",
",",
"b'midi.driver'",
",",
"midi_driver",
".",
"encode",
"(",
")",
")",
"self",
".",
"router",
"=",
"new_fluid_midi_router",
"(",
"self",
".",
"settings",
",",
"fluid_synth_handle_midi_event",
",",
"self",
".",
"synth",
")",
"fluid_synth_set_midi_router",
"(",
"self",
".",
"synth",
",",
"self",
".",
"router",
")",
"self",
".",
"midi_driver",
"=",
"new_fluid_midi_driver",
"(",
"self",
".",
"settings",
",",
"fluid_midi_router_handle_midi_event",
",",
"self",
".",
"router",
")"
] |
Get a list of configs . Whereas list fetches a single page of configs according to its limit and page arguments iter_list returns all configs by internally making successive calls to list . | def iter_list ( self , * args , * * kwargs ) : return self . service . iter_list ( self . list , * args , * * kwargs ) | 1,041 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L202-L213 | [
"def",
"geo_max_distance",
"(",
"left",
",",
"right",
")",
":",
"op",
"=",
"ops",
".",
"GeoMaxDistance",
"(",
"left",
",",
"right",
")",
"return",
"op",
".",
"to_expr",
"(",
")"
] |
Get a config as plaintext . | def get_plaintext ( self , id ) : # pylint: disable=invalid-name,redefined-builtin return self . service . get_id ( self . base , id , params = { 'format' : 'text' } ) . text | 1,042 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L233-L239 | [
"def",
"wave_infochunk",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file",
":",
"if",
"file",
".",
"read",
"(",
"4",
")",
"!=",
"b\"RIFF\"",
":",
"return",
"None",
"data_size",
"=",
"file",
".",
"read",
"(",
"4",
")",
"# container size",
"if",
"file",
".",
"read",
"(",
"4",
")",
"!=",
"b\"WAVE\"",
":",
"return",
"None",
"while",
"True",
":",
"chunkid",
"=",
"file",
".",
"read",
"(",
"4",
")",
"sizebuf",
"=",
"file",
".",
"read",
"(",
"4",
")",
"if",
"len",
"(",
"sizebuf",
")",
"<",
"4",
"or",
"len",
"(",
"chunkid",
")",
"<",
"4",
":",
"return",
"None",
"size",
"=",
"struct",
".",
"unpack",
"(",
"b'<L'",
",",
"sizebuf",
")",
"[",
"0",
"]",
"if",
"chunkid",
"[",
"0",
":",
"3",
"]",
"!=",
"b\"fmt\"",
":",
"if",
"size",
"%",
"2",
"==",
"1",
":",
"seek",
"=",
"size",
"+",
"1",
"else",
":",
"seek",
"=",
"size",
"file",
".",
"seek",
"(",
"size",
",",
"1",
")",
"else",
":",
"return",
"bytearray",
"(",
"b\"RIFF\"",
"+",
"data_size",
"+",
"b\"WAVE\"",
"+",
"chunkid",
"+",
"sizebuf",
"+",
"file",
".",
"read",
"(",
"size",
")",
")"
] |
Create a new config . | def create ( self , resource ) : schema = self . CREATE_SCHEMA json = self . service . encode ( schema , resource ) schema = self . GET_SCHEMA resp = self . service . create ( self . base , json ) return self . service . decode ( schema , resp ) | 1,043 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L253-L265 | [
"def",
"Nu_vertical_cylinder",
"(",
"Pr",
",",
"Gr",
",",
"L",
"=",
"None",
",",
"D",
"=",
"None",
",",
"Method",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"for",
"key",
",",
"values",
"in",
"vertical_cylinder_correlations",
".",
"items",
"(",
")",
":",
"if",
"values",
"[",
"4",
"]",
"or",
"all",
"(",
"(",
"L",
",",
"D",
")",
")",
":",
"methods",
".",
"append",
"(",
"key",
")",
"if",
"'Popiel & Churchill'",
"in",
"methods",
":",
"methods",
".",
"remove",
"(",
"'Popiel & Churchill'",
")",
"methods",
".",
"insert",
"(",
"0",
",",
"'Popiel & Churchill'",
")",
"elif",
"'McAdams, Weiss & Saunders'",
"in",
"methods",
":",
"methods",
".",
"remove",
"(",
"'McAdams, Weiss & Saunders'",
")",
"methods",
".",
"insert",
"(",
"0",
",",
"'McAdams, Weiss & Saunders'",
")",
"return",
"methods",
"if",
"AvailableMethods",
":",
"return",
"list_methods",
"(",
")",
"if",
"not",
"Method",
":",
"Method",
"=",
"list_methods",
"(",
")",
"[",
"0",
"]",
"if",
"Method",
"in",
"vertical_cylinder_correlations",
":",
"if",
"vertical_cylinder_correlations",
"[",
"Method",
"]",
"[",
"4",
"]",
":",
"return",
"vertical_cylinder_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"Pr",
"=",
"Pr",
",",
"Gr",
"=",
"Gr",
")",
"else",
":",
"return",
"vertical_cylinder_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"Pr",
"=",
"Pr",
",",
"Gr",
"=",
"Gr",
",",
"L",
"=",
"L",
",",
"D",
"=",
"D",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Correlation name not recognized; see the \"",
"\"documentation for the available options.\"",
")"
] |
Edit a config . | def edit ( self , resource ) : schema = self . EDIT_SCHEMA json = self . service . encode ( schema , resource ) schema = self . GET_SCHEMA resp = self . service . edit ( self . base , resource . id , json ) return self . service . decode ( schema , resp ) | 1,044 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L267-L279 | [
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Edit shares for a config . | def edit_shares ( self , id , user_ids ) : # pylint: disable=invalid-name,redefined-builtin return self . service . edit_shares ( self . base , id , user_ids ) | 1,045 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L296-L303 | [
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Process config contents with cdrouter - cli - check - config . | def check_config ( self , contents ) : schema = CheckConfigSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'check' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp ) | 1,046 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L313-L323 | [
"def",
"namedtuple_storable",
"(",
"namedtuple",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"default_storable",
"(",
"namedtuple",
",",
"namedtuple",
".",
"_fields",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Process config contents with cdrouter - cli - upgrade - config . | def upgrade_config ( self , contents ) : schema = UpgradeConfigSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'upgrade' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp ) | 1,047 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L325-L335 | [
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",
"query",
"[",
"'workspace_members'",
"]",
"=",
"userid",
"workspaces",
"=",
"[",
"IWorkspace",
"(",
"b",
".",
"_unrestrictedGetObject",
"(",
")",
")",
"for",
"b",
"in",
"catalog",
".",
"unrestrictedSearchResults",
"(",
"query",
")",
"]",
"for",
"workspace",
"in",
"workspaces",
":",
"workspace",
".",
"remove_from_team",
"(",
"userid",
")"
] |
Process config contents with cdrouter - cli - print - networks - json . | def get_networks ( self , contents ) : schema = NetworksSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'networks' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp ) | 1,048 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L337-L347 | [
"def",
"readKerningElement",
"(",
"self",
",",
"kerningElement",
",",
"instanceObject",
")",
":",
"kerningLocation",
"=",
"self",
".",
"locationFromElement",
"(",
"kerningElement",
")",
"instanceObject",
".",
"addKerning",
"(",
"kerningLocation",
")"
] |
Bulk copy a set of configs . | def bulk_copy ( self , ids ) : schema = self . GET_SCHEMA return self . service . bulk_copy ( self . base , self . RESOURCE , ids , schema ) | 1,049 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L357-L364 | [
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Bulk edit a set of configs . | def bulk_edit ( self , _fields , ids = None , filter = None , type = None , all = False , testvars = None ) : # pylint: disable=redefined-builtin schema = self . EDIT_SCHEMA _fields = self . service . encode ( schema , _fields , skip_none = True ) return self . service . bulk_edit ( self . base , self . RESOURCE , _fields , ids = ids , filter = filter , type = type , all = all , testvars = testvars ) | 1,050 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L366-L379 | [
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Bulk delete a set of configs . | def bulk_delete ( self , ids = None , filter = None , type = None , all = False ) : # pylint: disable=redefined-builtin return self . service . bulk_delete ( self . base , self . RESOURCE , ids = ids , filter = filter , type = type , all = all ) | 1,051 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L381-L390 | [
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Extract token from response and set it for the user . | def response_token_setter ( remote , resp ) : if resp is None : raise OAuthRejectedRequestError ( 'User rejected request.' , remote , resp ) else : if 'access_token' in resp : return oauth2_token_setter ( remote , resp ) elif 'oauth_token' in resp and 'oauth_token_secret' in resp : return oauth1_token_setter ( remote , resp ) elif 'error' in resp : # Only OAuth2 specifies how to send error messages raise OAuthClientError ( 'Authorization with remote service failed.' , remote , resp , ) raise OAuthResponseError ( 'Bad OAuth authorized request' , remote , resp ) | 1,052 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L69-L92 | [
"def",
"arcball_constrain_to_axis",
"(",
"point",
",",
"axis",
")",
":",
"v",
"=",
"np",
".",
"array",
"(",
"point",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"a",
"=",
"np",
".",
"array",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"v",
"-=",
"a",
"*",
"np",
".",
"dot",
"(",
"a",
",",
"v",
")",
"# on plane",
"n",
"=",
"vector_norm",
"(",
"v",
")",
"if",
"n",
">",
"_EPS",
":",
"if",
"v",
"[",
"2",
"]",
"<",
"0.0",
":",
"np",
".",
"negative",
"(",
"v",
",",
"v",
")",
"v",
"/=",
"n",
"return",
"v",
"if",
"a",
"[",
"2",
"]",
"==",
"1.0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"0.0",
",",
"0.0",
"]",
")",
"return",
"unit_vector",
"(",
"[",
"-",
"a",
"[",
"1",
"]",
",",
"a",
"[",
"0",
"]",
",",
"0.0",
"]",
")"
] |
Set an OAuth1 token . | def oauth1_token_setter ( remote , resp , token_type = '' , extra_data = None ) : return token_setter ( remote , resp [ 'oauth_token' ] , secret = resp [ 'oauth_token_secret' ] , extra_data = extra_data , token_type = token_type , ) | 1,053 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L95-L110 | [
"def",
"fetch_result",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"soup",
".",
"find_all",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'container container-small'",
"}",
")",
"href",
"=",
"None",
"is_match",
"=",
"False",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"results",
")",
"and",
"not",
"is_match",
":",
"result",
"=",
"results",
"[",
"i",
"]",
"anchor",
"=",
"result",
".",
"find",
"(",
"'a'",
",",
"{",
"'rel'",
":",
"'bookmark'",
"}",
")",
"is_match",
"=",
"self",
".",
"_filter_results",
"(",
"result",
",",
"anchor",
")",
"href",
"=",
"anchor",
"[",
"'href'",
"]",
"i",
"+=",
"1",
"try",
":",
"page",
"=",
"get_soup",
"(",
"href",
")",
"except",
"(",
"Exception",
")",
":",
"page",
"=",
"None",
"# Return page if search is successful",
"if",
"href",
"and",
"page",
":",
"return",
"page",
"else",
":",
"raise",
"PageNotFoundError",
"(",
"PAGE_ERROR",
")"
] |
Set an OAuth2 token . | def oauth2_token_setter ( remote , resp , token_type = '' , extra_data = None ) : return token_setter ( remote , resp [ 'access_token' ] , secret = '' , token_type = token_type , extra_data = extra_data , ) | 1,054 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L113-L133 | [
"def",
"Max",
"(",
"a",
",",
"axis",
",",
"keep_dims",
")",
":",
"return",
"np",
".",
"amax",
"(",
"a",
",",
"axis",
"=",
"axis",
"if",
"not",
"isinstance",
"(",
"axis",
",",
"np",
".",
"ndarray",
")",
"else",
"tuple",
"(",
"axis",
")",
",",
"keepdims",
"=",
"keep_dims",
")",
","
] |
Set token for user . | def token_setter ( remote , token , secret = '' , token_type = '' , extra_data = None , user = None ) : session [ token_session_key ( remote . name ) ] = ( token , secret ) user = user or current_user # Save token if user is not anonymous (user exists but can be not active at # this moment) if not user . is_anonymous : uid = user . id cid = remote . consumer_key # Check for already existing token t = RemoteToken . get ( uid , cid , token_type = token_type ) if t : t . update_token ( token , secret ) else : t = RemoteToken . create ( uid , cid , token , secret , token_type = token_type , extra_data = extra_data ) return t return None | 1,055 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L136-L169 | [
"def",
"delete_atom",
"(",
"self",
",",
"*",
"atom_numbers",
")",
":",
"for",
"atom_number",
"in",
"atom_numbers",
":",
"deletion_atom",
"=",
"self",
".",
"atom_by_number",
"(",
"atom_number",
"=",
"atom_number",
")",
"# update atom numbers",
"for",
"atom",
"in",
"self",
".",
"atoms",
":",
"if",
"int",
"(",
"atom",
".",
"atom_number",
")",
">",
"int",
"(",
"atom_number",
")",
":",
"atom",
".",
"atom_number",
"=",
"str",
"(",
"int",
"(",
"atom",
".",
"atom_number",
")",
"-",
"1",
")",
"# find index of a bond to remove and update ctab data dict with new atom numbers",
"for",
"index",
",",
"bond",
"in",
"enumerate",
"(",
"self",
".",
"bonds",
")",
":",
"bond",
".",
"update_atom_numbers",
"(",
")",
"if",
"atom_number",
"in",
"{",
"bond",
".",
"first_atom_number",
",",
"bond",
".",
"second_atom_number",
"}",
":",
"self",
".",
"bonds",
".",
"remove",
"(",
"bond",
")",
"# remove atom from neighbors list",
"for",
"atom",
"in",
"self",
".",
"atoms",
":",
"if",
"deletion_atom",
"in",
"atom",
".",
"neighbors",
":",
"atom",
".",
"neighbors",
".",
"remove",
"(",
"deletion_atom",
")",
"self",
".",
"atoms",
".",
"remove",
"(",
"deletion_atom",
")"
] |
Retrieve OAuth access token . | def token_getter ( remote , token = '' ) : session_key = token_session_key ( remote . name ) if session_key not in session and current_user . is_authenticated : # Fetch key from token store if user is authenticated, and the key # isn't already cached in the session. remote_token = RemoteToken . get ( current_user . get_id ( ) , remote . consumer_key , token_type = token , ) if remote_token is None : return None # Store token and secret in session session [ session_key ] = remote_token . token ( ) return session . get ( session_key , None ) | 1,056 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L172-L199 | [
"def",
"_compute_enlarge_labels",
"(",
"self",
",",
"locator",
",",
"base_index",
")",
":",
"# base_index_type can be pd.Index or pd.DatetimeIndex",
"# depending on user input and pandas behavior",
"# See issue #2264",
"base_index_type",
"=",
"type",
"(",
"base_index",
")",
"locator_as_index",
"=",
"base_index_type",
"(",
"locator",
")",
"nan_labels",
"=",
"locator_as_index",
".",
"difference",
"(",
"base_index",
")",
"common_labels",
"=",
"locator_as_index",
".",
"intersection",
"(",
"base_index",
")",
"if",
"len",
"(",
"common_labels",
")",
"==",
"0",
":",
"raise",
"KeyError",
"(",
"\"None of [{labels}] are in the [{base_index_name}]\"",
".",
"format",
"(",
"labels",
"=",
"list",
"(",
"locator_as_index",
")",
",",
"base_index_name",
"=",
"base_index",
")",
")",
"return",
"nan_labels"
] |
Remove OAuth access tokens from session . | def token_delete ( remote , token = '' ) : session_key = token_session_key ( remote . name ) return session . pop ( session_key , None ) | 1,057 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L202-L211 | [
"def",
"data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"self",
".",
"_enforceDataType",
"(",
"data",
")",
"# Enforce self._data to be a QFont",
"self",
".",
"familyCti",
".",
"data",
"=",
"fontFamilyIndex",
"(",
"self",
".",
"data",
",",
"list",
"(",
"self",
".",
"familyCti",
".",
"iterConfigValues",
")",
")",
"self",
".",
"pointSizeCti",
".",
"data",
"=",
"self",
".",
"data",
".",
"pointSize",
"(",
")",
"self",
".",
"weightCti",
".",
"data",
"=",
"fontWeightIndex",
"(",
"self",
".",
"data",
",",
"list",
"(",
"self",
".",
"weightCti",
".",
"iterConfigValues",
")",
")",
"self",
".",
"italicCti",
".",
"data",
"=",
"self",
".",
"data",
".",
"italic",
"(",
")"
] |
Decorator to handle exceptions . | def oauth_error_handler ( f ) : @ wraps ( f ) def inner ( * args , * * kwargs ) : # OAuthErrors should not happen, so they are not caught here. Hence # they will result in a 500 Internal Server Error which is what we # are interested in. try : return f ( * args , * * kwargs ) except OAuthClientError as e : current_app . logger . warning ( e . message , exc_info = True ) return oauth2_handle_error ( e . remote , e . response , e . code , e . uri , e . description ) except OAuthCERNRejectedAccountError as e : current_app . logger . warning ( e . message , exc_info = True ) flash ( _ ( 'CERN account not allowed.' ) , category = 'danger' ) return redirect ( '/' ) except OAuthRejectedRequestError : flash ( _ ( 'You rejected the authentication request.' ) , category = 'info' ) return redirect ( '/' ) except AlreadyLinkedError : flash ( _ ( 'External service is already linked to another account.' ) , category = 'danger' ) return redirect ( url_for ( 'invenio_oauthclient_settings.index' ) ) return inner | 1,058 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L217-L244 | [
"def",
"download_next_song",
"(",
"self",
",",
"song",
")",
":",
"dl_ydl_opts",
"=",
"dict",
"(",
"ydl_opts",
")",
"dl_ydl_opts",
"[",
"\"progress_hooks\"",
"]",
"=",
"[",
"self",
".",
"ytdl_progress_hook",
"]",
"dl_ydl_opts",
"[",
"\"outtmpl\"",
"]",
"=",
"self",
".",
"output_format",
"# Move the songs from the next cache to the current cache",
"self",
".",
"move_next_cache",
"(",
")",
"self",
".",
"state",
"=",
"'ready'",
"self",
".",
"play_empty",
"(",
")",
"# Download the file and create the stream",
"with",
"youtube_dl",
".",
"YoutubeDL",
"(",
"dl_ydl_opts",
")",
"as",
"ydl",
":",
"try",
":",
"ydl",
".",
"download",
"(",
"[",
"song",
"]",
")",
"except",
"DownloadStreamException",
":",
"# This is a livestream, use the appropriate player",
"future",
"=",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"self",
".",
"create_stream_player",
"(",
"song",
",",
"dl_ydl_opts",
")",
",",
"client",
".",
"loop",
")",
"try",
":",
"future",
".",
"result",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"self",
".",
"vafter_ts",
"(",
")",
"return",
"except",
"PermissionError",
":",
"# File is still in use, it'll get cleared next time",
"pass",
"except",
"youtube_dl",
".",
"utils",
".",
"DownloadError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"e",
")",
"self",
".",
"statuslog",
".",
"error",
"(",
"e",
")",
"self",
".",
"vafter_ts",
"(",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"e",
")",
"self",
".",
"vafter_ts",
"(",
")",
"return"
] |
Store access token in session . | def authorized_default_handler ( resp , remote , * args , * * kwargs ) : response_token_setter ( remote , resp ) db . session . commit ( ) return redirect ( url_for ( 'invenio_oauthclient_settings.index' ) ) | 1,059 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L251-L262 | [
"def",
"update_counts",
"(",
"self",
",",
"prior_counts",
",",
"subtype_counts",
")",
":",
"for",
"source",
",",
"(",
"pos",
",",
"neg",
")",
"in",
"prior_counts",
".",
"items",
"(",
")",
":",
"if",
"source",
"not",
"in",
"self",
".",
"prior_counts",
":",
"self",
".",
"prior_counts",
"[",
"source",
"]",
"=",
"[",
"0",
",",
"0",
"]",
"self",
".",
"prior_counts",
"[",
"source",
"]",
"[",
"0",
"]",
"+=",
"pos",
"self",
".",
"prior_counts",
"[",
"source",
"]",
"[",
"1",
"]",
"+=",
"neg",
"for",
"source",
",",
"subtype_dict",
"in",
"subtype_counts",
".",
"items",
"(",
")",
":",
"if",
"source",
"not",
"in",
"self",
".",
"subtype_counts",
":",
"self",
".",
"subtype_counts",
"[",
"source",
"]",
"=",
"{",
"}",
"for",
"subtype",
",",
"(",
"pos",
",",
"neg",
")",
"in",
"subtype_dict",
".",
"items",
"(",
")",
":",
"if",
"subtype",
"not",
"in",
"self",
".",
"subtype_counts",
"[",
"source",
"]",
":",
"self",
".",
"subtype_counts",
"[",
"source",
"]",
"[",
"subtype",
"]",
"=",
"[",
"0",
",",
"0",
"]",
"self",
".",
"subtype_counts",
"[",
"source",
"]",
"[",
"subtype",
"]",
"[",
"0",
"]",
"+=",
"pos",
"self",
".",
"subtype_counts",
"[",
"source",
"]",
"[",
"subtype",
"]",
"[",
"1",
"]",
"+=",
"neg",
"self",
".",
"update_probs",
"(",
")"
] |
Handle extra signup information . | def signup_handler ( remote , * args , * * kwargs ) : # User already authenticated so move on if current_user . is_authenticated : return redirect ( '/' ) # Retrieve token from session oauth_token = token_getter ( remote ) if not oauth_token : return redirect ( '/' ) session_prefix = token_session_key ( remote . name ) # Test to see if this is coming from on authorized request if not session . get ( session_prefix + '_autoregister' , False ) : return redirect ( url_for ( '.login' , remote_app = remote . name ) ) form = create_registrationform ( request . form ) if form . validate_on_submit ( ) : account_info = session . get ( session_prefix + '_account_info' ) response = session . get ( session_prefix + '_response' ) # Register user user = oauth_register ( form ) if user is None : raise OAuthError ( 'Could not create user.' , remote ) # Remove session key session . pop ( session_prefix + '_autoregister' , None ) # Link account and set session data token = token_setter ( remote , oauth_token [ 0 ] , secret = oauth_token [ 1 ] , user = user ) handlers = current_oauthclient . signup_handlers [ remote . name ] if token is None : raise OAuthError ( 'Could not create token for user.' , remote ) if not token . remote_account . extra_data : account_setup = handlers [ 'setup' ] ( token , response ) account_setup_received . send ( remote , token = token , response = response , account_setup = account_setup ) # Registration has been finished db . session . commit ( ) account_setup_committed . send ( remote , token = token ) else : # Registration has been finished db . session . commit ( ) # Authenticate the user if not oauth_authenticate ( remote . consumer_key , user , require_existing_link = False ) : # Redirect the user after registration (which doesn't include the # activation), waiting for user to confirm his email. return redirect ( url_for ( 'security.login' ) ) # Remove account info from session session . pop ( session_prefix + '_account_info' , None ) session . pop ( session_prefix + '_response' , None ) # Redirect to next next_url = get_session_next_url ( remote . name ) if next_url : return redirect ( next_url ) else : return redirect ( '/' ) # Pre-fill form account_info = session . get ( session_prefix + '_account_info' ) if not form . is_submitted ( ) : form = fill_form ( form , account_info [ 'user' ] ) return render_template ( current_app . config [ 'OAUTHCLIENT_SIGNUP_TEMPLATE' ] , form = form , remote = remote , app_title = current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] [ remote . name ] . get ( 'title' , '' ) , app_description = current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] [ remote . name ] . get ( 'description' , '' ) , app_icon = current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] [ remote . name ] . get ( 'icon' , None ) , ) | 1,060 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L376-L466 | [
"def",
"delete_binding",
"(",
"self",
",",
"vhost",
",",
"exchange",
",",
"queue",
",",
"rt_key",
")",
":",
"vhost",
"=",
"quote",
"(",
"vhost",
",",
"''",
")",
"exchange",
"=",
"quote",
"(",
"exchange",
",",
"''",
")",
"queue",
"=",
"quote",
"(",
"queue",
",",
"''",
")",
"body",
"=",
"''",
"path",
"=",
"Client",
".",
"urls",
"[",
"'rt_bindings_between_exch_queue'",
"]",
"%",
"(",
"vhost",
",",
"exchange",
",",
"queue",
",",
"rt_key",
")",
"return",
"self",
".",
"_call",
"(",
"path",
",",
"'DELETE'",
",",
"headers",
"=",
"Client",
".",
"json_headers",
")"
] |
Remove all access tokens from session on logout . | def oauth_logout_handler ( sender_app , user = None ) : oauth = current_app . extensions [ 'oauthlib.client' ] for remote in oauth . remote_apps . values ( ) : token_delete ( remote ) db . session . commit ( ) | 1,061 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L469-L474 | [
"def",
"update",
"(",
"self",
",",
"E",
"=",
"None",
",",
"*",
"*",
"F",
")",
":",
"def",
"_update",
"(",
"D",
")",
":",
"for",
"k",
",",
"v",
"in",
"D",
".",
"items",
"(",
")",
":",
"if",
"super",
"(",
"ConfigDict",
",",
"self",
")",
".",
"__contains__",
"(",
"k",
")",
":",
"if",
"isinstance",
"(",
"self",
"[",
"k",
"]",
",",
"ConfigDict",
")",
":",
"self",
"[",
"k",
"]",
".",
"update",
"(",
"v",
")",
"else",
":",
"self",
"[",
"k",
"]",
"=",
"self",
".",
"assimilate",
"(",
"v",
")",
"else",
":",
"self",
"[",
"k",
"]",
"=",
"self",
".",
"assimilate",
"(",
"v",
")",
"if",
"E",
"is",
"not",
"None",
":",
"if",
"not",
"hasattr",
"(",
"E",
",",
"'keys'",
")",
":",
"E",
"=",
"self",
".",
"assimilate",
"(",
"dict",
"(",
"E",
")",
")",
"_update",
"(",
"E",
")",
"_update",
"(",
"F",
")",
"return",
"self"
] |
Make a handler for authorized and disconnect callbacks . | def make_handler ( f , remote , with_response = True ) : if isinstance ( f , six . string_types ) : f = import_string ( f ) @ wraps ( f ) def inner ( * args , * * kwargs ) : if with_response : return f ( args [ 0 ] , remote , * args [ 1 : ] , * * kwargs ) else : return f ( remote , * args , * * kwargs ) return inner | 1,062 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L480-L494 | [
"def",
"replace_non_data_file",
"(",
"self",
",",
"dataset_identifier",
",",
"params",
",",
"file_data",
")",
":",
"resource",
"=",
"_format_old_api_request",
"(",
"dataid",
"=",
"dataset_identifier",
",",
"content_type",
"=",
"\"txt\"",
")",
"if",
"not",
"params",
".",
"get",
"(",
"'method'",
",",
"None",
")",
":",
"params",
"[",
"'method'",
"]",
"=",
"'replaceBlob'",
"params",
"[",
"'id'",
"]",
"=",
"dataset_identifier",
"return",
"self",
".",
"_perform_request",
"(",
"\"post\"",
",",
"resource",
",",
"params",
"=",
"params",
",",
"files",
"=",
"file_data",
")"
] |
The decorator for ensuring thread - safe when current cache instance is concurrent status . | def _enable_lock ( func ) : @ functools . wraps ( func ) def wrapper ( * args , * * kwargs ) : self = args [ 0 ] if self . is_concurrent : only_read = kwargs . get ( 'only_read' ) if only_read is None or only_read : with self . _rwlock : return func ( * args , * * kwargs ) else : self . _rwlock . acquire_writer ( ) try : return func ( * args , * * kwargs ) finally : self . _rwlock . release ( ) else : return func ( * args , * * kwargs ) return wrapper | 1,063 | https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/__init__.py#L18-L40 | [
"def",
"catalogFactory",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"fn",
"=",
"lambda",
"member",
":",
"inspect",
".",
"isclass",
"(",
"member",
")",
"and",
"member",
".",
"__module__",
"==",
"__name__",
"catalogs",
"=",
"odict",
"(",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
",",
"fn",
")",
")",
"if",
"name",
"not",
"in",
"list",
"(",
"catalogs",
".",
"keys",
"(",
")",
")",
":",
"msg",
"=",
"\"%s not found in catalogs:\\n %s\"",
"%",
"(",
"name",
",",
"list",
"(",
"kernels",
".",
"keys",
"(",
")",
")",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"msg",
"=",
"\"Unrecognized catalog: %s\"",
"%",
"name",
"raise",
"Exception",
"(",
"msg",
")",
"return",
"catalogs",
"[",
"name",
"]",
"(",
"*",
"*",
"kwargs",
")"
] |
Execute cleanup operation when the decorated function completed . | def _enable_cleanup ( func ) : @ functools . wraps ( func ) def wrapper ( * args , * * kwargs ) : self = args [ 0 ] result = func ( * args , * * kwargs ) self . cleanup ( self ) return result return wrapper | 1,064 | https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/__init__.py#L43-L55 | [
"def",
"populate",
"(",
"dataset_name",
",",
"data_web_service_url",
"=",
"DATA_WEB_SERVICE",
"+",
"\"CFHT\"",
")",
":",
"data_dest",
"=",
"get_uri",
"(",
"dataset_name",
",",
"version",
"=",
"'o'",
",",
"ext",
"=",
"FITS_EXT",
")",
"data_source",
"=",
"\"%s/%so.{}\"",
"%",
"(",
"data_web_service_url",
",",
"dataset_name",
",",
"FITS_EXT",
")",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"data_dest",
")",
")",
"try",
":",
"client",
".",
"link",
"(",
"data_source",
",",
"data_dest",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"pass",
"else",
":",
"raise",
"e",
"header_dest",
"=",
"get_uri",
"(",
"dataset_name",
",",
"version",
"=",
"'o'",
",",
"ext",
"=",
"'head'",
")",
"header_source",
"=",
"\"%s/%so.fits.fz?cutout=[0]\"",
"%",
"(",
"data_web_service_url",
",",
"dataset_name",
")",
"try",
":",
"client",
".",
"link",
"(",
"header_source",
",",
"header_dest",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"pass",
"else",
":",
"raise",
"e",
"header_dest",
"=",
"get_uri",
"(",
"dataset_name",
",",
"version",
"=",
"'p'",
",",
"ext",
"=",
"'head'",
")",
"header_source",
"=",
"\"%s/%s/%sp.head\"",
"%",
"(",
"'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub'",
",",
"'CFHTSG'",
",",
"dataset_name",
")",
"try",
":",
"client",
".",
"link",
"(",
"header_source",
",",
"header_dest",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"pass",
"else",
":",
"raise",
"e",
"return",
"True"
] |
Use thread pool for executing a task if self . enable_thread_pool is True . | def _enable_thread_pool ( func ) : @ functools . wraps ( func ) def wrapper ( * args , * * kwargs ) : self = args [ 0 ] if self . enable_thread_pool and hasattr ( self , 'thread_pool' ) : future = self . thread_pool . submit ( func , * args , * * kwargs ) is_async = kwargs . get ( 'is_async' ) if is_async is None or not is_async : timeout = kwargs . get ( 'timeout' ) if timeout is None : timeout = 2 try : result = future . result ( timeout = timeout ) except TimeoutError as e : self . logger . exception ( e ) result = None return result return future else : return func ( * args , * * kwargs ) return wrapper | 1,065 | https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/__init__.py#L58-L86 | [
"def",
"add_classes",
"(",
"self",
",",
"classes",
")",
":",
"if",
"not",
"isinstance",
"(",
"classes",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Input classes is not a dict!'",
")",
"if",
"not",
"len",
"(",
"classes",
")",
"==",
"self",
".",
"num_samples",
":",
"raise",
"ValueError",
"(",
"'Too few items - need {} keys'",
".",
"format",
"(",
"self",
".",
"num_samples",
")",
")",
"if",
"not",
"all",
"(",
"[",
"key",
"in",
"self",
".",
"keys",
"for",
"key",
"in",
"classes",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'One or more unrecognized keys!'",
")",
"self",
".",
"__classes",
"=",
"classes"
] |
Returns a list that each element is a dictionary of the statistic info of the cache item . | def statistic_record ( self , desc = True , timeout = 3 , is_async = False , only_read = True , * keys ) : if len ( keys ) == 0 : records = self . _generate_statistic_records ( ) else : records = self . _generate_statistic_records_by_keys ( keys ) return sorted ( records , key = lambda t : t [ 'hit_counts' ] , reverse = desc ) | 1,066 | https://github.com/SylvanasSun/python-common-cache/blob/f113eb3cd751eed5ab5373e8610a31a444220cf8/common_cache/__init__.py#L589-L597 | [
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Not safe to use with secret keys or secret data . See module docstring . This function should be used for testing only . | def signature_unsafe ( m , sk , pk , hash_func = H ) : h = hash_func ( sk ) a = 2 ** ( b - 2 ) + sum ( 2 ** i * bit ( h , i ) for i in range ( 3 , b - 2 ) ) r = Hint ( bytearray ( [ h [ j ] for j in range ( b // 8 , b // 4 ) ] ) + m ) R = scalarmult_B ( r ) S = ( r + Hint ( encodepoint ( R ) + pk + m ) * a ) % l return bytes ( encodepoint ( R ) + encodeint ( S ) ) | 1,067 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/ed25519_blake2.py#L214-L224 | [
"def",
"crl_distribution_points",
"(",
"self",
")",
":",
"if",
"self",
".",
"_crl_distribution_points",
"is",
"None",
":",
"self",
".",
"_crl_distribution_points",
"=",
"self",
".",
"_get_http_crl_distribution_points",
"(",
"self",
".",
"crl_distribution_points_value",
")",
"return",
"self",
".",
"_crl_distribution_points"
] |
Not safe to use when any argument is secret . See module docstring . This function should be used only for verifying public signatures of public messages . | def checkvalid ( s , m , pk ) : if len ( s ) != b // 4 : raise ValueError ( "signature length is wrong" ) if len ( pk ) != b // 8 : raise ValueError ( "public-key length is wrong" ) s = bytearray ( s ) m = bytearray ( m ) pk = bytearray ( pk ) R = decodepoint ( s [ : b // 8 ] ) A = decodepoint ( pk ) S = decodeint ( s [ b // 8 : b // 4 ] ) h = Hint ( encodepoint ( R ) + pk + m ) ( x1 , y1 , z1 , t1 ) = P = scalarmult_B ( S ) ( x2 , y2 , z2 , t2 ) = Q = edwards_add ( R , scalarmult ( A , h ) ) if ( not isoncurve ( P ) or not isoncurve ( Q ) or ( x1 * z2 - x2 * z1 ) % q != 0 or ( y1 * z2 - y2 * z1 ) % q != 0 ) : raise SignatureMismatch ( "signature does not pass verification" ) | 1,068 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/ed25519_blake2.py#L255-L285 | [
"def",
"bulk_delete",
"(",
"self",
",",
"container",
",",
"object_names",
",",
"async_",
"=",
"False",
")",
":",
"deleter",
"=",
"BulkDeleter",
"(",
"self",
",",
"container",
",",
"object_names",
")",
"deleter",
".",
"start",
"(",
")",
"if",
"async_",
":",
"return",
"deleter",
"while",
"not",
"deleter",
".",
"completed",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"bulk_delete_interval",
")",
"return",
"deleter",
".",
"results"
] |
Compatibility with NLTK . Returns the cmudict lexicon as a dictionary whose keys are lowercase words and whose values are lists of pronunciations . | def dict ( ) : default = defaultdict ( list ) for key , value in entries ( ) : default [ key ] . append ( value ) return default | 1,069 | https://github.com/prosegrinder/python-cmudict/blob/e7af7ae9e923add04e14fa303ad44d5abd0cc20a/cmudict/__init__.py#L42-L51 | [
"def",
"is_expired",
"(",
"self",
",",
"max_idle_seconds",
")",
":",
"now",
"=",
"current_time",
"(",
")",
"return",
"(",
"self",
".",
"expiration_time",
"is",
"not",
"None",
"and",
"self",
".",
"expiration_time",
"<",
"now",
")",
"or",
"(",
"max_idle_seconds",
"is",
"not",
"None",
"and",
"self",
".",
"last_access_time",
"+",
"max_idle_seconds",
"<",
"now",
")"
] |
Return a list of symbols . | def symbols ( ) : symbols = [ ] for line in symbols_stream ( ) : symbols . append ( line . decode ( 'utf-8' ) . strip ( ) ) return symbols | 1,070 | https://github.com/prosegrinder/python-cmudict/blob/e7af7ae9e923add04e14fa303ad44d5abd0cc20a/cmudict/__init__.py#L92-L97 | [
"def",
"mock_xray_client",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"Starting X-Ray Patch\"",
")",
"old_xray_context_var",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_XRAY_CONTEXT_MISSING'",
")",
"os",
".",
"environ",
"[",
"'AWS_XRAY_CONTEXT_MISSING'",
"]",
"=",
"'LOG_ERROR'",
"old_xray_context",
"=",
"aws_xray_sdk",
".",
"core",
".",
"xray_recorder",
".",
"_context",
"old_xray_emitter",
"=",
"aws_xray_sdk",
".",
"core",
".",
"xray_recorder",
".",
"_emitter",
"aws_xray_sdk",
".",
"core",
".",
"xray_recorder",
".",
"_context",
"=",
"AWSContext",
"(",
")",
"aws_xray_sdk",
".",
"core",
".",
"xray_recorder",
".",
"_emitter",
"=",
"MockEmitter",
"(",
")",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"if",
"old_xray_context_var",
"is",
"None",
":",
"del",
"os",
".",
"environ",
"[",
"'AWS_XRAY_CONTEXT_MISSING'",
"]",
"else",
":",
"os",
".",
"environ",
"[",
"'AWS_XRAY_CONTEXT_MISSING'",
"]",
"=",
"old_xray_context_var",
"aws_xray_sdk",
".",
"core",
".",
"xray_recorder",
".",
"_emitter",
"=",
"old_xray_emitter",
"aws_xray_sdk",
".",
"core",
".",
"xray_recorder",
".",
"_context",
"=",
"old_xray_context",
"return",
"_wrapped"
] |
Connects input Pipers to datas input data in the correct order determined by the Piper . ornament attribute and the Dagger . _cmp function . | def connect_inputs ( self , datas ) : start_pipers = self . get_inputs ( ) self . log . debug ( '%s trying to connect inputs in the order %s' % ( repr ( self ) , repr ( start_pipers ) ) ) for piper , data in izip ( start_pipers , datas ) : piper . connect ( [ data ] ) self . log . debug ( '%s succesfuly connected inputs' % repr ( self ) ) | 1,071 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L188-L209 | [
"def",
"truncate_schema",
"(",
"self",
")",
":",
"assert",
"self",
".",
"server",
"==",
"'localhost'",
"con",
"=",
"self",
".",
"connection",
"or",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_initialize",
"(",
"con",
")",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'DELETE FROM publication;'",
")",
"cur",
".",
"execute",
"(",
"'TRUNCATE systems CASCADE;'",
")",
"con",
".",
"commit",
"(",
")",
"con",
".",
"close",
"(",
")",
"return"
] |
Given the pipeline topology starts Pipers in the order input - > output . See Piper . start . Pipers instances are started in two stages which allows them to share NuMaps . | def start ( self ) : # top - > bottom of pipeline pipers = self . postorder ( ) # for piper in pipers : piper . start ( stages = ( 0 , 1 ) ) for piper in pipers : piper . start ( stages = ( 2 , ) ) | 1,072 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L234-L247 | [
"def",
"delete_table",
"(",
"self",
",",
"table",
")",
":",
"table",
"=",
"table",
".",
"get_soap_object",
"(",
"self",
".",
"client",
")",
"return",
"self",
".",
"call",
"(",
"'deleteTable'",
",",
"table",
")"
] |
Stops the Pipers according to pipeline topology . | def stop ( self ) : self . log . debug ( '%s begins stopping routine' % repr ( self ) ) self . log . debug ( '%s triggers stopping in input pipers' % repr ( self ) ) inputs = self . get_inputs ( ) for piper in inputs : piper . stop ( forced = True ) self . log . debug ( '%s pulls output pipers until stop' % repr ( self ) ) outputs = self . get_outputs ( ) while outputs : for piper in outputs : try : # for i in xrange(stride)? piper . next ( ) except StopIteration : outputs . remove ( piper ) self . log . debug ( "%s stopped output piper: %s" % ( repr ( self ) , repr ( piper ) ) ) continue except Exception , excp : self . log . debug ( "%s %s raised an exception: %s" % ( repr ( self ) , piper , excp ) ) self . log . debug ( "%s stops the remaining pipers" % repr ( self ) ) postorder = self . postorder ( ) for piper in postorder : if piper not in inputs : piper . stop ( ends = [ 0 ] ) self . log . debug ( "%s finishes stopping of input pipers" % repr ( self ) ) for piper in inputs : if hasattr ( piper . imap , 'stop' ) : piper . imap . stop ( ends = [ 0 ] ) self . log . debug ( '%s finishes stopping routine' % repr ( self ) ) | 1,073 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L249-L283 | [
"def",
"read_data",
"(",
"self",
",",
"blocksize",
"=",
"4096",
")",
":",
"frames",
"=",
"ctypes",
".",
"c_uint",
"(",
"blocksize",
"//",
"self",
".",
"_client_fmt",
".",
"mBytesPerFrame",
")",
"buf",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"blocksize",
")",
"buflist",
"=",
"AudioBufferList",
"(",
")",
"buflist",
".",
"mNumberBuffers",
"=",
"1",
"buflist",
".",
"mBuffers",
"[",
"0",
"]",
".",
"mNumberChannels",
"=",
"self",
".",
"_client_fmt",
".",
"mChannelsPerFrame",
"buflist",
".",
"mBuffers",
"[",
"0",
"]",
".",
"mDataByteSize",
"=",
"blocksize",
"buflist",
".",
"mBuffers",
"[",
"0",
"]",
".",
"mData",
"=",
"ctypes",
".",
"cast",
"(",
"buf",
",",
"ctypes",
".",
"c_void_p",
")",
"while",
"True",
":",
"check",
"(",
"_coreaudio",
".",
"ExtAudioFileRead",
"(",
"self",
".",
"_obj",
",",
"ctypes",
".",
"byref",
"(",
"frames",
")",
",",
"ctypes",
".",
"byref",
"(",
"buflist",
")",
")",
")",
"assert",
"buflist",
".",
"mNumberBuffers",
"==",
"1",
"size",
"=",
"buflist",
".",
"mBuffers",
"[",
"0",
"]",
".",
"mDataByteSize",
"if",
"not",
"size",
":",
"break",
"data",
"=",
"ctypes",
".",
"cast",
"(",
"buflist",
".",
"mBuffers",
"[",
"0",
"]",
".",
"mData",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char",
")",
")",
"blob",
"=",
"data",
"[",
":",
"size",
"]",
"yield",
"blob"
] |
Removes a Piper from the Dagger instance . | def del_piper ( self , piper , forced = False ) : self . log . debug ( '%s trying to delete piper %s' % ( repr ( self ) , repr ( piper ) ) ) try : piper = self . resolve ( piper , forgive = False ) except DaggerError : self . log . error ( '%s cannot resolve piper from %s' % ( repr ( self ) , repr ( piper ) ) ) raise DaggerError ( '%s cannot resolve piper from %s' % ( repr ( self ) , repr ( piper ) ) ) if self . incoming_edges ( piper ) and not forced : self . log . error ( '%s piper %s has down-stream pipers (use forced =True to override)' % ( repr ( self ) , piper ) ) raise DaggerError ( '%s piper %s has down-stream pipers (use forced =True to override)' % ( repr ( self ) , piper ) ) self . del_node ( piper ) self . log . debug ( '%s deleted piper %s' % ( repr ( self ) , piper ) ) | 1,074 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L346-L374 | [
"def",
"write_manifest",
"(",
"self",
")",
":",
"self",
".",
"filelist",
".",
"_repair",
"(",
")",
"# Now _repairs should encodability, but not unicode",
"files",
"=",
"[",
"self",
".",
"_manifest_normalize",
"(",
"f",
")",
"for",
"f",
"in",
"self",
".",
"filelist",
".",
"files",
"]",
"msg",
"=",
"\"writing manifest file '%s'\"",
"%",
"self",
".",
"manifest",
"self",
".",
"execute",
"(",
"write_file",
",",
"(",
"self",
".",
"manifest",
",",
"files",
")",
",",
"msg",
")"
] |
Starts the pipeline by connecting the input Pipers of the pipeline to the input data connecting the pipeline and starting the NuMap instances . The order of items in the datas argument sequence should correspond to the order of the input Pipers defined by Dagger . _cmp and Piper . ornament . | def start ( self , datas ) : if not self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : # Plumber statistics self . stats = { } self . stats [ 'start_time' ] = None self . stats [ 'run_time' ] = None # connects input pipers to external data self . connect_inputs ( datas ) # connects pipers within the pipeline self . connect ( ) # make pointers to results collected for pipers by imaps self . stats [ 'pipers_tracked' ] = { } for piper in self . postorder ( ) : if hasattr ( piper . imap , '_tasks_tracked' ) and piper . track : self . stats [ 'pipers_tracked' ] [ piper ] = [ piper . imap . _tasks_tracked [ t . task ] for t in piper . imap_tasks ] self . stats [ 'start_time' ] = time ( ) # starts the Dagger # this starts Pipers and NuMaps super ( Plumber , self ) . start ( ) # transitioning to started state self . _started . set ( ) self . _finished . clear ( ) else : raise PlumberError | 1,075 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L650-L692 | [
"def",
"viewbox",
"(",
"self",
")",
":",
"return",
"self",
".",
"left",
",",
"self",
".",
"top",
",",
"self",
".",
"right",
",",
"self",
".",
"bottom"
] |
Pauses a running pipeline . This will stop retrieving results from the pipeline . Parallel parts of the pipeline will stop after the NuMap buffer is has been filled . A paused pipeline can be run or stopped . | def pause ( self ) : # 1. stop the plumbing thread by raising a StopIteration on a stride # boundary if self . _started . isSet ( ) and self . _running . isSet ( ) and not self . _pausing . isSet ( ) : self . _pausing . set ( ) self . _plunger . join ( ) del self . _plunger self . _pausing . clear ( ) self . _running . clear ( ) else : raise PlumberError | 1,076 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L737-L755 | [
"def",
"cluster_types",
"(",
"types",
",",
"max_clust",
"=",
"12",
")",
":",
"if",
"len",
"(",
"types",
")",
"<",
"max_clust",
":",
"max_clust",
"=",
"len",
"(",
"types",
")",
"# Do actual clustering",
"cluster_dict",
"=",
"do_clustering",
"(",
"types",
",",
"max_clust",
")",
"cluster_ranks",
"=",
"rank_clusters",
"(",
"cluster_dict",
")",
"# Create a dictionary mapping binary numbers to indices",
"ranks",
"=",
"{",
"}",
"for",
"key",
"in",
"cluster_dict",
":",
"for",
"typ",
"in",
"cluster_dict",
"[",
"key",
"]",
":",
"ranks",
"[",
"typ",
"]",
"=",
"cluster_ranks",
"[",
"key",
"]",
"return",
"ranks"
] |
Stops a paused pipeline . This will a trigger a StopIteration in the inputs of the pipeline . And retrieve the buffered results . This will stop all Pipers and NuMaps . Python will not terminate cleanly if a pipeline is running or paused . | def stop ( self ) : if self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : # stops the dagger super ( Plumber , self ) . stop ( ) # disconnects all pipers self . disconnect ( ) self . stats [ 'run_time' ] = time ( ) - self . stats [ 'start_time' ] self . _started . clear ( ) else : raise PlumberError | 1,077 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L757-L775 | [
"def",
"checkIsConsistent",
"(",
"self",
")",
":",
"if",
"is_an_array",
"(",
"self",
".",
"mask",
")",
"and",
"self",
".",
"mask",
".",
"shape",
"!=",
"self",
".",
"data",
".",
"shape",
":",
"raise",
"ConsistencyError",
"(",
"\"Shape mismatch mask={}, data={}\"",
".",
"format",
"(",
"self",
".",
"mask",
".",
"shape",
"!=",
"self",
".",
"data",
".",
"shape",
")",
")"
] |
Returns the next sequence of results given stride and n . | def next ( self ) : try : results = self . _stride_buffer . pop ( ) except ( IndexError , AttributeError ) : self . _rebuffer ( ) results = self . _stride_buffer . pop ( ) if not results : raise StopIteration return results | 1,078 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L1490-L1502 | [
"def",
"check_origin",
"(",
"self",
",",
"origin",
")",
":",
"mod_opts",
"=",
"self",
".",
"application",
".",
"mod_opts",
"if",
"mod_opts",
".",
"get",
"(",
"'cors_origin'",
")",
":",
"return",
"bool",
"(",
"_check_cors_origin",
"(",
"origin",
",",
"mod_opts",
"[",
"'cors_origin'",
"]",
")",
")",
"else",
":",
"return",
"super",
"(",
"AllEventsHandler",
",",
"self",
")",
".",
"check_origin",
"(",
"origin",
")"
] |
Returns the next result from the chained iterables given stride . | def next ( self ) : if self . s : self . s -= 1 else : self . s = self . stride - 1 self . i = ( self . i + 1 ) % self . l # new iterable return self . iterables [ self . i ] . next ( ) | 1,079 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L1557-L1567 | [
"def",
"edit_miz",
"(",
"# noqa: C901",
"infile",
":",
"str",
",",
"outfile",
":",
"str",
"=",
"None",
",",
"metar",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Metar",
"]",
"=",
"None",
",",
"time",
":",
"str",
"=",
"None",
",",
"min_wind",
":",
"int",
"=",
"0",
",",
"max_wind",
":",
"int",
"=",
"40",
")",
"->",
"str",
":",
"# noinspection SpellCheckingInspection",
"if",
"outfile",
"is",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'editing in place: %s'",
",",
"infile",
")",
"outfile",
"=",
"infile",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'editing miz file: %s -> %s'",
",",
"infile",
",",
"outfile",
")",
"mission_weather",
"=",
"mission_time",
"=",
"None",
"if",
"metar",
":",
"error",
",",
"metar",
"=",
"emiz",
".",
"weather",
".",
"custom_metar",
".",
"CustomMetar",
".",
"get_metar",
"(",
"metar",
")",
"if",
"error",
":",
"return",
"error",
"mission_weather",
"=",
"emiz",
".",
"weather",
".",
"mission_weather",
".",
"MissionWeather",
"(",
"metar",
",",
"min_wind",
"=",
"min_wind",
",",
"max_wind",
"=",
"max_wind",
")",
"if",
"time",
":",
"try",
":",
"mission_time",
"=",
"MissionTime",
".",
"from_string",
"(",
"time",
")",
"except",
"ValueError",
":",
"return",
"f'badly formatted time string: {time}'",
"if",
"not",
"mission_weather",
"and",
"not",
"mission_time",
":",
"return",
"'nothing to do!'",
"with",
"Miz",
"(",
"infile",
")",
"as",
"miz",
":",
"if",
"mission_weather",
":",
"LOGGER",
".",
"debug",
"(",
"'applying MissionWeather'",
")",
"if",
"not",
"mission_weather",
".",
"apply_to_miz",
"(",
"miz",
")",
":",
"return",
"'error while applying METAR to mission'",
"if",
"mission_time",
":",
"LOGGER",
".",
"debug",
"(",
"'applying MissionTime'",
")",
"if",
"not",
"mission_time",
".",
"apply_to_miz",
"(",
"miz",
")",
":",
"return",
"'error while setting time on mission'",
"try",
":",
"miz",
".",
"zip",
"(",
"outfile",
")",
"return",
"''",
"except",
"OSError",
":",
"return",
"f'permission error: cannot edit \"{outfile}\"; maybe it is in use ?'"
] |
Get a list of results as CSV . | def list_csv ( self , filter = None , type = None , sort = None , limit = None , page = None ) : # pylint: disable=redefined-builtin return self . service . list ( self . base , filter , type , sort , limit , page , format = 'csv' ) . text | 1,080 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L600-L610 | [
"def",
"connect",
"(",
"image",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"image",
")",
":",
"log",
".",
"warning",
"(",
"'Could not connect image: %s does not exist'",
",",
"image",
")",
"return",
"''",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'sfdisk'",
")",
":",
"fdisk",
"=",
"'sfdisk -d'",
"else",
":",
"fdisk",
"=",
"'fdisk -l'",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'modprobe nbd max_part=63'",
")",
"for",
"nbd",
"in",
"glob",
".",
"glob",
"(",
"'/dev/nbd?'",
")",
":",
"if",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"'{0} {1}'",
".",
"format",
"(",
"fdisk",
",",
"nbd",
")",
")",
":",
"while",
"True",
":",
"# Sometimes nbd does not \"take hold\", loop until we can verify",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'qemu-nbd -c {0} {1}'",
".",
"format",
"(",
"nbd",
",",
"image",
")",
",",
"python_shell",
"=",
"False",
",",
")",
"if",
"not",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"'{0} {1}'",
".",
"format",
"(",
"fdisk",
",",
"nbd",
")",
")",
":",
"break",
"return",
"nbd",
"log",
".",
"warning",
"(",
"'Could not connect image: %s'",
",",
"image",
")",
"return",
"''"
] |
Get updates of a running result via long - polling . If no updates are available CDRouter waits up to 10 seconds before sending an empty response . | def updates ( self , id , update_id = None ) : # pylint: disable=invalid-name,redefined-builtin if update_id is None : update_id = - 1 schema = UpdateSchema ( ) resp = self . service . get_id ( self . base , id , params = { 'updates' : update_id } ) return self . service . decode ( schema , resp ) | 1,081 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L623-L636 | [
"def",
"parse",
"(",
"cls",
",",
"ss",
")",
":",
"up",
"=",
"urlparse",
"(",
"ss",
")",
"path",
"=",
"up",
".",
"path",
"query",
"=",
"up",
".",
"query",
"if",
"'?'",
"in",
"path",
":",
"path",
",",
"_",
"=",
"up",
".",
"path",
".",
"split",
"(",
"'?'",
")",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"bucket",
"=",
"path",
"options",
"=",
"parse_qs",
"(",
"query",
")",
"scheme",
"=",
"up",
".",
"scheme",
"hosts",
"=",
"up",
".",
"netloc",
".",
"split",
"(",
"','",
")",
"return",
"cls",
"(",
"bucket",
"=",
"bucket",
",",
"options",
"=",
"options",
",",
"hosts",
"=",
"hosts",
",",
"scheme",
"=",
"scheme",
")"
] |
Pause a running result . | def pause ( self , id , when = None ) : # pylint: disable=invalid-name,redefined-builtin return self . service . post ( self . base + str ( id ) + '/pause/' , params = { 'when' : when } ) | 1,082 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L660-L666 | [
"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"
] |
Unpause a running result . | def unpause ( self , id ) : # pylint: disable=invalid-name,redefined-builtin return self . service . post ( self . base + str ( id ) + '/unpause/' ) | 1,083 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L682-L687 | [
"def",
"cachedir_index_del",
"(",
"minion_id",
",",
"base",
"=",
"None",
")",
":",
"base",
"=",
"init_cachedir",
"(",
"base",
")",
"index_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"'index.p'",
")",
"lock_file",
"(",
"index_file",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"index_file",
")",
":",
"mode",
"=",
"'rb'",
"if",
"six",
".",
"PY3",
"else",
"'r'",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"index_file",
",",
"mode",
")",
"as",
"fh_",
":",
"index",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"salt",
".",
"utils",
".",
"msgpack",
".",
"load",
"(",
"fh_",
",",
"encoding",
"=",
"MSGPACK_ENCODING",
")",
")",
"else",
":",
"return",
"if",
"minion_id",
"in",
"index",
":",
"del",
"index",
"[",
"minion_id",
"]",
"mode",
"=",
"'wb'",
"if",
"six",
".",
"PY3",
"else",
"'w'",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"index_file",
",",
"mode",
")",
"as",
"fh_",
":",
"salt",
".",
"utils",
".",
"msgpack",
".",
"dump",
"(",
"index",
",",
"fh_",
",",
"encoding",
"=",
"MSGPACK_ENCODING",
")",
"unlock_file",
"(",
"index_file",
")"
] |
Export a result . | def export ( self , id , exclude_captures = False ) : # pylint: disable=invalid-name,redefined-builtin return self . service . export ( self . base , id , params = { 'exclude_captures' : exclude_captures } ) | 1,084 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L727-L734 | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_DISCONNECTED",
":",
"raise",
"Exception",
"(",
"\"WAMP is currently disconnected!\"",
")",
"message",
"=",
"message",
".",
"as_str",
"(",
")",
"logger",
".",
"debug",
"(",
"\"SND>: {}\"",
".",
"format",
"(",
"message",
")",
")",
"if",
"not",
"self",
".",
"ws",
":",
"raise",
"Exception",
"(",
"\"WAMP is currently disconnected!\"",
")",
"self",
".",
"ws",
".",
"send",
"(",
"message",
")"
] |
Bulk export a set of results . | def bulk_export ( self , ids , exclude_captures = False ) : return self . service . bulk_export ( self . base , ids , params = { 'exclude_captures' : exclude_captures } ) | 1,085 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L736-L742 | [
"def",
"from_parameter",
"(",
"cls",
":",
"Type",
"[",
"UnlockParameterType",
"]",
",",
"parameter",
":",
"str",
")",
"->",
"Optional",
"[",
"Union",
"[",
"SIGParameter",
",",
"XHXParameter",
"]",
"]",
":",
"sig_param",
"=",
"SIGParameter",
".",
"from_parameter",
"(",
"parameter",
")",
"if",
"sig_param",
":",
"return",
"sig_param",
"else",
":",
"xhx_param",
"=",
"XHXParameter",
".",
"from_parameter",
"(",
"parameter",
")",
"if",
"xhx_param",
":",
"return",
"xhx_param",
"return",
"None"
] |
Bulk copy a set of results . | def bulk_copy ( self , ids ) : schema = ResultSchema ( ) return self . service . bulk_copy ( self . base , self . RESOURCE , ids , schema ) | 1,086 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L744-L751 | [
"def",
"OnAdjustVolume",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"volume",
"=",
"self",
".",
"player",
".",
"audio_get_volume",
"(",
")",
"if",
"event",
".",
"GetWheelRotation",
"(",
")",
"<",
"0",
":",
"self",
".",
"volume",
"=",
"max",
"(",
"0",
",",
"self",
".",
"volume",
"-",
"10",
")",
"elif",
"event",
".",
"GetWheelRotation",
"(",
")",
">",
"0",
":",
"self",
".",
"volume",
"=",
"min",
"(",
"200",
",",
"self",
".",
"volume",
"+",
"10",
")",
"self",
".",
"player",
".",
"audio_set_volume",
"(",
"self",
".",
"volume",
")"
] |
Compute stats for all results . | def all_stats ( self ) : schema = AllStatsSchema ( ) resp = self . service . post ( self . base , params = { 'stats' : 'all' } ) return self . service . decode ( schema , resp ) | 1,087 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L776-L784 | [
"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",
")"
] |
Compute stats for a set of results . | def set_stats ( self , ids ) : schema = SetStatsSchema ( ) resp = self . service . post ( self . base , params = { 'stats' : 'set' } , json = [ { 'id' : str ( x ) } for x in ids ] ) return self . service . decode ( schema , resp ) | 1,088 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L786-L795 | [
"def",
"_update_dPxy",
"(",
"self",
")",
":",
"if",
"'kappa'",
"in",
"self",
".",
"freeparams",
":",
"scipy",
".",
"copyto",
"(",
"self",
".",
"dPxy",
"[",
"'kappa'",
"]",
",",
"self",
".",
"Pxy",
"/",
"self",
".",
"kappa",
",",
"where",
"=",
"CODON_TRANSITION",
")",
"_fill_diagonals",
"(",
"self",
".",
"dPxy",
"[",
"'kappa'",
"]",
",",
"self",
".",
"_diag_indices",
")",
"if",
"'omega'",
"in",
"self",
".",
"freeparams",
":",
"scipy",
".",
"copyto",
"(",
"self",
".",
"dPxy",
"[",
"'omega'",
"]",
",",
"self",
".",
"Pxy_no_omega",
",",
"where",
"=",
"CODON_NONSYN",
")",
"_fill_diagonals",
"(",
"self",
".",
"dPxy",
"[",
"'omega'",
"]",
",",
"self",
".",
"_diag_indices",
")"
] |
Compute diff stats for a set of results . | def diff_stats ( self , ids ) : schema = DiffStatsSchema ( ) resp = self . service . post ( self . base , params = { 'stats' : 'diff' } , json = [ { 'id' : str ( x ) } for x in ids ] ) return self . service . decode ( schema , resp ) | 1,089 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L797-L806 | [
"def",
"remove_binary_support",
"(",
"self",
",",
"api_id",
",",
"cors",
"=",
"False",
")",
":",
"response",
"=",
"self",
".",
"apigateway_client",
".",
"get_rest_api",
"(",
"restApiId",
"=",
"api_id",
")",
"if",
"\"binaryMediaTypes\"",
"in",
"response",
"and",
"\"*/*\"",
"in",
"response",
"[",
"\"binaryMediaTypes\"",
"]",
":",
"self",
".",
"apigateway_client",
".",
"update_rest_api",
"(",
"restApiId",
"=",
"api_id",
",",
"patchOperations",
"=",
"[",
"{",
"'op'",
":",
"'remove'",
",",
"'path'",
":",
"'/binaryMediaTypes/*~1*'",
"}",
"]",
")",
"if",
"cors",
":",
"# go through each resource and change the contentHandling type",
"response",
"=",
"self",
".",
"apigateway_client",
".",
"get_resources",
"(",
"restApiId",
"=",
"api_id",
")",
"resource_ids",
"=",
"[",
"item",
"[",
"'id'",
"]",
"for",
"item",
"in",
"response",
"[",
"'items'",
"]",
"if",
"'OPTIONS'",
"in",
"item",
".",
"get",
"(",
"'resourceMethods'",
",",
"{",
"}",
")",
"]",
"for",
"resource_id",
"in",
"resource_ids",
":",
"self",
".",
"apigateway_client",
".",
"update_integration",
"(",
"restApiId",
"=",
"api_id",
",",
"resourceId",
"=",
"resource_id",
",",
"httpMethod",
"=",
"'OPTIONS'",
",",
"patchOperations",
"=",
"[",
"{",
"\"op\"",
":",
"\"replace\"",
",",
"\"path\"",
":",
"\"/contentHandling\"",
",",
"\"value\"",
":",
"\"\"",
"}",
"]",
")"
] |
Compute stats for a result . | def single_stats ( self , id ) : # pylint: disable=invalid-name,redefined-builtin schema = SingleStatsSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'all' } ) return self . service . decode ( schema , resp ) | 1,090 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L808-L817 | [
"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",
")"
] |
Compute progress stats for a result . | def progress_stats ( self , id ) : # pylint: disable=invalid-name,redefined-builtin schema = ProgressSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'progress' } ) return self . service . decode ( schema , resp ) | 1,091 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L819-L828 | [
"def",
"preprocess",
"(",
"msg_body",
",",
"delimiter",
",",
"content_type",
"=",
"'text/plain'",
")",
":",
"msg_body",
"=",
"_replace_link_brackets",
"(",
"msg_body",
")",
"msg_body",
"=",
"_wrap_splitter_with_newline",
"(",
"msg_body",
",",
"delimiter",
",",
"content_type",
")",
"return",
"msg_body"
] |
Compute summary stats for a result . | def summary_stats ( self , id ) : # pylint: disable=invalid-name,redefined-builtin schema = SummaryStatsSchema ( ) resp = self . service . get ( self . base + str ( id ) + '/' , params = { 'stats' : 'summary' } ) return self . service . decode ( schema , resp ) | 1,092 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L830-L839 | [
"def",
"preprocess",
"(",
"msg_body",
",",
"delimiter",
",",
"content_type",
"=",
"'text/plain'",
")",
":",
"msg_body",
"=",
"_replace_link_brackets",
"(",
"msg_body",
")",
"msg_body",
"=",
"_wrap_splitter_with_newline",
"(",
"msg_body",
",",
"delimiter",
",",
"content_type",
")",
"return",
"msg_body"
] |
Get a list of logdir files . | def list_logdir ( self , id , filter = None , sort = None ) : # pylint: disable=invalid-name,redefined-builtin schema = LogDirFileSchema ( ) resp = self . service . list ( self . base + str ( id ) + '/logdir/' , filter , sort ) return self . service . decode ( schema , resp , many = True ) | 1,093 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L841-L851 | [
"def",
"get_word",
"(",
"self",
",",
"word",
"=",
"None",
")",
":",
"word",
"=",
"word",
"if",
"not",
"word",
"==",
"None",
"else",
"self",
".",
"initial",
"if",
"not",
"self",
".",
"terminal",
"in",
"word",
":",
"if",
"len",
"(",
"word",
")",
">",
"self",
".",
"average_word_length",
"and",
"self",
".",
"terminal",
"in",
"self",
".",
"links",
"[",
"word",
"[",
"-",
"self",
".",
"chunk_size",
":",
"]",
"]",
"and",
"random",
".",
"randint",
"(",
"0",
",",
"1",
")",
":",
"addon",
"=",
"self",
".",
"terminal",
"else",
":",
"options",
"=",
"self",
".",
"links",
"[",
"word",
"[",
"-",
"self",
".",
"chunk_size",
":",
"]",
"]",
"addon",
"=",
"random",
".",
"choice",
"(",
"options",
")",
"word",
"=",
"word",
"+",
"addon",
"return",
"self",
".",
"get_word",
"(",
"word",
")",
"return",
"word",
"[",
"1",
":",
"-",
"1",
"]"
] |
Download a logdir file . | def get_logdir_file ( self , id , filename ) : # pylint: disable=invalid-name,redefined-builtin resp = self . service . get ( self . base + str ( id ) + '/logdir/' + filename + '/' , stream = True ) b = io . BytesIO ( ) stream . stream_response_to_file ( resp , path = b ) resp . close ( ) b . seek ( 0 ) return ( b , self . service . filename ( resp ) ) | 1,094 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L853-L865 | [
"def",
"tile_metadata",
"(",
"tile",
",",
"product",
",",
"geometry_check",
"=",
"None",
")",
":",
"grid",
"=",
"'T{0}{1}{2}'",
".",
"format",
"(",
"pad",
"(",
"tile",
"[",
"'utmZone'",
"]",
",",
"2",
")",
",",
"tile",
"[",
"'latitudeBand'",
"]",
",",
"tile",
"[",
"'gridSquare'",
"]",
")",
"meta",
"=",
"OrderedDict",
"(",
"{",
"'tile_name'",
":",
"product",
"[",
"'tiles'",
"]",
"[",
"grid",
"]",
"}",
")",
"logger",
".",
"info",
"(",
"'%s Processing tile %s'",
"%",
"(",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
",",
"tile",
"[",
"'path'",
"]",
")",
")",
"meta",
"[",
"'date'",
"]",
"=",
"tile",
"[",
"'timestamp'",
"]",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
"meta",
"[",
"'thumbnail'",
"]",
"=",
"'{1}/{0}/preview.jp2'",
".",
"format",
"(",
"tile",
"[",
"'path'",
"]",
",",
"s3_url",
")",
"# remove unnecessary keys",
"product",
".",
"pop",
"(",
"'tiles'",
")",
"tile",
".",
"pop",
"(",
"'datastrip'",
")",
"bands",
"=",
"product",
".",
"pop",
"(",
"'band_list'",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"tile",
")",
":",
"meta",
"[",
"camelcase_underscore",
"(",
"k",
")",
"]",
"=",
"v",
"meta",
".",
"update",
"(",
"product",
")",
"# construct download links",
"links",
"=",
"[",
"'{2}/{0}/{1}.jp2'",
".",
"format",
"(",
"meta",
"[",
"'path'",
"]",
",",
"b",
",",
"s3_url",
")",
"for",
"b",
"in",
"bands",
"]",
"meta",
"[",
"'download_links'",
"]",
"=",
"{",
"'aws_s3'",
":",
"links",
"}",
"meta",
"[",
"'original_tile_meta'",
"]",
"=",
"'{0}/{1}/tileInfo.json'",
".",
"format",
"(",
"s3_url",
",",
"meta",
"[",
"'path'",
"]",
")",
"def",
"internal_latlon",
"(",
"meta",
")",
":",
"keys",
"=",
"[",
"'tile_origin'",
",",
"'tile_geometry'",
",",
"'tile_data_geometry'",
"]",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"in",
"meta",
":",
"meta",
"[",
"key",
"]",
"=",
"to_latlon",
"(",
"meta",
"[",
"key",
"]",
")",
"return",
"meta",
"# change coordinates to wsg4 degrees",
"if",
"geometry_check",
":",
"if",
"geometry_check",
"(",
"meta",
")",
":",
"meta",
"=",
"get_tile_geometry_from_s3",
"(",
"meta",
")",
"else",
":",
"meta",
"=",
"internal_latlon",
"(",
"meta",
")",
"else",
":",
"meta",
"=",
"internal_latlon",
"(",
"meta",
")",
"# rename path key to aws_path",
"meta",
"[",
"'aws_path'",
"]",
"=",
"meta",
".",
"pop",
"(",
"'path'",
")",
"return",
"meta"
] |
Download logdir archive in tgz or zip format . | def download_logdir_archive ( self , id , format = 'zip' , exclude_captures = False ) : # pylint: disable=invalid-name,redefined-builtin resp = self . service . get ( self . base + str ( id ) + '/logdir/' , params = { 'format' : format , 'exclude_captures' : exclude_captures } , stream = True ) b = io . BytesIO ( ) stream . stream_response_to_file ( resp , path = b ) resp . close ( ) b . seek ( 0 ) return ( b , self . service . filename ( resp ) ) | 1,095 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L867-L880 | [
"def",
"on_startup_error",
"(",
"self",
",",
"error",
")",
":",
"LOGGER",
".",
"critical",
"(",
"'Could not start %s: %s'",
",",
"self",
".",
"consumer_name",
",",
"error",
")",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_STOPPED",
")"
] |
CERN logout view . | def logout ( ) : logout_url = REMOTE_APP [ 'logout_url' ] apps = current_app . config . get ( 'OAUTHCLIENT_REMOTE_APPS' ) if apps : cern_app = apps . get ( 'cern' , REMOTE_APP ) logout_url = cern_app [ 'logout_url' ] return redirect ( logout_url , code = 302 ) | 1,096 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L178-L187 | [
"def",
"match_published_date",
"(",
"self",
",",
"start",
",",
"end",
",",
"match",
")",
":",
"self",
".",
"_match_minimum_date_time",
"(",
"'publishedDate'",
",",
"start",
",",
"match",
")",
"self",
".",
"_match_maximum_date_time",
"(",
"'publishedDate'",
",",
"end",
",",
"match",
")"
] |
Return a remote application based with given client ID . | def find_remote_by_client_id ( client_id ) : for remote in current_oauthclient . oauth . remote_apps . values ( ) : if remote . name == 'cern' and remote . consumer_key == client_id : return remote | 1,097 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L190-L194 | [
"def",
"namedtuple_storable",
"(",
"namedtuple",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"default_storable",
"(",
"namedtuple",
",",
"namedtuple",
".",
"_fields",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Prepare list of allowed group names . | def fetch_groups ( groups ) : hidden_groups = current_app . config . get ( 'OAUTHCLIENT_CERN_HIDDEN_GROUPS' , OAUTHCLIENT_CERN_HIDDEN_GROUPS ) hidden_groups_re = current_app . config . get ( 'OAUTHCLIENT_CERN_HIDDEN_GROUPS_RE' , OAUTHCLIENT_CERN_HIDDEN_GROUPS_RE ) groups = [ group for group in groups if group not in hidden_groups ] filter_groups = [ ] for regexp in hidden_groups_re : for group in groups : if regexp . match ( group ) : filter_groups . append ( group ) groups = [ group for group in groups if group not in filter_groups ] return groups | 1,098 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L197-L216 | [
"def",
"get_midpoint",
"(",
"file",
",",
"file_start",
",",
"file_end",
")",
":",
"filehandle",
"=",
"open",
"(",
"file",
",",
"'r'",
")",
"mid_point",
"=",
"(",
"file_start",
"+",
"file_end",
")",
"/",
"2",
"assert",
"mid_point",
">=",
"file_start",
"filehandle",
".",
"seek",
"(",
"mid_point",
")",
"line",
"=",
"filehandle",
".",
"readline",
"(",
")",
"assert",
"len",
"(",
"line",
")",
">=",
"1",
"if",
"len",
"(",
"line",
")",
"+",
"mid_point",
"<",
"file_end",
":",
"return",
"mid_point",
"+",
"len",
"(",
"line",
")",
"-",
"1",
"filehandle",
".",
"seek",
"(",
"file_start",
")",
"line",
"=",
"filehandle",
".",
"readline",
"(",
")",
"assert",
"len",
"(",
"line",
")",
">=",
"1",
"assert",
"len",
"(",
"line",
")",
"+",
"file_start",
"<=",
"file_end",
"return",
"len",
"(",
"line",
")",
"+",
"file_start",
"-",
"1"
] |
Return a dict with extra data retrieved from cern oauth . | def fetch_extra_data ( resource ) : person_id = resource . get ( 'PersonID' , [ None ] ) [ 0 ] identity_class = resource . get ( 'IdentityClass' , [ None ] ) [ 0 ] department = resource . get ( 'Department' , [ None ] ) [ 0 ] return dict ( person_id = person_id , identity_class = identity_class , department = department ) | 1,099 | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L219-L229 | [
"def",
"check_etag_header",
"(",
"self",
")",
"->",
"bool",
":",
"computed_etag",
"=",
"utf8",
"(",
"self",
".",
"_headers",
".",
"get",
"(",
"\"Etag\"",
",",
"\"\"",
")",
")",
"# Find all weak and strong etag values from If-None-Match header",
"# because RFC 7232 allows multiple etag values in a single header.",
"etags",
"=",
"re",
".",
"findall",
"(",
"br'\\*|(?:W/)?\"[^\"]*\"'",
",",
"utf8",
"(",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"If-None-Match\"",
",",
"\"\"",
")",
")",
")",
"if",
"not",
"computed_etag",
"or",
"not",
"etags",
":",
"return",
"False",
"match",
"=",
"False",
"if",
"etags",
"[",
"0",
"]",
"==",
"b\"*\"",
":",
"match",
"=",
"True",
"else",
":",
"# Use a weak comparison when comparing entity-tags.",
"def",
"val",
"(",
"x",
":",
"bytes",
")",
"->",
"bytes",
":",
"return",
"x",
"[",
"2",
":",
"]",
"if",
"x",
".",
"startswith",
"(",
"b\"W/\"",
")",
"else",
"x",
"for",
"etag",
"in",
"etags",
":",
"if",
"val",
"(",
"etag",
")",
"==",
"val",
"(",
"computed_etag",
")",
":",
"match",
"=",
"True",
"break",
"return",
"match"
] |