query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts . | def sum_num_dicts ( dicts , normalize = False ) : sum_dict = { } for dicti in dicts : for key in dicti : sum_dict [ key ] = sum_dict . get ( key , 0 ) + dicti [ key ] if normalize : return norm_int_dict ( sum_dict ) return sum_dict | 8,200 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L609-L643 | [
"def",
"free",
"(",
"self",
",",
"lpAddress",
")",
":",
"hProcess",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"PROCESS_VM_OPERATION",
")",
"win32",
".",
"VirtualFreeEx",
"(",
"hProcess",
",",
"lpAddress",
")"
] |
Reverse a dict so each value in it maps to a sorted list of its keys . | def reverse_dict ( dict_obj ) : new_dict = { } for key in dict_obj : add_to_dict_val_set ( dict_obj = new_dict , key = dict_obj [ key ] , val = key ) for key in new_dict : new_dict [ key ] = sorted ( new_dict [ key ] , reverse = False ) return new_dict | 8,201 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L677-L702 | [
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Reverse a dict so each value in it maps to one of its keys . | def reverse_dict_partial ( dict_obj ) : new_dict = { } for key in dict_obj : new_dict [ dict_obj [ key ] ] = key return new_dict | 8,202 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L705-L727 | [
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Reverse a list - valued dict so each element in a list maps to its key . | def reverse_list_valued_dict ( dict_obj ) : new_dict = { } for key in dict_obj : for element in dict_obj [ key ] : new_dict [ element ] = key return new_dict | 8,203 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L730-L755 | [
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Flattens the given dict into a single - level dict with flattend keys . | def flatten_dict ( dict_obj , separator = '.' , flatten_lists = False ) : reducer = _get_key_reducer ( separator ) flat = { } def _flatten_key_val ( key , val , parent ) : flat_key = reducer ( parent , key ) try : _flatten ( val , flat_key ) except TypeError : flat [ flat_key ] = val def _flatten ( d , parent = None ) : try : for key , val in d . items ( ) : _flatten_key_val ( key , val , parent ) except AttributeError : if isinstance ( d , ( str , bytes ) ) : raise TypeError for i , value in enumerate ( d ) : _flatten_key_val ( str ( i ) , value , parent ) _flatten ( dict_obj ) return flat | 8,204 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L766-L812 | [
"def",
"_text_image",
"(",
"page",
")",
":",
"img",
"=",
"None",
"alt",
"=",
"page",
".",
"data",
".",
"get",
"(",
"'label'",
")",
"or",
"page",
".",
"data",
".",
"get",
"(",
"'title'",
")",
"source",
"=",
"_image",
"(",
"page",
")",
"if",
"source",
":",
"img",
"=",
"\"\"",
"%",
"(",
"alt",
",",
"source",
")",
"return",
"img"
] |
Prints the given dict with int values in a nice way . | def pprint_int_dict ( int_dict , indent = 4 , descending = False ) : sorted_tup = sorted ( int_dict . items ( ) , key = lambda x : x [ 1 ] ) if descending : sorted_tup . reverse ( ) print ( '{' ) for tup in sorted_tup : print ( '{}{}: {}' . format ( ' ' * indent , tup [ 0 ] , tup [ 1 ] ) ) print ( '}' ) | 8,205 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L815-L829 | [
"def",
"is_labial",
"(",
"c",
",",
"lang",
")",
":",
"o",
"=",
"get_offset",
"(",
"c",
",",
"lang",
")",
"return",
"(",
"o",
">=",
"LABIAL_RANGE",
"[",
"0",
"]",
"and",
"o",
"<=",
"LABIAL_RANGE",
"[",
"1",
"]",
")"
] |
Recursively iterate over key - value pairs of nested dictionaries . | def key_value_nested_generator ( dict_obj ) : for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for key , value in key_value_nested_generator ( value ) : yield key , value else : yield key , value | 8,206 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L850-L874 | [
"def",
"stream_create_default_file_stream",
"(",
"fname",
",",
"isa_read_stream",
")",
":",
"ARGTYPES",
"=",
"[",
"ctypes",
".",
"c_char_p",
",",
"ctypes",
".",
"c_int32",
"]",
"OPENJP2",
".",
"opj_stream_create_default_file_stream",
".",
"argtypes",
"=",
"ARGTYPES",
"OPENJP2",
".",
"opj_stream_create_default_file_stream",
".",
"restype",
"=",
"STREAM_TYPE_P",
"read_stream",
"=",
"1",
"if",
"isa_read_stream",
"else",
"0",
"file_argument",
"=",
"ctypes",
".",
"c_char_p",
"(",
"fname",
".",
"encode",
"(",
")",
")",
"stream",
"=",
"OPENJP2",
".",
"opj_stream_create_default_file_stream",
"(",
"file_argument",
",",
"read_stream",
")",
"return",
"stream"
] |
Recursively iterate over key - tuple - value pairs of nested dictionaries . | def key_tuple_value_nested_generator ( dict_obj ) : for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for nested_key , value in key_tuple_value_nested_generator ( value ) : yield tuple ( [ key ] ) + nested_key , value else : yield tuple ( [ key ] ) , value | 8,207 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L877-L901 | [
"def",
"stream_create_default_file_stream",
"(",
"fname",
",",
"isa_read_stream",
")",
":",
"ARGTYPES",
"=",
"[",
"ctypes",
".",
"c_char_p",
",",
"ctypes",
".",
"c_int32",
"]",
"OPENJP2",
".",
"opj_stream_create_default_file_stream",
".",
"argtypes",
"=",
"ARGTYPES",
"OPENJP2",
".",
"opj_stream_create_default_file_stream",
".",
"restype",
"=",
"STREAM_TYPE_P",
"read_stream",
"=",
"1",
"if",
"isa_read_stream",
"else",
"0",
"file_argument",
"=",
"ctypes",
".",
"c_char_p",
"(",
"fname",
".",
"encode",
"(",
")",
")",
"stream",
"=",
"OPENJP2",
".",
"opj_stream_create_default_file_stream",
"(",
"file_argument",
",",
"read_stream",
")",
"return",
"stream"
] |
Register the current options to the global ConfigOpts object . | def register ( self ) : group = cfg . OptGroup ( self . group_name , title = "HNV (Hyper-V Network Virtualization) Options" ) self . _config . register_group ( group ) self . _config . register_opts ( self . _options , group = group ) | 8,208 | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/config/client.py#L68-L74 | [
"def",
"indication",
"(",
"self",
",",
"apdu",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"apdu",
")",
"if",
"self",
".",
"state",
"==",
"IDLE",
":",
"self",
".",
"idle",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"SEGMENTED_REQUEST",
":",
"self",
".",
"segmented_request",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"AWAIT_RESPONSE",
":",
"self",
".",
"await_response",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"SEGMENTED_RESPONSE",
":",
"self",
".",
"segmented_response",
"(",
"apdu",
")",
"else",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\" - invalid state\"",
")"
] |
languageExclusion = - LANGTAG STEM_MARK? | def _language_exclusions ( stem : LanguageStemRange , exclusions : List [ ShExDocParser . LanguageExclusionContext ] ) -> None : for excl in exclusions : excl_langtag = LANGTAG ( excl . LANGTAG ( ) . getText ( ) [ 1 : ] ) stem . exclusions . append ( LanguageStem ( excl_langtag ) if excl . STEM_MARK ( ) else excl_langtag ) | 8,209 | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_node_expression_parser.py#L147-L152 | [
"def",
"on_show_mainframe",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"parent",
".",
"Enable",
"(",
")",
"self",
".",
"parent",
".",
"Show",
"(",
")",
"self",
".",
"parent",
".",
"Raise",
"(",
")"
] |
This serves as a really basic example of a thumbnailing method . You may want to implement your own logic but this will work for simple cases . | def create_thumbnail ( self , image , geometry , upscale = True , crop = None , colorspace = 'RGB' ) : image = self . colorspace ( image , colorspace ) image = self . scale ( image , geometry , upscale , crop ) image = self . crop ( image , geometry , crop ) return image | 8,210 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/engines/base.py#L17-L42 | [
"def",
"RunValidationOutputToConsole",
"(",
"feed",
",",
"options",
")",
":",
"accumulator",
"=",
"CountingConsoleProblemAccumulator",
"(",
"options",
".",
"error_types_ignore_list",
")",
"problems",
"=",
"transitfeed",
".",
"ProblemReporter",
"(",
"accumulator",
")",
"_",
",",
"exit_code",
"=",
"RunValidation",
"(",
"feed",
",",
"options",
",",
"problems",
")",
"return",
"exit_code"
] |
With this functionality you can query previously the Credit Cards Token . | def get_tokens ( self , * , payer_id , credit_card_token_id , start_date , end_date ) : payload = { "language" : self . client . language . value , "command" : PaymentCommand . GET_TOKENS . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "creditCardTokenInformation" : { "payerId" : payer_id , "creditCardTokenId" : credit_card_token_id , "startDate" : start_date . strftime ( '%Y-%m-%dT%H:%M:%S' ) , "endDate" : end_date . strftime ( '%Y-%m-%dT%H:%M:%S' ) } , "test" : self . client . is_test } return self . client . _post ( self . url , json = payload ) | 8,211 | https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/tokenization.py#L294-L322 | [
"def",
"uniform_partition_fromintv",
"(",
"intv_prod",
",",
"shape",
",",
"nodes_on_bdry",
"=",
"False",
")",
":",
"grid",
"=",
"uniform_grid_fromintv",
"(",
"intv_prod",
",",
"shape",
",",
"nodes_on_bdry",
"=",
"nodes_on_bdry",
")",
"return",
"RectPartition",
"(",
"intv_prod",
",",
"grid",
")"
] |
This feature allows you to delete a tokenized credit card register . | def remove_token ( self , * , payer_id , credit_card_token_id ) : payload = { "language" : self . client . language . value , "command" : PaymentCommand . REMOVE_TOKEN . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "removeCreditCardToken" : { "payerId" : payer_id , "creditCardTokenId" : credit_card_token_id } , "test" : self . client . is_test } return self . client . _post ( self . url , json = payload ) | 8,212 | https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/tokenization.py#L324-L348 | [
"def",
"installStatsLoop",
"(",
"statsFile",
",",
"statsDelay",
")",
":",
"def",
"dumpStats",
"(",
")",
":",
"\"\"\"Actual stats dump function.\"\"\"",
"scales",
".",
"dumpStatsTo",
"(",
"statsFile",
")",
"reactor",
".",
"callLater",
"(",
"statsDelay",
",",
"dumpStats",
")",
"def",
"startStats",
"(",
")",
":",
"\"\"\"Starts the stats dump in \"statsDelay\" seconds.\"\"\"",
"reactor",
".",
"callLater",
"(",
"statsDelay",
",",
"dumpStats",
")",
"reactor",
".",
"callWhenRunning",
"(",
"startStats",
")"
] |
Set the file path that needs to be locked . | def set_file_path ( self , filePath ) : if filePath is not None : assert isinstance ( filePath , basestring ) , "filePath must be None or string" filePath = str ( filePath ) self . __filePath = filePath | 8,213 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L308-L321 | [
"def",
"StripTypeInfo",
"(",
"rendered_data",
")",
":",
"if",
"isinstance",
"(",
"rendered_data",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"StripTypeInfo",
"(",
"d",
")",
"for",
"d",
"in",
"rendered_data",
"]",
"elif",
"isinstance",
"(",
"rendered_data",
",",
"dict",
")",
":",
"if",
"\"value\"",
"in",
"rendered_data",
"and",
"\"type\"",
"in",
"rendered_data",
":",
"return",
"StripTypeInfo",
"(",
"rendered_data",
"[",
"\"value\"",
"]",
")",
"else",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"rendered_data",
")",
":",
"result",
"[",
"k",
"]",
"=",
"StripTypeInfo",
"(",
"v",
")",
"return",
"result",
"else",
":",
"return",
"rendered_data"
] |
Set the locking pass | def set_lock_pass ( self , lockPass ) : assert isinstance ( lockPass , basestring ) , "lockPass must be string" lockPass = str ( lockPass ) assert '\n' not in lockPass , "lockPass must be not contain a new line" self . __lockPass = lockPass | 8,214 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L323-L333 | [
"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"
] |
Set the managing lock file path . | def set_lock_path ( self , lockPath ) : if lockPath is not None : assert isinstance ( lockPath , basestring ) , "lockPath must be None or string" lockPath = str ( lockPath ) self . __lockPath = lockPath if self . __lockPath is None : if self . __filePath is None : self . __lockPath = os . path . join ( os . getcwd ( ) , ".lock" ) else : self . __lockPath = os . path . join ( os . path . dirname ( self . __filePath ) , '.lock' ) | 8,215 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L335-L352 | [
"def",
"clean_text",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"normalize_url",
"(",
"url",
")",
"except",
"UnicodeDecodeError",
":",
"log",
".",
"warning",
"(",
"\"Invalid URL: %r\"",
",",
"url",
")"
] |
set the timeout limit . | def set_timeout ( self , timeout ) : try : timeout = float ( timeout ) assert timeout >= 0 assert timeout >= self . __wait except : raise Exception ( 'timeout must be a positive number bigger than wait' ) self . __timeout = timeout | 8,216 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L354-L369 | [
"def",
"_read",
"(",
"self",
",",
"directory",
",",
"filename",
",",
"session",
",",
"path",
",",
"name",
",",
"extension",
",",
"spatial",
"=",
"None",
",",
"spatialReferenceID",
"=",
"None",
",",
"replaceParamFile",
"=",
"None",
")",
":",
"yml_events",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
")",
"as",
"fo",
":",
"yml_events",
"=",
"yaml",
".",
"load",
"(",
"fo",
")",
"for",
"yml_event",
"in",
"yml_events",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"yml_event",
".",
"subfolder",
")",
")",
":",
"orm_event",
"=",
"yml_event",
".",
"as_orm",
"(",
")",
"if",
"not",
"self",
".",
"_similar_event_exists",
"(",
"orm_event",
".",
"subfolder",
")",
":",
"session",
".",
"add",
"(",
"orm_event",
")",
"self",
".",
"events",
".",
"append",
"(",
"orm_event",
")",
"session",
".",
"commit",
"(",
")"
] |
set the waiting time . | def set_wait ( self , wait ) : try : wait = float ( wait ) assert wait >= 0 except : raise Exception ( 'wait must be a positive number' ) self . __wait = wait | 8,217 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L371-L388 | [
"def",
"register_for_app",
"(",
"self",
",",
"app_label",
"=",
"None",
",",
"exclude_models",
"=",
"None",
",",
"exclude_model_classes",
"=",
"None",
")",
":",
"models",
"=",
"[",
"]",
"exclude_models",
"=",
"exclude_models",
"or",
"[",
"]",
"app_config",
"=",
"django_apps",
".",
"get_app_config",
"(",
"app_label",
")",
"for",
"model",
"in",
"app_config",
".",
"get_models",
"(",
")",
":",
"if",
"model",
".",
"_meta",
".",
"label_lower",
"in",
"exclude_models",
":",
"pass",
"elif",
"exclude_model_classes",
"and",
"issubclass",
"(",
"model",
",",
"exclude_model_classes",
")",
":",
"pass",
"else",
":",
"models",
".",
"append",
"(",
"model",
".",
"_meta",
".",
"label_lower",
")",
"self",
".",
"register",
"(",
"models",
")"
] |
Set the dead lock time . | def set_dead_lock ( self , deadLock ) : try : deadLock = float ( deadLock ) assert deadLock >= 0 except : raise Exception ( 'deadLock must be a positive number' ) self . __deadLock = deadLock | 8,218 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L390-L405 | [
"def",
"upload_cbn_dir",
"(",
"dir_path",
",",
"manager",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"jfg_path",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"if",
"not",
"jfg_path",
".",
"endswith",
"(",
"'.jgf'",
")",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"jfg_path",
")",
"log",
".",
"info",
"(",
"'opening %s'",
",",
"path",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"cbn_jgif_dict",
"=",
"json",
".",
"load",
"(",
"f",
")",
"graph",
"=",
"pybel",
".",
"from_cbn_jgif",
"(",
"cbn_jgif_dict",
")",
"out_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"jfg_path",
".",
"replace",
"(",
"'.jgf'",
",",
"'.bel'",
")",
")",
"with",
"open",
"(",
"out_path",
",",
"'w'",
")",
"as",
"o",
":",
"pybel",
".",
"to_bel",
"(",
"graph",
",",
"o",
")",
"strip_annotations",
"(",
"graph",
")",
"enrich_pubmed_citations",
"(",
"manager",
"=",
"manager",
",",
"graph",
"=",
"graph",
")",
"pybel",
".",
"to_database",
"(",
"graph",
",",
"manager",
"=",
"manager",
")",
"log",
".",
"info",
"(",
"''",
")",
"log",
".",
"info",
"(",
"'done in %.2f'",
",",
"time",
".",
"time",
"(",
")",
"-",
"t",
")"
] |
Release the lock when set and close file descriptor if opened . | def release_lock ( self , verbose = VERBOSE , raiseError = RAISE_ERROR ) : if not os . path . isfile ( self . __lockPath ) : released = True code = 0 else : try : with open ( self . __lockPath , 'rb' ) as fd : lock = fd . readlines ( ) except Exception as err : code = Exception ( "Unable to read release lock file '%s' (%s)" % ( self . __lockPath , str ( err ) ) ) released = False if verbose : print ( str ( code ) ) if raiseError : raise code else : if not len ( lock ) : code = 1 released = True elif lock [ 0 ] . rstrip ( ) == self . __lockPass . encode ( ) : try : with open ( self . __lockPath , 'wb' ) as f : #f.write( ''.encode('utf-8') ) f . write ( '' . encode ( ) ) f . flush ( ) os . fsync ( f . fileno ( ) ) except Exception as err : released = False code = Exception ( "Unable to write release lock file '%s' (%s)" % ( self . __lockPath , str ( err ) ) ) if verbose : print ( str ( code ) ) if raiseError : raise code else : released = True code = 2 else : code = 4 released = False # close file descriptor if lock is released and descriptor is not None if released and self . __fd is not None : try : if not self . __fd . closed : self . __fd . flush ( ) os . fsync ( self . __fd . fileno ( ) ) self . __fd . close ( ) except Exception as err : code = Exception ( "Unable to close file descriptor of locked file '%s' (%s)" % ( self . __filePath , str ( err ) ) ) if verbose : print ( str ( code ) ) if raiseError : raise code else : code = 3 # return return released , code | 8,219 | https://github.com/bachiraoun/pylocker/blob/a542e5ec2204f5a01d67f1d73ce68d3f4eb05d8b/Locker.py#L541-L614 | [
"def",
"text_array_to_html",
"(",
"text_arr",
")",
":",
"if",
"not",
"text_arr",
".",
"shape",
":",
"# It is a scalar. No need to put it in a table, just apply markdown",
"return",
"plugin_util",
".",
"markdown_to_safe_html",
"(",
"np",
".",
"asscalar",
"(",
"text_arr",
")",
")",
"warning",
"=",
"''",
"if",
"len",
"(",
"text_arr",
".",
"shape",
")",
">",
"2",
":",
"warning",
"=",
"plugin_util",
".",
"markdown_to_safe_html",
"(",
"WARNING_TEMPLATE",
"%",
"len",
"(",
"text_arr",
".",
"shape",
")",
")",
"text_arr",
"=",
"reduce_to_2d",
"(",
"text_arr",
")",
"html_arr",
"=",
"[",
"plugin_util",
".",
"markdown_to_safe_html",
"(",
"x",
")",
"for",
"x",
"in",
"text_arr",
".",
"reshape",
"(",
"-",
"1",
")",
"]",
"html_arr",
"=",
"np",
".",
"array",
"(",
"html_arr",
")",
".",
"reshape",
"(",
"text_arr",
".",
"shape",
")",
"return",
"warning",
"+",
"make_table",
"(",
"html_arr",
")"
] |
BERT . ohm file import | def import_bert ( self , filename , * * kwargs ) : timestep = kwargs . get ( 'timestep' , None ) if 'timestep' in kwargs : del ( kwargs [ 'timestep' ] ) self . logger . info ( 'Unified data format (BERT/pyGIMLi) file import' ) with LogDataChanges ( self , filter_action = 'import' , filter_query = os . path . basename ( filename ) ) : data , electrodes , topography = reda_bert_import . import_ohm ( filename , * * kwargs ) if timestep is not None : data [ 'timestep' ] = timestep self . _add_to_container ( data ) self . electrode_positions = electrodes # See issue #22 if kwargs . get ( 'verbose' , False ) : print ( 'Summary:' ) self . _describe_data ( data ) | 8,220 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L118-L135 | [
"def",
"destroy_sns_event",
"(",
"app_name",
",",
"env",
",",
"region",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"sns_client",
"=",
"session",
".",
"client",
"(",
"'sns'",
")",
"lambda_subscriptions",
"=",
"get_sns_subscriptions",
"(",
"app_name",
"=",
"app_name",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
")",
"for",
"subscription_arn",
"in",
"lambda_subscriptions",
":",
"sns_client",
".",
"unsubscribe",
"(",
"SubscriptionArn",
"=",
"subscription_arn",
")",
"LOG",
".",
"debug",
"(",
"\"Lambda SNS event deleted\"",
")",
"return",
"True"
] |
Return of copy of the data inside a TDIP container | def to_ip ( self ) : if 'chargeability' in self . data . columns : tdip = reda . TDIP ( data = self . data ) else : raise Exception ( 'Missing column "chargeability"' ) return tdip | 8,221 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L189-L196 | [
"def",
"devices",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# b313b945 device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw",
"# from Android system/core/adb/transport.c statename()",
"re_device_info",
"=",
"re",
".",
"compile",
"(",
"r'([^\\s]+)\\s+(offline|bootloader|device|host|recovery|sideload|no permissions|unauthorized|unknown)'",
")",
"devices",
"=",
"[",
"]",
"lines",
"=",
"self",
".",
"command_output",
"(",
"[",
"\"devices\"",
",",
"\"-l\"",
"]",
",",
"timeout",
"=",
"timeout",
")",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
"==",
"'List of devices attached '",
":",
"continue",
"match",
"=",
"re_device_info",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"device",
"=",
"{",
"'device_serial'",
":",
"match",
".",
"group",
"(",
"1",
")",
",",
"'state'",
":",
"match",
".",
"group",
"(",
"2",
")",
"}",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"2",
")",
":",
"]",
".",
"strip",
"(",
")",
"if",
"remainder",
":",
"try",
":",
"device",
".",
"update",
"(",
"dict",
"(",
"[",
"j",
".",
"split",
"(",
"':'",
")",
"for",
"j",
"in",
"remainder",
".",
"split",
"(",
"' '",
")",
"]",
")",
")",
"except",
"ValueError",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"'devices: Unable to parse '",
"'remainder for device %s'",
"%",
"line",
")",
"devices",
".",
"append",
"(",
"device",
")",
"return",
"devices"
] |
Apply a filter to subset of the data | def sub_filter ( self , subset , filter , inplace = True ) : # build the full query full_query = '' . join ( ( 'not (' , subset , ') or not (' , filter , ')' ) ) with LogDataChanges ( self , filter_action = 'filter' , filter_query = filter ) : result = self . data . query ( full_query , inplace = inplace ) return result | 8,222 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L216-L234 | [
"def",
"dump_config",
"(",
"self",
")",
":",
"yaml_content",
"=",
"self",
".",
"get_merged_config",
"(",
")",
"print",
"(",
"'YAML Configuration\\n%s\\n'",
"%",
"yaml_content",
".",
"read",
"(",
")",
")",
"try",
":",
"self",
".",
"load",
"(",
")",
"print",
"(",
"'Python Configuration\\n%s\\n'",
"%",
"pretty",
"(",
"self",
".",
"yamldocs",
")",
")",
"except",
"ConfigError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'config parse error. try running with --logfile=/dev/tty\\n'",
")",
"raise"
] |
Use a query statement to filter data . Note that you specify the data to be removed! | def filter ( self , query , inplace = True ) : with LogDataChanges ( self , filter_action = 'filter' , filter_query = query ) : result = self . data . query ( 'not ({0})' . format ( query ) , inplace = inplace , ) return result | 8,223 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L236-L259 | [
"def",
"to_glyphs_blue_values",
"(",
"self",
",",
"ufo",
",",
"master",
")",
":",
"zones",
"=",
"[",
"]",
"blue_values",
"=",
"_pairs",
"(",
"ufo",
".",
"info",
".",
"postscriptBlueValues",
")",
"other_blues",
"=",
"_pairs",
"(",
"ufo",
".",
"info",
".",
"postscriptOtherBlues",
")",
"for",
"y1",
",",
"y2",
"in",
"blue_values",
":",
"size",
"=",
"y2",
"-",
"y1",
"if",
"y2",
"==",
"0",
":",
"pos",
"=",
"0",
"size",
"=",
"-",
"size",
"else",
":",
"pos",
"=",
"y1",
"zones",
".",
"append",
"(",
"self",
".",
"glyphs_module",
".",
"GSAlignmentZone",
"(",
"pos",
",",
"size",
")",
")",
"for",
"y1",
",",
"y2",
"in",
"other_blues",
":",
"size",
"=",
"y1",
"-",
"y2",
"pos",
"=",
"y2",
"zones",
".",
"append",
"(",
"self",
".",
"glyphs_module",
".",
"GSAlignmentZone",
"(",
"pos",
",",
"size",
")",
")",
"master",
".",
"alignmentZones",
"=",
"sorted",
"(",
"zones",
",",
"key",
"=",
"lambda",
"zone",
":",
"-",
"zone",
".",
"position",
")"
] |
Compute geometrical factors over the homogeneous half - space with a constant electrode spacing | def compute_K_analytical ( self , spacing ) : K = redaK . compute_K_analytical ( self . data , spacing = spacing ) self . data = redaK . apply_K ( self . data , K ) redafixK . fix_sign_with_K ( self . data ) | 8,224 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L261-L267 | [
"def",
"download_supplementary_files",
"(",
"self",
",",
"directory",
"=",
"\"./\"",
",",
"download_sra",
"=",
"True",
",",
"email",
"=",
"None",
",",
"sra_kwargs",
"=",
"None",
")",
":",
"directory_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"\"%s_%s_%s\"",
"%",
"(",
"'Supp'",
",",
"self",
".",
"get_accession",
"(",
")",
",",
"# the directory name cannot contain many of the signs",
"re",
".",
"sub",
"(",
"r'[\\s\\*\\?\\(\\),\\.;]'",
",",
"'_'",
",",
"self",
".",
"metadata",
"[",
"'title'",
"]",
"[",
"0",
"]",
")",
")",
")",
")",
"utils",
".",
"mkdir_p",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"directory_path",
")",
")",
"downloaded_paths",
"=",
"dict",
"(",
")",
"if",
"sra_kwargs",
"is",
"None",
":",
"sra_kwargs",
"=",
"{",
"}",
"# Possible erroneous values that could be identified and skipped right",
"# after",
"blacklist",
"=",
"(",
"'NONE'",
",",
")",
"for",
"metakey",
",",
"metavalue",
"in",
"iteritems",
"(",
"self",
".",
"metadata",
")",
":",
"if",
"'supplementary_file'",
"in",
"metakey",
":",
"assert",
"len",
"(",
"metavalue",
")",
"==",
"1",
"and",
"metavalue",
"!=",
"''",
"if",
"metavalue",
"[",
"0",
"]",
"in",
"blacklist",
":",
"logger",
".",
"warn",
"(",
"\"%s value is blacklisted as '%s' - skipping\"",
"%",
"(",
"metakey",
",",
"metavalue",
"[",
"0",
"]",
")",
")",
"continue",
"# SRA will be downloaded elsewhere",
"if",
"'sra'",
"not",
"in",
"metavalue",
"[",
"0",
"]",
":",
"download_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"os",
".",
"path",
".",
"join",
"(",
"directory_path",
",",
"metavalue",
"[",
"0",
"]",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
")",
")",
")",
"try",
":",
"utils",
".",
"download_from_url",
"(",
"metavalue",
"[",
"0",
"]",
",",
"download_path",
")",
"downloaded_paths",
"[",
"metavalue",
"[",
"0",
"]",
"]",
"=",
"download_path",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"\"Cannot download %s supplementary file (%s)\"",
"%",
"(",
"self",
".",
"get_accession",
"(",
")",
",",
"err",
")",
")",
"if",
"download_sra",
":",
"try",
":",
"downloaded_files",
"=",
"self",
".",
"download_SRA",
"(",
"email",
",",
"directory",
"=",
"directory",
",",
"*",
"*",
"sra_kwargs",
")",
"downloaded_paths",
".",
"update",
"(",
"downloaded_files",
")",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"\"Cannot download %s SRA file (%s)\"",
"%",
"(",
"self",
".",
"get_accession",
"(",
")",
",",
"err",
")",
")",
"return",
"downloaded_paths"
] |
Plot a pseudosection of the given column . Note that this function only works with dipole - dipole data at the moment . | def pseudosection ( self , column = 'r' , filename = None , log10 = False , * * kwargs ) : fig , ax , cb = PS . plot_pseudosection_type2 ( self . data , column = column , log10 = log10 , * * kwargs ) if filename is not None : fig . savefig ( filename , dpi = 300 ) return fig , ax , cb | 8,225 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L328-L358 | [
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"match_path",
"=",
"path",
"return",
"dict",
"(",
"[",
"i",
"for",
"i",
"in",
"_recurmatch",
"(",
"match_path",
",",
"aug",
")",
"]",
")"
] |
Plot a histogram of one data column | def histogram ( self , column = 'r' , filename = None , log10 = False , * * kwargs ) : return_dict = HS . plot_histograms ( self . data , column ) if filename is not None : return_dict [ 'all' ] . savefig ( filename , dpi = 300 ) return return_dict | 8,226 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L360-L365 | [
"def",
"write_lockfile",
"(",
"self",
",",
"content",
")",
":",
"s",
"=",
"self",
".",
"_lockfile_encoder",
".",
"encode",
"(",
"content",
")",
"open_kwargs",
"=",
"{",
"\"newline\"",
":",
"self",
".",
"_lockfile_newlines",
",",
"\"encoding\"",
":",
"\"utf-8\"",
"}",
"with",
"vistir",
".",
"contextmanagers",
".",
"atomic_open_for_write",
"(",
"self",
".",
"lockfile_location",
",",
"*",
"*",
"open_kwargs",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"s",
")",
"# Write newline at end of document. GH-319.",
"# Only need '\\n' here; the file object handles the rest.",
"if",
"not",
"s",
".",
"endswith",
"(",
"u\"\\n\"",
")",
":",
"f",
".",
"write",
"(",
"u\"\\n\"",
")"
] |
Delete one or more measurements by index of the DataFrame . | def delete_measurements ( self , row_or_rows ) : self . data . drop ( self . data . index [ row_or_rows ] , inplace = True ) self . data = self . data . reset_index ( ) | 8,227 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/ERT.py#L371-L388 | [
"def",
"cli",
"(",
"env",
",",
"access_id",
",",
"password",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"block_manager",
".",
"set_credential_password",
"(",
"access_id",
"=",
"access_id",
",",
"password",
"=",
"password",
")",
"if",
"result",
":",
"click",
".",
"echo",
"(",
"'Password updated for %s'",
"%",
"access_id",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'FAILED updating password for %s'",
"%",
"access_id",
")"
] |
Given a file - like object loads it up into a PIL . Image object and returns it . | def get_image ( self , source ) : buf = StringIO ( source . read ( ) ) return Image . open ( buf ) | 8,228 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/engines/pil_engine.py#L13-L23 | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_prepare",
"(",
")",
"self",
".",
"_disconnector",
"=",
"tornado",
".",
"ioloop",
".",
"PeriodicCallback",
"(",
"self",
".",
"_disconnect_hanging_devices",
",",
"1000",
",",
"self",
".",
"_loop",
")",
"self",
".",
"_disconnector",
".",
"start",
"(",
")"
] |
Checks if the supplied raw data is valid image data . | def is_valid_image ( self , raw_data ) : buf = StringIO ( raw_data ) try : trial_image = Image . open ( buf ) trial_image . verify ( ) except Exception : # TODO: Get more specific with this exception handling. return False return True | 8,229 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/engines/pil_engine.py#L35-L50 | [
"def",
"_replaceRenamedPairMembers",
"(",
"kerning",
",",
"leftRename",
",",
"rightRename",
")",
":",
"renamedKerning",
"=",
"{",
"}",
"for",
"(",
"left",
",",
"right",
")",
",",
"value",
"in",
"kerning",
".",
"items",
"(",
")",
":",
"left",
"=",
"leftRename",
".",
"get",
"(",
"left",
",",
"left",
")",
"right",
"=",
"rightRename",
".",
"get",
"(",
"right",
",",
"right",
")",
"renamedKerning",
"[",
"left",
",",
"right",
"]",
"=",
"value",
"return",
"renamedKerning"
] |
Sets the image s colorspace . This is typical RGB or GRAY but may be other things depending on your choice of Engine . | def _colorspace ( self , image , colorspace ) : if colorspace == 'RGB' : if image . mode == 'RGBA' : # RGBA is just RGB + Alpha return image if image . mode == 'P' and 'transparency' in image . info : return image . convert ( 'RGBA' ) return image . convert ( 'RGB' ) if colorspace == 'GRAY' : return image . convert ( 'L' ) return image | 8,230 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/engines/pil_engine.py#L52-L71 | [
"def",
"on_end_validation",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"Enable",
"(",
")",
"self",
".",
"Show",
"(",
")",
"self",
".",
"magic_gui_frame",
".",
"Destroy",
"(",
")"
] |
Returns the raw data from the Image which can be directly written to a something be it a file - like object or a database . | def _get_raw_data ( self , image , format , quality ) : ImageFile . MAXBLOCK = 1024 * 1024 buf = StringIO ( ) try : # ptimize makes the encoder do a second pass over the image, if # the format supports it. image . save ( buf , format = format , quality = quality , optimize = 1 ) except IOError : # optimize is a no-go, omit it this attempt. image . save ( buf , format = format , quality = quality ) raw_data = buf . getvalue ( ) buf . close ( ) return raw_data | 8,231 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/engines/pil_engine.py#L101-L134 | [
"def",
"wait_for_tuning_job",
"(",
"self",
",",
"job",
",",
"poll",
"=",
"5",
")",
":",
"desc",
"=",
"_wait_until",
"(",
"lambda",
":",
"_tuning_job_status",
"(",
"self",
".",
"sagemaker_client",
",",
"job",
")",
",",
"poll",
")",
"self",
".",
"_check_job_status",
"(",
"job",
",",
"desc",
",",
"'HyperParameterTuningJobStatus'",
")",
"return",
"desc"
] |
Enable the stream thread | def enable ( self ) : with self . _lock : if self . _event_listener_thread is None : self . _event_listener_thread = WVAEventListenerThread ( self , self . _http_client ) self . _event_listener_thread . start ( ) | 8,232 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/stream.py#L49-L62 | [
"def",
"clean_surface",
"(",
"surface",
",",
"span",
")",
":",
"surface",
"=",
"surface",
".",
"replace",
"(",
"'-'",
",",
"' '",
")",
"no_start",
"=",
"[",
"'and'",
",",
"' '",
"]",
"no_end",
"=",
"[",
"' and'",
",",
"' '",
"]",
"found",
"=",
"True",
"while",
"found",
":",
"found",
"=",
"False",
"for",
"word",
"in",
"no_start",
":",
"if",
"surface",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"word",
")",
":",
"surface",
"=",
"surface",
"[",
"len",
"(",
"word",
")",
":",
"]",
"span",
"=",
"(",
"span",
"[",
"0",
"]",
"+",
"len",
"(",
"word",
")",
",",
"span",
"[",
"1",
"]",
")",
"found",
"=",
"True",
"for",
"word",
"in",
"no_end",
":",
"if",
"surface",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"word",
")",
":",
"surface",
"=",
"surface",
"[",
":",
"-",
"len",
"(",
"word",
")",
"]",
"span",
"=",
"(",
"span",
"[",
"0",
"]",
",",
"span",
"[",
"1",
"]",
"-",
"len",
"(",
"word",
")",
")",
"found",
"=",
"True",
"if",
"not",
"surface",
":",
"return",
"None",
",",
"None",
"split",
"=",
"surface",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
"if",
"split",
"[",
"0",
"]",
"in",
"[",
"'one'",
",",
"'a'",
",",
"'an'",
"]",
"and",
"len",
"(",
"split",
")",
">",
"1",
"and",
"split",
"[",
"1",
"]",
"in",
"r",
".",
"UNITS",
"+",
"r",
".",
"TENS",
":",
"span",
"=",
"(",
"span",
"[",
"0",
"]",
"+",
"len",
"(",
"surface",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"+",
"1",
",",
"span",
"[",
"1",
"]",
")",
"surface",
"=",
"' '",
".",
"join",
"(",
"surface",
".",
"split",
"(",
")",
"[",
"1",
":",
"]",
")",
"return",
"surface",
",",
"span"
] |
Disconnect from the event stream | def disable ( self ) : with self . _lock : if self . _event_listener_thread is not None : self . _event_listener_thread . stop ( ) self . _event_listener_thread = None | 8,233 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/stream.py#L64-L69 | [
"def",
"get_availability_zone",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_availability_zone'",
")",
"# Exit if not running on AWS",
"if",
"not",
"is_aws",
"(",
")",
":",
"log",
".",
"info",
"(",
"'This machine is not running in AWS, exiting...'",
")",
"return",
"availability_zone_url",
"=",
"metadata_url",
"+",
"'placement/availability-zone'",
"try",
":",
"response",
"=",
"urllib",
".",
"urlopen",
"(",
"availability_zone_url",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"ex",
":",
"msg",
"=",
"'Unable to query URL to get Availability Zone: {u}\\n{e}'",
".",
"format",
"(",
"u",
"=",
"availability_zone_url",
",",
"e",
"=",
"ex",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"# Check the code",
"if",
"response",
".",
"getcode",
"(",
")",
"!=",
"200",
":",
"msg",
"=",
"'There was a problem querying url: {u}, returned code: {c}, unable to get the Availability Zone'",
".",
"format",
"(",
"u",
"=",
"availability_zone_url",
",",
"c",
"=",
"response",
".",
"getcode",
"(",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"availability_zone",
"=",
"response",
".",
"read",
"(",
")",
"return",
"availability_zone"
] |
Get the current status of the event stream system | def get_status ( self ) : with self . _lock : if self . _event_listener_thread is None : return EVENT_STREAM_STATE_DISABLED else : return self . _event_listener_thread . get_state ( ) | 8,234 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/stream.py#L71-L88 | [
"def",
"create_mappings",
"(",
"self",
",",
"config",
")",
":",
"mappings",
"=",
"{",
"}",
"for",
"name",
",",
"cfg",
"in",
"config",
".",
"items",
"(",
")",
":",
"# Ignore special config sections.",
"if",
"name",
"in",
"CONFIG_SPECIAL_SECTIONS",
":",
"continue",
"color",
"=",
"self",
".",
"get_config_attribute",
"(",
"name",
",",
"\"color\"",
")",
"if",
"hasattr",
"(",
"color",
",",
"\"none_setting\"",
")",
":",
"color",
"=",
"None",
"mappings",
"[",
"name",
"]",
"=",
"color",
"# Store mappings for later use.",
"self",
".",
"mappings_color",
"=",
"mappings"
] |
Parse the stream buffer and return either a single event or None | def _parse_one_event ( self ) : # WVA includes \r\n between messages which the parser doesn't like, so we # throw away any data before a opening brace try : open_brace_idx = self . _buf . index ( '{' ) except ValueError : self . _buf = six . u ( '' ) # no brace found else : if open_brace_idx > 0 : self . _buf = self . _buf [ open_brace_idx : ] try : event , idx = self . _decoder . raw_decode ( self . _buf ) self . _buf = self . _buf [ idx : ] return event except ValueError : return None | 8,235 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/stream.py#L144-L161 | [
"def",
"_distance_sqr_stats_naive_generic",
"(",
"x",
",",
"y",
",",
"matrix_centered",
",",
"product",
",",
"exponent",
"=",
"1",
")",
":",
"a",
"=",
"matrix_centered",
"(",
"x",
",",
"exponent",
"=",
"exponent",
")",
"b",
"=",
"matrix_centered",
"(",
"y",
",",
"exponent",
"=",
"exponent",
")",
"covariance_xy_sqr",
"=",
"product",
"(",
"a",
",",
"b",
")",
"variance_x_sqr",
"=",
"product",
"(",
"a",
",",
"a",
")",
"variance_y_sqr",
"=",
"product",
"(",
"b",
",",
"b",
")",
"denominator_sqr",
"=",
"np",
".",
"absolute",
"(",
"variance_x_sqr",
"*",
"variance_y_sqr",
")",
"denominator",
"=",
"_sqrt",
"(",
"denominator_sqr",
")",
"# Comparisons using a tolerance can change results if the",
"# covariance has a similar order of magnitude",
"if",
"denominator",
"==",
"0.0",
":",
"correlation_xy_sqr",
"=",
"0.0",
"else",
":",
"correlation_xy_sqr",
"=",
"covariance_xy_sqr",
"/",
"denominator",
"return",
"Stats",
"(",
"covariance_xy",
"=",
"covariance_xy_sqr",
",",
"correlation_xy",
"=",
"correlation_xy_sqr",
",",
"variance_x",
"=",
"variance_x_sqr",
",",
"variance_y",
"=",
"variance_y_sqr",
")"
] |
Look at file contents and guess its correct encoding . | def guess_codec ( file , errors = "strict" , require_char = False ) : # mapping of gedcom character set specifiers to Python encoding names gedcom_char_to_codec = { 'ansel' : 'gedcom' , } # check BOM first bom_codec = check_bom ( file ) bom_size = file . tell ( ) codec = bom_codec or 'gedcom' # scan header until CHAR or end of header while True : # this stops at '\n' line = file . readline ( ) if not line : raise IOError ( "Unexpected EOF while reading GEDCOM header" ) # do not decode bytes to strings here, reason is that some # stupid apps split CONC record at byte level (in middle of # of multi-byte characters). This implies that we can only # work with encodings that have ASCII as single-byte subset. line = line . lstrip ( ) . rstrip ( b"\r\n" ) words = line . split ( ) if len ( words ) >= 2 and words [ 0 ] == b"0" and words [ 1 ] != b"HEAD" : # past header but have not seen CHAR if require_char : raise CodecError ( "GEDCOM header does not have CHAR record" ) else : break elif len ( words ) >= 3 and words [ 0 ] == b"1" and words [ 1 ] == b"CHAR" : try : encoding = words [ 2 ] . decode ( codec , errors ) encoding = gedcom_char_to_codec . get ( encoding . lower ( ) , encoding . lower ( ) ) new_codec = codecs . lookup ( encoding ) . name except LookupError : raise CodecError ( "Unknown codec name {0}" . format ( encoding ) ) if bom_codec is None : codec = new_codec elif new_codec != bom_codec : raise CodecError ( "CHAR codec {0} is different from BOM " "codec {1}" . format ( new_codec , bom_codec ) ) break return codec , bom_size | 8,236 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/parser.py#L60-L129 | [
"def",
"update",
"(",
"request",
")",
":",
"session",
"=",
"yield",
"from",
"app",
".",
"ps",
".",
"session",
".",
"load",
"(",
"request",
")",
"session",
"[",
"'random'",
"]",
"=",
"random",
".",
"random",
"(",
")",
"return",
"session"
] |
Iterator over all level = 0 records . | def records0 ( self , tag = None ) : _log . debug ( "in records0" ) for offset , xtag in self . index0 : _log . debug ( " records0: offset: %s; xtag: %s" , offset , xtag ) if tag is None or tag == xtag : yield self . read_record ( offset ) | 8,237 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/parser.py#L319-L329 | [
"def",
"_check_kwargs",
"(",
"kallable",
",",
"kwargs",
")",
":",
"supported_keywords",
"=",
"sorted",
"(",
"_inspect_kwargs",
"(",
"kallable",
")",
")",
"unsupported_keywords",
"=",
"[",
"k",
"for",
"k",
"in",
"sorted",
"(",
"kwargs",
")",
"if",
"k",
"not",
"in",
"supported_keywords",
"]",
"supported_kwargs",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"in",
"supported_keywords",
"}",
"if",
"unsupported_keywords",
":",
"logger",
".",
"warning",
"(",
"'ignoring unsupported keyword arguments: %r'",
",",
"unsupported_keywords",
")",
"return",
"supported_kwargs"
] |
Read next complete record from a file starting at given position . | def read_record ( self , offset ) : _log . debug ( "in read_record(%s)" , offset ) stack = [ ] # stores per-level current records reclevel = None for gline in self . gedcom_lines ( offset ) : _log . debug ( " read_record, gline: %s" , gline ) level = gline . level if reclevel is None : # this is the first record, remember its level reclevel = level elif level <= reclevel : # stop at the record of the same or higher (smaller) level break # All previously seen records at this level and below can # be finalized now for rec in reversed ( stack [ level : ] ) : # decode bytes value into string if rec : if rec . value is not None : rec . value = rec . value . decode ( self . _encoding , self . _errors ) rec . freeze ( ) # _log.debug(" read_record, rec: %s", rec) del stack [ level + 1 : ] # extend stack to fit this level (and make parent levels if needed) stack . extend ( [ None ] * ( level + 1 - len ( stack ) ) ) # make Record out of it (it can be updated later) parent = stack [ level - 1 ] if level > 0 else None rec = self . _make_record ( parent , gline ) # store as current record at this level stack [ level ] = rec for rec in reversed ( stack [ reclevel : ] ) : if rec : if rec . value is not None : rec . value = rec . value . decode ( self . _encoding , self . _errors ) rec . freeze ( ) _log . debug ( " read_record, rec: %s" , rec ) return stack [ reclevel ] if stack else None | 8,238 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/parser.py#L331-L388 | [
"def",
"get_monolayer",
"(",
"self",
")",
":",
"unit_a",
"=",
"self",
".",
"get_unit_primitive_area",
"Nsurfs",
"=",
"self",
".",
"Nsurfs_ads_in_slab",
"Nads",
"=",
"self",
".",
"Nads_in_slab",
"return",
"Nads",
"/",
"(",
"unit_a",
"*",
"Nsurfs",
")"
] |
Process next record . | def _make_record ( self , parent , gline ) : if parent and gline . tag in ( "CONT" , "CONC" ) : # concatenate, only for non-BLOBs if parent . tag != "BLOB" : # have to be careful concatenating empty/None values value = gline . value if gline . tag == "CONT" : value = b"\n" + ( value or b"" ) if value is not None : parent . value = ( parent . value or b"" ) + value return None # avoid infinite cycle dialect = model . DIALECT_DEFAULT if not ( gline . level == 0 and gline . tag == "HEAD" ) and self . _header : dialect = self . dialect rec = model . make_record ( level = gline . level , xref_id = gline . xref_id , tag = gline . tag , value = gline . value , sub_records = [ ] , offset = gline . offset , dialect = dialect , parser = self ) # add to parent's sub-records list if parent : parent . sub_records . append ( rec ) return rec | 8,239 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/parser.py#L390-L436 | [
"def",
"configure_materials_manager",
"(",
"graph",
",",
"key_provider",
")",
":",
"if",
"graph",
".",
"config",
".",
"materials_manager",
".",
"enable_cache",
":",
"return",
"CachingCryptoMaterialsManager",
"(",
"cache",
"=",
"LocalCryptoMaterialsCache",
"(",
"graph",
".",
"config",
".",
"materials_manager",
".",
"cache_capacity",
")",
",",
"master_key_provider",
"=",
"key_provider",
",",
"max_age",
"=",
"graph",
".",
"config",
".",
"materials_manager",
".",
"cache_max_age",
",",
"max_messages_encrypted",
"=",
"graph",
".",
"config",
".",
"materials_manager",
".",
"cache_max_messages_encrypted",
",",
")",
"return",
"DefaultCryptoMaterialsManager",
"(",
"master_key_provider",
"=",
"key_provider",
")"
] |
Perform sanity checks on threshold values | def validate_options ( subscription_key , text ) : if not subscription_key or len ( subscription_key ) == 0 : print 'Error: Warning the option subscription_key should contain a string.' print USAGE sys . exit ( 3 ) if not text or len ( text ) == 0 : print 'Error: Warning the option text should contain a string.' print USAGE sys . exit ( 3 ) | 8,240 | https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/command_line.py#L40-L51 | [
"def",
"queries",
"(",
"self",
",",
"request",
")",
":",
"queries",
"=",
"self",
".",
"get_queries",
"(",
"request",
")",
"worlds",
"=",
"[",
"]",
"with",
"self",
".",
"mapper",
".",
"begin",
"(",
")",
"as",
"session",
":",
"for",
"_",
"in",
"range",
"(",
"queries",
")",
":",
"world",
"=",
"session",
".",
"query",
"(",
"World",
")",
".",
"get",
"(",
"randint",
"(",
"1",
",",
"MAXINT",
")",
")",
"worlds",
".",
"append",
"(",
"self",
".",
"get_json",
"(",
"world",
")",
")",
"return",
"Json",
"(",
"worlds",
")",
".",
"http_response",
"(",
"request",
")"
] |
Parse options and process text to Microsoft Translate | def main ( ) : # Parse arguments parser = OptionParser ( ) parser . add_option ( '-n' , '--subscription_key' , dest = 'subscription_key' , help = 'subscription_key for authentication' ) parser . add_option ( '-t' , '--text' , dest = 'text' , help = 'text to synthesize' ) parser . add_option ( '-l' , '--language' , dest = 'language' , help = 'language' ) parser . add_option ( '-g' , '--gender' , dest = 'gender' , help = 'gender' ) parser . add_option ( '-d' , '--directory' , dest = 'directory' , help = 'directory to store the file' ) ( options , args ) = parser . parse_args ( ) subscription_key = options . subscription_key text = options . text language = options . language gender = options . gender directory = options . directory # Perform sanity checks on options validate_options ( subscription_key , text ) if not directory : directory = default_directory if not language : language = default_language if not gender : gender = default_gender # format = 'riff-16khz-16bit-mono-pcm' format = 'riff-8khz-8bit-mono-mulaw' # lang = 'en-AU' # gender = 'Female' tts_msspeak = MSSpeak ( subscription_key , '/tmp/' ) tts_msspeak . set_cache ( False ) output_filename = tts_msspeak . speak ( text , language , gender , format ) print 'Recorded TTS to %s%s' % ( directory , output_filename ) | 8,241 | https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/command_line.py#L54-L99 | [
"def",
"match_color_index",
"(",
"self",
",",
"color",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"webcolors",
"import",
"color_diff",
"if",
"isinstance",
"(",
"color",
",",
"int",
")",
":",
"return",
"color",
"if",
"color",
":",
"if",
"isinstance",
"(",
"color",
",",
"six",
".",
"string_types",
")",
":",
"rgb",
"=",
"map",
"(",
"int",
",",
"color",
".",
"split",
"(",
"','",
")",
")",
"else",
":",
"rgb",
"=",
"color",
".",
"Get",
"(",
")",
"logging",
".",
"disable",
"(",
"logging",
".",
"DEBUG",
")",
"distances",
"=",
"[",
"color_diff",
"(",
"rgb",
",",
"x",
")",
"for",
"x",
"in",
"self",
".",
"xlwt_colors",
"]",
"logging",
".",
"disable",
"(",
"logging",
".",
"NOTSET",
")",
"result",
"=",
"distances",
".",
"index",
"(",
"min",
"(",
"distances",
")",
")",
"self",
".",
"unused_colors",
".",
"discard",
"(",
"self",
".",
"xlwt_colors",
"[",
"result",
"]",
")",
"return",
"result"
] |
Get the current value of this vehicle data element | def sample ( self ) : # Response: {'VehicleSpeed': {'timestamp': '2015-03-20T18:00:49Z', 'value': 223.368515}} data = self . _http_client . get ( "vehicle/data/{}" . format ( self . name ) ) [ self . name ] dt = arrow . get ( data [ "timestamp" ] ) . datetime value = data [ "value" ] return VehicleDataSample ( value , dt ) | 8,242 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/vehicle.py#L20-L36 | [
"def",
"login",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"session",
"=",
"session",
"or",
"self",
".",
"client",
".",
"session",
"try",
":",
"response",
"=",
"session",
".",
"get",
"(",
"self",
".",
"login_url",
")",
"except",
"ConnectionError",
":",
"raise",
"APIError",
"(",
"None",
",",
"self",
".",
"login_url",
",",
"None",
",",
"'ConnectionError'",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"APIError",
"(",
"None",
",",
"self",
".",
"login_url",
",",
"None",
",",
"e",
")",
"app_key",
"=",
"re",
".",
"findall",
"(",
"r'''\"appKey\":\\s\"(.*?)\"'''",
",",
"response",
".",
"text",
")",
"if",
"app_key",
":",
"self",
".",
"app_key",
"=",
"app_key",
"[",
"0",
"]",
"else",
":",
"raise",
"RaceCardError",
"(",
"\"Unable to find appKey\"",
")"
] |
Retrieves a bucket if it exists otherwise creates it . | def _get_or_create_bucket ( self , name ) : try : return self . connection . get_bucket ( name ) except S3ResponseError , e : if AUTO_CREATE_BUCKET : return self . connection . create_bucket ( name ) raise ImproperlyConfigured , ( "Bucket specified by " "AWS_STORAGE_BUCKET_NAME does not exist. Buckets can be " "automatically created by setting AWS_AUTO_CREATE_BUCKET=True" ) | 8,243 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/backends/s3boto.py#L128-L137 | [
"def",
"_handle_message",
"(",
"self",
",",
"tags",
",",
"source",
",",
"command",
",",
"target",
",",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"if",
"command",
"in",
"[",
"\"privmsg\"",
",",
"\"pubmsg\"",
"]",
":",
"command",
"=",
"\"ctcp\"",
"else",
":",
"command",
"=",
"\"ctcpreply\"",
"msg",
"=",
"list",
"(",
"msg",
")",
"log",
".",
"debug",
"(",
"\"tags: %s, command: %s, source: %s, target: %s, \"",
"\"arguments: %s\"",
",",
"tags",
",",
"command",
",",
"source",
",",
"target",
",",
"msg",
")",
"event",
"=",
"Event3",
"(",
"command",
",",
"source",
",",
"target",
",",
"msg",
",",
"tags",
"=",
"tags",
")",
"self",
".",
"_handle_event",
"(",
"event",
")",
"if",
"command",
"==",
"\"ctcp\"",
"and",
"msg",
"[",
"0",
"]",
"==",
"\"ACTION\"",
":",
"event",
"=",
"Event3",
"(",
"\"action\"",
",",
"source",
",",
"target",
",",
"msg",
"[",
"1",
":",
"]",
",",
"tags",
"=",
"tags",
")",
"self",
".",
"_handle_event",
"(",
"event",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"tags: %s, command: %s, source: %s, target: %s, \"",
"\"arguments: %s\"",
",",
"tags",
",",
"command",
",",
"source",
",",
"target",
",",
"[",
"msg",
"]",
")",
"event",
"=",
"Event3",
"(",
"command",
",",
"source",
",",
"target",
",",
"[",
"msg",
"]",
",",
"tags",
"=",
"tags",
")",
"self",
".",
"_handle_event",
"(",
"event",
")"
] |
Gzip a given string . | def _compress_content ( self , content ) : zbuf = StringIO ( ) zfile = GzipFile ( mode = 'wb' , compresslevel = 6 , fileobj = zbuf ) zfile . write ( content . read ( ) ) zfile . close ( ) content . file = zbuf return content | 8,244 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/backends/s3boto.py#L143-L150 | [
"def",
"merge_entities",
"(",
"self",
",",
"from_entity_ids",
",",
"to_entity_id",
",",
"force",
"=",
"False",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'from_entity_ids'",
":",
"from_entity_ids",
",",
"'to_entity_id'",
":",
"to_entity_id",
",",
"'force'",
":",
"force",
",",
"}",
"api_path",
"=",
"'/v1/{mount_point}/entity/merge'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
")",
"return",
"self",
".",
"_adapter",
".",
"post",
"(",
"url",
"=",
"api_path",
",",
"json",
"=",
"params",
",",
")"
] |
Since we assume all public storage with no authorization keys we can just simply dump out a URL rather than having to query S3 for new keys . | def url ( self , name ) : name = urllib . quote_plus ( self . _clean_name ( name ) , safe = '/' ) if self . bucket_cname : return "http://%s/%s" % ( self . bucket_cname , name ) elif self . host : return "http://%s/%s/%s" % ( self . host , self . bucket_name , name ) # No host ? Then it's the default region return "http://s3.amazonaws.com/%s/%s" % ( self . bucket_name , name ) | 8,245 | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/backends/s3boto.py#L260-L272 | [
"def",
"last_message",
"(",
"self",
",",
"timeout",
"=",
"5",
")",
":",
"if",
"self",
".",
"_thread",
"is",
"not",
"None",
":",
"self",
".",
"_thread",
".",
"join",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"self",
".",
"_task",
".",
"last_message"
] |
Normalization for dining menu data | def normalize_weekly ( data ) : if "tblMenu" not in data [ "result_data" ] [ "Document" ] : data [ "result_data" ] [ "Document" ] [ "tblMenu" ] = [ ] if isinstance ( data [ "result_data" ] [ "Document" ] [ "tblMenu" ] , dict ) : data [ "result_data" ] [ "Document" ] [ "tblMenu" ] = [ data [ "result_data" ] [ "Document" ] [ "tblMenu" ] ] for day in data [ "result_data" ] [ "Document" ] [ "tblMenu" ] : if "tblDayPart" not in day : continue if isinstance ( day [ "tblDayPart" ] , dict ) : day [ "tblDayPart" ] = [ day [ "tblDayPart" ] ] for meal in day [ "tblDayPart" ] : if isinstance ( meal [ "tblStation" ] , dict ) : meal [ "tblStation" ] = [ meal [ "tblStation" ] ] for station in meal [ "tblStation" ] : if isinstance ( station [ "tblItem" ] , dict ) : station [ "tblItem" ] = [ station [ "tblItem" ] ] return data | 8,246 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L29-L46 | [
"def",
"cal_v",
"(",
"self",
",",
"p",
",",
"temp",
",",
"min_strain",
"=",
"0.3",
",",
"max_strain",
"=",
"1.0",
")",
":",
"v0",
"=",
"self",
".",
"params_therm",
"[",
"'v0'",
"]",
".",
"nominal_value",
"self",
".",
"force_norm",
"=",
"True",
"pp",
"=",
"unp",
".",
"nominal_values",
"(",
"p",
")",
"ttemp",
"=",
"unp",
".",
"nominal_values",
"(",
"temp",
")",
"def",
"_cal_v_single",
"(",
"pp",
",",
"ttemp",
")",
":",
"if",
"(",
"pp",
"<=",
"1.e-5",
")",
"and",
"(",
"ttemp",
"==",
"300.",
")",
":",
"return",
"v0",
"def",
"f_diff",
"(",
"v",
",",
"ttemp",
",",
"pp",
")",
":",
"return",
"self",
".",
"cal_p",
"(",
"v",
",",
"ttemp",
")",
"-",
"pp",
"# print(f_diff(v0 * 0.3, temp, p))",
"v",
"=",
"brenth",
"(",
"f_diff",
",",
"v0",
"*",
"max_strain",
",",
"v0",
"*",
"min_strain",
",",
"args",
"=",
"(",
"ttemp",
",",
"pp",
")",
")",
"return",
"v",
"f_vu",
"=",
"np",
".",
"vectorize",
"(",
"_cal_v_single",
")",
"v",
"=",
"f_vu",
"(",
"pp",
",",
"ttemp",
")",
"self",
".",
"force_norm",
"=",
"False",
"return",
"v"
] |
Extract meals into old format from a DiningV2 JSON response | def get_meals ( v2_response , building_id ) : result_data = v2_response [ "result_data" ] meals = [ ] day_parts = result_data [ "days" ] [ 0 ] [ "cafes" ] [ building_id ] [ "dayparts" ] [ 0 ] for meal in day_parts : stations = [ ] for station in meal [ "stations" ] : items = [ ] for item_id in station [ "items" ] : item = result_data [ "items" ] [ item_id ] new_item = { } new_item [ "txtTitle" ] = item [ "label" ] new_item [ "txtPrice" ] = "" new_item [ "txtNutritionInfo" ] = "" new_item [ "txtDescription" ] = item [ "description" ] new_item [ "tblSide" ] = "" new_item [ "tblFarmToFork" ] = "" attrs = [ { "description" : item [ "cor_icon" ] [ attr ] } for attr in item [ "cor_icon" ] ] if len ( attrs ) == 1 : new_item [ "tblAttributes" ] = { "txtAttribute" : attrs [ 0 ] } elif len ( attrs ) > 1 : new_item [ "tblAttributes" ] = { "txtAttribute" : attrs } else : new_item [ "tblAttributes" ] = "" if isinstance ( item [ "options" ] , list ) : item [ "options" ] = { } if "values" in item [ "options" ] : for side in item [ "options" ] [ "values" ] : new_item [ "tblSide" ] = { "txtSideName" : side [ "label" ] } items . append ( new_item ) stations . append ( { "tblItem" : items , "txtStationDescription" : station [ "label" ] } ) meals . append ( { "tblStation" : stations , "txtDayPartDescription" : meal [ "label" ] } ) return meals | 8,247 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L49-L82 | [
"def",
"owned_ec_states",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_owned_ec_states",
":",
"if",
"self",
".",
"owned_ecs",
":",
"states",
"=",
"[",
"]",
"for",
"ec",
"in",
"self",
".",
"owned_ecs",
":",
"states",
".",
"append",
"(",
"self",
".",
"_get_ec_state",
"(",
"ec",
")",
")",
"self",
".",
"_owned_ec_states",
"=",
"states",
"else",
":",
"self",
".",
"_owned_ec_states",
"=",
"[",
"]",
"return",
"self",
".",
"_owned_ec_states"
] |
Get the menu for the venue corresponding to venue_id on date . | def menu ( self , venue_id , date ) : query = "&date=" + date response = self . _request ( V2_ENDPOINTS [ 'MENUS' ] + venue_id + query ) return response | 8,248 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L117-L131 | [
"def",
"_abort_all_transfers",
"(",
"self",
",",
"exception",
")",
":",
"pending_reads",
"=",
"len",
"(",
"self",
".",
"_commands_to_read",
")",
"# invalidate _transfer_list",
"for",
"transfer",
"in",
"self",
".",
"_transfer_list",
":",
"transfer",
".",
"add_error",
"(",
"exception",
")",
"# clear all deferred buffers",
"self",
".",
"_init_deferred_buffers",
"(",
")",
"# finish all pending reads and ignore the data",
"# Only do this if the error is a tranfer error.",
"# Otherwise this could cause another exception",
"if",
"isinstance",
"(",
"exception",
",",
"DAPAccessIntf",
".",
"TransferError",
")",
":",
"for",
"_",
"in",
"range",
"(",
"pending_reads",
")",
":",
"self",
".",
"_interface",
".",
"read",
"(",
")"
] |
Get a list of all venue objects . | def venues ( self ) : response = self . _request ( V2_ENDPOINTS [ 'VENUES' ] ) # Normalize `dateHours` to array for venue in response [ "result_data" ] [ "document" ] [ "venue" ] : if venue . get ( "id" ) in VENUE_NAMES : venue [ "name" ] = VENUE_NAMES [ venue . get ( "id" ) ] if isinstance ( venue . get ( "dateHours" ) , dict ) : venue [ "dateHours" ] = [ venue [ "dateHours" ] ] if "dateHours" in venue : for dh in venue [ "dateHours" ] : if isinstance ( dh . get ( "meal" ) , dict ) : dh [ "meal" ] = [ dh [ "meal" ] ] return response | 8,249 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L157-L173 | [
"def",
"__execute_sext",
"(",
"self",
",",
"instr",
")",
":",
"op0_size",
"=",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"op2_size",
"=",
"instr",
".",
"operands",
"[",
"2",
"]",
".",
"size",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"op0_msb",
"=",
"extract_sign_bit",
"(",
"op0_val",
",",
"op0_size",
")",
"op2_mask",
"=",
"(",
"2",
"**",
"op2_size",
"-",
"1",
")",
"&",
"~",
"(",
"2",
"**",
"op0_size",
"-",
"1",
")",
"if",
"op0_msb",
"==",
"1",
"else",
"0x0",
"op2_val",
"=",
"op0_val",
"|",
"op2_mask",
"self",
".",
"write_operand",
"(",
"instr",
".",
"operands",
"[",
"2",
"]",
",",
"op2_val",
")",
"return",
"None"
] |
Get a menu object corresponding to the daily menu for the venue with building_id . | def menu_daily ( self , building_id ) : today = str ( datetime . date . today ( ) ) v2_response = DiningV2 ( self . bearer , self . token ) . menu ( building_id , today ) response = { 'result_data' : { 'Document' : { } } } response [ "result_data" ] [ "Document" ] [ "menudate" ] = datetime . datetime . strptime ( today , '%Y-%m-%d' ) . strftime ( '%-m/%d/%Y' ) if building_id in VENUE_NAMES : response [ "result_data" ] [ "Document" ] [ "location" ] = VENUE_NAMES [ building_id ] else : response [ "result_data" ] [ "Document" ] [ "location" ] = v2_response [ "result_data" ] [ "days" ] [ 0 ] [ "cafes" ] [ building_id ] [ "name" ] response [ "result_data" ] [ "Document" ] [ "tblMenu" ] = { "tblDayPart" : get_meals ( v2_response , building_id ) } return response | 8,250 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L175-L194 | [
"def",
"write_strings_on_files_between_markers",
"(",
"filenames",
":",
"list",
",",
"strings",
":",
"list",
",",
"marker",
":",
"str",
")",
":",
"assert",
"len",
"(",
"filenames",
")",
"==",
"len",
"(",
"strings",
")",
"if",
"len",
"(",
"filenames",
")",
">",
"0",
":",
"for",
"f",
"in",
"filenames",
":",
"assert",
"isinstance",
"(",
"f",
",",
"str",
")",
"if",
"len",
"(",
"strings",
")",
">",
"0",
":",
"for",
"s",
"in",
"strings",
":",
"assert",
"isinstance",
"(",
"s",
",",
"str",
")",
"file_id",
"=",
"0",
"for",
"f",
"in",
"filenames",
":",
"write_string_on_file_between_markers",
"(",
"f",
",",
"strings",
"[",
"file_id",
"]",
",",
"marker",
")",
"file_id",
"+=",
"1"
] |
Get an array of menu objects corresponding to the weekly menu for the venue with building_id . | def menu_weekly ( self , building_id ) : din = DiningV2 ( self . bearer , self . token ) response = { 'result_data' : { 'Document' : { } } } days = [ ] for i in range ( 7 ) : date = str ( datetime . date . today ( ) + datetime . timedelta ( days = i ) ) v2_response = din . menu ( building_id , date ) if building_id in VENUE_NAMES : response [ "result_data" ] [ "Document" ] [ "location" ] = VENUE_NAMES [ building_id ] else : response [ "result_data" ] [ "Document" ] [ "location" ] = v2_response [ "result_data" ] [ "days" ] [ 0 ] [ "cafes" ] [ building_id ] [ "name" ] formatted_date = datetime . datetime . strptime ( date , '%Y-%m-%d' ) . strftime ( '%-m/%d/%Y' ) days . append ( { "tblDayPart" : get_meals ( v2_response , building_id ) , "menudate" : formatted_date } ) response [ "result_data" ] [ "Document" ] [ "tblMenu" ] = days return normalize_weekly ( response ) | 8,251 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/dining.py#L196-L218 | [
"def",
"is_transfer_complete",
"(",
"self",
",",
"relation_name",
")",
":",
"phold",
"=",
"self",
".",
"data_access",
".",
"sql_writer",
".",
"to_placeholder",
"(",
")",
"return",
"self",
".",
"data_access",
".",
"find_model",
"(",
"Relation",
",",
"(",
"\"name = {0} and completed_at is not null\"",
".",
"format",
"(",
"phold",
")",
",",
"[",
"relation_name",
"]",
")",
")",
"is",
"not",
"None"
] |
Convert container to a complex resistivity container using the CPA - conversion . | def to_cr ( self ) : data_new = self . data . copy ( ) data_new [ 'rpha' ] = - 1.5 * data_new [ 'chargeability' ] # now that we have magnitude and phase, compute the impedance Zt data_new [ 'Zt' ] = data_new [ 'r' ] * np . exp ( data_new [ 'rpha' ] * 1j / 1000.0 ) cr = reda . CR ( data = data_new ) return cr | 8,252 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/TDIP.py#L174-L200 | [
"def",
"ParsedSections",
"(",
"file_val",
")",
":",
"try",
":",
"template_dict",
"=",
"{",
"}",
"cur_section",
"=",
"''",
"for",
"val",
"in",
"file_val",
".",
"split",
"(",
"'\\n'",
")",
":",
"val",
"=",
"val",
".",
"strip",
"(",
")",
"if",
"val",
"!=",
"''",
":",
"section_match",
"=",
"re",
".",
"match",
"(",
"r'\\[.+\\]'",
",",
"val",
")",
"if",
"section_match",
":",
"cur_section",
"=",
"section_match",
".",
"group",
"(",
")",
"[",
"1",
":",
"-",
"1",
"]",
"template_dict",
"[",
"cur_section",
"]",
"=",
"{",
"}",
"else",
":",
"option",
",",
"value",
"=",
"val",
".",
"split",
"(",
"'='",
",",
"1",
")",
"option",
"=",
"option",
".",
"strip",
"(",
")",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"option",
".",
"startswith",
"(",
"'#'",
")",
":",
"template_dict",
"[",
"cur_section",
"]",
"[",
"val",
"]",
"=",
"''",
"else",
":",
"template_dict",
"[",
"cur_section",
"]",
"[",
"option",
"]",
"=",
"value",
"except",
"Exception",
":",
"# pragma: no cover",
"template_dict",
"=",
"{",
"}",
"return",
"template_dict"
] |
Manufacture decorator that filters return value with given function . | def apply ( filter ) : def decorator ( callable ) : return lambda * args , * * kwargs : filter ( callable ( * args , * * kwargs ) ) return decorator | 8,253 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L22-L30 | [
"def",
"format_z",
"(",
"cls",
",",
"offset",
")",
":",
"sec",
"=",
"offset",
".",
"total_seconds",
"(",
")",
"return",
"'{s}{h:02d}{m:02d}'",
".",
"format",
"(",
"s",
"=",
"'-'",
"if",
"sec",
"<",
"0",
"else",
"'+'",
",",
"h",
"=",
"abs",
"(",
"int",
"(",
"sec",
"/",
"3600",
")",
")",
",",
"m",
"=",
"int",
"(",
"(",
"sec",
"%",
"3600",
")",
"/",
"60",
")",
")"
] |
Format an outpat for the given transaction . | def format_outpat ( outpat , xn ) : return outpat . format ( year = str ( xn . date . year ) , month = '{:02}' . format ( xn . date . month ) , fy = str ( xn . date . year if xn . date . month < 7 else xn . date . year + 1 ) , date = xn . date ) | 8,254 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L33-L60 | [
"def",
"static_cdn_url",
"(",
"request",
")",
":",
"cdn_url",
",",
"ssl_url",
"=",
"_get_container_urls",
"(",
"CumulusStaticStorage",
"(",
")",
")",
"static_url",
"=",
"settings",
".",
"STATIC_URL",
"return",
"{",
"\"STATIC_URL\"",
":",
"cdn_url",
"+",
"static_url",
",",
"\"STATIC_SSL_URL\"",
":",
"ssl_url",
"+",
"static_url",
",",
"\"LOCAL_STATIC_URL\"",
":",
"static_url",
",",
"}"
] |
Return the named config for the given account . | def get ( self , name , acc = None , default = None ) : if acc in self . data [ 'accounts' ] and name in self . data [ 'accounts' ] [ acc ] : return self . data [ 'accounts' ] [ acc ] [ name ] if name in self . data : return self . data [ name ] return default | 8,255 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L84-L96 | [
"def",
"get_attachment_content",
"(",
"self",
",",
"ticket_id",
",",
"attachment_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments/{}/content'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"attachment_id",
")",
")",
",",
"text_response",
"=",
"False",
")",
"lines",
"=",
"msg",
".",
"split",
"(",
"b'\\n'",
",",
"3",
")",
"if",
"(",
"len",
"(",
"lines",
")",
"==",
"4",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'invalid_attachment_pattern_bytes'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern_bytes'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"return",
"msg",
"[",
"msg",
".",
"find",
"(",
"b'\\n'",
")",
"+",
"2",
":",
"-",
"3",
"]"
] |
Return the outdir for the given account . | def outdir ( self , acc = None ) : rootdir = self . rootdir ( ) outdir = self . get ( 'outdir' , acc = acc ) dir = os . path . join ( rootdir , outdir ) if rootdir and outdir else None if not os . path . exists ( dir ) : os . makedirs ( dir ) return dir | 8,256 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L104-L114 | [
"def",
"no_vim_headers",
"(",
"physical_line",
",",
"line_number",
",",
"lines",
")",
":",
"if",
"(",
"(",
"line_number",
"<=",
"5",
"or",
"line_number",
">",
"len",
"(",
"lines",
")",
"-",
"5",
")",
"and",
"vim_header_re",
".",
"match",
"(",
"physical_line",
")",
")",
":",
"return",
"0",
",",
"\"H106: Don't put vim configuration in source files\""
] |
Determine the full outfile pattern for the given account . | def outpat ( self , acc = None ) : outdir = self . outdir ( acc ) outpat = self . get ( 'outpat' , acc = acc ) return os . path . join ( outdir , outpat ) if outdir and outpat else None | 8,257 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L116-L124 | [
"def",
"api_start",
"(",
"working_dir",
",",
"host",
",",
"port",
",",
"thread",
"=",
"True",
")",
":",
"api_srv",
"=",
"BlockstackdAPIServer",
"(",
"working_dir",
",",
"host",
",",
"port",
")",
"log",
".",
"info",
"(",
"\"Starting API server on port {}\"",
".",
"format",
"(",
"port",
")",
")",
"if",
"thread",
":",
"api_srv",
".",
"start",
"(",
")",
"return",
"api_srv"
] |
Determine the rulesdir for the given account . | def rulesdir ( self , acc = None ) : rootdir = self . rootdir ( ) rulesdir = self . get ( 'rulesdir' , acc = acc , default = [ ] ) return os . path . join ( rootdir , rulesdir ) if rootdir and rulesdir else None | 8,258 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L127-L136 | [
"def",
"_set_final_freeness",
"(",
"self",
",",
"flag",
")",
":",
"if",
"flag",
":",
"self",
".",
"state",
".",
"memory",
".",
"store",
"(",
"self",
".",
"heap_base",
"+",
"self",
".",
"heap_size",
"-",
"self",
".",
"_chunk_size_t_size",
",",
"~",
"CHUNK_P_MASK",
")",
"else",
":",
"self",
".",
"state",
".",
"memory",
".",
"store",
"(",
"self",
".",
"heap_base",
"+",
"self",
".",
"heap_size",
"-",
"self",
".",
"_chunk_size_t_size",
",",
"CHUNK_P_MASK",
")"
] |
Return a list of rulefiles for the given account . | def rulefiles ( self , acc = None ) : rulesdir = self . rulesdir ( acc ) rules = [ os . path . join ( rulesdir , x ) for x in self . get ( 'rules' , acc , [ ] ) ] if acc is not None : rules += self . rulefiles ( acc = None ) return rules | 8,259 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L138-L147 | [
"def",
"set_tr_te",
"(",
"nifti_image",
",",
"repetition_time",
",",
"echo_time",
")",
":",
"# set the repetition time in pixdim",
"nifti_image",
".",
"header",
".",
"structarr",
"[",
"'pixdim'",
"]",
"[",
"4",
"]",
"=",
"repetition_time",
"/",
"1000.0",
"# set tr and te in db_name field",
"nifti_image",
".",
"header",
".",
"structarr",
"[",
"'db_name'",
"]",
"=",
"'?TR:%.3f TE:%d'",
"%",
"(",
"repetition_time",
",",
"echo_time",
")",
"return",
"nifti_image"
] |
Download data from a separate data repository for testing . | def download_data ( identifier , outdir ) : # determine target if use_local_data_repository is not None : url_base = 'file:' + request . pathname2url ( use_local_data_repository + os . sep ) else : url_base = repository_url print ( 'url_base: {}' . format ( url_base ) ) url = url_base + inventory_filename # download inventory file filename , headers = request . urlretrieve ( url ) df = pd . read_csv ( filename , delim_whitespace = True , comment = '#' , header = None , names = [ 'identifier' , 'rel_path' ] , ) # find relative path to data file rel_path_query = df . query ( 'identifier == "{}"' . format ( identifier ) ) if rel_path_query . shape [ 0 ] == 0 : raise Exception ( 'identifier not found' ) rel_path = rel_path_query [ 'rel_path' ] . values [ 0 ] # download the file url = url_base + rel_path print ( 'data url: {}' . format ( url ) ) filename , headers = request . urlretrieve ( url ) if not os . path . isdir ( outdir ) : os . makedirs ( outdir ) zip_obj = zipfile . ZipFile ( filename ) zip_obj . extractall ( outdir ) | 8,260 | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/data.py#L21-L66 | [
"def",
"_put_bucket_policy",
"(",
"self",
")",
":",
"if",
"self",
".",
"s3props",
"[",
"'bucket_policy'",
"]",
":",
"policy_str",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"s3props",
"[",
"'bucket_policy'",
"]",
")",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_policy",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"Policy",
"=",
"policy_str",
")",
"else",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"delete_bucket_policy",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"LOG",
".",
"debug",
"(",
"'Response adding bucket policy: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 Bucket Policy Attached'",
")"
] |
Append an item to the score set . | def append ( self , item ) : if item in self : self . items [ item [ 0 ] ] . append ( item [ 1 ] ) else : self . items [ item [ 0 ] ] = [ item [ 1 ] ] | 8,261 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/score.py#L34-L43 | [
"def",
"init_argparser_source_registry",
"(",
"self",
",",
"argparser",
",",
"default",
"=",
"None",
",",
"help",
"=",
"(",
"'comma separated list of registries to use for gathering '",
"'JavaScript sources from the given Python packages'",
")",
")",
":",
"argparser",
".",
"add_argument",
"(",
"'--source-registry'",
",",
"default",
"=",
"default",
",",
"dest",
"=",
"CALMJS_MODULE_REGISTRY_NAMES",
",",
"action",
"=",
"StoreDelimitedList",
",",
"metavar",
"=",
"'<registry>[,<registry>[...]]'",
",",
"help",
"=",
"help",
",",
")",
"argparser",
".",
"add_argument",
"(",
"'--source-registries'",
",",
"default",
"=",
"default",
",",
"dest",
"=",
"CALMJS_MODULE_REGISTRY_NAMES",
",",
"action",
"=",
"StoreDelimitedList",
",",
"help",
"=",
"SUPPRESS",
",",
")"
] |
Return a list of the items with their final scores . | def scores ( self ) : return map ( lambda x : ( x [ 0 ] , sum ( x [ 1 ] ) * len ( x [ 1 ] ) ** - .5 ) , iter ( self . items . viewitems ( ) ) ) | 8,262 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/score.py#L45-L54 | [
"def",
"diff",
"(",
"vault_client",
",",
"opt",
")",
":",
"if",
"opt",
".",
"thaw_from",
":",
"opt",
".",
"secrets",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'aomi-thaw'",
")",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
"ctx",
"=",
"Context",
".",
"load",
"(",
"get_secretfile",
"(",
"opt",
")",
",",
"opt",
")",
".",
"fetch",
"(",
"vault_client",
")",
"for",
"backend",
"in",
"ctx",
".",
"mounts",
"(",
")",
":",
"diff_a_thing",
"(",
"backend",
",",
"opt",
")",
"for",
"resource",
"in",
"ctx",
".",
"resources",
"(",
")",
":",
"diff_a_thing",
"(",
"resource",
",",
"opt",
")",
"if",
"opt",
".",
"thaw_from",
":",
"rmtree",
"(",
"opt",
".",
"secrets",
")"
] |
Return the items with the higest score . | def highest ( self ) : scores = self . scores ( ) if not scores : return None maxscore = max ( map ( score , scores ) ) return filter ( lambda x : score ( x ) == maxscore , scores ) | 8,263 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/score.py#L56-L65 | [
"def",
"create_bundle",
"(",
"self",
",",
"bundleId",
",",
"data",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
"}",
"url",
"=",
"self",
".",
"__get_base_bundle_url",
"(",
")",
"+",
"\"/\"",
"+",
"bundleId",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'sourceLanguage'",
"]",
"=",
"'en'",
"data",
"[",
"'targetLanguages'",
"]",
"=",
"[",
"]",
"data",
"[",
"'notes'",
"]",
"=",
"[",
"]",
"data",
"[",
"'metadata'",
"]",
"=",
"{",
"}",
"data",
"[",
"'partner'",
"]",
"=",
"''",
"data",
"[",
"'segmentSeparatorPattern'",
"]",
"=",
"''",
"data",
"[",
"'noTranslationPattern'",
"]",
"=",
"''",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"response",
"=",
"self",
".",
"__perform_rest_call",
"(",
"requestURL",
"=",
"url",
",",
"restType",
"=",
"'PUT'",
",",
"body",
"=",
"json_data",
",",
"headers",
"=",
"headers",
")",
"return",
"response"
] |
Determine whether sh has any value | def is_empty_shape ( sh : ShExJ . Shape ) -> bool : return sh . closed is None and sh . expression is None and sh . extra is None and sh . semActs is None | 8,264 | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/parser_context.py#L188-L191 | [
"def",
"configure",
"(",
")",
":",
"import",
"os",
"from",
"uwsgiconf",
".",
"presets",
".",
"nice",
"import",
"PythonSection",
"FILE",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"port",
"=",
"8000",
"configurations",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"2",
")",
":",
"alias",
"=",
"'app_%s'",
"%",
"(",
"idx",
"+",
"1",
")",
"section",
"=",
"PythonSection",
"(",
"# Automatically reload uWSGI if this file is changed.",
"touch_reload",
"=",
"FILE",
",",
"# To differentiate easily.",
"process_prefix",
"=",
"alias",
",",
"# Serve WSGI application (see above) from this very file.",
"wsgi_module",
"=",
"FILE",
",",
"# Custom WSGI callable for second app.",
"wsgi_callable",
"=",
"alias",
",",
"# One is just enough, no use in worker on every core",
"# for this demo.",
"workers",
"=",
"1",
",",
")",
".",
"networking",
".",
"register_socket",
"(",
"PythonSection",
".",
"networking",
".",
"sockets",
".",
"http",
"(",
"'127.0.0.1:%s'",
"%",
"port",
")",
")",
"port",
"+=",
"1",
"configurations",
".",
"append",
"(",
"# We give alias for configuration to prevent clashes.",
"section",
".",
"as_configuration",
"(",
"alias",
"=",
"alias",
")",
")",
"return",
"configurations"
] |
Fix the various text escapes | def fix_text_escapes ( self , txt : str , quote_char : str ) -> str : def _subf ( matchobj ) : return matchobj . group ( 0 ) . translate ( self . re_trans_table ) if quote_char : txt = re . sub ( r'\\' + quote_char , quote_char , txt ) return re . sub ( r'\\.' , _subf , txt , flags = re . MULTILINE + re . DOTALL + re . UNICODE ) | 8,265 | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/parser_context.py#L195-L201 | [
"def",
"catalogFactory",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"fn",
"=",
"lambda",
"member",
":",
"inspect",
".",
"isclass",
"(",
"member",
")",
"and",
"member",
".",
"__module__",
"==",
"__name__",
"catalogs",
"=",
"odict",
"(",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
",",
"fn",
")",
")",
"if",
"name",
"not",
"in",
"list",
"(",
"catalogs",
".",
"keys",
"(",
")",
")",
":",
"msg",
"=",
"\"%s not found in catalogs:\\n %s\"",
"%",
"(",
"name",
",",
"list",
"(",
"kernels",
".",
"keys",
"(",
")",
")",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"msg",
"=",
"\"Unrecognized catalog: %s\"",
"%",
"name",
"raise",
"Exception",
"(",
"msg",
")",
"return",
"catalogs",
"[",
"name",
"]",
"(",
"*",
"*",
"kwargs",
")"
] |
The ShEx RE engine allows escaping any character . We have to remove that escape for everything except those that CAN be legitimately escaped | def fix_re_escapes ( self , txt : str ) -> str : def _subf ( matchobj ) : # o = self.fix_text_escapes(matchobj.group(0)) o = matchobj . group ( 0 ) . translate ( self . re_trans_table ) if o [ 1 ] in '\b\f\n\t\r' : return o [ 0 ] + 'bfntr' [ '\b\f\n\t\r' . index ( o [ 1 ] ) ] else : return o if o [ 1 ] in '\\.?*+^$()[]{|}' else o [ 1 ] return re . sub ( r'\\.' , _subf , txt , flags = re . MULTILINE + re . DOTALL + re . UNICODE ) | 8,266 | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/parser_context.py#L203-L217 | [
"def",
"populateFromFile",
"(",
"self",
",",
"dataUrls",
",",
"indexFiles",
")",
":",
"assert",
"len",
"(",
"dataUrls",
")",
"==",
"len",
"(",
"indexFiles",
")",
"for",
"dataUrl",
",",
"indexFile",
"in",
"zip",
"(",
"dataUrls",
",",
"indexFiles",
")",
":",
"varFile",
"=",
"pysam",
".",
"VariantFile",
"(",
"dataUrl",
",",
"index_filename",
"=",
"indexFile",
")",
"try",
":",
"self",
".",
"_populateFromVariantFile",
"(",
"varFile",
",",
"dataUrl",
",",
"indexFile",
")",
"finally",
":",
"varFile",
".",
"close",
"(",
")"
] |
Return an enumerable that iterates through a multi - page API request | def _iter_response ( self , url , params = None ) : if params is None : params = { } params [ 'page_number' ] = 1 # Last page lists itself as next page while True : response = self . _request ( url , params ) for item in response [ 'result_data' ] : yield item # Last page lists itself as next page if response [ 'service_meta' ] [ 'next_page_number' ] == params [ 'page_number' ] : break params [ 'page_number' ] += 1 | 8,267 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L28-L45 | [
"def",
"delete_unit",
"(",
"unit_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"db_unit",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Unit",
")",
".",
"filter",
"(",
"Unit",
".",
"id",
"==",
"unit_id",
")",
".",
"one",
"(",
")",
"db",
".",
"DBSession",
".",
"delete",
"(",
"db_unit",
")",
"db",
".",
"DBSession",
".",
"flush",
"(",
")",
"return",
"True",
"except",
"NoResultFound",
":",
"raise",
"ResourceNotFoundError",
"(",
"\"Unit (ID=%s) does not exist\"",
"%",
"(",
"unit_id",
")",
")"
] |
Return a generator of section objects for the given search params . | def search ( self , params , validate = False ) : if self . val_info is None : self . val_info = self . search_params ( ) if validate : errors = self . validate ( self . val_info , params ) if not validate or len ( errors ) == 0 : return self . _iter_response ( ENDPOINTS [ 'SEARCH' ] , params ) else : return { 'Errors' : errors } | 8,268 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L47-L63 | [
"def",
"describe_api_deployment",
"(",
"restApiId",
",",
"deploymentId",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"deployment",
"=",
"conn",
".",
"get_deployment",
"(",
"restApiId",
"=",
"restApiId",
",",
"deploymentId",
"=",
"deploymentId",
")",
"return",
"{",
"'deployment'",
":",
"_convert_datetime_str",
"(",
"deployment",
")",
"}",
"except",
"ClientError",
"as",
"e",
":",
"return",
"{",
"'error'",
":",
"__utils__",
"[",
"'boto3.get_error'",
"]",
"(",
"e",
")",
"}"
] |
Return an object of semester - independent course info . All arguments should be strings . | def course ( self , dept , course_number ) : response = self . _request ( path . join ( ENDPOINTS [ 'CATALOG' ] , dept , course_number ) ) return response [ 'result_data' ] [ 0 ] | 8,269 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L65-L72 | [
"def",
"set_access_control",
"(",
"self",
",",
"mode",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"SetAccessControl",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"mode",
"=",
"mode",
")"
] |
Return a single section object for the given section . All arguments should be strings . Throws a ValueError if the section is not found . | def section ( self , dept , course_number , sect_number ) : section_id = dept + course_number + sect_number sections = self . search ( { 'course_id' : section_id } ) try : return next ( sections ) except StopIteration : raise ValueError ( 'Section %s not found' % section_id ) | 8,270 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L80-L91 | [
"def",
"_build_processor",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"web_processor",
"=",
"cls",
".",
"_build_web_processor",
"(",
"session",
")",
"ftp_processor",
"=",
"cls",
".",
"_build_ftp_processor",
"(",
"session",
")",
"delegate_processor",
"=",
"session",
".",
"factory",
".",
"new",
"(",
"'Processor'",
")",
"delegate_processor",
".",
"register",
"(",
"'http'",
",",
"web_processor",
")",
"delegate_processor",
".",
"register",
"(",
"'https'",
",",
"web_processor",
")",
"delegate_processor",
".",
"register",
"(",
"'ftp'",
",",
"ftp_processor",
")"
] |
Parse an ACS Geoid or a GVID to a GVID | def parse_to_gvid ( v ) : from geoid . civick import GVid from geoid . acs import AcsGeoid m1 = '' try : return GVid . parse ( v ) except ValueError as e : m1 = str ( e ) try : return AcsGeoid . parse ( v ) . convert ( GVid ) except ValueError as e : raise ValueError ( "Failed to parse to either ACS or GVid: {}; {}" . format ( m1 , str ( e ) ) ) | 8,271 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L342-L357 | [
"def",
"rebalance_replicas",
"(",
"self",
",",
"max_movement_count",
"=",
"None",
",",
"max_movement_size",
"=",
"None",
",",
")",
":",
"movement_count",
"=",
"0",
"movement_size",
"=",
"0",
"for",
"partition",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"cluster_topology",
".",
"partitions",
")",
":",
"count",
",",
"size",
"=",
"self",
".",
"_rebalance_partition_replicas",
"(",
"partition",
",",
"None",
"if",
"not",
"max_movement_count",
"else",
"max_movement_count",
"-",
"movement_count",
",",
"None",
"if",
"not",
"max_movement_size",
"else",
"max_movement_size",
"-",
"movement_size",
",",
")",
"movement_count",
"+=",
"count",
"movement_size",
"+=",
"size",
"return",
"movement_count",
",",
"movement_size"
] |
Decode a Base X encoded string into the number | def base62_decode ( string ) : alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' base = len ( alphabet ) strlen = len ( string ) num = 0 idx = 0 for char in string : power = ( strlen - ( idx + 1 ) ) num += alphabet . index ( char ) * ( base ** power ) idx += 1 return int ( num ) | 8,272 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L384-L405 | [
"def",
"generate_timing_stats",
"(",
"file_list",
",",
"var_list",
")",
":",
"timing_result",
"=",
"dict",
"(",
")",
"timing_summary",
"=",
"dict",
"(",
")",
"for",
"file",
"in",
"file_list",
":",
"timing_result",
"[",
"file",
"]",
"=",
"functions",
".",
"parse_gptl",
"(",
"file",
",",
"var_list",
")",
"for",
"var",
"in",
"var_list",
":",
"var_time",
"=",
"[",
"]",
"for",
"f",
",",
"data",
"in",
"timing_result",
".",
"items",
"(",
")",
":",
"try",
":",
"var_time",
".",
"append",
"(",
"data",
"[",
"var",
"]",
")",
"except",
":",
"continue",
"if",
"len",
"(",
"var_time",
")",
":",
"timing_summary",
"[",
"var",
"]",
"=",
"{",
"'mean'",
":",
"np",
".",
"mean",
"(",
"var_time",
")",
",",
"'max'",
":",
"np",
".",
"max",
"(",
"var_time",
")",
",",
"'min'",
":",
"np",
".",
"min",
"(",
"var_time",
")",
",",
"'std'",
":",
"np",
".",
"std",
"(",
"var_time",
")",
"}",
"return",
"timing_summary"
] |
Create derived classes and put them into the same module as the base class . | def make_classes ( base_class , module ) : from functools import partial for k in names : cls = base_class . class_factory ( k . capitalize ( ) ) cls . augment ( ) setattr ( module , k . capitalize ( ) , cls ) setattr ( module , 'get_class' , partial ( get_class , module ) ) | 8,273 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L428-L446 | [
"def",
"_ParseStorageMediaOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"_ParseStorageMediaImageOptions",
"(",
"options",
")",
"self",
".",
"_ParseVSSProcessingOptions",
"(",
"options",
")",
"self",
".",
"_ParseCredentialOptions",
"(",
"options",
")",
"self",
".",
"_ParseSourcePathOption",
"(",
"options",
")"
] |
Generate a dict that includes all of the available geoid values with keys for the most common names for those values . | def generate_all ( sumlevel , d ) : from geoid . civick import GVid from geoid . tiger import TigerGeoid from geoid . acs import AcsGeoid sumlevel = int ( sumlevel ) d = dict ( d . items ( ) ) # Map common name variants if 'cousub' in d : d [ 'cosub' ] = d [ 'cousub' ] del d [ 'cousub' ] if 'blkgrp' in d : d [ 'blockgroup' ] = d [ 'blkgrp' ] del d [ 'blkgrp' ] if 'zcta5' in d : d [ 'zcta' ] = d [ 'zcta5' ] del d [ 'zcta5' ] gvid_class = GVid . resolve_summary_level ( sumlevel ) if not gvid_class : return { } geoidt_class = TigerGeoid . resolve_summary_level ( sumlevel ) geoid_class = AcsGeoid . resolve_summary_level ( sumlevel ) try : return dict ( gvid = str ( gvid_class ( * * d ) ) , geoid = str ( geoid_class ( * * d ) ) , geoidt = str ( geoidt_class ( * * d ) ) ) except : raise | 8,274 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L887-L927 | [
"def",
"set_led",
"(",
"self",
",",
"red",
"=",
"0",
",",
"green",
"=",
"0",
",",
"blue",
"=",
"0",
")",
":",
"self",
".",
"_led",
"=",
"(",
"red",
",",
"green",
",",
"blue",
")",
"self",
".",
"_control",
"(",
")"
] |
Code to generate the state and county names | def _generate_names ( ) : from ambry import get_library l = get_library ( ) counties = l . partition ( 'census.gov-acs-geofile-2009-geofile50-20095-50' ) states = l . partition ( 'census.gov-acs-geofile-2009-geofile40-20095-40' ) names = { } for row in counties . remote_datafile . reader : names [ ( row . state , row . county ) ] = row . name for row in states . remote_datafile . reader : if row . component == '00' : names [ ( row . state , 0 ) ] = row . name pprint . pprint ( names ) | 8,275 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L930-L952 | [
"def",
"RepackAllTemplates",
"(",
"self",
",",
"upload",
"=",
"False",
",",
"token",
"=",
"None",
")",
":",
"for",
"template",
"in",
"os",
".",
"listdir",
"(",
"config",
".",
"CONFIG",
"[",
"\"ClientBuilder.template_dir\"",
"]",
")",
":",
"template_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"CONFIG",
"[",
"\"ClientBuilder.template_dir\"",
"]",
",",
"template",
")",
"self",
".",
"RepackTemplate",
"(",
"template_path",
",",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"CONFIG",
"[",
"\"ClientBuilder.executables_dir\"",
"]",
",",
"\"installers\"",
")",
",",
"upload",
"=",
"upload",
",",
"token",
"=",
"token",
")",
"# If it's windows also repack a debug version.",
"if",
"template_path",
".",
"endswith",
"(",
"\".exe.zip\"",
")",
":",
"print",
"(",
"\"Repacking as debug installer: %s.\"",
"%",
"template_path",
")",
"self",
".",
"RepackTemplate",
"(",
"template_path",
",",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"CONFIG",
"[",
"\"ClientBuilder.executables_dir\"",
"]",
",",
"\"installers\"",
")",
",",
"upload",
"=",
"upload",
",",
"token",
"=",
"token",
",",
"context",
"=",
"[",
"\"DebugClientBuild Context\"",
"]",
")"
] |
The type designation for the county or county equivalent such as County Parish or Borough | def division_name ( self ) : try : return next ( e for e in self . type_names_re . search ( self . name ) . groups ( ) if e is not None ) except AttributeError : # The search will fail for 'District of Columbia' return '' | 8,276 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L489-L495 | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"run_plugins",
"(",
")",
"while",
"True",
":",
"# Reload plugins and config if either the config file or plugin",
"# directory are modified.",
"if",
"self",
".",
"_config_mod_time",
"!=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"_config_file_path",
")",
"or",
"self",
".",
"_plugin_mod_time",
"!=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"_plugin_path",
")",
":",
"self",
".",
"thread_manager",
".",
"kill_all_threads",
"(",
")",
"self",
".",
"output_dict",
".",
"clear",
"(",
")",
"self",
".",
"reload",
"(",
")",
"self",
".",
"run_plugins",
"(",
")",
"self",
".",
"output_to_bar",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"_remove_empty_output",
"(",
")",
")",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"config",
".",
"general",
"[",
"'interval'",
"]",
")"
] |
Augment the class with computed formats regexes and other things . This caches these values so they don t have to be created for every instance . | def augment ( cls ) : import re level_name = cls . __name__ . lower ( ) cls . sl = names [ level_name ] cls . class_map [ cls . __name__ . lower ( ) ] = cls cls . sl_map [ cls . sl ] = cls cls . fmt = cls . make_format_string ( cls . __name__ . lower ( ) ) cls . regex_str = cls . make_regex ( cls . __name__ . lower ( ) ) cls . regex = re . compile ( cls . regex_str ) # List of field names cls . level = level_name cls . fields = segments [ cls . sl ] | 8,277 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L562-L583 | [
"def",
"delete_persistent_data",
"(",
"role",
",",
"zk_node",
")",
":",
"if",
"role",
":",
"destroy_volumes",
"(",
"role",
")",
"unreserve_resources",
"(",
"role",
")",
"if",
"zk_node",
":",
"delete_zk_node",
"(",
"zk_node",
")"
] |
Return a derived class based on the class name or the summary_level | def get_class ( cls , name_or_sl ) : try : return cls . sl_map [ int ( name_or_sl ) ] except TypeError as e : raise TypeError ( "Bad name or sl: {} : {}" . format ( name_or_sl , e ) ) except ValueError : try : return cls . class_map [ name_or_sl . lower ( ) ] except ( KeyError , ValueError ) : raise NotASummaryName ( "Value '{}' is not a valid summary level" . format ( name_or_sl ) ) | 8,278 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L587-L598 | [
"def",
"_start_vnc",
"(",
"self",
")",
":",
"self",
".",
"_display",
"=",
"self",
".",
"_get_free_display_port",
"(",
")",
"if",
"shutil",
".",
"which",
"(",
"\"Xvfb\"",
")",
"is",
"None",
"or",
"shutil",
".",
"which",
"(",
"\"x11vnc\"",
")",
"is",
"None",
":",
"raise",
"DockerError",
"(",
"\"Please install Xvfb and x11vnc before using the VNC support\"",
")",
"self",
".",
"_xvfb_process",
"=",
"yield",
"from",
"asyncio",
".",
"create_subprocess_exec",
"(",
"\"Xvfb\"",
",",
"\"-nolisten\"",
",",
"\"tcp\"",
",",
"\":{}\"",
".",
"format",
"(",
"self",
".",
"_display",
")",
",",
"\"-screen\"",
",",
"\"0\"",
",",
"self",
".",
"_console_resolution",
"+",
"\"x16\"",
")",
"# We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569",
"self",
".",
"_x11vnc_process",
"=",
"yield",
"from",
"asyncio",
".",
"create_subprocess_exec",
"(",
"\"x11vnc\"",
",",
"\"-forever\"",
",",
"\"-nopw\"",
",",
"\"-shared\"",
",",
"\"-geometry\"",
",",
"self",
".",
"_console_resolution",
",",
"\"-display\"",
",",
"\"WAIT:{}\"",
".",
"format",
"(",
"self",
".",
"_display",
")",
",",
"\"-rfbport\"",
",",
"str",
"(",
"self",
".",
"console",
")",
",",
"\"-rfbportv6\"",
",",
"str",
"(",
"self",
".",
"console",
")",
",",
"\"-noncache\"",
",",
"\"-listen\"",
",",
"self",
".",
"_manager",
".",
"port_manager",
".",
"console_host",
")",
"x11_socket",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"/tmp/.X11-unix/\"",
",",
"\"X{}\"",
".",
"format",
"(",
"self",
".",
"_display",
")",
")",
"yield",
"from",
"wait_for_file_creation",
"(",
"x11_socket",
")"
] |
Return a name of the state or county or for other lowever levels the name of the level type in the county . | def geo_name ( self ) : if self . level == 'county' : return str ( self . county_name ) elif self . level == 'state' : return self . state_name else : if hasattr ( self , 'county' ) : return "{} in {}" . format ( self . level , str ( self . county_name ) ) elif hasattr ( self , 'state' ) : return "{} in {}" . format ( self . level , self . state_name ) else : return "a {}" . format ( self . level ) | 8,279 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L668-L689 | [
"def",
"from_config",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"telegram",
"d",
"=",
"load_config_file",
"(",
"filename",
")",
"request",
"=",
"cls",
".",
"get_proxy_request",
"(",
"d",
")",
"if",
"'proxy_url'",
"in",
"d",
"else",
"None",
"if",
"'token'",
"in",
"d",
"and",
"'chat_id'",
"in",
"d",
":",
"bot",
"=",
"telegram",
".",
"Bot",
"(",
"d",
"[",
"'token'",
"]",
",",
"request",
"=",
"request",
")",
"obs",
"=",
"cls",
"(",
"bot",
",",
"*",
"*",
"d",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Telegram configuration file must contain \"",
"\"entries for 'token' and 'chat_id'!\"",
")",
"for",
"k",
"in",
"[",
"'completed_text'",
",",
"'interrupted_text'",
",",
"'failed_text'",
"]",
":",
"if",
"k",
"in",
"d",
":",
"setattr",
"(",
"obs",
",",
"k",
",",
"d",
"[",
"k",
"]",
")",
"return",
"obs"
] |
Parse a string value into the geoid of this class . | def parse ( cls , gvid , exception = True ) : if gvid == 'invalid' : return cls . get_class ( 'null' ) ( 0 ) if not bool ( gvid ) : return None if not isinstance ( gvid , six . string_types ) : raise TypeError ( "Can't parse; not a string. Got a '{}' " . format ( type ( gvid ) ) ) try : if not cls . sl : # Civick and ACS include the SL, so can call from base type. if six . PY3 : fn = cls . decode else : fn = cls . decode . __func__ sl = fn ( gvid [ 0 : cls . sl_width ] ) else : sl = cls . sl # Otherwise must use derived class. except ValueError as e : if exception : raise ValueError ( "Failed to parse gvid '{}': {}" . format ( gvid , str ( e ) ) ) else : return cls . get_class ( 'null' ) ( 0 ) try : cls = cls . sl_map [ sl ] except KeyError : if exception : raise ValueError ( "Failed to parse gvid '{}': Unknown summary level '{}' " . format ( gvid , sl ) ) else : return cls . get_class ( 'null' ) ( 0 ) m = cls . regex . match ( gvid ) if not m : raise ValueError ( "Failed to match '{}' to '{}' " . format ( gvid , cls . regex_str ) ) d = m . groupdict ( ) if not d : return None if six . PY3 : fn = cls . decode else : fn = cls . decode . __func__ d = { k : fn ( v ) for k , v in d . items ( ) } try : del d [ 'sl' ] except KeyError : pass return cls ( * * d ) | 8,280 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L714-L781 | [
"def",
"create_experiment",
"(",
"args",
")",
":",
"config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"nni_config",
"=",
"Config",
"(",
"config_file_name",
")",
"config_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"args",
".",
"config",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"print_error",
"(",
"'Please set correct config path!'",
")",
"exit",
"(",
"1",
")",
"experiment_config",
"=",
"get_yml_content",
"(",
"config_path",
")",
"validate_all_content",
"(",
"experiment_config",
",",
"config_path",
")",
"nni_config",
".",
"set_config",
"(",
"'experimentConfig'",
",",
"experiment_config",
")",
"launch_experiment",
"(",
"args",
",",
"experiment_config",
",",
"'new'",
",",
"config_file_name",
")",
"nni_config",
".",
"set_config",
"(",
"'restServerPort'",
",",
"args",
".",
"port",
")"
] |
Convert to another derived class . cls is the base class for the derived type ie AcsGeoid TigerGeoid etc . | def convert ( self , root_cls ) : d = self . __dict__ d [ 'sl' ] = self . sl try : cls = root_cls . get_class ( root_cls . sl ) except ( AttributeError , TypeError ) : # Hopefully because root_cls is a module cls = root_cls . get_class ( self . sl ) return cls ( * * d ) | 8,281 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L783-L796 | [
"def",
"add_section",
"(",
"self",
",",
"section",
")",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"self",
".",
"config",
".",
"add_section",
"(",
"section",
")",
"with",
"open",
"(",
"self",
".",
"filepath",
",",
"\"w\"",
")",
"as",
"f",
":",
"self",
".",
"config",
".",
"write",
"(",
"f",
")"
] |
Convert to the next higher level summary level | def promote ( self , level = None ) : if level is None : if len ( self . fields ) < 2 : if self . level in ( 'region' , 'division' , 'state' , 'ua' ) : cls = self . get_class ( 'us' ) else : return None else : cls = self . get_class ( self . fields [ - 2 ] ) else : cls = self . get_class ( level ) d = dict ( self . __dict__ . items ( ) ) d [ 'sl' ] = self . sl return cls ( * * d ) | 8,282 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L810-L828 | [
"def",
"ingest_volumes_param",
"(",
"self",
",",
"volumes",
")",
":",
"data",
"=",
"{",
"}",
"for",
"volume",
"in",
"volumes",
":",
"if",
"volume",
".",
"get",
"(",
"'host'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'sourcePath'",
")",
":",
"data",
"[",
"volume",
".",
"get",
"(",
"'name'",
")",
"]",
"=",
"{",
"'path'",
":",
"volume",
".",
"get",
"(",
"'host'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'sourcePath'",
")",
",",
"'readonly'",
":",
"volume",
".",
"get",
"(",
"'readOnly'",
",",
"False",
")",
"}",
"else",
":",
"data",
"[",
"volume",
".",
"get",
"(",
"'name'",
")",
"]",
"=",
"{",
"'path'",
":",
"'/tmp/{}'",
".",
"format",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"[",
":",
"8",
"]",
")",
",",
"'readonly'",
":",
"volume",
".",
"get",
"(",
"'readOnly'",
",",
"False",
")",
"}",
"return",
"data"
] |
Convert the last value to zero . This form represents the entire higher summary level at the granularity of the lower summary level . For example for a county it means All counties in the state | def allval ( self ) : d = dict ( self . __dict__ . items ( ) ) d [ 'sl' ] = self . sl d [ self . level ] = 0 cls = self . get_class ( self . sl ) return cls ( * * d ) | 8,283 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L835-L846 | [
"def",
"read",
"(",
"self",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"while",
"True",
":",
"incoming_bytes",
"=",
"self",
".",
"comport",
".",
"inWaiting",
"(",
")",
"if",
"incoming_bytes",
"==",
"0",
":",
"break",
"else",
":",
"content",
"=",
"self",
".",
"comport",
".",
"read",
"(",
"size",
"=",
"incoming_bytes",
")",
"data",
".",
"extend",
"(",
"bytearray",
"(",
"content",
")",
")",
"return",
"data"
] |
Create a new instance where all of the values are 0 | def nullval ( cls ) : d = dict ( cls . __dict__ . items ( ) ) for k in d : d [ k ] = 0 d [ 'sl' ] = cls . sl d [ cls . level ] = 0 return cls ( * * d ) | 8,284 | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L849-L860 | [
"def",
"_create_download_failed_message",
"(",
"exception",
",",
"url",
")",
":",
"message",
"=",
"'Failed to download from:\\n{}\\nwith {}:\\n{}'",
".",
"format",
"(",
"url",
",",
"exception",
".",
"__class__",
".",
"__name__",
",",
"exception",
")",
"if",
"_is_temporal_problem",
"(",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"requests",
".",
"ConnectionError",
")",
":",
"message",
"+=",
"'\\nPlease check your internet connection and try again.'",
"else",
":",
"message",
"+=",
"'\\nThere might be a problem in connection or the server failed to process '",
"'your request. Please try again.'",
"elif",
"isinstance",
"(",
"exception",
",",
"requests",
".",
"HTTPError",
")",
":",
"try",
":",
"server_message",
"=",
"''",
"for",
"elem",
"in",
"decode_data",
"(",
"exception",
".",
"response",
".",
"content",
",",
"MimeType",
".",
"XML",
")",
":",
"if",
"'ServiceException'",
"in",
"elem",
".",
"tag",
"or",
"'Message'",
"in",
"elem",
".",
"tag",
":",
"server_message",
"+=",
"elem",
".",
"text",
".",
"strip",
"(",
"'\\n\\t '",
")",
"except",
"ElementTree",
".",
"ParseError",
":",
"server_message",
"=",
"exception",
".",
"response",
".",
"text",
"message",
"+=",
"'\\nServer response: \"{}\"'",
".",
"format",
"(",
"server_message",
")",
"return",
"message"
] |
Extracts pieces of name from full name string . | def split_name ( name ) : given1 , _ , rem = name . partition ( "/" ) surname , _ , given2 = rem . partition ( "/" ) return given1 . strip ( ) , surname . strip ( ) , given2 . strip ( ) | 8,285 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/name.py#L7-L35 | [
"def",
"egress",
"(",
"self",
",",
"envelope",
",",
"http_headers",
",",
"operation",
",",
"binding_options",
")",
":",
"custom_headers",
"=",
"self",
".",
"_header_handler",
".",
"GetHTTPHeaders",
"(",
")",
"http_headers",
".",
"update",
"(",
"custom_headers",
")",
"return",
"envelope",
",",
"http_headers"
] |
Parse NAME structure assuming ALTREE dialect . | def parse_name_altree ( record ) : name_tuple = split_name ( record . value ) if name_tuple [ 1 ] == '?' : name_tuple = ( name_tuple [ 0 ] , '' , name_tuple [ 2 ] ) maiden = record . sub_tag_value ( "SURN" ) if maiden : # strip "(maiden)" from family name ending = '(' + maiden + ')' surname = name_tuple [ 1 ] if surname . endswith ( ending ) : surname = surname [ : - len ( ending ) ] . rstrip ( ) if surname == '?' : surname = '' name_tuple = ( name_tuple [ 0 ] , surname , name_tuple [ 2 ] , maiden ) return name_tuple | 8,286 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/name.py#L38-L85 | [
"def",
"find_entries",
"(",
"self",
",",
"users",
",",
"start",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"forever",
"=",
"kwargs",
".",
"get",
"(",
"'all'",
",",
"False",
")",
"for",
"user",
"in",
"users",
":",
"if",
"forever",
":",
"entries",
"=",
"Entry",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
")",
".",
"order_by",
"(",
"'start_time'",
")",
"else",
":",
"entries",
"=",
"Entry",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"start_time__gte",
"=",
"start",
")",
".",
"order_by",
"(",
"'start_time'",
")",
"yield",
"entries"
] |
Parse NAME structure assuming MYHERITAGE dialect . | def parse_name_myher ( record ) : name_tuple = split_name ( record . value ) married = record . sub_tag_value ( "_MARNM" ) if married : maiden = name_tuple [ 1 ] name_tuple = ( name_tuple [ 0 ] , married , name_tuple [ 2 ] , maiden ) return name_tuple | 8,287 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/name.py#L88-L127 | [
"def",
"remove_all_callbacks",
"(",
"self",
")",
":",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_next_tick_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_next_tick_callback",
"(",
"cb_id",
")",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_timeout_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_timeout_callback",
"(",
"cb_id",
")",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_periodic_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_periodic_callback",
"(",
"cb_id",
")"
] |
Maps numbering onto given values | def number ( items ) : n = len ( items ) if n == 0 : return items places = str ( int ( math . log10 ( n ) // 1 + 1 ) ) format = '[{0[0]:' + str ( int ( places ) ) + 'd}] {0[1]}' return map ( lambda x : format . format ( x ) , enumerate ( items ) ) | 8,288 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L35-L45 | [
"def",
"_redis_watcher",
"(",
"state",
")",
":",
"conf",
"=",
"state",
".",
"app",
".",
"config",
"r",
"=",
"redis",
".",
"client",
".",
"StrictRedis",
"(",
"host",
"=",
"conf",
".",
"get",
"(",
"'WAFFLE_REDIS_HOST'",
",",
"'localhost'",
")",
",",
"port",
"=",
"conf",
".",
"get",
"(",
"'WAFFLE_REDIS_PORT'",
",",
"6379",
")",
")",
"sub",
"=",
"r",
".",
"pubsub",
"(",
"ignore_subscribe_messages",
"=",
"True",
")",
"sub",
".",
"subscribe",
"(",
"conf",
".",
"get",
"(",
"'WAFFLE_REDIS_CHANNEL'",
",",
"'waffleconf'",
")",
")",
"while",
"True",
":",
"for",
"msg",
"in",
"sub",
".",
"listen",
"(",
")",
":",
"# Skip non-messages",
"if",
"not",
"msg",
"[",
"'type'",
"]",
"==",
"'message'",
":",
"continue",
"tstamp",
"=",
"float",
"(",
"msg",
"[",
"'data'",
"]",
")",
"# Compare timestamps and update config if needed",
"if",
"tstamp",
">",
"state",
".",
"_tstamp",
":",
"state",
".",
"update_conf",
"(",
")",
"state",
".",
"_tstamp",
"=",
"tstamp"
] |
Return True if yes False if no or the default . | def filter_yn ( string , default = None ) : if string . startswith ( ( 'Y' , 'y' ) ) : return True elif string . startswith ( ( 'N' , 'n' ) ) : return False elif not string and default is not None : return True if default else False raise InvalidInputError | 8,289 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L48-L56 | [
"def",
"GetAllUserSummaries",
"(",
")",
":",
"grr_api",
"=",
"maintenance_utils",
".",
"InitGRRRootAPI",
"(",
")",
"user_wrappers",
"=",
"sorted",
"(",
"grr_api",
".",
"ListGrrUsers",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"username",
")",
"summaries",
"=",
"[",
"_Summarize",
"(",
"w",
".",
"data",
")",
"for",
"w",
"in",
"user_wrappers",
"]",
"return",
"\"\\n\\n\"",
".",
"join",
"(",
"summaries",
")"
] |
Return the input integer or the default . | def filter_int ( string , default = None , start = None , stop = None ) : try : i = int ( string ) if start is not None and i < start : raise InvalidInputError ( "value too small" ) if stop is not None and i >= stop : raise InvalidInputError ( "value too large" ) return i except ValueError : if not string and default is not None : # empty string, default was given return default else : raise InvalidInputError | 8,290 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L59-L73 | [
"def",
"dump_all_handler_stats",
"(",
"self",
")",
":",
"stats",
"=",
"[",
"]",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"now",
"=",
"calendar",
".",
"timegm",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
"rot_time",
"=",
"calendar",
".",
"timegm",
"(",
"h",
"[",
"'log_rot_time'",
"]",
")",
"time_delta",
"=",
"now",
"-",
"rot_time",
"approx_data_rate",
"=",
"'{} bytes/second'",
".",
"format",
"(",
"h",
"[",
"'data_read'",
"]",
"/",
"float",
"(",
"time_delta",
")",
")",
"stats",
".",
"append",
"(",
"{",
"'name'",
":",
"h",
"[",
"'name'",
"]",
",",
"'reads'",
":",
"h",
"[",
"'reads'",
"]",
",",
"'data_read_length'",
":",
"'{} bytes'",
".",
"format",
"(",
"h",
"[",
"'data_read'",
"]",
")",
",",
"'approx_data_rate'",
":",
"approx_data_rate",
"}",
")",
"return",
"stats"
] |
Return the input decimal number or the default . | def filter_decimal ( string , default = None , lower = None , upper = None ) : try : d = decimal . Decimal ( string ) if lower is not None and d < lower : raise InvalidInputError ( "value too small" ) if upper is not None and d >= upper : raise InvalidInputError ( "value too large" ) return d except decimal . InvalidOperation : if not string and default is not None : # empty string, default was given return default else : raise InvalidInputError ( "invalid decimal number" ) | 8,291 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L76-L90 | [
"def",
"jks_pkey_encrypt",
"(",
"key",
",",
"password_str",
")",
":",
"password_bytes",
"=",
"password_str",
".",
"encode",
"(",
"'utf-16be'",
")",
"# Java chars are UTF-16BE code units",
"iv",
"=",
"os",
".",
"urandom",
"(",
"20",
")",
"key",
"=",
"bytearray",
"(",
"key",
")",
"xoring",
"=",
"zip",
"(",
"key",
",",
"_jks_keystream",
"(",
"iv",
",",
"password_bytes",
")",
")",
"data",
"=",
"bytearray",
"(",
"[",
"d",
"^",
"k",
"for",
"d",
",",
"k",
"in",
"xoring",
"]",
")",
"check",
"=",
"hashlib",
".",
"sha1",
"(",
"bytes",
"(",
"password_bytes",
"+",
"key",
")",
")",
".",
"digest",
"(",
")",
"return",
"bytes",
"(",
"iv",
"+",
"data",
"+",
"check",
")"
] |
Coerce to a date not beyond the current date | def filter_pastdate ( string , default = None ) : if not string and default is not None : return default today = datetime . date . today ( ) # split the string try : parts = map ( int , re . split ( '\D+' , string ) ) # split the string except ValueError : raise InvalidInputError ( "invalid date; use format: DD [MM [YYYY]]" ) if len ( parts ) < 1 or len ( parts ) > 3 : raise InvalidInputError ( "invalid date; use format: DD [MM [YYYY]]" ) if len ( parts ) == 1 : # no month or year given; append month parts . append ( today . month - 1 if parts [ 0 ] > today . day else today . month ) if parts [ 1 ] < 1 : parts [ 1 ] = 12 if len ( parts ) == 2 : # no year given; append year if parts [ 1 ] > today . month or parts [ 1 ] == today . month and parts [ 0 ] > today . day : parts . append ( today . year - 1 ) else : parts . append ( today . year ) parts . reverse ( ) try : date = datetime . date ( * parts ) if date > today : raise InvalidInputError ( "cannot choose a date in the future" ) return date except ValueError : print parts raise InvalidInputError ( "invalid date; use format: DD [MM [YYYY]]" ) | 8,292 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L102-L148 | [
"def",
"set_physical_page_for_file",
"(",
"self",
",",
"pageId",
",",
"ocrd_file",
",",
"order",
"=",
"None",
",",
"orderlabel",
"=",
"None",
")",
":",
"# print(pageId, ocrd_file)",
"# delete any page mapping for this file.ID",
"for",
"el_fptr",
"in",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'mets:structMap[@TYPE=\"PHYSICAL\"]/mets:div[@TYPE=\"physSequence\"]/mets:div[@TYPE=\"page\"]/mets:fptr[@FILEID=\"%s\"]'",
"%",
"ocrd_file",
".",
"ID",
",",
"namespaces",
"=",
"NS",
")",
":",
"el_fptr",
".",
"getparent",
"(",
")",
".",
"remove",
"(",
"el_fptr",
")",
"# find/construct as necessary",
"el_structmap",
"=",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'mets:structMap[@TYPE=\"PHYSICAL\"]'",
",",
"NS",
")",
"if",
"el_structmap",
"is",
"None",
":",
"el_structmap",
"=",
"ET",
".",
"SubElement",
"(",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
",",
"TAG_METS_STRUCTMAP",
")",
"el_structmap",
".",
"set",
"(",
"'TYPE'",
",",
"'PHYSICAL'",
")",
"el_seqdiv",
"=",
"el_structmap",
".",
"find",
"(",
"'mets:div[@TYPE=\"physSequence\"]'",
",",
"NS",
")",
"if",
"el_seqdiv",
"is",
"None",
":",
"el_seqdiv",
"=",
"ET",
".",
"SubElement",
"(",
"el_structmap",
",",
"TAG_METS_DIV",
")",
"el_seqdiv",
".",
"set",
"(",
"'TYPE'",
",",
"'physSequence'",
")",
"el_pagediv",
"=",
"el_seqdiv",
".",
"find",
"(",
"'mets:div[@ID=\"%s\"]'",
"%",
"pageId",
",",
"NS",
")",
"if",
"el_pagediv",
"is",
"None",
":",
"el_pagediv",
"=",
"ET",
".",
"SubElement",
"(",
"el_seqdiv",
",",
"TAG_METS_DIV",
")",
"el_pagediv",
".",
"set",
"(",
"'TYPE'",
",",
"'page'",
")",
"el_pagediv",
".",
"set",
"(",
"'ID'",
",",
"pageId",
")",
"if",
"order",
":",
"el_pagediv",
".",
"set",
"(",
"'ORDER'",
",",
"order",
")",
"if",
"orderlabel",
":",
"el_pagediv",
".",
"set",
"(",
"'ORDERLABEL'",
",",
"orderlabel",
")",
"el_fptr",
"=",
"ET",
".",
"SubElement",
"(",
"el_pagediv",
",",
"TAG_METS_FPTR",
")",
"el_fptr",
".",
"set",
"(",
"'FILEID'",
",",
"ocrd_file",
".",
"ID",
")"
] |
Prompt user until valid input is received . | def input ( self , filter_fn , prompt ) : while True : try : return filter_fn ( raw_input ( prompt ) ) except InvalidInputError as e : if e . message : self . show ( 'ERROR: ' + e . message ) except KeyboardInterrupt : raise RejectWarning | 8,293 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L161-L173 | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tree_parent_id",
":",
"url",
"=",
"reverse",
"(",
"'root_homepage'",
")",
"else",
":",
"url",
"=",
"reverse",
"(",
"'category_detail'",
",",
"kwargs",
"=",
"{",
"'category'",
":",
"self",
".",
"tree_path",
"}",
")",
"if",
"self",
".",
"site_id",
"!=",
"settings",
".",
"SITE_ID",
":",
"# prepend the domain if it doesn't match current Site",
"return",
"'http://'",
"+",
"self",
".",
"site",
".",
"domain",
"+",
"url",
"return",
"url"
] |
Prompts the user for some text with optional default | def text ( self , prompt , default = None ) : prompt = prompt if prompt is not None else 'Enter some text' prompt += " [{0}]: " . format ( default ) if default is not None else ': ' return self . input ( curry ( filter_text , default = default ) , prompt ) | 8,294 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L175-L179 | [
"def",
"write",
"(",
"self",
",",
"basename",
"=",
"None",
",",
"write_separate_manifests",
"=",
"True",
")",
":",
"self",
".",
"check_files",
"(",
")",
"n",
"=",
"0",
"for",
"manifest",
"in",
"self",
".",
"partition_dumps",
"(",
")",
":",
"dumpbase",
"=",
"\"%s%05d\"",
"%",
"(",
"basename",
",",
"n",
")",
"dumpfile",
"=",
"\"%s.%s\"",
"%",
"(",
"dumpbase",
",",
"self",
".",
"format",
")",
"if",
"(",
"write_separate_manifests",
")",
":",
"manifest",
".",
"write",
"(",
"basename",
"=",
"dumpbase",
"+",
"'.xml'",
")",
"if",
"(",
"self",
".",
"format",
"==",
"'zip'",
")",
":",
"self",
".",
"write_zip",
"(",
"manifest",
".",
"resources",
",",
"dumpfile",
")",
"elif",
"(",
"self",
".",
"format",
"==",
"'warc'",
")",
":",
"self",
".",
"write_warc",
"(",
"manifest",
".",
"resources",
",",
"dumpfile",
")",
"else",
":",
"raise",
"DumpError",
"(",
"\"Unknown dump format requested (%s)\"",
"%",
"(",
"self",
".",
"format",
")",
")",
"n",
"+=",
"1",
"self",
".",
"logger",
".",
"info",
"(",
"\"Wrote %d dump files\"",
"%",
"(",
"n",
")",
")",
"return",
"(",
"n",
")"
] |
Prompts user to input decimal with optional default and bounds . | def decimal ( self , prompt , default = None , lower = None , upper = None ) : prompt = prompt if prompt is not None else "Enter a decimal number" prompt += " [{0}]: " . format ( default ) if default is not None else ': ' return self . input ( curry ( filter_decimal , default = default , lower = lower , upper = upper ) , prompt ) | 8,295 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L189-L196 | [
"def",
"xor",
"(",
"cls",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"__eval_seqexp",
"(",
"obj",
",",
"operator",
".",
"xor",
",",
"*",
"*",
"kwargs",
")"
] |
Prompts user to input a date in the past . | def pastdate ( self , prompt , default = None ) : prompt = prompt if prompt is not None else "Enter a past date" if default is not None : prompt += " [" + default . strftime ( '%d %m %Y' ) + "]" prompt += ': ' return self . input ( curry ( filter_pastdate , default = default ) , prompt ) | 8,296 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L198-L204 | [
"def",
"get_ligands",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/ligandInfo?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
"'structureId'",
"]",
")"
] |
Prompts the user to choose one item from a list . | def choose ( self , prompt , items , default = None ) : if default is not None and ( default >= len ( items ) or default < 0 ) : raise IndexError prompt = prompt if prompt is not None else "Choose from following:" self . show ( prompt + '\n' ) self . show ( "\n" . join ( number ( items ) ) ) # show the items prompt = "Enter number of chosen item" prompt += " [{0}]: " . format ( default ) if default is not None else ': ' return items [ self . input ( curry ( filter_int , default = default , start = 0 , stop = len ( items ) ) , prompt ) ] | 8,297 | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L217-L233 | [
"def",
"load",
"(",
"dbname",
")",
":",
"db",
"=",
"Database",
"(",
"dbname",
")",
"# Get the name of the objects",
"tables",
"=",
"get_table_list",
"(",
"db",
".",
"cur",
")",
"# Create a Trace instance for each object",
"chains",
"=",
"0",
"for",
"name",
"in",
"tables",
":",
"db",
".",
"_traces",
"[",
"name",
"]",
"=",
"Trace",
"(",
"name",
"=",
"name",
",",
"db",
"=",
"db",
")",
"db",
".",
"_traces",
"[",
"name",
"]",
".",
"_shape",
"=",
"get_shape",
"(",
"db",
".",
"cur",
",",
"name",
")",
"setattr",
"(",
"db",
",",
"name",
",",
"db",
".",
"_traces",
"[",
"name",
"]",
")",
"db",
".",
"cur",
".",
"execute",
"(",
"'SELECT MAX(trace) FROM [%s]'",
"%",
"name",
")",
"chains",
"=",
"max",
"(",
"chains",
",",
"db",
".",
"cur",
".",
"fetchall",
"(",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"+",
"1",
")",
"db",
".",
"chains",
"=",
"chains",
"db",
".",
"trace_names",
"=",
"chains",
"*",
"[",
"tables",
",",
"]",
"db",
".",
"_state_",
"=",
"{",
"}",
"return",
"db"
] |
webpage extraction using Goose Library | def goose_extractor ( url ) : article = Goose ( ) . extract ( url = url ) return article . title , article . meta_description , article . cleaned_text | 8,298 | https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L24-L30 | [
"def",
"wait_for_compactions",
"(",
"self",
",",
"timeout",
"=",
"120",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"\"pending tasks: 0\"",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"output",
",",
"err",
",",
"rc",
"=",
"self",
".",
"nodetool",
"(",
"\"compactionstats\"",
")",
"if",
"pattern",
".",
"search",
"(",
"output",
")",
":",
"return",
"time",
".",
"sleep",
"(",
"1",
")",
"raise",
"TimeoutError",
"(",
"\"{} [{}] Compactions did not finish in {} seconds\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%d %b %Y %H:%M:%S\"",
",",
"time",
".",
"gmtime",
"(",
")",
")",
",",
"self",
".",
"name",
",",
"timeout",
")",
")"
] |
Tokenizer and Stemmer | def _tokenize ( sentence ) : _tokens = nltk . word_tokenize ( sentence ) tokens = [ stemmer . stem ( tk ) for tk in _tokens ] return tokens | 8,299 | https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L32-L37 | [
"def",
"read",
"(",
"self",
",",
"len",
"=",
"1024",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"self",
".",
"_sslobj",
".",
"read",
"(",
"len",
")",
"except",
"SSLError",
":",
"ex",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"ex",
".",
"args",
"[",
"0",
"]",
"==",
"SSL_ERROR_EOF",
"and",
"self",
".",
"suppress_ragged_eofs",
":",
"return",
"b''",
"elif",
"ex",
".",
"args",
"[",
"0",
"]",
"==",
"SSL_ERROR_WANT_READ",
":",
"if",
"self",
".",
"timeout",
"==",
"0.0",
":",
"raise",
"six",
".",
"exc_clear",
"(",
")",
"self",
".",
"_io",
".",
"wait_read",
"(",
"timeout",
"=",
"self",
".",
"timeout",
",",
"timeout_exc",
"=",
"_SSLErrorReadTimeout",
")",
"elif",
"ex",
".",
"args",
"[",
"0",
"]",
"==",
"SSL_ERROR_WANT_WRITE",
":",
"if",
"self",
".",
"timeout",
"==",
"0.0",
":",
"raise",
"six",
".",
"exc_clear",
"(",
")",
"self",
".",
"_io",
".",
"wait_write",
"(",
"timeout",
"=",
"self",
".",
"timeout",
",",
"timeout_exc",
"=",
"_SSLErrorReadTimeout",
")",
"else",
":",
"raise"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.