query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
listlengths 20
553
|
|---|---|---|---|---|
Encrypt a third - party caveat .
|
def encode_caveat ( condition , root_key , third_party_info , key , ns ) : if third_party_info . version == VERSION_1 : return _encode_caveat_v1 ( condition , root_key , third_party_info . public_key , key ) if ( third_party_info . version == VERSION_2 or third_party_info . version == VERSION_3 ) : return _encode_caveat_v2_v3 ( third_party_info . version , condition , root_key , third_party_info . public_key , key , ns ) raise NotImplementedError ( 'only bakery v1, v2, v3 supported' )
| 1,800
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L21-L46
|
[
"def",
"account_unblock",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/unblock'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"url",
")"
] |
Create a JSON - encoded third - party caveat .
|
def _encode_caveat_v1 ( condition , root_key , third_party_pub_key , key ) : plain_data = json . dumps ( { 'RootKey' : base64 . b64encode ( root_key ) . decode ( 'ascii' ) , 'Condition' : condition } ) box = nacl . public . Box ( key . key , third_party_pub_key . key ) encrypted = box . encrypt ( six . b ( plain_data ) ) nonce = encrypted [ 0 : nacl . public . Box . NONCE_SIZE ] encrypted = encrypted [ nacl . public . Box . NONCE_SIZE : ] return base64 . b64encode ( six . b ( json . dumps ( { 'ThirdPartyPublicKey' : str ( third_party_pub_key ) , 'FirstPartyPublicKey' : str ( key . public_key ) , 'Nonce' : base64 . b64encode ( nonce ) . decode ( 'ascii' ) , 'Id' : base64 . b64encode ( encrypted ) . decode ( 'ascii' ) } ) ) )
| 1,801
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L49-L76
|
[
"def",
"_action_remove",
"(",
"self",
",",
"ids",
")",
":",
"return",
"self",
".",
"_action_get",
"(",
"(",
"self",
".",
"unlisten_to_node",
"(",
"id_",
")",
"for",
"id_",
"in",
"ids",
")",
")"
] |
Create a version 2 or version 3 third - party caveat .
|
def _encode_caveat_v2_v3 ( version , condition , root_key , third_party_pub_key , key , ns ) : ns_data = bytearray ( ) if version >= VERSION_3 : ns_data = ns . serialize_text ( ) data = bytearray ( ) data . append ( version ) data . extend ( third_party_pub_key . serialize ( raw = True ) [ : _PUBLIC_KEY_PREFIX_LEN ] ) data . extend ( key . public_key . serialize ( raw = True ) [ : ] ) secret = _encode_secret_part_v2_v3 ( version , condition , root_key , ns_data ) box = nacl . public . Box ( key . key , third_party_pub_key . key ) encrypted = box . encrypt ( secret ) nonce = encrypted [ 0 : nacl . public . Box . NONCE_SIZE ] encrypted = encrypted [ nacl . public . Box . NONCE_SIZE : ] data . extend ( nonce [ : ] ) data . extend ( encrypted ) return bytes ( data )
| 1,802
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L79-L117
|
[
"def",
"_GetUncompressedStreamSize",
"(",
"self",
")",
":",
"self",
".",
"_file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"self",
".",
"_decompressor",
"=",
"self",
".",
"_GetDecompressor",
"(",
")",
"self",
".",
"_uncompressed_data",
"=",
"b''",
"compressed_data_offset",
"=",
"0",
"compressed_data_size",
"=",
"self",
".",
"_file_object",
".",
"get_size",
"(",
")",
"uncompressed_stream_size",
"=",
"0",
"while",
"compressed_data_offset",
"<",
"compressed_data_size",
":",
"read_count",
"=",
"self",
".",
"_ReadCompressedData",
"(",
"self",
".",
"_COMPRESSED_DATA_BUFFER_SIZE",
")",
"if",
"read_count",
"==",
"0",
":",
"break",
"compressed_data_offset",
"+=",
"read_count",
"uncompressed_stream_size",
"+=",
"self",
".",
"_uncompressed_data_size",
"return",
"uncompressed_stream_size"
] |
Creates a version 2 or version 3 secret part of the third party caveat . The returned data is not encrypted .
|
def _encode_secret_part_v2_v3 ( version , condition , root_key , ns ) : data = bytearray ( ) data . append ( version ) encode_uvarint ( len ( root_key ) , data ) data . extend ( root_key ) if version >= VERSION_3 : encode_uvarint ( len ( ns ) , data ) data . extend ( ns ) data . extend ( condition . encode ( 'utf-8' ) ) return bytes ( data )
| 1,803
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L120-L140
|
[
"def",
"setOverlayTexelAspect",
"(",
"self",
",",
"ulOverlayHandle",
",",
"fTexelAspect",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTexelAspect",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"fTexelAspect",
")",
"return",
"result"
] |
Decode caveat by decrypting the encrypted part using key .
|
def decode_caveat ( key , caveat ) : if len ( caveat ) == 0 : raise VerificationError ( 'empty third party caveat' ) first = caveat [ : 1 ] if first == b'e' : # 'e' will be the first byte if the caveatid is a base64 # encoded JSON object. return _decode_caveat_v1 ( key , caveat ) first_as_int = six . byte2int ( first ) if ( first_as_int == VERSION_2 or first_as_int == VERSION_3 ) : if ( len ( caveat ) < _VERSION3_CAVEAT_MIN_LEN and first_as_int == VERSION_3 ) : # If it has the version 3 caveat tag and it's too short, it's # almost certainly an id, not an encrypted payload. raise VerificationError ( 'caveat id payload not provided for caveat id {}' . format ( caveat ) ) return _decode_caveat_v2_v3 ( first_as_int , key , caveat ) raise VerificationError ( 'unknown version for caveat' )
| 1,804
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L143-L169
|
[
"def",
"_validate_residue_types",
"(",
"self",
")",
":",
"for",
"chain_id",
",",
"sequence_map",
"in",
"self",
".",
"rosetta_to_atom_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"rosetta_sequence",
"=",
"self",
".",
"rosetta_sequences",
"[",
"chain_id",
"]",
"atom_sequence",
"=",
"self",
".",
"atom_sequences",
"[",
"chain_id",
"]",
"for",
"rosetta_id",
",",
"atom_id",
",",
"_",
"in",
"sequence_map",
":",
"assert",
"(",
"rosetta_sequence",
"[",
"rosetta_id",
"]",
".",
"ResidueAA",
"==",
"atom_sequence",
"[",
"atom_id",
"]",
".",
"ResidueAA",
")",
"for",
"chain_id",
",",
"sequence_map",
"in",
"self",
".",
"atom_to_seqres_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"atom_sequence",
"=",
"self",
".",
"atom_sequences",
"[",
"chain_id",
"]",
"seqres_sequence",
"=",
"self",
".",
"seqres_sequences",
"[",
"chain_id",
"]",
"for",
"atom_id",
",",
"seqres_id",
",",
"_",
"in",
"sorted",
"(",
"sequence_map",
")",
":",
"assert",
"(",
"atom_sequence",
"[",
"atom_id",
"]",
".",
"ResidueAA",
"==",
"seqres_sequence",
"[",
"seqres_id",
"]",
".",
"ResidueAA",
")",
"for",
"chain_id",
",",
"sequence_map",
"in",
"self",
".",
"seqres_to_uniparc_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"if",
"self",
".",
"pdb_chain_to_uniparc_chain_mapping",
".",
"get",
"(",
"chain_id",
")",
":",
"seqres_sequence",
"=",
"self",
".",
"seqres_sequences",
"[",
"chain_id",
"]",
"uniparc_sequence",
"=",
"self",
".",
"uniparc_sequences",
"[",
"self",
".",
"pdb_chain_to_uniparc_chain_mapping",
"[",
"chain_id",
"]",
"]",
"for",
"seqres_id",
",",
"uniparc_id_resid_pair",
",",
"substitution_match",
"in",
"sequence_map",
":",
"uniparc_id",
"=",
"uniparc_id_resid_pair",
"[",
"1",
"]",
"# Some of the matches may not be identical but all the '*' Clustal Omega matches should be identical",
"if",
"substitution_match",
"and",
"substitution_match",
".",
"clustal",
"==",
"1",
":",
"assert",
"(",
"seqres_sequence",
"[",
"seqres_id",
"]",
".",
"ResidueAA",
"==",
"uniparc_sequence",
"[",
"uniparc_id",
"]",
".",
"ResidueAA",
")"
] |
Decode a base64 encoded JSON id .
|
def _decode_caveat_v1 ( key , caveat ) : data = base64 . b64decode ( caveat ) . decode ( 'utf-8' ) wrapper = json . loads ( data ) tp_public_key = nacl . public . PublicKey ( base64 . b64decode ( wrapper [ 'ThirdPartyPublicKey' ] ) ) if key . public_key . key != tp_public_key : raise Exception ( 'public key mismatch' ) # TODO if wrapper . get ( 'FirstPartyPublicKey' , None ) is None : raise Exception ( 'target service public key not specified' ) # The encrypted string is base64 encoded in the JSON representation. secret = base64 . b64decode ( wrapper . get ( 'Id' ) ) nonce = base64 . b64decode ( wrapper . get ( 'Nonce' ) ) fp_public_key = nacl . public . PublicKey ( base64 . b64decode ( wrapper . get ( 'FirstPartyPublicKey' ) ) ) box = nacl . public . Box ( key . key , fp_public_key ) c = box . decrypt ( secret , nonce ) record = json . loads ( c . decode ( 'utf-8' ) ) fp_key = nacl . public . PublicKey ( base64 . b64decode ( wrapper . get ( 'FirstPartyPublicKey' ) ) ) return ThirdPartyCaveatInfo ( condition = record . get ( 'Condition' ) , first_party_public_key = PublicKey ( fp_key ) , third_party_key_pair = key , root_key = base64 . b64decode ( record . get ( 'RootKey' ) ) , caveat = caveat , id = None , version = VERSION_1 , namespace = legacy_namespace ( ) )
| 1,805
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L172-L210
|
[
"def",
"getMetastable",
"(",
"rates",
",",
"ver",
":",
"np",
".",
"ndarray",
",",
"lamb",
",",
"br",
",",
"reactfn",
":",
"Path",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"reactfn",
",",
"'r'",
")",
"as",
"f",
":",
"A",
"=",
"f",
"[",
"'/metastable/A'",
"]",
"[",
":",
"]",
"lambnew",
"=",
"f",
"[",
"'/metastable/lambda'",
"]",
".",
"value",
".",
"ravel",
"(",
"order",
"=",
"'F'",
")",
"# some are not 1-D!",
"vnew",
"=",
"np",
".",
"concatenate",
"(",
"(",
"A",
"[",
":",
"2",
"]",
"*",
"rates",
".",
"loc",
"[",
"...",
",",
"'no1s'",
"]",
".",
"values",
"[",
":",
",",
"None",
"]",
",",
"A",
"[",
"2",
":",
"4",
"]",
"*",
"rates",
".",
"loc",
"[",
"...",
",",
"'no1d'",
"]",
".",
"values",
"[",
":",
",",
"None",
"]",
",",
"A",
"[",
"4",
":",
"]",
"*",
"rates",
".",
"loc",
"[",
"...",
",",
"'noii2p'",
"]",
".",
"values",
"[",
":",
",",
"None",
"]",
")",
",",
"axis",
"=",
"-",
"1",
")",
"assert",
"vnew",
".",
"shape",
"==",
"(",
"rates",
".",
"shape",
"[",
"0",
"]",
",",
"A",
".",
"size",
")",
"return",
"catvl",
"(",
"rates",
".",
"alt_km",
",",
"ver",
",",
"vnew",
",",
"lamb",
",",
"lambnew",
",",
"br",
")"
] |
Decodes a version 2 or version 3 caveat .
|
def _decode_caveat_v2_v3 ( version , key , caveat ) : if ( len ( caveat ) < 1 + _PUBLIC_KEY_PREFIX_LEN + _KEY_LEN + nacl . public . Box . NONCE_SIZE + 16 ) : raise VerificationError ( 'caveat id too short' ) original_caveat = caveat caveat = caveat [ 1 : ] # skip version (already checked) pk_prefix = caveat [ : _PUBLIC_KEY_PREFIX_LEN ] caveat = caveat [ _PUBLIC_KEY_PREFIX_LEN : ] if key . public_key . serialize ( raw = True ) [ : _PUBLIC_KEY_PREFIX_LEN ] != pk_prefix : raise VerificationError ( 'public key mismatch' ) first_party_pub = caveat [ : _KEY_LEN ] caveat = caveat [ _KEY_LEN : ] nonce = caveat [ : nacl . public . Box . NONCE_SIZE ] caveat = caveat [ nacl . public . Box . NONCE_SIZE : ] fp_public_key = nacl . public . PublicKey ( first_party_pub ) box = nacl . public . Box ( key . key , fp_public_key ) data = box . decrypt ( caveat , nonce ) root_key , condition , ns = _decode_secret_part_v2_v3 ( version , data ) return ThirdPartyCaveatInfo ( condition = condition . decode ( 'utf-8' ) , first_party_public_key = PublicKey ( fp_public_key ) , third_party_key_pair = key , root_key = root_key , caveat = original_caveat , version = version , id = None , namespace = ns )
| 1,806
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L213-L244
|
[
"def",
"_SeparateTypes",
"(",
"self",
",",
"metadata_value_pairs",
")",
":",
"registry_pairs",
"=",
"[",
"]",
"file_pairs",
"=",
"[",
"]",
"match_pairs",
"=",
"[",
"]",
"for",
"metadata",
",",
"result",
"in",
"metadata_value_pairs",
":",
"if",
"(",
"result",
".",
"stat_entry",
".",
"pathspec",
".",
"pathtype",
"==",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"REGISTRY",
")",
":",
"registry_pairs",
".",
"append",
"(",
"(",
"metadata",
",",
"result",
".",
"stat_entry",
")",
")",
"else",
":",
"file_pairs",
".",
"append",
"(",
"(",
"metadata",
",",
"result",
")",
")",
"match_pairs",
".",
"extend",
"(",
"[",
"(",
"metadata",
",",
"match",
")",
"for",
"match",
"in",
"result",
".",
"matches",
"]",
")",
"return",
"registry_pairs",
",",
"file_pairs",
",",
"match_pairs"
] |
encodes integer into variable - length format into data .
|
def encode_uvarint ( n , data ) : if n < 0 : raise ValueError ( 'only support positive integer' ) while True : this_byte = n & 127 n >>= 7 if n == 0 : data . append ( this_byte ) break data . append ( this_byte | 128 )
| 1,807
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L271-L281
|
[
"def",
"merge",
"(",
"self",
",",
"options",
")",
":",
"if",
"not",
"options",
":",
"return",
"_CallSettings",
"(",
"timeout",
"=",
"self",
".",
"timeout",
",",
"retry",
"=",
"self",
".",
"retry",
",",
"page_descriptor",
"=",
"self",
".",
"page_descriptor",
",",
"page_token",
"=",
"self",
".",
"page_token",
",",
"bundler",
"=",
"self",
".",
"bundler",
",",
"bundle_descriptor",
"=",
"self",
".",
"bundle_descriptor",
",",
"kwargs",
"=",
"self",
".",
"kwargs",
")",
"else",
":",
"if",
"options",
".",
"timeout",
"==",
"OPTION_INHERIT",
":",
"timeout",
"=",
"self",
".",
"timeout",
"else",
":",
"timeout",
"=",
"options",
".",
"timeout",
"if",
"options",
".",
"retry",
"==",
"OPTION_INHERIT",
":",
"retry",
"=",
"self",
".",
"retry",
"else",
":",
"retry",
"=",
"options",
".",
"retry",
"if",
"options",
".",
"page_token",
"==",
"OPTION_INHERIT",
":",
"page_token",
"=",
"self",
".",
"page_token",
"else",
":",
"page_token",
"=",
"options",
".",
"page_token",
"if",
"options",
".",
"is_bundling",
":",
"bundler",
"=",
"self",
".",
"bundler",
"else",
":",
"bundler",
"=",
"None",
"if",
"options",
".",
"kwargs",
"==",
"OPTION_INHERIT",
":",
"kwargs",
"=",
"self",
".",
"kwargs",
"else",
":",
"kwargs",
"=",
"self",
".",
"kwargs",
".",
"copy",
"(",
")",
"kwargs",
".",
"update",
"(",
"options",
".",
"kwargs",
")",
"return",
"_CallSettings",
"(",
"timeout",
"=",
"timeout",
",",
"retry",
"=",
"retry",
",",
"page_descriptor",
"=",
"self",
".",
"page_descriptor",
",",
"page_token",
"=",
"page_token",
",",
"bundler",
"=",
"bundler",
",",
"bundle_descriptor",
"=",
"self",
".",
"bundle_descriptor",
",",
"kwargs",
"=",
"kwargs",
")"
] |
Decode a variable - length integer .
|
def decode_uvarint ( data ) : n = 0 shift = 0 length = 0 for b in data : if not isinstance ( b , int ) : b = six . byte2int ( b ) n |= ( b & 0x7f ) << shift length += 1 if ( b & 0x80 ) == 0 : break shift += 7 return n , length
| 1,808
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L284-L301
|
[
"def",
"paga_expression_entropies",
"(",
"adata",
")",
"->",
"List",
"[",
"float",
"]",
":",
"from",
"scipy",
".",
"stats",
"import",
"entropy",
"groups_order",
",",
"groups_masks",
"=",
"utils",
".",
"select_groups",
"(",
"adata",
",",
"key",
"=",
"adata",
".",
"uns",
"[",
"'paga'",
"]",
"[",
"'groups'",
"]",
")",
"entropies",
"=",
"[",
"]",
"for",
"mask",
"in",
"groups_masks",
":",
"X_mask",
"=",
"adata",
".",
"X",
"[",
"mask",
"]",
".",
"todense",
"(",
")",
"x_median",
"=",
"np",
".",
"nanmedian",
"(",
"X_mask",
",",
"axis",
"=",
"1",
",",
"overwrite_input",
"=",
"True",
")",
"x_probs",
"=",
"(",
"x_median",
"-",
"np",
".",
"nanmin",
"(",
"x_median",
")",
")",
"/",
"(",
"np",
".",
"nanmax",
"(",
"x_median",
")",
"-",
"np",
".",
"nanmin",
"(",
"x_median",
")",
")",
"entropies",
".",
"append",
"(",
"entropy",
"(",
"x_probs",
")",
")",
"return",
"entropies"
] |
Creates a type converter for an enumeration or text - to - value mapping .
|
def make_enum ( enum_mappings ) : if ( inspect . isclass ( enum_mappings ) and issubclass ( enum_mappings , enum . Enum ) ) : enum_class = enum_mappings enum_mappings = enum_class . __members__ def convert_enum ( text ) : if text not in convert_enum . mappings : text = text . lower ( ) # REQUIRED-BY: parse re.IGNORECASE return convert_enum . mappings [ text ] #< text.lower() ??? convert_enum . pattern = r"|" . join ( enum_mappings . keys ( ) ) convert_enum . mappings = enum_mappings return convert_enum
| 1,809
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/builder.py#L98-L116
|
[
"def",
"private_messenger",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"WebSocketHandler",
".",
"send_private_message",
"(",
"user_id",
"=",
"message",
"[",
"'user_id'",
"]",
",",
"message",
"=",
"message",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Creates a type converter for a number of type converter alternatives . The first matching type converter is used .
|
def make_variant ( cls , converters , re_opts = None , compiled = False , strict = True ) : # -- NOTE: Uses double-dispatch with regex pattern rematch because # match is not passed through to primary type converter. assert converters , "REQUIRE: Non-empty list." if len ( converters ) == 1 : return converters [ 0 ] if re_opts is None : re_opts = cls . default_re_opts pattern = r")|(" . join ( [ tc . pattern for tc in converters ] ) pattern = r"(" + pattern + ")" group_count = len ( converters ) for converter in converters : group_count += pattern_group_count ( converter . pattern ) if compiled : convert_variant = cls . __create_convert_variant_compiled ( converters , re_opts , strict ) else : convert_variant = cls . __create_convert_variant ( re_opts , strict ) convert_variant . pattern = pattern convert_variant . converters = tuple ( converters ) # OLD: convert_variant.group_count = group_count convert_variant . regex_group_count = group_count return convert_variant
| 1,810
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/builder.py#L183-L227
|
[
"def",
"get_event_loop",
"(",
")",
":",
"ev",
"=",
"_state",
".",
"event_loop",
"if",
"not",
"os",
".",
"getenv",
"(",
"_EVENT_LOOP_KEY",
")",
"and",
"ev",
"is",
"not",
"None",
":",
"ev",
".",
"clear",
"(",
")",
"_state",
".",
"event_loop",
"=",
"None",
"ev",
"=",
"None",
"if",
"ev",
"is",
"None",
":",
"ev",
"=",
"EventLoop",
"(",
")",
"_state",
".",
"event_loop",
"=",
"ev",
"os",
".",
"environ",
"[",
"_EVENT_LOOP_KEY",
"]",
"=",
"'1'",
"return",
"ev"
] |
Checks if a string represents a valid quantities unit .
|
def isValidUnit ( self , w ) : bad = set ( [ 'point' , 'a' ] ) if w in bad : return False try : pq . Quantity ( 0.0 , w ) return True except : return w == '/'
| 1,811
|
https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/units.py#L73-L92
|
[
"def",
"handle_not_found",
"(",
"exception",
",",
"*",
"*",
"extra",
")",
":",
"assert",
"isinstance",
"(",
"exception",
",",
"NotFound",
")",
"page",
"=",
"Page",
".",
"query",
".",
"filter",
"(",
"db",
".",
"or_",
"(",
"Page",
".",
"url",
"==",
"request",
".",
"path",
",",
"Page",
".",
"url",
"==",
"request",
".",
"path",
"+",
"\"/\"",
")",
")",
".",
"first",
"(",
")",
"if",
"page",
":",
"_add_url_rule",
"(",
"page",
".",
"url",
")",
"return",
"render_template",
"(",
"[",
"page",
".",
"template_name",
",",
"current_app",
".",
"config",
"[",
"'PAGES_DEFAULT_TEMPLATE'",
"]",
"]",
",",
"page",
"=",
"page",
")",
"elif",
"'wrapped'",
"in",
"extra",
":",
"return",
"extra",
"[",
"'wrapped'",
"]",
"(",
"exception",
")",
"else",
":",
"return",
"exception"
] |
Collects all the valid units from an inp string . Works by appending consecutive words from the string and cross - referncing them with a set of valid units .
|
def extractUnits ( self , inp ) : inp = self . _preprocess ( inp ) units = [ ] description = "" for w in inp . split ( ' ' ) : if self . isValidUnit ( w ) or w == '/' : if description : description += " " description += w else : if description : units . append ( description ) description = "" if description : units . append ( description ) return units
| 1,812
|
https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/units.py#L94-L123
|
[
"def",
"_GetLoadConfigTimestamp",
"(",
"self",
",",
"pefile_object",
")",
":",
"if",
"not",
"hasattr",
"(",
"pefile_object",
",",
"'DIRECTORY_ENTRY_LOAD_CONFIG'",
")",
":",
"return",
"None",
"timestamp",
"=",
"getattr",
"(",
"pefile_object",
".",
"DIRECTORY_ENTRY_LOAD_CONFIG",
".",
"struct",
",",
"'TimeDateStamp'",
",",
"0",
")",
"return",
"timestamp"
] |
Converts a string representation of some quantity of units into a quantities object .
|
def convert ( self , inp ) : inp = self . _preprocess ( inp ) n = NumberService ( ) . longestNumber ( inp ) units = self . extractUnits ( inp ) # Convert to quantity object, attempt conversion quantity = pq . Quantity ( float ( n ) , units [ 0 ] ) quantity . units = units [ 1 ] return quantity
| 1,813
|
https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/units.py#L125-L146
|
[
"def",
"gc_velocity_update",
"(",
"particle",
",",
"social",
",",
"state",
")",
":",
"gbest",
"=",
"state",
".",
"swarm",
"[",
"gbest_idx",
"(",
"state",
".",
"swarm",
")",
"]",
".",
"position",
"if",
"not",
"np",
".",
"array_equal",
"(",
"gbest",
",",
"particle",
".",
"position",
")",
":",
"return",
"std_velocity",
"(",
"particle",
",",
"social",
",",
"state",
")",
"rho",
"=",
"state",
".",
"params",
"[",
"'rho'",
"]",
"inertia",
"=",
"state",
".",
"params",
"[",
"'inertia'",
"]",
"v_max",
"=",
"state",
".",
"params",
"[",
"'v_max'",
"]",
"size",
"=",
"particle",
".",
"position",
".",
"size",
"r2",
"=",
"state",
".",
"rng",
".",
"uniform",
"(",
"0.0",
",",
"1.0",
",",
"size",
")",
"velocity",
"=",
"__gc_velocity_equation__",
"(",
"inertia",
",",
"rho",
",",
"r2",
",",
"particle",
",",
"gbest",
")",
"return",
"__clamp__",
"(",
"velocity",
",",
"v_max",
")"
] |
Allow access to any ACL members that was equal to the user name .
|
def allow ( self , ctx , acls ) : for acl in acls : if self . _identity == acl : return True return False
| 1,814
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_identity.py#L68-L76
|
[
"def",
"retrieve_diaspora_hcard",
"(",
"handle",
")",
":",
"webfinger",
"=",
"retrieve_and_parse_diaspora_webfinger",
"(",
"handle",
")",
"document",
",",
"code",
",",
"exception",
"=",
"fetch_document",
"(",
"webfinger",
".",
"get",
"(",
"\"hcard_url\"",
")",
")",
"if",
"exception",
":",
"return",
"None",
"return",
"document"
] |
Return an unique list of resources or collections from a list of paths . Supports fq_name and wilcards resolution .
|
def expand_paths ( paths = None , predicate = None , filters = None , parent_uuid = None ) : if not paths : paths = [ Context ( ) . shell . current_path ] else : paths = [ Context ( ) . shell . current_path / res for res in paths ] # use a dict to have unique paths # but keep them ordered result = OrderedDict ( ) for res in parallel_map ( _path_to_resources , paths , kwargs = { 'predicate' : predicate , 'filters' : filters , 'parent_uuid' : parent_uuid } , workers = 50 ) : for r in res : result [ r . path ] = r resources = list ( result . values ( ) ) if not resources : raise NotFound ( ) return resources
| 1,815
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/command.py#L136-L174
|
[
"def",
"_initialize_connection",
"(",
"api_key",
",",
"app_key",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'api_key must be specified'",
")",
"if",
"app_key",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'app_key must be specified'",
")",
"options",
"=",
"{",
"'api_key'",
":",
"api_key",
",",
"'app_key'",
":",
"app_key",
"}",
"datadog",
".",
"initialize",
"(",
"*",
"*",
"options",
")"
] |
Renders a Jinja2 template to text .
|
def render ( self , template , filename , context = { } , filters = { } ) : filename = os . path . normpath ( filename ) path , file = os . path . split ( filename ) try : os . makedirs ( path ) except OSError as exception : if exception . errno != errno . EEXIST : raise path , file = os . path . split ( template ) loader = jinja2 . FileSystemLoader ( path ) env = jinja2 . Environment ( loader = loader , trim_blocks = True , lstrip_blocks = True ) env . filters . update ( filters ) template = env . get_template ( file ) text = template . render ( context ) with open ( filename , 'wt' ) as f : f . write ( text )
| 1,816
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/writer.py#L19-L38
|
[
"def",
"log_normalize",
"(",
"a",
",",
"axis",
"=",
"None",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"under",
"=",
"\"ignore\"",
")",
":",
"a_lse",
"=",
"logsumexp",
"(",
"a",
",",
"axis",
")",
"a",
"-=",
"a_lse",
"[",
":",
",",
"np",
".",
"newaxis",
"]"
] |
Utility method to spawn a VSGWriter for each element in a collection .
|
def write ( pylist , parallel = True ) : threads = [ VSGWriter ( o ) for o in pylist ] if parallel : for t in threads : t . start ( ) for t in threads : t . join ( ) else : for t in threads : t . run ( )
| 1,817
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/writer.py#L156-L171
|
[
"def",
"parse_human_timedelta",
"(",
"s",
":",
"str",
")",
":",
"cal",
"=",
"parsedatetime",
".",
"Calendar",
"(",
")",
"dttm",
"=",
"dttm_from_timtuple",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"timetuple",
"(",
")",
")",
"d",
"=",
"cal",
".",
"parse",
"(",
"s",
"or",
"''",
",",
"dttm",
")",
"[",
"0",
"]",
"d",
"=",
"datetime",
"(",
"d",
".",
"tm_year",
",",
"d",
".",
"tm_mon",
",",
"d",
".",
"tm_mday",
",",
"d",
".",
"tm_hour",
",",
"d",
".",
"tm_min",
",",
"d",
".",
"tm_sec",
")",
"return",
"d",
"-",
"dttm"
] |
Implement Interactor . interact by opening the browser window and waiting for the discharge token
|
def interact ( self , ctx , location , ir_err ) : p = ir_err . interaction_method ( self . kind ( ) , WebBrowserInteractionInfo ) if not location . endswith ( '/' ) : location += '/' visit_url = urljoin ( location , p . visit_url ) wait_token_url = urljoin ( location , p . wait_token_url ) self . _open_web_browser ( visit_url ) return self . _wait_for_token ( ctx , wait_token_url )
| 1,818
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_browser.py#L38-L47
|
[
"def",
"_writeImage",
"(",
"dataArray",
"=",
"None",
",",
"inputHeader",
"=",
"None",
")",
":",
"prihdu",
"=",
"fits",
".",
"PrimaryHDU",
"(",
"data",
"=",
"dataArray",
",",
"header",
"=",
"inputHeader",
")",
"pf",
"=",
"fits",
".",
"HDUList",
"(",
")",
"pf",
".",
"append",
"(",
"prihdu",
")",
"return",
"pf"
] |
Returns a token from a the wait token URL
|
def _wait_for_token ( self , ctx , wait_token_url ) : resp = requests . get ( wait_token_url ) if resp . status_code != 200 : raise InteractionError ( 'cannot get {}' . format ( wait_token_url ) ) json_resp = resp . json ( ) kind = json_resp . get ( 'kind' ) if kind is None : raise InteractionError ( 'cannot get kind token from {}' . format ( wait_token_url ) ) token_val = json_resp . get ( 'token' ) if token_val is None : token_val = json_resp . get ( 'token64' ) if token_val is None : raise InteractionError ( 'cannot get token from {}' . format ( wait_token_url ) ) token_val = base64 . b64decode ( token_val ) return DischargeToken ( kind = kind , value = token_val )
| 1,819
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_browser.py#L49-L69
|
[
"def",
"_enforceDataType",
"(",
"self",
",",
"data",
")",
":",
"value",
"=",
"float",
"(",
"data",
")",
"if",
"math",
".",
"isnan",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"\"FloatCti can't store NaNs\"",
")",
"if",
"math",
".",
"isinf",
"(",
"value",
")",
":",
"if",
"value",
">",
"0",
":",
"logger",
".",
"warn",
"(",
"\"Replacing inf by the largest representable float\"",
")",
"value",
"=",
"sys",
".",
"float_info",
".",
"max",
"else",
":",
"logger",
".",
"warn",
"(",
"\"Replacing -inf by the smallest representable float\"",
")",
"value",
"=",
"-",
"sys",
".",
"float_info",
".",
"max",
"return",
"value"
] |
Create a new instance of WebBrowserInteractionInfo as expected by the Error . interaction_method method .
|
def from_dict ( cls , info_dict ) : return WebBrowserInteractionInfo ( visit_url = info_dict . get ( 'VisitURL' ) , wait_token_url = info_dict . get ( 'WaitTokenURL' ) )
| 1,820
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_browser.py#L82-L90
|
[
"def",
"_set_categories",
"(",
"self",
")",
":",
"for",
"column",
",",
"_",
"in",
"self",
".",
"_categories",
".",
"items",
"(",
")",
":",
"if",
"column",
"in",
"self",
".",
"columns",
":",
"self",
"[",
"column",
"]",
"=",
"self",
"[",
"column",
"]",
".",
"astype",
"(",
"'category'",
")"
] |
Sets a new value for a given configuration parameter .
|
def set ( self , name , value , overwrite = False ) : if hasattr ( self , name ) : if overwrite : setattr ( self , name , value ) else : self . _log . warning ( "Configuration parameter %s exists and overwrite not allowed" % name ) raise Exception ( "Configuration parameter %s exists and overwrite not allowed" % name ) else : setattr ( self , name , value ) return getattr ( self , name )
| 1,821
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/configuration/config.py#L30-L50
|
[
"def",
"removeAllEntitlements",
"(",
"self",
",",
"appId",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appId\"",
":",
"appId",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/licenses/removeAllEntitlements\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Creates missing types for fields with a CardinalityField part . It is assumed that the primary type converter for cardinality = 1 is registered in the type dictionary .
|
def create_missing_types ( cls , schema , type_dict , type_builder = None ) : if not type_builder : type_builder = cls . type_builder missing = cls . extract_missing_special_type_names ( schema , type_dict ) return type_builder . create_type_variants ( missing , type_dict )
| 1,822
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cfparse.py#L56-L72
|
[
"def",
"stop_watching",
"(",
"self",
")",
":",
"self",
".",
"_watch",
"=",
"False",
"if",
"self",
".",
"_observer",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Stopping watcher'",
")",
"self",
".",
"_observer",
".",
"stop",
"(",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Watcher stopped'",
")"
] |
Extract the type names for fields with CardinalityField part . Selects only the missing type names that are not in the type dictionary .
|
def extract_missing_special_type_names ( schema , type_dict ) : for name in FieldParser . extract_types ( schema ) : if CardinalityField . matches_type ( name ) and ( name not in type_dict ) : yield name
| 1,823
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cfparse.py#L75-L85
|
[
"def",
"set_environment",
"(",
"environment",
",",
"system",
"=",
"False",
")",
":",
"config_filename",
"=",
"_SYSTEM_CONFIG_FILE",
"if",
"system",
"is",
"True",
"else",
"_USER_CONFIG_FILE",
"config",
"=",
"_read_config",
"(",
"config_filename",
")",
"section",
"=",
"_ENVIRONMENT_SECTION_NAME",
"for",
"key",
"in",
"environment",
".",
"keys",
"(",
")",
":",
"config",
".",
"set",
"(",
"section",
",",
"key",
",",
"environment",
"[",
"key",
"]",
")",
"_write_config",
"(",
"config",
",",
"config_filename",
")"
] |
Checks an allow or a deny caveat . The need_ops parameter specifies whether we require all the operations in the caveat to be declared in the context .
|
def _check_operations ( ctx , need_ops , arg ) : ctx_ops = ctx . get ( OP_KEY , [ ] ) if len ( ctx_ops ) == 0 : if need_ops : f = arg . split ( ) if len ( f ) == 0 : return 'no operations allowed' return '{} not allowed' . format ( f [ 0 ] ) return None fields = arg . split ( ) for op in ctx_ops : err = _check_op ( op , need_ops , fields ) if err is not None : return err return None
| 1,824
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_checkers.py#L210-L229
|
[
"def",
"spin",
"(",
"self",
",",
"start_message",
",",
"end_message",
",",
"fmt",
"=",
"None",
",",
"interval",
"=",
"100",
",",
"values",
"=",
"None",
")",
":",
"spinner",
"=",
"ProgressIndicator",
"(",
"self",
".",
"io",
",",
"fmt",
",",
"interval",
",",
"values",
")",
"return",
"spinner",
".",
"auto",
"(",
"start_message",
",",
"end_message",
")"
] |
Returns information on all the registered checkers .
|
def info ( self ) : return sorted ( self . _checkers . values ( ) , key = lambda x : ( x . ns , x . name ) )
| 1,825
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_checkers.py#L90-L96
|
[
"def",
"Initialize",
"(",
"self",
")",
":",
"super",
"(",
"AFF4MemoryStreamBase",
",",
"self",
")",
".",
"Initialize",
"(",
")",
"contents",
"=",
"b\"\"",
"if",
"\"r\"",
"in",
"self",
".",
"mode",
":",
"contents",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"CONTENT",
")",
".",
"AsBytes",
"(",
")",
"try",
":",
"if",
"contents",
"is",
"not",
"None",
":",
"contents",
"=",
"zlib",
".",
"decompress",
"(",
"contents",
")",
"except",
"zlib",
".",
"error",
":",
"pass",
"self",
".",
"fd",
"=",
"io",
".",
"BytesIO",
"(",
"contents",
")",
"self",
".",
"size",
"=",
"len",
"(",
"contents",
")",
"self",
".",
"offset",
"=",
"0"
] |
Registers all the standard checkers in the given checker .
|
def register_std ( self ) : self . _namespace . register ( STD_NAMESPACE , '' ) for cond in _ALL_CHECKERS : self . register ( cond , STD_NAMESPACE , _ALL_CHECKERS [ cond ] )
| 1,826
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_checkers.py#L137-L145
|
[
"def",
"_extract_word",
"(",
"self",
",",
"source",
",",
"position",
")",
":",
"boundry",
"=",
"re",
".",
"search",
"(",
"'{{|{|\\s|$'",
",",
"source",
"[",
":",
"position",
"]",
"[",
":",
":",
"-",
"1",
"]",
")",
"start_offset",
"=",
"boundry",
".",
"end",
"(",
")",
"if",
"boundry",
".",
"group",
"(",
"0",
")",
".",
"startswith",
"(",
"'{'",
")",
"else",
"boundry",
".",
"start",
"(",
")",
"boundry",
"=",
"re",
".",
"search",
"(",
"'}}|}|\\s|$'",
",",
"source",
"[",
"position",
":",
"]",
")",
"end_offset",
"=",
"boundry",
".",
"end",
"(",
")",
"if",
"boundry",
".",
"group",
"(",
"0",
")",
".",
"startswith",
"(",
"'}'",
")",
"else",
"boundry",
".",
"start",
"(",
")",
"return",
"source",
"[",
"position",
"-",
"start_offset",
":",
"position",
"+",
"end_offset",
"]"
] |
Implements Authorizer . authorize by calling f with the given identity for each operation .
|
def authorize ( self , ctx , identity , ops ) : allowed = [ ] caveats = [ ] for op in ops : ok , fcaveats = self . _f ( ctx , identity , op ) allowed . append ( ok ) if fcaveats is not None : caveats . extend ( fcaveats ) return allowed , caveats
| 1,827
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_authorizer.py#L50-L61
|
[
"def",
"terminate_obsolete",
"(",
"self",
")",
":",
"chats_terminated",
"=",
"[",
"]",
"live_chats",
"=",
"Chat",
".",
"live",
".",
"all",
"(",
")",
"for",
"live_chat",
"in",
"live_chats",
":",
"if",
"live_chat",
".",
"is_obsolete",
"(",
"self",
".",
"time_obsolete_offset",
")",
":",
"live_chat",
".",
"terminate",
"(",
")",
"live_chat",
".",
"save",
"(",
")",
"chats_terminated",
".",
"append",
"(",
"live_chat",
")",
"return",
"chats_terminated"
] |
Implements Authorizer . authorize by calling identity . allow to determine whether the identity is a member of the ACLs associated with the given operations .
|
def authorize ( self , ctx , identity , ops ) : if len ( ops ) == 0 : # Anyone is allowed to do nothing. return [ ] , [ ] allowed = [ False ] * len ( ops ) has_allow = isinstance ( identity , ACLIdentity ) for i , op in enumerate ( ops ) : acl = self . _get_acl ( ctx , op ) if has_allow : allowed [ i ] = identity . allow ( ctx , acl ) else : allowed [ i ] = self . _allow_public and EVERYONE in acl return allowed , [ ]
| 1,828
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_authorizer.py#L83-L99
|
[
"def",
"_get_all_data",
"(",
"self",
",",
"start_date",
",",
"end_date",
")",
":",
"return",
"[",
"self",
".",
"_get_input_data",
"(",
"var",
",",
"start_date",
",",
"end_date",
")",
"for",
"var",
"in",
"_replace_pressure",
"(",
"self",
".",
"variables",
",",
"self",
".",
"dtype_in_vert",
")",
"]"
] |
Matches both the subject and action not necessarily the conditions .
|
def is_relevant ( self , action , subject ) : return self . matches_action ( action ) and self . matches_subject ( subject )
| 1,829
|
https://github.com/cocoakekeyu/cancan/blob/f198d560e6e008e6c5580ba55581a939a5d544ed/cancan/rule.py#L42-L46
|
[
"def",
"writeJsonZipfile",
"(",
"filelike",
",",
"data",
",",
"compress",
"=",
"True",
",",
"mode",
"=",
"'w'",
",",
"name",
"=",
"'data'",
")",
":",
"zipcomp",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
"if",
"compress",
"else",
"zipfile",
".",
"ZIP_STORED",
"with",
"zipfile",
".",
"ZipFile",
"(",
"filelike",
",",
"mode",
",",
"allowZip64",
"=",
"True",
")",
"as",
"containerFile",
":",
"containerFile",
".",
"writestr",
"(",
"name",
",",
"json",
".",
"dumps",
"(",
"data",
",",
"cls",
"=",
"MaspyJsonEncoder",
")",
",",
"zipcomp",
")"
] |
Check that a given HAL id is a valid one .
|
def is_valid ( hal_id ) : match = REGEX . match ( hal_id ) return ( match is not None ) and ( match . group ( 0 ) == hal_id )
| 1,830
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/hal.py#L16-L36
|
[
"def",
"write",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"__buffer",
"+=",
"bytes",
"(",
"b",
")",
"bytes_written",
"=",
"0",
"while",
"len",
"(",
"self",
".",
"__buffer",
")",
">=",
"self",
".",
"__cipher_block_size",
":",
"io",
".",
"BufferedWriter",
".",
"write",
"(",
"self",
",",
"self",
".",
"__cipher",
".",
"encrypt_block",
"(",
"self",
".",
"__buffer",
"[",
":",
"self",
".",
"__cipher_block_size",
"]",
")",
")",
"self",
".",
"__buffer",
"=",
"self",
".",
"__buffer",
"[",
"self",
".",
"__cipher_block_size",
":",
"]",
"bytes_written",
"+=",
"self",
".",
"__cipher_block_size",
"return",
"len",
"(",
"b",
")"
] |
Extract HAL ids from a text .
|
def extract_from_text ( text ) : return tools . remove_duplicates ( [ i [ 0 ] for i in REGEX . findall ( text ) if i != '' ] )
| 1,831
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/hal.py#L39-L50
|
[
"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",
")"
] |
Creates a VSG solution from a configparser instance .
|
def _getsolution ( self , config , section , * * kwargs ) : if section not in config : raise ValueError ( 'Section [{}] not found in [{}]' . format ( section , ', ' . join ( config . sections ( ) ) ) ) s = VSGSolution ( * * kwargs ) s . Name = config . get ( section , 'name' , fallback = s . Name ) s . FileName = os . path . normpath ( config . get ( section , 'filename' , fallback = s . FileName ) ) s . VSVersion = config . getfloat ( section , 'visual_studio_version' , fallback = s . VSVersion ) if not s . VSVersion : raise ValueError ( 'Solution section [%s] requires a value for Visual Studio Version (visual_studio_version)' % section ) project_sections = config . getlist ( section , 'projects' , fallback = [ ] ) for project_section in project_sections : project = self . _getproject ( config , project_section , VSVersion = s . VSVersion ) s . Projects . append ( project ) return s
| 1,832
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L43-L68
|
[
"def",
"numpy_to_weld_type",
"(",
"np_dtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"np_dtype",
",",
"(",
"str",
",",
"bytes",
",",
"np",
".",
"dtype",
",",
"type",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Can only convert np.dtype or str'",
")",
"if",
"isinstance",
"(",
"np_dtype",
",",
"(",
"str",
",",
"bytes",
",",
"type",
")",
")",
":",
"np_dtype",
"=",
"np",
".",
"dtype",
"(",
"np_dtype",
")",
"return",
"_numpy_to_weld_type_mapping",
"[",
"np_dtype",
".",
"char",
"]"
] |
Creates a VSG project from a configparser instance .
|
def _getproject ( self , config , section , * * kwargs ) : if section not in config : raise ValueError ( 'Section [{}] not found in [{}]' . format ( section , ', ' . join ( config . sections ( ) ) ) ) type = config . get ( section , 'type' , fallback = None ) if not type : raise ValueError ( 'Section [{}] mandatory option "{}" not found' . format ( section , "type" ) ) project_class = entrypoint ( 'vsgen.projects' , type ) return project_class . from_section ( config , section , * * kwargs )
| 1,833
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L70-L87
|
[
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_poolingActivation",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"self",
".",
"_numColumns",
")",
",",
"dtype",
"=",
"\"int32\"",
")",
"self",
".",
"_poolingColumns",
"=",
"[",
"]",
"self",
".",
"_overlapDutyCycles",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"_numColumns",
",",
"dtype",
"=",
"realDType",
")",
"self",
".",
"_activeDutyCycles",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"_numColumns",
",",
"dtype",
"=",
"realDType",
")",
"self",
".",
"_minOverlapDutyCycles",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"_numColumns",
",",
"dtype",
"=",
"realDType",
")",
"self",
".",
"_minActiveDutyCycles",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"_numColumns",
",",
"dtype",
"=",
"realDType",
")",
"self",
".",
"_boostFactors",
"=",
"numpy",
".",
"ones",
"(",
"self",
".",
"_numColumns",
",",
"dtype",
"=",
"realDType",
")"
] |
Generates one or more VSGSuite instances from command line arguments .
|
def from_args ( cls , * * kwargs ) : # Create a VSGSuite for each filename on the command line. if kwargs . get ( 'suite_commands' , None ) == 'generate' : filenames = kwargs . pop ( 'configuration_filenames' , [ ] ) return [ cls . from_file ( f ) for f in filenames ] # Create a VSGSuit from the target directory and override commands if kwargs . get ( 'suite_commands' , None ) == 'auto' : type = kwargs . get ( 'suite_type' , None ) return [ cls . from_directory ( '' , type , * * kwargs ) ] # Create nothing. return [ ]
| 1,834
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L137-L154
|
[
"def",
"subentity",
"(",
"self",
",",
"Entity",
",",
"index",
")",
":",
"dim",
"=",
"Entity",
".",
"__dimension__",
"entity",
"=",
"Entity",
".",
"empty",
"(",
")",
"if",
"index",
">=",
"self",
".",
"dimensions",
"[",
"dim",
"]",
":",
"raise",
"ValueError",
"(",
"'index {} out of bounds for dimension {} (size {})'",
".",
"format",
"(",
"index",
",",
"dim",
",",
"self",
".",
"dimensions",
"[",
"dim",
"]",
")",
")",
"for",
"name",
",",
"attr",
"in",
"self",
".",
"__attributes__",
".",
"items",
"(",
")",
":",
"if",
"attr",
".",
"dim",
"==",
"dim",
":",
"# If the dimension of the attributes is the same of the",
"# dimension of the entity, we generate a field",
"entity",
".",
"__fields__",
"[",
"name",
"]",
"=",
"attr",
".",
"field",
"(",
"index",
")",
"elif",
"attr",
".",
"dim",
"in",
"entity",
".",
"dimensions",
":",
"# Special case, we don't need to do anything",
"if",
"self",
".",
"dimensions",
"[",
"attr",
".",
"dim",
"]",
"==",
"0",
":",
"continue",
"# Else, we generate a subattribute",
"mapped_index",
"=",
"self",
".",
"maps",
"[",
"attr",
".",
"dim",
",",
"dim",
"]",
".",
"value",
"==",
"index",
"entity",
".",
"__attributes__",
"[",
"name",
"]",
"=",
"attr",
".",
"sub",
"(",
"mapped_index",
")",
"entity",
".",
"dimensions",
"[",
"attr",
".",
"dim",
"]",
"=",
"np",
".",
"count_nonzero",
"(",
"mapped_index",
")",
"for",
"name",
",",
"rel",
"in",
"self",
".",
"__relations__",
".",
"items",
"(",
")",
":",
"if",
"rel",
".",
"map",
"==",
"dim",
":",
"# The relation is between entities we need to return",
"# which means the entity doesn't know about that",
"pass",
"if",
"rel",
".",
"map",
"in",
"entity",
".",
"dimensions",
":",
"# Special case, we don't need to do anything",
"if",
"self",
".",
"dimensions",
"[",
"rel",
".",
"dim",
"]",
"==",
"0",
":",
"continue",
"mapped_index",
"=",
"self",
".",
"maps",
"[",
"rel",
".",
"dim",
",",
"dim",
"]",
".",
"value",
"==",
"index",
"entity",
".",
"__relations__",
"[",
"name",
"]",
"=",
"rel",
".",
"sub",
"(",
"mapped_index",
")",
"entity",
".",
"dimensions",
"[",
"rel",
".",
"dim",
"]",
"=",
"np",
".",
"count_nonzero",
"(",
"mapped_index",
")",
"# We need to remap values",
"convert_index",
"=",
"self",
".",
"maps",
"[",
"rel",
".",
"map",
",",
"dim",
"]",
".",
"value",
"==",
"index",
"entity",
".",
"__relations__",
"[",
"name",
"]",
".",
"remap",
"(",
"convert_index",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
",",
"range",
"(",
"entity",
".",
"dimensions",
"[",
"rel",
".",
"map",
"]",
")",
")",
"return",
"entity"
] |
Writes the configuration to disk .
|
def write ( self , parallel = True ) : # Write the Solution files solutions = sorted ( self . _solutions , key = lambda x : x . Name ) with VSGWriteCommand ( 'Writing VSG Solution' , solutions , parallel ) as command : command . execute ( ) # Write the Projects files projects = set ( sorted ( ( p for s in solutions for p in s . Projects ) , key = lambda x : x . Name ) ) with VSGWriteCommand ( 'Writing VSG Projects' , projects , parallel ) as command : command . execute ( ) # Register the registerables registerables = set ( sorted ( ( p for s in solutions for p in s . Projects ) , key = lambda x : x . Name ) ) with VSGRegisterCommand ( 'Registering Project Registerables' , registerables ) as command : command . execute ( )
| 1,835
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L176-L193
|
[
"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"
] |
Return a plaintext representation of a bibitem from the . bbl file .
|
def bibitem_as_plaintext ( bibitem ) : try : output = subprocess . check_output ( [ "delatex" , "-s" ] , input = bibitem . encode ( "utf-8" ) ) except FileNotFoundError : script_dir = os . path . dirname ( os . path . abspath ( __file__ ) ) output = subprocess . check_output ( [ "%s/../external/opendetex/delatex" % ( script_dir , ) , "-s" ] , input = bibitem . encode ( "utf-8" ) ) output = output . decode ( "utf-8" ) output = tools . clean_whitespaces ( output ) return output
| 1,836
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/citations/bbl.py#L19-L49
|
[
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"self",
".",
"_driver",
".",
"get",
"(",
"url",
")",
"if",
"self",
".",
"bot_diary",
":",
"self",
".",
"bot_diary",
".",
"add_auto_entry",
"(",
"\"I went on\"",
",",
"target",
"=",
"url",
",",
"take_screenshot",
"=",
"True",
")",
"if",
"BROME_CONFIG",
"[",
"'proxy_driver'",
"]",
"[",
"'intercept_javascript_error'",
"]",
":",
"self",
".",
"init_javascript_error_interception",
"(",
")",
"return",
"True"
] |
Split type of a type name with CardinalityField suffix into its parts .
|
def split_type ( cls , type_name ) : if cls . matches_type ( type_name ) : basename = type_name [ : - 1 ] cardinality = cls . from_char_map [ type_name [ - 1 ] ] else : # -- ASSUME: Cardinality.one cardinality = Cardinality . one basename = type_name return ( basename , cardinality )
| 1,837
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality_field.py#L48-L61
|
[
"def",
"show_session",
"(",
"session_id",
"=",
"None",
",",
"url",
"=",
"'default'",
",",
"session",
"=",
"None",
",",
"browser",
"=",
"None",
",",
"new",
"=",
"\"tab\"",
",",
"controller",
"=",
"None",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"server_url",
"=",
"server_url_for_websocket_url",
"(",
"session",
".",
"_connection",
".",
"url",
")",
"session_id",
"=",
"session",
".",
"id",
"else",
":",
"coords",
"=",
"_SessionCoordinates",
"(",
"session_id",
"=",
"session_id",
",",
"url",
"=",
"url",
")",
"server_url",
"=",
"coords",
".",
"url",
"session_id",
"=",
"coords",
".",
"session_id",
"if",
"controller",
"is",
"None",
":",
"from",
"bokeh",
".",
"util",
".",
"browser",
"import",
"get_browser_controller",
"controller",
"=",
"get_browser_controller",
"(",
"browser",
"=",
"browser",
")",
"controller",
".",
"open",
"(",
"server_url",
"+",
"\"?bokeh-session-id=\"",
"+",
"quote_plus",
"(",
"session_id",
")",
",",
"new",
"=",
"NEW_PARAM",
"[",
"new",
"]",
")"
] |
Build new type name according to CardinalityField naming scheme .
|
def make_type ( cls , basename , cardinality ) : if cardinality is Cardinality . one : # -- POSTCONDITION: assert not cls.make_type(type_name) return basename # -- NORMAL CASE: type with CardinalityField suffix. type_name = "%s%s" % ( basename , cls . to_char_map [ cardinality ] ) # -- POSTCONDITION: assert cls.make_type(type_name) return type_name
| 1,838
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality_field.py#L64-L77
|
[
"def",
"CanonicalPathToLocalPath",
"(",
"path",
")",
":",
"# Account for raw devices",
"path",
"=",
"path",
".",
"replace",
"(",
"\"/\\\\\"",
",",
"\"\\\\\"",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"\"/\"",
",",
"\"\\\\\"",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\\\\([a-zA-Z]):(.*)$\"",
",",
"path",
")",
"if",
"m",
":",
"path",
"=",
"\"%s:\\\\%s\"",
"%",
"(",
"m",
".",
"group",
"(",
"1",
")",
",",
"m",
".",
"group",
"(",
"2",
")",
".",
"lstrip",
"(",
"\"\\\\\"",
")",
")",
"return",
"path"
] |
Create missing type variants for types with a cardinality field .
|
def create_missing_type_variants ( cls , type_names , type_dict ) : missing_type_names = [ name for name in type_names if name not in type_dict ] return cls . create_type_variants ( missing_type_names , type_dict )
| 1,839
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality_field.py#L162-L172
|
[
"def",
"_repo_url_to_path",
"(",
"self",
",",
"repo",
")",
":",
"repo",
"=",
"repo",
".",
"replace",
"(",
"'http://'",
",",
"''",
")",
"repo",
"=",
"repo",
".",
"replace",
"(",
"'https://'",
",",
"''",
")",
"repo",
"=",
"repo",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"return",
"os",
".",
"sep",
".",
"join",
"(",
"[",
"self",
".",
"_data_directory",
",",
"repo",
"]",
")"
] |
Put an ops only if not already there otherwise it s a no op .
|
def put_ops ( self , key , time , ops ) : if self . _store . get ( key ) is None : self . _store [ key ] = ops
| 1,840
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_store.py#L13-L17
|
[
"def",
"sfiles_to_event",
"(",
"sfile_list",
")",
":",
"event_list",
"=",
"[",
"]",
"sort_list",
"=",
"[",
"(",
"readheader",
"(",
"sfile",
")",
".",
"origins",
"[",
"0",
"]",
".",
"time",
",",
"sfile",
")",
"for",
"sfile",
"in",
"sfile_list",
"]",
"sort_list",
".",
"sort",
"(",
"key",
"=",
"lambda",
"tup",
":",
"tup",
"[",
"0",
"]",
")",
"sfile_list",
"=",
"[",
"sfile",
"[",
"1",
"]",
"for",
"sfile",
"in",
"sort_list",
"]",
"catalog",
"=",
"Catalog",
"(",
")",
"for",
"i",
",",
"sfile",
"in",
"enumerate",
"(",
"sfile_list",
")",
":",
"event_list",
".",
"append",
"(",
"(",
"i",
",",
"sfile",
")",
")",
"catalog",
".",
"append",
"(",
"readheader",
"(",
"sfile",
")",
")",
"# Hand off to sister function",
"write_event",
"(",
"catalog",
")",
"return",
"event_list"
] |
Returns ops from the key if found otherwise raises a KeyError .
|
def get_ops ( self , key ) : ops = self . _store . get ( key ) if ops is None : raise KeyError ( 'cannot get operations for {}' . format ( key ) ) return ops
| 1,841
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_store.py#L19-L26
|
[
"def",
"sync_with_s3",
"(",
"self",
")",
":",
"# Create a list to put all the files we're going to update",
"self",
".",
"update_list",
"=",
"[",
"]",
"# Figure out which files need to be updated and upload all these files",
"logger",
".",
"debug",
"(",
"\"Comparing {} local files with {} bucket files\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"local_file_list",
")",
",",
"len",
"(",
"self",
".",
"s3_obj_dict",
".",
"keys",
"(",
")",
")",
")",
")",
"if",
"self",
".",
"no_pooling",
":",
"[",
"self",
".",
"compare_local_file",
"(",
"f",
")",
"for",
"f",
"in",
"self",
".",
"local_file_list",
"]",
"else",
":",
"cpu_count",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Pooling local file comparison on {} CPUs\"",
".",
"format",
"(",
"cpu_count",
")",
")",
"pool",
"=",
"ThreadPool",
"(",
"processes",
"=",
"cpu_count",
")",
"pool",
".",
"map",
"(",
"self",
".",
"compare_local_file",
",",
"self",
".",
"local_file_list",
")",
"logger",
".",
"debug",
"(",
"\"Uploading {} new or updated files to bucket\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"update_list",
")",
")",
")",
"if",
"self",
".",
"no_pooling",
":",
"[",
"self",
".",
"upload_to_s3",
"(",
"*",
"u",
")",
"for",
"u",
"in",
"self",
".",
"update_list",
"]",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Pooling s3 uploads on {} CPUs\"",
".",
"format",
"(",
"cpu_count",
")",
")",
"pool",
"=",
"ThreadPool",
"(",
"processes",
"=",
"cpu_count",
")",
"pool",
".",
"map",
"(",
"self",
".",
"pooled_upload_to_s3",
",",
"self",
".",
"update_list",
")"
] |
Parse a local caveat location as generated by LocalThirdPartyCaveat .
|
def _parse_local_location ( loc ) : if not ( loc . startswith ( 'local ' ) ) : return None v = VERSION_1 fields = loc . split ( ) fields = fields [ 1 : ] # Skip 'local' if len ( fields ) == 2 : try : v = int ( fields [ 0 ] ) except ValueError : return None fields = fields [ 1 : ] if len ( fields ) == 1 : key = PublicKey . deserialize ( fields [ 0 ] ) return ThirdPartyInfo ( public_key = key , version = v ) return None
| 1,842
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L372-L400
|
[
"def",
"dict_delta",
"(",
"old",
",",
"new",
")",
":",
"r",
"=",
"{",
"}",
"oldkeys",
"=",
"set",
"(",
"old",
".",
"keys",
"(",
")",
")",
"newkeys",
"=",
"set",
"(",
"new",
".",
"keys",
"(",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",
"new",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"newkeys",
".",
"difference",
"(",
"oldkeys",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",
"None",
")",
"for",
"k",
"in",
"oldkeys",
".",
"difference",
"(",
"newkeys",
")",
")",
"for",
"k",
"in",
"oldkeys",
".",
"intersection",
"(",
"newkeys",
")",
":",
"if",
"old",
"[",
"k",
"]",
"!=",
"new",
"[",
"k",
"]",
":",
"r",
"[",
"k",
"]",
"=",
"new",
"[",
"k",
"]",
"return",
"r"
] |
Add a caveat to the macaroon .
|
def add_caveat ( self , cav , key = None , loc = None ) : if cav . location is None : self . _macaroon . add_first_party_caveat ( self . namespace . resolve_caveat ( cav ) . condition ) return if key is None : raise ValueError ( 'no private key to encrypt third party caveat' ) local_info = _parse_local_location ( cav . location ) if local_info is not None : info = local_info if cav . condition is not '' : raise ValueError ( 'cannot specify caveat condition in ' 'local third-party caveat' ) cav = checkers . Caveat ( location = 'local' , condition = 'true' ) else : if loc is None : raise ValueError ( 'no locator when adding third party caveat' ) info = loc . third_party_info ( cav . location ) root_key = os . urandom ( 24 ) # Use the least supported version to encode the caveat. if self . _version < info . version : info = ThirdPartyInfo ( version = self . _version , public_key = info . public_key , ) caveat_info = encode_caveat ( cav . condition , root_key , info , key , self . _namespace ) if info . version < VERSION_3 : # We're encoding for an earlier client or third party which does # not understand bundled caveat info, so use the encoded # caveat information as the caveat id. id = caveat_info else : id = self . _new_caveat_id ( self . _caveat_id_prefix ) self . _caveat_data [ id ] = caveat_info self . _macaroon . add_third_party_caveat ( cav . location , root_key , id )
| 1,843
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L90-L150
|
[
"def",
"get_data_dict_from_config",
"(",
"self",
",",
"config_dict",
")",
":",
"return",
"{",
"key",
":",
"self",
".",
"parsedpage",
".",
"get_filtered_values_by_selector",
"(",
"item_dict",
"[",
"'selector'",
"]",
",",
"item_dict",
".",
"get",
"(",
"'regex_filter'",
",",
"None",
")",
",",
"item_dict",
".",
"get",
"(",
"'regex_group'",
",",
"1",
")",
")",
"for",
"key",
",",
"item_dict",
"in",
"config_dict",
".",
"iteritems",
"(",
")",
"if",
"item_dict",
".",
"get",
"(",
"'selector'",
",",
"None",
")",
"is",
"not",
"None",
"}"
] |
Add an array of caveats to the macaroon .
|
def add_caveats ( self , cavs , key , loc ) : if cavs is None : return for cav in cavs : self . add_caveat ( cav , key , loc )
| 1,844
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L152-L164
|
[
"def",
"get_data_dict_from_config",
"(",
"self",
",",
"config_dict",
")",
":",
"return",
"{",
"key",
":",
"self",
".",
"parsedpage",
".",
"get_filtered_values_by_selector",
"(",
"item_dict",
"[",
"'selector'",
"]",
",",
"item_dict",
".",
"get",
"(",
"'regex_filter'",
",",
"None",
")",
",",
"item_dict",
".",
"get",
"(",
"'regex_group'",
",",
"1",
")",
")",
"for",
"key",
",",
"item_dict",
"in",
"config_dict",
".",
"iteritems",
"(",
")",
"if",
"item_dict",
".",
"get",
"(",
"'selector'",
",",
"None",
")",
"is",
"not",
"None",
"}"
] |
Return a dict representation of the macaroon data in JSON format .
|
def to_dict ( self ) : if self . version < VERSION_3 : if len ( self . _caveat_data ) > 0 : raise ValueError ( 'cannot serialize pre-version3 macaroon with ' 'external caveat data' ) return json . loads ( self . _macaroon . serialize ( json_serializer . JsonSerializer ( ) ) ) serialized = { 'm' : json . loads ( self . _macaroon . serialize ( json_serializer . JsonSerializer ( ) ) ) , 'v' : self . _version , } if self . _namespace is not None : serialized [ 'ns' ] = self . _namespace . serialize_text ( ) . decode ( 'utf-8' ) caveat_data = { } for id in self . _caveat_data : key = base64 . b64encode ( id ) . decode ( 'utf-8' ) value = base64 . b64encode ( self . _caveat_data [ id ] ) . decode ( 'utf-8' ) caveat_data [ key ] = value if len ( caveat_data ) > 0 : serialized [ 'cdata' ] = caveat_data return serialized
| 1,845
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L172-L196
|
[
"def",
"cmd_rot",
"(",
"self",
",",
"deg",
"=",
"None",
",",
"ch",
"=",
"None",
")",
":",
"viewer",
"=",
"self",
".",
"get_viewer",
"(",
"ch",
")",
"if",
"viewer",
"is",
"None",
":",
"self",
".",
"log",
"(",
"\"No current viewer/channel.\"",
")",
"return",
"if",
"deg",
"is",
"None",
":",
"self",
".",
"log",
"(",
"\"%f deg\"",
"%",
"(",
"viewer",
".",
"get_rotation",
"(",
")",
")",
")",
"else",
":",
"viewer",
".",
"rotate",
"(",
"deg",
")"
] |
Return a macaroon obtained from the given dictionary as deserialized from JSON .
|
def from_dict ( cls , json_dict ) : json_macaroon = json_dict . get ( 'm' ) if json_macaroon is None : # Try the v1 format if we don't have a macaroon field. m = pymacaroons . Macaroon . deserialize ( json . dumps ( json_dict ) , json_serializer . JsonSerializer ( ) ) macaroon = Macaroon ( root_key = None , id = None , namespace = legacy_namespace ( ) , version = _bakery_version ( m . version ) ) macaroon . _macaroon = m return macaroon version = json_dict . get ( 'v' , None ) if version is None : raise ValueError ( 'no version specified' ) if ( version < VERSION_3 or version > LATEST_VERSION ) : raise ValueError ( 'unknown bakery version {}' . format ( version ) ) m = pymacaroons . Macaroon . deserialize ( json . dumps ( json_macaroon ) , json_serializer . JsonSerializer ( ) ) if m . version != macaroon_version ( version ) : raise ValueError ( 'underlying macaroon has inconsistent version; ' 'got {} want {}' . format ( m . version , macaroon_version ( version ) ) ) namespace = checkers . deserialize_namespace ( json_dict . get ( 'ns' ) ) cdata = json_dict . get ( 'cdata' , { } ) caveat_data = { } for id64 in cdata : id = b64decode ( id64 ) data = b64decode ( cdata [ id64 ] ) caveat_data [ id ] = data macaroon = Macaroon ( root_key = None , id = None , namespace = namespace , version = version ) macaroon . _caveat_data = caveat_data macaroon . _macaroon = m return macaroon
| 1,846
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L199-L239
|
[
"def",
"moving_frequency",
"(",
"self",
",",
"data_frame",
")",
":",
"f",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"(",
"data_frame",
".",
"td",
"[",
"-",
"1",
"]",
".",
"astype",
"(",
"'int'",
")",
"-",
"self",
".",
"window",
")",
")",
":",
"f",
".",
"append",
"(",
"sum",
"(",
"data_frame",
".",
"action_type",
"[",
"(",
"data_frame",
".",
"td",
">=",
"i",
")",
"&",
"(",
"data_frame",
".",
"td",
"<",
"(",
"i",
"+",
"self",
".",
"window",
")",
")",
"]",
"==",
"1",
")",
"/",
"float",
"(",
"self",
".",
"window",
")",
")",
"diff_mov_freq",
"=",
"(",
"np",
".",
"array",
"(",
"f",
"[",
"1",
":",
"-",
"1",
"]",
")",
"-",
"np",
".",
"array",
"(",
"f",
"[",
"0",
":",
"-",
"2",
"]",
")",
")",
"/",
"np",
".",
"array",
"(",
"f",
"[",
"0",
":",
"-",
"2",
"]",
")",
"duration",
"=",
"math",
".",
"ceil",
"(",
"data_frame",
".",
"td",
"[",
"-",
"1",
"]",
")",
"return",
"diff_mov_freq",
",",
"duration"
] |
Return a macaroon deserialized from a string
|
def deserialize_json ( cls , serialized_json ) : serialized = json . loads ( serialized_json ) return Macaroon . from_dict ( serialized )
| 1,847
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L242-L248
|
[
"def",
"moving_frequency",
"(",
"self",
",",
"data_frame",
")",
":",
"f",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"(",
"data_frame",
".",
"td",
"[",
"-",
"1",
"]",
".",
"astype",
"(",
"'int'",
")",
"-",
"self",
".",
"window",
")",
")",
":",
"f",
".",
"append",
"(",
"sum",
"(",
"data_frame",
".",
"action_type",
"[",
"(",
"data_frame",
".",
"td",
">=",
"i",
")",
"&",
"(",
"data_frame",
".",
"td",
"<",
"(",
"i",
"+",
"self",
".",
"window",
")",
")",
"]",
"==",
"1",
")",
"/",
"float",
"(",
"self",
".",
"window",
")",
")",
"diff_mov_freq",
"=",
"(",
"np",
".",
"array",
"(",
"f",
"[",
"1",
":",
"-",
"1",
"]",
")",
"-",
"np",
".",
"array",
"(",
"f",
"[",
"0",
":",
"-",
"2",
"]",
")",
")",
"/",
"np",
".",
"array",
"(",
"f",
"[",
"0",
":",
"-",
"2",
"]",
")",
"duration",
"=",
"math",
".",
"ceil",
"(",
"data_frame",
".",
"td",
"[",
"-",
"1",
"]",
")",
"return",
"diff_mov_freq",
",",
"duration"
] |
Return a third party caveat id
|
def _new_caveat_id ( self , base ) : id = bytearray ( ) if len ( base ) > 0 : id . extend ( base ) else : # Add a version byte to the caveat id. Technically # this is unnecessary as the caveat-decoding logic # that looks at versions should never see this id, # but if the caveat payload isn't provided with the # payload, having this version gives a strong indication # that the payload has been omitted so we can produce # a better error for the user. id . append ( VERSION_3 ) # Iterate through integers looking for one that isn't already used, # starting from n so that if everyone is using this same algorithm, # we'll only perform one iteration. i = len ( self . _caveat_data ) caveats = self . _macaroon . caveats while True : # We append a varint to the end of the id and assume that # any client that's created the id that we're using as a base # is using similar conventions - in the worst case they might # end up with a duplicate third party caveat id and thus create # a macaroon that cannot be discharged. temp = id [ : ] encode_uvarint ( i , temp ) found = False for cav in caveats : if ( cav . verification_key_id is not None and cav . caveat_id == temp ) : found = True break if not found : return bytes ( temp ) i += 1
| 1,848
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L250-L293
|
[
"def",
"release",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subscription",
"and",
"self",
".",
"_subscription",
".",
"subscribed",
":",
"self",
".",
"_subscription",
".",
"unsubscribe",
"(",
")",
"self",
".",
"_subscription",
".",
"reset",
"(",
")"
] |
Returns an array of any macaroons found in the given slice of cookies . If the argument implements a get_header method that will be used instead of the get method to retrieve headers .
|
def extract_macaroons ( headers_or_request ) : def get_header ( key , default = None ) : try : return headers_or_request . get_header ( key , default ) except AttributeError : return headers_or_request . get ( key , default ) mss = [ ] def add_macaroon ( data ) : try : data = utils . b64decode ( data ) data_as_objs = json . loads ( data . decode ( 'utf-8' ) ) except ValueError : return ms = [ utils . macaroon_from_dict ( x ) for x in data_as_objs ] mss . append ( ms ) cookie_header = get_header ( 'Cookie' ) if cookie_header is not None : cs = SimpleCookie ( ) # The cookie might be a unicode object, so convert it # to ASCII. This may cause an exception under Python 2. # TODO is that a problem? cs . load ( str ( cookie_header ) ) for c in cs : if c . startswith ( 'macaroon-' ) : add_macaroon ( cs [ c ] . value ) # Python doesn't make it easy to have multiple values for a # key, so split the header instead, which is necessary # for HTTP1.1 compatibility anyway (see RFC 7230, section 3.2.2) macaroon_header = get_header ( 'Macaroons' ) if macaroon_header is not None : for h in macaroon_header . split ( ',' ) : add_macaroon ( h ) return mss
| 1,849
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L302-L344
|
[
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"try",
":",
"return",
"isinstance",
"(",
"rhs",
",",
"self",
".",
"_class_name",
")",
"except",
"TypeError",
":",
"# Check raw types if there was a type error. This is helpful for",
"# things like cStringIO.StringIO.",
"return",
"type",
"(",
"rhs",
")",
"==",
"type",
"(",
"self",
".",
"_class_name",
")"
] |
Returns a macaroon from a legacy wait endpoint .
|
def _wait_for_macaroon ( wait_url ) : headers = { BAKERY_PROTOCOL_HEADER : str ( bakery . LATEST_VERSION ) } resp = requests . get ( url = wait_url , headers = headers ) if resp . status_code != 200 : raise InteractionError ( 'cannot get {}' . format ( wait_url ) ) return bakery . Macaroon . from_dict ( resp . json ( ) . get ( 'Macaroon' ) )
| 1,850
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L361-L371
|
[
"def",
"analyze",
"(",
"self",
",",
"config_string",
"=",
"None",
")",
":",
"try",
":",
"if",
"config_string",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with the given config string\"",
")",
"return",
"self",
".",
"_analyze_txt_config",
"(",
"config_string",
"=",
"config_string",
")",
"elif",
"self",
".",
"container",
".",
"has_config_xml",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with XML config file\"",
")",
"return",
"self",
".",
"_analyze_xml_config",
"(",
"config_contents",
"=",
"None",
")",
"elif",
"self",
".",
"container",
".",
"has_config_txt",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with TXT config file\"",
")",
"return",
"self",
".",
"_analyze_txt_config",
"(",
"config_string",
"=",
"None",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"No configuration file in this container, returning None\"",
")",
"except",
"(",
"OSError",
",",
"KeyError",
",",
"TypeError",
")",
"as",
"exc",
":",
"self",
".",
"log_exc",
"(",
"u\"An unexpected error occurred while analyzing\"",
",",
"exc",
",",
"True",
",",
"None",
")",
"return",
"None"
] |
Try to resolve the given error which should be a response to the given URL by discharging any macaroon contained in it . That is if error . code is ERR_DISCHARGE_REQUIRED then it will try to discharge err . info . macaroon . If the discharge succeeds the discharged macaroon will be saved to the client s cookie jar otherwise an exception will be raised .
|
def handle_error ( self , error , url ) : if error . info is None or error . info . macaroon is None : raise BakeryException ( 'unable to read info in discharge error ' 'response' ) discharges = bakery . discharge_all ( error . info . macaroon , self . acquire_discharge , self . key , ) macaroons = '[' + ',' . join ( map ( utils . macaroon_to_json_string , discharges ) ) + ']' all_macaroons = base64 . urlsafe_b64encode ( utils . to_bytes ( macaroons ) ) full_path = urljoin ( url , error . info . macaroon_path ) if error . info . cookie_name_suffix is not None : name = 'macaroon-' + error . info . cookie_name_suffix else : name = 'macaroon-auth' expires = checkers . macaroons_expiry_time ( checkers . Namespace ( ) , discharges ) self . cookies . set_cookie ( utils . cookie ( name = name , value = all_macaroons . decode ( 'ascii' ) , url = full_path , expires = expires , ) )
| 1,851
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L89-L121
|
[
"def",
"crc",
"(",
"self",
")",
":",
"crc",
"=",
"sum",
"(",
"i",
".",
"crc",
"(",
")",
"for",
"i",
"in",
"self",
".",
"data",
".",
"values",
"(",
")",
")",
"return",
"crc"
] |
Request a discharge macaroon from the caveat location as an HTTP URL .
|
def acquire_discharge ( self , cav , payload ) : resp = self . _acquire_discharge_with_token ( cav , payload , None ) # TODO Fabrice what is the other http response possible ?? if resp . status_code == 200 : return bakery . Macaroon . from_dict ( resp . json ( ) . get ( 'Macaroon' ) ) cause = Error . from_dict ( resp . json ( ) ) if cause . code != ERR_INTERACTION_REQUIRED : raise DischargeError ( cause . message ) if cause . info is None : raise DischargeError ( 'interaction-required response with no info: {}' . format ( resp . json ( ) ) ) loc = cav . location if not loc . endswith ( '/' ) : loc = loc + '/' token , m = self . _interact ( loc , cause , payload ) if m is not None : # We've acquired the macaroon directly via legacy interaction. return m # Try to acquire the discharge again, but this time with # the token acquired by the interaction method. resp = self . _acquire_discharge_with_token ( cav , payload , token ) if resp . status_code == 200 : return bakery . Macaroon . from_dict ( resp . json ( ) . get ( 'Macaroon' ) ) else : raise DischargeError ( 'discharge failed with code {}' . format ( resp . status_code ) )
| 1,852
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L123-L156
|
[
"def",
"get_all_events",
"(",
"self",
")",
":",
"self",
".",
"all_events",
"=",
"{",
"}",
"events",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"\"$.events.frames\"",
")",
"if",
"events",
"is",
"None",
":",
"return",
"for",
"e",
"in",
"events",
":",
"event_type",
"=",
"e",
".",
"get",
"(",
"'type'",
")",
"frame_id",
"=",
"e",
".",
"get",
"(",
"'frame_id'",
")",
"try",
":",
"self",
".",
"all_events",
"[",
"event_type",
"]",
".",
"append",
"(",
"frame_id",
")",
"except",
"KeyError",
":",
"self",
".",
"all_events",
"[",
"event_type",
"]",
"=",
"[",
"frame_id",
"]"
] |
Gathers a macaroon by directing the user to interact with a web page . The error_info argument holds the interaction - required error response .
|
def _interact ( self , location , error_info , payload ) : if ( self . _interaction_methods is None or len ( self . _interaction_methods ) == 0 ) : raise InteractionError ( 'interaction required but not possible' ) # TODO(rogpeppe) make the robust against a wider range of error info. if error_info . info . interaction_methods is None and error_info . info . visit_url is not None : # It's an old-style error; deal with it differently. return None , self . _legacy_interact ( location , error_info ) for interactor in self . _interaction_methods : found = error_info . info . interaction_methods . get ( interactor . kind ( ) ) if found is None : continue try : token = interactor . interact ( self , location , error_info ) except InteractionMethodNotFound : continue if token is None : raise InteractionError ( 'interaction method returned an empty ' 'token' ) return token , None raise InteractionError ( 'no supported interaction method' )
| 1,853
|
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L173-L200
|
[
"def",
"get_event_handler_classes",
"(",
"categories",
"=",
"None",
")",
":",
"classes",
"=",
"[",
"c",
"for",
"c",
"in",
"all_subclasses",
"(",
"EventHandler",
")",
"if",
"c",
"not",
"in",
"_ABC_EVHANDLER_CLASSES",
"]",
"return",
"classes"
] |
Convert a single BibTeX entry dict to a BibTeX string .
|
def dict2bibtex ( data ) : bibtex = '@' + data [ 'ENTRYTYPE' ] + '{' + data [ 'ID' ] + ",\n" for field in [ i for i in sorted ( data ) if i not in [ 'ENTRYTYPE' , 'ID' ] ] : bibtex += "\t" + field + "={" + data [ field ] + "},\n" bibtex += "}\n\n" return bibtex
| 1,854
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L17-L30
|
[
"def",
"_on_disconnect",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Connection to device %s was interrupted\"",
",",
"self",
".",
"connection_string",
")",
"self",
".",
"connection_interrupted",
"=",
"True"
] |
Create a new BibTeX file .
|
def write ( filename , data ) : with open ( filename , 'w' ) as fh : fh . write ( bibdatabase2bibtex ( data ) )
| 1,855
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L43-L51
|
[
"def",
"make_workspace",
"(",
"measurement",
",",
"channel",
"=",
"None",
",",
"name",
"=",
"None",
",",
"silence",
"=",
"False",
")",
":",
"context",
"=",
"silence_sout_serr",
"if",
"silence",
"else",
"do_nothing",
"with",
"context",
"(",
")",
":",
"hist2workspace",
"=",
"ROOT",
".",
"RooStats",
".",
"HistFactory",
".",
"HistoToWorkspaceFactoryFast",
"(",
"measurement",
")",
"if",
"channel",
"is",
"not",
"None",
":",
"workspace",
"=",
"hist2workspace",
".",
"MakeSingleChannelModel",
"(",
"measurement",
",",
"channel",
")",
"else",
":",
"workspace",
"=",
"hist2workspace",
".",
"MakeCombinedModel",
"(",
"measurement",
")",
"workspace",
"=",
"asrootpy",
"(",
"workspace",
")",
"keepalive",
"(",
"workspace",
",",
"measurement",
")",
"if",
"name",
"is",
"not",
"None",
":",
"workspace",
".",
"SetName",
"(",
"'workspace_{0}'",
".",
"format",
"(",
"name",
")",
")",
"return",
"workspace"
] |
Update an entry in a BibTeX file .
|
def edit ( filename , identifier , data ) : # Get current bibtex with open ( filename , 'r' ) as fh : bibtex = bibtexparser . load ( fh ) # Update it # TODO: Not working bibtex . entries_dict [ identifier ] = data . entries [ 0 ] # Write the resulting BibTeX write ( filename , bibtex )
| 1,856
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L65-L83
|
[
"def",
"set_notification_callback",
"(",
"self",
",",
"notification_cb",
")",
":",
"self",
".",
"_notification_cb",
"=",
"notification_cb",
"if",
"not",
"notification_cb",
"and",
"self",
".",
"dimensions",
":",
"self",
".",
"measured_value",
".",
"notify_value_set",
"=",
"None",
"return",
"self"
] |
Delete an entry in a BibTeX file .
|
def delete ( filename , identifier ) : # Get current bibtex with open ( filename , 'r' ) as fh : bibtex = bibtexparser . load ( fh ) # Delete the bibtex entry # TODO: Not working try : del bibtex . entries_dict [ identifier ] except KeyError : pass # Write the resulting BibTeX write ( filename , bibtex )
| 1,857
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L107-L126
|
[
"def",
"set_notification_callback",
"(",
"self",
",",
"notification_cb",
")",
":",
"self",
".",
"_notification_cb",
"=",
"notification_cb",
"if",
"not",
"notification_cb",
"and",
"self",
".",
"dimensions",
":",
"self",
".",
"measured_value",
".",
"notify_value_set",
"=",
"None",
"return",
"self"
] |
Get all entries from a BibTeX file .
|
def get ( filename , ignore_fields = None ) : # Handle default argument if ignore_fields is None : ignore_fields = [ ] # Open bibtex file with open ( filename , 'r' ) as fh : bibtex = bibtexparser . load ( fh ) # Clean the entries if necessary bibtex . entries = [ { k : entry [ k ] for k in entry if k not in ignore_fields } for entry in bibtex . entries ] return bibtex
| 1,858
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L129-L153
|
[
"def",
"_state_stopped",
"(",
"self",
")",
":",
"if",
"self",
".",
"_reconnectDelayedCall",
":",
"self",
".",
"_reconnectDelayedCall",
".",
"cancel",
"(",
")",
"self",
".",
"_reconnectDelayedCall",
"=",
"None",
"self",
".",
"loseConnection",
"(",
")"
] |
Convert a bibtex entry to a formatted filename according to a given mask .
|
def to_filename ( data , mask = DEFAULT_PAPERS_FILENAME_MASK , extra_formatters = None ) : # Handle default argument if extra_formatters is None : extra_formatters = { } entry = data . entries [ 0 ] authors = re . split ( ' and ' , entry [ 'author' ] ) formatters = { "journal" : "" , "title" : "" , "year" : "" , "first" : "" , "last" : "" , "authors" : "" , "arxiv_version" : "" } formatters [ "journal" ] = entry . get ( "journal" , "" ) formatters [ "title" ] = entry . get ( "title" , "" ) formatters [ "year" ] = entry . get ( "year" , "" ) formatters [ "first" ] = authors [ 0 ] . split ( ',' ) [ 0 ] . strip ( ) formatters [ "last" ] = authors [ - 1 ] . split ( ',' ) [ 0 ] . strip ( ) formatters [ "authors" ] = ", " . join ( [ i . split ( ',' ) [ 0 ] . strip ( ) for i in authors ] ) for extra_formatter in extra_formatters : formatters [ extra_formatter ] = extra_formatters [ extra_formatter ] ( entry ) arxiv_version = "" if "eprint" in entry : arxiv_version = '-' + entry [ 'eprint' ] [ entry [ 'eprint' ] . rfind ( 'v' ) : ] formatters [ "arxiv_version" ] = arxiv_version return tools . slugify ( mask . format ( * * formatters ) )
| 1,859
|
https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L224-L285
|
[
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_exited",
":",
"self",
".",
"_exited",
"=",
"True",
"# signal task runner to terminate via SIGTERM",
"if",
"self",
".",
"_task_runner",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_task_runner",
".",
"terminate",
"(",
")",
"# if command server is running, then block until",
"# task runner completes so it has time to use",
"# the command server to clean up root plugins",
"if",
"self",
".",
"_command_server",
".",
"is_alive",
"(",
")",
":",
"if",
"self",
".",
"_task_runner",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_task_runner",
".",
"join",
"(",
")",
"_shutdown_pipe",
"(",
"self",
".",
"_pipe",
")",
"self",
".",
"_task",
".",
"stop",
"(",
")"
] |
Bind field to its name in model class .
|
def bind_name ( self , name ) : if self . name : raise errors . Error ( 'Already bound "{0}" with name "{1}" could not ' 'be rebound' . format ( self , self . name ) ) self . name = name self . storage_name = '' . join ( ( '_' , self . name ) ) return self
| 1,860
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L24-L31
|
[
"def",
"parse_report",
"(",
"self",
",",
"buf",
")",
":",
"dpad",
"=",
"buf",
"[",
"5",
"]",
"%",
"16",
"return",
"DS4Report",
"(",
"# Left analog stick",
"buf",
"[",
"1",
"]",
",",
"buf",
"[",
"2",
"]",
",",
"# Right analog stick",
"buf",
"[",
"3",
"]",
",",
"buf",
"[",
"4",
"]",
",",
"# L2 and R2 analog",
"buf",
"[",
"8",
"]",
",",
"buf",
"[",
"9",
"]",
",",
"# DPad up, down, left, right",
"(",
"dpad",
"in",
"(",
"0",
",",
"1",
",",
"7",
")",
")",
",",
"(",
"dpad",
"in",
"(",
"3",
",",
"4",
",",
"5",
")",
")",
",",
"(",
"dpad",
"in",
"(",
"5",
",",
"6",
",",
"7",
")",
")",
",",
"(",
"dpad",
"in",
"(",
"1",
",",
"2",
",",
"3",
")",
")",
",",
"# Buttons cross, circle, square, triangle",
"(",
"buf",
"[",
"5",
"]",
"&",
"32",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"5",
"]",
"&",
"64",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"5",
"]",
"&",
"16",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"5",
"]",
"&",
"128",
")",
"!=",
"0",
",",
"# L1, L2 and L3 buttons",
"(",
"buf",
"[",
"6",
"]",
"&",
"1",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"6",
"]",
"&",
"4",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"6",
"]",
"&",
"64",
")",
"!=",
"0",
",",
"# R1, R2,and R3 buttons",
"(",
"buf",
"[",
"6",
"]",
"&",
"2",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"6",
"]",
"&",
"8",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"6",
"]",
"&",
"128",
")",
"!=",
"0",
",",
"# Share and option buttons",
"(",
"buf",
"[",
"6",
"]",
"&",
"16",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"6",
"]",
"&",
"32",
")",
"!=",
"0",
",",
"# Trackpad and PS buttons",
"(",
"buf",
"[",
"7",
"]",
"&",
"2",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"7",
"]",
"&",
"1",
")",
"!=",
"0",
",",
"# Acceleration",
"S16LE",
".",
"unpack_from",
"(",
"buf",
",",
"13",
")",
"[",
"0",
"]",
",",
"S16LE",
".",
"unpack_from",
"(",
"buf",
",",
"15",
")",
"[",
"0",
"]",
",",
"S16LE",
".",
"unpack_from",
"(",
"buf",
",",
"17",
")",
"[",
"0",
"]",
",",
"# Orientation",
"-",
"(",
"S16LE",
".",
"unpack_from",
"(",
"buf",
",",
"19",
")",
"[",
"0",
"]",
")",
",",
"S16LE",
".",
"unpack_from",
"(",
"buf",
",",
"21",
")",
"[",
"0",
"]",
",",
"S16LE",
".",
"unpack_from",
"(",
"buf",
",",
"23",
")",
"[",
"0",
"]",
",",
"# Trackpad touch 1: id, active, x, y",
"buf",
"[",
"35",
"]",
"&",
"0x7f",
",",
"(",
"buf",
"[",
"35",
"]",
">>",
"7",
")",
"==",
"0",
",",
"(",
"(",
"buf",
"[",
"37",
"]",
"&",
"0x0f",
")",
"<<",
"8",
")",
"|",
"buf",
"[",
"36",
"]",
",",
"buf",
"[",
"38",
"]",
"<<",
"4",
"|",
"(",
"(",
"buf",
"[",
"37",
"]",
"&",
"0xf0",
")",
">>",
"4",
")",
",",
"# Trackpad touch 2: id, active, x, y",
"buf",
"[",
"39",
"]",
"&",
"0x7f",
",",
"(",
"buf",
"[",
"39",
"]",
">>",
"7",
")",
"==",
"0",
",",
"(",
"(",
"buf",
"[",
"41",
"]",
"&",
"0x0f",
")",
"<<",
"8",
")",
"|",
"buf",
"[",
"40",
"]",
",",
"buf",
"[",
"42",
"]",
"<<",
"4",
"|",
"(",
"(",
"buf",
"[",
"41",
"]",
"&",
"0xf0",
")",
">>",
"4",
")",
",",
"# Timestamp and battery",
"buf",
"[",
"7",
"]",
">>",
"2",
",",
"buf",
"[",
"30",
"]",
"%",
"16",
",",
"# External inputs (usb, audio, mic)",
"(",
"buf",
"[",
"30",
"]",
"&",
"16",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"30",
"]",
"&",
"32",
")",
"!=",
"0",
",",
"(",
"buf",
"[",
"30",
"]",
"&",
"64",
")",
"!=",
"0",
")"
] |
Bind field to model class .
|
def bind_model_cls ( self , model_cls ) : if self . model_cls : raise errors . Error ( '"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"' . format ( self , self . model_cls , model_cls ) ) self . model_cls = model_cls return self
| 1,861
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L33-L40
|
[
"def",
"add_string",
"(",
"self",
",",
"data",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"data",
":",
"match",
"=",
"self",
".",
"_line_end_re",
".",
"search",
"(",
"data",
")",
"if",
"match",
"is",
"None",
":",
"chunk",
"=",
"data",
"else",
":",
"chunk",
"=",
"data",
"[",
":",
"match",
".",
"end",
"(",
")",
"]",
"data",
"=",
"data",
"[",
"len",
"(",
"chunk",
")",
":",
"]",
"if",
"self",
".",
"_buf",
"and",
"self",
".",
"_buf",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"b",
"(",
"'\\r'",
")",
")",
"and",
"not",
"chunk",
".",
"startswith",
"(",
"b",
"(",
"'\\n'",
")",
")",
":",
"# if we get a carriage return followed by something other than",
"# a newline then we assume that we're overwriting the current",
"# line (ie. a progress bar)",
"#",
"# We don't terminate lines that end with a carriage return until",
"# we see what's coming next so we can distinguish between a",
"# progress bar situation and a Windows line terminator.",
"#",
"# TODO(adrian): some day these hacks should be replaced with",
"# real terminal emulation",
"lines",
".",
"append",
"(",
"self",
".",
"_finish_line",
"(",
")",
")",
"self",
".",
"_buf",
".",
"append",
"(",
"chunk",
")",
"if",
"chunk",
".",
"endswith",
"(",
"b",
"(",
"'\\n'",
")",
")",
":",
"lines",
".",
"append",
"(",
"self",
".",
"_finish_line",
"(",
")",
")",
"return",
"lines"
] |
Init model with field .
|
def init_model ( self , model , value ) : if value is None and self . default is not None : value = self . default ( ) if callable ( self . default ) else self . default self . set_value ( model , value )
| 1,862
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L42-L51
|
[
"def",
"get_latex_table",
"(",
"self",
",",
"parameters",
"=",
"None",
",",
"transpose",
"=",
"False",
",",
"caption",
"=",
"None",
",",
"label",
"=",
"\"tab:model_params\"",
",",
"hlines",
"=",
"True",
",",
"blank_fill",
"=",
"\"--\"",
")",
":",
"# pragma: no cover",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"self",
".",
"parent",
".",
"_all_parameters",
"for",
"p",
"in",
"parameters",
":",
"assert",
"isinstance",
"(",
"p",
",",
"str",
")",
",",
"\"Generating a LaTeX table requires all parameters have labels\"",
"num_parameters",
"=",
"len",
"(",
"parameters",
")",
"num_chains",
"=",
"len",
"(",
"self",
".",
"parent",
".",
"chains",
")",
"fit_values",
"=",
"self",
".",
"get_summary",
"(",
"squeeze",
"=",
"False",
")",
"if",
"label",
"is",
"None",
":",
"label",
"=",
"\"\"",
"if",
"caption",
"is",
"None",
":",
"caption",
"=",
"\"\"",
"end_text",
"=",
"\" \\\\\\\\ \\n\"",
"if",
"transpose",
":",
"column_text",
"=",
"\"c\"",
"*",
"(",
"num_chains",
"+",
"1",
")",
"else",
":",
"column_text",
"=",
"\"c\"",
"*",
"(",
"num_parameters",
"+",
"1",
")",
"center_text",
"=",
"\"\"",
"hline_text",
"=",
"\"\\\\hline\\n\"",
"if",
"hlines",
":",
"center_text",
"+=",
"hline_text",
"+",
"\"\\t\\t\"",
"if",
"transpose",
":",
"center_text",
"+=",
"\" & \"",
".",
"join",
"(",
"[",
"\"Parameter\"",
"]",
"+",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"self",
".",
"parent",
".",
"chains",
"]",
")",
"+",
"end_text",
"if",
"hlines",
":",
"center_text",
"+=",
"\"\\t\\t\"",
"+",
"hline_text",
"for",
"p",
"in",
"parameters",
":",
"arr",
"=",
"[",
"\"\\t\\t\"",
"+",
"p",
"]",
"for",
"chain_res",
"in",
"fit_values",
":",
"if",
"p",
"in",
"chain_res",
":",
"arr",
".",
"append",
"(",
"self",
".",
"get_parameter_text",
"(",
"*",
"chain_res",
"[",
"p",
"]",
",",
"wrap",
"=",
"True",
")",
")",
"else",
":",
"arr",
".",
"append",
"(",
"blank_fill",
")",
"center_text",
"+=",
"\" & \"",
".",
"join",
"(",
"arr",
")",
"+",
"end_text",
"else",
":",
"center_text",
"+=",
"\" & \"",
".",
"join",
"(",
"[",
"\"Model\"",
"]",
"+",
"parameters",
")",
"+",
"end_text",
"if",
"hlines",
":",
"center_text",
"+=",
"\"\\t\\t\"",
"+",
"hline_text",
"for",
"name",
",",
"chain_res",
"in",
"zip",
"(",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"self",
".",
"parent",
".",
"chains",
"]",
",",
"fit_values",
")",
":",
"arr",
"=",
"[",
"\"\\t\\t\"",
"+",
"name",
"]",
"for",
"p",
"in",
"parameters",
":",
"if",
"p",
"in",
"chain_res",
":",
"arr",
".",
"append",
"(",
"self",
".",
"get_parameter_text",
"(",
"*",
"chain_res",
"[",
"p",
"]",
",",
"wrap",
"=",
"True",
")",
")",
"else",
":",
"arr",
".",
"append",
"(",
"blank_fill",
")",
"center_text",
"+=",
"\" & \"",
".",
"join",
"(",
"arr",
")",
"+",
"end_text",
"if",
"hlines",
":",
"center_text",
"+=",
"\"\\t\\t\"",
"+",
"hline_text",
"final_text",
"=",
"get_latex_table_frame",
"(",
"caption",
",",
"label",
")",
"%",
"(",
"column_text",
",",
"center_text",
")",
"return",
"final_text"
] |
Return field s value .
|
def get_value ( self , model , default = None ) : if default is not None : default = self . _converter ( default ) value = getattr ( model , self . storage_name ) return value if value is not None else default
| 1,863
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L53-L64
|
[
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Set field s value .
|
def set_value ( self , model , value ) : if value is None and self . required : raise AttributeError ( "This field is required." ) if value is not None : value = self . _converter ( value ) setattr ( model , self . storage_name , value )
| 1,864
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L66-L78
|
[
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Convert dict into object of class of passed model .
|
def _get_model_instance ( model_cls , data ) : if not isinstance ( data , ( model_cls , dict ) ) : raise TypeError ( '{0} is not valid type, instance of ' '{1} or dict required' . format ( data , model_cls ) ) return model_cls ( * * data ) if isinstance ( data , dict ) else data
| 1,865
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L97-L107
|
[
"def",
"event_availability_array",
"(",
"events",
")",
":",
"array",
"=",
"np",
".",
"ones",
"(",
"(",
"len",
"(",
"events",
")",
",",
"len",
"(",
"events",
")",
")",
")",
"for",
"row",
",",
"event",
"in",
"enumerate",
"(",
"events",
")",
":",
"for",
"col",
",",
"other_event",
"in",
"enumerate",
"(",
"events",
")",
":",
"if",
"row",
"!=",
"col",
":",
"tags",
"=",
"set",
"(",
"event",
".",
"tags",
")",
"events_share_tag",
"=",
"len",
"(",
"tags",
".",
"intersection",
"(",
"other_event",
".",
"tags",
")",
")",
">",
"0",
"if",
"(",
"other_event",
"in",
"event",
".",
"unavailability",
")",
"or",
"events_share_tag",
":",
"array",
"[",
"row",
",",
"col",
"]",
"=",
"0",
"array",
"[",
"col",
",",
"row",
"]",
"=",
"0",
"return",
"array"
] |
Return built - in type representation of Collection .
|
def get_builtin_type ( self , model ) : return [ item . get_data ( ) if isinstance ( item , self . related_model_cls ) else item for item in self . get_value ( model ) ]
| 1,866
|
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L215-L222
|
[
"def",
"edit",
"(",
"self",
",",
"data_src",
",",
"value",
")",
":",
"# check if opening file",
"if",
"'filename'",
"in",
"value",
":",
"items",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"reg",
".",
"data_source",
".",
"iteritems",
"(",
")",
"if",
"v",
"==",
"data_src",
"]",
"self",
".",
"reg",
".",
"unregister",
"(",
"items",
")",
"# remove items from Registry",
"# open file and register new data",
"self",
".",
"open",
"(",
"data_src",
",",
"value",
"[",
"'filename'",
"]",
",",
"value",
".",
"get",
"(",
"'path'",
")",
")",
"self",
".",
"layer",
"[",
"data_src",
"]",
".",
"update",
"(",
"value",
")"
] |
Getter function to retrieve objects from a given object dictionary .
|
def gw_get ( object_dict , name = None , plugin = None ) : if plugin is not None : if name is None : object_list = { } for key in object_dict . keys ( ) : if object_dict [ key ] . plugin == plugin : object_list [ key ] = object_dict [ key ] return object_list else : if name in object_dict . keys ( ) : if object_dict [ name ] . plugin == plugin : return object_dict [ name ] else : return None else : return None else : if name is None : return object_dict else : if name in object_dict . keys ( ) : return object_dict [ name ] else : return None
| 1,867
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/util.py#L1-L36
|
[
"def",
"pprint_table",
"(",
"table",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"rstrip",
"=",
"False",
")",
":",
"def",
"max_width_col",
"(",
"table",
",",
"col_idx",
")",
":",
"\"\"\"\n Get the maximum width of the given column index\n \"\"\"",
"return",
"max",
"(",
"[",
"len",
"(",
"row",
"[",
"col_idx",
"]",
")",
"for",
"row",
"in",
"table",
"]",
")",
"if",
"rstrip",
":",
"for",
"row_idx",
",",
"row",
"in",
"enumerate",
"(",
"table",
")",
":",
"table",
"[",
"row_idx",
"]",
"=",
"[",
"c",
".",
"rstrip",
"(",
")",
"for",
"c",
"in",
"row",
"]",
"col_paddings",
"=",
"[",
"]",
"ncols",
"=",
"len",
"(",
"table",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"ncols",
")",
":",
"col_paddings",
".",
"append",
"(",
"max_width_col",
"(",
"table",
",",
"i",
")",
")",
"for",
"row",
"in",
"table",
":",
"# left col",
"out",
".",
"write",
"(",
"row",
"[",
"0",
"]",
".",
"ljust",
"(",
"col_paddings",
"[",
"0",
"]",
"+",
"1",
")",
")",
"# rest of the cols",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"row",
")",
")",
":",
"col",
"=",
"row",
"[",
"i",
"]",
".",
"rjust",
"(",
"col_paddings",
"[",
"i",
"]",
"+",
"2",
")",
"out",
".",
"write",
"(",
"col",
")",
"out",
".",
"write",
"(",
"\"\\n\"",
")"
] |
Handle 404 errors returned by the API server
|
def http_error_handler ( f ) : def hrefs_to_resources ( hrefs ) : for href in hrefs . replace ( ',' , '' ) . split ( ) : type , uuid = href . split ( '/' ) [ - 2 : ] yield Resource ( type , uuid = uuid ) def hrefs_list_to_resources ( hrefs_list ) : for href in eval ( hrefs_list ) : type , uuid = href . split ( '/' ) [ - 2 : ] yield Resource ( type , uuid = uuid ) @ wraps ( f ) def wrapper ( self , * args , * * kwargs ) : try : return f ( self , * args , * * kwargs ) except HttpError as e : if e . http_status == 404 : # remove previously created resource # from the cache self . emit ( 'deleted' , self ) if isinstance ( self , Resource ) : raise ResourceNotFound ( resource = self ) elif isinstance ( self , Collection ) : raise CollectionNotFound ( collection = self ) elif e . http_status == 409 : # contrail 3.2 matches = re . match ( r'^Delete when children still present: (\[[^]]*\])' , e . message ) if matches : raise ChildrenExists ( resources = list ( hrefs_list_to_resources ( matches . group ( 1 ) ) ) ) matches = re . match ( r'^Delete when resource still referred: (\[[^]]*\])' , e . message ) if matches : raise BackRefsExists ( resources = list ( hrefs_list_to_resources ( matches . group ( 1 ) ) ) ) # contrail 2.21 matches = re . match ( r'^Children (.*) still exist$' , e . message ) if matches : raise ChildrenExists ( resources = list ( hrefs_to_resources ( matches . group ( 1 ) ) ) ) matches = re . match ( r'^Back-References from (.*) still exist$' , e . message ) if matches : raise BackRefsExists ( resources = list ( hrefs_to_resources ( matches . group ( 1 ) ) ) ) raise return wrapper
| 1,868
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L30-L77
|
[
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"tablename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"is_table_name",
"(",
"tablename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"load_wdl",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"if",
"load_dtz",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"return",
"num"
] |
Return URL of the resource
|
def href ( self ) : url = self . session . base_url + str ( self . path ) if self . path . is_collection and not self . path . is_root : return url + 's' return url
| 1,869
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L205-L213
|
[
"def",
"_timestamp_regulator",
"(",
"self",
")",
":",
"unified_timestamps",
"=",
"_PrettyDefaultDict",
"(",
"list",
")",
"staged_files",
"=",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
"for",
"timestamp_basename",
"in",
"self",
".",
"__timestamps_unregulated",
":",
"if",
"len",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
">",
"1",
":",
"# File has been splitted",
"timestamp_name",
"=",
"''",
".",
"join",
"(",
"timestamp_basename",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"staged_splitted_files_of_timestamp",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"staged_file",
":",
"(",
"timestamp_name",
"==",
"staged_file",
"[",
":",
"-",
"3",
"]",
"and",
"all",
"(",
"[",
"(",
"x",
"in",
"set",
"(",
"map",
"(",
"str",
",",
"range",
"(",
"10",
")",
")",
")",
")",
"for",
"x",
"in",
"staged_file",
"[",
"-",
"3",
":",
"]",
"]",
")",
")",
",",
"staged_files",
")",
")",
"if",
"len",
"(",
"staged_splitted_files_of_timestamp",
")",
"==",
"0",
":",
"self",
".",
"__errors",
"[",
"(",
"time",
"(",
")",
",",
"timestamp_basename",
")",
"]",
"=",
"{",
"\"reason\"",
":",
"\"Missing staged file\"",
",",
"\"current_staged_files\"",
":",
"staged_files",
"}",
"continue",
"staged_splitted_files_of_timestamp",
".",
"sort",
"(",
")",
"unified_timestamp",
"=",
"list",
"(",
")",
"for",
"staging_digits",
",",
"splitted_file",
"in",
"enumerate",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
":",
"prev_splits_sec",
"=",
"0",
"if",
"int",
"(",
"staging_digits",
")",
"!=",
"0",
":",
"prev_splits_sec",
"=",
"self",
".",
"_get_audio_duration_seconds",
"(",
"\"{}/staging/{}{:03d}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"timestamp_name",
",",
"staging_digits",
"-",
"1",
")",
")",
"for",
"word_block",
"in",
"splitted_file",
":",
"unified_timestamp",
".",
"append",
"(",
"_WordBlock",
"(",
"word",
"=",
"word_block",
".",
"word",
",",
"start",
"=",
"round",
"(",
"word_block",
".",
"start",
"+",
"prev_splits_sec",
",",
"2",
")",
",",
"end",
"=",
"round",
"(",
"word_block",
".",
"end",
"+",
"prev_splits_sec",
",",
"2",
")",
")",
")",
"unified_timestamps",
"[",
"str",
"(",
"timestamp_basename",
")",
"]",
"+=",
"unified_timestamp",
"else",
":",
"unified_timestamps",
"[",
"timestamp_basename",
"]",
"+=",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
"[",
"0",
"]",
"self",
".",
"__timestamps",
".",
"update",
"(",
"unified_timestamps",
")",
"self",
".",
"__timestamps_unregulated",
"=",
"_PrettyDefaultDict",
"(",
"list",
")"
] |
Add permanent filter on the collection
|
def filter ( self , field_name , field_value ) : self . filters . append ( ( field_name , field_value ) ) return self
| 1,870
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L299-L309
|
[
"def",
"_send_register_payload",
"(",
"self",
",",
"websocket",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"HANDSHAKE_FILE_NAME",
")",
"data",
"=",
"codecs",
".",
"open",
"(",
"file",
",",
"'r'",
",",
"'utf-8'",
")",
"raw_handshake",
"=",
"data",
".",
"read",
"(",
")",
"handshake",
"=",
"json",
".",
"loads",
"(",
"raw_handshake",
")",
"handshake",
"[",
"'payload'",
"]",
"[",
"'client-key'",
"]",
"=",
"self",
".",
"client_key",
"yield",
"from",
"websocket",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"handshake",
")",
")",
"raw_response",
"=",
"yield",
"from",
"websocket",
".",
"recv",
"(",
")",
"response",
"=",
"json",
".",
"loads",
"(",
"raw_response",
")",
"if",
"response",
"[",
"'type'",
"]",
"==",
"'response'",
"and",
"response",
"[",
"'payload'",
"]",
"[",
"'pairingType'",
"]",
"==",
"'PROMPT'",
":",
"raw_response",
"=",
"yield",
"from",
"websocket",
".",
"recv",
"(",
")",
"response",
"=",
"json",
".",
"loads",
"(",
"raw_response",
")",
"if",
"response",
"[",
"'type'",
"]",
"==",
"'registered'",
":",
"self",
".",
"client_key",
"=",
"response",
"[",
"'payload'",
"]",
"[",
"'client-key'",
"]",
"self",
".",
"save_key_file",
"(",
")"
] |
Fetch collection from API server
|
def fetch ( self , recursive = 1 , fields = None , detail = None , filters = None , parent_uuid = None , back_refs_uuid = None ) : params = self . _format_fetch_params ( fields = fields , detail = detail , filters = filters , parent_uuid = parent_uuid , back_refs_uuid = back_refs_uuid ) data = self . session . get_json ( self . href , * * params ) if not self . type : self . data = [ Collection ( col [ "link" ] [ "name" ] , fetch = recursive - 1 > 0 , recursive = recursive - 1 , fields = self . _fetch_fields ( fields ) , detail = detail or self . detail , filters = self . _fetch_filters ( filters ) , parent_uuid = self . _fetch_parent_uuid ( parent_uuid ) , back_refs_uuid = self . _fetch_back_refs_uuid ( back_refs_uuid ) ) for col in data [ 'links' ] if col [ "link" ] [ "rel" ] == "collection" ] else : # when detail=False, res == {resource_attrs} # when detail=True, res == {'type': {resource_attrs}} self . data = [ Resource ( self . type , fetch = recursive - 1 > 0 , recursive = recursive - 1 , * * res . get ( self . type , res ) ) for res_type , res_list in data . items ( ) for res in res_list ] return self
| 1,871
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L346-L393
|
[
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"tablename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"is_table_name",
"(",
"tablename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"load_wdl",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"if",
"load_dtz",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"return",
"num"
] |
Check that the resource exists .
|
def check ( self ) : if self . fq_name : self [ 'uuid' ] = self . _check_fq_name ( self . fq_name ) elif self . uuid : self [ 'fq_name' ] = self . _check_uuid ( self . uuid ) return True
| 1,872
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L488-L497
|
[
"def",
"select_models",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'columns'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"don't pass 'columns' to select_models\"",
")",
"return",
"(",
"set_options",
"(",
"pool_or_cursor",
",",
"clas",
"(",
"*",
"row",
")",
")",
"for",
"row",
"in",
"clas",
".",
"select",
"(",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
")"
] |
Return FQDN of the resource
|
def fq_name ( self ) : return self . get ( 'fq_name' , self . get ( 'to' , super ( Resource , self ) . fq_name ) )
| 1,873
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L529-L534
|
[
"def",
"clean_file",
"(",
"c_source",
",",
"virtualenv_dirname",
")",
":",
"with",
"open",
"(",
"c_source",
",",
"\"r\"",
")",
"as",
"file_obj",
":",
"contents",
"=",
"file_obj",
".",
"read",
"(",
")",
".",
"rstrip",
"(",
")",
"# Replace the path to the Cython include files.",
"py_version",
"=",
"\"python{}.{}\"",
".",
"format",
"(",
"*",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
")",
"lib_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\".nox\"",
",",
"virtualenv_dirname",
",",
"\"lib\"",
",",
"py_version",
",",
"\"site-packages\"",
",",
"\"\"",
")",
"contents",
"=",
"contents",
".",
"replace",
"(",
"lib_path",
",",
"\"\"",
")",
"# Write the files back, but strip all trailing whitespace.",
"lines",
"=",
"contents",
".",
"split",
"(",
"\"\\n\"",
")",
"with",
"open",
"(",
"c_source",
",",
"\"w\"",
")",
"as",
"file_obj",
":",
"for",
"line",
"in",
"lines",
":",
"file_obj",
".",
"write",
"(",
"line",
".",
"rstrip",
"(",
")",
"+",
"\"\\n\"",
")"
] |
Return parent resource
|
def parent ( self ) : try : return Resource ( self [ 'parent_type' ] , uuid = self [ 'parent_uuid' ] , check = True ) except KeyError : raise ResourceMissing ( '%s has no parent resource' % self )
| 1,874
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L537-L547
|
[
"def",
"_timestamp_regulator",
"(",
"self",
")",
":",
"unified_timestamps",
"=",
"_PrettyDefaultDict",
"(",
"list",
")",
"staged_files",
"=",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
"for",
"timestamp_basename",
"in",
"self",
".",
"__timestamps_unregulated",
":",
"if",
"len",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
">",
"1",
":",
"# File has been splitted",
"timestamp_name",
"=",
"''",
".",
"join",
"(",
"timestamp_basename",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"staged_splitted_files_of_timestamp",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"staged_file",
":",
"(",
"timestamp_name",
"==",
"staged_file",
"[",
":",
"-",
"3",
"]",
"and",
"all",
"(",
"[",
"(",
"x",
"in",
"set",
"(",
"map",
"(",
"str",
",",
"range",
"(",
"10",
")",
")",
")",
")",
"for",
"x",
"in",
"staged_file",
"[",
"-",
"3",
":",
"]",
"]",
")",
")",
",",
"staged_files",
")",
")",
"if",
"len",
"(",
"staged_splitted_files_of_timestamp",
")",
"==",
"0",
":",
"self",
".",
"__errors",
"[",
"(",
"time",
"(",
")",
",",
"timestamp_basename",
")",
"]",
"=",
"{",
"\"reason\"",
":",
"\"Missing staged file\"",
",",
"\"current_staged_files\"",
":",
"staged_files",
"}",
"continue",
"staged_splitted_files_of_timestamp",
".",
"sort",
"(",
")",
"unified_timestamp",
"=",
"list",
"(",
")",
"for",
"staging_digits",
",",
"splitted_file",
"in",
"enumerate",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
":",
"prev_splits_sec",
"=",
"0",
"if",
"int",
"(",
"staging_digits",
")",
"!=",
"0",
":",
"prev_splits_sec",
"=",
"self",
".",
"_get_audio_duration_seconds",
"(",
"\"{}/staging/{}{:03d}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"timestamp_name",
",",
"staging_digits",
"-",
"1",
")",
")",
"for",
"word_block",
"in",
"splitted_file",
":",
"unified_timestamp",
".",
"append",
"(",
"_WordBlock",
"(",
"word",
"=",
"word_block",
".",
"word",
",",
"start",
"=",
"round",
"(",
"word_block",
".",
"start",
"+",
"prev_splits_sec",
",",
"2",
")",
",",
"end",
"=",
"round",
"(",
"word_block",
".",
"end",
"+",
"prev_splits_sec",
",",
"2",
")",
")",
")",
"unified_timestamps",
"[",
"str",
"(",
"timestamp_basename",
")",
"]",
"+=",
"unified_timestamp",
"else",
":",
"unified_timestamps",
"[",
"timestamp_basename",
"]",
"+=",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
"[",
"0",
"]",
"self",
".",
"__timestamps",
".",
"update",
"(",
"unified_timestamps",
")",
"self",
".",
"__timestamps_unregulated",
"=",
"_PrettyDefaultDict",
"(",
"list",
")"
] |
Set parent resource
|
def parent ( self , resource ) : resource . check ( ) self [ 'parent_type' ] = resource . type self [ 'parent_uuid' ] = resource . uuid
| 1,875
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L550-L560
|
[
"def",
"_timestamp_regulator",
"(",
"self",
")",
":",
"unified_timestamps",
"=",
"_PrettyDefaultDict",
"(",
"list",
")",
"staged_files",
"=",
"self",
".",
"_list_audio_files",
"(",
"sub_dir",
"=",
"\"staging\"",
")",
"for",
"timestamp_basename",
"in",
"self",
".",
"__timestamps_unregulated",
":",
"if",
"len",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
">",
"1",
":",
"# File has been splitted",
"timestamp_name",
"=",
"''",
".",
"join",
"(",
"timestamp_basename",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"staged_splitted_files_of_timestamp",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"staged_file",
":",
"(",
"timestamp_name",
"==",
"staged_file",
"[",
":",
"-",
"3",
"]",
"and",
"all",
"(",
"[",
"(",
"x",
"in",
"set",
"(",
"map",
"(",
"str",
",",
"range",
"(",
"10",
")",
")",
")",
")",
"for",
"x",
"in",
"staged_file",
"[",
"-",
"3",
":",
"]",
"]",
")",
")",
",",
"staged_files",
")",
")",
"if",
"len",
"(",
"staged_splitted_files_of_timestamp",
")",
"==",
"0",
":",
"self",
".",
"__errors",
"[",
"(",
"time",
"(",
")",
",",
"timestamp_basename",
")",
"]",
"=",
"{",
"\"reason\"",
":",
"\"Missing staged file\"",
",",
"\"current_staged_files\"",
":",
"staged_files",
"}",
"continue",
"staged_splitted_files_of_timestamp",
".",
"sort",
"(",
")",
"unified_timestamp",
"=",
"list",
"(",
")",
"for",
"staging_digits",
",",
"splitted_file",
"in",
"enumerate",
"(",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
")",
":",
"prev_splits_sec",
"=",
"0",
"if",
"int",
"(",
"staging_digits",
")",
"!=",
"0",
":",
"prev_splits_sec",
"=",
"self",
".",
"_get_audio_duration_seconds",
"(",
"\"{}/staging/{}{:03d}\"",
".",
"format",
"(",
"self",
".",
"src_dir",
",",
"timestamp_name",
",",
"staging_digits",
"-",
"1",
")",
")",
"for",
"word_block",
"in",
"splitted_file",
":",
"unified_timestamp",
".",
"append",
"(",
"_WordBlock",
"(",
"word",
"=",
"word_block",
".",
"word",
",",
"start",
"=",
"round",
"(",
"word_block",
".",
"start",
"+",
"prev_splits_sec",
",",
"2",
")",
",",
"end",
"=",
"round",
"(",
"word_block",
".",
"end",
"+",
"prev_splits_sec",
",",
"2",
")",
")",
")",
"unified_timestamps",
"[",
"str",
"(",
"timestamp_basename",
")",
"]",
"+=",
"unified_timestamp",
"else",
":",
"unified_timestamps",
"[",
"timestamp_basename",
"]",
"+=",
"self",
".",
"__timestamps_unregulated",
"[",
"timestamp_basename",
"]",
"[",
"0",
"]",
"self",
".",
"__timestamps",
".",
"update",
"(",
"unified_timestamps",
")",
"self",
".",
"__timestamps_unregulated",
"=",
"_PrettyDefaultDict",
"(",
"list",
")"
] |
Return creation date
|
def created ( self ) : if 'id_perms' not in self : self . fetch ( ) created = self [ 'id_perms' ] [ 'created' ] return datetime . strptime ( created , '%Y-%m-%dT%H:%M:%S.%f' )
| 1,876
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L563-L572
|
[
"def",
"_psturng",
"(",
"q",
",",
"r",
",",
"v",
")",
":",
"if",
"q",
"<",
"0.",
":",
"raise",
"ValueError",
"(",
"'q should be >= 0'",
")",
"opt_func",
"=",
"lambda",
"p",
",",
"r",
",",
"v",
":",
"abs",
"(",
"_qsturng",
"(",
"p",
",",
"r",
",",
"v",
")",
"-",
"q",
")",
"if",
"v",
"==",
"1",
":",
"if",
"q",
"<",
"_qsturng",
"(",
".9",
",",
"r",
",",
"1",
")",
":",
"return",
".1",
"elif",
"q",
">",
"_qsturng",
"(",
".999",
",",
"r",
",",
"1",
")",
":",
"return",
".001",
"return",
"1.",
"-",
"fminbound",
"(",
"opt_func",
",",
".9",
",",
".999",
",",
"args",
"=",
"(",
"r",
",",
"v",
")",
")",
"else",
":",
"if",
"q",
"<",
"_qsturng",
"(",
".1",
",",
"r",
",",
"v",
")",
":",
"return",
".9",
"elif",
"q",
">",
"_qsturng",
"(",
".999",
",",
"r",
",",
"v",
")",
":",
"return",
".001",
"return",
"1.",
"-",
"fminbound",
"(",
"opt_func",
",",
".1",
",",
".999",
",",
"args",
"=",
"(",
"r",
",",
"v",
")",
")"
] |
Save the resource to the API server
|
def save ( self ) : if self . path . is_collection : self . session . post_json ( self . href , { self . type : dict ( self . data ) } , cls = ResourceEncoder ) else : self . session . put_json ( self . href , { self . type : dict ( self . data ) } , cls = ResourceEncoder ) return self . fetch ( exclude_children = True , exclude_back_refs = True )
| 1,877
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L575-L591
|
[
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"tablename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"is_table_name",
"(",
"tablename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"load_wdl",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"if",
"load_dtz",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"return",
"num"
] |
Delete resource from the API server
|
def delete ( self ) : res = self . session . delete ( self . href ) self . emit ( 'deleted' , self ) return res
| 1,878
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L594-L599
|
[
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"tablename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"is_table_name",
"(",
"tablename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"load_wdl",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"if",
"load_dtz",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"return",
"num"
] |
Fetch resource from the API server
|
def fetch ( self , recursive = 1 , exclude_children = False , exclude_back_refs = False ) : if not self . path . is_resource and not self . path . is_uuid : self . check ( ) params = { } # even if the param is False the API will exclude resources if exclude_children : params [ 'exclude_children' ] = True if exclude_back_refs : params [ 'exclude_back_refs' ] = True data = self . session . get_json ( self . href , * * params ) [ self . type ] self . from_dict ( data ) return self
| 1,879
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L602-L624
|
[
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
",",
"*",
",",
"load_wdl",
":",
"bool",
"=",
"True",
",",
"load_dtz",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"num",
"=",
"0",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"tablename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"is_table_name",
"(",
"tablename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"load_wdl",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbw_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"wdl",
",",
"WdlTable",
",",
"path",
")",
"if",
"load_dtz",
":",
"if",
"ext",
"==",
"self",
".",
"variant",
".",
"tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"elif",
"\"P\"",
"not",
"in",
"tablename",
"and",
"ext",
"==",
"self",
".",
"variant",
".",
"pawnless_tbz_suffix",
":",
"num",
"+=",
"self",
".",
"_open_table",
"(",
"self",
".",
"dtz",
",",
"DtzTable",
",",
"path",
")",
"return",
"num"
] |
Populate the resource from a python dict
|
def from_dict ( self , data , recursive = 1 ) : # Find other linked resources data = self . _encode_resource ( data , recursive = recursive ) self . data = data
| 1,880
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L626-L634
|
[
"def",
"_get_feed_cache",
"(",
"self",
")",
":",
"feed_cache",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_feed_cache_file",
")",
":",
"maxage",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"self",
".",
"_cachetime",
")",
"file_ts",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"os",
".",
"stat",
"(",
"self",
".",
"_feed_cache_file",
")",
".",
"st_mtime",
")",
"if",
"file_ts",
">",
"maxage",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_feed_cache_file",
",",
"'rb'",
")",
"as",
"cache",
":",
"feed_cache",
"=",
"cache",
".",
"read",
"(",
")",
"finally",
":",
"pass",
"return",
"feed_cache"
] |
Remove reference from self to ref
|
def remove_ref ( self , ref ) : self . session . remove_ref ( self , ref ) return self . fetch ( )
| 1,881
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L669-L686
|
[
"def",
"update_experiment",
"(",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"return",
"None",
"for",
"key",
"in",
"experiment_dict",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"experiment_dict",
"[",
"key",
"]",
",",
"dict",
")",
":",
"if",
"experiment_dict",
"[",
"key",
"]",
".",
"get",
"(",
"'status'",
")",
"!=",
"'STOPPED'",
":",
"nni_config",
"=",
"Config",
"(",
"experiment_dict",
"[",
"key",
"]",
"[",
"'fileName'",
"]",
")",
"rest_pid",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPid'",
")",
"if",
"not",
"detect_process",
"(",
"rest_pid",
")",
":",
"experiment_config",
".",
"update_experiment",
"(",
"key",
",",
"'status'",
",",
"'STOPPED'",
")",
"continue",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"startTime",
",",
"endTime",
"=",
"get_experiment_time",
"(",
"rest_port",
")",
"if",
"startTime",
":",
"experiment_config",
".",
"update_experiment",
"(",
"key",
",",
"'startTime'",
",",
"startTime",
")",
"if",
"endTime",
":",
"experiment_config",
".",
"update_experiment",
"(",
"key",
",",
"'endTime'",
",",
"endTime",
")",
"status",
"=",
"get_experiment_status",
"(",
"rest_port",
")",
"if",
"status",
":",
"experiment_config",
".",
"update_experiment",
"(",
"key",
",",
"'status'",
",",
"status",
")"
] |
Set reference to resource
|
def set_ref ( self , ref , attr = None ) : ref_attr = '%s_refs' % ref . type . replace ( '-' , '_' ) ref = { 'to' : ref . fq_name , 'uuid' : ref . uuid , } if ref_attr in self : self [ ref_attr ] . append ( ref ) else : self [ ref_attr ] = [ ref ] return self
| 1,882
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L699-L719
|
[
"def",
"getDefaultItems",
"(",
"self",
")",
":",
"plugins",
"=",
"[",
"InspectorRegItem",
"(",
"DEFAULT_INSPECTOR",
",",
"'argos.inspector.qtplugins.table.TableInspector'",
")",
",",
"InspectorRegItem",
"(",
"'Qt/Text'",
",",
"'argos.inspector.qtplugins.text.TextInspector'",
")",
",",
"InspectorRegItem",
"(",
"'PyQtGraph/1D Line Plot'",
",",
"'argos.inspector.pgplugins.lineplot1d.PgLinePlot1d'",
")",
",",
"InspectorRegItem",
"(",
"'PyQtGraph/2D Image Plot'",
",",
"'argos.inspector.pgplugins.imageplot2d.PgImagePlot2d'",
")",
",",
"]",
"if",
"DEBUGGING",
":",
"plugins",
".",
"append",
"(",
"InspectorRegItem",
"(",
"'Debug Inspector'",
",",
"'argos.inspector.debug.DebugInspector'",
")",
")",
"return",
"plugins"
] |
Add reference to resource
|
def add_ref ( self , ref , attr = None ) : self . session . add_ref ( self , ref , attr ) return self . fetch ( )
| 1,883
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L721-L730
|
[
"def",
"getDefaultItems",
"(",
"self",
")",
":",
"plugins",
"=",
"[",
"InspectorRegItem",
"(",
"DEFAULT_INSPECTOR",
",",
"'argos.inspector.qtplugins.table.TableInspector'",
")",
",",
"InspectorRegItem",
"(",
"'Qt/Text'",
",",
"'argos.inspector.qtplugins.text.TextInspector'",
")",
",",
"InspectorRegItem",
"(",
"'PyQtGraph/1D Line Plot'",
",",
"'argos.inspector.pgplugins.lineplot1d.PgLinePlot1d'",
")",
",",
"InspectorRegItem",
"(",
"'PyQtGraph/2D Image Plot'",
",",
"'argos.inspector.pgplugins.imageplot2d.PgImagePlot2d'",
")",
",",
"]",
"if",
"DEBUGGING",
":",
"plugins",
".",
"append",
"(",
"InspectorRegItem",
"(",
"'Debug Inspector'",
",",
"'argos.inspector.debug.DebugInspector'",
")",
")",
"return",
"plugins"
] |
Add reference from back_ref to self
|
def add_back_ref ( self , back_ref , attr = None ) : back_ref . add_ref ( self , attr ) return self . fetch ( )
| 1,884
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L732-L741
|
[
"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",
")"
] |
Search in cache
|
def _search ( self , trie , strings , limit = None ) : results = [ trie . has_keys_with_prefix ( s ) for s in strings ] if not any ( results ) : return [ ] for result , s in zip ( results , strings ) : if result is True : return trie . values ( s ) [ : limit ]
| 1,885
|
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L777-L792
|
[
"def",
"cublasZgemm",
"(",
"handle",
",",
"transa",
",",
"transb",
",",
"m",
",",
"n",
",",
"k",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"B",
",",
"ldb",
",",
"beta",
",",
"C",
",",
"ldc",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasZgemm_v2",
"(",
"handle",
",",
"_CUBLAS_OP",
"[",
"transa",
"]",
",",
"_CUBLAS_OP",
"[",
"transb",
"]",
",",
"m",
",",
"n",
",",
"k",
",",
"ctypes",
".",
"byref",
"(",
"cuda",
".",
"cuDoubleComplex",
"(",
"alpha",
".",
"real",
",",
"alpha",
".",
"imag",
")",
")",
",",
"int",
"(",
"A",
")",
",",
"lda",
",",
"int",
"(",
"B",
")",
",",
"ldb",
",",
"ctypes",
".",
"byref",
"(",
"cuda",
".",
"cuDoubleComplex",
"(",
"beta",
".",
"real",
",",
"beta",
".",
"imag",
")",
")",
",",
"int",
"(",
"C",
")",
",",
"ldc",
")",
"cublasCheckStatus",
"(",
"status",
")"
] |
Registers a new signal .
|
def register ( self , signal , plugin , description = "" ) : if signal in self . signals . keys ( ) : raise Exception ( "Signal %s was already registered by %s" % ( signal , self . signals [ signal ] . plugin . name ) ) self . signals [ signal ] = Signal ( signal , plugin , self . _namespace , description ) self . __log . debug ( "Signal %s registered by %s" % ( signal , plugin . name ) ) return self . signals [ signal ]
| 1,886
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L48-L62
|
[
"def",
"build_caching_info_message",
"(",
"job_spec",
",",
"job_id",
",",
"workflow_workspace",
",",
"workflow_json",
",",
"result_path",
")",
":",
"caching_info_message",
"=",
"{",
"\"job_spec\"",
":",
"job_spec",
",",
"\"job_id\"",
":",
"job_id",
",",
"\"workflow_workspace\"",
":",
"workflow_workspace",
",",
"\"workflow_json\"",
":",
"workflow_json",
",",
"\"result_path\"",
":",
"result_path",
"}",
"return",
"caching_info_message"
] |
Unregisters an existing signal
|
def unregister ( self , signal ) : if signal in self . signals . keys ( ) : del ( self . signals [ signal ] ) self . __log . debug ( "Signal %s unregisterd" % signal ) else : self . __log . debug ( "Signal %s does not exist and could not be unregistered." )
| 1,887
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L64-L74
|
[
"def",
"generate_http_manifest",
"(",
"self",
")",
":",
"base_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"translate_path",
"(",
"self",
".",
"path",
")",
")",
"self",
".",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"base_path",
")",
"admin_metadata_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"\".dtool\"",
",",
"\"dtool\"",
")",
"with",
"open",
"(",
"admin_metadata_fpath",
")",
"as",
"fh",
":",
"admin_metadata",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"http_manifest",
"=",
"{",
"\"admin_metadata\"",
":",
"admin_metadata",
",",
"\"manifest_url\"",
":",
"self",
".",
"generate_url",
"(",
"\".dtool/manifest.json\"",
")",
",",
"\"readme_url\"",
":",
"self",
".",
"generate_url",
"(",
"\"README.yml\"",
")",
",",
"\"overlays\"",
":",
"self",
".",
"generate_overlay_urls",
"(",
")",
",",
"\"item_urls\"",
":",
"self",
".",
"generate_item_urls",
"(",
")",
"}",
"return",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"http_manifest",
")",
",",
"\"utf-8\"",
")"
] |
Disconnect a receiver from a signal . Signal and receiver must exist otherwise an exception is thrown .
|
def disconnect ( self , receiver ) : if receiver not in self . receivers . keys ( ) : raise Exception ( "No receiver %s was registered" % receiver ) self . receivers [ receiver ] . disconnect ( ) del ( self . receivers [ receiver ] ) self . __log . debug ( "Receiver %s disconnected" % receiver )
| 1,888
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L98-L109
|
[
"def",
"_map_scratch_files",
"(",
"self",
",",
"file_dict",
")",
":",
"if",
"self",
".",
"_file_stage",
"is",
"None",
":",
"return",
"(",
"{",
"}",
",",
"{",
"}",
")",
"input_files",
"=",
"file_dict",
".",
"input_files_to_stage",
"output_files",
"=",
"file_dict",
".",
"output_files_to_stage",
"input_file_mapping",
"=",
"self",
".",
"_file_stage",
".",
"map_files",
"(",
"input_files",
")",
"output_file_mapping",
"=",
"self",
".",
"_file_stage",
".",
"map_files",
"(",
"output_files",
")",
"self",
".",
"_update_file_args",
"(",
"input_file_mapping",
")",
"self",
".",
"_update_file_args",
"(",
"output_file_mapping",
")",
"return",
"input_file_mapping",
",",
"output_file_mapping"
] |
Get one or more signals .
|
def get ( self , signal = None , plugin = None ) : if plugin is not None : if signal is None : signals_list = { } for key in self . signals . keys ( ) : if self . signals [ key ] . plugin == plugin : signals_list [ key ] = self . signals [ key ] return signals_list else : if signal in self . signals . keys ( ) : if self . signals [ signal ] . plugin == plugin : return self . signals [ signal ] else : return None else : return None else : if signal is None : return self . signals else : if signal in self . signals . keys ( ) : return self . signals [ signal ] else : return None
| 1,889
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L126-L157
|
[
"def",
"_mmUpdateDutyCycles",
"(",
"self",
")",
":",
"period",
"=",
"self",
".",
"getDutyCyclePeriod",
"(",
")",
"unionSDRArray",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"getNumColumns",
"(",
")",
")",
"unionSDRArray",
"[",
"list",
"(",
"self",
".",
"_mmTraces",
"[",
"\"unionSDR\"",
"]",
".",
"data",
"[",
"-",
"1",
"]",
")",
"]",
"=",
"1",
"self",
".",
"_mmData",
"[",
"\"unionSDRDutyCycle\"",
"]",
"=",
"UnionTemporalPoolerMonitorMixin",
".",
"_mmUpdateDutyCyclesHelper",
"(",
"self",
".",
"_mmData",
"[",
"\"unionSDRDutyCycle\"",
"]",
",",
"unionSDRArray",
",",
"period",
")",
"self",
".",
"_mmData",
"[",
"\"persistenceDutyCycle\"",
"]",
"=",
"UnionTemporalPoolerMonitorMixin",
".",
"_mmUpdateDutyCyclesHelper",
"(",
"self",
".",
"_mmData",
"[",
"\"persistenceDutyCycle\"",
"]",
",",
"self",
".",
"_poolingActivation",
",",
"period",
")"
] |
Get one or more receivers .
|
def get_receiver ( self , receiver = None , plugin = None ) : if plugin is not None : if receiver is None : receiver_list = { } for key in self . receivers . keys ( ) : if self . receivers [ key ] . plugin == plugin : receiver_list [ key ] = self . receivers [ key ] return receiver_list else : if receiver in self . receivers . keys ( ) : if self . receivers [ receiver ] . plugin == plugin : return self . receivers [ receiver ] else : return None else : return None else : if receiver is None : return self . receivers else : if receiver in self . receivers . keys ( ) : return self . receivers [ receiver ] else : return None
| 1,890
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L159-L190
|
[
"def",
"get_offset",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"libfreqs",
".",
"_dont_uppercase",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"name",
"=",
"libfreqs",
".",
"_lite_rule_alias",
".",
"get",
"(",
"name",
",",
"name",
")",
"name",
"=",
"libfreqs",
".",
"_lite_rule_alias",
".",
"get",
"(",
"name",
".",
"lower",
"(",
")",
",",
"name",
")",
"else",
":",
"name",
"=",
"libfreqs",
".",
"_lite_rule_alias",
".",
"get",
"(",
"name",
",",
"name",
")",
"if",
"name",
"not",
"in",
"_offset_map",
":",
"try",
":",
"split",
"=",
"name",
".",
"split",
"(",
"'-'",
")",
"klass",
"=",
"prefix_mapping",
"[",
"split",
"[",
"0",
"]",
"]",
"# handles case where there's no suffix (and will TypeError if too",
"# many '-')",
"offset",
"=",
"klass",
".",
"_from_name",
"(",
"*",
"split",
"[",
"1",
":",
"]",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"# bad prefix or suffix",
"raise",
"ValueError",
"(",
"libfreqs",
".",
"INVALID_FREQ_ERR_MSG",
".",
"format",
"(",
"name",
")",
")",
"# cache",
"_offset_map",
"[",
"name",
"]",
"=",
"offset",
"return",
"_offset_map",
"[",
"name",
"]"
] |
Starts the listener with incoming and outgoing queues .
|
def start ( inqueue , outqueue = None ) : conf . init ( ) , db . init ( conf . DbPath ) Listener ( inqueue , outqueue ) . run ( )
| 1,891
|
https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L263-L266
|
[
"def",
"isFresh",
"(",
"self",
")",
":",
"max_age",
"=",
"self",
".",
"getMaxAge",
"(",
")",
"date",
"=",
"self",
".",
"getDate",
"(",
")",
"is_fresh",
"=",
"False",
"if",
"max_age",
"and",
"date",
":",
"delta_time",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"date",
"is_fresh",
"=",
"delta_time",
".",
"total_seconds",
"(",
")",
"<",
"max_age",
"return",
"is_fresh"
] |
Entry point for stand - alone execution .
|
def main ( ) : conf . init ( ) , db . init ( conf . DbPath ) inqueue = LineQueue ( sys . stdin ) . queue outqueue = type ( "" , ( ) , { "put" : lambda self , x : print ( "\r%s" % x , end = " " ) } ) ( ) if "--quiet" in sys . argv : outqueue = None if conf . MouseEnabled : inqueue . put ( "mouse_start" ) if conf . KeyboardEnabled : inqueue . put ( "keyboard_start" ) start ( inqueue , outqueue )
| 1,892
|
https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L269-L277
|
[
"def",
"upload_cbn_dir",
"(",
"dir_path",
",",
"manager",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"jfg_path",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"if",
"not",
"jfg_path",
".",
"endswith",
"(",
"'.jgf'",
")",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"jfg_path",
")",
"log",
".",
"info",
"(",
"'opening %s'",
",",
"path",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"cbn_jgif_dict",
"=",
"json",
".",
"load",
"(",
"f",
")",
"graph",
"=",
"pybel",
".",
"from_cbn_jgif",
"(",
"cbn_jgif_dict",
")",
"out_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"jfg_path",
".",
"replace",
"(",
"'.jgf'",
",",
"'.bel'",
")",
")",
"with",
"open",
"(",
"out_path",
",",
"'w'",
")",
"as",
"o",
":",
"pybel",
".",
"to_bel",
"(",
"graph",
",",
"o",
")",
"strip_annotations",
"(",
"graph",
")",
"enrich_pubmed_citations",
"(",
"manager",
"=",
"manager",
",",
"graph",
"=",
"graph",
")",
"pybel",
".",
"to_database",
"(",
"graph",
",",
"manager",
"=",
"manager",
")",
"log",
".",
"info",
"(",
"''",
")",
"log",
".",
"info",
"(",
"'done in %.2f'",
",",
"time",
".",
"time",
"(",
")",
"-",
"t",
")"
] |
Windows key event handler .
|
def _handle_windows ( self , event ) : vkey = self . _keyname ( event . GetKey ( ) ) if event . Message in self . KEYS_UP + self . KEYS_DOWN : if vkey in self . MODIFIERNAMES : self . _realmodifiers [ vkey ] = event . Message in self . KEYS_DOWN self . _modifiers [ self . MODIFIERNAMES [ vkey ] ] = self . _realmodifiers [ vkey ] if event . Message not in self . KEYS_DOWN : return True is_altgr = False if ( vkey , event . IsExtended ( ) ) in self . NUMPAD_SPECIALS : key = vkey = "Numpad-" + vkey elif not event . Ascii or vkey . startswith ( "Numpad" ) : key = vkey else : is_altgr = event . Ascii in self . ALT_GRS key = self . _keyname ( unichr ( event . Ascii ) ) if DEBUG : print ( "Adding key %s (real %s)" % ( key . encode ( "utf-8" ) , vkey . encode ( "utf-8" ) ) ) self . _output ( type = "keys" , key = key , realkey = vkey ) if vkey not in self . MODIFIERNAMES and not is_altgr : modifier = "-" . join ( k for k in [ "Ctrl" , "Alt" , "Shift" , "Win" ] if self . _modifiers [ k ] ) if modifier and modifier != "Shift" : # Shift-X is not a combo
if self . _modifiers [ "Ctrl" ] and event . Ascii : key = self . _keyname ( unichr ( event . KeyID ) ) realmodifier = "-" . join ( k for k , v in self . _realmodifiers . items ( ) if v ) realkey = "%s-%s" % ( realmodifier , key ) key = "%s-%s" % ( modifier , key ) if DEBUG : print ( "Adding combo %s (real %s)" % ( key . encode ( "utf-8" ) , realkey . encode ( "utf-8" ) ) ) self . _output ( type = "combos" , key = key , realkey = realkey ) if DEBUG : print ( "CHARACTER: %r" % key ) print ( 'GetKey: {0}' . format ( event . GetKey ( ) ) ) # Name of the virtual keycode, str
print ( 'IsAlt: {0}' . format ( event . IsAlt ( ) ) ) # Was the alt key depressed?, bool
print ( 'IsExtended: {0}' . format ( event . IsExtended ( ) ) ) # Is this an extended key?, bool
print ( 'IsInjected: {0}' . format ( event . IsInjected ( ) ) ) # Was this event generated programmatically?, bool
print ( 'IsTransition: {0}' . format ( event . IsTransition ( ) ) ) #Is this a transition from up to down or vice versa?, bool
print ( 'ASCII: {0}' . format ( event . Ascii ) ) # ASCII value, if one exists, str
print ( 'KeyID: {0}' . format ( event . KeyID ) ) # Virtual key code, int
print ( 'ScanCode: {0}' . format ( event . ScanCode ) ) # Scan code, int
print ( 'Message: {0}' . format ( event . Message ) ) # Name of the virtual keycode, str
print ( ) return True
| 1,893
|
https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L170-L216
|
[
"def",
"get_decompressed_waveform",
"(",
"self",
",",
"tempout",
",",
"index",
",",
"f_lower",
"=",
"None",
",",
"approximant",
"=",
"None",
",",
"df",
"=",
"None",
")",
":",
"from",
"pycbc",
".",
"waveform",
".",
"waveform",
"import",
"props",
"from",
"pycbc",
".",
"waveform",
"import",
"get_waveform_filter_length_in_time",
"# Get the template hash corresponding to the template index taken in as argument",
"tmplt_hash",
"=",
"self",
".",
"table",
".",
"template_hash",
"[",
"index",
"]",
"# Read the compressed waveform from the bank file",
"compressed_waveform",
"=",
"pycbc",
".",
"waveform",
".",
"compress",
".",
"CompressedWaveform",
".",
"from_hdf",
"(",
"self",
".",
"filehandler",
",",
"tmplt_hash",
",",
"load_now",
"=",
"True",
")",
"# Get the interpolation method to be used to decompress the waveform",
"if",
"self",
".",
"waveform_decompression_method",
"is",
"not",
"None",
":",
"decompression_method",
"=",
"self",
".",
"waveform_decompression_method",
"else",
":",
"decompression_method",
"=",
"compressed_waveform",
".",
"interpolation",
"logging",
".",
"info",
"(",
"\"Decompressing waveform using %s\"",
",",
"decompression_method",
")",
"if",
"df",
"is",
"not",
"None",
":",
"delta_f",
"=",
"df",
"else",
":",
"delta_f",
"=",
"self",
".",
"delta_f",
"# Create memory space for writing the decompressed waveform",
"decomp_scratch",
"=",
"FrequencySeries",
"(",
"tempout",
"[",
"0",
":",
"self",
".",
"filter_length",
"]",
",",
"delta_f",
"=",
"delta_f",
",",
"copy",
"=",
"False",
")",
"# Get the decompressed waveform",
"hdecomp",
"=",
"compressed_waveform",
".",
"decompress",
"(",
"out",
"=",
"decomp_scratch",
",",
"f_lower",
"=",
"f_lower",
",",
"interpolation",
"=",
"decompression_method",
")",
"p",
"=",
"props",
"(",
"self",
".",
"table",
"[",
"index",
"]",
")",
"p",
".",
"pop",
"(",
"'approximant'",
")",
"try",
":",
"tmpltdur",
"=",
"self",
".",
"table",
"[",
"index",
"]",
".",
"template_duration",
"except",
"AttributeError",
":",
"tmpltdur",
"=",
"None",
"if",
"tmpltdur",
"is",
"None",
"or",
"tmpltdur",
"==",
"0.0",
":",
"tmpltdur",
"=",
"get_waveform_filter_length_in_time",
"(",
"approximant",
",",
"*",
"*",
"p",
")",
"hdecomp",
".",
"chirp_length",
"=",
"tmpltdur",
"hdecomp",
".",
"length_in_time",
"=",
"hdecomp",
".",
"chirp_length",
"return",
"hdecomp"
] |
Mac key event handler
|
def _handle_mac ( self , keycode ) : key = self . _keyname ( unichr ( keycode ) ) self . _output ( type = "keys" , key = key , realkey = key )
| 1,894
|
https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L219-L222
|
[
"def",
"from_manifest",
"(",
"app",
",",
"filename",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not spend time here when testing",
"path",
"=",
"_manifests",
"[",
"app",
"]",
"[",
"filename",
"]",
"if",
"not",
"raw",
"and",
"cfg",
".",
"get",
"(",
"'CDN_DOMAIN'",
")",
"and",
"not",
"cfg",
".",
"get",
"(",
"'CDN_DEBUG'",
")",
":",
"scheme",
"=",
"'https'",
"if",
"cfg",
".",
"get",
"(",
"'CDN_HTTPS'",
")",
"else",
"request",
".",
"scheme",
"prefix",
"=",
"'{}://'",
".",
"format",
"(",
"scheme",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# CDN_DOMAIN has no trailing slash",
"path",
"=",
"'/'",
"+",
"path",
"return",
"''",
".",
"join",
"(",
"(",
"prefix",
",",
"cfg",
"[",
"'CDN_DOMAIN'",
"]",
",",
"path",
")",
")",
"elif",
"not",
"raw",
"and",
"kwargs",
".",
"get",
"(",
"'external'",
",",
"False",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# request.host_url has a trailing slash",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"return",
"''",
".",
"join",
"(",
"(",
"request",
".",
"host_url",
",",
"path",
")",
")",
"return",
"path"
] |
Linux key event handler .
|
def _handle_linux ( self , keycode , character , press ) : if character is None : return key = self . _keyname ( character , keycode ) if key in self . MODIFIERNAMES : self . _modifiers [ self . MODIFIERNAMES [ key ] ] = press self . _realmodifiers [ key ] = press if press : self . _output ( type = "keys" , key = key , realkey = key ) if press and key not in self . MODIFIERNAMES : modifier = "-" . join ( k for k in [ "Ctrl" , "Alt" , "Shift" , "Win" ] if self . _modifiers [ k ] ) if modifier and modifier != "Shift" : # Shift-X is not a combo
realmodifier = "-" . join ( k for k , v in self . _realmodifiers . items ( ) if v ) realkey = "%s-%s" % ( realmodifier , key ) key = "%s-%s" % ( modifier , key ) if DEBUG : print ( "Adding combo %s (real %s)" % ( key . encode ( "utf-8" ) , realkey . encode ( "utf-8" ) ) ) self . _output ( type = "combos" , key = key , realkey = realkey )
| 1,895
|
https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L224-L241
|
[
"def",
"get_decompressed_waveform",
"(",
"self",
",",
"tempout",
",",
"index",
",",
"f_lower",
"=",
"None",
",",
"approximant",
"=",
"None",
",",
"df",
"=",
"None",
")",
":",
"from",
"pycbc",
".",
"waveform",
".",
"waveform",
"import",
"props",
"from",
"pycbc",
".",
"waveform",
"import",
"get_waveform_filter_length_in_time",
"# Get the template hash corresponding to the template index taken in as argument",
"tmplt_hash",
"=",
"self",
".",
"table",
".",
"template_hash",
"[",
"index",
"]",
"# Read the compressed waveform from the bank file",
"compressed_waveform",
"=",
"pycbc",
".",
"waveform",
".",
"compress",
".",
"CompressedWaveform",
".",
"from_hdf",
"(",
"self",
".",
"filehandler",
",",
"tmplt_hash",
",",
"load_now",
"=",
"True",
")",
"# Get the interpolation method to be used to decompress the waveform",
"if",
"self",
".",
"waveform_decompression_method",
"is",
"not",
"None",
":",
"decompression_method",
"=",
"self",
".",
"waveform_decompression_method",
"else",
":",
"decompression_method",
"=",
"compressed_waveform",
".",
"interpolation",
"logging",
".",
"info",
"(",
"\"Decompressing waveform using %s\"",
",",
"decompression_method",
")",
"if",
"df",
"is",
"not",
"None",
":",
"delta_f",
"=",
"df",
"else",
":",
"delta_f",
"=",
"self",
".",
"delta_f",
"# Create memory space for writing the decompressed waveform",
"decomp_scratch",
"=",
"FrequencySeries",
"(",
"tempout",
"[",
"0",
":",
"self",
".",
"filter_length",
"]",
",",
"delta_f",
"=",
"delta_f",
",",
"copy",
"=",
"False",
")",
"# Get the decompressed waveform",
"hdecomp",
"=",
"compressed_waveform",
".",
"decompress",
"(",
"out",
"=",
"decomp_scratch",
",",
"f_lower",
"=",
"f_lower",
",",
"interpolation",
"=",
"decompression_method",
")",
"p",
"=",
"props",
"(",
"self",
".",
"table",
"[",
"index",
"]",
")",
"p",
".",
"pop",
"(",
"'approximant'",
")",
"try",
":",
"tmpltdur",
"=",
"self",
".",
"table",
"[",
"index",
"]",
".",
"template_duration",
"except",
"AttributeError",
":",
"tmpltdur",
"=",
"None",
"if",
"tmpltdur",
"is",
"None",
"or",
"tmpltdur",
"==",
"0.0",
":",
"tmpltdur",
"=",
"get_waveform_filter_length_in_time",
"(",
"approximant",
",",
"*",
"*",
"p",
")",
"hdecomp",
".",
"chirp_length",
"=",
"tmpltdur",
"hdecomp",
".",
"length_in_time",
"=",
"hdecomp",
".",
"chirp_length",
"return",
"hdecomp"
] |
Stores all documents on the file system .
|
def _store_documentation ( self , path , html , overwrite , quiet ) : echo ( "Storing groundwork application documents\n" ) echo ( "Application: %s" % self . app . name ) echo ( "Number of documents: %s\n" % len ( self . app . documents . get ( ) ) ) if not os . path . isabs ( path ) : path = os . path . abspath ( path ) if not os . path . isdir ( path ) : echo ( "Path %s is not a directory!" % path ) sys . exit ( 1 ) if not os . path . exists ( path ) : echo ( "Path %s does not exist" % path ) sys . exit ( 1 ) for dirpath , dirnames , files in os . walk ( path ) : if files : echo ( "Path %s is not empty!\n" % path ) if not overwrite : sys . exit ( 1 ) documents = [ ] for key , document in self . app . documents . get ( ) . items ( ) : file_extension = ".html" if html else ".rst" # lowers the name, removes all whitespaces and adds the file extension file_name_parts = key . lower ( ) . split ( ) file_name = "" . join ( file_name_parts ) file_name += file_extension documents . append ( ( file_name , document ) ) echo ( "Going to write to following files:" ) for document in documents : echo ( " %s" % document [ 0 ] ) echo ( "\nTarget directory: %s" % path ) answer = None while answer not in [ "N" , "Y" ] and not quiet : answer = prompt ( "Shall we go on? [Y]es, [N]o: " ) . upper ( ) if answer == "N" : sys . exit ( 0 ) for document in documents : try : with open ( os . path . join ( path , document [ 0 ] ) , "w" ) as doc_file : doc_rendered = Environment ( ) . from_string ( document [ 1 ] . content ) . render ( app = self . app , plugin = document [ 1 ] . plugin ) if html : output = publish_parts ( doc_rendered , writer_name = "html" ) [ 'whole' ] else : output = doc_rendered doc_file . write ( output ) except Exception as e : echo ( "%s error occurred: %s" % ( document [ 0 ] , e ) ) else : echo ( "%s stored." % document [ 0 ] )
| 1,896
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/plugins/gw_documents_info.py#L86-L150
|
[
"def",
"get_time_to_merge_request_response",
"(",
"self",
",",
"item",
")",
":",
"review_dates",
"=",
"[",
"str_to_datetime",
"(",
"review",
"[",
"'created_at'",
"]",
")",
"for",
"review",
"in",
"item",
"[",
"'review_comments_data'",
"]",
"if",
"item",
"[",
"'user'",
"]",
"[",
"'login'",
"]",
"!=",
"review",
"[",
"'user'",
"]",
"[",
"'login'",
"]",
"]",
"if",
"review_dates",
":",
"return",
"min",
"(",
"review_dates",
")",
"return",
"None"
] |
Shows all documents of the current groundwork app in the console .
|
def _show_documentation ( self ) : documents = [ ] for key , document in self . app . documents . get ( ) . items ( ) : if key != "main" : documents . append ( ( key , document ) ) documents = sorted ( documents , key = lambda x : x [ 0 ] ) main = self . app . documents . get ( "main" ) if main is not None : documents . insert ( 0 , ( main . name , main ) ) user_answer = "" index = 0 while user_answer != "X" : if index < 0 : index = 0 if index > len ( documents ) - 1 : index = len ( documents ) - 1 document = documents [ index ] [ 1 ] os . system ( 'cls' if os . name == 'nt' else 'clear' ) echo ( Environment ( ) . from_string ( document . content ) . render ( app = self . app , plugin = document . plugin ) ) source = "This document is registered by '%s' under the name '%s'" % ( document . plugin . name , document . name ) echo ( "-" * len ( source ) ) echo ( source ) echo ( "-" * len ( source ) ) commands = "Actions: " if index < len ( documents ) - 1 : commands += "[N]ext, " if index > 0 : commands += "[P]revious, " commands += "E[x]it" echo ( commands ) if index < len ( documents ) - 1 : default = "N" elif index > 0 : default = "P" else : default = "X" user_answer = prompt ( "Select your action" , default = default ) . upper ( ) if user_answer == "N" : index += 1 elif user_answer == "P" : index -= 1
| 1,897
|
https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/plugins/gw_documents_info.py#L152-L202
|
[
"def",
"_decayPoolingActivation",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decayFunctionType",
"==",
"'NoDecay'",
":",
"self",
".",
"_poolingActivation",
"=",
"self",
".",
"_decayFunction",
".",
"decay",
"(",
"self",
".",
"_poolingActivation",
")",
"elif",
"self",
".",
"_decayFunctionType",
"==",
"'Exponential'",
":",
"self",
".",
"_poolingActivation",
"=",
"self",
".",
"_decayFunction",
".",
"decay",
"(",
"self",
".",
"_poolingActivationInitLevel",
",",
"self",
".",
"_poolingTimer",
")",
"return",
"self",
".",
"_poolingActivation"
] |
Execute several cleanup tasks as part of the cleanup .
|
def execute_cleanup_tasks ( ctx , cleanup_tasks , dry_run = False ) : # pylint: disable=redefined-outer-name executor = Executor ( cleanup_tasks , ctx . config ) for cleanup_task in cleanup_tasks . tasks : print ( "CLEANUP TASK: %s" % cleanup_task ) executor . execute ( ( cleanup_task , dict ( dry_run = dry_run ) ) )
| 1,898
|
https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/tasks/_tasklet_cleanup.py#L70-L83
|
[
"def",
"parse_file",
"(",
"self",
",",
"sg_file",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"sg_file",
"is",
"not",
"None",
"and",
"data",
"is",
"not",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"You must pass either a path to an sgf file or the sgf contents but not both\"",
")",
"if",
"sg_file",
"is",
"None",
"and",
"data",
"is",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"You must pass either a path to an sgf file or the sgf contents, neither passed\"",
")",
"if",
"sg_file",
"is",
"not",
"None",
":",
"try",
":",
"with",
"open",
"(",
"sg_file",
",",
"\"r\"",
")",
"as",
"inf",
":",
"data",
"=",
"inf",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"raise",
"ArgumentError",
"(",
"\"Could not read sensor graph file\"",
",",
"path",
"=",
"sg_file",
")",
"# convert tabs to spaces so our line numbers match correctly",
"data",
"=",
"data",
".",
"replace",
"(",
"u'\\t'",
",",
"u' '",
")",
"lang",
"=",
"get_language",
"(",
")",
"result",
"=",
"lang",
".",
"parseString",
"(",
"data",
")",
"for",
"statement",
"in",
"result",
":",
"parsed",
"=",
"self",
".",
"parse_statement",
"(",
"statement",
",",
"orig_contents",
"=",
"data",
")",
"self",
".",
"statements",
".",
"append",
"(",
"parsed",
")"
] |
Returns the Entry Point for a given Entry Point section .
|
def entrypoints ( section ) : return { ep . name : ep . load ( ) for ep in pkg_resources . iter_entry_points ( section ) }
| 1,899
|
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/entrypoints.py#L12-L19
|
[
"def",
"surviors_are_inconsistent",
"(",
"survivor_mapping",
":",
"Mapping",
"[",
"BaseEntity",
",",
"Set",
"[",
"BaseEntity",
"]",
"]",
")",
"->",
"Set",
"[",
"BaseEntity",
"]",
":",
"victim_mapping",
"=",
"set",
"(",
")",
"for",
"victim",
"in",
"itt",
".",
"chain",
".",
"from_iterable",
"(",
"survivor_mapping",
".",
"values",
"(",
")",
")",
":",
"if",
"victim",
"in",
"survivor_mapping",
":",
"victim_mapping",
".",
"add",
"(",
"victim",
")",
"return",
"victim_mapping"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.