query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Calculate the weighted mean of a list . | def weighted_mean ( data , weights = None ) : if weights is None : return mean ( data ) total_weight = float ( sum ( weights ) ) weights = [ weight / total_weight for weight in weights ] w_mean = 0 for i , weight in enumerate ( weights ) : w_mean += weight * data [ i ] return w_mean | 5,000 | https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L43-L52 | [
"def",
"_init_libcrypto",
"(",
")",
":",
"libcrypto",
"=",
"_load_libcrypto",
"(",
")",
"try",
":",
"libcrypto",
".",
"OPENSSL_init_crypto",
"(",
")",
"except",
"AttributeError",
":",
"# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)",
"libcrypto",
".",
"OPENSSL_no_config",
"(",
")",
"libcrypto",
".",
"OPENSSL_add_all_algorithms_noconf",
"(",
")",
"libcrypto",
".",
"RSA_new",
".",
"argtypes",
"=",
"(",
")",
"libcrypto",
".",
"RSA_new",
".",
"restype",
"=",
"c_void_p",
"libcrypto",
".",
"RSA_free",
".",
"argtypes",
"=",
"(",
"c_void_p",
",",
")",
"libcrypto",
".",
"RSA_size",
".",
"argtype",
"=",
"(",
"c_void_p",
")",
"libcrypto",
".",
"BIO_new_mem_buf",
".",
"argtypes",
"=",
"(",
"c_char_p",
",",
"c_int",
")",
"libcrypto",
".",
"BIO_new_mem_buf",
".",
"restype",
"=",
"c_void_p",
"libcrypto",
".",
"BIO_free",
".",
"argtypes",
"=",
"(",
"c_void_p",
",",
")",
"libcrypto",
".",
"PEM_read_bio_RSAPrivateKey",
".",
"argtypes",
"=",
"(",
"c_void_p",
",",
"c_void_p",
",",
"c_void_p",
",",
"c_void_p",
")",
"libcrypto",
".",
"PEM_read_bio_RSAPrivateKey",
".",
"restype",
"=",
"c_void_p",
"libcrypto",
".",
"PEM_read_bio_RSA_PUBKEY",
".",
"argtypes",
"=",
"(",
"c_void_p",
",",
"c_void_p",
",",
"c_void_p",
",",
"c_void_p",
")",
"libcrypto",
".",
"PEM_read_bio_RSA_PUBKEY",
".",
"restype",
"=",
"c_void_p",
"libcrypto",
".",
"RSA_private_encrypt",
".",
"argtypes",
"=",
"(",
"c_int",
",",
"c_char_p",
",",
"c_char_p",
",",
"c_void_p",
",",
"c_int",
")",
"libcrypto",
".",
"RSA_public_decrypt",
".",
"argtypes",
"=",
"(",
"c_int",
",",
"c_char_p",
",",
"c_char_p",
",",
"c_void_p",
",",
"c_int",
")",
"return",
"libcrypto"
] |
Calculate the median of a list . | def median ( data ) : data . sort ( ) num_values = len ( data ) half = num_values // 2 if num_values % 2 : return data [ half ] return 0.5 * ( data [ half - 1 ] + data [ half ] ) | 5,001 | https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L60-L67 | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"device",
"=",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"self",
".",
"idVendor",
",",
"idProduct",
"=",
"self",
".",
"idProduct",
")",
"if",
"self",
".",
"device",
"is",
"None",
":",
"raise",
"NoDeviceError",
"(",
")",
"try",
":",
"if",
"self",
".",
"device",
".",
"is_kernel_driver_active",
"(",
"self",
".",
"interface",
")",
":",
"self",
".",
"device",
".",
"detach_kernel_driver",
"(",
"self",
".",
"interface",
")",
"self",
".",
"device",
".",
"set_configuration",
"(",
")",
"usb",
".",
"util",
".",
"claim_interface",
"(",
"self",
".",
"device",
",",
"self",
".",
"interface",
")",
"except",
"usb",
".",
"core",
".",
"USBError",
"as",
"e",
":",
"raise",
"HandleDeviceError",
"(",
"e",
")"
] |
Calculate the weighted median of a list . | def weighted_median ( data , weights = None ) : if weights is None : return median ( data ) midpoint = 0.5 * sum ( weights ) if any ( [ j > midpoint for j in weights ] ) : return data [ weights . index ( max ( weights ) ) ] if any ( [ j > 0 for j in weights ] ) : sorted_data , sorted_weights = zip ( * sorted ( zip ( data , weights ) ) ) cumulative_weight = 0 below_midpoint_index = 0 while cumulative_weight <= midpoint : below_midpoint_index += 1 cumulative_weight += sorted_weights [ below_midpoint_index - 1 ] cumulative_weight -= sorted_weights [ below_midpoint_index - 1 ] if cumulative_weight - midpoint < sys . float_info . epsilon : bounds = sorted_data [ below_midpoint_index - 2 : below_midpoint_index ] return sum ( bounds ) / float ( len ( bounds ) ) return sorted_data [ below_midpoint_index - 1 ] | 5,002 | https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L69-L87 | [
"def",
"getStartingApplication",
"(",
"self",
",",
"pchAppKeyBuffer",
",",
"unAppKeyBufferLen",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getStartingApplication",
"result",
"=",
"fn",
"(",
"pchAppKeyBuffer",
",",
"unAppKeyBufferLen",
")",
"return",
"result"
] |
Actual method to read Redis settings from app configuration and initialize the StrictRedis instance . | def init_app ( self , app , config_prefix = None ) : # Normalize the prefix and add this instance to app.extensions. config_prefix = ( config_prefix or 'REDIS' ) . rstrip ( '_' ) . upper ( ) if not hasattr ( app , 'extensions' ) : app . extensions = dict ( ) if config_prefix . lower ( ) in app . extensions : raise ValueError ( 'Already registered config prefix {0!r}.' . format ( config_prefix ) ) app . extensions [ config_prefix . lower ( ) ] = _RedisState ( self , app ) # Read config. args = read_config ( app . config , config_prefix ) # Instantiate StrictRedis. super ( Redis , self ) . __init__ ( * * args ) | 5,003 | https://github.com/Robpol86/Flask-Redis-Helper/blob/5708b1287274ab5f09a57bba25b6f1e79cea9148/flask_redis.py#L187-L211 | [
"def",
"cudnnDestroy",
"(",
"handle",
")",
":",
"status",
"=",
"_libcudnn",
".",
"cudnnDestroy",
"(",
"ctypes",
".",
"c_void_p",
"(",
"handle",
")",
")",
"cudnnCheckStatus",
"(",
"status",
")"
] |
A recursive non - atomic directory removal . | def _recursive_remove ( fs , path ) : if not fs . is_link ( path = path ) and fs . is_dir ( path = path ) : for child in fs . children ( path = path ) : _recursive_remove ( fs = fs , path = child ) fs . remove_empty_directory ( path = path ) else : fs . remove_file ( path = path ) | 5,004 | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L37-L46 | [
"def",
"cmd_playtune",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"print",
"(",
"\"Usage: playtune TUNE\"",
")",
"return",
"tune",
"=",
"args",
"[",
"0",
"]",
"str1",
"=",
"tune",
"[",
"0",
":",
"30",
"]",
"str2",
"=",
"tune",
"[",
"30",
":",
"]",
"if",
"sys",
".",
"version_info",
".",
"major",
">=",
"3",
"and",
"not",
"isinstance",
"(",
"str1",
",",
"bytes",
")",
":",
"str1",
"=",
"bytes",
"(",
"str1",
",",
"\"ascii\"",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
">=",
"3",
"and",
"not",
"isinstance",
"(",
"str2",
",",
"bytes",
")",
":",
"str2",
"=",
"bytes",
"(",
"str2",
",",
"\"ascii\"",
")",
"self",
".",
"master",
".",
"mav",
".",
"play_tune_send",
"(",
"self",
".",
"settings",
".",
"target_system",
",",
"self",
".",
"settings",
".",
"target_component",
",",
"str1",
",",
"str2",
")"
] |
Create a new kind of filesystem . | def create ( name , create_file , open_file , remove_file , create_directory , list_directory , remove_empty_directory , temporary_directory , stat , lstat , link , readlink , realpath = _realpath , remove = _recursive_remove , ) : methods = dict ( create = create_file , open = lambda fs , path , mode = "r" : open_file ( fs = fs , path = path , mode = mode , ) , remove_file = remove_file , create_directory = create_directory , list_directory = list_directory , remove_empty_directory = remove_empty_directory , temporary_directory = temporary_directory , get_contents = _get_contents , set_contents = _set_contents , create_with_contents = _create_with_contents , remove = remove , removing = _removing , stat = stat , lstat = lstat , link = link , readlink = readlink , realpath = realpath , exists = _exists , is_dir = _is_dir , is_file = _is_file , is_link = _is_link , touch = _touch , children = _children , glob_children = _glob_children , ) return attr . s ( hash = True ) ( type ( name , ( object , ) , methods ) ) | 5,005 | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L49-L110 | [
"async",
"def",
"postprocess_websocket",
"(",
"self",
",",
"response",
":",
"Optional",
"[",
"Response",
"]",
",",
"websocket_context",
":",
"Optional",
"[",
"WebsocketContext",
"]",
"=",
"None",
",",
")",
"->",
"Response",
":",
"websocket_",
"=",
"(",
"websocket_context",
"or",
"_websocket_ctx_stack",
".",
"top",
")",
".",
"websocket",
"functions",
"=",
"(",
"websocket_context",
"or",
"_websocket_ctx_stack",
".",
"top",
")",
".",
"_after_websocket_functions",
"blueprint",
"=",
"websocket_",
".",
"blueprint",
"if",
"blueprint",
"is",
"not",
"None",
":",
"functions",
"=",
"chain",
"(",
"functions",
",",
"self",
".",
"after_websocket_funcs",
"[",
"blueprint",
"]",
")",
"functions",
"=",
"chain",
"(",
"functions",
",",
"self",
".",
"after_websocket_funcs",
"[",
"None",
"]",
")",
"for",
"function",
"in",
"functions",
":",
"response",
"=",
"await",
"function",
"(",
"response",
")",
"session_",
"=",
"(",
"websocket_context",
"or",
"_request_ctx_stack",
".",
"top",
")",
".",
"session",
"if",
"not",
"self",
".",
"session_interface",
".",
"is_null_session",
"(",
"session_",
")",
":",
"if",
"response",
"is",
"None",
"and",
"isinstance",
"(",
"session_",
",",
"SecureCookieSession",
")",
"and",
"session_",
".",
"modified",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"\"Secure Cookie Session modified during websocket handling. \"",
"\"These modifications will be lost as a cookie cannot be set.\"",
")",
"else",
":",
"await",
"self",
".",
"save_session",
"(",
"session_",
",",
"response",
")",
"return",
"response"
] |
Check that the given path exists on the filesystem . | def _exists ( fs , path ) : try : fs . stat ( path ) except ( exceptions . FileNotFound , exceptions . NotADirectory ) : return False return True | 5,006 | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L157-L170 | [
"def",
"_rows_event_to_dict",
"(",
"e",
",",
"stream",
")",
":",
"pk_cols",
"=",
"e",
".",
"primary_key",
"if",
"isinstance",
"(",
"e",
".",
"primary_key",
",",
"(",
"list",
",",
"tuple",
")",
")",
"else",
"(",
"e",
".",
"primary_key",
",",
")",
"if",
"isinstance",
"(",
"e",
",",
"row_event",
".",
"UpdateRowsEvent",
")",
":",
"sig",
"=",
"signals",
".",
"rows_updated",
"action",
"=",
"'update'",
"row_converter",
"=",
"_convert_update_row",
"elif",
"isinstance",
"(",
"e",
",",
"row_event",
".",
"WriteRowsEvent",
")",
":",
"sig",
"=",
"signals",
".",
"rows_inserted",
"action",
"=",
"'insert'",
"row_converter",
"=",
"_convert_write_row",
"elif",
"isinstance",
"(",
"e",
",",
"row_event",
".",
"DeleteRowsEvent",
")",
":",
"sig",
"=",
"signals",
".",
"rows_deleted",
"action",
"=",
"'delete'",
"row_converter",
"=",
"_convert_write_row",
"else",
":",
"assert",
"False",
",",
"'Invalid binlog event'",
"meta",
"=",
"{",
"'time'",
":",
"e",
".",
"timestamp",
",",
"'log_pos'",
":",
"stream",
".",
"log_pos",
",",
"'log_file'",
":",
"stream",
".",
"log_file",
",",
"'schema'",
":",
"e",
".",
"schema",
",",
"'table'",
":",
"e",
".",
"table",
",",
"'action'",
":",
"action",
",",
"}",
"rows",
"=",
"list",
"(",
"map",
"(",
"row_converter",
",",
"e",
".",
"rows",
")",
")",
"for",
"row",
"in",
"rows",
":",
"row",
"[",
"'keys'",
"]",
"=",
"{",
"k",
":",
"row",
"[",
"'values'",
"]",
"[",
"k",
"]",
"for",
"k",
"in",
"pk_cols",
"}",
"return",
"rows",
",",
"meta"
] |
Check that the given path is a directory . | def _is_dir ( fs , path ) : try : return stat . S_ISDIR ( fs . stat ( path ) . st_mode ) except exceptions . FileNotFound : return False | 5,007 | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L173-L186 | [
"def",
"_update_specs",
"(",
"self",
",",
"instance",
",",
"specs",
")",
":",
"if",
"specs",
"is",
"None",
":",
"return",
"# N.B. we copy the records here, otherwise the spec will be written to",
"# the attached specification of this AR",
"rr",
"=",
"{",
"item",
"[",
"\"keyword\"",
"]",
":",
"item",
".",
"copy",
"(",
")",
"for",
"item",
"in",
"instance",
".",
"getResultsRange",
"(",
")",
"}",
"for",
"spec",
"in",
"specs",
":",
"keyword",
"=",
"spec",
".",
"get",
"(",
"\"keyword\"",
")",
"if",
"keyword",
"in",
"rr",
":",
"# overwrite the instance specification only, if the specific",
"# analysis spec has min/max values set",
"if",
"all",
"(",
"[",
"spec",
".",
"get",
"(",
"\"min\"",
")",
",",
"spec",
".",
"get",
"(",
"\"max\"",
")",
"]",
")",
":",
"rr",
"[",
"keyword",
"]",
".",
"update",
"(",
"spec",
")",
"else",
":",
"rr",
"[",
"keyword",
"]",
"=",
"spec",
"else",
":",
"rr",
"[",
"keyword",
"]",
"=",
"spec",
"return",
"instance",
".",
"setResultsRange",
"(",
"rr",
".",
"values",
"(",
")",
")"
] |
Check that the given path is a file . | def _is_file ( fs , path ) : try : return stat . S_ISREG ( fs . stat ( path ) . st_mode ) except exceptions . FileNotFound : return False | 5,008 | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L189-L201 | [
"def",
"ttl",
"(",
"self",
",",
"value",
")",
":",
"# get timer",
"timer",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"None",
")",
"# if timer is running, stop the timer",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"cancel",
"(",
")",
"# initialize timestamp",
"timestamp",
"=",
"None",
"# if value is None",
"if",
"value",
"is",
"None",
":",
"# nonify timer",
"timer",
"=",
"None",
"else",
":",
"# else, renew a timer",
"# get timestamp",
"timestamp",
"=",
"time",
"(",
")",
"+",
"value",
"# start a new timer",
"timer",
"=",
"Timer",
"(",
"value",
",",
"self",
".",
"__del__",
")",
"timer",
".",
"start",
"(",
")",
"# set/update attributes",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"timer",
")",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TS",
",",
"timestamp",
")"
] |
Check that the given path is a symbolic link . | def _is_link ( fs , path ) : try : return stat . S_ISLNK ( fs . lstat ( path ) . st_mode ) except exceptions . FileNotFound : return False | 5,009 | https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L204-L217 | [
"def",
"union",
"(",
"self",
",",
"*",
"dstreams",
")",
":",
"if",
"not",
"dstreams",
":",
"raise",
"ValueError",
"(",
"\"should have at least one DStream to union\"",
")",
"if",
"len",
"(",
"dstreams",
")",
"==",
"1",
":",
"return",
"dstreams",
"[",
"0",
"]",
"if",
"len",
"(",
"set",
"(",
"s",
".",
"_jrdd_deserializer",
"for",
"s",
"in",
"dstreams",
")",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All DStreams should have same serializer\"",
")",
"if",
"len",
"(",
"set",
"(",
"s",
".",
"_slideDuration",
"for",
"s",
"in",
"dstreams",
")",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All DStreams should have same slide duration\"",
")",
"cls",
"=",
"SparkContext",
".",
"_jvm",
".",
"org",
".",
"apache",
".",
"spark",
".",
"streaming",
".",
"api",
".",
"java",
".",
"JavaDStream",
"jdstreams",
"=",
"SparkContext",
".",
"_gateway",
".",
"new_array",
"(",
"cls",
",",
"len",
"(",
"dstreams",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"dstreams",
")",
")",
":",
"jdstreams",
"[",
"i",
"]",
"=",
"dstreams",
"[",
"i",
"]",
".",
"_jdstream",
"return",
"DStream",
"(",
"self",
".",
"_jssc",
".",
"union",
"(",
"jdstreams",
")",
",",
"self",
",",
"dstreams",
"[",
"0",
"]",
".",
"_jrdd_deserializer",
")"
] |
Fetch a list of resources from the API . | def list ( self , * * kwargs ) : return ModelList ( self . ghost . execute_get ( '%s/' % self . _type_name , * * kwargs ) , self . _type_name , self , kwargs , model_type = self . _model_type ) | 5,010 | https://github.com/rycus86/ghost-client/blob/863d332801d2c1b8e7ad4573c7b16db78a7f8c8d/ghost_client/models.py#L141-L154 | [
"def",
"dump_webdriver_cookies_into_requestdriver",
"(",
"requestdriver",
",",
"webdriverwrapper",
")",
":",
"for",
"cookie",
"in",
"webdriverwrapper",
".",
"get_cookies",
"(",
")",
":",
"# Wedbriver uses \"expiry\"; requests uses \"expires\", adjust for this",
"expires",
"=",
"cookie",
".",
"pop",
"(",
"'expiry'",
",",
"{",
"'expiry'",
":",
"None",
"}",
")",
"cookie",
".",
"update",
"(",
"{",
"'expires'",
":",
"expires",
"}",
")",
"requestdriver",
".",
"session",
".",
"cookies",
".",
"set",
"(",
"*",
"*",
"cookie",
")"
] |
Fetch a resource from the API . Either the id or the slug has to be present . | def get ( self , id = None , slug = None , * * kwargs ) : if id : items = self . ghost . execute_get ( '%s/%s/' % ( self . _type_name , id ) , * * kwargs ) elif slug : items = self . ghost . execute_get ( '%s/slug/%s/' % ( self . _type_name , slug ) , * * kwargs ) else : raise GhostException ( 500 , 'Either the ID or the Slug of the resource needs to be specified' ) return self . _model_type ( items [ self . _type_name ] [ 0 ] ) | 5,011 | https://github.com/rycus86/ghost-client/blob/863d332801d2c1b8e7ad4573c7b16db78a7f8c8d/ghost_client/models.py#L156-L180 | [
"def",
"cart_db",
"(",
")",
":",
"config",
"=",
"_config_file",
"(",
")",
"_config_test",
"(",
"config",
")",
"juicer",
".",
"utils",
".",
"Log",
".",
"log_debug",
"(",
"\"Establishing cart connection:\"",
")",
"cart_con",
"=",
"MongoClient",
"(",
"dict",
"(",
"config",
".",
"items",
"(",
"config",
".",
"sections",
"(",
")",
"[",
"0",
"]",
")",
")",
"[",
"'cart_host'",
"]",
")",
"cart_db",
"=",
"cart_con",
".",
"carts",
"return",
"cart_db"
] |
Creates a new resource . | def create ( self , * * kwargs ) : response = self . ghost . execute_post ( '%s/' % self . _type_name , json = { self . _type_name : [ kwargs ] } ) return self . _model_type ( response . get ( self . _type_name ) [ 0 ] ) | 5,012 | https://github.com/rycus86/ghost-client/blob/863d332801d2c1b8e7ad4573c7b16db78a7f8c8d/ghost_client/models.py#L182-L197 | [
"def",
"_purge_index",
"(",
"self",
",",
"database_name",
",",
"collection_name",
"=",
"None",
",",
"index_name",
"=",
"None",
")",
":",
"with",
"self",
".",
"__index_cache_lock",
":",
"if",
"not",
"database_name",
"in",
"self",
".",
"__index_cache",
":",
"return",
"if",
"collection_name",
"is",
"None",
":",
"del",
"self",
".",
"__index_cache",
"[",
"database_name",
"]",
"return",
"if",
"not",
"collection_name",
"in",
"self",
".",
"__index_cache",
"[",
"database_name",
"]",
":",
"return",
"if",
"index_name",
"is",
"None",
":",
"del",
"self",
".",
"__index_cache",
"[",
"database_name",
"]",
"[",
"collection_name",
"]",
"return",
"if",
"index_name",
"in",
"self",
".",
"__index_cache",
"[",
"database_name",
"]",
"[",
"collection_name",
"]",
":",
"del",
"self",
".",
"__index_cache",
"[",
"database_name",
"]",
"[",
"collection_name",
"]",
"[",
"index_name",
"]"
] |
Creates a new post . When the markdown property is present it will be automatically converted to mobiledoc on v1 . + of the server . | def create ( self , * * kwargs ) : return super ( PostController , self ) . create ( * * self . _with_markdown ( kwargs ) ) | 5,013 | https://github.com/rycus86/ghost-client/blob/863d332801d2c1b8e7ad4573c7b16db78a7f8c8d/ghost_client/models.py#L242-L252 | [
"def",
"expire",
"(",
"self",
",",
"name",
",",
"time",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"expire",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"time",
")"
] |
Updates an existing post . When the markdown property is present it will be automatically converted to mobiledoc on v1 . + of the server . | def update ( self , id , * * kwargs ) : return super ( PostController , self ) . update ( id , * * self . _with_markdown ( kwargs ) ) | 5,014 | https://github.com/rycus86/ghost-client/blob/863d332801d2c1b8e7ad4573c7b16db78a7f8c8d/ghost_client/models.py#L254-L265 | [
"def",
"do_forget",
"(",
"self",
",",
"repo",
")",
":",
"self",
".",
"abort_on_nonexisting_repo",
"(",
"repo",
",",
"'forget'",
")",
"self",
".",
"network",
".",
"forget",
"(",
"repo",
")"
] |
Since plotting all residues that have made contact with the ligand over a lenghty simulation is not always feasible or desirable . Therefore only the residues that have been in contact with ligand for a long amount of time will be plotted in the final image . | def define_residues_for_plotting_traj ( self , analysis_cutoff ) : self . residue_counts_fraction = { } #Calculate the fraction of time a residue spends in each simulation for traj in self . residue_counts : self . residue_counts_fraction [ traj ] = { residue : float ( values ) / len ( self . contacts_per_timeframe [ traj ] ) for residue , values in self . residue_counts [ traj ] . items ( ) } for traj in self . residue_counts_fraction : for residue in self . residue_counts_fraction [ traj ] : self . frequency [ residue ] . append ( self . residue_counts_fraction [ traj ] [ residue ] ) self . topology_data . dict_of_plotted_res = { i : self . frequency [ i ] for i in self . frequency if sum ( self . frequency [ i ] ) > ( int ( len ( self . trajectory ) ) * analysis_cutoff ) } assert len ( self . topology_data . dict_of_plotted_res ) != 0 , "Nothing to draw for this ligand:(residue number: " + str ( self . topology_data . universe . ligand . resids [ 0 ] ) + " on the chain " + str ( self . topology_data . universe . ligand . segids [ 0 ] ) + ") - try reducing the analysis cutoff." | 5,015 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/residence_time.py#L93-L125 | [
"def",
"classify_languages",
"(",
"self",
")",
":",
"return",
"BlobsWithLanguageDataFrame",
"(",
"self",
".",
"_engine_dataframe",
".",
"classifyLanguages",
"(",
")",
",",
"self",
".",
"_session",
",",
"self",
".",
"_implicits",
")"
] |
Using rdkit to detect aromatic rings in ligand - size 4 - 6 atoms and all atoms are part of the ring . Saves this data in self . ligrings . | def detect_aromatic_rings_in_ligand ( self ) : self . ligrings = { } try : ring_info = self . topology_data . mol . GetRingInfo ( ) self . ligand_ring_num = ring_info . NumRings ( ) except Exception as e : m = Chem . MolFromPDBFile ( "lig.pdb" ) ring_info = m . GetRingInfo ( ) self . ligand_ring_num = ring_info . NumRings ( ) i = 0 for ring in range ( self . ligand_ring_num ) : if 4 < len ( ring_info . AtomRings ( ) [ ring ] ) <= 6 and False not in [ self . topology_data . mol . GetAtomWithIdx ( x ) . GetIsAromatic ( ) for x in ring_info . AtomRings ( ) [ ring ] ] : #narrow ring definition atom_ids_in_ring = [ ] for atom in ring_info . AtomRings ( ) [ ring ] : atom_ids_in_ring . append ( self . topology_data . universe . ligand . atoms [ atom ] . name ) self . ligrings [ i ] = atom_ids_in_ring i += 1 | 5,016 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/pistacking.py#L69-L86 | [
"def",
"dst",
"(",
"self",
",",
"dt",
")",
":",
"if",
"not",
"self",
".",
"_is_dst",
"(",
"dt",
")",
":",
"return",
"datetime",
".",
"timedelta",
"(",
"0",
")",
"offset",
"=",
"time",
".",
"timezone",
"-",
"time",
".",
"altzone",
"return",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"-",
"offset",
")"
] |
Make MDAnalysis atom selections for rings in protein residues that will be plotted in the final figure - since they are the only ones that should be analysed . Saves the rings in self . protein_rings dictionary . | def define_all_protein_rings ( self ) : self . protein_rings = { } i = 0 for residue in self . topology_data . dict_of_plotted_res : for ring in self . rings : if ring [ 0 ] == residue [ 0 ] : atom_names = "" for atom in self . rings [ ring ] : atom_names = atom_names + " " + atom self . protein_rings [ i ] = self . topology_data . universe . select_atoms ( "resname " + residue [ 0 ] + " and resid " + residue [ 1 ] + " and segid " + residue [ 2 ] + " and name " + atom_names ) i += 1 | 5,017 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/pistacking.py#L115-L129 | [
"def",
"_aux_data",
"(",
"self",
",",
"i",
")",
":",
"self",
".",
"wait_to_read",
"(",
")",
"hdl",
"=",
"NDArrayHandle",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXNDArrayGetAuxNDArray",
"(",
"self",
".",
"handle",
",",
"i",
",",
"ctypes",
".",
"byref",
"(",
"hdl",
")",
")",
")",
"return",
"NDArray",
"(",
"hdl",
")"
] |
Count how many times each individual pi - pi interaction occured throughout the simulation . Returns numpy array . | def count_by_type ( self ) : pistack = defaultdict ( int ) for contact in self . timeseries : #count by residue name not by proteinring pkey = ( contact . ligandring , contact . type , contact . resid , contact . resname , contact . segid ) pistack [ pkey ] += 1 dtype = [ ( "ligand_ring_ids" , list ) , ( "type" , "|U4" ) , ( "resid" , int ) , ( "resname" , "|U4" ) , ( "segid" , "|U8" ) , ( "frequency" , float ) ] out = np . empty ( ( len ( pistack ) , ) , dtype = dtype ) tsteps = float ( len ( self . timesteps ) ) for cursor , ( key , count ) in enumerate ( pistack . iteritems ( ) ) : out [ cursor ] = key + ( count / tsteps , ) return out . view ( np . recarray ) | 5,018 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/pistacking.py#L209-L222 | [
"def",
"revoke_local_roles_for",
"(",
"brain_or_object",
",",
"roles",
",",
"user",
"=",
"None",
")",
":",
"user_id",
"=",
"get_user_id",
"(",
"user",
")",
"obj",
"=",
"api",
".",
"get_object",
"(",
"brain_or_object",
")",
"valid_roles",
"=",
"get_valid_roles_for",
"(",
"obj",
")",
"to_grant",
"=",
"list",
"(",
"get_local_roles_for",
"(",
"obj",
")",
")",
"if",
"isinstance",
"(",
"roles",
",",
"basestring",
")",
":",
"roles",
"=",
"[",
"roles",
"]",
"for",
"role",
"in",
"roles",
":",
"if",
"role",
"in",
"to_grant",
":",
"if",
"role",
"not",
"in",
"valid_roles",
":",
"raise",
"ValueError",
"(",
"\"The Role '{}' is invalid.\"",
".",
"format",
"(",
"role",
")",
")",
"# Remove the role",
"to_grant",
".",
"remove",
"(",
"role",
")",
"if",
"len",
"(",
"to_grant",
")",
">",
"0",
":",
"obj",
".",
"manage_setLocalRoles",
"(",
"user_id",
",",
"to_grant",
")",
"else",
":",
"obj",
".",
"manage_delLocalRoles",
"(",
"[",
"user_id",
"]",
")",
"return",
"get_local_roles_for",
"(",
"brain_or_object",
")"
] |
DB Replication app . | def main ( master_dsn , slave_dsn , tables , blocking = False ) : # currently only supports mysql master assert master_dsn . startswith ( "mysql" ) logger = logging . getLogger ( __name__ ) logger . info ( "replicating tables: %s" % ", " . join ( tables ) ) repl_db_sub ( master_dsn , slave_dsn , tables ) mysql_pub ( master_dsn , blocking = blocking ) | 5,019 | https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/examples/repl_db/repl.py#L131-L158 | [
"def",
"victim",
"(",
"self",
",",
"name",
",",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Victim",
"(",
"self",
".",
"tcex",
",",
"name",
",",
"owner",
"=",
"owner",
",",
"*",
"*",
"kwargs",
")"
] |
Return text position corresponding to given pos . The text alignment in the bounding box should be set accordingly in order to have a good - looking layout . This corresponding text alignment can be obtained by get_text_alignment or get_text_position_and_inner_alignment function . | def get_text_position_in_ax_coord ( ax , pos , scale = default_text_relative_padding ) : ratio = get_axes_ratio ( ax ) x , y = scale , scale if ratio > 1 : # vertical is longer y /= ratio elif 0 < ratio : # 0 < ratio <= 1 x *= ratio pos = pos . lower ( ) if pos == 'nw' : y = 1 - y elif pos == 'ne' : x , y = 1 - x , 1 - y elif pos == 'sw' : pass elif pos == 'se' : x = 1 - x else : raise ValueError ( "Unknown value for 'pos': %s" % ( str ( pos ) ) ) return x , y | 5,020 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/layout.py#L24-L44 | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"SacrificeDate",
":",
"self",
".",
"Active",
"=",
"False",
"super",
"(",
"PlugEvents",
",",
"self",
")",
".",
"save",
"(",
")"
] |
Return text position and its alignment in its bounding box . The returned position is given in Axes coordinate as defined in matplotlib documentation on transformation . | def get_text_position_and_inner_alignment ( ax , pos , scale = default_text_relative_padding , with_transAxes_kwargs = True ) : xy = get_text_position_in_ax_coord ( ax , pos , scale = scale ) alignment_fontdict = get_text_alignment ( pos ) if with_transAxes_kwargs : alignment_fontdict = { * * alignment_fontdict , * * { 'transform' : ax . transAxes } } return xy , alignment_fontdict | 5,021 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/layout.py#L59-L71 | [
"def",
"set_value",
"(",
"self",
",",
"dry_wet",
":",
"LeakSensorState",
")",
":",
"value",
"=",
"0",
"if",
"dry_wet",
"==",
"self",
".",
"_dry_wet_type",
":",
"value",
"=",
"1",
"self",
".",
"_update_subscribers",
"(",
"value",
")"
] |
Return text position inside of the given axis | def get_text_position ( fig , ax , ha = 'left' , va = 'top' , pad_scale = 1.0 ) : ## Check and preprocess input arguments try : pad_scale = float ( pad_scale ) except : raise TypeError ( "'pad_scale should be of type 'float'" ) for arg in [ va , ha ] : assert type ( arg ) is str arg = arg . lower ( ) # Make it lowercase to prevent case problem. ## Get axis size in inches ax_height , ax_width = get_ax_size_in_inch ( fig , ax ) ## Construct inversion factor from inch to plot coordinate length_x = ax . get_xlim ( ) [ 1 ] - ax . get_xlim ( ) [ 0 ] length_y = ax . get_ylim ( ) [ 1 ] - ax . get_ylim ( ) [ 0 ] inch2coord_x = length_x / ax_width inch2coord_y = length_y / ax_height ## Set padding size relative to the text size #pad_inch = text_bbox_inch.height * pad_scale #pad_inch = fontsize_points * point2inch * pad_scale ax_length_geom_average = ( ax_height * ax_width ) ** 0.5 pad_inch = ax_length_geom_average * 0.03 * pad_scale pad_inch_x , pad_inch_y = pad_inch , pad_inch pad_coord_x = pad_inch_x * inch2coord_x pad_coord_y = pad_inch_y * inch2coord_y if ha == 'left' : pos_x = ax . get_xlim ( ) [ 0 ] + pad_coord_x elif ha == 'right' : pos_x = ax . get_xlim ( ) [ 1 ] - pad_coord_x else : raise Exception ( "Unsupported value for 'ha'" ) if va in [ 'top' , 'up' , 'upper' ] : pos_y = ax . get_ylim ( ) [ 1 ] - pad_coord_y elif va in [ 'bottom' , 'down' , 'lower' ] : pos_y = ax . get_ylim ( ) [ 0 ] + pad_coord_y else : raise Exception ( "Unsupported value for 'va'" ) return pos_x , pos_y | 5,022 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/layout.py#L81-L118 | [
"def",
"countRandomBitFrequencies",
"(",
"numTerms",
"=",
"100000",
",",
"percentSparsity",
"=",
"0.01",
")",
":",
"# Accumulate counts by inplace-adding sparse matrices",
"counts",
"=",
"SparseMatrix",
"(",
")",
"size",
"=",
"128",
"*",
"128",
"counts",
".",
"resize",
"(",
"1",
",",
"size",
")",
"# Pre-allocate buffer sparse matrix",
"sparseBitmap",
"=",
"SparseMatrix",
"(",
")",
"sparseBitmap",
".",
"resize",
"(",
"1",
",",
"size",
")",
"random",
".",
"seed",
"(",
"42",
")",
"# Accumulate counts for each bit for each word",
"numWords",
"=",
"0",
"for",
"term",
"in",
"xrange",
"(",
"numTerms",
")",
":",
"bitmap",
"=",
"random",
".",
"sample",
"(",
"xrange",
"(",
"size",
")",
",",
"int",
"(",
"size",
"*",
"percentSparsity",
")",
")",
"bitmap",
".",
"sort",
"(",
")",
"sparseBitmap",
".",
"setRowFromSparse",
"(",
"0",
",",
"bitmap",
",",
"[",
"1",
"]",
"*",
"len",
"(",
"bitmap",
")",
")",
"counts",
"+=",
"sparseBitmap",
"numWords",
"+=",
"1",
"# Compute normalized version of counts as a separate matrix",
"frequencies",
"=",
"SparseMatrix",
"(",
")",
"frequencies",
".",
"resize",
"(",
"1",
",",
"size",
")",
"frequencies",
".",
"copy",
"(",
"counts",
")",
"frequencies",
".",
"divide",
"(",
"float",
"(",
"numWords",
")",
")",
"# Wrap up by printing some statistics and then saving the normalized version",
"printFrequencyStatistics",
"(",
"counts",
",",
"frequencies",
",",
"numWords",
",",
"size",
")",
"frequencyFilename",
"=",
"\"bit_frequencies_random.pkl\"",
"print",
"\"Saving frequency matrix in\"",
",",
"frequencyFilename",
"with",
"open",
"(",
"frequencyFilename",
",",
"\"wb\"",
")",
"as",
"frequencyPickleFile",
":",
"pickle",
".",
"dump",
"(",
"frequencies",
",",
"frequencyPickleFile",
")",
"return",
"counts"
] |
Flask app factory function . | def create_app ( config = None , config_obj = None ) : app = Flask ( __name__ ) # configure application from external configs configure_app ( app , config = config , config_obj = config_obj ) # register different parts of the application register_blueprints ( app ) # setup extensions bind_extensions ( app ) return app | 5,023 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/factory.py#L12-L26 | [
"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",
")"
] |
Configure application instance . | def configure_app ( app , config = None , config_obj = None ) : app . config . from_object ( config_obj or BaseConfig ) if config is not None : app . config . from_pyfile ( config ) | 5,024 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/factory.py#L29-L39 | [
"def",
"restore",
"(",
"self",
")",
":",
"clean_beam",
",",
"beam_params",
"=",
"beam_fit",
"(",
"self",
".",
"psf_data",
",",
"self",
".",
"cdelt1",
",",
"self",
".",
"cdelt2",
")",
"if",
"np",
".",
"all",
"(",
"np",
".",
"array",
"(",
"self",
".",
"psf_data_shape",
")",
"==",
"2",
"*",
"np",
".",
"array",
"(",
"self",
".",
"dirty_data_shape",
")",
")",
":",
"self",
".",
"restored",
"=",
"np",
".",
"fft",
".",
"fftshift",
"(",
"np",
".",
"fft",
".",
"irfft2",
"(",
"np",
".",
"fft",
".",
"rfft2",
"(",
"conv",
".",
"pad_array",
"(",
"self",
".",
"model",
")",
")",
"*",
"np",
".",
"fft",
".",
"rfft2",
"(",
"clean_beam",
")",
")",
")",
"self",
".",
"restored",
"=",
"self",
".",
"restored",
"[",
"self",
".",
"dirty_data_shape",
"[",
"0",
"]",
"/",
"2",
":",
"-",
"self",
".",
"dirty_data_shape",
"[",
"0",
"]",
"/",
"2",
",",
"self",
".",
"dirty_data_shape",
"[",
"1",
"]",
"/",
"2",
":",
"-",
"self",
".",
"dirty_data_shape",
"[",
"1",
"]",
"/",
"2",
"]",
"else",
":",
"self",
".",
"restored",
"=",
"np",
".",
"fft",
".",
"fftshift",
"(",
"np",
".",
"fft",
".",
"irfft2",
"(",
"np",
".",
"fft",
".",
"rfft2",
"(",
"self",
".",
"model",
")",
"*",
"np",
".",
"fft",
".",
"rfft2",
"(",
"clean_beam",
")",
")",
")",
"self",
".",
"restored",
"+=",
"self",
".",
"residual",
"self",
".",
"restored",
"=",
"self",
".",
"restored",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"return",
"beam_params"
] |
Configure extensions . | def bind_extensions ( app ) : # bind plugin to app object app . db = app . config [ 'PUZZLE_BACKEND' ] app . db . init_app ( app ) # bind bootstrap blueprints bootstrap . init_app ( app ) markdown ( app ) @ app . template_filter ( 'islist' ) def islist ( object ) : return isinstance ( object , ( tuple , list ) ) | 5,025 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/factory.py#L52-L68 | [
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Since MDAnalysis a pre - set list for acceptor and donor atoms for proteins and solvents from specific forcefields it is necessary to find donor and acceptor atoms for the ligand molecule . This function uses RDKit and searches through ligand atoms to find matches for pre - set list of possible donor and acceptor atoms . The resulting list is then parsed to MDAnalysis through the donors and acceptors arguments . | def find_donors_and_acceptors_in_ligand ( self ) : atom_names = [ x . name for x in self . topology_data . universe . ligand ] try : for atom in self . topology_data . mol . GetSubstructMatches ( self . HDonorSmarts , uniquify = 1 ) : self . donors . append ( atom_names [ atom [ 0 ] ] ) for atom in self . topology_data . mol . GetSubstructMatches ( self . HAcceptorSmarts , uniquify = 1 ) : self . acceptors . append ( atom_names [ atom [ 0 ] ] ) except Exception as e : m = Chem . MolFromPDBFile ( "lig.pdb" ) self . donors = [ ] self . acceptors = [ ] for atom in m . GetSubstructMatches ( self . HDonorSmarts , uniquify = 1 ) : self . donors . append ( atom_names [ atom [ 0 ] ] ) haccep = "[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N;v3;!$(N-*=!@[O,N,P,S])]),$([nH0,o,s;+0])]" self . HAcceptorSmarts = Chem . MolFromSmarts ( haccep ) for atom in m . GetSubstructMatches ( self . HAcceptorSmarts , uniquify = 1 ) : self . acceptors . append ( atom_names [ atom [ 0 ] ] ) | 5,026 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/hbonds.py#L64-L87 | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"_client",
".",
"remove_object",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"_bucket",
",",
"self",
".",
"name",
")"
] |
Count how many times each individual hydrogen bonds occured throughout the simulation . Returns numpy array . | def count_by_type ( self , table , timesteps ) : hbonds = defaultdict ( int ) for contact in table : #count by residue name not by proteinring pkey = ( contact . donor_idx , contact . acceptor_idx , contact . donor_atom , contact . acceptor_atom , contact . donor_resnm , contact . donor_resid , contact . acceptor_resnm , contact . acceptor_resid ) hbonds [ pkey ] += 1 dtype = [ ( "donor_idx" , int ) , ( "acceptor_idx" , int ) , ( "donor_atom" , "|U4" ) , ( "acceptor_atom" , "|U4" ) , ( "donor_resnm" , "|U8" ) , ( "donor_resid" , "|U8" ) , ( "acceptor_resnm" , "|U8" ) , ( "acceptor_resid" , "|U8" ) , ( "frequency" , float ) ] out = np . empty ( ( len ( hbonds ) , ) , dtype = dtype ) tsteps = float ( len ( timesteps ) ) for cursor , ( key , count ) in enumerate ( hbonds . iteritems ( ) ) : out [ cursor ] = key + ( count / tsteps , ) return out . view ( np . recarray ) | 5,027 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/hbonds.py#L118-L131 | [
"def",
"set_clipboard",
"(",
"self",
",",
"data",
",",
"datatype",
"=",
"\"text\"",
")",
":",
"error_log",
"=",
"[",
"]",
"if",
"datatype",
"==",
"\"text\"",
":",
"clip_data",
"=",
"wx",
".",
"TextDataObject",
"(",
"text",
"=",
"data",
")",
"elif",
"datatype",
"==",
"\"bitmap\"",
":",
"clip_data",
"=",
"wx",
".",
"BitmapDataObject",
"(",
"bitmap",
"=",
"data",
")",
"else",
":",
"msg",
"=",
"_",
"(",
"\"Datatype {type} unknown\"",
")",
".",
"format",
"(",
"type",
"=",
"datatype",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"self",
".",
"clipboard",
".",
"Open",
"(",
")",
":",
"self",
".",
"clipboard",
".",
"SetData",
"(",
"clip_data",
")",
"self",
".",
"clipboard",
".",
"Close",
"(",
")",
"else",
":",
"wx",
".",
"MessageBox",
"(",
"_",
"(",
"\"Can't open the clipboard\"",
")",
",",
"_",
"(",
"\"Error\"",
")",
")",
"return",
"error_log"
] |
Since plotting all hydrogen bonds could lead to a messy plot a cutoff has to be imple - mented . In this function the frequency of each hydrogen bond is summated and the total compared against analysis cutoff - a fraction multiplied by trajectory count . Those hydrogen bonds that are present for longer than analysis cutoff will be plotted in the final plot . | def determine_hbonds_for_drawing ( self , analysis_cutoff ) : self . frequency = defaultdict ( int ) for traj in self . hbonds_by_type : for bond in self . hbonds_by_type [ traj ] : # frequency[(residue_atom_idx,ligand_atom_name,residue_atom_name)]=frequency # residue atom name will be used to determine if hydrogen bond is interacting with a sidechain or bakcbone if bond [ "donor_resnm" ] != "LIG" : self . frequency [ ( bond [ "donor_idx" ] , bond [ "acceptor_atom" ] , bond [ "donor_atom" ] , bond [ "acceptor_idx" ] ) ] += bond [ "frequency" ] #check whether ligand is donor or acceptor else : self . frequency [ ( bond [ "acceptor_idx" ] , bond [ "donor_atom" ] , bond [ "acceptor_atom" ] , bond [ "donor_idx" ] ) ] += bond [ "frequency" ] #Add the frequency counts self . frequency = { i : self . frequency [ i ] for i in self . frequency if self . frequency [ i ] > ( int ( len ( self . trajectory ) ) * analysis_cutoff ) } #change the ligand atomname to a heavy atom - required for plot since only heavy atoms shown in final image self . hbonds_for_drawing = { } for bond in self . frequency : atomname = bond [ 1 ] if atomname . startswith ( "O" , 0 ) or atomname . startswith ( "N" , 0 ) : lig_atom = atomname else : atomindex = [ index for index , atom in enumerate ( self . topology_data . universe . ligand . atoms ) if atom . name == atomname ] [ 0 ] rdkit_atom = self . topology_data . mol . GetAtomWithIdx ( atomindex ) for neigh in rdkit_atom . GetNeighbors ( ) : neigh_atom_id = neigh . GetIdx ( ) lig_atom = [ atom . name for index , atom in enumerate ( self . topology_data . universe . ligand . atoms ) if index == neigh_atom_id ] [ 0 ] self . hbonds_for_drawing [ ( bond [ 0 ] , lig_atom , bond [ 2 ] , bond [ 3 ] ) ] = self . frequency [ bond ] | 5,028 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/hbonds.py#L153-L195 | [
"def",
"_sync_with_file",
"(",
"self",
")",
":",
"self",
".",
"_records",
"=",
"[",
"]",
"i",
"=",
"-",
"1",
"for",
"i",
",",
"line",
"in",
"self",
".",
"_enum_lines",
"(",
")",
":",
"self",
".",
"_records",
".",
"append",
"(",
"None",
")",
"self",
".",
"_last_synced_index",
"=",
"i"
] |
Converts value type from python to dbus according signature . | def convert2dbus ( value , signature ) : if len ( signature ) == 2 and signature . startswith ( 'a' ) : return dbus . Array ( value , signature = signature [ - 1 ] ) dbus_string_type = dbus . String if PY3 else dbus . UTF8String type_map = { 'b' : dbus . Boolean , 'y' : dbus . Byte , 'n' : dbus . Int16 , 'i' : dbus . Int32 , 'x' : dbus . Int64 , 'q' : dbus . UInt16 , 'u' : dbus . UInt32 , 't' : dbus . UInt64 , 'd' : dbus . Double , 'o' : dbus . ObjectPath , 'g' : dbus . Signature , 's' : dbus_string_type } return type_map [ signature ] ( value ) | 5,029 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L25-L40 | [
"def",
"save_lastnode_id",
"(",
")",
":",
"init_counter",
"(",
")",
"with",
"FileLock",
"(",
"_COUNTER_FILE",
")",
":",
"with",
"AtomicFile",
"(",
"_COUNTER_FILE",
",",
"mode",
"=",
"\"w\"",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"\"%d\\n\"",
"%",
"_COUNTER",
")"
] |
Converts dbus_obj from dbus type to python type . | def convert ( dbus_obj ) : _isinstance = partial ( isinstance , dbus_obj ) ConvertType = namedtuple ( 'ConvertType' , 'pytype dbustypes' ) pyint = ConvertType ( int , ( dbus . Byte , dbus . Int16 , dbus . Int32 , dbus . Int64 , dbus . UInt16 , dbus . UInt32 , dbus . UInt64 ) ) pybool = ConvertType ( bool , ( dbus . Boolean , ) ) pyfloat = ConvertType ( float , ( dbus . Double , ) ) pylist = ConvertType ( lambda _obj : list ( map ( convert , dbus_obj ) ) , ( dbus . Array , ) ) pytuple = ConvertType ( lambda _obj : tuple ( map ( convert , dbus_obj ) ) , ( dbus . Struct , ) ) types_str = ( dbus . ObjectPath , dbus . Signature , dbus . String ) if not PY3 : types_str += ( dbus . UTF8String , ) pystr = ConvertType ( str if PY3 else unicode , types_str ) pydict = ConvertType ( lambda _obj : dict ( zip ( map ( convert , dbus_obj . keys ( ) ) , map ( convert , dbus_obj . values ( ) ) ) ) , ( dbus . Dictionary , ) ) for conv in ( pyint , pybool , pyfloat , pylist , pytuple , pystr , pydict ) : if any ( map ( _isinstance , conv . dbustypes ) ) : return conv . pytype ( dbus_obj ) else : return dbus_obj | 5,030 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L43-L77 | [
"def",
"_get_manifest_list",
"(",
"self",
",",
"image",
")",
":",
"if",
"image",
"in",
"self",
".",
"manifest_list_cache",
":",
"return",
"self",
".",
"manifest_list_cache",
"[",
"image",
"]",
"manifest_list",
"=",
"get_manifest_list",
"(",
"image",
",",
"image",
".",
"registry",
",",
"insecure",
"=",
"self",
".",
"parent_registry_insecure",
",",
"dockercfg_path",
"=",
"self",
".",
"parent_registry_dockercfg_path",
")",
"if",
"'@sha256:'",
"in",
"str",
"(",
"image",
")",
"and",
"not",
"manifest_list",
":",
"# we want to adjust the tag only for manifest list fetching",
"image",
"=",
"image",
".",
"copy",
"(",
")",
"try",
":",
"config_blob",
"=",
"get_config_from_registry",
"(",
"image",
",",
"image",
".",
"registry",
",",
"image",
".",
"tag",
",",
"insecure",
"=",
"self",
".",
"parent_registry_insecure",
",",
"dockercfg_path",
"=",
"self",
".",
"parent_registry_dockercfg_path",
")",
"except",
"(",
"HTTPError",
",",
"RetryError",
",",
"Timeout",
")",
"as",
"ex",
":",
"self",
".",
"log",
".",
"warning",
"(",
"'Unable to fetch config for %s, got error %s'",
",",
"image",
",",
"ex",
".",
"response",
".",
"status_code",
")",
"raise",
"RuntimeError",
"(",
"'Unable to fetch config for base image'",
")",
"release",
"=",
"config_blob",
"[",
"'config'",
"]",
"[",
"'Labels'",
"]",
"[",
"'release'",
"]",
"version",
"=",
"config_blob",
"[",
"'config'",
"]",
"[",
"'Labels'",
"]",
"[",
"'version'",
"]",
"docker_tag",
"=",
"\"%s-%s\"",
"%",
"(",
"version",
",",
"release",
")",
"image",
".",
"tag",
"=",
"docker_tag",
"manifest_list",
"=",
"get_manifest_list",
"(",
"image",
",",
"image",
".",
"registry",
",",
"insecure",
"=",
"self",
".",
"parent_registry_insecure",
",",
"dockercfg_path",
"=",
"self",
".",
"parent_registry_dockercfg_path",
")",
"self",
".",
"manifest_list_cache",
"[",
"image",
"]",
"=",
"manifest_list",
"return",
"self",
".",
"manifest_list_cache",
"[",
"image",
"]"
] |
Decorator to convert value from dbus type to python type . | def converter ( f ) : @ wraps ( f ) def wrapper ( * args , * * kwds ) : return convert ( f ( * args , * * kwds ) ) return wrapper | 5,031 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L80-L85 | [
"def",
"header_footer_exists",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
")",
"as",
"f",
":",
"return",
"re",
".",
"search",
"(",
"Utils",
".",
"exp",
",",
"f",
".",
"read",
"(",
")",
")"
] |
Decorator to convert dbus exception to pympris exception . | def exception_wrapper ( f ) : @ wraps ( f ) def wrapper ( * args , * * kwds ) : try : return f ( * args , * * kwds ) except dbus . exceptions . DBusException as err : _args = err . args raise PyMPRISException ( * _args ) return wrapper | 5,032 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L88-L97 | [
"def",
"serialize_non_framed_open",
"(",
"algorithm",
",",
"iv",
",",
"plaintext_length",
",",
"signer",
"=",
"None",
")",
":",
"body_start_format",
"=",
"(",
"\">\"",
"\"{iv_length}s\"",
"\"Q\"",
")",
".",
"format",
"(",
"iv_length",
"=",
"algorithm",
".",
"iv_len",
")",
"# nonce (IV) # content length",
"body_start",
"=",
"struct",
".",
"pack",
"(",
"body_start_format",
",",
"iv",
",",
"plaintext_length",
")",
"if",
"signer",
":",
"signer",
".",
"update",
"(",
"body_start",
")",
"return",
"body_start"
] |
Searchs and returns set of unique names of objects which implements MPRIS2 interfaces . | def available_players ( ) : bus = dbus . SessionBus ( ) players = set ( ) for name in filter ( lambda item : item . startswith ( MPRIS_NAME_PREFIX ) , bus . list_names ( ) ) : owner_name = bus . get_name_owner ( name ) players . add ( convert ( owner_name ) ) return players | 5,033 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L100-L113 | [
"def",
"update_task_redundancy",
"(",
"config",
",",
"task_id",
",",
"redundancy",
")",
":",
"if",
"task_id",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Are you sure you want to update all the tasks redundancy?\"",
")",
"if",
"click",
".",
"confirm",
"(",
"msg",
")",
":",
"res",
"=",
"_update_tasks_redundancy",
"(",
"config",
",",
"task_id",
",",
"redundancy",
")",
"click",
".",
"echo",
"(",
"res",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"Aborting.\"",
")",
"else",
":",
"res",
"=",
"_update_tasks_redundancy",
"(",
"config",
",",
"task_id",
",",
"redundancy",
")",
"click",
".",
"echo",
"(",
"res",
")"
] |
Decorator converts function s arguments from dbus types to python . | def signal_wrapper ( f ) : @ wraps ( f ) def wrapper ( * args , * * kwds ) : args = map ( convert , args ) kwds = { convert ( k ) : convert ( v ) for k , v in kwds . items ( ) } return f ( * args , * * kwds ) return wrapper | 5,034 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L124-L131 | [
"def",
"is_vert_aligned_center",
"(",
"c",
")",
":",
"return",
"all",
"(",
"[",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
".",
"sentence",
".",
"is_visual",
"(",
")",
"and",
"bbox_vert_aligned_center",
"(",
"bbox_from_span",
"(",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
")",
",",
"bbox_from_span",
"(",
"_to_span",
"(",
"c",
"[",
"0",
"]",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"c",
")",
")",
"]",
")"
] |
Filters signals by iface name . | def filter_properties_signals ( f , signal_iface_name ) : @ wraps ( f ) def wrapper ( iface , changed_props , invalidated_props , * args , * * kwargs ) : if iface == signal_iface_name : f ( changed_props , invalidated_props ) return wrapper | 5,035 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/common.py#L134-L145 | [
"def",
"render_article",
"(",
"request",
",",
"article",
",",
"current_language",
",",
"slug",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'article'",
"]",
"=",
"article",
"context",
"[",
"'lang'",
"]",
"=",
"current_language",
"context",
"[",
"'current_article'",
"]",
"=",
"article",
"context",
"[",
"'has_change_permissions'",
"]",
"=",
"article",
".",
"has_change_permission",
"(",
"request",
")",
"response",
"=",
"TemplateResponse",
"(",
"request",
",",
"article",
".",
"template",
",",
"context",
")",
"response",
".",
"add_post_render_callback",
"(",
"set_page_cache",
")",
"# Add headers for X Frame Options - this really should be changed upon moving to class based views",
"xframe_options",
"=",
"article",
".",
"tree",
".",
"get_xframe_options",
"(",
")",
"# xframe_options can be None if there's no xframe information on the page",
"# (eg. a top-level page which has xframe options set to \"inherit\")",
"if",
"xframe_options",
"==",
"Page",
".",
"X_FRAME_OPTIONS_INHERIT",
"or",
"xframe_options",
"is",
"None",
":",
"# This is when we defer to django's own clickjacking handling",
"return",
"response",
"# We want to prevent django setting this in their middlewear",
"response",
".",
"xframe_options_exempt",
"=",
"True",
"if",
"xframe_options",
"==",
"Page",
".",
"X_FRAME_OPTIONS_ALLOW",
":",
"# Do nothing, allowed is no header.",
"return",
"response",
"elif",
"xframe_options",
"==",
"Page",
".",
"X_FRAME_OPTIONS_SAMEORIGIN",
":",
"response",
"[",
"'X-Frame-Options'",
"]",
"=",
"'SAMEORIGIN'",
"elif",
"xframe_options",
"==",
"Page",
".",
"X_FRAME_OPTIONS_DENY",
":",
"response",
"[",
"'X-Frame-Options'",
"]",
"=",
"'DENY'",
"return",
"response"
] |
Returns pairs of matching indices from l1 and l2 . | def distance_function_match ( l1 , l2 , thresh , dist_fn , norm_funcs = [ ] ) : common = [ ] # We will keep track of the global index in the source list as we # will successively reduce their sizes. l1 = list ( enumerate ( l1 ) ) l2 = list ( enumerate ( l2 ) ) # Use the distance function and threshold on hints given by normalization. # See _match_by_norm_func for implementation details. # Also wrap the list element function function to ignore the global list # index computed above. for norm_fn in norm_funcs : new_common , l1 , l2 = _match_by_norm_func ( l1 , l2 , lambda a : norm_fn ( a [ 1 ] ) , lambda a1 , a2 : dist_fn ( a1 [ 1 ] , a2 [ 1 ] ) , thresh ) # Keep only the global list index in the end result. common . extend ( ( c1 [ 0 ] , c2 [ 0 ] ) for c1 , c2 in new_common ) # Take any remaining umatched entries and try to match them using the # Munkres algorithm. dist_matrix = [ [ dist_fn ( e1 , e2 ) for i2 , e2 in l2 ] for i1 , e1 in l1 ] # Call Munkres on connected components on the remaining bipartite graph. # An edge links an element from l1 with an element from l2 only if # the distance between the elements is less (or equal) than the theshold. components = BipartiteConnectedComponents ( ) for l1_i in range ( len ( l1 ) ) : for l2_i in range ( len ( l2 ) ) : if dist_matrix [ l1_i ] [ l2_i ] > thresh : continue components . add_edge ( l1_i , l2_i ) for l1_indices , l2_indices in components . get_connected_components ( ) : # Build a partial distance matrix for each connected component. part_l1 = [ l1 [ i ] for i in l1_indices ] part_l2 = [ l2 [ i ] for i in l2_indices ] part_dist_matrix = [ [ dist_matrix [ l1_i ] [ l2_i ] for l2_i in l2_indices ] for l1_i in l1_indices ] part_cmn = _match_munkres ( part_l1 , part_l2 , part_dist_matrix , thresh ) common . extend ( ( c1 [ 0 ] , c2 [ 0 ] ) for c1 , c2 in part_cmn ) return common | 5,036 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L30-L76 | [
"def",
"get_credentials",
"(",
"credentials",
"=",
"None",
",",
"client_secret_file",
"=",
"CLIENT_SECRET_FILE",
",",
"refresh_token",
"=",
"None",
")",
":",
"# if the utility was provided credentials just return those",
"if",
"credentials",
":",
"if",
"_is_valid_credentials",
"(",
"credentials",
")",
":",
"# auth for gspread",
"return",
"credentials",
"else",
":",
"print",
"(",
"\"Invalid credentials supplied. Will generate from default token.\"",
")",
"token",
"=",
"refresh_token",
"or",
"DEFAULT_TOKEN",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"DEFAULT_TOKEN",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"dir_name",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_name",
")",
":",
"raise",
"store",
"=",
"file",
".",
"Storage",
"(",
"token",
")",
"credentials",
"=",
"store",
".",
"get",
"(",
")",
"try",
":",
"import",
"argparse",
"flags",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"parents",
"=",
"[",
"tools",
".",
"argparser",
"]",
")",
".",
"parse_known_args",
"(",
")",
"[",
"0",
"]",
"except",
"ImportError",
":",
"flags",
"=",
"None",
"logr",
".",
"error",
"(",
"'Unable to parse oauth2client args; `pip install argparse`'",
")",
"if",
"not",
"credentials",
"or",
"credentials",
".",
"invalid",
":",
"flow",
"=",
"client",
".",
"flow_from_clientsecrets",
"(",
"client_secret_file",
",",
"SCOPES",
")",
"flow",
".",
"redirect_uri",
"=",
"client",
".",
"OOB_CALLBACK_URN",
"if",
"flags",
":",
"credentials",
"=",
"tools",
".",
"run_flow",
"(",
"flow",
",",
"store",
",",
"flags",
")",
"else",
":",
"# Needed only for compatability with Python 2.6",
"credentials",
"=",
"tools",
".",
"run",
"(",
"flow",
",",
"store",
")",
"logr",
".",
"info",
"(",
"'Storing credentials to '",
"+",
"DEFAULT_TOKEN",
")",
"return",
"credentials"
] |
Matches elements in l1 and l2 using normalization functions . | def _match_by_norm_func ( l1 , l2 , norm_fn , dist_fn , thresh ) : common = [ ] l1_only_idx = set ( range ( len ( l1 ) ) ) l2_only_idx = set ( range ( len ( l2 ) ) ) buckets_l1 = _group_by_fn ( enumerate ( l1 ) , lambda x : norm_fn ( x [ 1 ] ) ) buckets_l2 = _group_by_fn ( enumerate ( l2 ) , lambda x : norm_fn ( x [ 1 ] ) ) for normed , l1_elements in buckets_l1 . items ( ) : l2_elements = buckets_l2 . get ( normed , [ ] ) if not l1_elements or not l2_elements : continue _ , ( _ , e1_first ) = l1_elements [ 0 ] _ , ( _ , e2_first ) = l2_elements [ 0 ] match_is_ambiguous = not ( len ( l1_elements ) == len ( l2_elements ) and ( all ( e2 == e2_first for ( _ , ( _ , e2 ) ) in l2_elements ) or all ( e1 == e1_first for ( _ , ( _ , e1 ) ) in l1_elements ) ) ) if match_is_ambiguous : continue for ( e1_idx , e1 ) , ( e2_idx , e2 ) in zip ( l1_elements , l2_elements ) : if dist_fn ( e1 , e2 ) > thresh : continue l1_only_idx . remove ( e1_idx ) l2_only_idx . remove ( e2_idx ) common . append ( ( e1 , e2 ) ) l1_only = [ l1 [ i ] for i in l1_only_idx ] l2_only = [ l2 [ i ] for i in l2_only_idx ] return common , l1_only , l2_only | 5,037 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L79-L138 | [
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"-",
"1",
"message",
"=",
"super",
"(",
"AvroConsumer",
",",
"self",
")",
".",
"poll",
"(",
"timeout",
")",
"if",
"message",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"message",
".",
"error",
"(",
")",
":",
"try",
":",
"if",
"message",
".",
"value",
"(",
")",
"is",
"not",
"None",
":",
"decoded_value",
"=",
"self",
".",
"_serializer",
".",
"decode_message",
"(",
"message",
".",
"value",
"(",
")",
",",
"is_key",
"=",
"False",
")",
"message",
".",
"set_value",
"(",
"decoded_value",
")",
"if",
"message",
".",
"key",
"(",
")",
"is",
"not",
"None",
":",
"decoded_key",
"=",
"self",
".",
"_serializer",
".",
"decode_message",
"(",
"message",
".",
"key",
"(",
")",
",",
"is_key",
"=",
"True",
")",
"message",
".",
"set_key",
"(",
"decoded_key",
")",
"except",
"SerializerError",
"as",
"e",
":",
"raise",
"SerializerError",
"(",
"\"Message deserialization failed for message at {} [{}] offset {}: {}\"",
".",
"format",
"(",
"message",
".",
"topic",
"(",
")",
",",
"message",
".",
"partition",
"(",
")",
",",
"message",
".",
"offset",
"(",
")",
",",
"e",
")",
")",
"return",
"message"
] |
Matches two lists using the Munkres algorithm . | def _match_munkres ( l1 , l2 , dist_matrix , thresh ) : equal_dist_matches = set ( ) m = Munkres ( ) indices = m . compute ( dist_matrix ) for l1_idx , l2_idx in indices : dst = dist_matrix [ l1_idx ] [ l2_idx ] if dst > thresh : continue for eq_l2_idx , eq_val in enumerate ( dist_matrix [ l1_idx ] ) : if abs ( dst - eq_val ) < 1e-9 : equal_dist_matches . add ( ( l1_idx , eq_l2_idx ) ) for eq_l1_idx , eq_row in enumerate ( dist_matrix ) : if abs ( dst - eq_row [ l2_idx ] ) < 1e-9 : equal_dist_matches . add ( ( eq_l1_idx , l2_idx ) ) return [ ( l1 [ l1_idx ] , l2 [ l2_idx ] ) for l1_idx , l2_idx in equal_dist_matches ] | 5,038 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L141-L163 | [
"def",
"_ParsePage",
"(",
"self",
",",
"parser_mediator",
",",
"file_offset",
",",
"page_data",
")",
":",
"page_header_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'binarycookies_page_header'",
")",
"try",
":",
"page_header",
"=",
"self",
".",
"_ReadStructureFromByteStream",
"(",
"page_data",
",",
"file_offset",
",",
"page_header_map",
")",
"except",
"(",
"ValueError",
",",
"errors",
".",
"ParseError",
")",
"as",
"exception",
":",
"raise",
"errors",
".",
"ParseError",
"(",
"(",
"'Unable to map page header data at offset: 0x{0:08x} with error: '",
"'{1!s}'",
")",
".",
"format",
"(",
"file_offset",
",",
"exception",
")",
")",
"for",
"record_offset",
"in",
"page_header",
".",
"offsets",
":",
"if",
"parser_mediator",
".",
"abort",
":",
"break",
"self",
".",
"_ParseRecord",
"(",
"parser_mediator",
",",
"page_data",
",",
"record_offset",
")"
] |
Link a suspect to a case . | def add_suspect ( self , case_obj , variant_obj ) : new_suspect = Suspect ( case = case_obj , variant_id = variant_obj . variant_id , name = variant_obj . display_name ) self . session . add ( new_suspect ) self . save ( ) return new_suspect | 5,039 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/suspect.py#L10-L16 | [
"def",
"default_blockstack_api_opts",
"(",
"working_dir",
",",
"config_file",
"=",
"None",
")",
":",
"from",
".",
"util",
"import",
"url_to_host_port",
",",
"url_protocol",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"virtualchain",
".",
"get_config_filename",
"(",
"get_default_virtualchain_impl",
"(",
")",
",",
"working_dir",
")",
"parser",
"=",
"SafeConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"config_file",
")",
"blockstack_api_opts",
"=",
"{",
"}",
"indexer_url",
"=",
"None",
"api_port",
"=",
"DEFAULT_API_PORT",
"api_host",
"=",
"DEFAULT_API_HOST",
"run_api",
"=",
"True",
"if",
"parser",
".",
"has_section",
"(",
"'blockstack-api'",
")",
":",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'enabled'",
")",
":",
"run_api",
"=",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'enabled'",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'true'",
",",
"'1'",
",",
"'on'",
"]",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'api_port'",
")",
":",
"api_port",
"=",
"int",
"(",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'api_port'",
")",
")",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'api_host'",
")",
":",
"api_host",
"=",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'api_host'",
")",
"if",
"parser",
".",
"has_option",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
":",
"indexer_host",
",",
"indexer_port",
"=",
"url_to_host_port",
"(",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
")",
"indexer_protocol",
"=",
"url_protocol",
"(",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
")",
"if",
"indexer_protocol",
"is",
"None",
":",
"indexer_protocol",
"=",
"'http'",
"indexer_url",
"=",
"parser",
".",
"get",
"(",
"'blockstack-api'",
",",
"'indexer_url'",
")",
"if",
"indexer_url",
"is",
"None",
":",
"# try defaults",
"indexer_url",
"=",
"'http://localhost:{}'",
".",
"format",
"(",
"RPC_SERVER_PORT",
")",
"blockstack_api_opts",
"=",
"{",
"'indexer_url'",
":",
"indexer_url",
",",
"'api_host'",
":",
"api_host",
",",
"'api_port'",
":",
"api_port",
",",
"'enabled'",
":",
"run_api",
"}",
"# strip Nones",
"for",
"(",
"k",
",",
"v",
")",
"in",
"blockstack_api_opts",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"del",
"blockstack_api_opts",
"[",
"k",
"]",
"return",
"blockstack_api_opts"
] |
De - link a suspect from a case . | def delete_suspect ( self , suspect_id ) : suspect_obj = self . suspect ( suspect_id ) logger . debug ( "Deleting suspect {0}" . format ( suspect_obj . name ) ) self . session . delete ( suspect_obj ) self . save ( ) | 5,040 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/suspect.py#L22-L27 | [
"async",
"def",
"oauth2_request",
"(",
"self",
",",
"url",
":",
"str",
",",
"access_token",
":",
"str",
"=",
"None",
",",
"post_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"*",
"*",
"args",
":",
"Any",
")",
"->",
"Any",
":",
"all_args",
"=",
"{",
"}",
"if",
"access_token",
":",
"all_args",
"[",
"\"access_token\"",
"]",
"=",
"access_token",
"all_args",
".",
"update",
"(",
"args",
")",
"if",
"all_args",
":",
"url",
"+=",
"\"?\"",
"+",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"all_args",
")",
"http",
"=",
"self",
".",
"get_auth_http_client",
"(",
")",
"if",
"post_args",
"is",
"not",
"None",
":",
"response",
"=",
"await",
"http",
".",
"fetch",
"(",
"url",
",",
"method",
"=",
"\"POST\"",
",",
"body",
"=",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"post_args",
")",
")",
"else",
":",
"response",
"=",
"await",
"http",
".",
"fetch",
"(",
"url",
")",
"return",
"escape",
".",
"json_decode",
"(",
"response",
".",
"body",
")"
] |
Configure root logger using a standard stream handler . | def configure_stream ( level = 'WARNING' ) : # get the root logger root_logger = logging . getLogger ( ) # set the logger level to the same as will be used by the handler root_logger . setLevel ( level ) # customize formatter, align each column template = "[%(asctime)s] %(name)-25s %(levelname)-8s %(message)s" formatter = logging . Formatter ( template ) # add a basic STDERR handler to the logger console = logging . StreamHandler ( ) console . setLevel ( level ) console . setFormatter ( formatter ) root_logger . addHandler ( console ) return root_logger | 5,041 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/log.py#L7-L31 | [
"def",
"time_func",
"(",
"func",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"out",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"toc",
"=",
"time",
".",
"time",
"(",
")",
"print",
"(",
"'%s took %0.2f seconds'",
"%",
"(",
"name",
",",
"toc",
"-",
"tic",
")",
")",
"return",
"out"
] |
Testing if we try to collect an object of the same type as root . This is not really a good sign because it means that we are going to collect a whole new tree that will maybe collect a new tree that will ... | def _is_same_type_as_root ( self , obj ) : if not self . ALLOWS_SAME_TYPE_AS_ROOT_COLLECT : obj_model = get_model_from_instance ( obj ) obj_key = get_key_from_instance ( obj ) is_same_type_as_root = obj_model == self . root_obj_model and obj_key != self . root_obj_key if is_same_type_as_root : self . emit_event ( type = 'same_type_as_root' , obj = obj ) return is_same_type_as_root else : return False | 5,042 | https://github.com/iwoca/django-deep-collector/blob/1bd599d5362ade525cb51d6ee70713a3f58af219/deep_collector/core.py#L203-L219 | [
"def",
"Write",
"(",
"self",
",",
"Text",
")",
":",
"self",
".",
"Application",
".",
"_Alter",
"(",
"'WRITE'",
",",
"'%s %s'",
"%",
"(",
"self",
".",
"Handle",
",",
"tounicode",
"(",
"Text",
")",
")",
")"
] |
initialize variable from loaded data | def initialize ( self , data ) : for item in data : if hasattr ( self , item ) : setattr ( self , item , data [ item ] ) | 5,043 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/media_status.py#L57-L61 | [
"def",
"match_template",
"(",
"template",
",",
"image",
",",
"options",
"=",
"None",
")",
":",
"# If the input has max of 3 channels, use the faster OpenCV matching",
"if",
"len",
"(",
"image",
".",
"shape",
")",
"<=",
"3",
"and",
"image",
".",
"shape",
"[",
"2",
"]",
"<=",
"3",
":",
"return",
"match_template_opencv",
"(",
"template",
",",
"image",
",",
"options",
")",
"op",
"=",
"_DEF_TM_OPT",
".",
"copy",
"(",
")",
"if",
"options",
"is",
"not",
"None",
":",
"op",
".",
"update",
"(",
"options",
")",
"template",
"=",
"img_utils",
".",
"gray3",
"(",
"template",
")",
"image",
"=",
"img_utils",
".",
"gray3",
"(",
"image",
")",
"h",
",",
"w",
",",
"d",
"=",
"template",
".",
"shape",
"im_h",
",",
"im_w",
"=",
"image",
".",
"shape",
"[",
":",
"2",
"]",
"template_v",
"=",
"template",
".",
"flatten",
"(",
")",
"heatmap",
"=",
"np",
".",
"zeros",
"(",
"(",
"im_h",
"-",
"h",
",",
"im_w",
"-",
"w",
")",
")",
"for",
"col",
"in",
"range",
"(",
"0",
",",
"im_w",
"-",
"w",
")",
":",
"for",
"row",
"in",
"range",
"(",
"0",
",",
"im_h",
"-",
"h",
")",
":",
"cropped_im",
"=",
"image",
"[",
"row",
":",
"row",
"+",
"h",
",",
"col",
":",
"col",
"+",
"w",
",",
":",
"]",
"cropped_v",
"=",
"cropped_im",
".",
"flatten",
"(",
")",
"if",
"op",
"[",
"'distance'",
"]",
"==",
"'euclidean'",
":",
"heatmap",
"[",
"row",
",",
"col",
"]",
"=",
"scipy",
".",
"spatial",
".",
"distance",
".",
"euclidean",
"(",
"template_v",
",",
"cropped_v",
")",
"elif",
"op",
"[",
"'distance'",
"]",
"==",
"'correlation'",
":",
"heatmap",
"[",
"row",
",",
"col",
"]",
"=",
"scipy",
".",
"spatial",
".",
"distance",
".",
"correlation",
"(",
"template_v",
",",
"cropped_v",
")",
"# normalize",
"if",
"op",
"[",
"'normalize'",
"]",
":",
"heatmap",
"/=",
"heatmap",
".",
"max",
"(",
")",
"# size",
"if",
"op",
"[",
"'retain_size'",
"]",
":",
"hmap",
"=",
"np",
".",
"ones",
"(",
"image",
".",
"shape",
"[",
":",
"2",
"]",
")",
"*",
"heatmap",
".",
"max",
"(",
")",
"h",
",",
"w",
"=",
"heatmap",
".",
"shape",
"hmap",
"[",
":",
"h",
",",
":",
"w",
"]",
"=",
"heatmap",
"heatmap",
"=",
"hmap",
"return",
"heatmap"
] |
Return all transcripts sound in the vcf file | def _add_transcripts ( self , variant_obj , info_dict ) : vep_string = info_dict . get ( 'CSQ' ) #Check if snpeff annotation: snpeff_string = info_dict . get ( 'ANN' ) # We check one of these. # VEP has presedence over snpeff if vep_string : #Get the vep annotations vep_info = get_vep_info ( vep_string = vep_string , vep_header = self . vep_header ) for transcript_info in vep_info : transcript = self . _get_vep_transcript ( transcript_info ) variant_obj . add_transcript ( transcript ) elif snpeff_string : #Get the vep annotations snpeff_info = get_snpeff_info ( snpeff_string = snpeff_string , snpeff_header = self . snpeff_header ) for transcript_info in snpeff_info : transcript = self . _get_snpeff_transcript ( transcript_info ) variant_obj . add_transcript ( transcript ) | 5,044 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/vcf/mixins/variant_extras/transcripts.py#L9-L36 | [
"def",
"getTotalAssociations",
"(",
"self",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wifi",
".",
"getServiceType",
"(",
"\"getTotalAssociations\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetTotalAssociations\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"int",
"(",
"results",
"[",
"\"NewTotalAssociations\"",
"]",
")"
] |
Create a Transcript based on the vep annotation | def _get_vep_transcript ( self , transcript_info ) : transcript = Transcript ( hgnc_symbol = transcript_info . get ( 'SYMBOL' ) , transcript_id = transcript_info . get ( 'Feature' ) , ensembl_id = transcript_info . get ( 'Gene' ) , biotype = transcript_info . get ( 'BIOTYPE' ) , consequence = transcript_info . get ( 'Consequence' ) , strand = transcript_info . get ( 'STRAND' ) , sift = transcript_info . get ( 'SIFT' ) , polyphen = transcript_info . get ( 'PolyPhen' ) , exon = transcript_info . get ( 'EXON' ) , HGVSc = transcript_info . get ( 'HGVSc' ) , HGVSp = transcript_info . get ( 'HGVSp' ) , GMAF = transcript_info . get ( 'GMAF' ) , ExAC_MAF = transcript_info . get ( 'ExAC_MAF' ) ) return transcript | 5,045 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/vcf/mixins/variant_extras/transcripts.py#L39-L63 | [
"def",
"saturation",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"clean_float",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"unit_moisture_weight",
"=",
"self",
".",
"unit_moist_weight",
"-",
"self",
".",
"unit_dry_weight",
"unit_moisture_volume",
"=",
"unit_moisture_weight",
"/",
"self",
".",
"_pw",
"saturation",
"=",
"unit_moisture_volume",
"/",
"self",
".",
"_calc_unit_void_volume",
"(",
")",
"if",
"saturation",
"is",
"not",
"None",
"and",
"not",
"ct",
".",
"isclose",
"(",
"saturation",
",",
"value",
",",
"rel_tol",
"=",
"self",
".",
"_tolerance",
")",
":",
"raise",
"ModelError",
"(",
"\"New saturation (%.3f) is inconsistent \"",
"\"with calculated value (%.3f)\"",
"%",
"(",
"value",
",",
"saturation",
")",
")",
"except",
"TypeError",
":",
"pass",
"old_value",
"=",
"self",
".",
"saturation",
"self",
".",
"_saturation",
"=",
"value",
"try",
":",
"self",
".",
"recompute_all_weights_and_void",
"(",
")",
"self",
".",
"_add_to_stack",
"(",
"\"saturation\"",
",",
"value",
")",
"except",
"ModelError",
"as",
"e",
":",
"self",
".",
"_saturation",
"=",
"old_value",
"raise",
"ModelError",
"(",
"e",
")"
] |
Create a transcript based on the snpeff annotation | def _get_snpeff_transcript ( self , transcript_info ) : transcript = Transcript ( hgnc_symbol = transcript_info . get ( 'Gene_Name' ) , transcript_id = transcript_info . get ( 'Feature' ) , ensembl_id = transcript_info . get ( 'Gene_ID' ) , biotype = transcript_info . get ( 'Transcript_BioType' ) , consequence = transcript_info . get ( 'Annotation' ) , exon = transcript_info . get ( 'Rank' ) , HGVSc = transcript_info . get ( 'HGVS.c' ) , HGVSp = transcript_info . get ( 'HGVS.p' ) ) return transcript | 5,046 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/vcf/mixins/variant_extras/transcripts.py#L65-L84 | [
"def",
"select_color",
"(",
"cpcolor",
",",
"evalcolor",
",",
"idx",
"=",
"0",
")",
":",
"# Random colors by default",
"color",
"=",
"utilities",
".",
"color_generator",
"(",
")",
"# Constant color for control points grid",
"if",
"isinstance",
"(",
"cpcolor",
",",
"str",
")",
":",
"color",
"[",
"0",
"]",
"=",
"cpcolor",
"# User-defined color for control points grid",
"if",
"isinstance",
"(",
"cpcolor",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"color",
"[",
"0",
"]",
"=",
"cpcolor",
"[",
"idx",
"]",
"# Constant color for evaluated points grid",
"if",
"isinstance",
"(",
"evalcolor",
",",
"str",
")",
":",
"color",
"[",
"1",
"]",
"=",
"evalcolor",
"# User-defined color for evaluated points grid",
"if",
"isinstance",
"(",
"evalcolor",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"color",
"[",
"1",
"]",
"=",
"evalcolor",
"[",
"idx",
"]",
"return",
"color"
] |
A decorator that returns a clone of the current object so that we can re - use the object for similar requests . | def _makes_clone ( _func , * args , * * kw ) : self = args [ 0 ] . _clone ( ) _func ( self , * args [ 1 : ] , * * kw ) return self | 5,047 | https://github.com/tswicegood/Dolt/blob/e0da1918b7db18f885734a89f824b9e173cc30a5/dolt/__init__.py#L22-L29 | [
"def",
"_set_exit_timeout",
"(",
"self",
",",
"timeout",
",",
"reason",
")",
":",
"self",
".",
"_exit_timeout_start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_exit_timeout",
"=",
"timeout",
"self",
".",
"_exit_reason",
"=",
"reason"
] |
Deserializes JSON if the content - type matches otherwise returns the response body as is . | def _handle_response ( self , response , data ) : # Content-Type headers can include additional parameters(RFC 1521), so # we split on ; to match against only the type/subtype if data and response . get ( 'content-type' , '' ) . split ( ';' ) [ 0 ] in ( 'application/json' , 'application/x-javascript' , 'text/javascript' , 'text/x-javascript' , 'text/x-json' ) : return json . loads ( data ) else : return data | 5,048 | https://github.com/tswicegood/Dolt/blob/e0da1918b7db18f885734a89f824b9e173cc30a5/dolt/__init__.py#L80-L96 | [
"def",
"spkopa",
"(",
"filename",
")",
":",
"filename",
"=",
"stypes",
".",
"stringToCharP",
"(",
"filename",
")",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"spkopa_c",
"(",
"filename",
",",
"ctypes",
".",
"byref",
"(",
"handle",
")",
")",
"return",
"handle",
".",
"value"
] |
Returns the URL for this request . | def get_url ( self , * paths , * * params ) : path_stack = self . _attribute_stack [ : ] if paths : path_stack . extend ( paths ) u = self . _stack_collapser ( path_stack ) url = self . _url_template % { "domain" : self . _api_url , "generated_url" : u , } if self . _params or params : internal_params = self . _params . copy ( ) internal_params . update ( params ) url += self . _generate_params ( internal_params ) return url | 5,049 | https://github.com/tswicegood/Dolt/blob/e0da1918b7db18f885734a89f824b9e173cc30a5/dolt/__init__.py#L222-L244 | [
"def",
"get_partition_trees",
"(",
"self",
",",
"p",
")",
":",
"trees",
"=",
"[",
"]",
"for",
"grp",
"in",
"p",
".",
"get_membership",
"(",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"get_group_result",
"(",
"grp",
")",
"trees",
".",
"append",
"(",
"result",
"[",
"'ml_tree'",
"]",
")",
"except",
"ValueError",
":",
"trees",
".",
"append",
"(",
"None",
")",
"logger",
".",
"error",
"(",
"'No tree found for group {}'",
".",
"format",
"(",
"grp",
")",
")",
"return",
"trees"
] |
Clones the state of the current operation . | def _clone ( self ) : cls = self . __class__ q = cls . __new__ ( cls ) q . __dict__ = self . __dict__ . copy ( ) q . _params = self . _params . copy ( ) q . _headers = self . _headers . copy ( ) q . _attribute_stack = self . _attribute_stack [ : ] return q | 5,050 | https://github.com/tswicegood/Dolt/blob/e0da1918b7db18f885734a89f824b9e173cc30a5/dolt/__init__.py#L246-L271 | [
"def",
"update_webhook",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"api",
"=",
"self",
".",
"_get_api",
"(",
"mds",
".",
"NotificationsApi",
")",
"# Delete notifications channel",
"api",
".",
"delete_long_poll_channel",
"(",
")",
"# Send the request to register the webhook",
"webhook_obj",
"=",
"WebhookData",
"(",
"url",
"=",
"url",
",",
"headers",
"=",
"headers",
")",
"api",
".",
"register_webhook",
"(",
"webhook_obj",
")",
"return"
] |
Delete a case or individual from the database . | def delete ( ctx , family_id , individual_id , root ) : root = root or ctx . obj . get ( 'root' ) or os . path . expanduser ( "~/.puzzle" ) if os . path . isfile ( root ) : logger . error ( "'root' can't be a file" ) ctx . abort ( ) logger . info ( "Root directory is: {}" . format ( root ) ) db_path = os . path . join ( root , 'puzzle_db.sqlite3' ) logger . info ( "db path is: {}" . format ( db_path ) ) if not os . path . exists ( db_path ) : logger . warn ( "database not initialized, run 'puzzle init'" ) ctx . abort ( ) store = SqlStore ( db_path ) if family_id : case_obj = store . case ( case_id = family_id ) if case_obj is None : logger . warning ( "Family {0} does not exist in database" . format ( family_id ) ) ctx . abort ( ) store . delete_case ( case_obj ) elif individual_id : ind_obj = store . individual ( ind_id = individual_id ) if ind_obj . ind_id != individual_id : logger . warning ( "Individual {0} does not exist in database" . format ( individual_id ) ) ctx . abort ( ) store . delete_individual ( ind_obj ) else : logger . warning ( "Please provide a family or individual id" ) ctx . abort ( ) | 5,051 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/cli/delete.py#L18-L57 | [
"def",
"update_cluster",
"(",
"cluster_ref",
",",
"cluster_spec",
")",
":",
"cluster_name",
"=",
"get_managed_object_name",
"(",
"cluster_ref",
")",
"log",
".",
"trace",
"(",
"'Updating cluster \\'%s\\''",
",",
"cluster_name",
")",
"try",
":",
"task",
"=",
"cluster_ref",
".",
"ReconfigureComputeResource_Task",
"(",
"cluster_spec",
",",
"modify",
"=",
"True",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"wait_for_task",
"(",
"task",
",",
"cluster_name",
",",
"'ClusterUpdateTask'",
")"
] |
Show all variants for a case . | def variants ( case_id ) : filters = parse_filters ( ) values = [ value for key , value in iteritems ( filters ) if not isinstance ( value , dict ) and key != 'skip' ] is_active = any ( values ) variants , nr_of_variants = app . db . variants ( case_id , skip = filters [ 'skip' ] , filters = { 'gene_ids' : filters [ 'gene_symbols' ] , 'frequency' : filters . get ( 'frequency' ) , 'cadd' : filters . get ( 'cadd' ) , 'sv_len' : filters . get ( 'sv_len' ) , 'consequence' : filters [ 'selected_consequences' ] , 'genetic_models' : filters [ 'selected_models' ] , 'sv_types' : filters [ 'selected_sv_types' ] , 'gene_lists' : filters [ 'gene_lists' ] , 'impact_severities' : filters [ 'impact_severities' ] , 'gemini_query' : filters [ 'gemini_query' ] , 'range' : filters [ 'range' ] , } ) gene_lists = ( [ gene_list . list_id for gene_list in app . db . gene_lists ( ) ] if app . config [ 'STORE_ENABLED' ] else [ ] ) queries = ( [ ( query . name or query . query , query . query ) for query in app . db . gemini_queries ( ) ] if app . config [ 'STORE_ENABLED' ] else [ ] ) kwargs = dict ( variants = variants , case_id = case_id , db = app . db , filters = filters , consequences = SO_TERMS , inheritance_models = INHERITANCE_MODELS_SHORT , gene_lists = gene_lists , impact_severities = IMPACT_LEVELS , is_active = is_active , nr_of_variants = nr_of_variants , queries = queries ) if app . db . variant_type == 'sv' : return render_template ( 'sv_variants.html' , sv_types = SV_TYPES , * * kwargs ) else : return render_template ( 'variants.html' , * * kwargs ) | 5,052 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/variants/views.py#L16-L54 | [
"def",
"setOverlayTransformTrackedDeviceRelative",
"(",
"self",
",",
"ulOverlayHandle",
",",
"unTrackedDevice",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTransformTrackedDeviceRelative",
"pmatTrackedDeviceToOverlayTransform",
"=",
"HmdMatrix34_t",
"(",
")",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"unTrackedDevice",
",",
"byref",
"(",
"pmatTrackedDeviceToOverlayTransform",
")",
")",
"return",
"result",
",",
"pmatTrackedDeviceToOverlayTransform"
] |
Show a single variant . | def variant ( case_id , variant_id ) : case_obj = app . db . case ( case_id ) variant = app . db . variant ( case_id , variant_id ) if variant is None : return abort ( 404 , "variant not found" ) comments = app . db . comments ( variant_id = variant . md5 ) template = 'sv_variant.html' if app . db . variant_type == 'sv' else 'variant.html' return render_template ( template , variant = variant , case_id = case_id , comments = comments , case = case_obj ) | 5,053 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/variants/views.py#L58-L68 | [
"def",
"_connect",
"(",
"self",
")",
":",
"try",
":",
"# Open Connection",
"self",
".",
"influx",
"=",
"InfluxDBClient",
"(",
"self",
".",
"hostname",
",",
"self",
".",
"port",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
",",
"self",
".",
"database",
",",
"self",
".",
"ssl",
")",
"# Log",
"self",
".",
"log",
".",
"debug",
"(",
"\"InfluxdbHandler: Established connection to \"",
"\"%s:%d/%s.\"",
",",
"self",
".",
"hostname",
",",
"self",
".",
"port",
",",
"self",
".",
"database",
")",
"except",
"Exception",
"as",
"ex",
":",
"# Log Error",
"self",
".",
"_throttle_error",
"(",
"\"InfluxdbHandler: Failed to connect to \"",
"\"%s:%d/%s. %s\"",
",",
"self",
".",
"hostname",
",",
"self",
".",
"port",
",",
"self",
".",
"database",
",",
"ex",
")",
"# Close Socket",
"self",
".",
"_close",
"(",
")",
"return"
] |
Parse variant filters from the request object . | def parse_filters ( ) : genes_str = request . args . get ( 'gene_symbol' ) filters = { } for key in ( 'frequency' , 'cadd' , 'sv_len' ) : try : filters [ key ] = float ( request . args . get ( key ) ) except ( ValueError , TypeError ) : pass filters [ 'gene_symbols' ] = genes_str . split ( ',' ) if genes_str else None filters [ 'selected_models' ] = request . args . getlist ( 'inheritance_models' ) filters [ 'selected_consequences' ] = request . args . getlist ( 'consequences' ) filters [ 'selected_sv_types' ] = request . args . getlist ( 'sv_types' ) filters [ 'skip' ] = int ( request . args . get ( 'skip' , 0 ) ) filters [ 'gene_lists' ] = request . args . getlist ( 'gene_lists' ) filters [ 'gemini_query' ] = ( request . args . get ( 'gemini_query' ) or request . args . get ( 'preset_gemini_query' ) ) filters [ 'impact_severities' ] = request . args . getlist ( 'impact_severities' ) filters [ 'range' ] = None if request . args . get ( 'range' ) : chromosome , raw_pos = request . args . get ( 'range' ) . split ( ':' ) start , end = map ( int , raw_pos . split ( '-' ) ) filters [ 'range' ] = { 'chromosome' : chromosome , 'start' : start , 'end' : end } filters [ 'query_dict' ] = { key : request . args . getlist ( key ) for key in request . args . keys ( ) } filters [ 'query_dict' ] . update ( { 'skip' : ( filters [ 'skip' ] + 30 ) } ) return filters | 5,054 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/variants/views.py#L71-L102 | [
"def",
"create_option_group",
"(",
"name",
",",
"engine_name",
",",
"major_engine_version",
",",
"option_group_description",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"res",
"=",
"__salt__",
"[",
"'boto_rds.option_group_exists'",
"]",
"(",
"name",
",",
"tags",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
"if",
"res",
".",
"get",
"(",
"'exists'",
")",
":",
"return",
"{",
"'exists'",
":",
"bool",
"(",
"res",
")",
"}",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"conn",
":",
"return",
"{",
"'results'",
":",
"bool",
"(",
"conn",
")",
"}",
"taglist",
"=",
"_tag_doc",
"(",
"tags",
")",
"rds",
"=",
"conn",
".",
"create_option_group",
"(",
"OptionGroupName",
"=",
"name",
",",
"EngineName",
"=",
"engine_name",
",",
"MajorEngineVersion",
"=",
"major_engine_version",
",",
"OptionGroupDescription",
"=",
"option_group_description",
",",
"Tags",
"=",
"taglist",
")",
"return",
"{",
"'exists'",
":",
"bool",
"(",
"rds",
")",
"}",
"except",
"ClientError",
"as",
"e",
":",
"return",
"{",
"'error'",
":",
"__utils__",
"[",
"'boto3.get_error'",
"]",
"(",
"e",
")",
"}"
] |
Pin a variant as a suspect for a given case . | def suspects ( case_id , variant_id ) : case_obj = app . db . case ( case_id ) variant_obj = app . db . variant ( case_id , variant_id ) app . db . add_suspect ( case_obj , variant_obj ) return redirect ( request . referrer ) | 5,055 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/variants/views.py#L106-L111 | [
"def",
"save",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"_to_dict",
"(",
")",
"if",
"len",
"(",
"d",
".",
"get",
"(",
"'videoIds'",
",",
"[",
"]",
")",
")",
">",
"0",
":",
"if",
"not",
"self",
".",
"id",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_playlist'",
",",
"playlist",
"=",
"d",
")",
"else",
":",
"data",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'update_playlist'",
",",
"playlist",
"=",
"d",
")",
"if",
"data",
":",
"self",
".",
"_load",
"(",
"data",
")"
] |
Store a new GEMINI query . | def queries ( ) : query = request . form [ 'query' ] name = request . form . get ( 'name' ) app . db . add_gemini_query ( name , query ) return redirect ( request . referrer ) | 5,056 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/variants/views.py#L122-L127 | [
"def",
"transport_meta_data",
"(",
"self",
")",
":",
"# For each packet in the pcap process the contents",
"for",
"item",
"in",
"self",
".",
"input_stream",
":",
"# Get the transport data and type",
"trans_data",
"=",
"item",
"[",
"'packet'",
"]",
"[",
"'data'",
"]",
"trans_type",
"=",
"self",
".",
"_get_transport_type",
"(",
"trans_data",
")",
"if",
"trans_type",
"and",
"trans_data",
":",
"item",
"[",
"'transport'",
"]",
"=",
"data_utils",
".",
"make_dict",
"(",
"trans_data",
")",
"item",
"[",
"'transport'",
"]",
"[",
"'type'",
"]",
"=",
"trans_type",
"item",
"[",
"'transport'",
"]",
"[",
"'flags'",
"]",
"=",
"self",
".",
"_readable_flags",
"(",
"item",
"[",
"'transport'",
"]",
")",
"item",
"[",
"'transport'",
"]",
"[",
"'data'",
"]",
"=",
"trans_data",
"[",
"'data'",
"]",
"# All done",
"yield",
"item"
] |
Parse the contents of the ~io . IOBase . readline - supporting file - like object fp as a simple line - oriented . properties file and return a dict of the key - value pairs . | def load ( fp , object_pairs_hook = dict ) : return object_pairs_hook ( ( k , v ) for k , v , _ in parse ( fp ) if k is not None ) | 5,057 | https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/reading.py#L6-L36 | [
"def",
"validate_contribution",
"(",
"the_con",
")",
":",
"passing",
"=",
"True",
"for",
"dtype",
"in",
"list",
"(",
"the_con",
".",
"tables",
".",
"keys",
"(",
")",
")",
":",
"print",
"(",
"\"validating {}\"",
".",
"format",
"(",
"dtype",
")",
")",
"fail",
"=",
"validate_table",
"(",
"the_con",
",",
"dtype",
")",
"if",
"fail",
":",
"passing",
"=",
"False",
"print",
"(",
"'--'",
")"
] |
Parse the contents of the string s as a simple line - oriented . properties file and return a dict of the key - value pairs . | def loads ( s , object_pairs_hook = dict ) : fp = BytesIO ( s ) if isinstance ( s , binary_type ) else StringIO ( s ) return load ( fp , object_pairs_hook = object_pairs_hook ) | 5,058 | https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/reading.py#L38-L66 | [
"def",
"convert_adc",
"(",
"value",
",",
"output_type",
",",
"max_volts",
")",
":",
"return",
"{",
"const",
".",
"ADC_RAW",
":",
"lambda",
"x",
":",
"x",
",",
"const",
".",
"ADC_PERCENTAGE",
":",
"adc_to_percentage",
",",
"const",
".",
"ADC_VOLTS",
":",
"adc_to_volts",
",",
"const",
".",
"ADC_MILLIVOLTS",
":",
"adc_to_millivolts",
"}",
"[",
"output_type",
"]",
"(",
"value",
",",
"max_volts",
")"
] |
Extracts a single clip according to audioClipSpec . | def _extractClipData ( self , audioClipSpec , showLogs = False ) : command = [ self . _ffmpegPath ] if not showLogs : command += [ '-nostats' , '-loglevel' , '0' ] command += [ '-i' , self . _audioFilePath , '-ss' , '%.3f' % audioClipSpec . start , '-t' , '%.3f' % audioClipSpec . duration ( ) , '-c' , 'copy' , '-map' , '0' , '-acodec' , 'libmp3lame' , '-ab' , '128k' , '-f' , 'mp3' ] # Add clip TEXT as metadata and set a few more to default metadata = { self . _textMetadataName : audioClipSpec . text } for k , v in metadata . items ( ) : command . append ( '-metadata' ) command . append ( "{}='{}'" . format ( k , v ) ) command . append ( 'pipe:1' ) return subprocess . check_output ( command ) | 5,059 | https://github.com/TiagoBras/audio-clip-extractor/blob/b0dd90266656dcbf7e663b3e174dce4d09e74c32/audioclipextractor/core.py#L82-L114 | [
"def",
"import_organizations",
"(",
"self",
",",
"parser",
",",
"overwrite",
"=",
"False",
")",
":",
"orgs",
"=",
"parser",
".",
"organizations",
"for",
"org",
"in",
"orgs",
":",
"try",
":",
"api",
".",
"add_organization",
"(",
"self",
".",
"db",
",",
"org",
".",
"name",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"RuntimeError",
"(",
"str",
"(",
"e",
")",
")",
"except",
"AlreadyExistsError",
"as",
"e",
":",
"pass",
"for",
"dom",
"in",
"org",
".",
"domains",
":",
"try",
":",
"api",
".",
"add_domain",
"(",
"self",
".",
"db",
",",
"org",
".",
"name",
",",
"dom",
".",
"domain",
",",
"is_top_domain",
"=",
"dom",
".",
"is_top_domain",
",",
"overwrite",
"=",
"overwrite",
")",
"self",
".",
"display",
"(",
"'load_domains.tmpl'",
",",
"domain",
"=",
"dom",
".",
"domain",
",",
"organization",
"=",
"org",
".",
"name",
")",
"except",
"(",
"ValueError",
",",
"NotFoundError",
")",
"as",
"e",
":",
"raise",
"RuntimeError",
"(",
"str",
"(",
"e",
")",
")",
"except",
"AlreadyExistsError",
"as",
"e",
":",
"msg",
"=",
"\"%s. Not updated.\"",
"%",
"str",
"(",
"e",
")",
"self",
".",
"warning",
"(",
"msg",
")"
] |
Add a phenotype term to the case . | def add_phenotype ( self , ind_obj , phenotype_id ) : if phenotype_id . startswith ( 'HP:' ) or len ( phenotype_id ) == 7 : logger . debug ( 'querying on HPO term' ) hpo_results = phizz . query_hpo ( [ phenotype_id ] ) else : logger . debug ( 'querying on OMIM term' ) hpo_results = phizz . query_disease ( [ phenotype_id ] ) added_terms = [ ] if hpo_results else None existing_ids = set ( term . phenotype_id for term in ind_obj . phenotypes ) for result in hpo_results : if result [ 'hpo_term' ] not in existing_ids : term = PhenotypeTerm ( phenotype_id = result [ 'hpo_term' ] , description = result [ 'description' ] ) logger . info ( 'adding new HPO term: %s' , term . phenotype_id ) ind_obj . phenotypes . append ( term ) added_terms . append ( term ) logger . debug ( 'storing new HPO terms' ) self . save ( ) if added_terms is not None and len ( added_terms ) > 0 : for case_obj in ind_obj . cases : self . update_hpolist ( case_obj ) return added_terms | 5,060 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/phenotype.py#L13-L39 | [
"def",
"free",
"(",
"self",
",",
"local_path",
")",
":",
"# Process local ~~~",
"# 1. Syncthing config",
"config",
"=",
"self",
".",
"get_config",
"(",
")",
"# Check whether folders are still connected to this device ",
"folder",
"=",
"st_util",
".",
"find_folder_with_path",
"(",
"local_path",
",",
"config",
")",
"self",
".",
"delete_folder",
"(",
"local_path",
",",
"config",
")",
"pruned",
"=",
"st_util",
".",
"prune_devices",
"(",
"folder",
",",
"config",
")",
"# Done processing st config, commit :)",
"self",
".",
"set_config",
"(",
"config",
")",
"if",
"pruned",
":",
"self",
".",
"restart",
"(",
")",
"# 2. App config",
"dir_config",
"=",
"self",
".",
"adapter",
".",
"get_dir_config",
"(",
"local_path",
")",
"if",
"not",
"dir_config",
":",
"raise",
"custom_errors",
".",
"FileNotInConfig",
"(",
"local_path",
")",
"kodrive_config",
"=",
"self",
".",
"adapter",
".",
"get_config",
"(",
")",
"for",
"key",
"in",
"kodrive_config",
"[",
"'directories'",
"]",
":",
"d",
"=",
"kodrive_config",
"[",
"'directories'",
"]",
"[",
"key",
"]",
"if",
"d",
"[",
"'local_path'",
"]",
".",
"rstrip",
"(",
"'/'",
")",
"==",
"local_path",
".",
"rstrip",
"(",
"'/'",
")",
":",
"del",
"kodrive_config",
"[",
"'directories'",
"]",
"[",
"key",
"]",
"break",
"# Done process app config, commit :)",
"self",
".",
"adapter",
".",
"set_config",
"(",
"kodrive_config",
")",
"# If the folder was shared, try remove data from remote ",
"if",
"dir_config",
"[",
"'is_shared'",
"]",
"and",
"dir_config",
"[",
"'server'",
"]",
":",
"# Process remote ~~~",
"r_api_key",
"=",
"dir_config",
"[",
"'api_key'",
"]",
"r_device_id",
"=",
"dir_config",
"[",
"'device_id'",
"]",
"if",
"dir_config",
"[",
"'host'",
"]",
":",
"host",
"=",
"dir_config",
"[",
"'host'",
"]",
"else",
":",
"host",
"=",
"self",
".",
"devid_to_ip",
"(",
"r_device_id",
",",
"False",
")",
"try",
":",
"# Create remote proxy to interact with remote",
"remote",
"=",
"SyncthingProxy",
"(",
"r_device_id",
",",
"host",
",",
"r_api_key",
",",
"port",
"=",
"dir_config",
"[",
"'port'",
"]",
"if",
"'port'",
"in",
"dir_config",
"else",
"None",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"True",
"r_config",
"=",
"remote",
".",
"get_config",
"(",
")",
"r_folder",
"=",
"st_util",
".",
"find_folder_with_path",
"(",
"dir_config",
"[",
"'remote_path'",
"]",
",",
"r_config",
")",
"# Delete device id from folder",
"r_config",
"=",
"remote",
".",
"get_config",
"(",
")",
"self_devid",
"=",
"self",
".",
"get_device_id",
"(",
")",
"del_device",
"=",
"remote",
".",
"delete_device_from_folder",
"(",
"dir_config",
"[",
"'remote_path'",
"]",
",",
"self_devid",
",",
"r_config",
")",
"# Check to see if no other folder depends has this device",
"pruned",
"=",
"st_util",
".",
"prune_devices",
"(",
"r_folder",
",",
"r_config",
")",
"remote",
".",
"set_config",
"(",
"r_config",
")",
"if",
"pruned",
":",
"remote",
".",
"restart",
"(",
")",
"return",
"True"
] |
Update the HPO gene list for a case based on current terms . | def update_hpolist ( self , case_obj ) : hpo_list = self . case_genelist ( case_obj ) hpo_results = hpo_genes ( case_obj . phenotype_ids ( ) , * self . phenomizer_auth ) if hpo_results is None : pass # Why raise here? # raise RuntimeError("couldn't link to genes, try again") else : gene_ids = [ result [ 'gene_id' ] for result in hpo_results if result [ 'gene_id' ] ] hpo_list . gene_ids = gene_ids self . save ( ) | 5,061 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/phenotype.py#L41-L55 | [
"async",
"def",
"metadata_verify",
"(",
"config",
",",
"args",
")",
"->",
"int",
":",
"all_package_files",
"=",
"[",
"]",
"# type: List[Path]",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"mirror_base",
"=",
"config",
".",
"get",
"(",
"\"mirror\"",
",",
"\"directory\"",
")",
"json_base",
"=",
"Path",
"(",
"mirror_base",
")",
"/",
"\"web\"",
"/",
"\"json\"",
"workers",
"=",
"args",
".",
"workers",
"or",
"config",
".",
"getint",
"(",
"\"mirror\"",
",",
"\"workers\"",
")",
"executor",
"=",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"workers",
")",
"logger",
".",
"info",
"(",
"f\"Starting verify for {mirror_base} with {workers} workers\"",
")",
"try",
":",
"json_files",
"=",
"await",
"loop",
".",
"run_in_executor",
"(",
"executor",
",",
"os",
".",
"listdir",
",",
"json_base",
")",
"except",
"FileExistsError",
"as",
"fee",
":",
"logger",
".",
"error",
"(",
"f\"Metadata base dir {json_base} does not exist: {fee}\"",
")",
"return",
"2",
"if",
"not",
"json_files",
":",
"logger",
".",
"error",
"(",
"\"No JSON metadata files found. Can not verify\"",
")",
"return",
"3",
"logger",
".",
"debug",
"(",
"f\"Found {len(json_files)} objects in {json_base}\"",
")",
"logger",
".",
"debug",
"(",
"f\"Using a {workers} thread ThreadPoolExecutor\"",
")",
"await",
"async_verify",
"(",
"config",
",",
"all_package_files",
",",
"mirror_base",
",",
"json_files",
",",
"args",
",",
"executor",
")",
"if",
"not",
"args",
".",
"delete",
":",
"return",
"0",
"return",
"await",
"delete_files",
"(",
"mirror_base",
",",
"executor",
",",
"all_package_files",
",",
"args",
".",
"dry_run",
")"
] |
Remove multiple phenotypes from an individual . | def remove_phenotype ( self , ind_obj , phenotypes = None ) : if phenotypes is None : logger . info ( "delete all phenotypes related to %s" , ind_obj . ind_id ) self . query ( PhenotypeTerm ) . filter_by ( ind_id = ind_obj . id ) . delete ( ) else : for term in ind_obj . phenotypes : if term . phenotype_id in phenotypes : logger . info ( "delete phenotype: %s from %s" , term . phenotype_id , ind_obj . ind_id ) self . session . delete ( term ) logger . debug ( 'persist removals' ) self . save ( ) for case_obj in ind_obj . cases : self . update_hpolist ( case_obj ) | 5,062 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/phenotype.py#L57-L71 | [
"def",
"handle",
"(",
"self",
",",
"error",
",",
"connection",
")",
":",
"error_class",
"=",
"error",
".",
"__class__",
"if",
"error_class",
"in",
"(",
"ConnectionExpired",
",",
"ServiceUnavailable",
",",
"DatabaseUnavailableError",
")",
":",
"self",
".",
"deactivate",
"(",
"connection",
".",
"address",
")",
"elif",
"error_class",
"in",
"(",
"NotALeaderError",
",",
"ForbiddenOnReadOnlyDatabaseError",
")",
":",
"self",
".",
"remove_writer",
"(",
"connection",
".",
"address",
")"
] |
>>> from Redy . ADT . Core import match data P >>> from Redy . ADT . traits import ConsInd Discrete >>> | def match ( mode_lst : list , obj : 'object that has __destruct__ method' ) : # noinspection PyUnresolvedReferences try : # noinspection PyUnresolvedReferences structure = obj . __destruct__ ( ) except AttributeError : return False n = len ( mode_lst ) if n > len ( structure ) : return False for i in range ( n ) : mode = mode_lst [ i ] # noinspection PyUnresolvedReferences elem = obj [ i ] if isinstance ( mode , PatternList ) : if not match ( mode , elem ) : return False elif mode is P : # noinspection PyUnresolvedReferences mode_lst [ i ] = elem elif mode is any : pass elif mode != elem : return False return True | 5,063 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/ADT/Core.py#L185-L227 | [
"def",
"ubridge",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ubridge_hypervisor",
"and",
"not",
"self",
".",
"_ubridge_hypervisor",
".",
"is_running",
"(",
")",
":",
"self",
".",
"_ubridge_hypervisor",
"=",
"None",
"return",
"self",
".",
"_ubridge_hypervisor"
] |
Return a gemini query | def gemini_query ( self , query_id ) : logger . debug ( "Looking for query with id {0}" . format ( query_id ) ) return self . query ( GeminiQuery ) . filter_by ( id = query_id ) . first ( ) | 5,064 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/gemini.py#L10-L17 | [
"def",
"translateprotocolmask",
"(",
"protocol",
")",
":",
"pcscprotocol",
"=",
"0",
"if",
"None",
"!=",
"protocol",
":",
"if",
"CardConnection",
".",
"T0_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T0",
"if",
"CardConnection",
".",
"T1_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T1",
"if",
"CardConnection",
".",
"RAW_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_RAW",
"if",
"CardConnection",
".",
"T15_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T15",
"return",
"pcscprotocol"
] |
Add a user defined gemini query | def add_gemini_query ( self , name , query ) : logger . info ( "Adding query {0} with text {1}" . format ( name , query ) ) new_query = GeminiQuery ( name = name , query = query ) self . session . add ( new_query ) self . save ( ) return new_query | 5,065 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/gemini.py#L23-L34 | [
"def",
"getAmountOfHostsConnected",
"(",
"self",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"getAmountOfHostsConnected\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetHostNumberOfEntries\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"int",
"(",
"results",
"[",
"\"NewHostNumberOfEntries\"",
"]",
")"
] |
Delete a gemini query | def delete_gemini_query ( self , query_id ) : query_obj = self . gemini_query ( query_id ) logger . debug ( "Delete query: {0}" . format ( query_obj . name_query ) ) self . session . delete ( query_obj ) self . save ( ) | 5,066 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/gemini.py#L36-L45 | [
"def",
"translateprotocolmask",
"(",
"protocol",
")",
":",
"pcscprotocol",
"=",
"0",
"if",
"None",
"!=",
"protocol",
":",
"if",
"CardConnection",
".",
"T0_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T0",
"if",
"CardConnection",
".",
"T1_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T1",
"if",
"CardConnection",
".",
"RAW_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_RAW",
"if",
"CardConnection",
".",
"T15_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T15",
"return",
"pcscprotocol"
] |
Calculate distance in miles or kilometers between current and other passed point . | def distance_to ( self , point , unit = 'km' ) : assert isinstance ( point , GeoPoint ) , ( 'Other point should also be a Point instance.' ) if self == point : return 0.0 coefficient = 69.09 theta = self . longitude - point . longitude unit = unit . lower ( ) if unit else None distance = math . degrees ( math . acos ( math . sin ( self . rad_latitude ) * math . sin ( point . rad_latitude ) + math . cos ( self . rad_latitude ) * math . cos ( point . rad_latitude ) * math . cos ( math . radians ( theta ) ) ) ) * coefficient if unit == 'km' : return utils . mi_to_km ( distance ) return distance | 5,067 | https://github.com/gusdan/geoindex/blob/d1b3b5a52271200713a64041576caa1f2d588f55/geoindex/geo_point.py#L49-L72 | [
"async",
"def",
"_wait_exponentially",
"(",
"self",
",",
"exception",
",",
"max_wait_time",
"=",
"300",
")",
":",
"wait_time",
"=",
"min",
"(",
"(",
"2",
"**",
"self",
".",
"_connection_attempts",
")",
"+",
"random",
".",
"random",
"(",
")",
",",
"max_wait_time",
")",
"try",
":",
"wait_time",
"=",
"exception",
".",
"response",
"[",
"\"headers\"",
"]",
"[",
"\"Retry-After\"",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"pass",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Waiting %s seconds before reconnecting.\"",
",",
"wait_time",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"float",
"(",
"wait_time",
")",
")"
] |
Lazy conversion degrees latitude to radians . | def rad_latitude ( self ) : if self . _rad_latitude is None : self . _rad_latitude = math . radians ( self . latitude ) return self . _rad_latitude | 5,068 | https://github.com/gusdan/geoindex/blob/d1b3b5a52271200713a64041576caa1f2d588f55/geoindex/geo_point.py#L75-L81 | [
"def",
"getShocks",
"(",
"self",
")",
":",
"PersistentShockConsumerType",
".",
"getShocks",
"(",
"self",
")",
"# Get permanent and transitory income shocks",
"MedShkNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"# Initialize medical shock array",
"MedPriceNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"# Initialize relative price array",
"for",
"t",
"in",
"range",
"(",
"self",
".",
"T_cycle",
")",
":",
"these",
"=",
"t",
"==",
"self",
".",
"t_cycle",
"N",
"=",
"np",
".",
"sum",
"(",
"these",
")",
"if",
"N",
">",
"0",
":",
"MedShkAvg",
"=",
"self",
".",
"MedShkAvg",
"[",
"t",
"]",
"MedShkStd",
"=",
"self",
".",
"MedShkStd",
"[",
"t",
"]",
"MedPrice",
"=",
"self",
".",
"MedPrice",
"[",
"t",
"]",
"MedShkNow",
"[",
"these",
"]",
"=",
"self",
".",
"RNG",
".",
"permutation",
"(",
"approxLognormal",
"(",
"N",
",",
"mu",
"=",
"np",
".",
"log",
"(",
"MedShkAvg",
")",
"-",
"0.5",
"*",
"MedShkStd",
"**",
"2",
",",
"sigma",
"=",
"MedShkStd",
")",
"[",
"1",
"]",
")",
"MedPriceNow",
"[",
"these",
"]",
"=",
"MedPrice",
"self",
".",
"MedShkNow",
"=",
"MedShkNow",
"self",
".",
"MedPriceNow",
"=",
"MedPriceNow"
] |
Lazy conversion degrees longitude to radians . | def rad_longitude ( self ) : if self . _rad_longitude is None : self . _rad_longitude = math . radians ( self . longitude ) return self . _rad_longitude | 5,069 | https://github.com/gusdan/geoindex/blob/d1b3b5a52271200713a64041576caa1f2d588f55/geoindex/geo_point.py#L84-L90 | [
"def",
"getShocks",
"(",
"self",
")",
":",
"PersistentShockConsumerType",
".",
"getShocks",
"(",
"self",
")",
"# Get permanent and transitory income shocks",
"MedShkNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"# Initialize medical shock array",
"MedPriceNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"# Initialize relative price array",
"for",
"t",
"in",
"range",
"(",
"self",
".",
"T_cycle",
")",
":",
"these",
"=",
"t",
"==",
"self",
".",
"t_cycle",
"N",
"=",
"np",
".",
"sum",
"(",
"these",
")",
"if",
"N",
">",
"0",
":",
"MedShkAvg",
"=",
"self",
".",
"MedShkAvg",
"[",
"t",
"]",
"MedShkStd",
"=",
"self",
".",
"MedShkStd",
"[",
"t",
"]",
"MedPrice",
"=",
"self",
".",
"MedPrice",
"[",
"t",
"]",
"MedShkNow",
"[",
"these",
"]",
"=",
"self",
".",
"RNG",
".",
"permutation",
"(",
"approxLognormal",
"(",
"N",
",",
"mu",
"=",
"np",
".",
"log",
"(",
"MedShkAvg",
")",
"-",
"0.5",
"*",
"MedShkStd",
"**",
"2",
",",
"sigma",
"=",
"MedShkStd",
")",
"[",
"1",
"]",
")",
"MedPriceNow",
"[",
"these",
"]",
"=",
"MedPrice",
"self",
".",
"MedShkNow",
"=",
"MedShkNow",
"self",
".",
"MedPriceNow",
"=",
"MedPriceNow"
] |
Write an Erlang term to an output stream . | def send ( term , stream ) : payload = erlang . term_to_binary ( term ) header = struct . pack ( '!I' , len ( payload ) ) stream . write ( header ) stream . write ( payload ) stream . flush ( ) | 5,070 | https://github.com/okeuday/erlang_py/blob/81b7c2ace66b6bdee23602a6802efff541223fa3/examples/port.py#L6-L12 | [
"def",
"set_default_cwc",
"(",
"self",
",",
"section",
",",
"option_header",
"=",
"None",
",",
"cwc",
"=",
"[",
"'50'",
",",
"'70'",
",",
"'90'",
"]",
")",
":",
"if",
"option_header",
"is",
"None",
":",
"header",
"=",
"''",
"else",
":",
"header",
"=",
"option_header",
"+",
"'_'",
"self",
".",
"set_default",
"(",
"section",
",",
"header",
"+",
"'careful'",
",",
"cwc",
"[",
"0",
"]",
")",
"self",
".",
"set_default",
"(",
"section",
",",
"header",
"+",
"'warning'",
",",
"cwc",
"[",
"1",
"]",
")",
"self",
".",
"set_default",
"(",
"section",
",",
"header",
"+",
"'critical'",
",",
"cwc",
"[",
"2",
"]",
")"
] |
Read an Erlang term from an input stream . | def recv ( stream ) : header = stream . read ( 4 ) if len ( header ) != 4 : return None # EOF ( length , ) = struct . unpack ( '!I' , header ) payload = stream . read ( length ) if len ( payload ) != length : return None term = erlang . binary_to_term ( payload ) return term | 5,071 | https://github.com/okeuday/erlang_py/blob/81b7c2ace66b6bdee23602a6802efff541223fa3/examples/port.py#L14-L24 | [
"def",
"remove_not_allowed_chars",
"(",
"savepath",
")",
":",
"split_savepath",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"savepath",
")",
"# https://msdn.microsoft.com/en-us/library/aa365247.aspx",
"savepath_without_invalid_chars",
"=",
"re",
".",
"sub",
"(",
"r'<|>|:|\\\"|\\||\\?|\\*'",
",",
"'_'",
",",
"split_savepath",
"[",
"1",
"]",
")",
"return",
"split_savepath",
"[",
"0",
"]",
"+",
"savepath_without_invalid_chars"
] |
Yield Erlang terms from an input stream . | def recv_loop ( stream ) : message = recv ( stream ) while message : yield message message = recv ( stream ) | 5,072 | https://github.com/okeuday/erlang_py/blob/81b7c2ace66b6bdee23602a6802efff541223fa3/examples/port.py#L26-L31 | [
"def",
"fix_auth_url_version_prefix",
"(",
"auth_url",
")",
":",
"auth_url",
"=",
"_augment_url_with_version",
"(",
"auth_url",
")",
"url_fixed",
"=",
"False",
"if",
"get_keystone_version",
"(",
")",
">=",
"3",
"and",
"has_in_url_path",
"(",
"auth_url",
",",
"[",
"\"/v2.0\"",
"]",
")",
":",
"url_fixed",
"=",
"True",
"auth_url",
"=",
"url_path_replace",
"(",
"auth_url",
",",
"\"/v2.0\"",
",",
"\"/v3\"",
",",
"1",
")",
"return",
"auth_url",
",",
"url_fixed"
] |
Add the genotype calls for the variant | def _add_genotype_calls ( self , variant_obj , variant_line , case_obj ) : variant_line = variant_line . split ( '\t' ) #if there is gt calls we have no individuals to add if len ( variant_line ) > 8 : gt_format = variant_line [ 8 ] . split ( ':' ) for individual in case_obj . individuals : sample_id = individual . ind_id index = individual . ind_index gt_call = variant_line [ 9 + index ] . split ( ':' ) raw_call = dict ( zip ( gt_format , gt_call ) ) genotype = Genotype ( * * raw_call ) variant_obj . add_individual ( puzzle_genotype ( sample_id = sample_id , genotype = genotype . genotype , case_id = case_obj . name , phenotype = individual . phenotype , ref_depth = genotype . ref_depth , alt_depth = genotype . alt_depth , genotype_quality = genotype . genotype_quality , depth = genotype . depth_of_coverage , supporting_evidence = genotype . supporting_evidence , pe_support = genotype . pe_support , sr_support = genotype . sr_support , ) ) | 5,073 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/vcf/mixins/variant_extras/genotype.py#L12-L47 | [
"def",
"process_config",
"(",
"config",
",",
"config_data",
")",
":",
"if",
"'components'",
"in",
"config_data",
":",
"process_components_config_section",
"(",
"config",
",",
"config_data",
"[",
"'components'",
"]",
")",
"if",
"'data'",
"in",
"config_data",
":",
"process_data_config_section",
"(",
"config",
",",
"config_data",
"[",
"'data'",
"]",
")",
"if",
"'log'",
"in",
"config_data",
":",
"process_log_config_section",
"(",
"config",
",",
"config_data",
"[",
"'log'",
"]",
")",
"if",
"'management'",
"in",
"config_data",
":",
"process_management_config_section",
"(",
"config",
",",
"config_data",
"[",
"'management'",
"]",
")",
"if",
"'session'",
"in",
"config_data",
":",
"process_session_config_section",
"(",
"config",
",",
"config_data",
"[",
"'session'",
"]",
")"
] |
Returns a new conflict with a prepended prefix as a path . | def with_prefix ( self , root_path ) : return Conflict ( self . conflict_type , root_path + self . path , self . body ) | 5,074 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/conflict.py#L95-L97 | [
"def",
"get_datasource",
"(",
"name",
",",
"orgname",
"=",
"None",
",",
"profile",
"=",
"'grafana'",
")",
":",
"data",
"=",
"get_datasources",
"(",
"orgname",
"=",
"orgname",
",",
"profile",
"=",
"profile",
")",
"for",
"datasource",
"in",
"data",
":",
"if",
"datasource",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"datasource",
"return",
"None"
] |
Deserializes conflict to a JSON object . | def to_json ( self ) : # map ConflictType to json-patch operator path = self . path if self . conflict_type in ( 'REORDER' , 'SET_FIELD' ) : op = 'replace' elif self . conflict_type in ( 'MANUAL_MERGE' , 'ADD_BACK_TO_HEAD' ) : op = 'add' path += ( '-' , ) elif self . conflict_type == 'REMOVE_FIELD' : op = 'remove' else : raise ValueError ( 'Conflict Type %s can not be mapped to a json-patch operation' % conflict_type ) # stringify path array json_pointer = '/' + '/' . join ( str ( el ) for el in path ) conflict_values = force_list ( self . body ) conflicts = [ ] for value in conflict_values : if value is not None or self . conflict_type == 'REMOVE_FIELD' : conflicts . append ( { 'path' : json_pointer , 'op' : op , 'value' : value , '$type' : self . conflict_type } ) return json . dumps ( conflicts ) | 5,075 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/conflict.py#L99-L139 | [
"def",
"remover",
"(",
"self",
",",
"id_user_group",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_user_group",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Invalid or inexistent user group id.'",
")",
"url",
"=",
"'ugroup/'",
"+",
"str",
"(",
"id_user_group",
")",
"+",
"'/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'DELETE'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] |
Write a series of key - value pairs to a file in simple line - oriented . properties format . | def dump ( props , fp , separator = '=' , comments = None , timestamp = True , sort_keys = False ) : if comments is not None : print ( to_comment ( comments ) , file = fp ) if timestamp is not None and timestamp is not False : print ( to_comment ( java_timestamp ( timestamp ) ) , file = fp ) for k , v in itemize ( props , sort_keys = sort_keys ) : print ( join_key_value ( k , v , separator ) , file = fp ) | 5,076 | https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/writing.py#L10-L45 | [
"def",
"delete_table",
"(",
"self",
",",
"table",
")",
":",
"response",
"=",
"self",
".",
"layer1",
".",
"delete_table",
"(",
"table",
".",
"name",
")",
"table",
".",
"update_from_response",
"(",
"response",
")"
] |
Convert a series of key - value pairs to a text string in simple line - oriented . properties format . | def dumps ( props , separator = '=' , comments = None , timestamp = True , sort_keys = False ) : s = StringIO ( ) dump ( props , s , separator = separator , comments = comments , timestamp = timestamp , sort_keys = sort_keys ) return s . getvalue ( ) | 5,077 | https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/writing.py#L47-L77 | [
"def",
"validate_submission",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_prepare_temp_dir",
"(",
")",
"# Convert filename to be absolute path, relative path might cause problems",
"# with mounting directory in Docker",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"# extract submission",
"if",
"not",
"self",
".",
"_extract_submission",
"(",
"filename",
")",
":",
"return",
"None",
"# verify submission size",
"if",
"not",
"self",
".",
"_verify_submission_size",
"(",
")",
":",
"return",
"None",
"# Load metadata",
"metadata",
"=",
"self",
".",
"_load_and_verify_metadata",
"(",
")",
"if",
"not",
"metadata",
":",
"return",
"None",
"submission_type",
"=",
"metadata",
"[",
"'type'",
"]",
"# verify docker container size",
"if",
"not",
"self",
".",
"_verify_docker_image_size",
"(",
"metadata",
"[",
"'container_gpu'",
"]",
")",
":",
"return",
"None",
"# Try to run submission on sample data",
"self",
".",
"_prepare_sample_data",
"(",
"submission_type",
")",
"if",
"not",
"self",
".",
"_run_submission",
"(",
"metadata",
")",
":",
"logging",
".",
"error",
"(",
"'Failure while running submission'",
")",
"return",
"None",
"if",
"not",
"self",
".",
"_verify_output",
"(",
"submission_type",
")",
":",
"logging",
".",
"warning",
"(",
"'Some of the outputs of your submission are invalid or '",
"'missing. You submission still will be evaluation '",
"'but you might get lower score.'",
")",
"return",
"metadata"
] |
r Join a key and value together into a single line suitable for adding to a simple line - oriented . properties file . No trailing newline is added . | def join_key_value ( key , value , separator = '=' ) : # Escapes `key` and `value` the same way as java.util.Properties.store() return escape ( key ) + separator + re . sub ( r'^ +' , lambda m : r'\ ' * m . end ( ) , _base_escape ( value ) ) | 5,078 | https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/writing.py#L99-L120 | [
"def",
"RefreshClaims",
"(",
"self",
",",
"ids",
",",
"timeout",
"=",
"\"30m\"",
")",
":",
"with",
"data_store",
".",
"DB",
".",
"GetMutationPool",
"(",
")",
"as",
"mutation_pool",
":",
"mutation_pool",
".",
"QueueRefreshClaims",
"(",
"ids",
",",
"timeout",
"=",
"timeout",
")"
] |
Gets a set of playlists . | def GetPlaylists ( self , start , max_count , order , reversed ) : cv = convert2dbus return self . iface . GetPlaylists ( cv ( start , 'u' ) , cv ( max_count , 'u' ) , cv ( order , 's' ) , cv ( reversed , 'b' ) ) | 5,079 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/PlayLists.py#L58-L71 | [
"def",
"set_scale",
"(",
"self",
",",
"scale",
")",
":",
"register",
"=",
"self",
".",
"MMA8452Q_Register",
"[",
"'XYZ_DATA_CFG'",
"]",
"self",
".",
"board",
".",
"i2c_read_request",
"(",
"self",
".",
"address",
",",
"register",
",",
"1",
",",
"Constants",
".",
"I2C_READ",
"|",
"Constants",
".",
"I2C_END_TX_MASK",
",",
"self",
".",
"data_val",
",",
"Constants",
".",
"CB_TYPE_DIRECT",
")",
"config_reg",
"=",
"self",
".",
"wait_for_read_result",
"(",
")",
"config_reg",
"=",
"config_reg",
"[",
"self",
".",
"data_start",
"]",
"config_reg",
"&=",
"0xFC",
"# Mask out scale bits",
"config_reg",
"|=",
"(",
"scale",
">>",
"2",
")",
"self",
".",
"board",
".",
"i2c_write_request",
"(",
"self",
".",
"address",
",",
"[",
"register",
",",
"config_reg",
"]",
")"
] |
Initializes the Flask application with this extension . It grabs the necessary configuration values from app . config those being HASHING_METHOD and HASHING_ROUNDS . HASHING_METHOD defaults to sha256 but can be any one of hashlib . algorithms . HASHING_ROUNDS specifies the number of times to hash the input with the specified algorithm . This defaults to 1 . | def init_app ( self , app ) : self . algorithm = app . config . get ( 'HASHING_METHOD' , 'sha256' ) if self . algorithm not in algs : raise ValueError ( '{} not one of {}' . format ( self . algorithm , algs ) ) self . rounds = app . config . get ( 'HASHING_ROUNDS' , 1 ) if not isinstance ( self . rounds , int ) : raise TypeError ( 'HASHING_ROUNDS must be type int' ) | 5,080 | https://github.com/ThaWeatherman/flask-hashing/blob/e2cc8526569f63362e2d79bea49c4809d4416c8a/flask_hashing.py#L62-L77 | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_closed",
"and",
"not",
"self",
".",
"_owned",
":",
"self",
".",
"_dispose",
"(",
")",
"finally",
":",
"self",
".",
"detach",
"(",
")"
] |
Hashes the specified value combined with the specified salt . The hash is done HASHING_ROUNDS times as specified by the application configuration . | def hash_value ( self , value , salt = '' ) : def hashit ( value , salt ) : h = hashlib . new ( self . algorithm ) tgt = salt + value h . update ( tgt ) return h . hexdigest ( ) def fix_unicode ( value ) : if VER < 3 and isinstance ( value , unicode ) : value = str ( value ) elif VER >= 3 and isinstance ( value , str ) : value = str . encode ( value ) return value salt = fix_unicode ( salt ) for i in range ( self . rounds ) : value = fix_unicode ( value ) value = hashit ( value , salt ) return value | 5,081 | https://github.com/ThaWeatherman/flask-hashing/blob/e2cc8526569f63362e2d79bea49c4809d4416c8a/flask_hashing.py#L79-L111 | [
"def",
"unfollow_user",
"(",
"self",
",",
"user",
",",
"delegate",
")",
":",
"parser",
"=",
"txml",
".",
"Users",
"(",
"delegate",
")",
"return",
"self",
".",
"__postPage",
"(",
"'/friendships/destroy/%s.xml'",
"%",
"(",
"user",
")",
",",
"parser",
")"
] |
Checks the specified hash value against the hash of the provided salt and value . | def check_value ( self , value_hash , value , salt = '' ) : h = self . hash_value ( value , salt = salt ) return h == value_hash | 5,082 | https://github.com/ThaWeatherman/flask-hashing/blob/e2cc8526569f63362e2d79bea49c4809d4416c8a/flask_hashing.py#L113-L130 | [
"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",
")",
")"
] |
Adds a URI in the TrackList . | def AddTrack ( self , uri , after_track , set_as_current ) : self . iface . AddTrack ( uri , convert2dbus ( after_track , 'o' ) , convert2dbus ( set_as_current , 'b' ) ) | 5,083 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/TrackList.py#L48-L59 | [
"def",
"variable_matrix",
"(",
"variables",
":",
"VarType",
",",
"parent",
":",
"str",
"=",
"None",
",",
"iterator",
":",
"str",
"=",
"\"product\"",
")",
"->",
"Iterable",
"[",
"Dict",
"[",
"str",
",",
"YamlValue",
"]",
"]",
":",
"_iters",
":",
"Dict",
"[",
"str",
",",
"Callable",
"]",
"=",
"{",
"\"product\"",
":",
"product",
",",
"\"zip\"",
":",
"zip",
"}",
"_special_keys",
":",
"Dict",
"[",
"str",
",",
"Callable",
"[",
"[",
"VarType",
",",
"Any",
"]",
",",
"Iterable",
"[",
"VarMatrix",
"]",
"]",
"]",
"=",
"{",
"\"zip\"",
":",
"iterator_zip",
",",
"\"product\"",
":",
"iterator_product",
",",
"\"arange\"",
":",
"iterator_arange",
",",
"\"chain\"",
":",
"iterator_chain",
",",
"\"append\"",
":",
"iterator_chain",
",",
"\"cycle\"",
":",
"iterator_cycle",
",",
"\"repeat\"",
":",
"iterator_cycle",
",",
"}",
"if",
"isinstance",
"(",
"variables",
",",
"dict",
")",
":",
"key_vars",
":",
"List",
"[",
"List",
"[",
"Dict",
"[",
"str",
",",
"YamlValue",
"]",
"]",
"]",
"=",
"[",
"]",
"# Handling of specialised iterators",
"for",
"key",
",",
"function",
"in",
"_special_keys",
".",
"items",
"(",
")",
":",
"if",
"variables",
".",
"get",
"(",
"key",
")",
":",
"item",
"=",
"variables",
"[",
"key",
"]",
"assert",
"item",
"is",
"not",
"None",
"for",
"val",
"in",
"function",
"(",
"item",
",",
"parent",
")",
":",
"key_vars",
".",
"append",
"(",
"val",
")",
"del",
"variables",
"[",
"key",
"]",
"for",
"key",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"key_vars",
".",
"append",
"(",
"list",
"(",
"variable_matrix",
"(",
"value",
",",
"key",
",",
"iterator",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"key vars: %s\"",
",",
"key_vars",
")",
"# Iterate through all possible products generating a dictionary",
"for",
"i",
"in",
"_iters",
"[",
"iterator",
"]",
"(",
"*",
"key_vars",
")",
":",
"logger",
".",
"debug",
"(",
"\"dicts: %s\"",
",",
"i",
")",
"yield",
"combine_dictionaries",
"(",
"i",
")",
"# Iterate through a list of values",
"elif",
"isinstance",
"(",
"variables",
",",
"list",
")",
":",
"for",
"item",
"in",
"variables",
":",
"yield",
"from",
"variable_matrix",
"(",
"item",
",",
"parent",
",",
"iterator",
")",
"# Stopping condition -> we have either a single value from a list",
"# or a value had only one item",
"else",
":",
"assert",
"parent",
"is",
"not",
"None",
"yield",
"{",
"parent",
":",
"variables",
"}"
] |
Delete one or more gene ids form the list . | def delete_gene ( self , * gene_ids ) : self . gene_ids = [ gene_id for gene_id in self . gene_ids if gene_id not in gene_ids ] | 5,084 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/models/sql/genelist.py#L44-L47 | [
"def",
"_mmUpdateDutyCycles",
"(",
"self",
")",
":",
"period",
"=",
"self",
".",
"getDutyCyclePeriod",
"(",
")",
"unionSDRArray",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"getNumColumns",
"(",
")",
")",
"unionSDRArray",
"[",
"list",
"(",
"self",
".",
"_mmTraces",
"[",
"\"unionSDR\"",
"]",
".",
"data",
"[",
"-",
"1",
"]",
")",
"]",
"=",
"1",
"self",
".",
"_mmData",
"[",
"\"unionSDRDutyCycle\"",
"]",
"=",
"UnionTemporalPoolerMonitorMixin",
".",
"_mmUpdateDutyCyclesHelper",
"(",
"self",
".",
"_mmData",
"[",
"\"unionSDRDutyCycle\"",
"]",
",",
"unionSDRArray",
",",
"period",
")",
"self",
".",
"_mmData",
"[",
"\"persistenceDutyCycle\"",
"]",
"=",
"UnionTemporalPoolerMonitorMixin",
".",
"_mmUpdateDutyCyclesHelper",
"(",
"self",
".",
"_mmData",
"[",
"\"persistenceDutyCycle\"",
"]",
",",
"self",
".",
"_poolingActivation",
",",
"period",
")"
] |
Check state of update timer . | def healthy_update_timer ( self ) : state = None if self . update_status_timer and self . update_status_timer . is_alive ( ) : _LOGGER . debug ( "Timer: healthy" ) state = True else : _LOGGER . debug ( "Timer: not healthy" ) state = False return state | 5,085 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L71-L82 | [
"def",
"render_cvmfs_pvc",
"(",
"cvmfs_volume",
")",
":",
"name",
"=",
"CVMFS_REPOSITORIES",
"[",
"cvmfs_volume",
"]",
"rendered_template",
"=",
"dict",
"(",
"REANA_CVMFS_PVC_TEMPLATE",
")",
"rendered_template",
"[",
"'metadata'",
"]",
"[",
"'name'",
"]",
"=",
"'csi-cvmfs-{}-pvc'",
".",
"format",
"(",
"name",
")",
"rendered_template",
"[",
"'spec'",
"]",
"[",
"'storageClassName'",
"]",
"=",
"\"csi-cvmfs-{}\"",
".",
"format",
"(",
"name",
")",
"return",
"rendered_template"
] |
initialize the object | def initialize ( self ) : self . network_status = self . get_network_status ( ) self . name = self . network_status . get ( 'network_name' , 'Unknown' ) self . location_info = self . get_location_info ( ) self . device_info = self . get_device_info ( ) self . device_id = ( self . device_info . get ( 'device_id' ) if self . device_info else "Unknown" ) self . initialize_socket ( ) self . initialize_worker ( ) self . initialize_zones ( ) | 5,086 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L84-L95 | [
"def",
"create",
"(",
"*",
"*",
"kwargs",
")",
":",
"secType",
"=",
"kwargs",
".",
"get",
"(",
"'secType'",
",",
"''",
")",
"cls",
"=",
"{",
"''",
":",
"Contract",
",",
"'STK'",
":",
"Stock",
",",
"'OPT'",
":",
"Option",
",",
"'FUT'",
":",
"Future",
",",
"'CONTFUT'",
":",
"ContFuture",
",",
"'CASH'",
":",
"Forex",
",",
"'IND'",
":",
"Index",
",",
"'CFD'",
":",
"CFD",
",",
"'BOND'",
":",
"Bond",
",",
"'CMDTY'",
":",
"Commodity",
",",
"'FOP'",
":",
"FuturesOption",
",",
"'FUND'",
":",
"MutualFund",
",",
"'WAR'",
":",
"Warrant",
",",
"'IOPT'",
":",
"Warrant",
",",
"'BAG'",
":",
"Bag",
",",
"'NEWS'",
":",
"Contract",
"}",
".",
"get",
"(",
"secType",
",",
"Contract",
")",
"if",
"cls",
"is",
"not",
"Contract",
":",
"kwargs",
".",
"pop",
"(",
"'secType'",
",",
"''",
")",
"return",
"cls",
"(",
"*",
"*",
"kwargs",
")"
] |
initialize the socket | def initialize_socket ( self ) : try : _LOGGER . debug ( "Trying to open socket." ) self . _socket = socket . socket ( socket . AF_INET , # IPv4 socket . SOCK_DGRAM # UDP ) self . _socket . bind ( ( '' , self . _udp_port ) ) except socket . error as err : raise err else : _LOGGER . debug ( "Socket open." ) socket_thread = threading . Thread ( name = "SocketThread" , target = socket_worker , args = ( self . _socket , self . messages , ) ) socket_thread . setDaemon ( True ) socket_thread . start ( ) | 5,087 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L97-L114 | [
"def",
"tag_pos_volume",
"(",
"line",
")",
":",
"def",
"tagger",
"(",
"match",
")",
":",
"groups",
"=",
"match",
".",
"groupdict",
"(",
")",
"try",
":",
"year",
"=",
"match",
".",
"group",
"(",
"'year'",
")",
"except",
"IndexError",
":",
"# Extract year from volume name",
"# which should always include the year",
"g",
"=",
"re",
".",
"search",
"(",
"re_pos_year_num",
",",
"match",
".",
"group",
"(",
"'volume_num'",
")",
",",
"re",
".",
"UNICODE",
")",
"year",
"=",
"g",
".",
"group",
"(",
"0",
")",
"if",
"year",
":",
"groups",
"[",
"'year'",
"]",
"=",
"' <cds.YR>(%s)</cds.YR>'",
"%",
"year",
".",
"strip",
"(",
")",
".",
"strip",
"(",
"'()'",
")",
"else",
":",
"groups",
"[",
"'year'",
"]",
"=",
"''",
"return",
"'<cds.JOURNAL>PoS</cds.JOURNAL>'",
"' <cds.VOL>%(volume_name)s%(volume_num)s</cds.VOL>'",
"'%(year)s'",
"' <cds.PG>%(page)s</cds.PG>'",
"%",
"groups",
"for",
"p",
"in",
"re_pos",
":",
"line",
"=",
"p",
".",
"sub",
"(",
"tagger",
",",
"line",
")",
"return",
"line"
] |
initialize the worker thread | def initialize_worker ( self ) : worker_thread = threading . Thread ( name = "WorkerThread" , target = message_worker , args = ( self , ) ) worker_thread . setDaemon ( True ) worker_thread . start ( ) | 5,088 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L116-L121 | [
"def",
"strip_uri",
"(",
"repo",
")",
":",
"splits",
"=",
"repo",
".",
"split",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"splits",
")",
")",
":",
"if",
"any",
"(",
"splits",
"[",
"idx",
"]",
".",
"startswith",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"'http://'",
",",
"'https://'",
",",
"'ftp://'",
")",
")",
":",
"splits",
"[",
"idx",
"]",
"=",
"splits",
"[",
"idx",
"]",
".",
"rstrip",
"(",
"'/'",
")",
"return",
"' '",
".",
"join",
"(",
"splits",
")"
] |
initialize receiver zones | def initialize_zones ( self ) : zone_list = self . location_info . get ( 'zone_list' , { 'main' : True } ) for zone_id in zone_list : if zone_list [ zone_id ] : # Location setup is valid self . zones [ zone_id ] = Zone ( self , zone_id = zone_id ) else : # Location setup is not valid _LOGGER . debug ( "Ignoring zone: %s" , zone_id ) | 5,089 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L123-L131 | [
"def",
"extract_audio",
"(",
"filename",
",",
"channels",
"=",
"1",
",",
"rate",
"=",
"16000",
")",
":",
"temp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.wav'",
",",
"delete",
"=",
"False",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"print",
"(",
"\"The given file does not exist: {}\"",
".",
"format",
"(",
"filename",
")",
")",
"raise",
"Exception",
"(",
"\"Invalid filepath: {}\"",
".",
"format",
"(",
"filename",
")",
")",
"if",
"not",
"which",
"(",
"\"ffmpeg\"",
")",
":",
"print",
"(",
"\"ffmpeg: Executable not found on machine.\"",
")",
"raise",
"Exception",
"(",
"\"Dependency not found: ffmpeg\"",
")",
"command",
"=",
"[",
"\"ffmpeg\"",
",",
"\"-y\"",
",",
"\"-i\"",
",",
"filename",
",",
"\"-ac\"",
",",
"str",
"(",
"channels",
")",
",",
"\"-ar\"",
",",
"str",
"(",
"rate",
")",
",",
"\"-loglevel\"",
",",
"\"error\"",
",",
"temp",
".",
"name",
"]",
"use_shell",
"=",
"True",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
"else",
"False",
"subprocess",
".",
"check_output",
"(",
"command",
",",
"stdin",
"=",
"open",
"(",
"os",
".",
"devnull",
")",
",",
"shell",
"=",
"use_shell",
")",
"return",
"temp",
".",
"name",
",",
"rate"
] |
Handle status from device | def handle_status ( self ) : status = self . get_status ( ) if status : # Update main-zone self . zones [ 'main' ] . update_status ( status ) | 5,090 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L162-L168 | [
"def",
"_label_faces",
"(",
"self",
")",
":",
"coords",
"=",
"sp",
".",
"around",
"(",
"self",
"[",
"'pore.coords'",
"]",
",",
"decimals",
"=",
"10",
")",
"min_labels",
"=",
"[",
"'front'",
",",
"'left'",
",",
"'bottom'",
"]",
"max_labels",
"=",
"[",
"'back'",
",",
"'right'",
",",
"'top'",
"]",
"min_coords",
"=",
"sp",
".",
"amin",
"(",
"coords",
",",
"axis",
"=",
"0",
")",
"max_coords",
"=",
"sp",
".",
"amax",
"(",
"coords",
",",
"axis",
"=",
"0",
")",
"for",
"ax",
"in",
"range",
"(",
"3",
")",
":",
"self",
"[",
"'pore.'",
"+",
"min_labels",
"[",
"ax",
"]",
"]",
"=",
"coords",
"[",
":",
",",
"ax",
"]",
"==",
"min_coords",
"[",
"ax",
"]",
"self",
"[",
"'pore.'",
"+",
"max_labels",
"[",
"ax",
"]",
"]",
"=",
"coords",
"[",
":",
",",
"ax",
"]",
"==",
"max_coords",
"[",
"ax",
"]"
] |
Handles netusb in message | def handle_netusb ( self , message ) : # _LOGGER.debug("message: {}".format(message)) needs_update = 0 if self . _yamaha : if 'play_info_updated' in message : play_info = self . get_play_info ( ) # _LOGGER.debug(play_info) if play_info : new_media_status = MediaStatus ( play_info , self . _ip_address ) if self . _yamaha . media_status != new_media_status : # we need to send an update upwards self . _yamaha . new_media_status ( new_media_status ) needs_update += 1 playback = play_info . get ( 'playback' ) # _LOGGER.debug("Playback: {}".format(playback)) if playback == "play" : new_status = STATE_PLAYING elif playback == "stop" : new_status = STATE_IDLE elif playback == "pause" : new_status = STATE_PAUSED else : new_status = STATE_UNKNOWN if self . _yamaha . status is not new_status : _LOGGER . debug ( "playback: %s" , new_status ) self . _yamaha . status = new_status needs_update += 1 return needs_update | 5,091 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L170-L203 | [
"def",
"get_logging_file",
"(",
"maximum_logging_files",
"=",
"10",
",",
"retries",
"=",
"2",
"^",
"16",
")",
":",
"logging_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"RuntimeGlobals",
".",
"user_application_data_directory",
",",
"Constants",
".",
"logging_directory",
")",
"for",
"file",
"in",
"sorted",
"(",
"foundations",
".",
"walkers",
".",
"files_walker",
"(",
"logging_directory",
")",
",",
"key",
"=",
"lambda",
"y",
":",
"os",
".",
"path",
".",
"getmtime",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"y",
")",
")",
",",
"reverse",
"=",
"True",
")",
"[",
"maximum_logging_files",
":",
"]",
":",
"try",
":",
"os",
".",
"remove",
"(",
"file",
")",
"except",
"OSError",
":",
"LOGGER",
".",
"warning",
"(",
"\"!> {0} | Cannot remove '{1}' file!\"",
".",
"format",
"(",
"__name__",
",",
"file",
",",
"Constants",
".",
"application_name",
")",
")",
"path",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"retries",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"RuntimeGlobals",
".",
"user_application_data_directory",
",",
"Constants",
".",
"logging_directory",
",",
"Constants",
".",
"logging_file",
".",
"format",
"(",
"foundations",
".",
"strings",
".",
"get_random_sequence",
"(",
")",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"break",
"if",
"path",
"is",
"None",
":",
"raise",
"umbra",
".",
"exceptions",
".",
"EngineConfigurationError",
"(",
"\"{0} | Logging file is not available, '{1}' will now close!\"",
".",
"format",
"(",
"__name__",
",",
"Constants",
".",
"application_name",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"> Current Logging file: '{0}'\"",
".",
"format",
"(",
"path",
")",
")",
"return",
"path"
] |
Handles features of the device | def handle_features ( self , device_features ) : self . device_features = device_features if device_features and 'zone' in device_features : for zone in device_features [ 'zone' ] : zone_id = zone . get ( 'id' ) if zone_id in self . zones : _LOGGER . debug ( "handle_features: %s" , zone_id ) input_list = zone . get ( 'input_list' , [ ] ) input_list . sort ( ) self . zones [ zone_id ] . source_list = input_list | 5,092 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L205-L217 | [
"def",
"_requires_submission",
"(",
"self",
")",
":",
"if",
"self",
".",
"dbcon_part",
"is",
"None",
":",
"return",
"False",
"tables",
"=",
"get_table_list",
"(",
"self",
".",
"dbcon_part",
")",
"nrows",
"=",
"0",
"for",
"table",
"in",
"tables",
":",
"if",
"table",
"==",
"'__submissions__'",
":",
"continue",
"nrows",
"+=",
"get_number_of_rows",
"(",
"self",
".",
"dbcon_part",
",",
"table",
")",
"if",
"nrows",
":",
"logger",
".",
"debug",
"(",
"'%d new statistics were added since the last submission.'",
"%",
"nrows",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'No new statistics were added since the last submission.'",
")",
"t0",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"s",
"=",
"self",
"[",
"'__submissions__'",
"]",
"last_submission",
"=",
"s",
".",
"get_last",
"(",
"1",
")",
"if",
"last_submission",
":",
"logger",
".",
"debug",
"(",
"'Last submission was %s'",
"%",
"last_submission",
"[",
"0",
"]",
"[",
"'Time'",
"]",
")",
"t_ref",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"last_submission",
"[",
"0",
"]",
"[",
"'Time'",
"]",
",",
"Table",
".",
"time_fmt",
")",
"else",
":",
"t_ref",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"filepath",
")",
")",
"submission_interval_passed",
"=",
"(",
"t0",
"-",
"t_ref",
")",
".",
"total_seconds",
"(",
")",
">",
"self",
".",
"submit_interval_s",
"submission_required",
"=",
"bool",
"(",
"submission_interval_passed",
"and",
"nrows",
")",
"if",
"submission_required",
":",
"logger",
".",
"debug",
"(",
"'A submission is overdue.'",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'No submission required.'",
")",
"return",
"submission_required"
] |
Dispatch all event messages | def handle_event ( self , message ) : # _LOGGER.debug(message) needs_update = 0 for zone in self . zones : if zone in message : _LOGGER . debug ( "Received message for zone: %s" , zone ) self . zones [ zone ] . update_status ( message [ zone ] ) if 'netusb' in message : needs_update += self . handle_netusb ( message [ 'netusb' ] ) if needs_update > 0 : _LOGGER . debug ( "needs_update: %d" , needs_update ) self . update_hass ( ) | 5,093 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L219-L233 | [
"def",
"assignParameters",
"(",
"self",
",",
"solution_next",
",",
"IncomeDstn",
",",
"LivPrb",
",",
"DiscFac",
",",
"CRRA",
",",
"Rfree",
",",
"PermGroFac",
",",
"BoroCnstArt",
",",
"aXtraGrid",
",",
"vFuncBool",
",",
"CubicBool",
")",
":",
"ConsPerfForesightSolver",
".",
"assignParameters",
"(",
"self",
",",
"solution_next",
",",
"DiscFac",
",",
"LivPrb",
",",
"CRRA",
",",
"Rfree",
",",
"PermGroFac",
")",
"self",
".",
"BoroCnstArt",
"=",
"BoroCnstArt",
"self",
".",
"IncomeDstn",
"=",
"IncomeDstn",
"self",
".",
"aXtraGrid",
"=",
"aXtraGrid",
"self",
".",
"vFuncBool",
"=",
"vFuncBool",
"self",
".",
"CubicBool",
"=",
"CubicBool"
] |
Update device status . | def update_status ( self , reset = False ) : if self . healthy_update_timer and not reset : return # get device features only once if not self . device_features : self . handle_features ( self . get_features ( ) ) # Get status from device to register/keep alive UDP self . handle_status ( ) # Schedule next execution self . setup_update_timer ( ) | 5,094 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L239-L252 | [
"def",
"on_response",
"(",
"self",
",",
"ch",
",",
"method_frame",
",",
"props",
",",
"body",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"rabbitmq.Requester.on_response\"",
")",
"if",
"self",
".",
"corr_id",
"==",
"props",
".",
"correlation_id",
":",
"self",
".",
"response",
"=",
"{",
"'props'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
"else",
":",
"LOGGER",
".",
"warn",
"(",
"\"rabbitmq.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"props",
".",
"correlation_id",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
")",
")"
] |
Schedule a Timer Thread . | def setup_update_timer ( self , reset = False ) : _LOGGER . debug ( "Timer: firing again in %d seconds" , self . _interval ) self . update_status_timer = threading . Timer ( self . _interval , self . update_status , [ True ] ) self . update_status_timer . setDaemon ( True ) self . update_status_timer . start ( ) | 5,095 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L254-L260 | [
"def",
"_read_columns_file",
"(",
"f",
")",
":",
"try",
":",
"columns",
"=",
"json",
".",
"loads",
"(",
"open",
"(",
"f",
",",
"'r'",
")",
".",
"read",
"(",
")",
",",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
")",
"except",
"Exception",
"as",
"err",
":",
"raise",
"InvalidColumnsFileError",
"(",
"\"There was an error while reading {0}: {1}\"",
".",
"format",
"(",
"f",
",",
"err",
")",
")",
"# Options are not supported yet:",
"if",
"'__options'",
"in",
"columns",
":",
"del",
"columns",
"[",
"'__options'",
"]",
"return",
"columns"
] |
Send Playback command . | def set_playback ( self , playback ) : req_url = ENDPOINTS [ "setPlayback" ] . format ( self . _ip_address ) params = { "playback" : playback } return request ( req_url , params = params ) | 5,096 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/__init__.py#L272-L276 | [
"def",
"merge_config",
"(",
"self",
",",
"user_config",
")",
":",
"# provisioanlly update the default configurations with the user preferences",
"temp_data_config",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"data_config",
")",
".",
"update",
"(",
"user_config",
")",
"temp_model_config",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"model_config",
")",
".",
"update",
"(",
"user_config",
")",
"temp_conversation_config",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"conversation_config",
")",
".",
"update",
"(",
"user_config",
")",
"# if the new configurations validate, apply them",
"if",
"validate_data_config",
"(",
"temp_data_config",
")",
":",
"self",
".",
"data_config",
"=",
"temp_data_config",
"if",
"validate_model_config",
"(",
"temp_model_config",
")",
":",
"self",
".",
"model_config",
"=",
"temp_model_config",
"if",
"validate_conversation_config",
"(",
"temp_conversation_config",
")",
":",
"self",
".",
"conversation_config",
"=",
"temp_conversation_config"
] |
Append sql to a gemini query | def build_gemini_query ( self , query , extra_info ) : if 'WHERE' in query : return "{0} AND {1}" . format ( query , extra_info ) else : return "{0} WHERE {1}" . format ( query , extra_info ) | 5,097 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/gemini/mixins/variant.py#L20-L33 | [
"def",
"delete_group",
"(",
"group_id",
",",
"purge_data",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"try",
":",
"group_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceGroup",
")",
".",
"filter",
"(",
"ResourceGroup",
".",
"id",
"==",
"group_id",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"raise",
"ResourceNotFoundError",
"(",
"\"Group %s not found\"",
"%",
"(",
"group_id",
")",
")",
"group_items",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceGroupItem",
")",
".",
"filter",
"(",
"ResourceGroupItem",
".",
"group_id",
"==",
"group_id",
")",
".",
"all",
"(",
")",
"for",
"gi",
"in",
"group_items",
":",
"db",
".",
"DBSession",
".",
"delete",
"(",
"gi",
")",
"if",
"purge_data",
"==",
"'Y'",
":",
"_purge_datasets_unique_to_resource",
"(",
"'GROUP'",
",",
"group_id",
")",
"log",
".",
"info",
"(",
"\"Deleting group %s, id=%s\"",
",",
"group_i",
".",
"name",
",",
"group_id",
")",
"group_i",
".",
"network",
".",
"check_write_permission",
"(",
"user_id",
")",
"db",
".",
"DBSession",
".",
"delete",
"(",
"group_i",
")",
"db",
".",
"DBSession",
".",
"flush",
"(",
")"
] |
Return count variants for a case . | def variants ( self , case_id , skip = 0 , count = 1000 , filters = None ) : filters = filters or { } logger . debug ( "Looking for variants in {0}" . format ( case_id ) ) limit = count + skip gemini_query = filters . get ( 'gemini_query' ) or "SELECT * from variants v" any_filter = False if filters . get ( 'frequency' ) : frequency = filters [ 'frequency' ] extra_info = "(v.max_aaf_all < {0} or v.max_aaf_all is" " Null)" . format ( frequency ) gemini_query = self . build_gemini_query ( gemini_query , extra_info ) if filters . get ( 'cadd' ) : cadd_score = filters [ 'cadd' ] extra_info = "(v.cadd_scaled > {0})" . format ( cadd_score ) gemini_query = self . build_gemini_query ( gemini_query , extra_info ) if filters . get ( 'gene_ids' ) : gene_list = [ gene_id . strip ( ) for gene_id in filters [ 'gene_ids' ] ] gene_string = "v.gene in (" for index , gene_id in enumerate ( gene_list ) : if index == 0 : gene_string += "'{0}'" . format ( gene_id ) else : gene_string += ", '{0}'" . format ( gene_id ) gene_string += ")" gemini_query = self . build_gemini_query ( gemini_query , gene_string ) if filters . get ( 'range' ) : chrom = filters [ 'range' ] [ 'chromosome' ] if not chrom . startswith ( 'chr' ) : chrom = "chr{0}" . format ( chrom ) range_string = "v.chrom = '{0}' AND " "((v.start BETWEEN {1} AND {2}) OR " "(v.end BETWEEN {1} AND {2}))" . format ( chrom , filters [ 'range' ] [ 'start' ] , filters [ 'range' ] [ 'end' ] ) gemini_query = self . build_gemini_query ( gemini_query , range_string ) filtered_variants = self . _variants ( case_id = case_id , gemini_query = gemini_query , ) if filters . get ( 'consequence' ) : consequences = set ( filters [ 'consequence' ] ) filtered_variants = ( variant for variant in filtered_variants if set ( variant . consequences ) . intersection ( consequences ) ) if filters . get ( 'impact_severities' ) : severities = set ( [ severity . strip ( ) for severity in filters [ 'impact_severities' ] ] ) new_filtered_variants = [ ] filtered_variants = ( variant for variant in filtered_variants if set ( [ variant . impact_severity ] ) . intersection ( severities ) ) if filters . get ( 'sv_len' ) : sv_len = int ( filters [ 'sv_len' ] ) filtered_variants = ( variant for variant in filtered_variants if variant . sv_len >= sv_len ) variants = [ ] for index , variant_obj in enumerate ( filtered_variants ) : if index >= skip : if index < limit : variants . append ( variant_obj ) else : break return Results ( variants , len ( variants ) ) | 5,098 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/gemini/mixins/variant.py#L35-L144 | [
"def",
"setOverlayTransformTrackedDeviceRelative",
"(",
"self",
",",
"ulOverlayHandle",
",",
"unTrackedDevice",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTransformTrackedDeviceRelative",
"pmatTrackedDeviceToOverlayTransform",
"=",
"HmdMatrix34_t",
"(",
")",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"unTrackedDevice",
",",
"byref",
"(",
"pmatTrackedDeviceToOverlayTransform",
")",
")",
"return",
"result",
",",
"pmatTrackedDeviceToOverlayTransform"
] |
Return variants found in the gemini database | def _variants ( self , case_id , gemini_query ) : individuals = [ ] # Get the individuals for the case case_obj = self . case ( case_id ) for individual in case_obj . individuals : individuals . append ( individual ) self . db = case_obj . variant_source self . variant_type = case_obj . variant_type gq = GeminiQuery ( self . db ) gq . run ( gemini_query ) index = 0 for gemini_variant in gq : variant = None # Check if variant is non ref in the individuals is_variant = self . _is_variant ( gemini_variant , individuals ) if self . variant_type == 'snv' and not is_variant : variant = None else : index += 1 logger . debug ( "Updating index to: {0}" . format ( index ) ) variant = self . _format_variant ( case_id = case_id , gemini_variant = gemini_variant , individual_objs = individuals , index = index ) if variant : yield variant | 5,099 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/gemini/mixins/variant.py#L189-L235 | [
"def",
"_ensure_connection",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"connect",
"(",
")",
"if",
"conn",
".",
"recycle",
"and",
"conn",
".",
"recycle",
"<",
"time",
".",
"time",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"'Client session expired after %is. Recycling.'",
",",
"self",
".",
"_recycle",
")",
"self",
".",
"close",
"(",
")",
"conn",
"=",
"self",
".",
"connect",
"(",
")",
"return",
"conn"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.