query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Sets up and serves specified chatrooms . Main entrypoint to Hermes . | def run_server ( chatrooms , use_default_logging = True ) : if use_default_logging : configure_logging ( ) logger . info ( 'Starting Hermes chatroom server...' ) bots = [ ] for name , params in chatrooms . items ( ) : bot_class = params . get ( 'CLASS' , 'hermes.Chatroom' ) if type ( bot_class ) == type : pass else : bot_class_path = bot_class . split ( '.' ) if len ( bot_class_path ) == 1 : module , classname = '__main__' , bot_class_path [ - 1 ] else : module , classname = '.' . join ( bot_class_path [ : - 1 ] ) , bot_class_path [ - 1 ] _ = __import__ ( module , globals ( ) , locals ( ) , [ classname ] ) bot_class = getattr ( _ , classname ) bot = bot_class ( name , params ) bots . append ( bot ) while True : try : logger . info ( "Connecting to servers..." ) sockets = _get_sockets ( bots ) if len ( sockets . keys ( ) ) == 0 : logger . info ( 'No chatrooms defined. Exiting.' ) return _listen ( sockets ) except socket . error , ex : if ex . errno == 9 : logger . exception ( 'broken socket detected' ) else : logger . exception ( 'Unknown socket error %d' % ( ex . errno , ) ) except Exception : logger . exception ( 'Unexpected exception' ) time . sleep ( 1 ) | 10,800 | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/server.py#L23-L67 | [
"def",
"is_dtype_union_equal",
"(",
"source",
",",
"target",
")",
":",
"source",
"=",
"_get_dtype",
"(",
"source",
")",
"target",
"=",
"_get_dtype",
"(",
"target",
")",
"if",
"is_categorical_dtype",
"(",
"source",
")",
"and",
"is_categorical_dtype",
"(",
"target",
")",
":",
"# ordered False for both",
"return",
"source",
".",
"ordered",
"is",
"target",
".",
"ordered",
"return",
"is_dtype_equal",
"(",
"source",
",",
"target",
")"
] |
Connects and gathers sockets for all chatrooms | def _get_sockets ( bots ) : sockets = { } #sockets[sys.stdin] = 'stdio' for bot in bots : bot . connect ( ) sockets [ bot . client . Connection . _sock ] = bot return sockets | 10,801 | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/server.py#L69-L76 | [
"def",
"generate_citation_counter",
"(",
"self",
")",
":",
"cite_counter",
"=",
"dict",
"(",
")",
"filename",
"=",
"'%s.aux'",
"%",
"self",
".",
"project_name",
"with",
"open",
"(",
"filename",
")",
"as",
"fobj",
":",
"main_aux",
"=",
"fobj",
".",
"read",
"(",
")",
"cite_counter",
"[",
"filename",
"]",
"=",
"_count_citations",
"(",
"filename",
")",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'\\\\@input\\{(.*.aux)\\}'",
",",
"main_aux",
")",
":",
"filename",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"try",
":",
"counter",
"=",
"_count_citations",
"(",
"filename",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"cite_counter",
"[",
"filename",
"]",
"=",
"counter",
"return",
"cite_counter"
] |
Main server loop . Listens for incoming events and dispatches them to appropriate chatroom | def _listen ( sockets ) : while True : ( i , o , e ) = select . select ( sockets . keys ( ) , [ ] , [ ] , 1 ) for socket in i : if isinstance ( sockets [ socket ] , Chatroom ) : data_len = sockets [ socket ] . client . Process ( 1 ) if data_len is None or data_len == 0 : raise Exception ( 'Disconnected from server' ) #elif sockets[socket] == 'stdio': # msg = sys.stdin.readline().rstrip('\r\n') # logger.info('stdin: [%s]' % (msg,)) else : raise Exception ( "Unknown socket type: %s" % repr ( sockets [ socket ] ) ) | 10,802 | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/server.py#L78-L91 | [
"def",
"is_url_equal",
"(",
"url",
",",
"other_url",
")",
":",
"# type: (str, str) -> bool",
"if",
"not",
"isinstance",
"(",
"url",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected string for url, received {0!r}\"",
".",
"format",
"(",
"url",
")",
")",
"if",
"not",
"isinstance",
"(",
"other_url",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected string for url, received {0!r}\"",
".",
"format",
"(",
"other_url",
")",
")",
"parsed_url",
"=",
"urllib3_util",
".",
"parse_url",
"(",
"url",
")",
"parsed_other_url",
"=",
"urllib3_util",
".",
"parse_url",
"(",
"other_url",
")",
"unparsed",
"=",
"parsed_url",
".",
"_replace",
"(",
"auth",
"=",
"None",
",",
"query",
"=",
"None",
",",
"fragment",
"=",
"None",
")",
".",
"url",
"unparsed_other",
"=",
"parsed_other_url",
".",
"_replace",
"(",
"auth",
"=",
"None",
",",
"query",
"=",
"None",
",",
"fragment",
"=",
"None",
")",
".",
"url",
"return",
"unparsed",
"==",
"unparsed_other"
] |
Send data to a remote server either with a POST or a PUT request . | def _send ( self , method , path , data , filename ) : if filename is None : return self . _send_json ( method , path , data ) else : return self . _send_file ( method , path , data , filename ) | 10,803 | https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/http/http_requests.py#L123-L139 | [
"def",
"set_forbidden_statuses",
"(",
"self",
",",
"statuses",
")",
":",
"if",
"self",
".",
"_forbidden_status",
"==",
"statuses",
":",
"return",
"self",
".",
"_forbidden_status",
"=",
"statuses",
"self",
".",
"invalidateFilter",
"(",
")"
] |
Returns the content of settings . PLATFORMS with a twist . | def get_platform_settings ( ) : s = settings . PLATFORMS if hasattr ( settings , 'FACEBOOK' ) and settings . FACEBOOK : s . append ( { 'class' : 'bernard.platforms.facebook.platform.Facebook' , 'settings' : settings . FACEBOOK , } ) return s | 10,804 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L39-L58 | [
"def",
"loadWallet",
"(",
"self",
",",
"fpath",
")",
":",
"if",
"not",
"fpath",
":",
"raise",
"ValueError",
"(",
"\"empty path\"",
")",
"_fpath",
"=",
"self",
".",
"_normalize",
"(",
"fpath",
")",
"_dpath",
"=",
"_fpath",
".",
"parent",
"try",
":",
"_dpath",
".",
"relative_to",
"(",
"self",
".",
"_baseDir",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"path {} is not is not relative to the wallets {}\"",
".",
"format",
"(",
"fpath",
",",
"self",
".",
"_baseDir",
")",
")",
"with",
"_fpath",
".",
"open",
"(",
")",
"as",
"wf",
":",
"wallet",
"=",
"self",
".",
"decode",
"(",
"wf",
".",
"read",
"(",
")",
")",
"return",
"wallet"
] |
Run checks on itself and on the FSM | async def run_checks ( self ) : async for check in self . fsm . health_check ( ) : yield check async for check in self . self_check ( ) : yield check for check in MiddlewareManager . health_check ( ) : yield check | 10,805 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L109-L121 | [
"def",
"recompress_archive",
"(",
"archive",
",",
"verbosity",
"=",
"0",
",",
"interactive",
"=",
"True",
")",
":",
"util",
".",
"check_existing_filename",
"(",
"archive",
")",
"util",
".",
"check_writable_filename",
"(",
"archive",
")",
"if",
"verbosity",
">=",
"0",
":",
"util",
".",
"log_info",
"(",
"\"Recompressing %s ...\"",
"%",
"(",
"archive",
",",
")",
")",
"res",
"=",
"_recompress_archive",
"(",
"archive",
",",
"verbosity",
"=",
"verbosity",
",",
"interactive",
"=",
"interactive",
")",
"if",
"res",
"and",
"verbosity",
">=",
"0",
":",
"util",
".",
"log_info",
"(",
"res",
")",
"return",
"0"
] |
Checks that the platforms configuration is all right . | async def self_check ( self ) : platforms = set ( ) for platform in get_platform_settings ( ) : try : name = platform [ 'class' ] cls : Type [ Platform ] = import_class ( name ) except KeyError : yield HealthCheckFail ( '00004' , 'Missing platform `class` name in configuration.' ) except ( AttributeError , ImportError , ValueError ) : yield HealthCheckFail ( '00003' , f'Platform "{name}" cannot be imported.' ) else : if cls in platforms : yield HealthCheckFail ( '00002' , f'Platform "{name}" is imported more than once.' ) platforms . add ( cls ) # noinspection PyTypeChecker async for check in cls . self_check ( ) : yield check | 10,806 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L123-L154 | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_path",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_file_path",
"temp_path",
"=",
"self",
".",
"context",
".",
"work_path",
"if",
"self",
".",
"_content_hash",
"is",
"not",
"None",
":",
"self",
".",
"_file_path",
"=",
"storage",
".",
"load_file",
"(",
"self",
".",
"_content_hash",
",",
"temp_path",
"=",
"temp_path",
")",
"return",
"self",
".",
"_file_path",
"if",
"self",
".",
"response",
"is",
"not",
"None",
":",
"self",
".",
"_file_path",
"=",
"random_filename",
"(",
"temp_path",
")",
"content_hash",
"=",
"sha1",
"(",
")",
"with",
"open",
"(",
"self",
".",
"_file_path",
",",
"'wb'",
")",
"as",
"fh",
":",
"for",
"chunk",
"in",
"self",
".",
"response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"8192",
")",
":",
"content_hash",
".",
"update",
"(",
"chunk",
")",
"fh",
".",
"write",
"(",
"chunk",
")",
"self",
".",
"_remove_file",
"=",
"True",
"chash",
"=",
"content_hash",
".",
"hexdigest",
"(",
")",
"self",
".",
"_content_hash",
"=",
"storage",
".",
"archive_file",
"(",
"self",
".",
"_file_path",
",",
"content_hash",
"=",
"chash",
")",
"if",
"self",
".",
"http",
".",
"cache",
"and",
"self",
".",
"ok",
":",
"self",
".",
"context",
".",
"set_tag",
"(",
"self",
".",
"request_id",
",",
"self",
".",
"serialize",
"(",
")",
")",
"self",
".",
"retrieved_at",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"return",
"self",
".",
"_file_path"
] |
Build a name index for all platform classes | def _index_classes ( self ) -> Dict [ Text , Type [ Platform ] ] : out = { } for p in get_platform_settings ( ) : cls : Type [ Platform ] = import_class ( p [ 'class' ] ) if 'name' in p : out [ p [ 'name' ] ] = cls else : out [ cls . NAME ] = cls return out | 10,807 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L156-L171 | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"snapshot_schedules",
"=",
"file_manager",
".",
"list_volume_schedules",
"(",
"volume_id",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'active'",
",",
"'type'",
",",
"'replication'",
",",
"'date_created'",
",",
"'minute'",
",",
"'hour'",
",",
"'day'",
",",
"'week'",
",",
"'day_of_week'",
",",
"'date_of_month'",
",",
"'month_of_year'",
",",
"'maximum_snapshots'",
"]",
")",
"for",
"schedule",
"in",
"snapshot_schedules",
":",
"if",
"'REPLICATION'",
"in",
"schedule",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
":",
"replication",
"=",
"'*'",
"else",
":",
"replication",
"=",
"formatting",
".",
"blank",
"(",
")",
"file_schedule_type",
"=",
"schedule",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
".",
"replace",
"(",
"'REPLICATION_'",
",",
"''",
")",
"file_schedule_type",
"=",
"file_schedule_type",
".",
"replace",
"(",
"'SNAPSHOT_'",
",",
"''",
")",
"property_list",
"=",
"[",
"'MINUTE'",
",",
"'HOUR'",
",",
"'DAY'",
",",
"'WEEK'",
",",
"'DAY_OF_WEEK'",
",",
"'DAY_OF_MONTH'",
",",
"'MONTH_OF_YEAR'",
",",
"'SNAPSHOT_LIMIT'",
"]",
"schedule_properties",
"=",
"[",
"]",
"for",
"prop_key",
"in",
"property_list",
":",
"item",
"=",
"formatting",
".",
"blank",
"(",
")",
"for",
"schedule_property",
"in",
"schedule",
".",
"get",
"(",
"'properties'",
",",
"[",
"]",
")",
":",
"if",
"schedule_property",
"[",
"'type'",
"]",
"[",
"'keyname'",
"]",
"==",
"prop_key",
":",
"if",
"schedule_property",
"[",
"'value'",
"]",
"==",
"'-1'",
":",
"item",
"=",
"'*'",
"else",
":",
"item",
"=",
"schedule_property",
"[",
"'value'",
"]",
"break",
"schedule_properties",
".",
"append",
"(",
"item",
")",
"table_row",
"=",
"[",
"schedule",
"[",
"'id'",
"]",
",",
"'*'",
"if",
"schedule",
".",
"get",
"(",
"'active'",
",",
"''",
")",
"else",
"''",
",",
"file_schedule_type",
",",
"replication",
",",
"schedule",
".",
"get",
"(",
"'createDate'",
",",
"''",
")",
"]",
"table_row",
".",
"extend",
"(",
"schedule_properties",
")",
"table",
".",
"add_row",
"(",
"table_row",
")",
"env",
".",
"fout",
"(",
"table",
")"
] |
Build the Facebook platform . Nothing fancy . | async def build_platform ( self , cls : Type [ Platform ] , custom_id ) : from bernard . server . http import router p = cls ( ) if custom_id : p . _id = custom_id await p . async_init ( ) p . on_message ( self . fsm . handle_message ) p . hook_up ( router ) return p | 10,808 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L173-L188 | [
"def",
"remove_resource",
"(",
"zone",
",",
"resource_type",
",",
"resource_key",
",",
"resource_value",
")",
":",
"ret",
"=",
"{",
"'status'",
":",
"True",
"}",
"# generate update script",
"cfg_file",
"=",
"salt",
".",
"utils",
".",
"files",
".",
"mkstemp",
"(",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fpopen",
"(",
"cfg_file",
",",
"'w+'",
",",
"mode",
"=",
"0o600",
")",
"as",
"fp_",
":",
"if",
"resource_key",
":",
"fp_",
".",
"write",
"(",
"\"remove {0} {1}={2}\\n\"",
".",
"format",
"(",
"resource_type",
",",
"resource_key",
",",
"_sanitize_value",
"(",
"resource_value",
")",
")",
")",
"else",
":",
"fp_",
".",
"write",
"(",
"\"remove {0}\\n\"",
".",
"format",
"(",
"resource_type",
")",
")",
"# update property",
"if",
"cfg_file",
":",
"_dump_cfg",
"(",
"cfg_file",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'zonecfg -z {zone} -f {path}'",
".",
"format",
"(",
"zone",
"=",
"zone",
",",
"path",
"=",
"cfg_file",
",",
")",
")",
"ret",
"[",
"'status'",
"]",
"=",
"res",
"[",
"'retcode'",
"]",
"==",
"0",
"ret",
"[",
"'message'",
"]",
"=",
"res",
"[",
"'stdout'",
"]",
"if",
"ret",
"[",
"'status'",
"]",
"else",
"res",
"[",
"'stderr'",
"]",
"if",
"ret",
"[",
"'message'",
"]",
"==",
"''",
":",
"del",
"ret",
"[",
"'message'",
"]",
"else",
":",
"ret",
"[",
"'message'",
"]",
"=",
"_clean_message",
"(",
"ret",
"[",
"'message'",
"]",
")",
"# cleanup config file",
"if",
"__salt__",
"[",
"'file.file_exists'",
"]",
"(",
"cfg_file",
")",
":",
"__salt__",
"[",
"'file.remove'",
"]",
"(",
"cfg_file",
")",
"return",
"ret"
] |
For a given platform name gets the matching class | def get_class ( self , platform ) -> Type [ Platform ] : if platform in self . _classes : return self . _classes [ platform ] raise PlatformDoesNotExist ( 'Platform "{}" is not in configuration' . format ( platform ) ) | 10,809 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L190-L199 | [
"def",
"encode",
"(",
"self",
",",
"frame",
":",
"Frame",
")",
"->",
"Frame",
":",
"# Skip control frames.",
"if",
"frame",
".",
"opcode",
"in",
"CTRL_OPCODES",
":",
"return",
"frame",
"# Since we always encode and never fragment messages, there's no logic",
"# similar to decode() here at this time.",
"if",
"frame",
".",
"opcode",
"!=",
"OP_CONT",
":",
"# Re-initialize per-message decoder.",
"if",
"self",
".",
"local_no_context_takeover",
":",
"self",
".",
"encoder",
"=",
"zlib",
".",
"compressobj",
"(",
"wbits",
"=",
"-",
"self",
".",
"local_max_window_bits",
",",
"*",
"*",
"self",
".",
"compress_settings",
")",
"# Compress data frames.",
"data",
"=",
"self",
".",
"encoder",
".",
"compress",
"(",
"frame",
".",
"data",
")",
"+",
"self",
".",
"encoder",
".",
"flush",
"(",
"zlib",
".",
"Z_SYNC_FLUSH",
")",
"if",
"frame",
".",
"fin",
"and",
"data",
".",
"endswith",
"(",
"_EMPTY_UNCOMPRESSED_BLOCK",
")",
":",
"data",
"=",
"data",
"[",
":",
"-",
"4",
"]",
"# Allow garbage collection of the encoder if it won't be reused.",
"if",
"frame",
".",
"fin",
"and",
"self",
".",
"local_no_context_takeover",
":",
"del",
"self",
".",
"encoder",
"return",
"frame",
".",
"_replace",
"(",
"data",
"=",
"data",
",",
"rsv1",
"=",
"True",
")"
] |
Get a valid instance of the specified platform . Do not cache this object it might change with configuration changes . | async def get_platform ( self , name : Text ) : if not self . _is_init : await self . init ( ) if name not in self . platforms : self . platforms [ name ] = await self . build_platform ( self . get_class ( name ) , name ) return self . platforms [ name ] | 10,810 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L201-L214 | [
"def",
"on_end_validation",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"Enable",
"(",
")",
"self",
".",
"Show",
"(",
")",
"self",
".",
"magic_gui_frame",
".",
"Destroy",
"(",
")"
] |
Returns all platform instances | async def get_all_platforms ( self ) -> AsyncIterator [ Platform ] : for name in self . _classes . keys ( ) : yield await self . get_platform ( name ) | 10,811 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L216-L222 | [
"def",
"editLogSettings",
"(",
"self",
",",
"logLocation",
",",
"logLevel",
"=",
"\"WARNING\"",
",",
"maxLogFileAge",
"=",
"90",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/settings/edit\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"logDir\"",
":",
"logLocation",
",",
"\"logLevel\"",
":",
"logLevel",
",",
"\"maxLogFileAge\"",
":",
"maxLogFileAge",
"}",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Given an authentication token find the right platform that can recognize this token and create a message for this platform . | async def message_from_token ( self , token : Text , payload : Any ) -> Tuple [ Optional [ BaseMessage ] , Optional [ Platform ] ] : async for platform in self . get_all_platforms ( ) : m = await platform . message_from_token ( token , payload ) if m : return m , platform return None , None | 10,812 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L224-L239 | [
"def",
"get_random",
"(",
"self",
",",
"size",
"=",
"10",
")",
":",
"bin_i",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"np",
".",
"arange",
"(",
"len",
"(",
"self",
".",
"bin_centers",
")",
")",
",",
"size",
"=",
"size",
",",
"p",
"=",
"self",
".",
"normalized_histogram",
")",
"return",
"self",
".",
"bin_centers",
"[",
"bin_i",
"]",
"+",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"0.5",
",",
"0.5",
",",
"size",
"=",
"size",
")",
"*",
"self",
".",
"bin_volumes",
"(",
")",
"[",
"bin_i",
"]"
] |
Extends a commandline argument parser with arguments for specifying read sources . | def add_args ( parser , positional = False ) : group = parser . add_argument_group ( "read loading" ) group . add_argument ( "reads" if positional else "--reads" , nargs = "+" , default = [ ] , help = "Paths to bam files. Any number of paths may be specified." ) group . add_argument ( "--read-source-name" , nargs = "+" , help = "Names for each read source. The number of names specified " "must match the number of bam files. If not specified, filenames are " "used for names." ) # Add filters group = parser . add_argument_group ( "read filtering" , "A number of read filters are available. See the pysam " "documentation (http://pysam.readthedocs.org/en/latest/api.html) " "for details on what these fields mean. When multiple filter " "options are specified, reads must match *all* filters." ) for ( name , ( kind , message , function ) ) in READ_FILTERS . items ( ) : extra = { } if kind is bool : extra [ "action" ] = "store_true" extra [ "default" ] = None elif kind is int : extra [ "type" ] = int extra [ "metavar" ] = "N" elif kind is str : extra [ "metavar" ] = "STRING" group . add_argument ( "--" + name . replace ( "_" , "-" ) , help = message , * * extra ) | 10,813 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/reads_util.py#L104-L141 | [
"def",
"invert_dict",
"(",
"invertible_dict",
")",
":",
"inverted",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"invertible_dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"Hashable",
")",
":",
"raise",
"TypeError",
"(",
"u'Expected an invertible dict, but value at key {} has type {}'",
".",
"format",
"(",
"k",
",",
"type",
"(",
"v",
")",
".",
"__name__",
")",
")",
"if",
"v",
"in",
"inverted",
":",
"raise",
"TypeError",
"(",
"u'Expected an invertible dict, but keys '",
"u'{} and {} map to the same value'",
".",
"format",
"(",
"inverted",
"[",
"v",
"]",
",",
"k",
")",
")",
"inverted",
"[",
"v",
"]",
"=",
"k",
"return",
"inverted"
] |
Given parsed commandline arguments returns a list of ReadSource objects | def load_from_args ( args ) : if not args . reads : return None if args . read_source_name : read_source_names = util . expand ( args . read_source_name , 'read_source_name' , 'read source' , len ( args . reads ) ) else : read_source_names = util . drop_prefix ( args . reads ) filters = [ ] for ( name , info ) in READ_FILTERS . items ( ) : value = getattr ( args , name ) if value is not None : filters . append ( functools . partial ( info [ - 1 ] , value ) ) return [ load_bam ( filename , name , filters ) for ( filename , name ) in zip ( args . reads , read_source_names ) ] | 10,814 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/reads_util.py#L143-L169 | [
"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",
")"
] |
A helper to retrieve an integer value from a given dictionary containing string values . If the requested value is not present in the dictionary or if it cannot be converted to an integer a default value will be returned instead . | def get_int ( config , key , default ) : try : return int ( config [ key ] ) except ( KeyError , ValueError ) : return default | 10,815 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L64-L83 | [
"def",
"_elapsed",
"(",
"self",
")",
":",
"self",
".",
"last_time",
"=",
"time",
".",
"time",
"(",
")",
"return",
"self",
".",
"last_time",
"-",
"self",
".",
"start"
] |
Perform the compaction operation . This reads in the bucket information from the database builds a compacted bucket record inserts that record in the appropriate place in the database then removes outdated updates . | def compact_bucket ( db , buck_key , limit ) : # Suck in the bucket records and generate our bucket records = db . lrange ( str ( buck_key ) , 0 , - 1 ) loader = limits . BucketLoader ( limit . bucket_class , db , limit , str ( buck_key ) , records , stop_summarize = True ) # We now have the bucket loaded in; generate a 'bucket' record buck_record = msgpack . dumps ( dict ( bucket = loader . bucket . dehydrate ( ) , uuid = str ( uuid . uuid4 ( ) ) ) ) # Now we need to insert it into the record list result = db . linsert ( str ( buck_key ) , 'after' , loader . last_summarize_rec , buck_record ) # Were we successful? if result < 0 : # Insert failed; we'll try again when max_age is hit LOG . warning ( "Bucket compaction on %s failed; will retry" % buck_key ) return # OK, we have confirmed that the compacted bucket record has been # inserted correctly; now all we need to do is trim off the # outdated update records db . ltrim ( str ( buck_key ) , loader . last_summarize_idx + 1 , - 1 ) | 10,816 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L379-L415 | [
"def",
"request_all_data",
"(",
"cls",
",",
"time",
",",
"pressure",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"cls",
"(",
")",
"df",
"=",
"endpoint",
".",
"_get_data",
"(",
"time",
",",
"None",
",",
"pressure",
",",
"*",
"*",
"kwargs",
")",
"return",
"df"
] |
The compactor daemon . This fuction watches the sorted set containing bucket keys that need to be compacted performing the necessary compaction . | def compactor ( conf ) : # Get the database handle db = conf . get_database ( 'compactor' ) # Get the limits container limit_map = LimitContainer ( conf , db ) # Get the compactor configuration config = conf [ 'compactor' ] # Make sure compaction is enabled if get_int ( config , 'max_updates' , 0 ) <= 0 : # We'll just warn about it, since they could be running # the compactor with a different configuration file LOG . warning ( "Compaction is not enabled. Enable it by " "setting a positive integer value for " "'compactor.max_updates' in the configuration." ) # Select the bucket key getter key_getter = GetBucketKey . factory ( config , db ) LOG . info ( "Compactor initialized" ) # Now enter our loop while True : # Get a bucket key to compact try : buck_key = limits . BucketKey . decode ( key_getter ( ) ) except ValueError as exc : # Warn about invalid bucket keys LOG . warning ( "Error interpreting bucket key: %s" % exc ) continue # Ignore version 1 keys--they can't be compacted if buck_key . version < 2 : continue # Get the corresponding limit class try : limit = limit_map [ buck_key . uuid ] except KeyError : # Warn about missing limits LOG . warning ( "Unable to compact bucket for limit %s" % buck_key . uuid ) continue LOG . debug ( "Compacting bucket %s" % buck_key ) # OK, we now have the limit (which we really only need for # the bucket class); let's compact the bucket try : compact_bucket ( db , buck_key , limit ) except Exception : LOG . exception ( "Failed to compact bucket %s" % buck_key ) else : LOG . debug ( "Finished compacting bucket %s" % buck_key ) | 10,817 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L418-L485 | [
"def",
"random_date",
"(",
")",
":",
"d",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"d",
"=",
"d",
"-",
"datetime",
".",
"timedelta",
"(",
"random",
".",
"randint",
"(",
"20",
",",
"2001",
")",
")",
"return",
"d"
] |
Given a configuration and database select and return an appropriate instance of a subclass of GetBucketKey . This will ensure that both client and server support are available for the Lua script feature of Redis and if not a lock will be used . | def factory ( cls , config , db ) : # Make sure that the client supports register_script() if not hasattr ( db , 'register_script' ) : LOG . debug ( "Redis client does not support register_script()" ) return GetBucketKeyByLock ( config , db ) # OK, the client supports register_script(); what about the # server? info = db . info ( ) if version_greater ( '2.6' , info [ 'redis_version' ] ) : LOG . debug ( "Redis server supports register_script()" ) return GetBucketKeyByScript ( config , db ) # OK, use our fallback... LOG . debug ( "Redis server does not support register_script()" ) return GetBucketKeyByLock ( config , db ) | 10,818 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L99-L128 | [
"def",
"print_search_results",
"(",
"self",
",",
"search_results",
",",
"buf",
"=",
"sys",
".",
"stdout",
")",
":",
"formatted_lines",
"=",
"self",
".",
"format_search_results",
"(",
"search_results",
")",
"pr",
"=",
"Printer",
"(",
"buf",
")",
"for",
"txt",
",",
"style",
"in",
"formatted_lines",
":",
"pr",
"(",
"txt",
",",
"style",
")"
] |
Get a bucket key to compact . If none are available returns None . This uses a configured lock to ensure that the bucket key is popped off the sorted set in an atomic fashion . | def get ( self , now ) : with self . lock : items = self . db . zrangebyscore ( self . key , 0 , now - self . min_age , start = 0 , num = 1 ) # Did we get any items? if not items : return None # Drop the item we got item = items [ 0 ] self . db . zrem ( item ) return item | 10,819 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L210-L236 | [
"def",
"get_characters",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"character",
"import",
"Character",
",",
"CharacterDataWrapper",
"return",
"self",
".",
"get_related_resource",
"(",
"Character",
",",
"CharacterDataWrapper",
",",
"args",
",",
"kwargs",
")"
] |
Get a bucket key to compact . If none are available returns None . This uses a Lua script to ensure that the bucket key is popped off the sorted set in an atomic fashion . | def get ( self , now ) : items = self . script ( keys = [ self . key ] , args = [ now - self . min_age ] ) return items [ 0 ] if items else None | 10,820 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L265-L281 | [
"def",
"is_registration_possible",
"(",
"self",
",",
"user_info",
")",
":",
"return",
"self",
".",
"get_accessibility",
"(",
")",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"_registration",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"is_user_accepted_by_access_control",
"(",
"user_info",
")"
] |
Parse given text and produce a list of inline elements . | def parse ( text , elements , fallback ) : # this is a raw list of elements that may contain overlaps. tokens = [ ] for etype in elements : for match in etype . find ( text ) : tokens . append ( Token ( etype , match , text , fallback ) ) tokens . sort ( ) tokens = _resolve_overlap ( tokens ) return make_elements ( tokens , text , fallback = fallback ) | 10,821 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L12-L26 | [
"def",
"similarity",
"(",
"self",
",",
"other",
")",
":",
"sim",
"=",
"self",
".",
"Similarity",
"(",
")",
"total",
"=",
"0.0",
"# Calculate similarity ratio for each attribute",
"cname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"for",
"aname",
",",
"weight",
"in",
"self",
".",
"attributes",
".",
"items",
"(",
")",
":",
"attr1",
"=",
"getattr",
"(",
"self",
",",
"aname",
",",
"None",
")",
"attr2",
"=",
"getattr",
"(",
"other",
",",
"aname",
",",
"None",
")",
"self",
".",
"log",
"(",
"attr1",
",",
"attr2",
",",
"'%'",
",",
"cname",
"=",
"cname",
",",
"aname",
"=",
"aname",
")",
"# Similarity is ignored if None on both objects",
"if",
"attr1",
"is",
"None",
"and",
"attr2",
"is",
"None",
":",
"self",
".",
"log",
"(",
"attr1",
",",
"attr2",
",",
"'%'",
",",
"cname",
"=",
"cname",
",",
"aname",
"=",
"aname",
",",
"result",
"=",
"\"attributes are both None\"",
")",
"continue",
"# Similarity is 0 if either attribute is non-Comparable",
"if",
"not",
"all",
"(",
"(",
"isinstance",
"(",
"attr1",
",",
"Comparable",
")",
",",
"isinstance",
"(",
"attr2",
",",
"Comparable",
")",
")",
")",
":",
"self",
".",
"log",
"(",
"attr1",
",",
"attr2",
",",
"'%'",
",",
"cname",
"=",
"cname",
",",
"aname",
"=",
"aname",
",",
"result",
"=",
"\"attributes not Comparable\"",
")",
"total",
"+=",
"weight",
"continue",
"# Calculate similarity between the attributes",
"attr_sim",
"=",
"(",
"attr1",
"%",
"attr2",
")",
"self",
".",
"log",
"(",
"attr1",
",",
"attr2",
",",
"'%'",
",",
"cname",
"=",
"cname",
",",
"aname",
"=",
"aname",
",",
"result",
"=",
"attr_sim",
")",
"# Add the similarity to the total",
"sim",
"+=",
"attr_sim",
"*",
"weight",
"total",
"+=",
"weight",
"# Scale the similarity so the total is 1.0",
"if",
"total",
":",
"sim",
"*=",
"(",
"1.0",
"/",
"total",
")",
"return",
"sim"
] |
Make elements from a list of parsed tokens . It will turn all unmatched holes into fallback elements . | def make_elements ( tokens , text , start = 0 , end = None , fallback = None ) : result = [ ] end = end or len ( text ) prev_end = start for token in tokens : if prev_end < token . start : result . append ( fallback ( text [ prev_end : token . start ] ) ) result . append ( token . as_element ( ) ) prev_end = token . end if prev_end < end : result . append ( fallback ( text [ prev_end : end ] ) ) return result | 10,822 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L47-L68 | [
"def",
"_aggregate",
"(",
"self",
",",
"instanceId",
",",
"container",
",",
"value",
",",
"subKey",
"=",
"None",
")",
":",
"# Get the aggregator.",
"if",
"instanceId",
"not",
"in",
"self",
".",
"_aggregators",
":",
"self",
".",
"_aggregators",
"[",
"instanceId",
"]",
"=",
"_Stats",
".",
"getAggregator",
"(",
"instanceId",
",",
"self",
".",
"__name",
")",
"aggregator",
"=",
"self",
".",
"_aggregators",
"[",
"instanceId",
"]",
"# If we are aggregating, get the old value.",
"if",
"aggregator",
":",
"oldValue",
"=",
"container",
".",
"get",
"(",
"self",
".",
"__name",
")",
"if",
"subKey",
":",
"oldValue",
"=",
"oldValue",
"[",
"subKey",
"]",
"aggregator",
"[",
"0",
"]",
".",
"update",
"(",
"aggregator",
"[",
"1",
"]",
",",
"oldValue",
",",
"value",
",",
"subKey",
")",
"else",
":",
"aggregator",
"[",
"0",
"]",
".",
"update",
"(",
"aggregator",
"[",
"1",
"]",
",",
"oldValue",
",",
"value",
")"
] |
CLI minimal interface . | def main_cli ( ) : # Get params args = _cli_argument_parser ( ) delta_secs = args . delay i2cbus = args . bus i2c_address = args . address sensor_key = args . sensor sensor_params = args . params params = { } if sensor_params : def _parse_param ( str_param ) : key , value = str_param . split ( '=' ) try : value = int ( value ) except ValueError : pass return { key . strip ( ) : value } [ params . update ( _parse_param ( sp ) ) for sp in sensor_params ] if sensor_key : from time import sleep # Bus init try : # noinspection PyUnresolvedReferences import smbus bus_handler = smbus . SMBus ( i2cbus ) except ImportError as exc : print ( exc , "\n" , "Please install smbus-cffi before." ) sys . exit ( - 1 ) # Sensor selection try : sensor_handler , i2c_default_address = SENSORS [ sensor_key ] except KeyError : print ( "'%s' is not recognized as an implemented i2c sensor." % sensor_key ) sys . exit ( - 1 ) if i2c_address : i2c_address = hex ( int ( i2c_address , 0 ) ) else : i2c_address = i2c_default_address # Sensor init sensor = sensor_handler ( bus_handler , i2c_address , * * params ) # Infinite loop try : while True : sensor . update ( ) if not sensor . sample_ok : print ( "An error has occured." ) break print ( sensor . current_state_str ) sleep ( delta_secs ) except KeyboardInterrupt : print ( "Bye!" ) else : # Run detection mode from subprocess import check_output cmd = '/usr/sbin/i2cdetect -y {}' . format ( i2cbus ) try : output = check_output ( cmd . split ( ) ) print ( "Running i2cdetect utility in i2c bus {}:\n" "The command '{}' has returned:\n{}" . format ( i2cbus , cmd , output . decode ( ) ) ) except FileNotFoundError : print ( "Please install i2cdetect before." ) sys . exit ( - 1 ) # Parse output addresses = [ '0x' + l for line in output . decode ( ) . splitlines ( ) [ 1 : ] for l in line . split ( ) [ 1 : ] if l != '--' ] if addresses : print ( "{} sensors detected in {}" . format ( len ( addresses ) , ', ' . join ( addresses ) ) ) else : print ( "No i2c sensors detected." ) | 10,823 | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__main__.py#L60-L139 | [
"def",
"delete_secret_versions",
"(",
"self",
",",
"path",
",",
"versions",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"if",
"not",
"isinstance",
"(",
"versions",
",",
"list",
")",
"or",
"len",
"(",
"versions",
")",
"==",
"0",
":",
"error_msg",
"=",
"'argument to \"versions\" must be a list containing one or more integers, \"{versions}\" provided.'",
".",
"format",
"(",
"versions",
"=",
"versions",
")",
"raise",
"exceptions",
".",
"ParamValidationError",
"(",
"error_msg",
")",
"params",
"=",
"{",
"'versions'",
":",
"versions",
",",
"}",
"api_path",
"=",
"'/v1/{mount_point}/delete/{path}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"path",
"=",
"path",
")",
"return",
"self",
".",
"_adapter",
".",
"post",
"(",
"url",
"=",
"api_path",
",",
"json",
"=",
"params",
",",
")"
] |
Extracts just the domain name from an URL and adds it to a list | def extract_domain ( var_name , output ) : var = getenv ( var_name ) if var : p = urlparse ( var ) output . append ( p . hostname ) | 10,824 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/examples/number_bot/src/number_bot/settings.py#L11-L20 | [
"def",
"_ion_equals",
"(",
"a",
",",
"b",
",",
"timestamp_comparison_func",
",",
"recursive_comparison_func",
")",
":",
"for",
"a",
",",
"b",
"in",
"(",
"(",
"a",
",",
"b",
")",
",",
"(",
"b",
",",
"a",
")",
")",
":",
"# Ensures that operand order does not matter.",
"if",
"isinstance",
"(",
"a",
",",
"_IonNature",
")",
":",
"if",
"isinstance",
"(",
"b",
",",
"_IonNature",
")",
":",
"# Both operands have _IonNature. Their IonTypes and annotations must be equivalent.",
"eq",
"=",
"a",
".",
"ion_type",
"is",
"b",
".",
"ion_type",
"and",
"_annotations_eq",
"(",
"a",
",",
"b",
")",
"else",
":",
"# Only one operand has _IonNature. It cannot be equivalent to the other operand if it has annotations.",
"eq",
"=",
"not",
"a",
".",
"ion_annotations",
"if",
"eq",
":",
"if",
"isinstance",
"(",
"a",
",",
"IonPyList",
")",
":",
"return",
"_sequences_eq",
"(",
"a",
",",
"b",
",",
"recursive_comparison_func",
")",
"elif",
"isinstance",
"(",
"a",
",",
"IonPyDict",
")",
":",
"return",
"_structs_eq",
"(",
"a",
",",
"b",
",",
"recursive_comparison_func",
")",
"elif",
"isinstance",
"(",
"a",
",",
"IonPyTimestamp",
")",
":",
"return",
"timestamp_comparison_func",
"(",
"a",
",",
"b",
")",
"elif",
"isinstance",
"(",
"a",
",",
"IonPyNull",
")",
":",
"return",
"isinstance",
"(",
"b",
",",
"IonPyNull",
")",
"or",
"(",
"b",
"is",
"None",
"and",
"a",
".",
"ion_type",
"is",
"IonType",
".",
"NULL",
")",
"elif",
"isinstance",
"(",
"a",
",",
"IonPySymbol",
")",
"or",
"(",
"isinstance",
"(",
"a",
",",
"IonPyText",
")",
"and",
"a",
".",
"ion_type",
"is",
"IonType",
".",
"SYMBOL",
")",
":",
"return",
"_symbols_eq",
"(",
"a",
",",
"b",
")",
"elif",
"isinstance",
"(",
"a",
",",
"IonPyDecimal",
")",
":",
"return",
"_decimals_eq",
"(",
"a",
",",
"b",
")",
"elif",
"isinstance",
"(",
"a",
",",
"IonPyFloat",
")",
":",
"return",
"_floats_eq",
"(",
"a",
",",
"b",
")",
"else",
":",
"return",
"a",
"==",
"b",
"return",
"False",
"# Reaching this point means that neither operand has _IonNature.",
"for",
"a",
",",
"b",
"in",
"(",
"(",
"a",
",",
"b",
")",
",",
"(",
"b",
",",
"a",
")",
")",
":",
"# Ensures that operand order does not matter.",
"if",
"isinstance",
"(",
"a",
",",
"list",
")",
":",
"return",
"_sequences_eq",
"(",
"a",
",",
"b",
",",
"recursive_comparison_func",
")",
"elif",
"isinstance",
"(",
"a",
",",
"dict",
")",
":",
"return",
"_structs_eq",
"(",
"a",
",",
"b",
",",
"recursive_comparison_func",
")",
"elif",
"isinstance",
"(",
"a",
",",
"datetime",
")",
":",
"return",
"timestamp_comparison_func",
"(",
"a",
",",
"b",
")",
"elif",
"isinstance",
"(",
"a",
",",
"SymbolToken",
")",
":",
"return",
"_symbols_eq",
"(",
"a",
",",
"b",
")",
"elif",
"isinstance",
"(",
"a",
",",
"Decimal",
")",
":",
"return",
"_decimals_eq",
"(",
"a",
",",
"b",
")",
"elif",
"isinstance",
"(",
"a",
",",
"float",
")",
":",
"return",
"_floats_eq",
"(",
"a",
",",
"b",
")",
"return",
"a",
"==",
"b"
] |
return the number of channels present in samples | def numchannels ( samples : np . ndarray ) -> int : if len ( samples . shape ) == 1 : return 1 else : return samples . shape [ 1 ] | 10,825 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/util.py#L5-L19 | [
"def",
"_get_cursor",
"(",
"self",
",",
"n_retries",
"=",
"1",
")",
":",
"n_tries_rem",
"=",
"n_retries",
"+",
"1",
"while",
"n_tries_rem",
">",
"0",
":",
"try",
":",
"conn",
"=",
"self",
".",
"_pool",
".",
"getconn",
"(",
")",
"if",
"self",
".",
"pooling",
"else",
"self",
".",
"_conn",
"# autocommit=True obviates closing explicitly",
"conn",
".",
"autocommit",
"=",
"True",
"cur",
"=",
"conn",
".",
"cursor",
"(",
"cursor_factory",
"=",
"psycopg2",
".",
"extras",
".",
"DictCursor",
")",
"cur",
".",
"execute",
"(",
"\"set search_path = {self.url.schema};\"",
".",
"format",
"(",
"self",
"=",
"self",
")",
")",
"yield",
"cur",
"# contextmanager executes these when context exits",
"cur",
".",
"close",
"(",
")",
"if",
"self",
".",
"pooling",
":",
"self",
".",
"_pool",
".",
"putconn",
"(",
"conn",
")",
"break",
"except",
"psycopg2",
".",
"OperationalError",
":",
"_logger",
".",
"warning",
"(",
"\"Lost connection to {url}; attempting reconnect\"",
".",
"format",
"(",
"url",
"=",
"self",
".",
"url",
")",
")",
"if",
"self",
".",
"pooling",
":",
"self",
".",
"_pool",
".",
"closeall",
"(",
")",
"self",
".",
"_connect",
"(",
")",
"_logger",
".",
"warning",
"(",
"\"Reconnected to {url}\"",
".",
"format",
"(",
"url",
"=",
"self",
".",
"url",
")",
")",
"n_tries_rem",
"-=",
"1",
"else",
":",
"# N.B. Probably never reached",
"raise",
"HGVSError",
"(",
"\"Permanently lost connection to {url} ({n} retries)\"",
".",
"format",
"(",
"url",
"=",
"self",
".",
"url",
",",
"n",
"=",
"n_retries",
")",
")"
] |
Factory function for turnstile . | def turnstile_filter ( global_conf , * * local_conf ) : # Select the appropriate middleware class to return klass = TurnstileMiddleware if 'turnstile' in local_conf : klass = utils . find_entrypoint ( 'turnstile.middleware' , local_conf [ 'turnstile' ] , required = True ) def wrapper ( app ) : return klass ( app , local_conf ) return wrapper | 10,826 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/middleware.py#L133-L150 | [
"def",
"delete_user",
"(",
"self",
",",
"user",
")",
":",
"assert",
"self",
".",
"user",
"==",
"'catroot'",
"or",
"self",
".",
"user",
"==",
"'postgres'",
"assert",
"not",
"user",
"==",
"'public'",
"con",
"=",
"self",
".",
"connection",
"or",
"self",
".",
"_connect",
"(",
")",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'DROP SCHEMA {user} CASCADE;'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"cur",
".",
"execute",
"(",
"'REVOKE USAGE ON SCHEMA public FROM {user};'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"cur",
".",
"execute",
"(",
"'REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM {user};'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"cur",
".",
"execute",
"(",
"'DROP ROLE {user};'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'REMOVED USER {user}\\n'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"con",
".",
"commit",
"(",
")",
"con",
".",
"close",
"(",
")",
"return",
"self"
] |
Formats the over - limit response for the request . May be overridden in subclasses to allow alternate responses . | def format_delay ( self , delay , limit , bucket , environ , start_response ) : # Set up the default status status = self . conf . status # Set up the retry-after header... headers = HeadersDict ( [ ( 'Retry-After' , "%d" % math . ceil ( delay ) ) ] ) # Let format fiddle with the headers status , entity = limit . format ( status , headers , environ , bucket , delay ) # Return the response start_response ( status , headers . items ( ) ) return entity | 10,827 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/middleware.py#L337-L355 | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
"and",
"not",
"self",
".",
"is_connecting",
"(",
")",
":",
"return",
"LOG",
".",
"debug",
"(",
"\"disconnecting from %s...\"",
",",
"self",
".",
"_redis_server",
"(",
")",
")",
"self",
".",
"__periodic_callback",
".",
"stop",
"(",
")",
"try",
":",
"self",
".",
"_ioloop",
".",
"remove_handler",
"(",
"self",
".",
"__socket_fileno",
")",
"self",
".",
"_listened_events",
"=",
"0",
"except",
"Exception",
":",
"pass",
"self",
".",
"__socket_fileno",
"=",
"-",
"1",
"try",
":",
"self",
".",
"__socket",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"_state",
".",
"set_disconnected",
"(",
")",
"self",
".",
"_close_callback",
"(",
")",
"LOG",
".",
"debug",
"(",
"\"disconnected from %s\"",
",",
"self",
".",
"_redis_server",
"(",
")",
")"
] |
Finds the first available entrypoint with the given name in the given group . | def find_entrypoint ( group , name , compat = True , required = False ) : if group is None or ( compat and ':' in name ) : try : return pkg_resources . EntryPoint . parse ( "x=" + name ) . load ( False ) except ( ImportError , pkg_resources . UnknownExtra ) as exc : pass else : for ep in pkg_resources . iter_entry_points ( group , name ) : try : # Load and return the object return ep . load ( ) except ( ImportError , pkg_resources . UnknownExtra ) : # Couldn't load it; try the next one continue # Raise an ImportError if requested if required : raise ImportError ( "Cannot import %r entrypoint %r" % ( group , name ) ) # Couldn't find one... return None | 10,828 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/utils.py#L21-L60 | [
"def",
"swd_sync",
"(",
"self",
",",
"pad",
"=",
"False",
")",
":",
"if",
"pad",
":",
"self",
".",
"_dll",
".",
"JLINK_SWD_SyncBytes",
"(",
")",
"else",
":",
"self",
".",
"_dll",
".",
"JLINK_SWD_SyncBits",
"(",
")",
"return",
"None"
] |
Transfer this entity to another owner on the backing persistence layer | def transfer ( self , transfer_payload = None , * , from_user , to_user ) : if self . persist_id is None : raise EntityNotYetPersistedError ( ( 'Entities cannot be transferred ' 'until they have been ' 'persisted' ) ) return self . plugin . transfer ( self . persist_id , transfer_payload , from_user = from_user , to_user = to_user ) | 10,829 | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/entities.py#L409-L442 | [
"def",
"gnuplot",
"(",
"script_name",
",",
"args_dict",
"=",
"{",
"}",
",",
"data",
"=",
"[",
"]",
",",
"silent",
"=",
"True",
")",
":",
"gnuplot_command",
"=",
"'gnuplot'",
"if",
"data",
":",
"assert",
"'data'",
"not",
"in",
"args_dict",
",",
"'Can\\'t use \\'data\\' variable twice.'",
"data_temp",
"=",
"_GnuplotDataTemp",
"(",
"*",
"data",
")",
"args_dict",
"[",
"'data'",
"]",
"=",
"data_temp",
".",
"name",
"if",
"args_dict",
":",
"gnuplot_command",
"+=",
"' -e \"'",
"for",
"arg",
"in",
"args_dict",
".",
"items",
"(",
")",
":",
"gnuplot_command",
"+=",
"arg",
"[",
"0",
"]",
"+",
"'='",
"if",
"isinstance",
"(",
"arg",
"[",
"1",
"]",
",",
"str",
")",
":",
"gnuplot_command",
"+=",
"'\\''",
"+",
"arg",
"[",
"1",
"]",
"+",
"'\\''",
"elif",
"isinstance",
"(",
"arg",
"[",
"1",
"]",
",",
"bool",
")",
":",
"if",
"arg",
"[",
"1",
"]",
"is",
"True",
":",
"gnuplot_command",
"+=",
"'1'",
"else",
":",
"gnuplot_command",
"+=",
"'0'",
"elif",
"hasattr",
"(",
"arg",
"[",
"1",
"]",
",",
"'__iter__'",
")",
":",
"gnuplot_command",
"+=",
"'\\''",
"+",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"arg",
"[",
"1",
"]",
"]",
")",
"+",
"'\\''",
"else",
":",
"gnuplot_command",
"+=",
"str",
"(",
"arg",
"[",
"1",
"]",
")",
"gnuplot_command",
"+=",
"'; '",
"gnuplot_command",
"=",
"gnuplot_command",
"[",
":",
"-",
"1",
"]",
"gnuplot_command",
"+=",
"'\"'",
"gnuplot_command",
"+=",
"' '",
"+",
"script_name",
"if",
"silent",
":",
"gnuplot_command",
"+=",
"' > /dev/null 2>&1'",
"os",
".",
"system",
"(",
"gnuplot_command",
")",
"return",
"gnuplot_command"
] |
Transfer this Right to another owner on the backing persistence layer . | def transfer ( self , rights_assignment_data = None , * , from_user , to_user , rights_assignment_format = 'jsonld' ) : rights_assignment = RightsAssignment . from_data ( rights_assignment_data or { } , plugin = self . plugin ) transfer_payload = rights_assignment . _to_format ( data_format = rights_assignment_format ) transfer_id = super ( ) . transfer ( transfer_payload , from_user = from_user , to_user = to_user ) rights_assignment . persist_id = transfer_id return rights_assignment | 10,830 | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/entities.py#L506-L542 | [
"def",
"makeEndOfPrdvPfuncCond",
"(",
"self",
")",
":",
"# Get data to construct the end-of-period marginal value function (conditional on next state)",
"self",
".",
"aNrm_cond",
"=",
"self",
".",
"prepareToCalcEndOfPrdvP",
"(",
")",
"self",
".",
"EndOfPrdvP_cond",
"=",
"self",
".",
"calcEndOfPrdvPcond",
"(",
")",
"EndOfPrdvPnvrs_cond",
"=",
"self",
".",
"uPinv",
"(",
"self",
".",
"EndOfPrdvP_cond",
")",
"# \"decurved\" marginal value",
"if",
"self",
".",
"CubicBool",
":",
"EndOfPrdvPP_cond",
"=",
"self",
".",
"calcEndOfPrdvPP",
"(",
")",
"EndOfPrdvPnvrsP_cond",
"=",
"EndOfPrdvPP_cond",
"*",
"self",
".",
"uPinvP",
"(",
"self",
".",
"EndOfPrdvP_cond",
")",
"# \"decurved\" marginal marginal value",
"# Construct the end-of-period marginal value function conditional on the next state.",
"if",
"self",
".",
"CubicBool",
":",
"EndOfPrdvPnvrsFunc_cond",
"=",
"CubicInterp",
"(",
"self",
".",
"aNrm_cond",
",",
"EndOfPrdvPnvrs_cond",
",",
"EndOfPrdvPnvrsP_cond",
",",
"lower_extrap",
"=",
"True",
")",
"else",
":",
"EndOfPrdvPnvrsFunc_cond",
"=",
"LinearInterp",
"(",
"self",
".",
"aNrm_cond",
",",
"EndOfPrdvPnvrs_cond",
",",
"lower_extrap",
"=",
"True",
")",
"EndofPrdvPfunc_cond",
"=",
"MargValueFunc",
"(",
"EndOfPrdvPnvrsFunc_cond",
",",
"self",
".",
"CRRA",
")",
"# \"recurve\" the interpolated marginal value function",
"return",
"EndofPrdvPfunc_cond"
] |
sets the underlying repo object | def _set_repo ( self , url ) : if url . startswith ( 'http' ) : try : self . repo = Proxy ( url ) except ProxyError , e : log . exception ( 'Error setting repo: %s' % url ) raise GritError ( e ) else : try : self . repo = Local ( url ) except NotGitRepository : raise GritError ( 'Invalid url: %s' % url ) except Exception , e : log . exception ( 'Error setting repo: %s' % url ) raise GritError ( e ) | 10,831 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/base.py#L73-L88 | [
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Creates a new Repo instance . | def new ( self , url , clone_from = None , bare = True ) : #note to self: look into using templates (--template) if clone_from : self . clone ( path = url , bare = bare ) else : if url . startswith ( 'http' ) : proxy = Proxy ( url ) proxy . new ( path = url , bare = bare ) else : local = Local . new ( path = url , bare = bare ) return Repo ( url ) | 10,832 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/base.py#L91-L117 | [
"def",
"bulk_stop",
"(",
"workers",
",",
"lbn",
",",
"profile",
"=",
"'default'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"workers",
",",
"six",
".",
"string_types",
")",
":",
"workers",
"=",
"workers",
".",
"split",
"(",
"','",
")",
"for",
"worker",
"in",
"workers",
":",
"try",
":",
"ret",
"[",
"worker",
"]",
"=",
"worker_stop",
"(",
"worker",
",",
"lbn",
",",
"profile",
")",
"except",
"Exception",
":",
"ret",
"[",
"worker",
"]",
"=",
"False",
"return",
"ret"
] |
Checks Emails in List Wether they are Correct or not | def CheckEmails ( self , checkTypo = False , fillWrong = True ) : self . wrong_emails = [ ] for email in self . emails : if self . CheckEmail ( email , checkTypo ) is False : self . wrong_emails . append ( email ) | 10,833 | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L31-L36 | [
"def",
"print_debug",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"WTF_CONFIG_READER",
".",
"get",
"(",
"\"debug\"",
",",
"False",
")",
"==",
"True",
":",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Checks a Single email if it is correct | def CheckEmail ( self , email , checkTypo = False ) : contents = email . split ( '@' ) if len ( contents ) == 2 : if contents [ 1 ] in self . valid : return True return False | 10,834 | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L38-L44 | [
"def",
"db_create",
"(",
"cls",
",",
"impl",
",",
"working_dir",
")",
":",
"global",
"VIRTUALCHAIN_DB_SCRIPT",
"log",
".",
"debug",
"(",
"\"Setup chain state in {}\"",
".",
"format",
"(",
"working_dir",
")",
")",
"path",
"=",
"config",
".",
"get_snapshots_filename",
"(",
"impl",
",",
"working_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"Exception",
"(",
"\"Database {} already exists\"",
")",
"lines",
"=",
"[",
"l",
"+",
"\";\"",
"for",
"l",
"in",
"VIRTUALCHAIN_DB_SCRIPT",
".",
"split",
"(",
"\";\"",
")",
"]",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"path",
",",
"isolation_level",
"=",
"None",
",",
"timeout",
"=",
"2",
"**",
"30",
")",
"for",
"line",
"in",
"lines",
":",
"con",
".",
"execute",
"(",
"line",
")",
"con",
".",
"row_factory",
"=",
"StateEngine",
".",
"db_row_factory",
"return",
"con"
] |
Corrects Emails in wrong_emails | def CorrectWrongEmails ( self , askInput = True ) : for email in self . wrong_emails : corrected_email = self . CorrectEmail ( email ) self . emails [ self . emails . index ( email ) ] = corrected_email self . wrong_emails = [ ] | 10,835 | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L46-L52 | [
"def",
"load_zae",
"(",
"file_obj",
",",
"resolver",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# a dict, {file name : file object}",
"archive",
"=",
"util",
".",
"decompress",
"(",
"file_obj",
",",
"file_type",
"=",
"'zip'",
")",
"# load the first file with a .dae extension",
"file_name",
"=",
"next",
"(",
"i",
"for",
"i",
"in",
"archive",
".",
"keys",
"(",
")",
"if",
"i",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.dae'",
")",
")",
"# a resolver so the loader can load textures / etc",
"resolver",
"=",
"visual",
".",
"resolvers",
".",
"ZipResolver",
"(",
"archive",
")",
"# run the regular collada loader",
"loaded",
"=",
"load_collada",
"(",
"archive",
"[",
"file_name",
"]",
",",
"resolver",
"=",
"resolver",
",",
"*",
"*",
"kwargs",
")",
"return",
"loaded"
] |
Returns a Corrected email USER INPUT REQUIRED | def CorrectEmail ( self , email ) : print ( "Wrong Email : " + email ) contents = email . split ( '@' ) if len ( contents ) == 2 : domain_data = contents [ 1 ] . split ( '.' ) for vemail in self . valid : alters = perms ( vemail . split ( '.' , 1 ) [ 0 ] ) if domain_data [ 0 ] in alters and qyn . query_yes_no ( "Did you mean : " + contents [ 0 ] + '@' + vemail ) is True : return contents [ 0 ] + '@' + vemail corrected = input ( 'Enter Corrected Email : ' ) while self . CheckEmail ( corrected ) is False : corrected = input ( 'PLEASE Enter "Corrected" Email : ' ) return corrected else : print ( 'Looks like you missed/overused `@`' ) if len ( contents ) == 1 : for vemail in self . valid : if email [ len ( email ) - len ( vemail ) : ] == vemail and qyn . query_yes_no ( "Did you mean : " + email [ : len ( email ) - len ( vemail ) ] + '@' + vemail ) is True : return email [ : len ( email ) - len ( vemail ) ] + '@' + vemail corrected = input ( 'Enter Corrected Email : ' ) while self . CheckEmail ( corrected ) is False : corrected = input ( 'PLEASE Enter "Corrected" Email : ' ) return corrected | 10,836 | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L54-L80 | [
"def",
"main_dump",
"(",
"paths",
",",
"directory",
",",
"dry_run",
")",
":",
"table_map",
"=",
"get_table_map",
"(",
"paths",
")",
"for",
"conn_name",
",",
"conn_info",
"in",
"table_map",
".",
"items",
"(",
")",
":",
"inter",
"=",
"conn_info",
"[",
"\"interface\"",
"]",
"conn",
"=",
"inter",
".",
"connection_config",
"table_names",
"=",
"conn_info",
"[",
"\"table_names\"",
"]",
"cmd",
"=",
"get_base_cmd",
"(",
"\"backup\"",
",",
"inter",
",",
"directory",
")",
"cmd",
".",
"extend",
"(",
"table_names",
")",
"if",
"dry_run",
":",
"echo",
".",
"out",
"(",
"\" \"",
".",
"join",
"(",
"cmd",
")",
")",
"else",
":",
"run_cmd",
"(",
"cmd",
")"
] |
Add an element to the parser . | def add_element ( self , element , override = False ) : if issubclass ( element , inline . InlineElement ) : dest = self . inline_elements elif issubclass ( element , block . BlockElement ) : dest = self . block_elements else : raise TypeError ( 'The element should be a subclass of either `BlockElement` or ' '`InlineElement`.' ) if not override : dest [ element . __name__ ] = element else : for cls in element . __bases__ : if cls in dest . values ( ) : dest [ cls . __name__ ] = element break else : dest [ element . __name__ ] = element | 10,837 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L37-L63 | [
"def",
"FindClonedClients",
"(",
"token",
"=",
"None",
")",
":",
"index",
"=",
"client_index",
".",
"CreateClientIndex",
"(",
"token",
"=",
"token",
")",
"clients",
"=",
"index",
".",
"LookupClients",
"(",
"[",
"\".\"",
"]",
")",
"hw_infos",
"=",
"_GetHWInfos",
"(",
"clients",
",",
"token",
"=",
"token",
")",
"# We get all clients that have reported more than one hardware serial",
"# number over time. This doesn't necessarily indicate a cloned client - the",
"# machine might just have new hardware. We need to search for clients that",
"# alternate between different IDs.",
"clients_with_multiple_serials",
"=",
"[",
"client_id",
"for",
"client_id",
",",
"serials",
"in",
"iteritems",
"(",
"hw_infos",
")",
"if",
"len",
"(",
"serials",
")",
">",
"1",
"]",
"client_list",
"=",
"aff4",
".",
"FACTORY",
".",
"MultiOpen",
"(",
"clients_with_multiple_serials",
",",
"age",
"=",
"aff4",
".",
"ALL_TIMES",
",",
"token",
"=",
"token",
")",
"cloned_clients",
"=",
"[",
"]",
"for",
"c",
"in",
"client_list",
":",
"hwis",
"=",
"c",
".",
"GetValuesForAttribute",
"(",
"c",
".",
"Schema",
".",
"HARDWARE_INFO",
")",
"# Here we search for the earliest and latest time each ID was reported.",
"max_index",
"=",
"{",
"}",
"min_index",
"=",
"{",
"}",
"ids",
"=",
"set",
"(",
")",
"for",
"i",
",",
"hwi",
"in",
"enumerate",
"(",
"hwis",
")",
":",
"s",
"=",
"hwi",
".",
"serial_number",
"max_index",
"[",
"s",
"]",
"=",
"i",
"if",
"s",
"not",
"in",
"min_index",
":",
"min_index",
"[",
"s",
"]",
"=",
"i",
"ids",
".",
"add",
"(",
"s",
")",
"# Construct ranges [first occurrence, last occurrence] for every ID. If",
"# a client just changed from one ID to the other, those ranges of IDs should",
"# be disjunct. If they overlap at some point, it indicates that two IDs were",
"# reported in the same time frame.",
"ranges",
"=",
"[",
"]",
"for",
"hwid",
"in",
"ids",
":",
"ranges",
".",
"append",
"(",
"(",
"min_index",
"[",
"hwid",
"]",
",",
"max_index",
"[",
"hwid",
"]",
")",
")",
"# Sort ranges by first occurrence time.",
"ranges",
".",
"sort",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"ranges",
")",
"-",
"1",
")",
":",
"if",
"ranges",
"[",
"i",
"]",
"[",
"1",
"]",
">",
"ranges",
"[",
"i",
"+",
"1",
"]",
"[",
"0",
"]",
":",
"cloned_clients",
".",
"append",
"(",
"c",
")",
"msg",
"=",
"\"Found client with multiple, overlapping serial numbers: %s\"",
"logging",
".",
"info",
"(",
"msg",
",",
"c",
".",
"urn",
")",
"for",
"hwi",
"in",
"c",
".",
"GetValuesForAttribute",
"(",
"c",
".",
"Schema",
".",
"HARDWARE_INFO",
")",
":",
"logging",
".",
"info",
"(",
"\"%s %s\"",
",",
"hwi",
".",
"age",
",",
"hwi",
".",
"serial_number",
")",
"break",
"return",
"cloned_clients"
] |
Do the actual parsing and returns an AST or parsed element . | def parse ( self , source_or_text ) : if isinstance ( source_or_text , string_types ) : block . parser = self inline . parser = self return self . block_elements [ 'Document' ] ( source_or_text ) element_list = self . _build_block_element_list ( ) ast = [ ] while not source_or_text . exhausted : for ele_type in element_list : if ele_type . match ( source_or_text ) : result = ele_type . parse ( source_or_text ) if not hasattr ( result , 'priority' ) : result = ele_type ( result ) ast . append ( result ) break else : # Quit the current parsing and go back to the last level. break return ast | 10,838 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L65-L90 | [
"def",
"ensure_compatible_admin",
"(",
"view",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_roles",
"=",
"request",
".",
"user",
".",
"user_data",
".",
"get",
"(",
"'roles'",
",",
"[",
"]",
")",
"if",
"len",
"(",
"user_roles",
")",
"!=",
"1",
":",
"context",
"=",
"{",
"'message'",
":",
"'I need to be able to manage user accounts. '",
"'My username is %s'",
"%",
"request",
".",
"user",
".",
"username",
"}",
"return",
"render",
"(",
"request",
",",
"'mtp_common/user_admin/incompatible-admin.html'",
",",
"context",
"=",
"context",
")",
"return",
"view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Parses text into inline elements . RawText is not considered in parsing but created as a wrapper of holes that don t match any other elements . | def parse_inline ( self , text ) : element_list = self . _build_inline_element_list ( ) return inline_parser . parse ( text , element_list , fallback = self . inline_elements [ 'RawText' ] ) | 10,839 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L92-L103 | [
"def",
"decrease_frequency",
"(",
"self",
",",
"frequency",
"=",
"None",
")",
":",
"if",
"frequency",
"is",
"None",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"decreaseFrequency\"",
",",
"\"()V\"",
")",
"else",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"decreaseFrequency\"",
",",
"\"(I)V\"",
",",
"frequency",
")"
] |
Return a list of block elements ordered from highest priority to lowest . | def _build_block_element_list ( self ) : return sorted ( [ e for e in self . block_elements . values ( ) if not e . virtual ] , key = lambda e : e . priority , reverse = True ) | 10,840 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L105-L112 | [
"def",
"_get_management_client",
"(",
"self",
",",
"client_class",
")",
":",
"try",
":",
"client",
"=",
"get_client_from_auth_file",
"(",
"client_class",
",",
"auth_path",
"=",
"self",
".",
"service_account_file",
")",
"except",
"ValueError",
"as",
"error",
":",
"raise",
"AzureCloudException",
"(",
"'Service account file format is invalid: {0}.'",
".",
"format",
"(",
"error",
")",
")",
"except",
"KeyError",
"as",
"error",
":",
"raise",
"AzureCloudException",
"(",
"'Service account file missing key: {0}.'",
".",
"format",
"(",
"error",
")",
")",
"except",
"Exception",
"as",
"error",
":",
"raise",
"AzureCloudException",
"(",
"'Unable to create resource management client: '",
"'{0}.'",
".",
"format",
"(",
"error",
")",
")",
"return",
"client"
] |
Assembles basic WSGI - compatible application providing functionality of git - http - backend . | def make_app ( * args , * * kw ) : default_options = [ [ 'content_path' , '.' ] , [ 'uri_marker' , '' ] ] args = list ( args ) options = dict ( default_options ) options . update ( kw ) while default_options and args : _d = default_options . pop ( 0 ) _a = args . pop ( 0 ) options [ _d [ 0 ] ] = _a options [ 'content_path' ] = os . path . abspath ( options [ 'content_path' ] . decode ( 'utf8' ) ) options [ 'uri_marker' ] = options [ 'uri_marker' ] . decode ( 'utf8' ) selector = WSGIHandlerSelector ( ) git_inforefs_handler = GitHTTPBackendInfoRefs ( * * options ) git_rpc_handler = GitHTTPBackendSmartHTTP ( * * options ) static_handler = StaticServer ( * * options ) file_handler = FileServer ( * * options ) json_handler = JSONServer ( * * options ) ui_handler = UIServer ( * * options ) if options [ 'uri_marker' ] : marker_regex = r'(?P<decorative_path>.*?)(?:/' + options [ 'uri_marker' ] + ')' else : marker_regex = '' selector . add ( marker_regex + r'(?P<working_path>.*?)/info/refs\?.*?service=(?P<git_command>git-[^&]+).*$' , GET = git_inforefs_handler , HEAD = git_inforefs_handler ) selector . add ( marker_regex + r'(?P<working_path>.*)/(?P<git_command>git-[^/]+)$' , POST = git_rpc_handler ) selector . add ( marker_regex + r'/static/(?P<working_path>.*)$' , GET = static_handler , HEAD = static_handler ) selector . add ( marker_regex + r'(?P<working_path>.*)/file$' , GET = file_handler , HEAD = file_handler ) selector . add ( marker_regex + r'(?P<working_path>.*)$' , GET = ui_handler , POST = json_handler , HEAD = ui_handler ) return selector | 10,841 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/server.py#L41-L116 | [
"def",
"block",
"(",
"seed",
")",
":",
"num",
"=",
"SAMPLE_RATE",
"*",
"BLOCK_SIZE",
"rng",
"=",
"RandomState",
"(",
"seed",
"%",
"2",
"**",
"32",
")",
"variance",
"=",
"SAMPLE_RATE",
"/",
"2",
"return",
"rng",
".",
"normal",
"(",
"size",
"=",
"num",
",",
"scale",
"=",
"variance",
"**",
"0.5",
")"
] |
Return an aware or naive datetime . datetime depending on settings . USE_TZ . | def now ( tzinfo = True ) : if dj_now : return dj_now ( ) if tzinfo : # timeit shows that datetime.now(tz=utc) is 24% slower return datetime . utcnow ( ) . replace ( tzinfo = utc ) return datetime . now ( ) | 10,842 | https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/tz_utils.py#L21-L31 | [
"def",
"_unbind_topics",
"(",
"self",
",",
"topics",
")",
":",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"status",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"tracing",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"streaming",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"response",
")"
] |
Match data to basic match unit . | def match_unit ( data , p , m = 'a' ) : if data is None : return p is None # compile search value only once for non exact search if m != 'e' and isinstance ( p , six . string_types ) : p = re . compile ( p ) if isinstance ( data , Sequence ) and not isinstance ( data , six . string_types ) : return any ( [ match_unit ( field , p , m = m ) for field in data ] ) elif isinstance ( data , MutableMapping ) : return any ( [ match_unit ( field , p , m = m ) for field in data . values ( ) ] ) # Inclusive range query if isinstance ( p , tuple ) : left , right = p return ( left <= data ) and ( data <= right ) if m == 'e' : return six . text_type ( data ) == p return p . search ( six . text_type ( data ) ) is not None | 10,843 | https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/walkers/match_unit.py#L57-L80 | [
"def",
"remove_armor",
"(",
"armored_data",
")",
":",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
"armored_data",
")",
"lines",
"=",
"stream",
".",
"readlines",
"(",
")",
"[",
"3",
":",
"-",
"1",
"]",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"b''",
".",
"join",
"(",
"lines",
")",
")",
"payload",
",",
"checksum",
"=",
"data",
"[",
":",
"-",
"3",
"]",
",",
"data",
"[",
"-",
"3",
":",
"]",
"assert",
"util",
".",
"crc24",
"(",
"payload",
")",
"==",
"checksum",
"return",
"payload"
] |
Generate the protein - protein interaction network . | def generate_ppi_network ( ppi_graph_path : str , dge_list : List [ Gene ] , max_adj_p : float , max_log2_fold_change : float , min_log2_fold_change : float , ppi_edge_min_confidence : Optional [ float ] = None , current_disease_ids_path : Optional [ str ] = None , disease_associations_path : Optional [ str ] = None , ) -> Network : # Compilation of a protein-protein interaction (PPI) graph (HIPPIE) protein_interactions = parsers . parse_ppi_graph ( ppi_graph_path , ppi_edge_min_confidence ) protein_interactions = protein_interactions . simplify ( ) if disease_associations_path is not None and current_disease_ids_path is not None : current_disease_ids = parsers . parse_disease_ids ( current_disease_ids_path ) disease_associations = parsers . parse_disease_associations ( disease_associations_path , current_disease_ids ) else : disease_associations = None # Build an undirected weighted graph with the remaining interactions based on Entrez gene IDs network = Network ( protein_interactions , max_adj_p = max_adj_p , max_l2fc = max_log2_fold_change , min_l2fc = min_log2_fold_change , ) network . set_up_network ( dge_list , disease_associations = disease_associations ) return network | 10,844 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/pipeline.py#L20-L54 | [
"def",
"codemirror_field_js_bundle",
"(",
"field",
")",
":",
"manifesto",
"=",
"CodemirrorAssetTagRender",
"(",
")",
"manifesto",
".",
"register_from_fields",
"(",
"field",
")",
"try",
":",
"bundle_name",
"=",
"manifesto",
".",
"js_bundle_names",
"(",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"msg",
"=",
"(",
"\"Given field with configuration name '{}' does not have a \"",
"\"Javascript bundle name\"",
")",
"raise",
"CodeMirrorFieldBundleError",
"(",
"msg",
".",
"format",
"(",
"field",
".",
"config_name",
")",
")",
"return",
"bundle_name"
] |
Parse a differential expression file . | def parse_dge ( dge_path : str , entrez_id_header : str , log2_fold_change_header : str , adj_p_header : str , entrez_delimiter : str , base_mean_header : Optional [ str ] = None ) -> List [ Gene ] : if dge_path . endswith ( '.xlsx' ) : return parsers . parse_excel ( dge_path , entrez_id_header = entrez_id_header , log_fold_change_header = log2_fold_change_header , adjusted_p_value_header = adj_p_header , entrez_delimiter = entrez_delimiter , base_mean_header = base_mean_header , ) if dge_path . endswith ( '.csv' ) : return parsers . parse_csv ( dge_path , entrez_id_header = entrez_id_header , log_fold_change_header = log2_fold_change_header , adjusted_p_value_header = adj_p_header , entrez_delimiter = entrez_delimiter , base_mean_header = base_mean_header , ) if dge_path . endswith ( '.tsv' ) : return parsers . parse_csv ( dge_path , entrez_id_header = entrez_id_header , log_fold_change_header = log2_fold_change_header , adjusted_p_value_header = adj_p_header , entrez_delimiter = entrez_delimiter , base_mean_header = base_mean_header , sep = "\t" ) raise ValueError ( f'Unsupported extension: {dge_path}' ) | 10,845 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/pipeline.py#L57-L106 | [
"def",
"get_sns_topic_arn",
"(",
"topic_name",
",",
"account",
",",
"region",
")",
":",
"if",
"topic_name",
".",
"count",
"(",
"':'",
")",
"==",
"5",
"and",
"topic_name",
".",
"startswith",
"(",
"'arn:aws:sns:'",
")",
":",
"return",
"topic_name",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"account",
",",
"region_name",
"=",
"region",
")",
"sns_client",
"=",
"session",
".",
"client",
"(",
"'sns'",
")",
"topics",
"=",
"sns_client",
".",
"list_topics",
"(",
")",
"[",
"'Topics'",
"]",
"matched_topic",
"=",
"None",
"for",
"topic",
"in",
"topics",
":",
"topic_arn",
"=",
"topic",
"[",
"'TopicArn'",
"]",
"if",
"topic_name",
"==",
"topic_arn",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
":",
"matched_topic",
"=",
"topic_arn",
"break",
"else",
":",
"LOG",
".",
"critical",
"(",
"\"No topic with name %s found.\"",
",",
"topic_name",
")",
"raise",
"SNSTopicNotFound",
"(",
"'No topic with name {0} found'",
".",
"format",
"(",
"topic_name",
")",
")",
"return",
"matched_topic"
] |
Load the configuration from a plain Python file . This file is executed on its own . | def _load ( self , file_path : Text ) -> None : # noinspection PyUnresolvedReferences module_ = types . ModuleType ( 'settings' ) module_ . __file__ = file_path try : with open ( file_path , encoding = 'utf-8' ) as f : exec ( compile ( f . read ( ) , file_path , 'exec' ) , module_ . __dict__ ) except IOError as e : e . strerror = 'Unable to load configuration file ({})' . format ( e . strerror ) raise for key in dir ( module_ ) : if CONFIG_ATTR . match ( key ) : self [ key ] = getattr ( module_ , key ) | 10,846 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/conf/loader.py#L38-L63 | [
"def",
"_set_idx_to_vec_by_embeddings",
"(",
"self",
",",
"token_embeddings",
",",
"vocab_len",
",",
"vocab_idx_to_token",
")",
":",
"new_vec_len",
"=",
"sum",
"(",
"embed",
".",
"vec_len",
"for",
"embed",
"in",
"token_embeddings",
")",
"new_idx_to_vec",
"=",
"nd",
".",
"zeros",
"(",
"shape",
"=",
"(",
"vocab_len",
",",
"new_vec_len",
")",
")",
"col_start",
"=",
"0",
"# Concatenate all the embedding vectors in token_embeddings.",
"for",
"embed",
"in",
"token_embeddings",
":",
"col_end",
"=",
"col_start",
"+",
"embed",
".",
"vec_len",
"# Cancatenate vectors of the unknown token.",
"new_idx_to_vec",
"[",
"0",
",",
"col_start",
":",
"col_end",
"]",
"=",
"embed",
".",
"idx_to_vec",
"[",
"0",
"]",
"new_idx_to_vec",
"[",
"1",
":",
",",
"col_start",
":",
"col_end",
"]",
"=",
"embed",
".",
"get_vecs_by_tokens",
"(",
"vocab_idx_to_token",
"[",
"1",
":",
"]",
")",
"col_start",
"=",
"col_end",
"self",
".",
"_vec_len",
"=",
"new_vec_len",
"self",
".",
"_idx_to_vec",
"=",
"new_idx_to_vec"
] |
Return the actual settings object or create it if missing . | def _settings ( self ) -> Settings : if self . __dict__ [ '__settings' ] is None : self . __dict__ [ '__settings' ] = Settings ( ) for file_path in self . _get_files ( ) : if file_path : # noinspection PyProtectedMember self . __dict__ [ '__settings' ] . _load ( file_path ) return self . __dict__ [ '__settings' ] | 10,847 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/conf/loader.py#L84-L94 | [
"def",
"remove_async_sns_topic",
"(",
"self",
",",
"lambda_name",
")",
":",
"topic_name",
"=",
"get_topic_name",
"(",
"lambda_name",
")",
"removed_arns",
"=",
"[",
"]",
"for",
"sub",
"in",
"self",
".",
"sns_client",
".",
"list_subscriptions",
"(",
")",
"[",
"'Subscriptions'",
"]",
":",
"if",
"topic_name",
"in",
"sub",
"[",
"'TopicArn'",
"]",
":",
"self",
".",
"sns_client",
".",
"delete_topic",
"(",
"TopicArn",
"=",
"sub",
"[",
"'TopicArn'",
"]",
")",
"removed_arns",
".",
"append",
"(",
"sub",
"[",
"'TopicArn'",
"]",
")",
"return",
"removed_arns"
] |
Start the lock . | async def _start ( self , key : Text ) -> None : for _ in range ( 0 , 1000 ) : with await self . pool as r : just_set = await r . set ( self . lock_key ( key ) , '' , expire = settings . REGISTER_LOCK_TIME , exist = r . SET_IF_NOT_EXIST , ) if just_set : break await asyncio . sleep ( settings . REDIS_POLL_INTERVAL ) | 10,848 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L42-L60 | [
"def",
"__GetTypeInfo",
"(",
"self",
",",
"attrs",
",",
"name_hint",
")",
":",
"type_ref",
"=",
"self",
".",
"__names",
".",
"ClassName",
"(",
"attrs",
".",
"get",
"(",
"'$ref'",
")",
")",
"type_name",
"=",
"attrs",
".",
"get",
"(",
"'type'",
")",
"if",
"not",
"(",
"type_ref",
"or",
"type_name",
")",
":",
"raise",
"ValueError",
"(",
"'No type found for %s'",
"%",
"attrs",
")",
"if",
"type_ref",
":",
"self",
".",
"__AddIfUnknown",
"(",
"type_ref",
")",
"# We don't actually know this is a message -- it might be an",
"# enum. However, we can't check that until we've created all the",
"# types, so we come back and fix this up later.",
"return",
"TypeInfo",
"(",
"type_name",
"=",
"type_ref",
",",
"variant",
"=",
"messages",
".",
"Variant",
".",
"MESSAGE",
")",
"if",
"'enum'",
"in",
"attrs",
":",
"enum_name",
"=",
"'%sValuesEnum'",
"%",
"name_hint",
"return",
"self",
".",
"__DeclareEnum",
"(",
"enum_name",
",",
"attrs",
")",
"if",
"'format'",
"in",
"attrs",
":",
"type_info",
"=",
"self",
".",
"PRIMITIVE_FORMAT_MAP",
".",
"get",
"(",
"attrs",
"[",
"'format'",
"]",
")",
"if",
"type_info",
"is",
"None",
":",
"# If we don't recognize the format, the spec says we fall back",
"# to just using the type name.",
"if",
"type_name",
"in",
"self",
".",
"PRIMITIVE_TYPE_INFO_MAP",
":",
"return",
"self",
".",
"PRIMITIVE_TYPE_INFO_MAP",
"[",
"type_name",
"]",
"raise",
"ValueError",
"(",
"'Unknown type/format \"%s\"/\"%s\"'",
"%",
"(",
"attrs",
"[",
"'format'",
"]",
",",
"type_name",
")",
")",
"if",
"type_info",
".",
"type_name",
".",
"startswith",
"(",
"(",
"'apitools.base.protorpclite.message_types.'",
",",
"'message_types.'",
")",
")",
":",
"self",
".",
"__AddImport",
"(",
"'from %s import message_types as _message_types'",
"%",
"self",
".",
"__protorpc_package",
")",
"if",
"type_info",
".",
"type_name",
".",
"startswith",
"(",
"'extra_types.'",
")",
":",
"self",
".",
"__AddImport",
"(",
"'from %s import extra_types'",
"%",
"self",
".",
"__base_files_package",
")",
"return",
"type_info",
"if",
"type_name",
"in",
"self",
".",
"PRIMITIVE_TYPE_INFO_MAP",
":",
"type_info",
"=",
"self",
".",
"PRIMITIVE_TYPE_INFO_MAP",
"[",
"type_name",
"]",
"if",
"type_info",
".",
"type_name",
".",
"startswith",
"(",
"'extra_types.'",
")",
":",
"self",
".",
"__AddImport",
"(",
"'from %s import extra_types'",
"%",
"self",
".",
"__base_files_package",
")",
"return",
"type_info",
"if",
"type_name",
"==",
"'array'",
":",
"items",
"=",
"attrs",
".",
"get",
"(",
"'items'",
")",
"if",
"not",
"items",
":",
"raise",
"ValueError",
"(",
"'Array type with no item type: %s'",
"%",
"attrs",
")",
"entry_name_hint",
"=",
"self",
".",
"__names",
".",
"ClassName",
"(",
"items",
".",
"get",
"(",
"'title'",
")",
"or",
"'%sListEntry'",
"%",
"name_hint",
")",
"entry_label",
"=",
"self",
".",
"__ComputeLabel",
"(",
"items",
")",
"if",
"entry_label",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"Label",
".",
"REPEATED",
":",
"parent_name",
"=",
"self",
".",
"__names",
".",
"ClassName",
"(",
"items",
".",
"get",
"(",
"'title'",
")",
"or",
"name_hint",
")",
"entry_type_name",
"=",
"self",
".",
"__AddEntryType",
"(",
"entry_name_hint",
",",
"items",
".",
"get",
"(",
"'items'",
")",
",",
"parent_name",
")",
"return",
"TypeInfo",
"(",
"type_name",
"=",
"entry_type_name",
",",
"variant",
"=",
"messages",
".",
"Variant",
".",
"MESSAGE",
")",
"return",
"self",
".",
"__GetTypeInfo",
"(",
"items",
",",
"entry_name_hint",
")",
"elif",
"type_name",
"==",
"'any'",
":",
"self",
".",
"__AddImport",
"(",
"'from %s import extra_types'",
"%",
"self",
".",
"__base_files_package",
")",
"return",
"self",
".",
"PRIMITIVE_TYPE_INFO_MAP",
"[",
"'any'",
"]",
"elif",
"type_name",
"==",
"'object'",
":",
"# TODO(craigcitro): Think of a better way to come up with names.",
"if",
"not",
"name_hint",
":",
"raise",
"ValueError",
"(",
"'Cannot create subtype without some name hint'",
")",
"schema",
"=",
"dict",
"(",
"attrs",
")",
"schema",
"[",
"'id'",
"]",
"=",
"name_hint",
"self",
".",
"AddDescriptorFromSchema",
"(",
"name_hint",
",",
"schema",
")",
"self",
".",
"__AddIfUnknown",
"(",
"name_hint",
")",
"return",
"TypeInfo",
"(",
"type_name",
"=",
"name_hint",
",",
"variant",
"=",
"messages",
".",
"Variant",
".",
"MESSAGE",
")",
"raise",
"ValueError",
"(",
"'Unknown type: %s'",
"%",
"type_name",
")"
] |
Get the value for the key . It is automatically deserialized from JSON and returns an empty dictionary by default . | async def _get ( self , key : Text ) -> Dict [ Text , Any ] : try : with await self . pool as r : return ujson . loads ( await r . get ( self . register_key ( key ) ) ) except ( ValueError , TypeError ) : return { } | 10,849 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L70-L80 | [
"def",
"blit",
"(",
"self",
",",
"src_rect",
",",
"dst_surf",
",",
"dst_rect",
")",
":",
"check_int_err",
"(",
"lib",
".",
"SDL_UpperBlit",
"(",
"self",
".",
"_ptr",
",",
"src_rect",
".",
"_ptr",
",",
"dst_surf",
".",
"_ptr",
",",
"dst_rect",
".",
"_ptr",
")",
")"
] |
Replace the register with a new value . | async def _replace ( self , key : Text , data : Dict [ Text , Any ] ) -> None : with await self . pool as r : await r . set ( self . register_key ( key ) , ujson . dumps ( data ) ) | 10,850 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L82-L88 | [
"def",
"_lsm_load_pages",
"(",
"self",
")",
":",
"# cache all pages to preserve corrected values",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"cache",
"=",
"True",
"pages",
".",
"useframes",
"=",
"True",
"# use first and second page as keyframes",
"pages",
".",
"keyframe",
"=",
"1",
"pages",
".",
"keyframe",
"=",
"0",
"# load remaining pages as frames",
"pages",
".",
"_load",
"(",
"keyframe",
"=",
"None",
")",
"# fix offsets and bytecounts first",
"self",
".",
"_lsm_fix_strip_offsets",
"(",
")",
"self",
".",
"_lsm_fix_strip_bytecounts",
"(",
")",
"# assign keyframes for data and thumbnail series",
"keyframe",
"=",
"pages",
"[",
"0",
"]",
"for",
"page",
"in",
"pages",
"[",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe",
"keyframe",
"=",
"pages",
"[",
"1",
"]",
"for",
"page",
"in",
"pages",
"[",
"1",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe"
] |
Returns the basename of the artifact s file using Maven s conventions . | def getFileName ( self , suffix = None , extension = "jar" ) : assert ( self . _artifactId is not None ) assert ( self . _version is not None ) return "{0}-{1}{2}{3}" . format ( self . _artifactId , self . _version . getRawString ( ) , "-" + suffix . lstrip ( "-" ) if suffix is not None else "" , "." + extension . lstrip ( "." ) if extension is not None else "" ) | 10,851 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/maven.py#L50-L67 | [
"def",
"poisson_noise",
"(",
"intensity",
",",
"seed",
"=",
"None",
")",
":",
"from",
"odl",
".",
"space",
"import",
"ProductSpace",
"with",
"NumpyRandomSeed",
"(",
"seed",
")",
":",
"if",
"isinstance",
"(",
"intensity",
".",
"space",
",",
"ProductSpace",
")",
":",
"values",
"=",
"[",
"poisson_noise",
"(",
"subintensity",
")",
"for",
"subintensity",
"in",
"intensity",
"]",
"else",
":",
"values",
"=",
"np",
".",
"random",
".",
"poisson",
"(",
"intensity",
".",
"asarray",
"(",
")",
")",
"return",
"intensity",
".",
"space",
".",
"element",
"(",
"values",
")"
] |
Returns the full path relative to the root of a Maven repository of the current artifact using Maven s conventions . | def getPath ( self , suffix = None , extension = "jar" , separator = os . sep ) : assert ( self . _groupId is not None ) resultComponents = [ self . _groupId . replace ( "." , separator ) ] if self . _artifactId is not None : resultComponents . append ( self . _artifactId ) version = self . _version if version is not None : resultComponents . append ( version . getRawString ( ) ) resultComponents . append ( self . getFileName ( suffix , extension ) ) return separator . join ( resultComponents ) | 10,852 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/maven.py#L70-L96 | [
"def",
"random_public_ip",
"(",
"self",
")",
":",
"randomip",
"=",
"random_ip",
"(",
")",
"while",
"self",
".",
"is_reserved_ip",
"(",
"randomip",
")",
":",
"randomip",
"=",
"random_ip",
"(",
")",
"return",
"randomip"
] |
Returns a DataFrame of allele counts for all given loci in the read sources | def allele_support_df ( loci , sources ) : return pandas . DataFrame ( allele_support_rows ( loci , sources ) , columns = EXPECTED_COLUMNS ) | 10,853 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/support.py#L29-L35 | [
"async",
"def",
"list_keys",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"keys_dir",
"=",
"CONFIG",
"[",
"'wifi_keys_dir'",
"]",
"keys",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"[",
"]",
"# TODO(mc, 2018-10-24): add last modified info to keys for sort purposes",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"keys_dir",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"keys_dir",
",",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"full_path",
")",
":",
"in_path",
"=",
"os",
".",
"listdir",
"(",
"full_path",
")",
"if",
"len",
"(",
"in_path",
")",
">",
"1",
":",
"log",
".",
"warning",
"(",
"\"Garbage in key dir for key {}\"",
".",
"format",
"(",
"path",
")",
")",
"keys",
".",
"append",
"(",
"{",
"'uri'",
":",
"'/wifi/keys/{}'",
".",
"format",
"(",
"path",
")",
",",
"'id'",
":",
"path",
",",
"'name'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"in_path",
"[",
"0",
"]",
")",
"}",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"Garbage in wifi keys dir: {}\"",
".",
"format",
"(",
"full_path",
")",
")",
"return",
"web",
".",
"json_response",
"(",
"{",
"'keys'",
":",
"keys",
"}",
",",
"status",
"=",
"200",
")"
] |
Collect the read evidence support for the given variants . | def variant_support ( variants , allele_support_df , ignore_missing = False ) : missing = [ c for c in EXPECTED_COLUMNS if c not in allele_support_df . columns ] if missing : raise ValueError ( "Missing columns: %s" % " " . join ( missing ) ) # Ensure our start and end fields are ints. allele_support_df [ [ "interbase_start" , "interbase_end" ] ] = ( allele_support_df [ [ "interbase_start" , "interbase_end" ] ] . astype ( int ) ) sources = sorted ( allele_support_df [ "source" ] . unique ( ) ) allele_support_dict = collections . defaultdict ( dict ) for ( i , row ) in allele_support_df . iterrows ( ) : key = ( row [ 'source' ] , row . contig , row . interbase_start , row . interbase_end ) allele_support_dict [ key ] [ row . allele ] = row [ "count" ] # We want an exception on bad lookups, so convert to a regular dict. allele_support_dict = dict ( allele_support_dict ) dataframe_dicts = collections . defaultdict ( lambda : collections . defaultdict ( list ) ) for variant in variants : for source in sources : key = ( source , variant . contig , variant . start - 1 , variant . end ) try : alleles = allele_support_dict [ key ] except KeyError : message = ( "No allele counts in source %s for variant %s" % ( source , str ( variant ) ) ) if ignore_missing : logging . warning ( message ) alleles = { } else : raise ValueError ( message ) alt = alleles . get ( variant . alt , 0 ) ref = alleles . get ( variant . ref , 0 ) total = sum ( alleles . values ( ) ) other = total - alt - ref dataframe_dicts [ "num_alt" ] [ source ] . append ( alt ) dataframe_dicts [ "num_ref" ] [ source ] . append ( ref ) dataframe_dicts [ "num_other" ] [ source ] . append ( other ) dataframe_dicts [ "total_depth" ] [ source ] . append ( total ) dataframe_dicts [ "alt_fraction" ] [ source ] . append ( float ( alt ) / max ( 1 , total ) ) dataframe_dicts [ "any_alt_fraction" ] [ source ] . append ( float ( alt + other ) / max ( 1 , total ) ) dataframes = dict ( ( label , pandas . DataFrame ( value , index = variants ) ) for ( label , value ) in dataframe_dicts . items ( ) ) return pandas . Panel ( dataframes ) | 10,854 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/support.py#L57-L153 | [
"async",
"def",
"renew",
"(",
"self",
",",
"session",
",",
"*",
",",
"dc",
"=",
"None",
")",
":",
"session_id",
"=",
"extract_attr",
"(",
"session",
",",
"keys",
"=",
"[",
"\"ID\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"put",
"(",
"\"/v1/session/renew\"",
",",
"session_id",
",",
"params",
"=",
"{",
"\"dc\"",
":",
"dc",
"}",
")",
"try",
":",
"result",
"=",
"response",
".",
"body",
"[",
"0",
"]",
"except",
"IndexError",
":",
"meta",
"=",
"extract_meta",
"(",
"response",
".",
"headers",
")",
"raise",
"NotFound",
"(",
"\"No session for %r\"",
"%",
"session_id",
",",
"meta",
"=",
"meta",
")",
"return",
"consul",
"(",
"result",
",",
"meta",
"=",
"extract_meta",
"(",
"response",
".",
"headers",
")",
")"
] |
Get info about a soundfile | def sndinfo ( path : str ) -> SndInfo : backend = _getBackend ( path ) logger . debug ( f"sndinfo: using backend {backend.name}" ) return backend . getinfo ( path ) | 10,855 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L215-L225 | [
"def",
"tournament_selection",
"(",
"population",
",",
"fitnesses",
",",
"num_competitors",
"=",
"2",
",",
"diversity_weight",
"=",
"0.0",
")",
":",
"# Optimization if diversity factor is disabled",
"if",
"diversity_weight",
"<=",
"0.0",
":",
"fitness_pop",
"=",
"zip",
"(",
"fitnesses",
",",
"population",
")",
"# Zip for easy fitness comparison",
"# Get num_competitors random chromosomes, then add best to result,",
"# by taking max fitness and getting chromosome from tuple.",
"# Repeat until full.",
"return",
"[",
"max",
"(",
"random",
".",
"sample",
"(",
"fitness_pop",
",",
"num_competitors",
")",
")",
"[",
"1",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"population",
")",
")",
"]",
"else",
":",
"indices",
"=",
"range",
"(",
"len",
"(",
"population",
")",
")",
"# Select tournament winners by either max fitness or diversity.",
"# The metric to check is randomly selected, weighted by diversity_weight.",
"# diversity_metric is calculated between the given solution,",
"# and the list of all currently selected solutions.",
"selected_solutions",
"=",
"[",
"]",
"# Select as many solutions are there are in population",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"population",
")",
")",
":",
"competitor_indices",
"=",
"random",
".",
"sample",
"(",
"indices",
",",
"num_competitors",
")",
"# Select by either fitness or diversity,",
"# Selected by weighted random selection",
"# NOTE: We assume fitness has a weight of 1.0",
"if",
"random",
".",
"uniform",
"(",
"0.0",
",",
"1.0",
")",
"<",
"(",
"1.0",
"/",
"(",
"1.0",
"+",
"diversity_weight",
")",
")",
":",
"# Fitness",
"selected_solutions",
".",
"append",
"(",
"max",
"(",
"zip",
"(",
"[",
"fitnesses",
"[",
"i",
"]",
"for",
"i",
"in",
"competitor_indices",
"]",
",",
"[",
"population",
"[",
"i",
"]",
"for",
"i",
"in",
"competitor_indices",
"]",
")",
")",
"[",
"-",
"1",
"]",
")",
"else",
":",
"# Diversity",
"# Break ties by fitness",
"selected_solutions",
".",
"append",
"(",
"max",
"(",
"zip",
"(",
"[",
"_diversity_metric",
"(",
"population",
"[",
"i",
"]",
",",
"selected_solutions",
")",
"for",
"i",
"in",
"competitor_indices",
"]",
",",
"[",
"fitnesses",
"[",
"i",
"]",
"for",
"i",
"in",
"competitor_indices",
"]",
",",
"[",
"population",
"[",
"i",
"]",
"for",
"i",
"in",
"competitor_indices",
"]",
")",
")",
"[",
"-",
"1",
"]",
")",
"return",
"selected_solutions"
] |
convert samples to mono if they are not mono already . | def asmono ( samples : np . ndarray , channel : Union [ int , str ] = 0 ) -> np . ndarray : if numchannels ( samples ) == 1 : # it could be [1,2,3,4,...], or [[1], [2], [3], [4], ...] if isinstance ( samples [ 0 ] , float ) : return samples elif isinstance ( samples [ 0 ] , np . dnarray ) : return np . reshape ( samples , ( len ( samples ) , ) ) else : raise TypeError ( "Samples should be numeric, found: %s" % str ( type ( samples [ 0 ] ) ) ) if isinstance ( channel , int ) : return samples [ : , channel ] elif channel == 'mix' : return _mix ( samples , scale_by_numchannels = True ) else : raise ValueError ( "channel has to be an integer indicating a channel," " or 'mix' to mix down all channels" ) | 10,856 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L298-L322 | [
"def",
"get_license_assignment_manager",
"(",
"service_instance",
")",
":",
"log",
".",
"debug",
"(",
"'Retrieving license assignment manager'",
")",
"try",
":",
"lic_assignment_manager",
"=",
"service_instance",
".",
"content",
".",
"licenseManager",
".",
"licenseAssignmentManager",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"if",
"not",
"lic_assignment_manager",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareObjectRetrievalError",
"(",
"'License assignment manager was not retrieved'",
")",
"return",
"lic_assignment_manager"
] |
Returns a view into a channel of samples . | def getchannel ( samples : np . ndarray , ch : int ) -> np . ndarray : N = numchannels ( samples ) if ch > ( N - 1 ) : raise ValueError ( "channel %d out of range" % ch ) if N == 1 : return samples return samples [ : , ch ] | 10,857 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L325-L337 | [
"def",
"authors_titles_validator",
"(",
"record",
",",
"result",
")",
":",
"record_authors",
"=",
"get_value",
"(",
"record",
",",
"'authors'",
",",
"[",
"]",
")",
"result_authors",
"=",
"get_value",
"(",
"result",
",",
"'_source.authors'",
",",
"[",
"]",
")",
"author_score",
"=",
"compute_author_match_score",
"(",
"record_authors",
",",
"result_authors",
")",
"title_max_score",
"=",
"0.0",
"record_titles",
"=",
"get_value",
"(",
"record",
",",
"'titles.title'",
",",
"[",
"]",
")",
"result_titles",
"=",
"get_value",
"(",
"result",
",",
"'_source.titles.title'",
",",
"[",
"]",
")",
"for",
"cartesian_pair",
"in",
"product",
"(",
"record_titles",
",",
"result_titles",
")",
":",
"record_title_tokens",
"=",
"get_tokenized_title",
"(",
"cartesian_pair",
"[",
"0",
"]",
")",
"result_title_tokens",
"=",
"get_tokenized_title",
"(",
"cartesian_pair",
"[",
"1",
"]",
")",
"current_title_jaccard",
"=",
"compute_jaccard_index",
"(",
"record_title_tokens",
",",
"result_title_tokens",
")",
"if",
"current_title_jaccard",
">",
"title_max_score",
"and",
"current_title_jaccard",
">=",
"0.5",
":",
"title_max_score",
"=",
"current_title_jaccard",
"return",
"(",
"author_score",
"+",
"title_max_score",
")",
"/",
"2",
">",
"0.5"
] |
returns the number of bits actually used to represent the data . | def bitdepth ( data : np . ndarray , snap : bool = True ) -> int : data = asmono ( data ) maxitems = min ( 4096 , data . shape [ 0 ] ) maxbits = max ( x . as_integer_ratio ( ) [ 1 ] for x in data [ : maxitems ] ) . bit_length ( ) if snap : if maxbits <= 8 : maxbits = 8 elif maxbits <= 16 : maxbits = 16 elif maxbits <= 24 : maxbits = 24 elif maxbits <= 32 : maxbits = 32 else : maxbits = 64 return maxbits | 10,858 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L340-L362 | [
"async",
"def",
"subscribe_to",
"(",
"self",
",",
"stream",
",",
"start_from",
"=",
"-",
"1",
",",
"resolve_link_tos",
"=",
"True",
",",
"batch_size",
":",
"int",
"=",
"100",
")",
":",
"if",
"start_from",
"==",
"-",
"1",
":",
"cmd",
":",
"convo",
".",
"Conversation",
"=",
"convo",
".",
"SubscribeToStream",
"(",
"stream",
",",
"resolve_link_tos",
",",
"credentials",
"=",
"self",
".",
"credential",
")",
"else",
":",
"cmd",
"=",
"convo",
".",
"CatchupSubscription",
"(",
"stream",
",",
"start_from",
",",
"batch_size",
",",
"credential",
"=",
"self",
".",
"credential",
")",
"future",
"=",
"await",
"self",
".",
"dispatcher",
".",
"start_conversation",
"(",
"cmd",
")",
"return",
"await",
"future"
] |
Write samples to outfile with samplerate and encoding taken from likefile | def sndwrite_like ( samples : np . ndarray , likefile : str , outfile : str ) -> None : info = sndinfo ( likefile ) sndwrite ( samples , info . samplerate , outfile , encoding = info . encoding ) | 10,859 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L365-L371 | [
"def",
"exec_cmd",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_reduce_boolean_pair",
"(",
"kwargs",
",",
"'online'",
",",
"'offline'",
")",
"if",
"'offline'",
"in",
"kwargs",
":",
"self",
".",
"_meta_data",
"[",
"'exclusive_attributes'",
"]",
".",
"append",
"(",
"(",
"'offline'",
",",
"'standby'",
")",
")",
"if",
"'online'",
"in",
"kwargs",
":",
"self",
".",
"_meta_data",
"[",
"'exclusive_attributes'",
"]",
".",
"append",
"(",
"(",
"'online'",
",",
"'standby'",
")",
")",
"self",
".",
"_is_allowed_command",
"(",
"command",
")",
"self",
".",
"_check_command_parameters",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_exec_cmd",
"(",
"command",
",",
"*",
"*",
"kwargs",
")"
] |
adapted from scipy . io . wavfile . _read_data_chunk | def _wavReadData ( fid , size : int , channels : int , encoding : str , bigendian : bool ) -> np . ndarray : bits = int ( encoding [ 3 : ] ) if bits == 8 : data = np . fromfile ( fid , dtype = np . ubyte , count = size ) if channels > 1 : data = data . reshape ( - 1 , channels ) else : bytes = bits // 8 if encoding in ( 'pcm16' , 'pcm32' , 'pcm64' ) : if bigendian : dtype = '>i%d' % bytes else : dtype = '<i%d' % bytes data = np . fromfile ( fid , dtype = dtype , count = size // bytes ) if channels > 1 : data = data . reshape ( - 1 , channels ) elif encoding [ : 3 ] == 'flt' : print ( "flt32!" ) if bits == 32 : if bigendian : dtype = '>f4' else : dtype = '<f4' else : raise NotImplementedError data = np . fromfile ( fid , dtype = dtype , count = size // bytes ) if channels > 1 : data = data . reshape ( - 1 , channels ) elif encoding == 'pcm24' : # this conversion approach is really bad for long files # TODO: do the same but in chunks data = _numpy24to32bit ( np . fromfile ( fid , dtype = np . ubyte , count = size ) , bigendian = False ) if channels > 1 : data = data . reshape ( - 1 , channels ) return data | 10,860 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L788-L832 | [
"def",
"reset",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'StackInABox({0}): Resetting...'",
".",
"format",
"(",
"self",
".",
"__id",
")",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"services",
")",
":",
"matcher",
",",
"service",
"=",
"v",
"logger",
".",
"debug",
"(",
"'StackInABox({0}): Resetting Service {1}'",
".",
"format",
"(",
"self",
".",
"__id",
",",
"service",
".",
"name",
")",
")",
"service",
".",
"reset",
"(",
")",
"self",
".",
"services",
"=",
"{",
"}",
"self",
".",
"holds",
"=",
"{",
"}",
"logger",
".",
"debug",
"(",
"'StackInABox({0}): Reset Complete'",
".",
"format",
"(",
"self",
".",
"__id",
")",
")"
] |
Read the info of a wav file . taken mostly from scipy . io . wavfile | def _wavGetInfo ( f : Union [ IO , str ] ) -> Tuple [ SndInfo , Dict [ str , Any ] ] : if isinstance ( f , ( str , bytes ) ) : f = open ( f , 'rb' ) needsclosing = True else : needsclosing = False fsize , bigendian = _wavReadRiff ( f ) fmt = ">i" if bigendian else "<i" while ( f . tell ( ) < fsize ) : chunk_id = f . read ( 4 ) if chunk_id == b'fmt ' : chunksize , sampfmt , chans , sr , byterate , align , bits = _wavReadFmt ( f , bigendian ) elif chunk_id == b'data' : datasize = _struct . unpack ( fmt , f . read ( 4 ) ) [ 0 ] nframes = int ( datasize / ( chans * ( bits / 8 ) ) ) break else : _warnings . warn ( "chunk not understood: %s" % chunk_id ) data = f . read ( 4 ) size = _struct . unpack ( fmt , data ) [ 0 ] f . seek ( size , 1 ) encoding = _encoding ( sampfmt , bits ) if needsclosing : f . close ( ) info = SndInfo ( sr , nframes , chans , encoding , "wav" ) return info , { 'fsize' : fsize , 'bigendian' : bigendian , 'datasize' : datasize } | 10,861 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L866-L896 | [
"def",
"put_if_not_exists",
"(",
"self",
",",
"key",
",",
"value",
",",
"lease",
"=",
"None",
")",
":",
"status",
",",
"_",
"=",
"self",
".",
"transaction",
"(",
"compare",
"=",
"[",
"self",
".",
"transactions",
".",
"create",
"(",
"key",
")",
"==",
"'0'",
"]",
",",
"success",
"=",
"[",
"self",
".",
"transactions",
".",
"put",
"(",
"key",
",",
"value",
",",
"lease",
"=",
"lease",
")",
"]",
",",
"failure",
"=",
"[",
"]",
",",
")",
"return",
"status"
] |
Create connection to server | def connect ( self ) : family , stype , proto , cname , sockaddr = self . best_connection_params ( self . host , self . port ) self . sock = socket . socket ( family , stype ) self . sock . settimeout ( self . timeout ) self . sock . connect ( sockaddr ) | 10,862 | https://github.com/bacher09/xrcon/blob/6a883f780265cbca31af7a379dc7cb28fdd8b73f/xrcon/client.py#L53-L59 | [
"def",
"from_string",
"(",
"cls",
",",
"contents",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"contents",
".",
"splitlines",
"(",
")",
"title",
"=",
"None",
"description",
"=",
"None",
"line",
"=",
"lines",
".",
"pop",
"(",
"0",
")",
"while",
"line",
"!=",
"''",
":",
"if",
"not",
"title",
"and",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"title",
"=",
"line",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
"elif",
"line",
".",
"startswith",
"(",
"'title:'",
")",
":",
"title",
"=",
"line",
"[",
"6",
":",
"]",
".",
"strip",
"(",
")",
"elif",
"line",
".",
"startswith",
"(",
"'description:'",
")",
":",
"description",
"=",
"line",
"[",
"12",
":",
"]",
".",
"strip",
"(",
")",
"elif",
"line",
".",
"startswith",
"(",
"'subtitle:'",
")",
":",
"kwargs",
"[",
"'subtitle'",
"]",
"=",
"line",
"[",
"9",
":",
"]",
".",
"strip",
"(",
")",
"elif",
"line",
".",
"startswith",
"(",
"'comments:'",
")",
":",
"try",
":",
"kwargs",
"[",
"'allow_comments'",
"]",
"=",
"_str_to_bool",
"(",
"line",
"[",
"9",
":",
"]",
")",
"except",
"ValueError",
":",
"LOG",
".",
"warning",
"(",
"'invalid boolean value for comments'",
",",
"exc_info",
"=",
"True",
")",
"cls",
".",
"process_meta",
"(",
"line",
",",
"kwargs",
")",
"line",
"=",
"lines",
".",
"pop",
"(",
"0",
")",
"# the only lines left should be the actual contents",
"body",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
".",
"strip",
"(",
")",
"excerpt",
"=",
"_get_excerpt",
"(",
"body",
")",
"if",
"description",
"is",
"None",
":",
"description",
"=",
"_get_description",
"(",
"excerpt",
",",
"160",
")",
"if",
"issubclass",
"(",
"cls",
",",
"Post",
")",
":",
"kwargs",
"[",
"'excerpt'",
"]",
"=",
"render_markdown",
"(",
"excerpt",
")",
"body",
"=",
"render_markdown",
"(",
"body",
")",
"return",
"cls",
"(",
"title",
"=",
"title",
",",
"body",
"=",
"body",
",",
"description",
"=",
"description",
",",
"*",
"*",
"kwargs",
")"
] |
Return server challenge | def getchallenge ( self ) : self . sock . send ( CHALLENGE_PACKET ) # wait challenge response for packet in self . read_iterator ( self . CHALLENGE_TIMEOUT ) : if packet . startswith ( CHALLENGE_RESPONSE_HEADER ) : return parse_challenge_response ( packet ) | 10,863 | https://github.com/bacher09/xrcon/blob/6a883f780265cbca31af7a379dc7cb28fdd8b73f/xrcon/client.py#L86-L92 | [
"def",
"cfg",
"(",
"self",
")",
":",
"config",
"=",
"LStruct",
"(",
"self",
".",
"defaults",
")",
"module",
"=",
"config",
"[",
"'CONFIG'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"CONFIGURATION_ENVIRON_VARIABLE",
",",
"config",
"[",
"'CONFIG'",
"]",
")",
"if",
"module",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"module",
")",
"config",
".",
"update",
"(",
"{",
"name",
":",
"getattr",
"(",
"module",
",",
"name",
")",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
"if",
"name",
"==",
"name",
".",
"upper",
"(",
")",
"and",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"}",
")",
"except",
"ImportError",
"as",
"exc",
":",
"config",
".",
"CONFIG",
"=",
"None",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error importing %s: %s\"",
",",
"module",
",",
"exc",
")",
"# Patch configuration from ENV",
"for",
"name",
"in",
"config",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"name",
"!=",
"name",
".",
"upper",
"(",
")",
"or",
"name",
"not",
"in",
"os",
".",
"environ",
":",
"continue",
"try",
":",
"config",
"[",
"name",
"]",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
"[",
"name",
"]",
")",
"except",
"ValueError",
":",
"pass",
"return",
"config"
] |
Send rcon command to server | def send ( self , command ) : if self . secure_rcon == self . RCON_NOSECURE : self . sock . send ( rcon_nosecure_packet ( self . password , command ) ) elif self . secure_rcon == self . RCON_SECURE_TIME : self . sock . send ( rcon_secure_time_packet ( self . password , command ) ) elif self . secure_rcon == self . RCON_SECURE_CHALLENGE : challenge = self . getchallenge ( ) self . sock . send ( rcon_secure_challenge_packet ( self . password , challenge , command ) ) else : raise ValueError ( "Bad value of secure_rcon" ) | 10,864 | https://github.com/bacher09/xrcon/blob/6a883f780265cbca31af7a379dc7cb28fdd8b73f/xrcon/client.py#L174-L185 | [
"def",
"cfg",
"(",
"self",
")",
":",
"config",
"=",
"LStruct",
"(",
"self",
".",
"defaults",
")",
"module",
"=",
"config",
"[",
"'CONFIG'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"CONFIGURATION_ENVIRON_VARIABLE",
",",
"config",
"[",
"'CONFIG'",
"]",
")",
"if",
"module",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"module",
")",
"config",
".",
"update",
"(",
"{",
"name",
":",
"getattr",
"(",
"module",
",",
"name",
")",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
"if",
"name",
"==",
"name",
".",
"upper",
"(",
")",
"and",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"}",
")",
"except",
"ImportError",
"as",
"exc",
":",
"config",
".",
"CONFIG",
"=",
"None",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error importing %s: %s\"",
",",
"module",
",",
"exc",
")",
"# Patch configuration from ENV",
"for",
"name",
"in",
"config",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"name",
"!=",
"name",
".",
"upper",
"(",
")",
"or",
"name",
"not",
"in",
"os",
".",
"environ",
":",
"continue",
"try",
":",
"config",
"[",
"name",
"]",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
"[",
"name",
"]",
")",
"except",
"ValueError",
":",
"pass",
"return",
"config"
] |
Parse html with wrapper | def parse ( html_string , wrapper = Parser , * args , * * kwargs ) : return Parser ( lxml . html . fromstring ( html_string ) , * args , * * kwargs ) | 10,865 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L112-L114 | [
"def",
"match_url",
"(",
"self",
",",
"request",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"request",
".",
"path_url",
")",
"path_url",
"=",
"parsed_url",
".",
"path",
"query_params",
"=",
"parsed_url",
".",
"query",
"match",
"=",
"None",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"for",
"item",
"in",
"self",
".",
"index",
":",
"target_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BASE_PATH",
",",
"path",
",",
"path_url",
"[",
"1",
":",
"]",
")",
"query_path",
"=",
"target_path",
".",
"lower",
"(",
")",
"+",
"quote",
"(",
"'?'",
"+",
"query_params",
")",
".",
"lower",
"(",
")",
"if",
"target_path",
".",
"lower",
"(",
")",
"==",
"item",
"[",
"0",
"]",
":",
"match",
"=",
"item",
"[",
"1",
"]",
"break",
"elif",
"query_path",
"==",
"item",
"[",
"0",
"]",
":",
"match",
"=",
"item",
"[",
"1",
"]",
"break",
"return",
"match"
] |
Collect digits from a string | def str2int ( string_with_int ) : return int ( "" . join ( [ char for char in string_with_int if char in string . digits ] ) or 0 ) | 10,866 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L117-L119 | [
"def",
"get_listing",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'listing'",
")",
":",
"allEvents",
"=",
"self",
".",
"get_allEvents",
"(",
")",
"openEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
"closedEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
"publicEvents",
"=",
"allEvents",
".",
"instance_of",
"(",
"PublicEvent",
")",
"allSeries",
"=",
"allEvents",
".",
"instance_of",
"(",
"Series",
")",
"self",
".",
"listing",
"=",
"{",
"'allEvents'",
":",
"allEvents",
",",
"'openEvents'",
":",
"openEvents",
",",
"'closedEvents'",
":",
"closedEvents",
",",
"'publicEvents'",
":",
"publicEvents",
",",
"'allSeries'",
":",
"allSeries",
",",
"'regOpenEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'publicevent__category'",
")",
",",
"'regOpenSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateSeries'",
":",
"allSeries",
".",
"filter",
"(",
"series__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'series__category'",
")",
",",
"}",
"return",
"self",
".",
"listing"
] |
Convert string to unicode string | def to_unicode ( obj , encoding = 'utf-8' ) : if isinstance ( obj , string_types ) or isinstance ( obj , binary_type ) : if not isinstance ( obj , text_type ) : obj = text_type ( obj , encoding ) return obj | 10,867 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L122-L127 | [
"def",
"namer",
"(",
"cls",
",",
"imageUrl",
",",
"pageUrl",
")",
":",
"start",
"=",
"''",
"tsmatch",
"=",
"compile",
"(",
"r'/(\\d+)-'",
")",
".",
"search",
"(",
"imageUrl",
")",
"if",
"tsmatch",
":",
"start",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"int",
"(",
"tsmatch",
".",
"group",
"(",
"1",
")",
")",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"else",
":",
"# There were only chapter 1, page 4 and 5 not matching when writing",
"# this...",
"start",
"=",
"'2015-04-11x'",
"return",
"start",
"+",
"\"-\"",
"+",
"pageUrl",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"-",
"1",
"]"
] |
Strip excess spaces from a string | def strip_spaces ( s ) : return u" " . join ( [ c for c in s . split ( u' ' ) if c ] ) | 10,868 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L162-L164 | [
"def",
"updateSeriesRegistrationStatus",
"(",
")",
":",
"from",
".",
"models",
"import",
"Series",
"if",
"not",
"getConstant",
"(",
"'general__enableCronTasks'",
")",
":",
"return",
"logger",
".",
"info",
"(",
"'Checking status of Series that are open for registration.'",
")",
"open_series",
"=",
"Series",
".",
"objects",
".",
"filter",
"(",
")",
".",
"filter",
"(",
"*",
"*",
"{",
"'registrationOpen'",
":",
"True",
"}",
")",
"for",
"series",
"in",
"open_series",
":",
"series",
".",
"updateRegistrationStatus",
"(",
")"
] |
Strip excess line breaks from a string | def strip_linebreaks ( s ) : return u"\n" . join ( [ c for c in s . split ( u'\n' ) if c ] ) | 10,869 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L167-L169 | [
"def",
"updateSeriesRegistrationStatus",
"(",
")",
":",
"from",
".",
"models",
"import",
"Series",
"if",
"not",
"getConstant",
"(",
"'general__enableCronTasks'",
")",
":",
"return",
"logger",
".",
"info",
"(",
"'Checking status of Series that are open for registration.'",
")",
"open_series",
"=",
"Series",
".",
"objects",
".",
"filter",
"(",
")",
".",
"filter",
"(",
"*",
"*",
"{",
"'registrationOpen'",
":",
"True",
"}",
")",
"for",
"series",
"in",
"open_series",
":",
"series",
".",
"updateRegistrationStatus",
"(",
")"
] |
Get first element from CSSSelector | def get ( self , selector , index = 0 , default = None ) : elements = self ( selector ) if elements : try : return elements [ index ] except ( IndexError ) : pass return default | 10,870 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L26-L34 | [
"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",
")"
] |
Return HTML of element | def html ( self , unicode = False ) : html = lxml . html . tostring ( self . element , encoding = self . encoding ) if unicode : html = html . decode ( self . encoding ) return html | 10,871 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L36-L41 | [
"def",
"get_bars",
"(",
"self",
",",
"assets",
",",
"data_frequency",
",",
"bar_count",
"=",
"500",
")",
":",
"assets_is_scalar",
"=",
"not",
"isinstance",
"(",
"assets",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
"is_daily",
"=",
"'d'",
"in",
"data_frequency",
"# 'daily' or '1d'",
"if",
"assets_is_scalar",
":",
"symbols",
"=",
"[",
"assets",
".",
"symbol",
"]",
"else",
":",
"symbols",
"=",
"[",
"asset",
".",
"symbol",
"for",
"asset",
"in",
"assets",
"]",
"symbol_bars",
"=",
"self",
".",
"_symbol_bars",
"(",
"symbols",
",",
"'day'",
"if",
"is_daily",
"else",
"'minute'",
",",
"limit",
"=",
"bar_count",
")",
"if",
"is_daily",
":",
"intra_bars",
"=",
"{",
"}",
"symbol_bars_minute",
"=",
"self",
".",
"_symbol_bars",
"(",
"symbols",
",",
"'minute'",
",",
"limit",
"=",
"1000",
")",
"for",
"symbol",
",",
"df",
"in",
"symbol_bars_minute",
".",
"items",
"(",
")",
":",
"agged",
"=",
"df",
".",
"resample",
"(",
"'1D'",
")",
".",
"agg",
"(",
"dict",
"(",
"open",
"=",
"'first'",
",",
"high",
"=",
"'max'",
",",
"low",
"=",
"'min'",
",",
"close",
"=",
"'last'",
",",
"volume",
"=",
"'sum'",
",",
")",
")",
".",
"dropna",
"(",
")",
"intra_bars",
"[",
"symbol",
"]",
"=",
"agged",
"dfs",
"=",
"[",
"]",
"for",
"asset",
"in",
"assets",
"if",
"not",
"assets_is_scalar",
"else",
"[",
"assets",
"]",
":",
"symbol",
"=",
"asset",
".",
"symbol",
"df",
"=",
"symbol_bars",
".",
"get",
"(",
"symbol",
")",
"if",
"df",
"is",
"None",
":",
"dfs",
".",
"append",
"(",
"pd",
".",
"DataFrame",
"(",
"[",
"]",
",",
"columns",
"=",
"[",
"'open'",
",",
"'high'",
",",
"'low'",
",",
"'close'",
",",
"'volume'",
"]",
")",
")",
"continue",
"if",
"is_daily",
":",
"agged",
"=",
"intra_bars",
".",
"get",
"(",
"symbol",
")",
"if",
"agged",
"is",
"not",
"None",
"and",
"len",
"(",
"agged",
".",
"index",
")",
">",
"0",
"and",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
"not",
"in",
"df",
".",
"index",
":",
"if",
"not",
"(",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
">",
"df",
".",
"index",
"[",
"-",
"1",
"]",
")",
":",
"log",
".",
"warn",
"(",
"(",
"'agged.index[-1] = {}, df.index[-1] = {} '",
"'for {}'",
")",
".",
"format",
"(",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
",",
"df",
".",
"index",
"[",
"-",
"1",
"]",
",",
"symbol",
")",
")",
"df",
"=",
"df",
".",
"append",
"(",
"agged",
".",
"iloc",
"[",
"-",
"1",
"]",
")",
"df",
".",
"columns",
"=",
"pd",
".",
"MultiIndex",
".",
"from_product",
"(",
"[",
"[",
"asset",
",",
"]",
",",
"df",
".",
"columns",
"]",
")",
"dfs",
".",
"append",
"(",
"df",
")",
"return",
"pd",
".",
"concat",
"(",
"dfs",
",",
"axis",
"=",
"1",
")"
] |
Parse element with given function | def parse ( self , func , * args , * * kwargs ) : result = [ ] for element in self . xpath ( 'child::node()' ) : if isinstance ( element , Parser ) : children = element . parse ( func , * args , * * kwargs ) element_result = func ( element , children , * args , * * kwargs ) if element_result : result . append ( element_result ) else : result . append ( element ) return u"" . join ( result ) | 10,872 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L55-L66 | [
"def",
"DeleteSnapshot",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"self",
".",
"GetSnapshots",
"(",
")",
"requests_lst",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"name_links",
"=",
"[",
"obj",
"[",
"'links'",
"]",
"for",
"obj",
"in",
"self",
".",
"data",
"[",
"'details'",
"]",
"[",
"'snapshots'",
"]",
"if",
"obj",
"[",
"'name'",
"]",
"==",
"name",
"]",
"[",
"0",
"]",
"requests_lst",
".",
"append",
"(",
"clc",
".",
"v2",
".",
"Requests",
"(",
"clc",
".",
"v2",
".",
"API",
".",
"Call",
"(",
"'DELETE'",
",",
"[",
"obj",
"[",
"'href'",
"]",
"for",
"obj",
"in",
"name_links",
"if",
"obj",
"[",
"'rel'",
"]",
"==",
"'delete'",
"]",
"[",
"0",
"]",
",",
"session",
"=",
"self",
".",
"session",
")",
",",
"alias",
"=",
"self",
".",
"alias",
",",
"session",
"=",
"self",
".",
"session",
")",
")",
"return",
"(",
"sum",
"(",
"requests_lst",
")",
")"
] |
Wrap result in Parser instance | def _wrap_result ( self , func ) : def wrapper ( * args ) : result = func ( * args ) if hasattr ( result , '__iter__' ) and not isinstance ( result , etree . _Element ) : return [ self . _wrap_element ( element ) for element in result ] else : return self . _wrap_element ( result ) return wrapper | 10,873 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L68-L76 | [
"def",
"generate_urls",
"(",
"self",
",",
"first_url",
",",
"last_url",
")",
":",
"first_url",
"=",
"first_url",
".",
"split",
"(",
"\"/\"",
")",
"last_url",
"=",
"last_url",
".",
"split",
"(",
"\"/\"",
")",
"if",
"first_url",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"\"http:\"",
"or",
"last_url",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"\"http:\"",
":",
"raise",
"Exception",
"(",
"\"URLs should be accessible via HTTP.\"",
")",
"url_base",
"=",
"\"/\"",
".",
"join",
"(",
"first_url",
"[",
":",
"-",
"1",
"]",
")",
"start_index",
"=",
"first_url",
"[",
"-",
"1",
"]",
".",
"index",
"(",
"\"a\"",
")",
"file_name",
"=",
"first_url",
"[",
"-",
"1",
"]",
"[",
"0",
":",
"start_index",
"]",
"url_base",
"+=",
"\"/\"",
"+",
"file_name",
"start",
"=",
"first_url",
"[",
"-",
"1",
"]",
"[",
"start_index",
":",
"]",
"finish",
"=",
"last_url",
"[",
"-",
"1",
"]",
"[",
"start_index",
":",
"]",
"if",
"start",
".",
"count",
"(",
"\".\"",
")",
"==",
"1",
"and",
"finish",
".",
"count",
"(",
"\".\"",
")",
"==",
"1",
":",
"start",
",",
"file_extension",
"=",
"start",
".",
"split",
"(",
"\".\"",
")",
"finish",
",",
"_",
"=",
"finish",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"start",
")",
"!=",
"len",
"(",
"finish",
")",
":",
"raise",
"Exception",
"(",
"\"Filenames in url should have the same length.\"",
")",
"file_extension",
"=",
"\".\"",
"+",
"file_extension",
"else",
":",
"raise",
"Exception",
"(",
"\"URLs does not have the same pattern.\"",
")",
"alphabet",
"=",
"\"abcdefghijklmnopqrstuvwxyz\"",
"product",
"=",
"itertools",
".",
"product",
"(",
"alphabet",
",",
"repeat",
"=",
"len",
"(",
"start",
")",
")",
"urls",
"=",
"[",
"]",
"for",
"p",
"in",
"product",
":",
"urls",
".",
"append",
"(",
"[",
"url_base",
"+",
"\"\"",
".",
"join",
"(",
"p",
")",
"+",
"file_extension",
"]",
")",
"if",
"\"\"",
".",
"join",
"(",
"p",
")",
"==",
"finish",
":",
"break",
"return",
"urls"
] |
Wrap single element in Parser instance | def _wrap_element ( self , result ) : if isinstance ( result , lxml . html . HtmlElement ) : return Parser ( result ) else : return result | 10,874 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L78-L83 | [
"def",
"_index_audio_ibm",
"(",
"self",
",",
"basename",
"=",
"None",
",",
"replace_already_indexed",
"=",
"False",
",",
"continuous",
"=",
"True",
",",
"model",
"=",
"\"en-US_BroadbandModel\"",
",",
"word_confidence",
"=",
"True",
",",
"word_alternatives_threshold",
"=",
"0.9",
",",
"profanity_filter_for_US_results",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'continuous'",
":",
"continuous",
",",
"'model'",
":",
"model",
",",
"'word_alternatives_threshold'",
":",
"word_alternatives_threshold",
",",
"'word_confidence'",
":",
"word_confidence",
",",
"'timestamps'",
":",
"True",
",",
"'inactivity_timeout'",
":",
"str",
"(",
"-",
"1",
")",
",",
"'profanity_filter'",
":",
"profanity_filter_for_US_results",
"}",
"self",
".",
"_prepare_audio",
"(",
"basename",
"=",
"basename",
",",
"replace_already_indexed",
"=",
"replace_already_indexed",
")",
"for",
"staging_audio_basename",
"in",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
":",
"original_audio_name",
"=",
"''",
".",
"join",
"(",
"staging_audio_basename",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"[",
":",
"-",
"3",
"]",
"with",
"open",
"(",
"\"{}/staging/{}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"staging_audio_basename",
")",
",",
"\"rb\"",
")",
"as",
"f",
":",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Uploading {}...\"",
".",
"format",
"(",
"staging_audio_basename",
")",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"(",
"\"https://stream.watsonplatform.net/\"",
"\"speech-to-text/api/v1/recognize\"",
")",
",",
"auth",
"=",
"(",
"self",
".",
"get_username_ibm",
"(",
")",
",",
"self",
".",
"get_password_ibm",
"(",
")",
")",
",",
"headers",
"=",
"{",
"'content-type'",
":",
"'audio/wav'",
"}",
",",
"data",
"=",
"f",
".",
"read",
"(",
")",
",",
"params",
"=",
"params",
")",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Indexing {}...\"",
".",
"format",
"(",
"staging_audio_basename",
")",
")",
"self",
".",
"__timestamps_unregulated",
"[",
"original_audio_name",
"+",
"\".wav\"",
"]",
".",
"append",
"(",
"self",
".",
"_timestamp_extractor_ibm",
"(",
"staging_audio_basename",
",",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
")",
")",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Done indexing {}\"",
".",
"format",
"(",
"staging_audio_basename",
")",
")",
"self",
".",
"_timestamp_regulator",
"(",
")",
"if",
"self",
".",
"get_verbosity",
"(",
")",
":",
"print",
"(",
"\"Indexing procedure finished\"",
")"
] |
Inline parsing is postponed so that all link references are seen before that . | def parse_inline ( self ) : if self . inline_children : self . children = parser . parse_inline ( self . children ) elif isinstance ( getattr ( self , 'children' , None ) , list ) : for child in self . children : if isinstance ( child , BlockElement ) : child . parse_inline ( ) | 10,875 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/block.py#L59-L68 | [
"def",
"compact",
"(",
"self",
",",
"revision",
",",
"physical",
"=",
"False",
")",
":",
"compact_request",
"=",
"etcdrpc",
".",
"CompactionRequest",
"(",
"revision",
"=",
"revision",
",",
"physical",
"=",
"physical",
")",
"self",
".",
"kvstub",
".",
"Compact",
"(",
"compact_request",
",",
"self",
".",
"timeout",
",",
"credentials",
"=",
"self",
".",
"call_credentials",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] |
Generate a Work model . | def work_model_factory ( * , validator = validators . is_work_model , * * kwargs ) : kwargs [ 'ld_type' ] = 'AbstractWork' return _model_factory ( validator = validator , * * kwargs ) | 10,876 | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L241-L252 | [
"def",
"shutdown_kernel",
"(",
"self",
")",
":",
"kernel_id",
"=",
"self",
".",
"get_kernel_id",
"(",
")",
"if",
"kernel_id",
":",
"delete_url",
"=",
"self",
".",
"add_token",
"(",
"url_path_join",
"(",
"self",
".",
"server_url",
",",
"'api/kernels/'",
",",
"kernel_id",
")",
")",
"delete_req",
"=",
"requests",
".",
"delete",
"(",
"delete_url",
")",
"if",
"delete_req",
".",
"status_code",
"!=",
"204",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"_",
"(",
"\"Server error\"",
")",
",",
"_",
"(",
"\"The Jupyter Notebook server \"",
"\"failed to shutdown the kernel \"",
"\"associated with this notebook. \"",
"\"If you want to shut it down, \"",
"\"you'll have to close Spyder.\"",
")",
")"
] |
Generate a Manifestation model . | def manifestation_model_factory ( * , validator = validators . is_manifestation_model , ld_type = 'CreativeWork' , * * kwargs ) : return _model_factory ( validator = validator , ld_type = ld_type , * * kwargs ) | 10,877 | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L255-L262 | [
"def",
"stop",
"(",
"self",
")",
":",
"try",
":",
"if",
"(",
"self",
".",
"websock",
"and",
"self",
".",
"websock",
".",
"sock",
"and",
"self",
".",
"websock",
".",
"sock",
".",
"connected",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'shutting down websocket connection'",
")",
"try",
":",
"self",
".",
"websock",
".",
"close",
"(",
")",
"except",
"BaseException",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'exception closing websocket %s - %s'",
",",
"self",
".",
"websock",
",",
"e",
")",
"self",
".",
"chrome",
".",
"stop",
"(",
")",
"if",
"self",
".",
"websock_thread",
"and",
"(",
"self",
".",
"websock_thread",
"!=",
"threading",
".",
"current_thread",
"(",
")",
")",
":",
"self",
".",
"websock_thread",
".",
"join",
"(",
"timeout",
"=",
"30",
")",
"if",
"self",
".",
"websock_thread",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'%s still alive 30 seconds after closing %s, will '",
"'forcefully nudge it again'",
",",
"self",
".",
"websock_thread",
",",
"self",
".",
"websock",
")",
"self",
".",
"websock",
".",
"keep_running",
"=",
"False",
"self",
".",
"websock_thread",
".",
"join",
"(",
"timeout",
"=",
"30",
")",
"if",
"self",
".",
"websock_thread",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"logger",
".",
"critical",
"(",
"'%s still alive 60 seconds after closing %s'",
",",
"self",
".",
"websock_thread",
",",
"self",
".",
"websock",
")",
"self",
".",
"websock_url",
"=",
"None",
"except",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'problem stopping'",
",",
"exc_info",
"=",
"True",
")"
] |
Generate a Right model . | def right_model_factory ( * , validator = validators . is_right_model , ld_type = 'Right' , * * kwargs ) : return _model_factory ( validator = validator , ld_type = ld_type , * * kwargs ) | 10,878 | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L265-L272 | [
"async",
"def",
"setup_streamer",
"(",
"self",
")",
":",
"self",
".",
"streamer",
".",
"volume",
"=",
"self",
".",
"volume",
"/",
"100",
"self",
".",
"streamer",
".",
"start",
"(",
")",
"self",
".",
"pause_time",
"=",
"None",
"self",
".",
"vclient_starttime",
"=",
"self",
".",
"vclient",
".",
"loop",
".",
"time",
"(",
")",
"# Cache next song",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Caching next song\"",
")",
"dl_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"download_next_song_cache",
")",
"dl_thread",
".",
"start",
"(",
")"
] |
Generate a Copyright model . | def copyright_model_factory ( * , validator = validators . is_copyright_model , * * kwargs ) : kwargs [ 'ld_type' ] = 'Copyright' return _model_factory ( validator = validator , * * kwargs ) | 10,879 | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L276-L288 | [
"def",
"get_queue_info",
"(",
"self",
",",
"instance",
",",
"cursor",
")",
":",
"cursor",
".",
"execute",
"(",
"self",
".",
"QUEUE_INFO_STATEMENT",
")",
"for",
"queue_name",
",",
"ticker_lag",
",",
"ev_per_sec",
"in",
"cursor",
":",
"yield",
"queue_name",
",",
"{",
"'ticker_lag'",
":",
"ticker_lag",
",",
"'ev_per_sec'",
":",
"ev_per_sec",
",",
"}"
] |
Mark an exception instance or type as retryable . If this exception is caught by pyramid_retry then it may retry the request . | def mark_error_retryable ( error ) : if isinstance ( error , Exception ) : alsoProvides ( error , IRetryableError ) elif inspect . isclass ( error ) and issubclass ( error , Exception ) : classImplements ( error , IRetryableError ) else : raise ValueError ( 'only exception objects or types may be marked retryable' ) | 10,880 | https://github.com/Pylons/pyramid_retry/blob/4518d0655159fcf5cf79c0d7d4c86e8315f16082/src/pyramid_retry/__init__.py#L149-L161 | [
"def",
"getWorkersName",
"(",
"data",
")",
":",
"names",
"=",
"[",
"fichier",
"for",
"fichier",
"in",
"data",
".",
"keys",
"(",
")",
"]",
"names",
".",
"sort",
"(",
")",
"try",
":",
"names",
".",
"remove",
"(",
"\"broker\"",
")",
"except",
"ValueError",
":",
"pass",
"return",
"names"
] |
Return True if the request is on its last attempt meaning that pyramid_retry will not be issuing any new attempts regardless of what happens when executing this request . | def is_last_attempt ( request ) : environ = request . environ attempt = environ . get ( 'retry.attempt' ) attempts = environ . get ( 'retry.attempts' ) if attempt is None or attempts is None : return True return attempt + 1 == attempts | 10,881 | https://github.com/Pylons/pyramid_retry/blob/4518d0655159fcf5cf79c0d7d4c86e8315f16082/src/pyramid_retry/__init__.py#L182-L198 | [
"def",
"from_raw_message",
"(",
"cls",
",",
"rawmessage",
")",
":",
"empty",
"=",
"cls",
".",
"create_empty",
"(",
"0x00",
")",
"userdata_dict",
"=",
"cls",
".",
"normalize",
"(",
"empty",
",",
"rawmessage",
")",
"return",
"Userdata",
"(",
"userdata_dict",
")"
] |
Activate the pyramid_retry execution policy in your application . | def includeme ( config ) : settings = config . get_settings ( ) config . add_view_predicate ( 'last_retry_attempt' , LastAttemptPredicate ) config . add_view_predicate ( 'retryable_error' , RetryableErrorPredicate ) def register ( ) : attempts = int ( settings . get ( 'retry.attempts' ) or 3 ) settings [ 'retry.attempts' ] = attempts activate_hook = settings . get ( 'retry.activate_hook' ) activate_hook = config . maybe_dotted ( activate_hook ) policy = RetryableExecutionPolicy ( attempts , activate_hook = activate_hook , ) config . set_execution_policy ( policy ) # defer registration to allow time to modify settings config . action ( None , register , order = PHASE1_CONFIG ) | 10,882 | https://github.com/Pylons/pyramid_retry/blob/4518d0655159fcf5cf79c0d7d4c86e8315f16082/src/pyramid_retry/__init__.py#L259-L292 | [
"def",
"_readASCII",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"waveunits",
"=",
"units",
".",
"Units",
"(",
"'angstrom'",
")",
"self",
".",
"fluxunits",
"=",
"units",
".",
"Units",
"(",
"'flam'",
")",
"wlist",
",",
"flist",
"=",
"self",
".",
"_columnsFromASCII",
"(",
"filename",
")",
"self",
".",
"_wavetable",
"=",
"N",
".",
"array",
"(",
"wlist",
",",
"dtype",
"=",
"N",
".",
"float64",
")",
"self",
".",
"_fluxtable",
"=",
"N",
".",
"array",
"(",
"flist",
",",
"dtype",
"=",
"N",
".",
"float64",
")"
] |
calculates the coefficients for a digital butterworth filter | def filter_butter_coeffs ( filtertype , freq , samplerate , order = 5 ) : # type: (str, Union[float, Tuple[float, float]], int, int) -> Tuple[np.ndarray, np.ndarray] assert filtertype in ( 'low' , 'high' , 'band' ) nyq = 0.5 * samplerate if isinstance ( freq , tuple ) : assert filtertype == 'band' low , high = freq low /= nyq high /= nyq b , a = signal . butter ( order , [ low , high ] , btype = 'band' ) else : freq = freq / nyq b , a = signal . butter ( order , freq , btype = filtertype ) return b , a | 10,883 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/dsp.py#L63-L85 | [
"def",
"classify",
"(",
"self",
",",
"txt",
")",
":",
"ranks",
"=",
"[",
"]",
"for",
"lang",
",",
"score",
"in",
"langid",
".",
"rank",
"(",
"txt",
")",
":",
"if",
"lang",
"in",
"self",
".",
"preferred_languages",
":",
"score",
"+=",
"self",
".",
"preferred_factor",
"ranks",
".",
"append",
"(",
"(",
"lang",
",",
"score",
")",
")",
"ranks",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"reverse",
"=",
"True",
")",
"return",
"ranks",
"[",
"0",
"]",
"[",
"0",
"]"
] |
Filters the samples with a digital butterworth filter | def filter_butter ( samples , samplerate , filtertype , freq , order = 5 ) : # type: (np.ndarray, int, str, float, int) -> np.ndarray assert filtertype in ( 'low' , 'high' , 'band' ) b , a = filter_butter_coeffs ( filtertype , freq , samplerate , order = order ) return apply_multichannel ( samples , lambda data : signal . lfilter ( b , a , data ) ) | 10,884 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/dsp.py#L88-L106 | [
"def",
"mangle_volume",
"(",
"citation_elements",
")",
":",
"volume_re",
"=",
"re",
".",
"compile",
"(",
"ur\"(\\d+)([A-Z])\"",
",",
"re",
".",
"U",
"|",
"re",
".",
"I",
")",
"for",
"el",
"in",
"citation_elements",
":",
"if",
"el",
"[",
"'type'",
"]",
"==",
"'JOURNAL'",
":",
"matches",
"=",
"volume_re",
".",
"match",
"(",
"el",
"[",
"'volume'",
"]",
")",
"if",
"matches",
":",
"el",
"[",
"'volume'",
"]",
"=",
"matches",
".",
"group",
"(",
"2",
")",
"+",
"matches",
".",
"group",
"(",
"1",
")",
"return",
"citation_elements"
] |
Reinject token and consistency into requests . | def token_middleware ( ctx , get_response ) : async def middleware ( request ) : params = request . setdefault ( 'params' , { } ) if params . get ( "token" ) is None : params [ 'token' ] = ctx . token return await get_response ( request ) return middleware | 10,885 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/api.py#L212-L220 | [
"def",
"download_file",
"(",
"self",
",",
"regex",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.download_file'",
")",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'regex argument is not a string'",
")",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"dest_dir",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'dest_dir argument is not a string'",
")",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest_dir",
")",
":",
"log",
".",
"error",
"(",
"'Directory not found on file system: %s'",
",",
"dest_dir",
")",
"return",
"None",
"key",
"=",
"self",
".",
"find_key",
"(",
"regex",
")",
"if",
"key",
"is",
"None",
":",
"log",
".",
"warn",
"(",
"'Could not find a matching S3 key for: %s'",
",",
"regex",
")",
"return",
"None",
"return",
"self",
".",
"__download_from_s3",
"(",
"key",
",",
"dest_dir",
")"
] |
Rebuilds the dependency path for this item . | def rebuild ( self ) : scene = self . scene ( ) if ( not scene ) : return sourcePos = self . sourceItem ( ) . viewItem ( ) . pos ( ) sourceRect = self . sourceItem ( ) . viewItem ( ) . rect ( ) targetPos = self . targetItem ( ) . viewItem ( ) . pos ( ) targetRect = self . targetItem ( ) . viewItem ( ) . rect ( ) cellWidth = scene . ganttWidget ( ) . cellWidth ( ) startX = sourcePos . x ( ) + sourceRect . width ( ) - ( cellWidth / 2.0 ) startY = sourcePos . y ( ) + ( sourceRect . height ( ) / 2.0 ) endX = targetPos . x ( ) - 2 endY = targetPos . y ( ) + ( targetRect . height ( ) / 2.0 ) path = QPainterPath ( ) path . moveTo ( startX , startY ) path . lineTo ( startX , endY ) path . lineTo ( endX , endY ) a = QPointF ( endX - 10 , endY - 3 ) b = QPointF ( endX , endY ) c = QPointF ( endX - 10 , endY + 3 ) self . _polygon = QPolygonF ( [ a , b , c , a ] ) path . addPolygon ( self . _polygon ) self . setPath ( path ) | 10,886 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttdepitem.py#L60-L95 | [
"def",
"on_start",
"(",
"self",
",",
"session",
",",
"session_context",
")",
":",
"session_id",
"=",
"session",
".",
"session_id",
"web_registry",
"=",
"session_context",
"[",
"'web_registry'",
"]",
"if",
"self",
".",
"is_session_id_cookie_enabled",
":",
"web_registry",
".",
"session_id",
"=",
"session_id",
"logger",
".",
"debug",
"(",
"\"Set SessionID cookie using id: \"",
"+",
"str",
"(",
"session_id",
")",
")",
"else",
":",
"msg",
"=",
"(",
"\"Session ID cookie is disabled. No cookie has been set for \"",
"\"new session with id: \"",
"+",
"str",
"(",
"session_id",
")",
")",
"logger",
".",
"debug",
"(",
"msg",
")"
] |
writes the block to a file with the id | def _writeBlock ( block , blockID ) : with open ( "blockIDs.txt" , "a" ) as fp : fp . write ( "blockID: " + str ( blockID ) + "\n" ) sentences = "" for sentence in block : sentences += sentence + "," fp . write ( "block sentences: " + sentences [ : - 1 ] + "\n" ) fp . write ( "\n" ) | 10,887 | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L38-L46 | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'aggregations'",
"in",
"_dict",
":",
"args",
"[",
"'aggregations'",
"]",
"=",
"[",
"MetricAggregation",
".",
"_from_dict",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"_dict",
".",
"get",
"(",
"'aggregations'",
")",
")",
"]",
"return",
"cls",
"(",
"*",
"*",
"args",
")"
] |
writes the sentence in a block to a file with the id | def _writeSentenceInBlock ( sentence , blockID , sentenceID ) : with open ( "sentenceIDs.txt" , "a" ) as fp : fp . write ( "sentenceID: " + str ( blockID ) + "_" + str ( sentenceID ) + "\n" ) fp . write ( "sentence string: " + sentence + "\n" ) fp . write ( "\n" ) | 10,888 | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L49-L54 | [
"def",
"remove_stale_javascripts",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing stale javascripts ...\"",
")",
"for",
"js",
"in",
"JAVASCRIPTS_TO_REMOVE",
":",
"logger",
".",
"info",
"(",
"\"Unregistering JS %s\"",
"%",
"js",
")",
"portal",
".",
"portal_javascripts",
".",
"unregisterResource",
"(",
"js",
")"
] |
writes the word from a sentence in a block to a file with the id | def _writeWordFromSentenceInBlock ( word , blockID , sentenceID , wordID ) : with open ( "wordIDs.txt" , "a" ) as fp : fp . write ( "wordID: " + str ( blockID ) + "_" + str ( sentenceID ) + "_" + str ( wordID ) + "\n" ) fp . write ( "wordString: " + word + "\n" ) fp . write ( "\n" ) | 10,889 | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L57-L63 | [
"def",
"is_registration_possible",
"(",
"self",
",",
"user_info",
")",
":",
"return",
"self",
".",
"get_accessibility",
"(",
")",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"_registration",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"is_user_accepted_by_access_control",
"(",
"user_info",
")"
] |
Writes a background file to disk . | def _writeBk ( target = "sentenceContainsTarget(+SID,+WID)." , treeDepth = "3" , nodeSize = "3" , numOfClauses = "8" ) : with open ( 'bk.txt' , 'w' ) as bk : bk . write ( "useStdLogicVariables: true\n" ) bk . write ( "setParam: treeDepth=" + str ( treeDepth ) + '.\n' ) bk . write ( "setParam: nodeSize=" + str ( nodeSize ) + '.\n' ) bk . write ( "setParam: numOfClauses=" + str ( numOfClauses ) + '.\n' ) bk . write ( "mode: nextSentenceInBlock(+BID,+SID,-SID).\n" ) bk . write ( "mode: nextSentenceInBlock(+BID,-SID,+SID).\n" ) bk . write ( "mode: earlySentenceInBlock(+BID,-SID).\n" ) bk . write ( "mode: midWaySentenceInBlock(+BID,-SID).\n" ) bk . write ( "mode: lateSentenceInBlock(+BID,-SID).\n" ) bk . write ( "mode: sentenceInBlock(-SID,+BID).\n" ) bk . write ( "mode: wordString(+WID,#WSTR).\n" ) bk . write ( "mode: partOfSpeechTag(+WID,#WPOS).\n" ) bk . write ( "mode: nextWordInSentence(+SID,+WID,-WID).\n" ) bk . write ( "mode: earlyWordInSentence(+SID,-WID).\n" ) bk . write ( "mode: midWayWordInSentence(+SID,-WID).\n" ) bk . write ( "mode: lateWordInSentence(+SID,-WID).\n" ) bk . write ( "mode: wordInSentence(-WID,+SID).\n" ) bk . write ( "mode: " + target + "\n" ) return | 10,890 | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L72-L111 | [
"def",
"immediateAspects",
"(",
"self",
",",
"ID",
",",
"aspList",
")",
":",
"asps",
"=",
"self",
".",
"aspectsByCat",
"(",
"ID",
",",
"aspList",
")",
"applications",
"=",
"asps",
"[",
"const",
".",
"APPLICATIVE",
"]",
"separations",
"=",
"asps",
"[",
"const",
".",
"SEPARATIVE",
"]",
"exact",
"=",
"asps",
"[",
"const",
".",
"EXACT",
"]",
"# Get applications and separations sorted by orb",
"applications",
"=",
"applications",
"+",
"[",
"val",
"for",
"val",
"in",
"exact",
"if",
"val",
"[",
"'orb'",
"]",
">=",
"0",
"]",
"applications",
"=",
"sorted",
"(",
"applications",
",",
"key",
"=",
"lambda",
"var",
":",
"var",
"[",
"'orb'",
"]",
")",
"separations",
"=",
"sorted",
"(",
"separations",
",",
"key",
"=",
"lambda",
"var",
":",
"var",
"[",
"'orb'",
"]",
")",
"return",
"(",
"separations",
"[",
"0",
"]",
"if",
"separations",
"else",
"None",
",",
"applications",
"[",
"0",
"]",
"if",
"applications",
"else",
"None",
")"
] |
Visits the internal nodes of the enhanced suffix array in depth - first pre - order . | def traverse_depth_first_pre_order ( self , callback ) : n = len ( self . suftab ) root = [ 0 , 0 , n - 1 , "" ] # <l, i, j, char> def _traverse_top_down ( interval ) : # TODO: Rewrite with stack? As in bottom-up callback ( interval ) i , j = interval [ 1 ] , interval [ 2 ] if i != j : children = self . _get_child_intervals ( i , j ) children . sort ( key = lambda child : child [ 3 ] ) for child in children : _traverse_top_down ( child ) _traverse_top_down ( root ) | 10,891 | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L38-L55 | [
"def",
"WriteBlobs",
"(",
"self",
",",
"blob_id_data_map",
",",
"cursor",
"=",
"None",
")",
":",
"chunks",
"=",
"[",
"]",
"for",
"blob_id",
",",
"blob",
"in",
"iteritems",
"(",
"blob_id_data_map",
")",
":",
"chunks",
".",
"extend",
"(",
"_BlobToChunks",
"(",
"blob_id",
".",
"AsBytes",
"(",
")",
",",
"blob",
")",
")",
"for",
"values",
"in",
"_PartitionChunks",
"(",
"chunks",
")",
":",
"_Insert",
"(",
"cursor",
",",
"\"blobs\"",
",",
"values",
")"
] |
Visits the internal nodes of the enhanced suffix array in depth - first post - order . | def traverse_depth_first_post_order ( self , callback ) : # a. Reimplement without python lists?.. # b. Interface will require it to have not internal nodes only?.. # (but actually this implementation gives a ~2x gain of performance) last_interval = None n = len ( self . suftab ) stack = [ [ 0 , 0 , None , [ ] ] ] # <l, i, j, children> for i in xrange ( 1 , n ) : lb = i - 1 while self . lcptab [ i ] < stack [ - 1 ] [ 0 ] : stack [ - 1 ] [ 2 ] = i - 1 last_interval = stack . pop ( ) callback ( last_interval ) lb = last_interval [ 1 ] if self . lcptab [ i ] <= stack [ - 1 ] [ 0 ] : stack [ - 1 ] [ 3 ] . append ( last_interval ) last_interval = None if self . lcptab [ i ] > stack [ - 1 ] [ 0 ] : if last_interval : stack . append ( [ self . lcptab [ i ] , lb , None , [ last_interval ] ] ) last_interval = None else : stack . append ( [ self . lcptab [ i ] , lb , None , [ ] ] ) stack [ - 1 ] [ 2 ] = n - 1 callback ( stack [ - 1 ] ) | 10,892 | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L57-L85 | [
"def",
"DIV",
"(",
"classical_reg",
",",
"right",
")",
":",
"left",
",",
"right",
"=",
"unpack_reg_val_pair",
"(",
"classical_reg",
",",
"right",
")",
"return",
"ClassicalDiv",
"(",
"left",
",",
"right",
")"
] |
Turn a key into a string if possible | def _DecodeKey ( self , key ) : if self . dict . attrindex . HasBackward ( key ) : return self . dict . attrindex . GetBackward ( key ) return key | 10,893 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L146-L151 | [
"def",
"IOR",
"(",
"classical_reg1",
",",
"classical_reg2",
")",
":",
"left",
",",
"right",
"=",
"unpack_reg_val_pair",
"(",
"classical_reg1",
",",
"classical_reg2",
")",
"return",
"ClassicalInclusiveOr",
"(",
"left",
",",
"right",
")"
] |
Add an attribute to the packet . | def AddAttribute ( self , key , value ) : if isinstance ( value , list ) : values = value else : values = [ value ] ( key , values ) = self . _EncodeKeyValues ( key , values ) self . setdefault ( key , [ ] ) . extend ( values ) | 10,894 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L153-L167 | [
"def",
"read",
"(",
"self",
",",
"path",
",",
"ext",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"npartitions",
"=",
"None",
")",
":",
"from",
".",
"utils",
"import",
"connection_with_anon",
",",
"connection_with_gs",
"path",
"=",
"addextension",
"(",
"path",
",",
"ext",
")",
"scheme",
",",
"bucket_name",
",",
"keylist",
"=",
"self",
".",
"getfiles",
"(",
"path",
",",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"recursive",
"=",
"recursive",
")",
"if",
"not",
"keylist",
":",
"raise",
"FileNotFoundError",
"(",
"\"No objects found for '%s'\"",
"%",
"path",
")",
"credentials",
"=",
"self",
".",
"credentials",
"self",
".",
"nfiles",
"=",
"len",
"(",
"keylist",
")",
"if",
"spark",
"and",
"isinstance",
"(",
"self",
".",
"engine",
",",
"spark",
")",
":",
"def",
"getsplit",
"(",
"kvIter",
")",
":",
"if",
"scheme",
"==",
"'s3'",
"or",
"scheme",
"==",
"'s3n'",
":",
"conn",
"=",
"connection_with_anon",
"(",
"credentials",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
"bucket_name",
")",
"elif",
"scheme",
"==",
"'gs'",
":",
"conn",
"=",
"boto",
".",
"storage_uri",
"(",
"bucket_name",
",",
"'gs'",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"No file reader implementation for URL scheme \"",
"+",
"scheme",
")",
"for",
"kv",
"in",
"kvIter",
":",
"idx",
",",
"keyname",
"=",
"kv",
"key",
"=",
"bucket",
".",
"get_key",
"(",
"keyname",
")",
"buf",
"=",
"key",
".",
"get_contents_as_string",
"(",
")",
"yield",
"idx",
",",
"buf",
",",
"keyname",
"npartitions",
"=",
"min",
"(",
"npartitions",
",",
"self",
".",
"nfiles",
")",
"if",
"npartitions",
"else",
"self",
".",
"nfiles",
"rdd",
"=",
"self",
".",
"engine",
".",
"parallelize",
"(",
"enumerate",
"(",
"keylist",
")",
",",
"npartitions",
")",
"return",
"rdd",
".",
"mapPartitions",
"(",
"getsplit",
")",
"else",
":",
"if",
"scheme",
"==",
"'s3'",
"or",
"scheme",
"==",
"'s3n'",
":",
"conn",
"=",
"connection_with_anon",
"(",
"credentials",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
"bucket_name",
")",
"elif",
"scheme",
"==",
"'gs'",
":",
"conn",
"=",
"connection_with_gs",
"(",
"bucket_name",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"No file reader implementation for URL scheme \"",
"+",
"scheme",
")",
"def",
"getsplit",
"(",
"kv",
")",
":",
"idx",
",",
"keyName",
"=",
"kv",
"key",
"=",
"bucket",
".",
"get_key",
"(",
"keyName",
")",
"buf",
"=",
"key",
".",
"get_contents_as_string",
"(",
")",
"return",
"idx",
",",
"buf",
",",
"keyName",
"return",
"[",
"getsplit",
"(",
"kv",
")",
"for",
"kv",
"in",
"enumerate",
"(",
"keylist",
")",
"]"
] |
Create a packet autenticator . All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm . This function returns a suitable random string that can be used as an authenticator . | def CreateAuthenticator ( ) : data = [ ] for i in range ( 16 ) : data . append ( random_generator . randrange ( 0 , 256 ) ) if six . PY3 : return bytes ( data ) else : return '' . join ( chr ( b ) for b in data ) | 10,895 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L208-L224 | [
"def",
"_record_offset",
"(",
"self",
")",
":",
"offset",
"=",
"self",
".",
"blob_file",
".",
"tell",
"(",
")",
"self",
".",
"event_offsets",
".",
"append",
"(",
"offset",
")"
] |
Initialize the object from raw packet data . Decode a packet as received from the network and decode it . | def DecodePacket ( self , packet ) : try : ( self . code , self . id , length , self . authenticator ) = struct . unpack ( '!BBH16s' , packet [ 0 : 20 ] ) except struct . error : raise PacketError ( 'Packet header is corrupt' ) if len ( packet ) != length : raise PacketError ( 'Packet has invalid length' ) if length > 8192 : raise PacketError ( 'Packet length is too long (%d)' % length ) self . clear ( ) packet = packet [ 20 : ] while packet : try : ( key , attrlen ) = struct . unpack ( '!BB' , packet [ 0 : 2 ] ) except struct . error : raise PacketError ( 'Attribute header is corrupt' ) if attrlen < 2 : raise PacketError ( 'Attribute length is too small (%d)' % attrlen ) value = packet [ 2 : attrlen ] if key == 26 : # 26 is the Vendor-Specific attribute ( vendor , subattrs ) = self . _PktDecodeVendorAttribute ( value ) if vendor is None : self . setdefault ( key , [ ] ) . append ( value ) else : for ( k , v ) in subattrs : self . setdefault ( ( vendor , k ) , [ ] ) . append ( v ) else : self . setdefault ( key , [ ] ) . append ( value ) packet = packet [ attrlen : ] | 10,896 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L308-L350 | [
"def",
"swap_leader",
"(",
"self",
",",
"new_leader",
")",
":",
"# Replica set cannot be changed",
"assert",
"(",
"new_leader",
"in",
"self",
".",
"_replicas",
")",
"curr_leader",
"=",
"self",
".",
"leader",
"idx",
"=",
"self",
".",
"_replicas",
".",
"index",
"(",
"new_leader",
")",
"self",
".",
"_replicas",
"[",
"0",
"]",
",",
"self",
".",
"_replicas",
"[",
"idx",
"]",
"=",
"self",
".",
"_replicas",
"[",
"idx",
"]",
",",
"self",
".",
"_replicas",
"[",
"0",
"]",
"return",
"curr_leader"
] |
Unobfuscate a RADIUS password . RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret . This function reverses the obfuscation process . | def PwDecrypt ( self , password ) : buf = password pw = six . b ( '' ) last = self . authenticator while buf : hash = md5_constructor ( self . secret + last ) . digest ( ) if six . PY3 : for i in range ( 16 ) : pw += bytes ( ( hash [ i ] ^ buf [ i ] , ) ) else : for i in range ( 16 ) : pw += chr ( ord ( hash [ i ] ) ^ ord ( buf [ i ] ) ) ( last , buf ) = ( buf [ : 16 ] , buf [ 16 : ] ) while pw . endswith ( six . b ( '\x00' ) ) : pw = pw [ : - 1 ] return pw . decode ( 'utf-8' ) | 10,897 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L404-L432 | [
"def",
"num_workers",
"(",
"self",
")",
":",
"size",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreGetGroupSize",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"size",
")",
")",
")",
"return",
"size",
".",
"value"
] |
Obfuscate password . RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret . If no authenticator has been set before calling PwCrypt one is created automatically . Changing the authenticator after setting a password that has been encrypted using this function will not work . | def PwCrypt ( self , password ) : if self . authenticator is None : self . authenticator = self . CreateAuthenticator ( ) if isinstance ( password , six . text_type ) : password = password . encode ( 'utf-8' ) buf = password if len ( password ) % 16 != 0 : buf += six . b ( '\x00' ) * ( 16 - ( len ( password ) % 16 ) ) hash = md5_constructor ( self . secret + self . authenticator ) . digest ( ) result = six . b ( '' ) last = self . authenticator while buf : hash = md5_constructor ( self . secret + last ) . digest ( ) if six . PY3 : for i in range ( 16 ) : result += bytes ( ( hash [ i ] ^ buf [ i ] , ) ) else : for i in range ( 16 ) : result += chr ( ord ( hash [ i ] ) ^ ord ( buf [ i ] ) ) last = result [ - 16 : ] buf = buf [ 16 : ] return result | 10,898 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L434-L474 | [
"def",
"_record_offset",
"(",
"self",
")",
":",
"offset",
"=",
"self",
".",
"blob_file",
".",
"tell",
"(",
")",
"self",
".",
"event_offsets",
".",
"append",
"(",
"offset",
")"
] |
Clears out this toolbar from the system . | def clear ( self ) : # preserve the collapse button super ( XToolBar , self ) . clear ( ) # clears out the toolbar if self . isCollapsable ( ) : self . _collapseButton = QToolButton ( self ) self . _collapseButton . setAutoRaise ( True ) self . _collapseButton . setSizePolicy ( QSizePolicy . Expanding , QSizePolicy . Expanding ) self . addWidget ( self . _collapseButton ) self . refreshButton ( ) # create connection self . _collapseButton . clicked . connect ( self . toggleCollapsed ) elif self . _collapseButton : self . _collapseButton . setParent ( None ) self . _collapseButton . deleteLater ( ) self . _collapseButton = None | 10,899 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbar.py#L64-L87 | [
"def",
"_extract_match",
"(",
"self",
",",
"candidate",
",",
"offset",
")",
":",
"# Skip a match that is more likely a publication page reference or a",
"# date.",
"if",
"(",
"_SLASH_SEPARATED_DATES",
".",
"search",
"(",
"candidate",
")",
")",
":",
"return",
"None",
"# Skip potential time-stamps.",
"if",
"_TIME_STAMPS",
".",
"search",
"(",
"candidate",
")",
":",
"following_text",
"=",
"self",
".",
"text",
"[",
"offset",
"+",
"len",
"(",
"candidate",
")",
":",
"]",
"if",
"_TIME_STAMPS_SUFFIX",
".",
"match",
"(",
"following_text",
")",
":",
"return",
"None",
"# Try to come up with a valid match given the entire candidate.",
"match",
"=",
"self",
".",
"_parse_and_verify",
"(",
"candidate",
",",
"offset",
")",
"if",
"match",
"is",
"not",
"None",
":",
"return",
"match",
"# If that failed, try to find an \"inner match\" -- there might be a",
"# phone number within this candidate.",
"return",
"self",
".",
"_extract_inner_match",
"(",
"candidate",
",",
"offset",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.