query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Combine arrays using mix max rejection with masks .
def minmax ( arrays , masks = None , dtype = None , out = None , zeros = None , scales = None , weights = None , nmin = 1 , nmax = 1 ) : return generic_combine ( intl_combine . minmax_method ( nmin , nmax ) , arrays , masks = masks , dtype = dtype , out = out , zeros = zeros , scales = scales , weights = weights )
4,100
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L115-L138
[ "def", "YamlDumper", "(", "aff4object", ")", ":", "aff4object", ".", "Flush", "(", ")", "result", "=", "{", "}", "for", "attribute", ",", "values", "in", "iteritems", "(", "aff4object", ".", "synced_attributes", ")", ":", "result", "[", "attribute", ".", "predicate", "]", "=", "[", "]", "for", "value", "in", "values", ":", "# This value is really a LazyDecoder() instance. We need to get at the", "# real data here.", "value", "=", "value", ".", "ToRDFValue", "(", ")", "result", "[", "attribute", ".", "predicate", "]", ".", "append", "(", "[", "value", ".", "__class__", ".", "__name__", ",", "value", ".", "SerializeToString", "(", ")", ",", "str", "(", "value", ".", "age", ")", "]", ")", "return", "yaml", ".", "Dump", "(", "{", "\"aff4_class\"", ":", "compatibility", ".", "GetName", "(", "aff4object", ")", ",", "\"_urn\"", ":", "aff4object", ".", "urn", ".", "SerializeToString", "(", ")", ",", "\"attributes\"", ":", "result", ",", "\"age_policy\"", ":", "aff4object", ".", "age_policy", ",", "}", ")" ]
Combine flat arrays .
def flatcombine ( arrays , masks = None , dtype = None , scales = None , low = 3.0 , high = 3.0 , blank = 1.0 ) : result = sigmaclip ( arrays , masks = masks , dtype = dtype , scales = scales , low = low , high = high ) # Substitute values <= 0 by blank mm = result [ 0 ] <= 0 result [ 0 , mm ] = blank # Add values to mask result [ 1 : 2 , mm ] = 0 return result
4,101
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L166-L188
[ "def", "delete", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "customer", ",", "_created", "=", "Customer", ".", "get_or_create", "(", "subscriber", "=", "subscriber_request_callback", "(", "self", ".", "request", ")", ")", "customer", ".", "subscription", ".", "cancel", "(", "at_period_end", "=", "CANCELLATION_AT_PERIOD_END", ")", "return", "Response", "(", "status", "=", "status", ".", "HTTP_204_NO_CONTENT", ")", "except", "Exception", ":", "return", "Response", "(", "\"Something went wrong cancelling the subscription.\"", ",", "status", "=", "status", ".", "HTTP_400_BAD_REQUEST", ",", ")" ]
Combine zero arrays .
def zerocombine ( arrays , masks , dtype = None , scales = None ) : result = median ( arrays , masks = masks , dtype = dtype , scales = scales ) return result
4,102
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L191-L204
[ "def", "delete", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "customer", ",", "_created", "=", "Customer", ".", "get_or_create", "(", "subscriber", "=", "subscriber_request_callback", "(", "self", ".", "request", ")", ")", "customer", ".", "subscription", ".", "cancel", "(", "at_period_end", "=", "CANCELLATION_AT_PERIOD_END", ")", "return", "Response", "(", "status", "=", "status", ".", "HTTP_204_NO_CONTENT", ")", "except", "Exception", ":", "return", "Response", "(", "\"Something went wrong cancelling the subscription.\"", ",", "status", "=", "status", ".", "HTTP_400_BAD_REQUEST", ",", ")" ]
Combine arrays by addition with masks and offsets .
def sum ( arrays , masks = None , dtype = None , out = None , zeros = None , scales = None ) : return generic_combine ( intl_combine . sum_method ( ) , arrays , masks = masks , dtype = dtype , out = out , zeros = zeros , scales = scales )
4,103
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L207-L242
[ "def", "defBoundary", "(", "self", ")", ":", "self", ".", "BoroCnstNatAll", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "# Find the natural borrowing constraint conditional on next period's state", "for", "j", "in", "range", "(", "self", ".", "StateCount", ")", ":", "PermShkMinNext", "=", "np", ".", "min", "(", "self", ".", "IncomeDstn_list", "[", "j", "]", "[", "1", "]", ")", "TranShkMinNext", "=", "np", ".", "min", "(", "self", ".", "IncomeDstn_list", "[", "j", "]", "[", "2", "]", ")", "self", ".", "BoroCnstNatAll", "[", "j", "]", "=", "(", "self", ".", "solution_next", ".", "mNrmMin", "[", "j", "]", "-", "TranShkMinNext", ")", "*", "(", "self", ".", "PermGroFac_list", "[", "j", "]", "*", "PermShkMinNext", ")", "/", "self", ".", "Rfree_list", "[", "j", "]", "self", ".", "BoroCnstNat_list", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "self", ".", "mNrmMin_list", "=", "np", ".", "zeros", "(", "self", ".", "StateCount", ")", "+", "np", ".", "nan", "self", ".", "BoroCnstDependency", "=", "np", ".", "zeros", "(", "(", "self", ".", "StateCount", ",", "self", ".", "StateCount", ")", ")", "+", "np", ".", "nan", "# The natural borrowing constraint in each current state is the *highest*", "# among next-state-conditional natural borrowing constraints that could", "# occur from this current state.", "for", "i", "in", "range", "(", "self", ".", "StateCount", ")", ":", "possible_next_states", "=", "self", ".", "MrkvArray", "[", "i", ",", ":", "]", ">", "0", "self", ".", "BoroCnstNat_list", "[", "i", "]", "=", "np", ".", "max", "(", "self", ".", "BoroCnstNatAll", "[", "possible_next_states", "]", ")", "# Explicitly handle the \"None\" case: ", "if", "self", ".", "BoroCnstArt", "is", "None", ":", "self", ".", "mNrmMin_list", "[", "i", "]", "=", "self", ".", "BoroCnstNat_list", "[", "i", "]", "else", ":", "self", ".", "mNrmMin_list", "[", "i", "]", "=", "np", ".", "max", "(", "[", "self", ".", "BoroCnstNat_list", "[", "i", "]", ",", "self", ".", "BoroCnstArt", "]", ")", "self", ".", "BoroCnstDependency", "[", "i", ",", ":", "]", "=", "self", ".", "BoroCnstNat_list", "[", "i", "]", "==", "self", ".", "BoroCnstNatAll" ]
Stack arrays using different methods .
def generic_combine ( method , arrays , masks = None , dtype = None , out = None , zeros = None , scales = None , weights = None ) : arrays = [ numpy . asarray ( arr , dtype = dtype ) for arr in arrays ] if masks is not None : masks = [ numpy . asarray ( msk ) for msk in masks ] if out is None : # Creating out if needed # We need three numbers try : outshape = ( 3 , ) + tuple ( arrays [ 0 ] . shape ) out = numpy . zeros ( outshape , dtype ) except AttributeError : raise TypeError ( 'First element in arrays does ' 'not have .shape attribute' ) else : out = numpy . asanyarray ( out ) intl_combine . generic_combine ( method , arrays , out [ 0 ] , out [ 1 ] , out [ 2 ] , masks , zeros , scales , weights ) return out
4,104
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L245-L281
[ "def", "future_set_exception_unless_cancelled", "(", "future", ":", "\"Union[futures.Future[_T], Future[_T]]\"", ",", "exc", ":", "BaseException", ")", "->", "None", ":", "if", "not", "future", ".", "cancelled", "(", ")", ":", "future", ".", "set_exception", "(", "exc", ")", "else", ":", "app_log", ".", "error", "(", "\"Exception after Future was cancelled\"", ",", "exc_info", "=", "exc", ")" ]
Compute the FWHM .
def compute_fwhm_1d_simple ( Y , xc , X = None ) : return compute_fw_at_frac_max_1d_simple ( Y , xc , X = X , f = 0.5 )
4,105
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/fwhm.py#L63-L65
[ "def", "associate_api_key_stagekeys", "(", "apiKey", ",", "stagekeyslist", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "pvlist", "=", "[", "(", "'/stages'", ",", "stagekey", ")", "for", "stagekey", "in", "stagekeyslist", "]", "response", "=", "_api_key_patch_add", "(", "conn", ",", "apiKey", ",", "pvlist", ")", "return", "{", "'associated'", ":", "True", ",", "'apiKey'", ":", "_convert_datetime_str", "(", "response", ")", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'associated'", ":", "False", ",", "'error'", ":", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "}" ]
Compute the full width at fraction f of the maximum
def compute_fw_at_frac_max_1d_simple ( Y , xc , X = None , f = 0.5 ) : yy = np . asarray ( Y ) if yy . ndim != 1 : raise ValueError ( 'array must be 1-d' ) if yy . size == 0 : raise ValueError ( 'array is empty' ) if X is None : xx = np . arange ( yy . shape [ 0 ] ) else : xx = X xpix = coor_to_pix_1d ( xc - xx [ 0 ] ) try : peak = yy [ xpix ] except IndexError : raise ValueError ( 'peak is out of array' ) fwhm_x , _codex , _msgx = compute_fwhm_1d ( xx , yy - f * peak , xc , xpix ) return peak , fwhm_x
4,106
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/fwhm.py#L68-L92
[ "def", "start_journaling", "(", "self", ")", ":", "import", "numpy", ".", "distutils", ".", "ccompiler", "if", "self", ".", "journal_file", "is", "None", ":", "return", "def", "journaled_spawn", "(", "patched_self", ",", "cmd", ",", "display", "=", "None", ")", ":", "self", ".", "commands", ".", "append", "(", "cmd", ")", "return", "numpy", ".", "distutils", ".", "ccompiler", ".", "CCompiler_spawn", "(", "patched_self", ",", "cmd", ",", "display", "=", "None", ")", "numpy", ".", "distutils", ".", "ccompiler", ".", "replace_method", "(", "distutils", ".", "ccompiler", ".", "CCompiler", ",", "\"spawn\"", ",", "journaled_spawn", ")" ]
Compute r12 using linear interpolation .
def _fwhm_side_lineal ( uu , vv ) : res1 , = np . nonzero ( vv < 0 ) if len ( res1 ) == 0 : return 0 , 1 # error, no negative value else : # first value i2 = res1 [ 0 ] i1 = i2 - 1 dx = uu [ i2 ] - uu [ i1 ] dy = vv [ i2 ] - vv [ i1 ] r12 = uu [ i1 ] - vv [ i1 ] * dx / dy return r12 , 0
4,107
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/fwhm.py#L95-L107
[ "def", "__getBio", "(", "self", ",", "web", ")", ":", "bio", "=", "web", ".", "find_all", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"user-profile-bio\"", "}", ")", "if", "bio", ":", "try", ":", "bio", "=", "bio", "[", "0", "]", ".", "text", "if", "bio", "and", "GitHubUser", ".", "isASCII", "(", "bio", ")", ":", "bioText", "=", "bio", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "bioText", "=", "bioText", ".", "replace", "(", "\"\\t\"", ",", "\" \"", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"\"", ")", "bioText", "=", "bioText", ".", "replace", "(", "\"\\'\"", ",", "\"\"", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"\"", ")", "self", ".", "bio", "=", "bioText", "else", ":", "self", ".", "bio", "=", "\"\"", "except", "IndexError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")", "except", "AttributeError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")" ]
Returns the zero point energy from a list of frequencies .
def get_ZPE ( viblist ) : if type ( viblist ) is str : l = ast . literal_eval ( viblist ) else : l = viblist l = [ float ( w ) for w in l ] ZPE = 0.5 * sum ( l ) * cm2ev return ( ZPE )
4,108
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L276-L293
[ "def", "session_registration", "(", "uri", ",", "session", ")", ":", "# log the URI that is used to access the Stack-In-A-Box services", "logger", ".", "debug", "(", "'Registering Stack-In-A-Box at {0} under Python Requests-Mock'", ".", "format", "(", "uri", ")", ")", "logger", ".", "debug", "(", "'Session has id {0}'", ".", "format", "(", "id", "(", "session", ")", ")", ")", "# tell Stack-In-A-Box what URI to match with", "StackInABox", ".", "update_uri", "(", "uri", ")", "# Create a Python Requests Adapter object for handling the session", "StackInABox", ".", "hold_onto", "(", "'adapter'", ",", "requests_mock", ".", "Adapter", "(", ")", ")", "# Add the Request handler object for the URI", "StackInABox", ".", "hold_out", "(", "'adapter'", ")", ".", "add_matcher", "(", "RequestMockCallable", "(", "uri", ")", ")", "# Tell the session about the adapter and the URI", "session", ".", "mount", "(", "'http://{0}'", ".", "format", "(", "uri", ")", ",", "StackInABox", ".", "hold_out", "(", "'adapter'", ")", ")", "session", ".", "mount", "(", "'https://{0}'", ".", "format", "(", "uri", ")", ",", "StackInABox", ".", "hold_out", "(", "'adapter'", ")", ")" ]
Transforms atomic system information into well - formatted labels .
def auto_labels ( df ) : systems = list ( df . system ) facets = list ( df . facet ) systems_labels = [ w . replace ( '_' , '\ ' ) for w in systems ] systems_labels = [ sub ( w ) for w in systems_labels ] systems_labels = [ w . replace ( '}$$_{' , '' ) for w in systems_labels ] systems_labels = [ w . replace ( '$' , '' ) for w in systems_labels ] systems_labels = [ '$' + w + '$' for w in systems_labels ] facets_label = [ w . replace ( '_' , '\ ' ) for w in facets ] facets_label = [ '(' + w + ')' for w in facets_label ] labels = [ ] for i , sys in enumerate ( systems_labels ) : labels . append ( sys + facets_label [ i ] ) # labels = list(set(labels)) return ( labels )
4,109
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L295-L321
[ "def", "add_editor", "(", "self", ",", "username", ",", "_delete", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "reddit_session", ".", "config", "[", "'wiki_page_editor'", "]", "url", "=", "url", ".", "format", "(", "subreddit", "=", "six", ".", "text_type", "(", "self", ".", "subreddit", ")", ",", "method", "=", "'del'", "if", "_delete", "else", "'add'", ")", "data", "=", "{", "'page'", ":", "self", ".", "page", ",", "'username'", ":", "six", ".", "text_type", "(", "username", ")", "}", "return", "self", ".", "reddit_session", ".", "request_json", "(", "url", ",", "data", "=", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Returns the Gibbs free energy of proton in bulk solution .
def proton_hydroxide_free_energy ( temperature , pressure , pH ) : H2 = GasMolecule ( 'H2' ) H2O = GasMolecule ( 'H2O' ) G_H2 = H2 . get_free_energy ( temperature = temperature , pressure = pressure ) G_H2O = H2O . get_free_energy ( temperature = temperature ) G_H = ( 0.5 * G_H2 ) - ( ( R * temperature ) / ( z * F ) ) * ln10 * pH G_OH = G_H2O - G_H # Do not need Kw when water equilibrated return ( G_H , G_OH )
4,110
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L323-L344
[ "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" ]
Returns the Gibbs free energy corrections to be added to raw reaction energies .
def get_FEC ( molecule_list , temperature , pressure , electronic_energy = 'Default' ) : if not temperature or not pressure : return ( 0 ) else : molecule_list = [ m for m in molecule_list if m != 'star' ] # print(molecule_list) FEC_sum = [ ] for molecule in molecule_list : if 'gas' in molecule : mol = GasMolecule ( molecule . replace ( 'gas' , '' ) ) if pressure == 'Default' : p = mol . pressure else : p = pressure if electronic_energy == 'Default' : ee = mol . electronic_energy else : ee = electronic_energy FEC = mol . get_free_energy ( temperature = temperature , pressure = p , electronic_energy = ee ) FEC_sum . append ( FEC ) if 'star' in molecule : FEC = Adsorbate ( molecule . replace ( 'star' , '' ) ) FEC = FEC . get_helmholtz_energy ( temperature = temperature ) FEC_sum . append ( FEC ) FEC_sum = sum ( FEC_sum ) return ( FEC_sum )
4,111
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L346-L385
[ "def", "stop", "(", "self", ",", "message", ")", ":", "self", ".", "_stop", "=", "time", ".", "clock", "(", ")", "VSGLogger", ".", "info", "(", "\"{0:<20} - Finished [{1}s]\"", ".", "format", "(", "message", ",", "self", ".", "pprint", "(", "self", ".", "_stop", "-", "self", ".", "_start", ")", ")", ")" ]
Gathers relevant data from SQL database generated by CATHUB .
def select_data ( db_file , slab = None , facet = None ) : con = sql . connect ( db_file ) cur = con . cursor ( ) if slab and facet : select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' 'from reaction where facet=' + str ( facet ) + ' and chemical_composition LIKE "%' + slab + '%";' elif slab and not facet : select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' 'from reaction where chemical_composition LIKE "%' + slab + '%";' else : select_command = 'select chemical_composition, facet, reactants, products, reaction_energy from reaction;' cur . execute ( select_command ) data = cur . fetchall ( ) return ( data )
4,112
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L476-L501
[ "def", "delete_share", "(", "self", ",", "share_name", ",", "fail_not_exist", "=", "False", ",", "timeout", "=", "None", ",", "snapshot", "=", "None", ",", "delete_snapshots", "=", "None", ")", ":", "_validate_not_none", "(", "'share_name'", ",", "share_name", ")", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", "=", "'DELETE'", "request", ".", "host_locations", "=", "self", ".", "_get_host_locations", "(", ")", "request", ".", "path", "=", "_get_path", "(", "share_name", ")", "request", ".", "headers", "=", "{", "'x-ms-delete-snapshots'", ":", "_to_str", "(", "delete_snapshots", ")", "}", "request", ".", "query", "=", "{", "'restype'", ":", "'share'", ",", "'timeout'", ":", "_int_to_str", "(", "timeout", ")", ",", "'sharesnapshot'", ":", "_to_str", "(", "snapshot", ")", ",", "}", "if", "not", "fail_not_exist", ":", "try", ":", "self", ".", "_perform_request", "(", "request", ",", "expected_errors", "=", "[", "_SHARE_NOT_FOUND_ERROR_CODE", "]", ")", "return", "True", "except", "AzureHttpError", "as", "ex", ":", "_dont_fail_not_exist", "(", "ex", ")", "return", "False", "else", ":", "self", ".", "_perform_request", "(", "request", ")", "return", "True" ]
Read in file and return pandas data_frame .
def file_to_df ( file_name ) : filename , file_extension = os . path . splitext ( file_name ) if file_extension == '.csv' : df = pd . read_csv ( file_name , sep = ',' , header = 0 ) . iloc [ : , 1 : ] elif file_extension == '.tsv' : df = pd . read_csv ( file_name , sep = '\t' , header = 0 ) . iloc [ : , 1 : ] else : print ( 'Please provide valid csv or tsv file format with header names.' ) return ( df )
4,113
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L503-L521
[ "def", "user_deleted_from_site_event", "(", "event", ")", ":", "userid", "=", "event", ".", "principal", "catalog", "=", "api", ".", "portal", ".", "get_tool", "(", "'portal_catalog'", ")", "query", "=", "{", "'object_provides'", ":", "WORKSPACE_INTERFACE", "}", "query", "[", "'workspace_members'", "]", "=", "userid", "workspaces", "=", "[", "IWorkspace", "(", "b", ".", "_unrestrictedGetObject", "(", ")", ")", "for", "b", "in", "catalog", ".", "unrestrictedSearchResults", "(", "query", ")", "]", "for", "workspace", "in", "workspaces", ":", "workspace", ".", "remove_from_team", "(", "userid", ")" ]
Transforms database to data frame .
def db_to_df ( db_file , slabs = None , facet = None ) : systems = [ ] data = [ ] if slabs : for slab in slabs : data_tmp = select_data ( db_file , slab = slab , facet = facet ) data . append ( data_tmp ) subsystem = [ tup [ 0 ] for i , tup in enumerate ( data_tmp ) ] systems . append ( list ( set ( subsystem ) ) [ 0 ] ) else : data_tmp = select_data ( db_file ) data . append ( data_tmp ) df = pd . DataFrame ( ) system , facet , reactants , products , reaction_energy = [ ] , [ ] , [ ] , [ ] , [ ] for entry in data : for reaction in entry : system . append ( str ( reaction [ 0 ] ) ) facet . append ( str ( reaction [ 1 ] ) ) reactants_i = [ molecule for molecule in ast . literal_eval ( reaction [ 2 ] ) . keys ( ) ] reactants . append ( reactants_i ) products_i = [ molecule for molecule in ast . literal_eval ( reaction [ 3 ] ) . keys ( ) ] products . append ( products_i ) reaction_energy . append ( float ( reaction [ 4 ] ) ) df [ 0 ] = system df [ 1 ] = facet df [ 2 ] = reactants df [ 4 ] = products df [ 5 ] = reaction_energy df . columns = [ 'system' , 'facet' , 'reactants' , 'products' , 'reaction_energy' ] labs = auto_labels ( df ) df [ 'labels' ] = labs df = df . sort_values ( by = [ 'facet' , 'system' ] ) df = df . reset_index ( drop = True ) return ( df )
4,114
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L523-L571
[ "def", "cfg", "(", "self", ")", ":", "config", "=", "LStruct", "(", "self", ".", "defaults", ")", "module", "=", "config", "[", "'CONFIG'", "]", "=", "os", ".", "environ", ".", "get", "(", "CONFIGURATION_ENVIRON_VARIABLE", ",", "config", "[", "'CONFIG'", "]", ")", "if", "module", ":", "try", ":", "module", "=", "import_module", "(", "module", ")", "config", ".", "update", "(", "{", "name", ":", "getattr", "(", "module", ",", "name", ")", "for", "name", "in", "dir", "(", "module", ")", "if", "name", "==", "name", ".", "upper", "(", ")", "and", "not", "name", ".", "startswith", "(", "'_'", ")", "}", ")", "except", "ImportError", "as", "exc", ":", "config", ".", "CONFIG", "=", "None", "self", ".", "logger", ".", "error", "(", "\"Error importing %s: %s\"", ",", "module", ",", "exc", ")", "# Patch configuration from ENV", "for", "name", "in", "config", ":", "if", "name", ".", "startswith", "(", "'_'", ")", "or", "name", "!=", "name", ".", "upper", "(", ")", "or", "name", "not", "in", "os", ".", "environ", ":", "continue", "try", ":", "config", "[", "name", "]", "=", "json", ".", "loads", "(", "os", ".", "environ", "[", "name", "]", ")", "except", "ValueError", ":", "pass", "return", "config" ]
Identifies unique elementary reactions in data frame .
def unique_reactions ( df ) : reaction_list = [ ] for idx , entry in enumerate ( df [ 'reactants' ] ) : reaction = [ ] for x in entry : reaction . append ( x ) reaction . append ( '-->' ) for y in df [ 'products' ] [ idx ] : reaction . append ( y ) reaction_list . append ( reaction ) string_list = [ str ( reaction ) for reaction in reaction_list ] string_list = sorted ( list ( set ( string_list ) ) ) reaction_list = [ ast . literal_eval ( entry ) for entry in string_list ] return ( reaction_list )
4,115
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L573-L596
[ "def", "cancel_job", "(", "self", ",", "id_job", ",", "hub", "=", "None", ",", "group", "=", "None", ",", "project", "=", "None", ",", "access_token", "=", "None", ",", "user_id", "=", "None", ")", ":", "if", "access_token", ":", "self", ".", "req", ".", "credential", ".", "set_token", "(", "access_token", ")", "if", "user_id", ":", "self", ".", "req", ".", "credential", ".", "set_user_id", "(", "user_id", ")", "if", "not", "self", ".", "check_credentials", "(", ")", ":", "respond", "=", "{", "}", "respond", "[", "\"status\"", "]", "=", "'Error'", "respond", "[", "\"error\"", "]", "=", "\"Not credentials valid\"", "return", "respond", "if", "not", "id_job", ":", "respond", "=", "{", "}", "respond", "[", "\"status\"", "]", "=", "'Error'", "respond", "[", "\"error\"", "]", "=", "\"Job ID not specified\"", "return", "respond", "url", "=", "get_job_url", "(", "self", ".", "config", ",", "hub", ",", "group", ",", "project", ")", "url", "+=", "'/{}/cancel'", ".", "format", "(", "id_job", ")", "res", "=", "self", ".", "req", ".", "post", "(", "url", ")", "return", "res" ]
Returns the Helmholtz energy of an adsorbed molecule .
def get_helmholtz_energy ( self , temperature , electronic_energy = 0 , verbose = False ) : thermo_object = HarmonicThermo ( vib_energies = self . vib_energies , potentialenergy = electronic_energy ) self . helmholtz_energy = thermo_object . get_helmholtz_energy ( temperature = temperature , verbose = verbose ) return ( self . helmholtz_energy )
4,116
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L131-L151
[ "def", "_read_para_reg_failed", "(", "self", ",", "code", ",", "cbit", ",", "clen", ",", "*", ",", "desc", ",", "length", ",", "version", ")", ":", "_life", "=", "collections", ".", "namedtuple", "(", "'Lifetime'", ",", "(", "'min'", ",", "'max'", ")", ")", "_mint", "=", "self", ".", "_read_unpack", "(", "1", ")", "_maxt", "=", "self", ".", "_read_unpack", "(", "1", ")", "_type", "=", "list", "(", ")", "for", "_", "in", "range", "(", "clen", "-", "2", ")", ":", "_code", "=", "self", ".", "_read_unpack", "(", "1", ")", "_kind", "=", "_REG_FAILURE_TYPE", ".", "get", "(", "_code", ")", "if", "_kind", "is", "None", ":", "if", "0", "<=", "_code", "<=", "200", ":", "_kind", "=", "'Unassigned (IETF Review)'", "elif", "201", "<=", "_code", "<=", "255", ":", "_kind", "=", "'Unassigned (Reserved for Private Use)'", "else", ":", "raise", "ProtocolError", "(", "f'HIPv{version}: [Parano {code}] invalid format'", ")", "_type", ".", "append", "(", "_kind", ")", "reg_failed", "=", "dict", "(", "type", "=", "desc", ",", "critical", "=", "cbit", ",", "length", "=", "clen", ",", "lifetime", "=", "_life", "(", "_mint", ",", "_maxt", ")", ",", "reg_type", "=", "tuple", "(", "_type", ")", ",", ")", "_plen", "=", "length", "-", "clen", "if", "_plen", ":", "self", ".", "_read_fileng", "(", "_plen", ")", "return", "reg_failed" ]
Returns a list of vibration in energy units eV .
def get_vib_energies ( self ) : vibs = self . molecule_dict [ self . name ] [ 'vibrations' ] vibs = np . array ( vibs ) * cm2ev return ( vibs )
4,117
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L265-L274
[ "def", "on_complete", "(", "cls", ",", "req", ")", ":", "# handle http errors", "if", "not", "(", "req", ".", "status", "==", "200", "or", "req", ".", "status", "==", "0", ")", ":", "alert", "(", "\"Couldn't connect to authority base.\"", ")", "LogView", ".", "add", "(", "\"Error when calling Aleph authority base: %s\"", "%", "req", ".", "text", ")", "AuthorBar", ".", "hide", "(", ")", "return", "AuthorBar", ".", "hide", "(", ")", "cls", ".", "set_select", "(", "json", ".", "loads", "(", "req", ".", "text", ")", ")" ]
Sets up intermediates and specifies whether it s an electrochemical step . Either provide individual contributions or net contributions . If both are given only the net contributions are used .
def set_intermediates ( self , intermediates , betas = None , transition_states = None ) : self . intermediates = intermediates self . betas = betas self . transition_states = transition_states if self . corrections is None : self . net_corrections = [ 0.0 for _ in intermediates ] if not self . betas : self . betas = [ 0.0 for _ in intermediates ] if not self . transition_states : self . transition_states = [ False for _ in intermediates ] # check if all lists have same length: props = [ len ( self . intermediates ) , len ( self . net_corrections ) , len ( self . transition_states ) , len ( self . betas ) ] if not len ( set ( props ) ) <= 1 : raise ValueError ( 'intermediate, net_corrections, transition_states and , ' 'betas all have to have the same length' ) self . get_corrections ( ) return ( True )
4,118
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L689-L721
[ "def", "_get_entity_by_class", "(", "self", ",", "entity_cls", ")", ":", "entity_qualname", "=", "fully_qualified_name", "(", "entity_cls", ")", "if", "entity_qualname", "in", "self", ".", "_registry", ":", "return", "self", ".", "_registry", "[", "entity_qualname", "]", "else", ":", "return", "self", ".", "_find_entity_in_records_by_class_name", "(", "entity_cls", ".", "__name__", ")" ]
Return the current debugger instance or create if none .
def debugger ( ) : sdb = _current [ 0 ] if sdb is None or not sdb . active : sdb = _current [ 0 ] = Sdb ( ) return sdb
4,119
https://github.com/ryanpetrello/sdb/blob/4a198757a17e753ac88081d192ecc952b4228a36/sdb.py#L268-L273
[ "def", "create_calcs", "(", "self", ")", ":", "specs", "=", "self", ".", "_combine_core_aux_specs", "(", ")", "for", "spec", "in", "specs", ":", "spec", "[", "'dtype_out_time'", "]", "=", "_prune_invalid_time_reductions", "(", "spec", ")", "return", "[", "Calc", "(", "*", "*", "sp", ")", "for", "sp", "in", "specs", "]" ]
Compute matches when text is a simple name . Return a list of all keywords built - in functions and names currently defined in self . namespace that match .
def global_matches ( self , text ) : matches = [ ] n = len ( text ) for word in self . namespace : if word [ : n ] == text and word != "__builtins__" : matches . append ( word ) return matches
4,120
https://github.com/ryanpetrello/sdb/blob/4a198757a17e753ac88081d192ecc952b4228a36/sdb.py#L65-L75
[ "def", "get_rng", "(", "obj", "=", "None", ")", ":", "seed", "=", "(", "id", "(", "obj", ")", "+", "os", ".", "getpid", "(", ")", "+", "int", "(", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y%m%d%H%M%S%f\"", ")", ")", ")", "%", "4294967295", "if", "_RNG_SEED", "is", "not", "None", ":", "seed", "=", "_RNG_SEED", "return", "np", ".", "random", ".", "RandomState", "(", "seed", ")" ]
decimal number to string .
def dec2str ( n ) : s = hex ( int ( n ) ) [ 2 : ] . rstrip ( 'L' ) if len ( s ) % 2 != 0 : s = '0' + s return hex2str ( s )
4,121
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L163-L170
[ "def", "deserialize_footer", "(", "stream", ",", "verifier", "=", "None", ")", ":", "_LOGGER", ".", "debug", "(", "\"Starting footer deserialization\"", ")", "signature", "=", "b\"\"", "if", "verifier", "is", "None", ":", "return", "MessageFooter", "(", "signature", "=", "signature", ")", "try", ":", "(", "sig_len", ",", ")", "=", "unpack_values", "(", "\">H\"", ",", "stream", ")", "(", "signature", ",", ")", "=", "unpack_values", "(", "\">{sig_len}s\"", ".", "format", "(", "sig_len", "=", "sig_len", ")", ",", "stream", ")", "except", "SerializationError", ":", "raise", "SerializationError", "(", "\"No signature found in message\"", ")", "if", "verifier", ":", "verifier", ".", "verify", "(", "signature", ")", "return", "MessageFooter", "(", "signature", "=", "signature", ")" ]
Binary to string .
def bin2str ( b ) : ret = [ ] for pos in range ( 0 , len ( b ) , 8 ) : ret . append ( chr ( int ( b [ pos : pos + 8 ] , 2 ) ) ) return '' . join ( ret )
4,122
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L183-L190
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Number to string .
def n2s ( n ) : s = hex ( n ) [ 2 : ] . rstrip ( "L" ) if len ( s ) % 2 != 0 : s = "0" + s return s . decode ( "hex" )
4,123
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L254-L261
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
String to binary .
def s2b ( s ) : ret = [ ] for c in s : ret . append ( bin ( ord ( c ) ) [ 2 : ] . zfill ( 8 ) ) return "" . join ( ret )
4,124
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L264-L271
[ "def", "_accountForNlinkEquals2", "(", "self", ",", "localFilePath", ")", ":", "fileStats", "=", "os", ".", "stat", "(", "localFilePath", ")", "assert", "fileStats", ".", "st_nlink", ">=", "self", ".", "nlinkThreshold", "with", "self", ".", "_CacheState", ".", "open", "(", "self", ")", "as", "cacheInfo", ":", "cacheInfo", ".", "sigmaJob", "-=", "fileStats", ".", "st_size", "jobState", "=", "self", ".", "_JobState", "(", "cacheInfo", ".", "jobState", "[", "self", ".", "jobID", "]", ")", "jobState", ".", "updateJobReqs", "(", "fileStats", ".", "st_size", ",", "'remove'", ")" ]
Convert an integer to a byte string .
def long_to_bytes ( n , blocksize = 0 ) : # after much testing, this algorithm was deemed to be the fastest s = b'' n = int ( n ) pack = struct . pack while n > 0 : s = pack ( '>I' , n & 0xffffffff ) + s n = n >> 32 # strip off leading zeros for i in range ( len ( s ) ) : if s [ i ] != b'\000' [ 0 ] : break else : # only happens when n == 0 s = b'\000' i = 0 s = s [ i : ] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and len ( s ) % blocksize : s = ( blocksize - len ( s ) % blocksize ) * b'\000' + s return s
4,125
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L287-L327
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Send a request to server .
def make_request ( endpoint , * * kwargs ) : data = kwargs . get ( 'json' , [ ] ) package = kwargs . get ( 'package' , None ) method = kwargs . get ( 'method' , 'GET' ) function = getattr ( requests , method . lower ( ) ) try : if package : response = function ( endpoint , data = data , files = { 'file' : package } ) else : response = function ( endpoint , json = data ) except requests . exceptions . ConnectionError : LOG . error ( "Couldn't connect to NApps server %s." , endpoint ) sys . exit ( 1 ) return response
4,126
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L33-L51
[ "def", "partition_by_vid", "(", "self", ",", "ref", ")", ":", "from", "ambry", ".", "orm", "import", "Partition", "p", "=", "self", ".", "session", ".", "query", "(", "Partition", ")", ".", "filter", "(", "Partition", ".", "vid", "==", "str", "(", "ref", ")", ")", ".", "first", "(", ")", "if", "p", ":", "return", "self", ".", "wrap_partition", "(", "p", ")", "else", ":", "return", "None" ]
Get all NApps from the server .
def get_napps ( self ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' ) res = self . make_request ( endpoint ) if res . status_code != 200 : msg = 'Error getting NApps from server (%s) - %s' LOG . error ( msg , res . status_code , res . reason ) sys . exit ( 1 ) return json . loads ( res . content . decode ( 'utf-8' ) ) [ 'napps' ]
4,127
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L57-L67
[ "def", "update", "(", "self", ",", "predicate_value", ",", "dct", ",", "upsert", "=", "False", ",", "attribute", "=", "\"_id\"", ")", ":", "if", "self", ".", "schema", ":", "jsonschema", ".", "validate", "(", "dct", ",", "self", ".", "schema", ")", "if", "attribute", "==", "\"_id\"", "and", "not", "isinstance", "(", "predicate_value", ",", "ObjectId", ")", ":", "predicate_value", "=", "ObjectId", "(", "predicate_value", ")", "predicate", "=", "{", "attribute", ":", "predicate_value", "}", "dct", "=", "self", ".", "_dictionary_to_cursor", "(", "dct", ")", "mongo_response", "=", "yield", "self", ".", "collection", ".", "update", "(", "predicate", ",", "dct", ",", "upsert", ")", "raise", "Return", "(", "self", ".", "_obj_cursor_to_dictionary", "(", "mongo_response", ")", ")" ]
Return napp metadata or None if not found .
def get_napp ( self , username , name ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , username , name , '' ) res = self . make_request ( endpoint ) if res . status_code == 404 : # We need to know if NApp is not found return None if res . status_code != 200 : msg = 'Error getting %s/%s from server: (%d) - %s' raise KytosException ( msg % ( username , name , res . status_code , res . reason ) ) return json . loads ( res . content )
4,128
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L69-L80
[ "def", "_FlushEvents", "(", "self", ")", ":", "try", ":", "# pylint: disable=unexpected-keyword-arg", "# pylint does not recognizes request_timeout as a valid kwarg. According", "# to http://elasticsearch-py.readthedocs.io/en/master/api.html#timeout", "# it should be supported.", "self", ".", "_client", ".", "bulk", "(", "body", "=", "self", ".", "_event_documents", ",", "doc_type", "=", "self", ".", "_document_type", ",", "index", "=", "self", ".", "_index_name", ",", "request_timeout", "=", "self", ".", "_DEFAULT_REQUEST_TIMEOUT", ")", "except", "ValueError", "as", "exception", ":", "# Ignore problematic events", "logger", ".", "warning", "(", "'Unable to bulk insert with error: {0!s}'", ".", "format", "(", "exception", ")", ")", "logger", ".", "debug", "(", "'Inserted {0:d} events into Elasticsearch'", ".", "format", "(", "self", ".", "_number_of_buffered_events", ")", ")", "self", ".", "_event_documents", "=", "[", "]", "self", ".", "_number_of_buffered_events", "=", "0" ]
Reload a specific NApp or all Napps .
def reload_napps ( self , napps = None ) : if napps is None : napps = [ ] api = self . _config . get ( 'kytos' , 'api' ) endpoint = os . path . join ( api , 'api' , 'kytos' , 'core' , 'reload' , 'all' ) response = self . make_request ( endpoint ) for napp in napps : api = self . _config . get ( 'kytos' , 'api' ) endpoint = os . path . join ( api , 'api' , 'kytos' , 'core' , 'reload' , napp [ 0 ] , napp [ 1 ] ) response = self . make_request ( endpoint ) if response . status_code != 200 : raise KytosException ( 'Error reloading the napp: Module not founded' ' or could not be imported' ) return response . content
4,129
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L82-L108
[ "def", "_load_candidate_wrapper", "(", "self", ",", "source_file", "=", "None", ",", "source_config", "=", "None", ",", "dest_file", "=", "None", ",", "file_system", "=", "None", ")", ":", "return_status", "=", "False", "msg", "=", "''", "if", "source_file", "and", "source_config", ":", "raise", "ValueError", "(", "\"Cannot simultaneously set source_file and source_config\"", ")", "if", "source_config", ":", "if", "self", ".", "inline_transfer", ":", "(", "return_status", ",", "msg", ")", "=", "self", ".", "_inline_tcl_xfer", "(", "source_config", "=", "source_config", ",", "dest_file", "=", "dest_file", ",", "file_system", "=", "file_system", ")", "else", ":", "# Use SCP", "tmp_file", "=", "self", ".", "_create_tmp_file", "(", "source_config", ")", "(", "return_status", ",", "msg", ")", "=", "self", ".", "_scp_file", "(", "source_file", "=", "tmp_file", ",", "dest_file", "=", "dest_file", ",", "file_system", "=", "file_system", ")", "if", "tmp_file", "and", "os", ".", "path", ".", "isfile", "(", "tmp_file", ")", ":", "os", ".", "remove", "(", "tmp_file", ")", "if", "source_file", ":", "if", "self", ".", "inline_transfer", ":", "(", "return_status", ",", "msg", ")", "=", "self", ".", "_inline_tcl_xfer", "(", "source_file", "=", "source_file", ",", "dest_file", "=", "dest_file", ",", "file_system", "=", "file_system", ")", "else", ":", "(", "return_status", ",", "msg", ")", "=", "self", ".", "_scp_file", "(", "source_file", "=", "source_file", ",", "dest_file", "=", "dest_file", ",", "file_system", "=", "file_system", ")", "if", "not", "return_status", ":", "if", "msg", "==", "''", ":", "msg", "=", "\"Transfer to remote device failed\"", "return", "(", "return_status", ",", "msg", ")" ]
Upload the napp from the current directory to the napps server .
def upload_napp ( self , metadata , package ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' ) metadata [ 'token' ] = self . _config . get ( 'auth' , 'token' ) request = self . make_request ( endpoint , json = metadata , package = package , method = "POST" ) if request . status_code != 201 : KytosConfig ( ) . clear_token ( ) LOG . error ( "%s: %s" , request . status_code , request . reason ) sys . exit ( 1 ) # WARNING: this will change in future versions, when 'author' will get # removed. username = metadata . get ( 'username' , metadata . get ( 'author' ) ) name = metadata . get ( 'name' ) print ( "SUCCESS: NApp {}/{} uploaded." . format ( username , name ) )
4,130
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L111-L127
[ "def", "get_column_type", "(", "column", ",", "column_values", ")", ":", "try", ":", "return", "_get_column_type_heur", "(", "column", ",", "column_values", ")", "except", "util", ".", "TableDefinitionError", "as", "e", ":", "logging", ".", "error", "(", "\"Column type couldn't be determined: {}\"", ".", "format", "(", "e", ".", "message", ")", ")", "return", "ColumnType", ".", "text", ",", "None", ",", "None", ",", "1" ]
Send an user_dict to NApps server using POST request .
def register ( self , user_dict ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'users' , '' ) res = self . make_request ( endpoint , method = 'POST' , json = user_dict ) return res . content . decode ( 'utf-8' )
4,131
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L147-L160
[ "def", "remove_range", "(", "cls", ",", "elem", ",", "end_elem", ",", "delete_end", "=", "True", ")", ":", "while", "elem", "is", "not", "None", "and", "elem", "!=", "end_elem", "and", "end_elem", "not", "in", "elem", ".", "xpath", "(", "\"descendant::*\"", ")", ":", "parent", "=", "elem", ".", "getparent", "(", ")", "nxt", "=", "elem", ".", "getnext", "(", ")", "parent", ".", "remove", "(", "elem", ")", "if", "DEBUG", "==", "True", ":", "print", "(", "etree", ".", "tounicode", "(", "elem", ")", ")", "elem", "=", "nxt", "if", "elem", "==", "end_elem", ":", "if", "delete_end", "==", "True", ":", "cls", ".", "remove", "(", "end_elem", ",", "leave_tail", "=", "True", ")", "elif", "elem", "is", "None", ":", "if", "parent", ".", "tail", "not", "in", "[", "None", ",", "''", "]", ":", "parent", ".", "tail", "=", "''", "cls", ".", "remove_range", "(", "parent", ".", "getnext", "(", ")", ",", "end_elem", ")", "XML", ".", "remove_if_empty", "(", "parent", ")", "elif", "end_elem", "in", "elem", ".", "xpath", "(", "\"descendant::*\"", ")", ":", "if", "DEBUG", "==", "True", ":", "print", "(", "elem", ".", "text", ")", "elem", ".", "text", "=", "''", "cls", ".", "remove_range", "(", "elem", ".", "getchildren", "(", ")", "[", "0", "]", ",", "end_elem", ")", "XML", ".", "remove_if_empty", "(", "elem", ")", "else", ":", "print", "(", "\"LOGIC ERROR\"", ",", "file", "=", "sys", ".", "stderr", ")" ]
Process received message
def on_message ( self , message ) : if message . address != self . _address : return if isinstance ( message , velbus . ChannelNamePart1Message ) or isinstance ( message , velbus . ChannelNamePart1Message2 ) : self . _process_channel_name_message ( 1 , message ) elif isinstance ( message , velbus . ChannelNamePart2Message ) or isinstance ( message , velbus . ChannelNamePart2Message2 ) : self . _process_channel_name_message ( 2 , message ) elif isinstance ( message , velbus . ChannelNamePart3Message ) or isinstance ( message , velbus . ChannelNamePart3Message2 ) : self . _process_channel_name_message ( 3 , message ) elif isinstance ( message , velbus . ModuleTypeMessage ) : self . _process_module_type_message ( message ) else : self . _on_message ( message )
4,132
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L65-L80
[ "def", "_openResources", "(", "self", ")", ":", "try", ":", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "True", ")", "except", "Exception", "as", "ex", ":", "logger", ".", "warning", "(", "ex", ")", "logger", ".", "warning", "(", "\"Unable to read wav with memmory mapping. Trying without now.\"", ")", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "False", ")", "self", ".", "_array", "=", "data", "self", ".", "attributes", "[", "'rate'", "]", "=", "rate" ]
Retrieve names of channels
def load ( self , callback ) : if callback is None : def callb ( ) : """No-op""" pass callback = callb if len ( self . _loaded_callbacks ) == 0 : self . _request_module_status ( ) self . _request_channel_name ( ) else : print ( "++++++++++++++++++++++++++++++++++" ) self . _loaded_callbacks . append ( callback ) self . _load ( )
4,133
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L90-L105
[ "def", "exercise_callback_factory", "(", "match", ",", "url_template", ",", "mc_client", "=", "None", ",", "token", "=", "None", ",", "mml_url", "=", "None", ")", ":", "def", "_replace_exercises", "(", "elem", ")", ":", "item_code", "=", "elem", ".", "get", "(", "'href'", ")", "[", "len", "(", "match", ")", ":", "]", "url", "=", "url_template", ".", "format", "(", "itemCode", "=", "item_code", ")", "exercise", "=", "{", "}", "if", "mc_client", ":", "mc_key", "=", "item_code", "+", "(", "token", "or", "''", ")", "exercise", "=", "json", ".", "loads", "(", "mc_client", ".", "get", "(", "mc_key", ")", "or", "'{}'", ")", "if", "not", "exercise", ":", "if", "token", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "token", ")", "}", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ")", "else", ":", "res", "=", "requests", ".", "get", "(", "url", ")", "if", "res", ":", "# grab the json exercise, run it through Jinja2 template,", "# replace element w/ it", "exercise", "=", "res", ".", "json", "(", ")", "if", "mc_client", ":", "mc_client", ".", "set", "(", "mc_key", ",", "res", ".", "text", ")", "if", "exercise", "[", "'total_count'", "]", "==", "0", ":", "logger", ".", "warning", "(", "'MISSING EXERCISE: {}'", ".", "format", "(", "url", ")", ")", "XHTML", "=", "'{{{}}}'", ".", "format", "(", "HTML_DOCUMENT_NAMESPACES", "[", "'xhtml'", "]", ")", "missing", "=", "etree", ".", "Element", "(", "XHTML", "+", "'div'", ",", "{", "'class'", ":", "'missing-exercise'", "}", ",", "nsmap", "=", "HTML_DOCUMENT_NAMESPACES", ")", "missing", ".", "text", "=", "'MISSING EXERCISE: tag:{}'", ".", "format", "(", "item_code", ")", "nodes", "=", "[", "missing", "]", "else", ":", "html", "=", "EXERCISE_TEMPLATE", ".", "render", "(", "data", "=", "exercise", ")", "try", ":", "nodes", "=", "etree", ".", "fromstring", "(", "'<div>{}</div>'", ".", "format", "(", "html", ")", ")", "except", "etree", ".", "XMLSyntaxError", ":", "# Probably HTML", "nodes", "=", "etree", ".", "HTML", "(", "html", ")", "[", "0", "]", "# body node", "if", "mml_url", ":", "for", "node", "in", "nodes", ".", "xpath", "(", "'//*[@data-math]'", ")", ":", "mathml", "=", "_replace_tex_math", "(", "node", ",", "mml_url", ",", "mc_client", ")", "if", "mathml", "is", "not", "None", ":", "mparent", "=", "node", ".", "getparent", "(", ")", "mparent", ".", "replace", "(", "node", ",", "mathml", ")", "else", ":", "mathtext", "=", "node", ".", "get", "(", "'data-math'", ")", "or", "node", ".", "text", "or", "''", "logger", ".", "warning", "(", "'BAD TEX CONVERSION: \"%s\" URL: %s'", "%", "(", "mathtext", ".", "encode", "(", "'utf-8'", ")", ",", "url", ")", ")", "parent", "=", "elem", ".", "getparent", "(", ")", "if", "etree", ".", "QName", "(", "parent", ".", "tag", ")", ".", "localname", "==", "'p'", ":", "elem", "=", "parent", "parent", "=", "elem", ".", "getparent", "(", ")", "parent", ".", "remove", "(", "elem", ")", "# Special case - assumes single wrapper elem", "for", "child", "in", "nodes", ":", "parent", ".", "append", "(", "child", ")", "xpath", "=", "'//xhtml:a[contains(@href, \"{}\")]'", ".", "format", "(", "match", ")", "return", "(", "xpath", ",", "_replace_exercises", ")" ]
Check if all name messages have been received
def _name_messages_complete ( self ) : for channel in range ( 1 , self . number_of_channels ( ) + 1 ) : try : for name_index in range ( 1 , 4 ) : if not isinstance ( self . _name_data [ channel ] [ name_index ] , str ) : return False except Exception : return False return True
4,134
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L147-L158
[ "def", "open", "(", "dataset_dir", ",", "access_mode", "=", "READ_ONLY_ACCESS", ")", ":", "# check access mode", "if", "access_mode", "==", "WRITE_ACCESS", ":", "raise", "ValueError", "(", "'Cannot open a dataset with write-only access'", ")", "# read config", "try", ":", "# json load", "config_filename", "=", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "'config.json'", ")", "config", "=", "json", ".", "load", "(", "open", "(", "config_filename", ",", "'r'", ")", ")", "except", ":", "# YAML load", "config_filename", "=", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "'config.yaml'", ")", "config", "=", "YamlConfig", "(", "config_filename", ")", "# open dataset", "dataset", "=", "TensorDataset", "(", "dataset_dir", ",", "config", ",", "access_mode", "=", "access_mode", ")", "return", "dataset" ]
Represent effect as JSON dict .
def as_json ( self ) : # type: () -> dict self . _config [ 'applyCss' ] = self . applyCss self . _json [ 'config' ] = self . _config return self . _json
4,135
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/validators/effects.py#L98-L103
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", ".", "_project", ")", "self", ".", "_aux", "=", "None", "if", "aux", "is", "not", "None", ":", "self", ".", "_aux", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "aux", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: aux port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "aux", ")", ")" ]
Delete files left in self . _stale_files . Also delete their directories if empty .
def _delete_stale ( self ) : for name , hash_ in self . _stale_files . items ( ) : path = self . download_root . joinpath ( name ) if not path . exists ( ) : continue current_hash = self . _path_hash ( path ) if current_hash == hash_ : progress_logger . info ( 'deleting: %s which is stale...' , name ) path . unlink ( ) self . _stale_deleted += 1 while True : path = path . parent if path == self . download_root or list ( path . iterdir ( ) ) : break progress_logger . info ( 'deleting: %s which is stale..' , path . relative_to ( self . download_root ) ) path . rmdir ( ) else : progress_logger . error ( 'Not deleting "%s" which is in the lock file but not the definition ' 'file, however appears to have been modified since it was downloaded. ' 'Please check and delete the file manually.' , name ) raise GrablibError ( 'stale file modified' )
4,136
https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/download.py#L172-L195
[ "def", "set_service_value", "(", "self", ",", "service_id", ",", "set_name", ",", "parameter_name", ",", "value", ")", ":", "payload", "=", "{", "'id'", ":", "'lu_action'", ",", "'action'", ":", "'Set'", "+", "set_name", ",", "'serviceId'", ":", "service_id", ",", "parameter_name", ":", "value", "}", "result", "=", "self", ".", "vera_request", "(", "*", "*", "payload", ")", "logger", ".", "debug", "(", "\"set_service_value: \"", "\"result of vera_request with payload %s: %s\"", ",", "payload", ",", "result", ".", "text", ")" ]
check src_path complies with regex and generate new filename
def _file_path ( self , src_path , dest , regex ) : m = re . search ( regex , src_path ) if dest . endswith ( '/' ) or dest == '' : dest += '{filename}' names = m . groupdict ( ) if not names and m . groups ( ) : names = { 'filename' : m . groups ( ) [ - 1 ] } for name , value in names . items ( ) : dest = dest . replace ( '{%s}' % name , value ) # remove starting slash so path can't be absolute dest = dest . strip ( ' /' ) if not dest : progress_logger . error ( 'destination path must not resolve to be null' ) raise GrablibError ( 'bad path' ) new_path = self . download_root . joinpath ( dest ) new_path . relative_to ( self . download_root ) return new_path
4,137
https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/download.py#L197-L216
[ "def", "readKerningElement", "(", "self", ",", "kerningElement", ",", "instanceObject", ")", ":", "kerningLocation", "=", "self", ".", "locationFromElement", "(", "kerningElement", ")", "instanceObject", ".", "addKerning", "(", "kerningLocation", ")" ]
Add details of the files downloaded to _new_lock so they can be saved to the lock file . Also remove path from _stale_files whatever remains at the end therefore is stale and can be deleted .
def _lock ( self , url : str , name : str , hash_ : str ) : self . _new_lock . append ( { 'url' : url , 'name' : name , 'hash' : hash_ , } ) self . _stale_files . pop ( name , None )
4,138
https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/download.py#L241-L251
[ "def", "setOverlayTextureColorSpace", "(", "self", ",", "ulOverlayHandle", ",", "eTextureColorSpace", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTextureColorSpace", "result", "=", "fn", "(", "ulOverlayHandle", ",", "eTextureColorSpace", ")", "return", "result" ]
Set up the crash reporter to send reports via email using SMTP
def setup_smtp ( self , host , port , user , passwd , recipients , * * kwargs ) : self . _smtp = kwargs self . _smtp . update ( { 'host' : host , 'port' : port , 'user' : user , 'passwd' : passwd , 'recipients' : recipients } ) try : self . _smtp [ 'timeout' ] = int ( kwargs . get ( 'timeout' , SMTP_DEFAULT_TIMEOUT ) ) except Exception as e : logging . error ( e ) self . _smtp [ 'timeout' ] = None self . _smtp [ 'from' ] = kwargs . get ( 'from' , user )
4,139
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L95-L112
[ "def", "google_calendar", "(", "self", ")", ":", "composite", "=", "{", "}", "if", "not", "self", ".", "is_authorized", ":", "cached_until", "=", "0", "self", ".", "is_authorized", "=", "self", ".", "_authorize_credentials", "(", ")", "else", ":", "if", "not", "self", ".", "no_update", ":", "self", ".", "events", "=", "self", ".", "_get_events", "(", ")", "composite", "=", "self", ".", "_build_response", "(", ")", "cached_until", "=", "self", ".", "cache_timeout", "return", "{", "\"cached_until\"", ":", "self", ".", "py3", ".", "time_in", "(", "cached_until", ")", ",", "\"composite\"", ":", "self", ".", "py3", ".", "safe_format", "(", "self", ".", "format", ",", "composite", ")", ",", "}" ]
Enable the crash reporter . CrashReporter is defaulted to be enabled on creation .
def enable ( self ) : if not CrashReporter . active : CrashReporter . active = True # Store this function so we can set it back if the CrashReporter is deactivated self . _excepthook = sys . excepthook sys . excepthook = self . exception_handler self . logger . info ( 'CrashReporter: Enabled' ) if self . report_dir : if os . path . exists ( self . report_dir ) : if self . get_offline_reports ( ) : # First attempt to send the reports, if that fails then start the watcher self . submit_offline_reports ( ) remaining_reports = len ( self . get_offline_reports ( ) ) if remaining_reports and self . watcher_enabled : self . start_watcher ( ) else : os . makedirs ( self . report_dir )
4,140
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L123-L142
[ "def", "delete", "(", "self", ",", "data_src", ")", ":", "items", "=", "self", ".", "objects", "[", "data_src", "]", ".", "data", ".", "keys", "(", ")", "# items to edit", "self", ".", "reg", ".", "unregister", "(", "items", ")", "# remove items from Registry", "self", ".", "layer", ".", "pop", "(", "data_src", ")", "# remove data source from layer", "self", ".", "objects", ".", "pop", "(", "data_src", ")", "# remove data_source object", "self", ".", "sources", ".", "pop", "(", "data_src", ")" ]
Disable the crash reporter . No reports will be sent or saved .
def disable ( self ) : if CrashReporter . active : CrashReporter . active = False # Restore the original excepthook sys . excepthook = self . _excepthook self . stop_watcher ( ) self . logger . info ( 'CrashReporter: Disabled' )
4,141
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L144-L153
[ "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\"", ")" ]
Start the watcher that periodically checks for offline reports and attempts to upload them .
def start_watcher ( self ) : if self . _watcher and self . _watcher . is_alive : self . _watcher_running = True else : self . logger . info ( 'CrashReporter: Starting watcher.' ) self . _watcher = Thread ( target = self . _watcher_thread , name = 'offline_reporter' ) self . _watcher . setDaemon ( True ) self . _watcher_running = True self . _watcher . start ( )
4,142
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L155-L166
[ "def", "augment_audio_with_sox", "(", "path", ",", "sample_rate", ",", "tempo", ",", "gain", ")", ":", "with", "NamedTemporaryFile", "(", "suffix", "=", "\".wav\"", ")", "as", "augmented_file", ":", "augmented_filename", "=", "augmented_file", ".", "name", "sox_augment_params", "=", "[", "\"tempo\"", ",", "\"{:.3f}\"", ".", "format", "(", "tempo", ")", ",", "\"gain\"", ",", "\"{:.3f}\"", ".", "format", "(", "gain", ")", "]", "sox_params", "=", "\"sox \\\"{}\\\" -r {} -c 1 -b 16 {} {} >/dev/null 2>&1\"", ".", "format", "(", "path", ",", "sample_rate", ",", "augmented_filename", ",", "\" \"", ".", "join", "(", "sox_augment_params", ")", ")", "os", ".", "system", "(", "sox_params", ")", "y", "=", "load_audio", "(", "augmented_filename", ")", "return", "y" ]
Stop the watcher thread that tries to send offline reports .
def stop_watcher ( self ) : if self . _watcher : self . _watcher_running = False self . logger . info ( 'CrashReporter: Stopping watcher.' )
4,143
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L168-L174
[ "def", "orthologize", "(", "self", ",", "ortho_species_id", ",", "belast", ")", ":", "if", "(", "self", ".", "orthologs", "and", "ortho_species_id", "in", "self", ".", "orthologs", "and", "ortho_species_id", "!=", "self", ".", "species_id", ")", ":", "self", ".", "orthology_species", "=", "ortho_species_id", "self", ".", "canonical", "=", "self", ".", "orthologs", "[", "ortho_species_id", "]", "[", "\"canonical\"", "]", "self", ".", "decanonical", "=", "self", ".", "orthologs", "[", "ortho_species_id", "]", "[", "\"decanonical\"", "]", "self", ".", "update_nsval", "(", "nsval", "=", "self", ".", "decanonical", ")", "self", ".", "orthologized", "=", "True", "elif", "self", ".", "species_id", "and", "ortho_species_id", "not", "in", "self", ".", "orthologs", ":", "self", ".", "orthologized", "=", "False", "belast", ".", "partially_orthologized", "=", "True", "return", "self" ]
Return a string to be used as the email subject line .
def subject ( self ) : if self . application_name and self . application_version : return 'Crash Report - {name} (v{version})' . format ( name = self . application_name , version = self . application_version ) else : return 'Crash Report'
4,144
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L301-L309
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Initializing...\"", ")", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"initialize\"", ",", "\"()V\"", ")", "logger", ".", "info", "(", "\"Running...\"", ")", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"runExperiment\"", ",", "\"()V\"", ")", "logger", ".", "info", "(", "\"Finished...\"", ")", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"postProcess\"", ",", "\"()V\"", ")" ]
Save the crash report to a file . Keeping the last offline_report_limit files in a cyclical FIFO buffer . The newest crash report always named is 01
def store_report ( self , payload ) : offline_reports = self . get_offline_reports ( ) if offline_reports : # Increment the name of all existing reports 1 --> 2, 2 --> 3 etc. for ii , report in enumerate ( reversed ( offline_reports ) ) : rpath , ext = os . path . splitext ( report ) n = int ( re . findall ( '(\d+)' , rpath ) [ - 1 ] ) new_name = os . path . join ( self . report_dir , self . _report_name % ( n + 1 ) ) + ext shutil . copy2 ( report , new_name ) os . remove ( report ) # Delete the oldest report if len ( offline_reports ) >= self . offline_report_limit : oldest = glob . glob ( os . path . join ( self . report_dir , self . _report_name % ( self . offline_report_limit + 1 ) + '*' ) ) [ 0 ] os . remove ( oldest ) new_report_path = os . path . join ( self . report_dir , self . _report_name % 1 + '.json' ) # Write a new report with open ( new_report_path , 'w' ) as _f : json . dump ( payload , _f ) return new_report_path
4,145
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L389-L412
[ "def", "SQRT", "(", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "MetaField", ")", ":", "return", "argument", ".", "_unary_expression", "(", "\"SQRT\"", ")", "elif", "isinstance", "(", "argument", ",", "RegField", ")", ":", "return", "argument", ".", "_unary_expression", "(", "\"SQRT\"", ")", "else", ":", "raise", "TypeError", "(", "\"You have to give as input a RegField (dataset.field)\"", "\"or a MetaField (dataset['field']\"", ")" ]
Periodically attempt to upload the crash reports . If any upload method is successful delete the saved reports .
def _watcher_thread ( self ) : while 1 : time . sleep ( self . check_interval ) if not self . _watcher_running : break self . logger . info ( 'CrashReporter: Attempting to send offline reports.' ) self . submit_offline_reports ( ) remaining_reports = len ( self . get_offline_reports ( ) ) if remaining_reports == 0 : break self . _watcher = None self . logger . info ( 'CrashReporter: Watcher stopped.' )
4,146
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L471-L485
[ "def", "setRandomSeed", "(", "self", ",", "seed", ")", ":", "self", ".", "seed", "=", "seed", "self", ".", "_random", "=", "Random", "(", ")", "self", ".", "_random", ".", "setSeed", "(", "seed", ")" ]
Taken and modified from django . utils . log . ServerFormatter . format to mimic runserver s styling .
def colorize ( style , msg , resp ) : code = resp . status . split ( maxsplit = 1 ) [ 0 ] if code [ 0 ] == '2' : # Put 2XX first, since it should be the common case msg = style . HTTP_SUCCESS ( msg ) elif code [ 0 ] == '1' : msg = style . HTTP_INFO ( msg ) elif code == '304' : msg = style . HTTP_NOT_MODIFIED ( msg ) elif code [ 0 ] == '3' : msg = style . HTTP_REDIRECT ( msg ) elif code == '404' : msg = style . HTTP_NOT_FOUND ( msg ) elif code [ 0 ] == '4' : msg = style . HTTP_BAD_REQUEST ( msg ) else : # Any 5XX, or any other response msg = style . HTTP_SERVER_ERROR ( msg ) return msg
4,147
https://github.com/uranusjr/django-gunicorn/blob/4fb16f48048ff5fff8f889a007f376236646497b/djgunicorn/logging.py#L11-L32
[ "def", "free_extent_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_free_extent_count", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
Override to apply styling on access logs .
def access ( self , resp , req , environ , request_time ) : if not ( self . cfg . accesslog or self . cfg . logconfig or self . cfg . syslog ) : return msg = self . make_access_message ( resp , req , environ , request_time ) try : self . access_log . info ( msg ) except : self . error ( traceback . format_exc ( ) )
4,148
https://github.com/uranusjr/django-gunicorn/blob/4fb16f48048ff5fff8f889a007f376236646497b/djgunicorn/logging.py#L60-L73
[ "def", "cwl_input_directories", "(", "cwl_data", ",", "job_data", ",", "input_dir", "=", "None", ")", ":", "results", "=", "{", "}", "for", "input_identifier", ",", "input_data", "in", "cwl_data", "[", "'inputs'", "]", ".", "items", "(", ")", ":", "cwl_type", "=", "parse_cwl_type", "(", "input_data", "[", "'type'", "]", ")", "(", "is_optional", ",", "is_array", ",", "cwl_type", ")", "=", "itemgetter", "(", "'isOptional'", ",", "'isArray'", ",", "'type'", ")", "(", "cwl_type", ")", "if", "cwl_type", "==", "'Directory'", ":", "result", "=", "{", "'isOptional'", ":", "is_optional", ",", "'isArray'", ":", "is_array", ",", "'directories'", ":", "None", "}", "if", "input_identifier", "in", "job_data", ":", "arg", "=", "job_data", "[", "input_identifier", "]", "if", "is_array", ":", "result", "[", "'directories'", "]", "=", "[", "_input_directory_description", "(", "input_identifier", ",", "i", ",", "input_dir", ")", "for", "i", "in", "arg", "]", "else", ":", "result", "[", "'directories'", "]", "=", "[", "_input_directory_description", "(", "input_identifier", ",", "arg", ",", "input_dir", ")", "]", "results", "[", "input_identifier", "]", "=", "result", "return", "results" ]
Call the method to update the Web UI .
def update ( cls , args ) : kytos_api = KytosConfig ( ) . config . get ( 'kytos' , 'api' ) url = f"{kytos_api}api/kytos/core/web/update" version = args [ "<version>" ] if version : url += f"/{version}" try : result = requests . post ( url ) except ( HTTPError , URLError , requests . exceptions . ConnectionError ) : LOG . error ( "Can't connect to server: %s" , kytos_api ) return if result . status_code != 200 : LOG . info ( "Error while updating web ui: %s" , result . content ) else : LOG . info ( "Web UI updated." )
4,149
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/web/api.py#L16-L33
[ "def", "TxKazooClient", "(", "reactor", ",", "pool", ",", "client", ")", ":", "make_thimble", "=", "partial", "(", "Thimble", ",", "reactor", ",", "pool", ")", "wrapper", "=", "_RunCallbacksInReactorThreadWrapper", "(", "reactor", ",", "client", ")", "client_thimble", "=", "make_thimble", "(", "wrapper", ",", "_blocking_client_methods", ")", "def", "_Lock", "(", "path", ",", "identifier", "=", "None", ")", ":", "\"\"\"Return a wrapped :class:`kazoo.recipe.lock.Lock` for this client.\"\"\"", "lock", "=", "client", ".", "Lock", "(", "path", ",", "identifier", ")", "return", "Thimble", "(", "reactor", ",", "pool", ",", "lock", ",", "_blocking_lock_methods", ")", "client_thimble", ".", "Lock", "=", "_Lock", "client_thimble", ".", "SetPartitioner", "=", "partial", "(", "_SetPartitionerWrapper", ",", "reactor", ",", "pool", ",", "client", ")", "# Expose these so e.g. recipes can access them from the kzclient", "client", ".", "reactor", "=", "reactor", "client", ".", "pool", "=", "pool", "client", ".", "kazoo_client", "=", "client", "return", "client_thimble" ]
Disable subcommand .
def disable ( cls , args ) : mgr = NAppsManager ( ) if args [ 'all' ] : napps = mgr . get_enabled ( ) else : napps = args [ '<napp>' ] for napp in napps : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) cls . disable_napp ( mgr )
4,150
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L25-L37
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Disable a NApp .
def disable_napp ( mgr ) : if mgr . is_enabled ( ) : LOG . info ( ' Disabling...' ) mgr . disable ( ) LOG . info ( ' Disabled.' ) else : LOG . error ( " NApp isn't enabled." )
4,151
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L40-L47
[ "def", "_has_terms", "(", "self", ")", ":", "loc", "=", "self", ".", "_super_get", "(", "'_term_location'", ")", "return", "self", ".", "_super_has", "(", "loc", ")", "and", "isiterable", "(", "self", ".", "_super_get", "(", "loc", ")", ")", "and", "len", "(", "self", ".", "_super_get", "(", "loc", ")", ")", ">", "0", "and", "all", "(", "[", "isinstance", "(", "term", ",", "Term", ")", "for", "term", "in", "self", ".", "_super_get", "(", "loc", ")", "]", ")" ]
Enable subcommand .
def enable ( cls , args ) : mgr = NAppsManager ( ) if args [ 'all' ] : napps = mgr . get_disabled ( ) else : napps = args [ '<napp>' ] cls . enable_napps ( napps )
4,152
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L50-L59
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Install one NApp using NAppManager object .
def enable_napp ( cls , mgr ) : try : if not mgr . is_enabled ( ) : LOG . info ( ' Enabling...' ) mgr . enable ( ) LOG . info ( ' Enabled.' ) except ( FileNotFoundError , PermissionError ) as exception : LOG . error ( ' %s' , exception )
4,153
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L62-L70
[ "def", "_has_terms", "(", "self", ")", ":", "loc", "=", "self", ".", "_super_get", "(", "'_term_location'", ")", "return", "self", ".", "_super_has", "(", "loc", ")", "and", "isiterable", "(", "self", ".", "_super_get", "(", "loc", ")", ")", "and", "len", "(", "self", ".", "_super_get", "(", "loc", ")", ")", ">", "0", "and", "all", "(", "[", "isinstance", "(", "term", ",", "Term", ")", "for", "term", "in", "self", ".", "_super_get", "(", "loc", ")", "]", ")" ]
Enable a list of NApps .
def enable_napps ( cls , napps ) : mgr = NAppsManager ( ) for napp in napps : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) cls . enable_napp ( mgr )
4,154
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L73-L83
[ "def", "min_and", "(", "a", ",", "b", ",", "c", ",", "d", ",", "w", ")", ":", "m", "=", "(", "1", "<<", "(", "w", "-", "1", ")", ")", "while", "m", "!=", "0", ":", "if", "(", "~", "a", "&", "~", "c", "&", "m", ")", "!=", "0", ":", "temp", "=", "(", "a", "|", "m", ")", "&", "-", "m", "if", "temp", "<=", "b", ":", "a", "=", "temp", "break", "temp", "=", "(", "c", "|", "m", ")", "&", "-", "m", "if", "temp", "<=", "d", ":", "c", "=", "temp", "break", "m", ">>=", "1", "return", "a", "&", "c" ]
Uninstall and delete NApps .
def uninstall ( cls , args ) : mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) if mgr . is_installed ( ) : if mgr . is_enabled ( ) : cls . disable_napp ( mgr ) LOG . info ( ' Uninstalling...' ) mgr . uninstall ( ) LOG . info ( ' Uninstalled.' ) else : LOG . error ( " NApp isn't installed." )
4,155
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L102-L119
[ "def", "_get_type", "(", "self", ",", "policy", ")", ":", "# Must handle intrinsic functions. Policy could be a primitive type or an intrinsic function", "# Managed policies are either string or an intrinsic function that resolves to a string", "if", "isinstance", "(", "policy", ",", "string_types", ")", "or", "is_instrinsic", "(", "policy", ")", ":", "return", "PolicyTypes", ".", "MANAGED_POLICY", "# Policy statement is a dictionary with the key \"Statement\" in it", "if", "isinstance", "(", "policy", ",", "dict", ")", "and", "\"Statement\"", "in", "policy", ":", "return", "PolicyTypes", ".", "POLICY_STATEMENT", "# This could be a policy template then.", "if", "self", ".", "_is_policy_template", "(", "policy", ")", ":", "return", "PolicyTypes", ".", "POLICY_TEMPLATE", "# Nothing matches. Don't take opinions on how to handle it. Instead just set the appropriate type.", "return", "PolicyTypes", ".", "UNKNOWN" ]
Install local or remote NApps .
def install_napps ( cls , napps ) : mgr = NAppsManager ( ) for napp in napps : mgr . set_napp ( * napp ) LOG . info ( ' NApp %s:' , mgr . napp_id ) if not mgr . is_installed ( ) : try : cls . install_napp ( mgr ) if not mgr . is_enabled ( ) : cls . enable_napp ( mgr ) napp_dependencies = mgr . dependencies ( ) if napp_dependencies : LOG . info ( 'Installing Dependencies:' ) cls . install_napps ( napp_dependencies ) else : LOG . warning ( ' Napp already enabled.' ) except KytosException : continue else : LOG . warning ( ' Napp already enabled.' )
4,156
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L127-L152
[ "def", "get_matching_property_names", "(", "self", ",", "regex", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.get_matching_property_names'", ")", "prop_list_matched", "=", "[", "]", "if", "not", "isinstance", "(", "regex", ",", "basestring", ")", ":", "log", ".", "warn", "(", "'regex arg is not a string, found type: {t}'", ".", "format", "(", "t", "=", "regex", ".", "__class__", ".", "__name__", ")", ")", "return", "prop_list_matched", "log", ".", "debug", "(", "'Finding properties matching regex: {r}'", ".", "format", "(", "r", "=", "regex", ")", ")", "for", "prop_name", "in", "self", ".", "properties", ".", "keys", "(", ")", ":", "match", "=", "re", ".", "search", "(", "regex", ",", "prop_name", ")", "if", "match", ":", "prop_list_matched", ".", "append", "(", "prop_name", ")", "return", "prop_list_matched" ]
Install a NApp .
def install_napp ( cls , mgr ) : try : LOG . info ( ' Searching local NApp...' ) mgr . install_local ( ) LOG . info ( ' Found and installed.' ) except FileNotFoundError : LOG . info ( ' Not found. Downloading from NApps Server...' ) try : mgr . install_remote ( ) LOG . info ( ' Downloaded and installed.' ) return except HTTPError as exception : if exception . code == 404 : LOG . error ( ' NApp not found.' ) else : LOG . error ( ' NApps Server error: %s' , exception ) except URLError as exception : LOG . error ( ' NApps Server error: %s' , str ( exception . reason ) ) raise KytosException ( "NApp not found." )
4,157
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L155-L179
[ "def", "_has_terms", "(", "self", ")", ":", "loc", "=", "self", ".", "_super_get", "(", "'_term_location'", ")", "return", "self", ".", "_super_has", "(", "loc", ")", "and", "isiterable", "(", "self", ".", "_super_get", "(", "loc", ")", ")", "and", "len", "(", "self", ".", "_super_get", "(", "loc", ")", ")", ">", "0", "and", "all", "(", "[", "isinstance", "(", "term", ",", "Term", ")", "for", "term", "in", "self", ".", "_super_get", "(", "loc", ")", "]", ")" ]
Search for NApps in NApps server matching a pattern .
def search ( cls , args ) : safe_shell_pat = re . escape ( args [ '<pattern>' ] ) . replace ( r'\*' , '.*' ) pat_str = '.*{}.*' . format ( safe_shell_pat ) pattern = re . compile ( pat_str , re . IGNORECASE ) remote_json = NAppsManager . search ( pattern ) remote = set ( ) for napp in remote_json : # WARNING: This will be changed in future versions, when 'author' # will be removed. username = napp . get ( 'username' , napp . get ( 'author' ) ) remote . add ( ( ( username , napp . get ( 'name' ) ) , napp . get ( 'description' ) ) ) cls . _print_napps ( remote )
4,158
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L182-L195
[ "def", "store", "(", "self", ",", "correlation_id", ",", "key", ",", "credential", ")", ":", "if", "credential", "!=", "None", ":", "self", ".", "_items", ".", "put", "(", "key", ",", "credential", ")", "else", ":", "self", ".", "_items", ".", "remove", "(", "key", ")" ]
Format the NApp list to be printed .
def _print_napps ( cls , napp_list ) : mgr = NAppsManager ( ) enabled = mgr . get_enabled ( ) installed = mgr . get_installed ( ) napps = [ ] for napp , desc in sorted ( napp_list ) : status = 'i' if napp in installed else '-' status += 'e' if napp in enabled else '-' status = '[{}]' . format ( status ) name = '{}/{}' . format ( * napp ) napps . append ( ( status , name , desc ) ) cls . print_napps ( napps )
4,159
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L198-L210
[ "async", "def", "stop", "(", "self", ",", "_task", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Stopping adapter wrapper\"", ")", "if", "self", ".", "_task", ".", "stopped", ":", "return", "for", "task", "in", "self", ".", "_task", ".", "subtasks", ":", "await", "task", ".", "stop", "(", ")", "self", ".", "_logger", ".", "debug", "(", "\"Stopping underlying adapter %s\"", ",", "self", ".", "_adapter", ".", "__class__", ".", "__name__", ")", "await", "self", ".", "_execute", "(", "self", ".", "_adapter", ".", "stop_sync", ")" ]
List all installed NApps and inform whether they are enabled .
def list ( cls , args ) : # pylint: disable=unused-argument mgr = NAppsManager ( ) # Add status napps = [ napp + ( '[ie]' , ) for napp in mgr . get_enabled ( ) ] napps += [ napp + ( '[i-]' , ) for napp in mgr . get_disabled ( ) ] # Sort, add description and reorder columns napps . sort ( ) napps_ordered = [ ] for user , name , status in napps : description = mgr . get_description ( user , name ) version = mgr . get_version ( user , name ) napp_id = f'{user}/{name}' if version : napp_id += f':{version}' napps_ordered . append ( ( status , napp_id , description ) ) cls . print_napps ( napps_ordered )
4,160
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L213-L233
[ "def", "update_custom_field_options", "(", "self", ",", "custom_field_key", ",", "new_options", ",", "keep_existing_options", ")", ":", "custom_field_key", "=", "quote", "(", "custom_field_key", ",", "''", ")", "body", "=", "{", "\"Options\"", ":", "new_options", ",", "\"KeepExistingOptions\"", ":", "keep_existing_options", "}", "response", "=", "self", ".", "_put", "(", "self", ".", "uri_for", "(", "\"customfields/%s/options\"", "%", "custom_field_key", ")", ",", "json", ".", "dumps", "(", "body", ")", ")" ]
Print status name and description .
def print_napps ( napps ) : if not napps : print ( 'No NApps found.' ) return stat_w = 6 # We already know the size of Status col name_w = max ( len ( n [ 1 ] ) for n in napps ) desc_w = max ( len ( n [ 2 ] ) for n in napps ) term_w = os . popen ( 'stty size' , 'r' ) . read ( ) . split ( ) [ 1 ] remaining = max ( 0 , int ( term_w ) - stat_w - name_w - 6 ) desc_w = min ( desc_w , remaining ) widths = ( stat_w , name_w , desc_w ) header = '\n{:^%d} | {:^%d} | {:^%d}' % widths row = '{:^%d} | {:<%d} | {:<%d}' % widths print ( header . format ( 'Status' , 'NApp ID' , 'Description' ) ) print ( '=+=' . join ( '=' * w for w in widths ) ) for user , name , desc in napps : desc = ( desc [ : desc_w - 3 ] + '...' ) if len ( desc ) > desc_w else desc print ( row . format ( user , name , desc ) ) print ( '\nStatus: (i)nstalled, (e)nabled\n' )
4,161
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L236-L258
[ "def", "rpc_start", "(", "working_dir", ",", "port", ",", "subdomain_index", "=", "None", ",", "thread", "=", "True", ")", ":", "rpc_srv", "=", "BlockstackdRPCServer", "(", "working_dir", ",", "port", ",", "subdomain_index", "=", "subdomain_index", ")", "log", ".", "debug", "(", "\"Starting RPC on port {}\"", ".", "format", "(", "port", ")", ")", "if", "thread", ":", "rpc_srv", ".", "start", "(", ")", "return", "rpc_srv" ]
Delete NApps from server .
def delete ( args ) : mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'Deleting NApp %s from server...' , mgr . napp_id ) try : mgr . delete ( ) LOG . info ( ' Deleted.' ) except requests . HTTPError as exception : if exception . response . status_code == 405 : LOG . error ( 'Delete Napp is not allowed yet.' ) else : msg = json . loads ( exception . response . content ) LOG . error ( ' Server error: %s - ' , msg [ 'error' ] )
4,162
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L261-L275
[ "def", "update", "(", "self", ",", "predicate_value", ",", "dct", ",", "upsert", "=", "False", ",", "attribute", "=", "\"_id\"", ")", ":", "if", "self", ".", "schema", ":", "jsonschema", ".", "validate", "(", "dct", ",", "self", ".", "schema", ")", "if", "attribute", "==", "\"_id\"", "and", "not", "isinstance", "(", "predicate_value", ",", "ObjectId", ")", ":", "predicate_value", "=", "ObjectId", "(", "predicate_value", ")", "predicate", "=", "{", "attribute", ":", "predicate_value", "}", "dct", "=", "self", ".", "_dictionary_to_cursor", "(", "dct", ")", "mongo_response", "=", "yield", "self", ".", "collection", ".", "update", "(", "predicate", ",", "dct", ",", "upsert", ")", "raise", "Return", "(", "self", ".", "_obj_cursor_to_dictionary", "(", "mongo_response", ")", ")" ]
Reload NApps code .
def reload ( cls , args ) : LOG . info ( 'Reloading NApps...' ) mgr = NAppsManager ( ) try : if args [ 'all' ] : mgr . reload ( None ) else : napps = args [ '<napp>' ] mgr . reload ( napps ) LOG . info ( '\tReloaded.' ) except requests . HTTPError as exception : if exception . response . status_code != 200 : msg = json . loads ( exception . response . content ) LOG . error ( '\tServer error: %s - ' , msg [ 'error' ] )
4,163
https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L284-L300
[ "def", "from_dict", "(", "self", ",", "d", ")", ":", "for", "key", "in", "d", ":", "if", "key", "==", "'data'", ":", "for", "dkey", "in", "d", "[", "'data'", "]", ":", "if", "dkey", "in", "self", ".", "_encode_fields", ":", "setattr", "(", "self", ",", "str", "(", "dkey", ")", ",", "base64", ".", "b64decode", "(", "d", "[", "'data'", "]", "[", "dkey", "]", ")", ")", "else", ":", "setattr", "(", "self", ",", "str", "(", "dkey", ")", ",", "d", "[", "'data'", "]", "[", "dkey", "]", ")", "else", ":", "setattr", "(", "self", ",", "str", "(", "key", ")", ",", "d", "[", "key", "]", ")" ]
Retrieve the parts that you can reference for this ReferenceProperty .
def choices ( self ) : # from the reference property (instance) we need to get the value of the reference property in the model # in the reference property of the model the value is set to the ID of the model from which we can choose parts model_parent_part = self . part . model ( ) # makes single part call property_model = model_parent_part . property ( self . name ) referenced_model = self . _client . model ( pk = property_model . _value [ 'id' ] ) # makes single part call possible_choices = self . _client . parts ( model = referenced_model ) # makes multiple parts call return possible_choices
4,164
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_reference.py#L70-L93
[ "def", "create_from_textgrid", "(", "self", ",", "word_list", ")", ":", "self", ".", "timing_included", "=", "True", "for", "i", ",", "entry", "in", "enumerate", "(", "word_list", ")", ":", "self", ".", "unit_list", ".", "append", "(", "Unit", "(", "entry", ",", "format", "=", "\"TextGrid\"", ",", "type", "=", "self", ".", "type", ",", "index_in_timed_response", "=", "i", ")", ")", "# combine compound words, remove pluralizations, etc", "if", "self", ".", "type", "==", "\"SEMANTIC\"", ":", "self", ".", "lemmatize", "(", ")", "self", ".", "tokenize", "(", ")" ]
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically .
def opensignals_hierarchy ( root = None , update = False , clone = False ) : if root is None : root = os . getcwd ( ) categories = list ( NOTEBOOK_KEYS . keys ( ) ) # ============================ Creation of the main directory ================================== current_dir = root + "\\opensignalstools_environment" if not os . path . isdir ( current_dir ) : os . makedirs ( current_dir ) # ================== Copy of 'images' 'styles' and 'signal_samples' folders ==================== for var in [ "images" , "styles" , "signal_samples" ] : if not os . path . isdir ( root + "\\opensignalstools_environment\\" + var ) : src = os . getcwd ( ) + "\\" + var destination = current_dir + "\\" + var shutil . copytree ( src , destination ) elif update is True : shutil . rmtree ( root + "\\opensignalstools_environment\\" + var ) src = os . getcwd ( ) + "\\" + var destination = current_dir + "\\" + var shutil . copytree ( src , destination ) # =========================== Generation of 'Categories' folder ================================ current_dir = root + "\\opensignalstools_environment\\Categories" if not os . path . isdir ( current_dir ) : os . makedirs ( current_dir ) for category in categories : if not os . path . isdir ( current_dir + "\\" + category ) : os . makedirs ( current_dir + "\\" + category ) if clone is True : # Fill each folder inside "Categories" directory with the respective notebooks. # Each notebook will be created by a specific function. dir_path = root + "\\notebook_code" list_of_code_dirs = os . listdir ( dir_path ) for folder in list_of_code_dirs : folder_path = root + "\\notebook_code\\" + folder if folder != "MainFiles" and folder != "__pycache__" : list_of_code_files = os . listdir ( folder_path ) for file in list_of_code_files : if file != "__pycache__" : spec = importlib . util . spec_from_file_location ( file , folder_path + "\\" + file ) foo = importlib . util . module_from_spec ( spec ) spec . loader . exec_module ( foo ) foo . run ( root + "\\opensignalstools_environment" ) # Generation of opensignalstools environment main files. main_page = notebook ( "Main_Files_By_Category" ) main_page . write_to_file ( root + "\\opensignalstools_environment" , "opensignalstools" , footer = False ) by_difficulty = notebook ( "Main_Files_By_Difficulty" , "Notebooks Grouped by Difficulty" , notebook_description = DESCRIPTION_GROUP_BY ) by_difficulty . write_to_file ( root + "\\opensignalstools_environment" , "by_diff" , footer = False ) by_tags = notebook ( "Main_Files_By_Tag" , "Notebooks Grouped by Tag Values" , notebook_description = DESCRIPTION_GROUP_BY ) by_tags . write_to_file ( root + "\\opensignalstools_environment" , "by_tag" , footer = False ) by_signal_type = notebook ( "Main_Files_By_Signal_Type" , "Notebooks Grouped by Signal Type" , notebook_description = DESCRIPTION_GROUP_BY ) by_signal_type . write_to_file ( root + "\\opensignalstools_environment" , "by_signal_type" , footer = False ) signal_samples = notebook ( "Main_Files_Signal_Samples" , "Signal Samples Library" , notebook_description = DESCRIPTION_SIGNAL_SAMPLES ) signal_samples . write_to_file ( root + "\\opensignalstools_environment" , "signal_samples" , footer = False ) return root + "\\opensignalstools_environment"
4,165
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L225-L321
[ "def", "inspect_work_unit", "(", "self", ",", "work_spec_name", ",", "work_unit_key", ")", ":", "with", "self", ".", "registry", ".", "lock", "(", "identifier", "=", "self", ".", "worker_id", ")", "as", "session", ":", "work_unit_data", "=", "session", ".", "get", "(", "WORK_UNITS_", "+", "work_spec_name", ",", "work_unit_key", ")", "if", "not", "work_unit_data", ":", "work_unit_data", "=", "session", ".", "get", "(", "WORK_UNITS_", "+", "work_spec_name", "+", "_BLOCKED", ",", "work_unit_key", ")", "if", "not", "work_unit_data", ":", "work_unit_data", "=", "session", ".", "get", "(", "WORK_UNITS_", "+", "work_spec_name", "+", "_FINISHED", ",", "work_unit_key", ")", "if", "not", "work_unit_data", ":", "work_unit_data", "=", "session", ".", "get", "(", "WORK_UNITS_", "+", "work_spec_name", "+", "_FAILED", ",", "work_unit_key", ")", "return", "work_unit_data" ]
Internal function that is used for generation of the page where notebooks are organized by tag values .
def _generate_notebook_by_tag_body ( notebook_object , dict_by_tag ) : tag_keys = list ( dict_by_tag . keys ( ) ) tag_keys . sort ( ) for tag in tag_keys : if tag . lower ( ) not in SIGNAL_TYPE_LIST : markdown_cell = group_tag_code . TAG_TABLE_HEADER markdown_cell = markdown_cell . replace ( "Tag i" , tag ) for notebook_file in dict_by_tag [ tag ] : split_path = notebook_file . split ( "\\" ) notebook_type = split_path [ - 2 ] notebook_name = split_path [ - 1 ] . split ( "&" ) [ 0 ] notebook_title = split_path [ - 1 ] . split ( "&" ) [ 1 ] markdown_cell += "\t<tr>\n\t\t<td width='20%' class='header_image_color_" + str ( NOTEBOOK_KEYS [ notebook_type ] ) + "'><img " "src='../../images/icons/" + notebook_type . title ( ) + ".png' width='15%'>\n\t\t</td>" markdown_cell += "\n\t\t<td width='60%' class='center_cell open_cell_light'>" + notebook_title + "\n\t\t</td>" markdown_cell += "\n\t\t<td width='20%' class='center_cell'>\n\t\t\t<a href='" "../" + notebook_type . title ( ) + "/" + notebook_name + "'><div class='file_icon'></div></a>\n\t\t</td>\n\t</tr>" markdown_cell += "</table>" # ==================== Insertion of HTML table in a new Notebook cell ====================== notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( markdown_cell ) )
4,166
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L640-L681
[ "def", "basic_client", "(", ")", ":", "es_connected", "=", "False", "while", "not", "es_connected", ":", "try", ":", "ES", "=", "Elasticsearch", "(", "hosts", "=", "[", "HOSTNAME", "]", ")", "es_connected", "=", "True", "except", "TransportError", "as", "e", ":", "logging", ".", "info", "(", "'Not yet connected: %s, sleeping for 1s'", ",", "e", ")", "time", ".", "sleep", "(", "1", ")", "return", "ES" ]
Class method responsible for adding a markdown cell with content content to the Notebook object .
def add_markdown_cell ( self , content , tags = None ) : self . notebook [ "cells" ] . append ( nb . v4 . new_markdown_cell ( content , * * { "metadata" : { "tags" : tags } } ) )
4,167
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L186-L201
[ "def", "interpoled_resampling", "(", "W", ",", "x", ")", ":", "N", "=", "W", ".", "shape", "[", "0", "]", "idx", "=", "np", ".", "argsort", "(", "x", ")", "xs", "=", "x", "[", "idx", "]", "ws", "=", "W", "[", "idx", "]", "cs", "=", "np", ".", "cumsum", "(", "avg_n_nplusone", "(", "ws", ")", ")", "u", "=", "random", ".", "rand", "(", "N", ")", "xrs", "=", "np", ".", "empty", "(", "N", ")", "where", "=", "np", ".", "searchsorted", "(", "cs", ",", "u", ")", "# costs O(N log(N)) but algorithm has O(N log(N)) complexity anyway", "for", "n", "in", "range", "(", "N", ")", ":", "m", "=", "where", "[", "n", "]", "if", "m", "==", "0", ":", "xrs", "[", "n", "]", "=", "xs", "[", "0", "]", "elif", "m", "==", "N", ":", "xrs", "[", "n", "]", "=", "xs", "[", "-", "1", "]", "else", ":", "xrs", "[", "n", "]", "=", "interpol", "(", "cs", "[", "m", "-", "1", "]", ",", "cs", "[", "m", "]", ",", "xs", "[", "m", "-", "1", "]", ",", "xs", "[", "m", "]", ",", "u", "[", "n", "]", ")", "return", "xrs" ]
Class method responsible for adding a code cell with content content to the Notebook object .
def add_code_cell ( self , content , tags = None ) : self . notebook [ "cells" ] . append ( nb . v4 . new_code_cell ( content , * * { "metadata" : { "tags" : tags } } ) )
4,168
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L203-L219
[ "def", "all", "(", "cls", ")", ":", "# Start with raw queues we know exist from the config", "queues", "=", "{", "x", ":", "0", "for", "x", "in", "Queue", ".", "get_queues_config", "(", ")", "}", "stats", "=", "list", "(", "context", ".", "connections", ".", "mongodb_jobs", ".", "mrq_jobs", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "{", "\"status\"", ":", "\"queued\"", "}", "}", ",", "{", "\"$group\"", ":", "{", "\"_id\"", ":", "\"$queue\"", ",", "\"jobs\"", ":", "{", "\"$sum\"", ":", "1", "}", "}", "}", "]", ")", ")", "queues", ".", "update", "(", "{", "x", "[", "\"_id\"", "]", ":", "x", "[", "\"jobs\"", "]", "for", "x", "in", "stats", "}", ")", "return", "queues" ]
Tracking Protection shield .
def is_tracking_shield_displayed ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : if self . window . firefox_version >= 63 : # Bug 1471713, 1476218 el = self . root . find_element ( * self . _tracking_protection_shield_locator ) return el . get_attribute ( "active" ) is not None el = self . root . find_element ( By . ID , "tracking-protection-icon" ) return bool ( el . get_attribute ( "state" ) )
4,169
https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/navbar.py#L26-L38
[ "def", "log_tail", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "request", "(", "'/log/tail'", ",", "decoder", "=", "'json'", ",", "stream", "=", "True", ",", "*", "*", "kwargs", ")" ]
Checks if the device + username have already been registered with the bridge .
def validate_registration ( self ) : url = '/api/%s' % self . username response = self . make_request ( 'GET' , url ) if 'error' in response : return False return True
4,170
https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L64-L75
[ "def", "read_content", "(", "self", ")", ":", "if", "self", ".", "is_directory", "(", ")", ":", "self", ".", "url_connection", ".", "cwd", "(", "self", ".", "filename", ")", "self", ".", "files", "=", "self", ".", "get_files", "(", ")", "# XXX limit number of files?", "data", "=", "get_index_html", "(", "self", ".", "files", ")", "else", ":", "# download file in BINARY mode", "ftpcmd", "=", "\"RETR %s\"", "%", "self", ".", "filename", "buf", "=", "StringIO", "(", ")", "def", "stor_data", "(", "s", ")", ":", "\"\"\"Helper method storing given data\"\"\"", "# limit the download size", "if", "(", "buf", ".", "tell", "(", ")", "+", "len", "(", "s", ")", ")", ">", "self", ".", "max_size", ":", "raise", "LinkCheckerError", "(", "_", "(", "\"FTP file size too large\"", ")", ")", "buf", ".", "write", "(", "s", ")", "self", ".", "url_connection", ".", "retrbinary", "(", "ftpcmd", ",", "stor_data", ")", "data", "=", "buf", ".", "getvalue", "(", ")", "buf", ".", "close", "(", ")", "return", "data" ]
Registers a new device + username with the bridge
def connect ( self ) : # Don't try to register if we already have if self . validate_registration ( ) : return True body = { 'devicetype' : self . device_type , 'username' : self . username , } response = self . make_request ( 'POST' , '/api' , body ) if 'error' in response : if response [ 'error' ] [ 'type' ] == 101 : msg = 'Please press the link button and try again' else : msg = response [ 'error' ] [ 'description' ] raise Exception ( msg )
4,171
https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L77-L97
[ "def", "get_time", "(", "self", ",", "instance", ")", ":", "url", "=", "'/instances/{}'", ".", "format", "(", "instance", ")", "response", "=", "self", ".", "get_proto", "(", "url", ")", "message", "=", "yamcsManagement_pb2", ".", "YamcsInstance", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "if", "message", ".", "HasField", "(", "'missionTime'", ")", ":", "return", "parse_isostring", "(", "message", ".", "missionTime", ")", "return", "None" ]
Lists all available lights on the bridge .
def get_lights ( self ) : url = '/api/%s/lights' % self . username response = self . make_request ( 'GET' , url ) lights = [ ] # Did we get a success response back? # error responses look like: # [{'error': {'address': '/lights', # 'description': 'unauthorized user', # 'type': 1}}] if 'error' in response : raise Exception ( response [ 'error' ] [ 'description' ] ) for id_ , data in response . items ( ) : lights . append ( Light ( id_ , data [ 'modelid' ] , data [ 'name' ] , data [ 'state' ] , data [ 'swversion' ] , data [ 'type' ] , data [ 'uniqueid' ] ) ) lights = sorted ( lights , key = lambda x : x . light_id ) self . _lights = lights return lights
4,172
https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L99-L128
[ "def", "to_value", "(", "original_string", ",", "corenlp_value", "=", "None", ")", ":", "if", "isinstance", "(", "original_string", ",", "Value", ")", ":", "# Already a Value", "return", "original_string", "if", "not", "corenlp_value", ":", "corenlp_value", "=", "original_string", "# Number?", "amount", "=", "NumberValue", ".", "parse", "(", "corenlp_value", ")", "if", "amount", "is", "not", "None", ":", "return", "NumberValue", "(", "amount", ",", "original_string", ")", "# Date?", "ymd", "=", "DateValue", ".", "parse", "(", "corenlp_value", ")", "if", "ymd", "is", "not", "None", ":", "if", "ymd", "[", "1", "]", "==", "ymd", "[", "2", "]", "==", "-", "1", ":", "return", "NumberValue", "(", "ymd", "[", "0", "]", ",", "original_string", ")", "else", ":", "return", "DateValue", "(", "ymd", "[", "0", "]", ",", "ymd", "[", "1", "]", ",", "ymd", "[", "2", "]", ",", "original_string", ")", "# String.", "return", "StringValue", "(", "original_string", ")" ]
This will set the light color based on a hex value
def set_color ( self , light_id , hex_value , brightness = None ) : light = self . get_light ( light_id ) xy = get_xy_from_hex ( hex_value ) data = { 'xy' : [ xy . x , xy . y ] , } if brightness is not None : data [ 'bri' ] = brightness return self . set_state ( light . light_id , * * data )
4,173
https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L170-L184
[ "def", "parse_journal", "(", "journal", ")", ":", "events", "=", "[", "e", "for", "e", "in", "journal", "if", "not", "isinstance", "(", "e", ",", "CorruptedUsnRecord", ")", "]", "keyfunc", "=", "lambda", "e", ":", "str", "(", "e", ".", "file_reference_number", ")", "+", "e", ".", "file_name", "+", "e", ".", "timestamp", "event_groups", "=", "(", "tuple", "(", "g", ")", "for", "k", ",", "g", "in", "groupby", "(", "events", ",", "key", "=", "keyfunc", ")", ")", "if", "len", "(", "events", ")", "<", "len", "(", "list", "(", "journal", ")", ")", ":", "LOGGER", ".", "debug", "(", "\"Corrupted records in UsnJrnl, some events might be missing.\"", ")", "return", "[", "journal_event", "(", "g", ")", "for", "g", "in", "event_groups", "]" ]
This functions computes the fft of a signal returning the frequency and their magnitude values .
def plotfft ( s , fmax , doplot = False ) : fs = abs ( np . fft . fft ( s ) ) f = linspace ( 0 , fmax / 2 , len ( s ) / 2 ) if doplot : #pl.plot(f[1:int(len(s) / 2)], fs[1:int(len(s) / 2)]) pass return ( f [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) , fs [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) )
4,174
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py#L8-L34
[ "def", "list_blobs", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "# pylint: disable=unused-argument", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "'container'", "not", "in", "kwargs", ":", "raise", "SaltCloudSystemExit", "(", "'A container must be specified'", ")", "storageservice", "=", "_get_block_blob_service", "(", "kwargs", ")", "ret", "=", "{", "}", "try", ":", "for", "blob", "in", "storageservice", ".", "list_blobs", "(", "kwargs", "[", "'container'", "]", ")", ".", "items", ":", "ret", "[", "blob", ".", "name", "]", "=", "{", "'blob_type'", ":", "blob", ".", "properties", ".", "blob_type", ",", "'last_modified'", ":", "blob", ".", "properties", ".", "last_modified", ".", "isoformat", "(", ")", ",", "'server_encrypted'", ":", "blob", ".", "properties", ".", "server_encrypted", ",", "}", "except", "Exception", "as", "exc", ":", "log", ".", "warning", "(", "six", ".", "text_type", "(", "exc", ")", ")", "return", "ret" ]
Discovers services on a network using the SSDP Protocol .
def discover ( service , timeout = 5 , retries = 5 ) : group = ( '239.255.255.250' , 1900 ) message = '\r\n' . join ( [ 'M-SEARCH * HTTP/1.1' , 'HOST: {0}:{1}' , 'MAN: "ssdp:discover"' , 'ST: {st}' , 'MX: 3' , '' , '' ] ) socket . setdefaulttimeout ( timeout ) responses = { } for _ in range ( retries ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP ) sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) sock . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_TTL , 2 ) data = message . format ( * group , st = service ) sock . sendto ( data . encode ( 'utf-8' ) , group ) while True : try : response = SSDPResponse ( sock . recv ( 1024 ) ) responses [ response . location ] = response except socket . timeout : break if responses : break return responses . values ( )
4,175
https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/ssdp.py#L32-L65
[ "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" ]
Checks if the specified model instance matches the class model . By default this method will raise a ValueError if the model is not of expected type .
def _isinstance ( self , model , raise_error = True ) : rv = isinstance ( model , self . __model__ ) if not rv and raise_error : raise ValueError ( '%s is not of type %s' % ( model , self . __model__ ) ) return rv
4,176
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L108-L128
[ "def", "_config_options", "(", "self", ")", ":", "self", ".", "_config_sortable", "(", "self", ".", "_sortable", ")", "self", ".", "_config_drag_cols", "(", "self", ".", "_drag_cols", ")" ]
Returns a preprocessed dictionary of parameters . Use this to filter the kwargs passed to new create build methods .
def _preprocess_params ( cls , kwargs ) : # kwargs.pop('csrf_token', None) for attr , val in kwargs . items ( ) : if cls . is_the_primary_key ( attr ) and cls . _prevent_primary_key_initialization_ : del kwargs [ attr ] continue if val == "" : # Making an assumption that there is no good usecase # for setting an empty string. This will help prevent # cases where empty string is sent because of client # not clearing form fields to null kwargs [ attr ] = None continue if attr in class_mapper ( cls ) . relationships and attr not in cls . _no_overwrite_ : rel = class_mapper ( cls ) . relationships [ attr ] if rel . uselist : if isinstance ( val , list ) : if all ( isinstance ( v , dict ) for v in val ) : rel_cls = cls . mapped_rel_class ( attr ) kwargs [ attr ] = rel_cls . update_or_new_all ( list_of_kwargs = val , keys = [ rel_cls . primary_key_name ( ) ] ) elif isinstance ( val , dict ) : rel_cls = cls . mapped_rel_class ( attr ) mapping_col = rel . collection_class ( ) . keyfunc . name list_of_kwargs = [ merge ( v , { mapping_col : k } ) for k , v in val . items ( ) ] kwargs [ attr ] = { getattr ( obj , mapping_col ) : obj for obj in rel_cls . update_or_new_all ( list_of_kwargs = list_of_kwargs , keys = [ rel_cls . primary_key_name ( ) ] ) } elif isinstance ( val , dict ) : rel_cls = cls . mapped_rel_class ( attr ) kwargs [ attr ] = rel_cls . update_or_new ( * * merge ( val , { 'keys' : [ rel_cls . primary_key_name ( ) ] } ) ) return kwargs
4,177
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L135-L174
[ "def", "getChargingVoltage", "(", "self", ")", ":", "command", "=", "'$GG'", "currentAndVoltage", "=", "self", ".", "sendCommand", "(", "command", ")", "volts", "=", "float", "(", "currentAndVoltage", "[", "2", "]", ")", "/", "1000", "return", "volts" ]
Updates an instance .
def update ( self , * * kwargs ) : kwargs = self . _preprocess_params ( kwargs ) kwargs = self . preprocess_kwargs_before_update ( kwargs ) for key , value in kwargs . iteritems ( ) : cls = type ( self ) if not hasattr ( cls , key ) or isinstance ( getattr ( cls , key ) , property ) : continue if key not in self . _no_overwrite_ : setattr ( self , key , value ) if isinstance ( getattr ( self , key ) , OrderingList ) : getattr ( self , key ) . reorder ( ) elif isinstance ( getattr ( cls , key ) , AssociationProxyInstance ) : target_name = getattr ( cls , key ) . target_collection target_rel = getattr ( self , target_name ) if isinstance ( target_rel , OrderingList ) : target_rel . reorder ( ) try : self . session . commit ( ) return self except Exception as e : self . session . rollback ( ) raise e
4,178
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L203-L235
[ "def", "restore", "(", "self", ")", ":", "clean_beam", ",", "beam_params", "=", "beam_fit", "(", "self", ".", "psf_data", ",", "self", ".", "cdelt1", ",", "self", ".", "cdelt2", ")", "if", "np", ".", "all", "(", "np", ".", "array", "(", "self", ".", "psf_data_shape", ")", "==", "2", "*", "np", ".", "array", "(", "self", ".", "dirty_data_shape", ")", ")", ":", "self", ".", "restored", "=", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "irfft2", "(", "np", ".", "fft", ".", "rfft2", "(", "conv", ".", "pad_array", "(", "self", ".", "model", ")", ")", "*", "np", ".", "fft", ".", "rfft2", "(", "clean_beam", ")", ")", ")", "self", ".", "restored", "=", "self", ".", "restored", "[", "self", ".", "dirty_data_shape", "[", "0", "]", "/", "2", ":", "-", "self", ".", "dirty_data_shape", "[", "0", "]", "/", "2", ",", "self", ".", "dirty_data_shape", "[", "1", "]", "/", "2", ":", "-", "self", ".", "dirty_data_shape", "[", "1", "]", "/", "2", "]", "else", ":", "self", ".", "restored", "=", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "irfft2", "(", "np", ".", "fft", ".", "rfft2", "(", "self", ".", "model", ")", "*", "np", ".", "fft", ".", "rfft2", "(", "clean_beam", ")", ")", ")", "self", ".", "restored", "+=", "self", ".", "residual", "self", ".", "restored", "=", "self", ".", "restored", ".", "astype", "(", "np", ".", "float32", ")", "return", "beam_params" ]
Same as SQLAlchemy s filter_by . Additionally this accepts two special keyword arguments limit and reverse for limiting the results and reversing the order respectively .
def filter_by ( cls , * * kwargs ) : limit = kwargs . pop ( 'limit' , None ) reverse = kwargs . pop ( 'reverse' , False ) q = cls . query . filter_by ( * * kwargs ) if reverse : q = q . order_by ( cls . id . desc ( ) ) if limit : q = q . limit ( limit ) return q
4,179
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L238-L261
[ "def", "generation", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "state", "is", "not", "MemberState", ".", "STABLE", ":", "return", "None", "return", "self", ".", "_generation" ]
Returns a count of the instances meeting the specified filter criterion and kwargs .
def count ( cls , * criterion , * * kwargs ) : if criterion or kwargs : return cls . filter ( * criterion , * * kwargs ) . count ( ) else : return cls . query . count ( )
4,180
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L290-L311
[ "def", "main", "(", "inputstructs", ",", "inputpdbids", ")", ":", "pdbid", ",", "pdbpath", "=", "None", ",", "None", "# #@todo For multiprocessing, implement better stacktracing for errors", "# Print title and version", "title", "=", "\"* Protein-Ligand Interaction Profiler v%s *\"", "%", "__version__", "write_message", "(", "'\\n'", "+", "'*'", "*", "len", "(", "title", ")", "+", "'\\n'", ")", "write_message", "(", "title", ")", "write_message", "(", "'\\n'", "+", "'*'", "*", "len", "(", "title", ")", "+", "'\\n\\n'", ")", "outputprefix", "=", "config", ".", "OUTPUTFILENAME", "if", "inputstructs", "is", "not", "None", ":", "# Process PDB file(s)", "num_structures", "=", "len", "(", "inputstructs", ")", "inputstructs", "=", "remove_duplicates", "(", "inputstructs", ")", "read_from_stdin", "=", "False", "for", "inputstruct", "in", "inputstructs", ":", "if", "inputstruct", "==", "'-'", ":", "inputstruct", "=", "sys", ".", "stdin", ".", "read", "(", ")", "read_from_stdin", "=", "True", "if", "config", ".", "RAWSTRING", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", ")", ":", "inputstruct", "=", "bytes", "(", "inputstruct", ")", ".", "decode", "(", "'unicode_escape'", ")", "else", ":", "inputstruct", "=", "bytes", "(", "inputstruct", ",", "'utf8'", ")", ".", "decode", "(", "'unicode_escape'", ")", "else", ":", "if", "os", ".", "path", ".", "getsize", "(", "inputstruct", ")", "==", "0", ":", "sysexit", "(", "2", ",", "'Empty PDB file\\n'", ")", "# Exit if input file is empty", "if", "num_structures", ">", "1", ":", "basename", "=", "inputstruct", ".", "split", "(", "'.'", ")", "[", "-", "2", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "config", ".", "OUTPATH", "=", "'/'", ".", "join", "(", "[", "config", ".", "BASEPATH", ",", "basename", "]", ")", "outputprefix", "=", "'report'", "process_pdb", "(", "inputstruct", ",", "config", ".", "OUTPATH", ",", "as_string", "=", "read_from_stdin", ",", "outputprefix", "=", "outputprefix", ")", "else", ":", "# Try to fetch the current PDB structure(s) directly from the RCBS server", "num_pdbids", "=", "len", "(", "inputpdbids", ")", "inputpdbids", "=", "remove_duplicates", "(", "inputpdbids", ")", "for", "inputpdbid", "in", "inputpdbids", ":", "pdbpath", ",", "pdbid", "=", "download_structure", "(", "inputpdbid", ")", "if", "num_pdbids", ">", "1", ":", "config", ".", "OUTPATH", "=", "'/'", ".", "join", "(", "[", "config", ".", "BASEPATH", ",", "pdbid", "[", "1", ":", "3", "]", ".", "upper", "(", ")", ",", "pdbid", ".", "upper", "(", ")", "]", ")", "outputprefix", "=", "'report'", "process_pdb", "(", "pdbpath", ",", "config", ".", "OUTPATH", ",", "outputprefix", "=", "outputprefix", ")", "if", "(", "pdbid", "is", "not", "None", "or", "inputstructs", "is", "not", "None", ")", "and", "config", ".", "BASEPATH", "is", "not", "None", ":", "if", "config", ".", "BASEPATH", "in", "[", "'.'", ",", "'./'", "]", ":", "write_message", "(", "'\\nFinished analysis. Find the result files in the working directory.\\n\\n'", ")", "else", ":", "write_message", "(", "'\\nFinished analysis. Find the result files in %s\\n\\n'", "%", "config", ".", "BASEPATH", ")" ]
Returns a new unsaved instance of the model class .
def new ( cls , * * kwargs ) : kwargs = cls . preprocess_kwargs_before_new ( kwargs ) if cls . __mapper__ . polymorphic_on is not None : discriminator_key = cls . __mapper__ . polymorphic_on . name discriminator_val = kwargs . get ( discriminator_key ) if discriminator_val is not None and discriminator_val in cls . __mapper__ . polymorphic_map : actual_cls = cls . __mapper__ . polymorphic_map [ discriminator_val ] . class_ return actual_cls ( * * subdict ( actual_cls . _preprocess_params ( kwargs ) , actual_cls . all_settable_keys ( ) ) ) return cls ( * * subdict ( cls . _preprocess_params ( kwargs ) , cls . all_settable_keys ( ) ) )
4,181
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L371-L386
[ "def", "external_metadata", "(", "self", ",", "datasource_type", "=", "None", ",", "datasource_id", "=", "None", ")", ":", "if", "datasource_type", "==", "'druid'", ":", "datasource", "=", "ConnectorRegistry", ".", "get_datasource", "(", "datasource_type", ",", "datasource_id", ",", "db", ".", "session", ")", "elif", "datasource_type", "==", "'table'", ":", "database", "=", "(", "db", ".", "session", ".", "query", "(", "Database", ")", ".", "filter_by", "(", "id", "=", "request", ".", "args", ".", "get", "(", "'db_id'", ")", ")", ".", "one", "(", ")", ")", "Table", "=", "ConnectorRegistry", ".", "sources", "[", "'table'", "]", "datasource", "=", "Table", "(", "database", "=", "database", ",", "table_name", "=", "request", ".", "args", ".", "get", "(", "'table_name'", ")", ",", "schema", "=", "request", ".", "args", ".", "get", "(", "'schema'", ")", "or", "None", ",", ")", "external_metadata", "=", "datasource", ".", "external_metadata", "(", ")", "return", "self", ".", "json_response", "(", "external_metadata", ")" ]
Adds a model instance to session and commits the transaction .
def add ( cls , model , commit = True ) : if not isinstance ( model , cls ) : raise ValueError ( '%s is not of type %s' % ( model , cls ) ) cls . session . add ( model ) try : if commit : cls . session . commit ( ) return model except : cls . session . rollback ( ) raise
4,182
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L389-L413
[ "def", "calibrate_data", "(", "params", ",", "raw_data", ",", "calib_data", ")", ":", "start", "=", "calib_data", ".", "before", "(", "datetime", ".", "max", ")", "if", "start", "is", "None", ":", "start", "=", "datetime", ".", "min", "start", "=", "raw_data", ".", "after", "(", "start", "+", "SECOND", ")", "if", "start", "is", "None", ":", "return", "start", "del", "calib_data", "[", "start", ":", "]", "calibrator", "=", "Calib", "(", "params", ",", "raw_data", ")", "def", "calibgen", "(", "inputdata", ")", ":", "\"\"\"Internal generator function\"\"\"", "count", "=", "0", "for", "data", "in", "inputdata", ":", "idx", "=", "data", "[", "'idx'", "]", "count", "+=", "1", "if", "count", "%", "10000", "==", "0", ":", "logger", ".", "info", "(", "\"calib: %s\"", ",", "idx", ".", "isoformat", "(", "' '", ")", ")", "elif", "count", "%", "500", "==", "0", ":", "logger", ".", "debug", "(", "\"calib: %s\"", ",", "idx", ".", "isoformat", "(", "' '", ")", ")", "for", "key", "in", "(", "'rain'", ",", "'abs_pressure'", ",", "'temp_in'", ")", ":", "if", "data", "[", "key", "]", "is", "None", ":", "logger", ".", "error", "(", "'Ignoring invalid data at %s'", ",", "idx", ".", "isoformat", "(", "' '", ")", ")", "break", "else", ":", "yield", "calibrator", ".", "calib", "(", "data", ")", "calib_data", ".", "update", "(", "calibgen", "(", "raw_data", "[", "start", ":", "]", ")", ")", "return", "start" ]
Batch method for adding a list of model instances to the db in one get_or_404 .
def add_all ( cls , models , commit = True , check_type = False ) : if check_type : for model in models : if not isinstance ( model , cls ) : raise ValueError ( '%s is not of type %s' ( model , cls ) ) if None in models : cls . session . add_all ( [ m for m in models if m is not None ] ) else : cls . session . add_all ( models ) try : if commit : cls . session . commit ( ) return models except : cls . session . rollback ( ) raise
4,183
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L416-L447
[ "def", "register_on_snapshot_taken", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_snapshot_taken", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_type", ")" ]
Fetches a single instance which has value keyval for the attribute key .
def get ( cls , keyval , key = 'id' , user_id = None ) : if keyval is None : return None if ( key in cls . __table__ . columns and cls . __table__ . columns [ key ] . primary_key ) : # if user_id and hasattr(cls, 'user_id'): # return cls.query.filter_by(id=keyval, user_id=user_id).first() return cls . query . get ( keyval ) else : result = cls . query . filter ( getattr ( cls , key ) == keyval ) # if user_id and hasattr(cls, 'user_id'): # result = result.filter(cls.user_id == user_id) return result . first ( )
4,184
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L458-L494
[ "def", "get_correlation_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Correlations\"", ",", "label", "=", "\"tab:parameter_correlations\"", ")", ":", "parameters", ",", "cor", "=", "self", ".", "get_correlations", "(", "chain", "=", "chain", ",", "parameters", "=", "parameters", ")", "return", "self", ".", "_get_2d_latex_table", "(", "parameters", ",", "cor", ",", "caption", ",", "label", ")" ]
Works like a map function from keyvals to instances .
def get_all ( cls , keyvals , key = 'id' , user_id = None ) : if len ( keyvals ) == 0 : return [ ] original_keyvals = keyvals keyvals_set = list ( set ( keyvals ) ) resultset = cls . query . filter ( getattr ( cls , key ) . in_ ( keyvals_set ) ) # This is ridiculous. user_id check cannot be here. A hangover # from the time this lib was inside our app codebase # if user_id and hasattr(cls, 'user_id'): # resultset = resultset.filter(cls.user_id == user_id) # We need the results in the same order as the input keyvals # So order by field in SQL key_result_mapping = { getattr ( result , key ) : result for result in resultset . all ( ) } return [ key_result_mapping . get ( kv ) for kv in original_keyvals ]
4,185
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L497-L537
[ "def", "_corrupt", "(", "self", ",", "data", ",", "dpos", ")", ":", "ws", "=", "list", "(", "self", ".", "_BLK_BE", ".", "unpack_from", "(", "data", ",", "dpos", ")", ")", "for", "t", "in", "range", "(", "16", ",", "80", ")", ":", "tmp", "=", "ws", "[", "(", "t", "-", "3", ")", "&", "15", "]", "^", "ws", "[", "(", "t", "-", "8", ")", "&", "15", "]", "^", "ws", "[", "(", "t", "-", "14", ")", "&", "15", "]", "^", "ws", "[", "(", "t", "-", "16", ")", "&", "15", "]", "ws", "[", "t", "&", "15", "]", "=", "(", "(", "tmp", "<<", "1", ")", "|", "(", "tmp", ">>", "(", "32", "-", "1", ")", ")", ")", "&", "0xFFFFFFFF", "self", ".", "_BLK_LE", ".", "pack_into", "(", "data", ",", "dpos", ",", "*", "ws", ")" ]
Initializes a new instance adds it to the db and commits the transaction .
def create ( cls , * * kwargs ) : try : return cls . add ( cls . new ( * * kwargs ) ) except : cls . session . rollback ( ) raise
4,186
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L559-L577
[ "def", "calculateOptionPrice", "(", "self", ",", "contract", ":", "Contract", ",", "volatility", ":", "float", ",", "underPrice", ":", "float", ",", "optPrcOptions", "=", "None", ")", "->", "OptionComputation", ":", "return", "self", ".", "_run", "(", "self", ".", "calculateOptionPriceAsync", "(", "contract", ",", "volatility", ",", "underPrice", ",", "optPrcOptions", ")", ")" ]
Checks if an instance already exists by filtering with the kwargs . If yes returns that instance . If not creates a new instance with kwargs and returns it
def find_or_create ( cls , * * kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] return cls . first ( * * subdict ( kwargs , keys ) ) or cls . create ( * * kwargs )
4,187
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L580-L615
[ "def", "sort_response", "(", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "OrderedDict", ":", "root_order", "=", "[", "\"jsonrpc\"", ",", "\"result\"", ",", "\"error\"", ",", "\"id\"", "]", "error_order", "=", "[", "\"code\"", ",", "\"message\"", ",", "\"data\"", "]", "req", "=", "OrderedDict", "(", "sorted", "(", "response", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "root_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")", "if", "\"error\"", "in", "response", ":", "req", "[", "\"error\"", "]", "=", "OrderedDict", "(", "sorted", "(", "response", "[", "\"error\"", "]", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "error_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")", "return", "req" ]
Checks if an instance already exists by filtering with the kwargs . If yes updates the instance with new kwargs and returns that instance . If not creates a new instance with kwargs and returns it .
def update_or_create ( cls , * * kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] filter_kwargs = subdict ( kwargs , keys ) if filter_kwargs == { } : obj = None else : obj = cls . first ( * * filter_kwargs ) if obj is not None : for key , value in kwargs . iteritems ( ) : if ( key not in keys and key not in cls . _no_overwrite_ ) : setattr ( obj , key , value ) try : cls . session . commit ( ) except : cls . session . rollback ( ) raise else : obj = cls . create ( * * kwargs ) return obj
4,188
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L671-L725
[ "def", "sort_response", "(", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "OrderedDict", ":", "root_order", "=", "[", "\"jsonrpc\"", ",", "\"result\"", ",", "\"error\"", ",", "\"id\"", "]", "error_order", "=", "[", "\"code\"", ",", "\"message\"", ",", "\"data\"", "]", "req", "=", "OrderedDict", "(", "sorted", "(", "response", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "root_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")", "if", "\"error\"", "in", "response", ":", "req", "[", "\"error\"", "]", "=", "OrderedDict", "(", "sorted", "(", "response", "[", "\"error\"", "]", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "error_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")", "return", "req" ]
Batch method for creating a list of instances
def create_all ( cls , list_of_kwargs ) : try : return cls . add_all ( [ cls . new ( * * kwargs ) if kwargs is not None else None for kwargs in list_of_kwargs ] ) except : cls . session . rollback ( ) raise
4,189
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L728-L747
[ "def", "dir", "(", "self", ",", "path", "=", "'/'", ",", "slash", "=", "True", ",", "bus", "=", "False", ",", "timeout", "=", "0", ")", ":", "if", "slash", ":", "msg", "=", "MSG_DIRALLSLASH", "else", ":", "msg", "=", "MSG_DIRALL", "if", "bus", ":", "flags", "=", "self", ".", "flags", "|", "FLG_BUS_RET", "else", ":", "flags", "=", "self", ".", "flags", "&", "~", "FLG_BUS_RET", "ret", ",", "data", "=", "self", ".", "sendmess", "(", "msg", ",", "str2bytez", "(", "path", ")", ",", "flags", ",", "timeout", "=", "timeout", ")", "if", "ret", "<", "0", ":", "raise", "OwnetError", "(", "-", "ret", ",", "self", ".", "errmess", "[", "-", "ret", "]", ",", "path", ")", "if", "data", ":", "return", "bytes2str", "(", "data", ")", ".", "split", "(", "','", ")", "else", ":", "return", "[", "]" ]
Batch method for querying for a list of instances and creating them if required
def find_or_create_all ( cls , list_of_kwargs , keys = [ ] ) : list_of_kwargs_wo_dupes , markers = remove_and_mark_duplicate_dicts ( list_of_kwargs , keys ) added_objs = cls . add_all ( [ cls . first ( * * subdict ( kwargs , keys ) ) or cls . new ( * * kwargs ) for kwargs in list_of_kwargs_wo_dupes ] ) result_objs = [ ] iterator_of_added_objs = iter ( added_objs ) for idx in range ( len ( list_of_kwargs ) ) : if idx in markers : result_objs . append ( added_objs [ markers [ idx ] ] ) else : result_objs . append ( next ( iterator_of_added_objs ) ) return result_objs
4,190
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L750-L783
[ "def", "_parse_ftp_error", "(", "error", ")", ":", "# type: (ftplib.Error) -> Tuple[Text, Text]", "code", ",", "_", ",", "message", "=", "text_type", "(", "error", ")", ".", "partition", "(", "\" \"", ")", "return", "code", ",", "message" ]
Batch method for updating a list of instances and creating them if required
def update_or_create_all ( cls , list_of_kwargs , keys = [ ] ) : objs = [ ] for kwargs in list_of_kwargs : filter_kwargs = subdict ( kwargs , keys ) if filter_kwargs == { } : obj = None else : obj = cls . first ( * * filter_kwargs ) if obj is not None : for key , value in kwargs . iteritems ( ) : if ( key not in keys and key not in cls . _no_overwrite_ ) : setattr ( obj , key , value ) else : obj = cls . new ( * * kwargs ) objs . append ( obj ) try : return cls . add_all ( objs ) except : cls . session . rollback ( ) raise
4,191
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L786-L825
[ "def", "dir", "(", "self", ",", "path", "=", "'/'", ",", "slash", "=", "True", ",", "bus", "=", "False", ",", "timeout", "=", "0", ")", ":", "if", "slash", ":", "msg", "=", "MSG_DIRALLSLASH", "else", ":", "msg", "=", "MSG_DIRALL", "if", "bus", ":", "flags", "=", "self", ".", "flags", "|", "FLG_BUS_RET", "else", ":", "flags", "=", "self", ".", "flags", "&", "~", "FLG_BUS_RET", "ret", ",", "data", "=", "self", ".", "sendmess", "(", "msg", ",", "str2bytez", "(", "path", ")", ",", "flags", ",", "timeout", "=", "timeout", ")", "if", "ret", "<", "0", ":", "raise", "OwnetError", "(", "-", "ret", ",", "self", ".", "errmess", "[", "-", "ret", "]", ",", "path", ")", "if", "data", ":", "return", "bytes2str", "(", "data", ")", ".", "split", "(", "','", ")", "else", ":", "return", "[", "]" ]
Similar to create . But the transaction is not committed
def build ( cls , * * kwargs ) : return cls . add ( cls . new ( * * kwargs ) , commit = False )
4,192
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L870-L882
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Checks if an instance already exists in db with these kwargs else returns a new saved instance of the service s model class .
def find_or_build ( cls , * * kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] return cls . first ( * * subdict ( kwargs , keys ) ) or cls . build ( * * kwargs )
4,193
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L885-L893
[ "def", "zlib_decompress_all_frames", "(", "data", ")", ":", "frames", "=", "bytearray", "(", ")", "data", "=", "bytes", "(", "data", ")", "while", "data", ":", "decomp", "=", "zlib", ".", "decompressobj", "(", ")", "try", ":", "frames", ".", "extend", "(", "decomp", ".", "decompress", "(", "data", ")", ")", "data", "=", "decomp", ".", "unused_data", "except", "zlib", ".", "error", ":", "frames", ".", "extend", "(", "data", ")", "break", "return", "frames" ]
Similar to create_all . But transaction is not committed .
def build_all ( cls , list_of_kwargs ) : return cls . add_all ( [ cls . new ( * * kwargs ) for kwargs in list_of_kwargs ] , commit = False )
4,194
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L909-L913
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Similar to find_or_create_all . But transaction is not committed .
def find_or_build_all ( cls , list_of_kwargs ) : return cls . add_all ( [ cls . first ( * * kwargs ) or cls . new ( * * kwargs ) for kwargs in list_of_kwargs ] , commit = False )
4,195
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L916-L920
[ "def", "get_publications", "(", ")", ":", "data", "=", "DOWNER", ".", "download", "(", "URL", ")", "dom", "=", "dhtmlparser", ".", "parseString", "(", "handle_encodnig", "(", "data", ")", ")", "book_list", "=", "dom", ".", "find", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"polozka\"", "}", ")", "books", "=", "[", "]", "for", "book", "in", "book_list", ":", "books", ".", "append", "(", "_process_book", "(", "book", ")", ")", "return", "books" ]
Batch method for updating all instances obeying the criterion
def update_all ( cls , * criterion , * * kwargs ) : try : r = cls . query . filter ( * criterion ) . update ( kwargs , 'fetch' ) cls . session . commit ( ) return r except : cls . session . rollback ( ) raise
4,196
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L923-L946
[ "def", "inputs_from_dataframe", "(", "df", ",", "delays", "=", "(", "1", ",", "2", ",", "3", ")", ",", "inputs", "=", "(", "1", ",", "2", ",", "-", "1", ")", ",", "outputs", "=", "None", ",", "normalize", "=", "True", ",", "verbosity", "=", "1", ")", ":", "ds", "=", "input_dataset_from_dataframe", "(", "df", "=", "df", ",", "delays", "=", "delays", ",", "inputs", "=", "inputs", ",", "outputs", "=", "outputs", ",", "normalize", "=", "normalize", ",", "verbosity", "=", "verbosity", ")", "return", "ds", "[", "'input'", "]" ]
Returns two arrays
def peakdelta ( v , delta , x = None ) : maxtab = [ ] mintab = [ ] if x is None : x = arange ( len ( v ) ) v = asarray ( v ) if len ( v ) != len ( x ) : sys . exit ( 'Input vectors v and x must have same length' ) if not isscalar ( delta ) : sys . exit ( 'Input argument delta must be a scalar' ) if delta <= 0 : sys . exit ( 'Input argument delta must be positive' ) mn , mx = Inf , - Inf mnpos , mxpos = NaN , NaN lookformax = True for i in arange ( len ( v ) ) : this = v [ i ] if this > mx : mx = this mxpos = x [ i ] if this < mn : mn = this mnpos = x [ i ] if lookformax : if this < mx - delta : maxtab . append ( ( mxpos , mx ) ) mn = this mnpos = x [ i ] lookformax = False else : if this > mn + delta : mintab . append ( ( mnpos , mn ) ) mx = this mxpos = x [ i ] lookformax = True return array ( maxtab ) , array ( mintab )
4,197
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/peakdelta.py#L15-L81
[ "def", "findNextPoint", "(", "DiscFac", ",", "Rfree", ",", "CRRA", ",", "PermGroFacCmp", ",", "UnempPrb", ",", "Rnrm", ",", "Beth", ",", "cNext", ",", "mNext", ",", "MPCnext", ",", "PFMPC", ")", ":", "uPP", "=", "lambda", "x", ":", "utilityPP", "(", "x", ",", "gam", "=", "CRRA", ")", "cNow", "=", "PermGroFacCmp", "*", "(", "DiscFac", "*", "Rfree", ")", "**", "(", "-", "1.0", "/", "CRRA", ")", "*", "cNext", "*", "(", "1", "+", "UnempPrb", "*", "(", "(", "cNext", "/", "(", "PFMPC", "*", "(", "mNext", "-", "1.0", ")", ")", ")", "**", "CRRA", "-", "1.0", ")", ")", "**", "(", "-", "1.0", "/", "CRRA", ")", "mNow", "=", "(", "PermGroFacCmp", "/", "Rfree", ")", "*", "(", "mNext", "-", "1.0", ")", "+", "cNow", "cUNext", "=", "PFMPC", "*", "(", "mNow", "-", "cNow", ")", "*", "Rnrm", "# See TBS Appendix \"E.1 The Consumption Function\" ", "natural", "=", "Beth", "*", "Rnrm", "*", "(", "1.0", "/", "uPP", "(", "cNow", ")", ")", "*", "(", "(", "1.0", "-", "UnempPrb", ")", "*", "uPP", "(", "cNext", ")", "*", "MPCnext", "+", "UnempPrb", "*", "uPP", "(", "cUNext", ")", "*", "PFMPC", ")", "# Convenience variable", "MPCnow", "=", "natural", "/", "(", "natural", "+", "1", ")", "return", "mNow", ",", "cNow", ",", "MPCnow" ]
Callback to execute on status of update of channel
def on_status_update ( self , channel , callback ) : if channel not in self . _callbacks : self . _callbacks [ channel ] = [ ] self . _callbacks [ channel ] . append ( callback )
4,198
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/modules/vmbpbn.py#L46-L52
[ "def", "dump", "(", "self", ",", "path", ":", "str", ",", "file_name", ":", "str", "=", "\"\"", ",", "*", "*", "kwargs", ":", "dict", ")", ":", "export", "=", "list", "(", ")", "for", "results", "in", "self", ".", "scroll", "(", ")", ":", "export", ".", "extend", "(", "results", ")", "if", "not", "path", ".", "endswith", "(", "'/'", ")", ":", "path", "+=", "'/'", "if", "file_name", "==", "''", ":", "file_name", "=", "self", ".", "index", "if", "not", "file_name", ".", "endswith", "(", "'.json'", ")", ":", "file_name", "+=", "'.json'", "store", "=", "path", "+", "file_name", "with", "open", "(", "store", ",", "'w'", ")", "as", "fp", ":", "json", ".", "dump", "(", "export", ",", "fp", ",", "*", "*", "kwargs", ")", "logging", ".", "info", "(", "\"Extracted %s records from the index %s and stored them in %s/%s.\"", ",", "len", "(", "export", ")", ",", "self", ".", "index", ",", "path", ",", "file_name", ")" ]
Create and return a temporary directory which you can use as a context manager .
def temp_chdir ( cwd = None ) : if six . PY3 : from tempfile import TemporaryDirectory with TemporaryDirectory ( ) as tempwd : origin = cwd or os . getcwd ( ) os . chdir ( tempwd ) try : yield tempwd if os . path . exists ( tempwd ) else '' finally : os . chdir ( origin ) else : from tempfile import mkdtemp tempwd = mkdtemp ( ) origin = cwd or os . getcwd ( ) os . chdir ( tempwd ) try : yield tempwd if os . path . exists ( tempwd ) else '' finally : os . chdir ( origin )
4,199
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/utils.py#L42-L83
[ "def", "update_qos_aggregated_configuration", "(", "self", ",", "qos_configuration", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}{}\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ",", "self", ".", "QOS_AGGREGATED_CONFIGURATION", ")", "return", "self", ".", "_helper", ".", "update", "(", "qos_configuration", ",", "uri", "=", "uri", ",", "timeout", "=", "timeout", ")" ]