idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
239,400 | def _getMyFirstDatetimeFrom ( self ) : myStartDt = getAwareDatetime ( self . repeat . dtstart , None , self . tz , dt . time . min ) return self . __after ( myStartDt , excludeCancellations = False ) | The datetime this event first started or None if it never did . |
239,401 | def _getMyFirstDatetimeTo ( self ) : myFirstDt = self . _getMyFirstDatetimeFrom ( ) if myFirstDt is not None : daysDelta = dt . timedelta ( days = self . num_days - 1 ) return getAwareDatetime ( myFirstDt . date ( ) + daysDelta , self . time_to , self . tz , dt . time . max ) | The datetime this event first finished or None if it never did . |
239,402 | def local_title ( self ) : name = self . title . partition ( " for " ) [ 0 ] exceptDate = getLocalDate ( self . except_date , self . time_from , self . tz ) title = _ ( "{exception} for {date}" ) . format ( exception = _ ( name ) , date = dateFormat ( exceptDate ) ) return title | Localised version of the human - readable title of the page . |
239,403 | def full_clean ( self , * args , ** kwargs ) : name = getattr ( self , 'name' , self . slugName . title ( ) ) self . title = "{} for {}" . format ( name , dateFormat ( self . except_date ) ) self . slug = "{}-{}" . format ( self . except_date , self . slugName ) super ( ) . full_clean ( * args , ** kwargs ) | Apply fixups that need to happen before per - field validation occurs . Sets the page s title . |
239,404 | def what ( self ) : originalFromDt = dt . datetime . combine ( self . except_date , timeFrom ( self . overrides . time_from ) ) changedFromDt = dt . datetime . combine ( self . date , timeFrom ( self . time_from ) ) originalDaysDelta = dt . timedelta ( days = self . overrides . num_days - 1 ) originalToDt = getAwareDat... | May return a postponed or rescheduled string depending what the start and finish time of the event has been changed to . |
239,405 | def _convertTZ ( self ) : tz = timezone . get_current_timezone ( ) dtstart = self [ 'DTSTART' ] dtend = self [ 'DTEND' ] if dtstart . zone ( ) == "UTC" : dtstart . dt = dtstart . dt . astimezone ( tz ) if dtend . zone ( ) == "UTC" : dtend . dt = dtend . dt . astimezone ( tz ) | Will convert UTC datetimes to the current local timezone |
239,406 | def to_naive_utc ( dtime ) : if not hasattr ( dtime , 'tzinfo' ) or dtime . tzinfo is None : return dtime dtime_utc = dtime . astimezone ( pytz . UTC ) dtime_naive = dtime_utc . replace ( tzinfo = None ) return dtime_naive | convert a datetime object to UTC and than remove the tzinfo if datetime is naive already return it |
239,407 | def create_timezone ( tz , first_date = None , last_date = None ) : if isinstance ( tz , pytz . tzinfo . StaticTzInfo ) : return _create_timezone_static ( tz ) first_date = dt . datetime . today ( ) if not first_date else to_naive_utc ( first_date ) last_date = dt . datetime . today ( ) if not last_date else to_naive_u... | create an icalendar vtimezone from a pytz . tzinfo object |
239,408 | def _create_timezone_static ( tz ) : timezone = icalendar . Timezone ( ) timezone . add ( 'TZID' , tz ) subcomp = icalendar . TimezoneStandard ( ) subcomp . add ( 'TZNAME' , tz ) subcomp . add ( 'DTSTART' , dt . datetime ( 1601 , 1 , 1 ) ) subcomp . add ( 'RDATE' , dt . datetime ( 1601 , 1 , 1 ) ) subcomp . add ( 'TZOF... | create an icalendar vtimezone from a pytz . tzinfo . StaticTzInfo |
239,409 | def bend ( mapping , source , context = None ) : context = { } if context is None else context transport = Transport ( source , context ) return _bend ( mapping , transport ) | The main bending function . |
239,410 | def protect ( self , protect_against = None ) : return ProtectedF ( self . _func , * self . _args , protect_against = protect_against , ** self . _kwargs ) | Return a ProtectedF with the same parameters and with the given protect_against . |
239,411 | def init_logs ( args , tool = "NanoPlot" ) : start_time = dt . fromtimestamp ( time ( ) ) . strftime ( '%Y%m%d_%H%M' ) logname = os . path . join ( args . outdir , args . prefix + tool + "_" + start_time + ".log" ) handlers = [ logging . FileHandler ( logname ) ] if args . verbose : handlers . append ( logging . Stream... | Initiate log file and log arguments . |
239,412 | def flag_length_outliers ( df , columnname ) : return df [ columnname ] > ( np . median ( df [ columnname ] ) + 3 * np . std ( df [ columnname ] ) ) | Return index of records with length - outliers above 3 standard deviations from the median . |
239,413 | def _raise_for_status ( response ) : http_error_msg = "" if 400 <= response . status_code < 500 : http_error_msg = "{0} Client Error: {1}" . format ( response . status_code , response . reason ) elif 500 <= response . status_code < 600 : http_error_msg = "{0} Server Error: {1}" . format ( response . status_code , respo... | Custom raise_for_status with more appropriate error message . |
239,414 | def _clear_empty_values ( args ) : result = { } for param in args : if args [ param ] is not None : result [ param ] = args [ param ] return result | Scrap junk data from a dict . |
239,415 | def authentication_validation ( username , password , access_token ) : if bool ( username ) is not bool ( password ) : raise Exception ( "Basic authentication requires a username AND" " password." ) if ( username and access_token ) or ( password and access_token ) : raise Exception ( "Cannot use both Basic Authenticati... | Only accept one form of authentication . |
239,416 | def _download_file ( url , local_filename ) : response = requests . get ( url , stream = True ) with open ( local_filename , 'wb' ) as outfile : for chunk in response . iter_content ( chunk_size = 1024 ) : if chunk : outfile . write ( chunk ) | Utility function that downloads a chunked response from the specified url to a local path . This method is suitable for larger downloads . |
239,417 | def set_permission ( self , dataset_identifier , permission = "private" , content_type = "json" ) : resource = _format_old_api_request ( dataid = dataset_identifier , content_type = content_type ) params = { "method" : "setPermission" , "value" : "public.read" if permission == "public" else permission } return self . _... | Set a dataset s permissions to private or public Options are private public |
239,418 | def get_metadata ( self , dataset_identifier , content_type = "json" ) : resource = _format_old_api_request ( dataid = dataset_identifier , content_type = content_type ) return self . _perform_request ( "get" , resource ) | Retrieve the metadata for a particular dataset . |
239,419 | def download_attachments ( self , dataset_identifier , content_type = "json" , download_dir = "~/sodapy_downloads" ) : metadata = self . get_metadata ( dataset_identifier , content_type = content_type ) files = [ ] attachments = metadata [ 'metadata' ] . get ( "attachments" ) if not attachments : logging . info ( "No a... | Download all of the attachments associated with a dataset . Return the paths of downloaded files . |
239,420 | def replace_non_data_file ( self , dataset_identifier , params , file_data ) : resource = _format_old_api_request ( dataid = dataset_identifier , content_type = "txt" ) if not params . get ( 'method' , None ) : params [ 'method' ] = 'replaceBlob' params [ 'id' ] = dataset_identifier return self . _perform_request ( "po... | Same as create_non_data_file but replaces a file that already exists in a file - based dataset . |
239,421 | def _perform_update ( self , method , resource , payload ) : try : file_type = file except NameError : file_type = IOBase if isinstance ( payload , ( dict , list ) ) : response = self . _perform_request ( method , resource , data = json . dumps ( payload ) ) elif isinstance ( payload , file_type ) : headers = { "conten... | Execute the update task . |
239,422 | def _perform_request ( self , request_type , resource , ** kwargs ) : request_type_methods = set ( [ "get" , "post" , "put" , "delete" ] ) if request_type not in request_type_methods : raise Exception ( "Unknown request type. Supported request types are" ": {0}" . format ( ", " . join ( request_type_methods ) ) ) uri =... | Utility method that performs all requests . |
239,423 | def exec_request ( self , URL ) : interval = time . time ( ) - self . __ts_last_req if ( interval < self . __min_req_interval ) : time . sleep ( self . __min_req_interval - interval ) headers = { "X-ELS-APIKey" : self . api_key , "User-Agent" : self . __user_agent , "Accept" : 'application/json' } if self . inst_token ... | Sends the actual request ; returns response . |
239,424 | def write ( self ) : if ( self . data ) : dataPath = self . client . local_dir / ( urllib . parse . quote_plus ( self . uri ) + '.json' ) with dataPath . open ( mode = 'w' ) as dump_file : json . dump ( self . data , dump_file ) dump_file . close ( ) logger . info ( 'Wrote ' + self . uri + ' to file' ) return True else... | If data exists for the entity writes it to disk as a . JSON file with the url - encoded URI as the filename and returns True . Else returns False . |
239,425 | def write_docs ( self ) : if self . doc_list : dataPath = self . client . local_dir dump_file = open ( 'data/' + urllib . parse . quote_plus ( self . uri + '?view=documents' ) + '.json' , mode = 'w' ) dump_file . write ( '[' + json . dumps ( self . doc_list [ 0 ] ) ) for i in range ( 1 , len ( self . doc_list ) ) : dum... | If a doclist exists for the entity writes it to disk as a . JSON file with the url - encoded URI as the filename and returns True . Else returns False . |
239,426 | def read ( self , els_client = None ) : if ElsProfile . read ( self , self . __payload_type , els_client ) : return True else : return False | Reads the JSON representation of the author from ELSAPI . Returns True if successful ; else False . |
239,427 | def read ( self , els_client = None ) : if super ( ) . read ( self . __payload_type , els_client ) : return True else : return False | Reads the JSON representation of the document from ELSAPI . Returns True if successful ; else False . |
239,428 | def _extract_obo_synonyms ( rawterm ) : synonyms = set ( ) keys = set ( owl_synonyms ) . intersection ( rawterm . keys ( ) ) for k in keys : for s in rawterm [ k ] : synonyms . add ( Synonym ( s , owl_synonyms [ k ] ) ) return synonyms | Extract the synonyms defined in the rawterm . |
239,429 | def _extract_obo_relation ( cls , rawterm ) : relations = { } if 'subClassOf' in rawterm : relations [ Relationship ( 'is_a' ) ] = l = [ ] l . extend ( map ( cls . _get_id_from_url , rawterm . pop ( 'subClassOf' ) ) ) return relations | Extract the relationships defined in the rawterm . |
239,430 | def _relabel_to_obo ( d ) : return { owl_to_obo . get ( old_k , old_k ) : old_v for old_k , old_v in six . iteritems ( d ) } | Change the keys of d to use Obo labels . |
239,431 | def complement ( self ) : if self . complementary : try : return self . _instances [ self . complementary ] except KeyError : raise ValueError ( '{} has a complementary but it was not defined !' ) else : return None | Return the complementary relationship of self . |
239,432 | def topdown ( cls ) : return tuple ( unique_everseen ( r for r in cls . _instances . values ( ) if r . direction == 'topdown' ) ) | Get all topdown Relationship instances . |
239,433 | def bottomup ( cls ) : return tuple ( unique_everseen ( r for r in cls . _instances . values ( ) if r . direction == 'bottomup' ) ) | Get all bottomup Relationship instances . |
239,434 | def unique_everseen ( iterable ) : seen = set ( ) seen_add = seen . add for element in six . moves . filterfalse ( seen . __contains__ , iterable ) : seen_add ( element ) yield element | List unique elements preserving order . Remember all elements ever seen . |
239,435 | def output_str ( f ) : if six . PY2 : def new_f ( * args , ** kwargs ) : return f ( * args , ** kwargs ) . encode ( "utf-8" ) else : new_f = f return new_f | Create a function that always return instances of str . |
239,436 | def nowarnings ( func ) : @ functools . wraps ( func ) def new_func ( * args , ** kwargs ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( 'ignore' ) return func ( * args , ** kwargs ) return new_func | Create a function wrapped in a context that ignores warnings . |
239,437 | def parse ( self , stream , parser = None ) : force , parsers = self . _get_parsers ( parser ) try : stream . seek ( 0 ) lookup = stream . read ( 1024 ) stream . seek ( 0 ) except ( io . UnsupportedOperation , AttributeError ) : lookup = None for p in parsers : if p . hook ( path = self . path , force = force , lookup ... | Parse the given file using available BaseParser instances . |
239,438 | def _get_parsers ( self , name ) : parserlist = BaseParser . __subclasses__ ( ) forced = name is None if isinstance ( name , ( six . text_type , six . binary_type ) ) : parserlist = [ p for p in parserlist if p . __name__ == name ] if not parserlist : raise ValueError ( "could not find parser: {}" . format ( name ) ) e... | Return the appropriate parser asked by the user . |
239,439 | def adopt ( self ) : valid_relationships = set ( Relationship . _instances . keys ( ) ) relationships = [ ( parent , relation . complement ( ) , term . id ) for term in six . itervalues ( self . terms ) for relation in term . relations for parent in term . relations [ relation ] if relation . complementary and relation... | Make terms aware of their children . |
239,440 | def reference ( self ) : for termkey , termval in six . iteritems ( self . terms ) : termval . relations . update ( ( relkey , TermList ( ( self . terms . get ( x ) or Term ( x , '' , '' ) if not isinstance ( x , Term ) else x ) for x in relval ) ) for relkey , relval in six . iteritems ( termval . relations ) ) | Make relations point to ontology terms instead of term ids . |
239,441 | def resolve_imports ( self , imports , import_depth , parser = None ) : if imports and import_depth : for i in list ( self . imports ) : try : if os . path . exists ( i ) or i . startswith ( ( 'http' , 'ftp' ) ) : self . merge ( Ontology ( i , import_depth = import_depth - 1 , parser = parser ) ) else : self . merge ( ... | Import required ontologies . |
239,442 | def include ( self , * terms ) : ref_needed = False for term in terms : if isinstance ( term , TermList ) : ref_needed = ref_needed or self . _include_term_list ( term ) elif isinstance ( term , Term ) : ref_needed = ref_needed or self . _include_term ( term ) else : raise TypeError ( 'include only accepts <Term> or <T... | Add new terms to the current ontology . |
239,443 | def merge ( self , other ) : if not isinstance ( other , Ontology ) : raise TypeError ( "'merge' requires an Ontology as argument," " not {}" . format ( type ( other ) ) ) self . terms . update ( other . terms ) self . _empty_cache ( ) self . adopt ( ) self . reference ( ) | Merge another ontology into the current one . |
239,444 | def _include_term_list ( self , termlist ) : ref_needed = False for term in termlist : ref_needed = ref_needed or self . _include_term ( term ) return ref_needed | Add terms from a TermList to the ontology . |
239,445 | def _include_term ( self , term ) : ref_needed = False if term . relations : for k , v in six . iteritems ( term . relations ) : for i , t in enumerate ( v ) : try : if t . id not in self : self . _include_term ( t ) v [ i ] = t . id except AttributeError : pass ref_needed = True self . terms [ term . id ] = term retur... | Add a single term to the current ontology . |
239,446 | def _empty_cache ( self , termlist = None ) : if termlist is None : for term in six . itervalues ( self . terms ) : term . _empty_cache ( ) else : for term in termlist : try : self . terms [ term . id ] . _empty_cache ( ) except AttributeError : self . terms [ term ] . _empty_cache ( ) | Empty the cache associated with each Term instance . |
239,447 | def _obo_meta ( self ) : metatags = ( "format-version" , "data-version" , "date" , "saved-by" , "auto-generated-by" , "import" , "subsetdef" , "synonymtypedef" , "default-namespace" , "namespace-id-rule" , "idspace" , "treat-xrefs-as-equivalent" , "treat-xrefs-as-genus-differentia" , "treat-xrefs-as-is_a" , "remark" , ... | Generate the obo metadata header and updates metadata . |
239,448 | def _empty_cache ( self ) : self . _children , self . _parents = None , None self . _rchildren , self . _rparents = { } , { } | Empty the cache of the Term s memoized functions . |
239,449 | def _check_section ( line , section ) : if "[Term]" in line : section = OboSection . term elif "[Typedef]" in line : section = OboSection . typedef return section | Update the section being parsed . |
239,450 | def _parse_metadata ( cls , line , meta , parse_remarks = True ) : key , value = line . split ( ':' , 1 ) key , value = key . strip ( ) , value . strip ( ) if parse_remarks and "remark" in key : if 0 < value . find ( ': ' ) < 20 : try : cls . _parse_metadata ( value , meta , parse_remarks ) except ValueError : pass els... | Parse a metadata line . |
239,451 | def _parse_typedef ( line , _rawtypedef ) : if "[Typedef]" in line : _rawtypedef . append ( collections . defaultdict ( list ) ) else : key , value = line . split ( ':' , 1 ) _rawtypedef [ - 1 ] [ key . strip ( ) ] . append ( value . strip ( ) ) | Parse a typedef line . |
239,452 | def _parse_term ( _rawterms ) : line = yield _rawterms . append ( collections . defaultdict ( list ) ) while True : line = yield if "[Term]" in line : _rawterms . append ( collections . defaultdict ( list ) ) else : key , value = line . split ( ':' , 1 ) _rawterms [ - 1 ] [ key . strip ( ) ] . append ( value . strip ( ... | Parse a term line . |
239,453 | def _classify ( _rawtypedef , _rawterms ) : terms = collections . OrderedDict ( ) _cached_synonyms = { } typedefs = [ Relationship . _from_obo_dict ( { k : v for k , lv in six . iteritems ( _typedef ) for v in lv } ) for _typedef in _rawtypedef ] for _term in _rawterms : synonyms = set ( ) _id = _term [ 'id' ] [ 0 ] _n... | Create proper objects out of extracted dictionnaries . |
239,454 | def calculate_first_digit ( number ) : sum = 0 if len ( number ) == 9 : weights = CPF_WEIGHTS [ 0 ] else : weights = CNPJ_WEIGHTS [ 0 ] for i in range ( len ( number ) ) : sum = sum + int ( number [ i ] ) * weights [ i ] rest_division = sum % DIVISOR if rest_division < 2 : return '0' return str ( 11 - rest_division ) | This function calculates the first check digit of a cpf or cnpj . |
239,455 | def validate ( number ) : clean_number = clear_punctuation ( number ) if len ( clean_number ) == 11 : return cpf . validate ( clean_number ) elif len ( clean_number ) == 14 : return cnpj . validate ( clean_number ) return False | This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers . Feel free to use this or the other modules directly . |
239,456 | def validate ( cpf_number ) : _cpf = compat . clear_punctuation ( cpf_number ) if ( len ( _cpf ) != 11 or len ( set ( _cpf ) ) == 1 ) : return False first_part = _cpf [ : 9 ] second_part = _cpf [ : 10 ] first_digit = _cpf [ 9 ] second_digit = _cpf [ 10 ] if ( first_digit == calc . calculate_first_digit ( first_part ) a... | This function validates a CPF number . |
239,457 | def validate ( cnpj_number ) : _cnpj = compat . clear_punctuation ( cnpj_number ) if ( len ( _cnpj ) != 14 or len ( set ( _cnpj ) ) == 1 ) : return False first_part = _cnpj [ : 12 ] second_part = _cnpj [ : 13 ] first_digit = _cnpj [ 12 ] second_digit = _cnpj [ 13 ] if ( first_digit == calc . calculate_first_digit ( fir... | This function validates a CNPJ number . |
239,458 | def xml_open ( filename , expected_root = None ) : if zipfile . is_zipfile ( filename ) : tree = get_xml_from_archive ( filename ) else : tree = ET . parse ( filename ) tree_root = tree . getroot ( ) file_version = Version ( tree_root . attrib . get ( 'version' , '0.0' ) ) if file_version < MIN_SUPPORTED_VERSION : rais... | Opens the provided filename . Handles detecting if the file is an archive detecting the document version and validating the root tag . |
239,459 | def build_archive_file ( archive_contents , zip_file ) : for root_dir , _ , files in os . walk ( archive_contents ) : relative_dir = os . path . relpath ( root_dir , archive_contents ) for f in files : temp_file_full_path = os . path . join ( archive_contents , relative_dir , f ) zipname = os . path . join ( relative_d... | Build a Tableau - compatible archive file . |
239,460 | def from_attributes ( cls , server , dbname , username , dbclass , port = None , query_band = None , initial_sql = None , authentication = '' ) : root = ET . Element ( 'connection' , authentication = authentication ) xml = cls ( root ) xml . server = server xml . dbname = dbname xml . username = username xml . dbclass ... | Creates a new connection that can be added into a Data Source . defaults to which will be treated as prompt by Tableau . |
239,461 | def dbname ( self , value ) : self . _dbname = value self . _connectionXML . set ( 'dbname' , value ) | Set the connection s database name property . |
239,462 | def server ( self , value ) : self . _server = value self . _connectionXML . set ( 'server' , value ) | Set the connection s server property . |
239,463 | def username ( self , value ) : self . _username = value self . _connectionXML . set ( 'username' , value ) | Set the connection s username property . |
239,464 | def dbclass ( self , value ) : if not is_valid_dbclass ( value ) : raise AttributeError ( "'{}' is not a valid database type" . format ( value ) ) self . _class = value self . _connectionXML . set ( 'class' , value ) | Set the connection s dbclass property . |
239,465 | def port ( self , value ) : self . _port = value if value is None : try : del self . _connectionXML . attrib [ 'port' ] except KeyError : pass else : self . _connectionXML . set ( 'port' , value ) | Set the connection s port property . |
239,466 | def query_band ( self , value ) : self . _query_band = value if value is None : try : del self . _connectionXML . attrib [ 'query-band-spec' ] except KeyError : pass else : self . _connectionXML . set ( 'query-band-spec' , value ) | Set the connection s query_band property . |
239,467 | def initial_sql ( self , value ) : self . _initial_sql = value if value is None : try : del self . _connectionXML . attrib [ 'one-time-sql' ] except KeyError : pass else : self . _connectionXML . set ( 'one-time-sql' , value ) | Set the connection s initial_sql property . |
239,468 | def base36encode ( number ) : ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" base36 = '' sign = '' if number < 0 : sign = '-' number = - number if 0 <= number < len ( ALPHABET ) : return sign + ALPHABET [ number ] while number != 0 : number , i = divmod ( number , len ( ALPHABET ) ) base36 = ALPHABET [ i ] + base36 ... | Converts an integer into a base36 string . |
239,469 | def get_connections ( self ) : if float ( self . _dsversion ) < 10 : connections = self . _extract_legacy_connection ( ) else : connections = self . _extract_federated_connections ( ) return connections | Find and return all connections based on file format version . |
239,470 | def from_connections ( cls , caption , connections ) : root = ET . Element ( 'datasource' , caption = caption , version = '10.0' , inline = 'true' ) outer_connection = ET . SubElement ( root , 'connection' ) outer_connection . set ( 'class' , 'federated' ) named_conns = ET . SubElement ( outer_connection , 'named-conne... | Create a new Data Source give a list of Connections . |
239,471 | def name ( self ) : alias = getattr ( self , 'alias' , None ) if alias : return alias caption = getattr ( self , 'caption' , None ) if caption : return caption return self . id | Provides a nice name for the field which is derived from the alias caption or the id . |
239,472 | def _check_configuration ( self , * attrs ) : for attr in attrs : if getattr ( self , attr , None ) is None : raise ConfigurationError ( "{} not configured" . format ( attr ) ) | Check that each named attr has been configured |
239,473 | def _make_request ( self , url , ** kwargs ) : response = requests . post ( url , ** kwargs ) try : return response . json ( ) except ValueError : pass return parse_qs ( response . content ) | Make a request to an OAuth2 endpoint |
239,474 | def get_token ( self , code , headers = None , ** kwargs ) : self . _check_configuration ( "site" , "token_url" , "redirect_uri" , "client_id" , "client_secret" ) url = "%s%s" % ( self . site , quote ( self . token_url ) ) data = { 'redirect_uri' : self . redirect_uri , 'client_id' : self . client_id , 'client_secret' ... | Requests an access token |
239,475 | def refresh_token ( self , headers = None , ** kwargs ) : self . _check_configuration ( "site" , "token_url" , "client_id" , "client_secret" ) url = "%s%s" % ( self . site , quote ( self . token_url ) ) data = { 'client_id' : self . client_id , 'client_secret' : self . client_secret , } data . update ( kwargs ) return ... | Request a refreshed token |
239,476 | def revoke_token ( self , token , headers = None , ** kwargs ) : self . _check_configuration ( "site" , "revoke_uri" ) url = "%s%s" % ( self . site , quote ( self . revoke_url ) ) data = { 'token' : token } data . update ( kwargs ) return self . _make_request ( url , data = data , headers = headers ) | Revoke an access token |
239,477 | def save_network_to_file ( self , filename = "network0.pkl" ) : import cPickle , os , re if filename == "network0.pkl" : while os . path . exists ( os . path . join ( os . getcwd ( ) , filename ) ) : filename = re . sub ( '\d(?!\d)' , lambda x : str ( int ( x . group ( 0 ) ) + 1 ) , filename ) with open ( filename , 'w... | This save method pickles the parameters of the current network into a binary file for persistant storage . |
239,478 | def load_network_from_file ( filename ) : import cPickle network = NeuralNet ( { "n_inputs" : 1 , "layers" : [ [ 0 , None ] ] } ) with open ( filename , 'rb' ) as file : store_dict = cPickle . load ( file ) network . n_inputs = store_dict [ "n_inputs" ] network . n_weights = store_dict [ "n_weights" ] network . layers ... | Load the complete configuration of a previously stored network . |
239,479 | def replace_nan ( trainingset , replace_with = None ) : training_data = np . array ( [ instance . features for instance in trainingset ] ) . astype ( np . float64 ) def encoder ( dataset ) : for instance in dataset : instance . features = instance . features . astype ( np . float64 ) if np . sum ( np . isnan ( instance... | Replace instanced of not a number with either the mean of the signal feature or a specific value assigned by replace_nan_with |
239,480 | def elliot_function ( signal , derivative = False ) : s = 1 abs_signal = ( 1 + np . abs ( signal * s ) ) if derivative : return 0.5 * s / abs_signal ** 2 else : return 0.5 * ( signal * s ) / abs_signal + 0.5 | A fast approximation of sigmoid |
239,481 | def symmetric_elliot_function ( signal , derivative = False ) : s = 1.0 abs_signal = ( 1 + np . abs ( signal * s ) ) if derivative : return s / abs_signal ** 2 else : return ( signal * s ) / abs_signal | A fast approximation of tanh |
239,482 | def LReLU_function ( signal , derivative = False , leakage = 0.01 ) : if derivative : return np . clip ( signal > 0 , leakage , 1.0 ) else : output = np . copy ( signal ) output [ output < 0 ] *= leakage return output | Leaky Rectified Linear Unit |
239,483 | def is_zipfile ( filename ) : result = False try : if hasattr ( filename , "read" ) : result = _check_zipfile ( fp = filename ) else : with open ( filename , "rb" ) as fp : result = _check_zipfile ( fp ) except OSError : pass return result | Quickly see if a file is a ZIP file by checking the magic number . |
239,484 | def readline ( self , limit = - 1 ) : if not self . _universal and limit < 0 : i = self . _readbuffer . find ( b'\n' , self . _offset ) + 1 if i > 0 : line = self . _readbuffer [ self . _offset : i ] self . _offset = i return line if not self . _universal : return io . BufferedIOBase . readline ( self , limit ) line = ... | Read and return a line from the stream . |
239,485 | def setpassword ( self , pwd ) : if pwd and not isinstance ( pwd , bytes ) : raise TypeError ( "pwd: expected bytes, got %s" % type ( pwd ) ) if pwd : self . pwd = pwd else : self . pwd = None | Set default password for encrypted files . |
239,486 | def _sanitize_windows_name ( cls , arcname , pathsep ) : table = cls . _windows_illegal_name_trans_table if not table : illegal = ':<>|"?*' table = str . maketrans ( illegal , '_' * len ( illegal ) ) cls . _windows_illegal_name_trans_table = table arcname = arcname . translate ( table ) arcname = ( x . rstrip ( '.' ) f... | Replace bad characters and remove trailing dots from parts . |
239,487 | def close ( self ) : if self . fp is None : return try : if self . mode in ( 'w' , 'x' , 'a' ) and self . _didModify : with self . _lock : if self . _seekable : self . fp . seek ( self . start_dir ) self . _write_end_record ( ) finally : fp = self . fp self . fp = None self . _fpclose ( fp ) | Close the file and for mode w x and a write the ending records . |
239,488 | def display_string_dump ( self , section_spec ) : section = _section_from_spec ( self . elf_file , section_spec ) if section is None : print ( "Section '%s' does not exist in the file!" % section_spec ) return None data = section . data ( ) dataptr = 0 strs = [ ] while dataptr < len ( data ) : while dataptr < len ( dat... | Display a strings dump of a section . section_spec is either a section number or a name . |
239,489 | def _EnvOpen ( var , mode ) : value = os . getenv ( var ) if value is None : raise ValueError ( "%s is not set" % var ) fd = int ( value ) if _WINDOWS : fd = msvcrt . open_osfhandle ( fd , 0 ) return os . fdopen ( fd , mode ) | Open a file descriptor identified by an environment variable . |
239,490 | def Send ( self , message ) : if not isinstance ( message , common_pb2 . Message ) : raise ValueError ( "Send requires a fleetspeak.Message" ) if message . destination . service_name == "system" : raise ValueError ( "Only predefined messages can have destination.service_name == \"system\"" ) return self . _SendImpl ( m... | Send a message through Fleetspeak . |
239,491 | def Recv ( self ) : size = struct . unpack ( _STRUCT_FMT , self . _ReadN ( _STRUCT_LEN ) ) [ 0 ] if size > MAX_SIZE : raise ProtocolError ( "Expected size to be at most %d, got %d" % ( MAX_SIZE , size ) ) with self . _read_lock : buf = self . _ReadN ( size ) self . _ReadMagic ( ) res = common_pb2 . Message ( ) res . Pa... | Accept a message from Fleetspeak . |
239,492 | def Heartbeat ( self ) : heartbeat_msg = common_pb2 . Message ( message_type = "Heartbeat" , destination = common_pb2 . Address ( service_name = "system" ) ) self . _SendImpl ( heartbeat_msg ) | Sends a heartbeat to the Fleetspeak client . |
239,493 | def _ReadN ( self , n ) : ret = "" while True : chunk = self . _read_file . read ( n - len ( ret ) ) ret += chunk if len ( ret ) == n or not chunk : return ret | Reads n characters from the input stream or until EOF . |
239,494 | def _CompileProtos ( ) : proto_files = [ ] for dir_path , _ , filenames in os . walk ( THIS_DIRECTORY ) : for filename in filenames : if filename . endswith ( ".proto" ) : proto_files . append ( os . path . join ( dir_path , filename ) ) if not proto_files : return protoc_command = [ "python" , "-m" , "grpc_tools.proto... | Compiles all Fleetspeak protos . |
239,495 | def _RetryLoop ( self , func , timeout = None ) : timeout = timeout or self . DEFAULT_TIMEOUT deadline = time . time ( ) + timeout sleep = 1 while True : try : return func ( timeout ) except grpc . RpcError : if time . time ( ) + sleep > deadline : raise time . sleep ( sleep ) sleep *= 2 timeout = deadline - time . tim... | Retries an operation until success or deadline . |
239,496 | def InsertMessage ( self , message , timeout = None ) : if not isinstance ( message , common_pb2 . Message ) : raise InvalidArgument ( "Attempt to send unexpected message type: %s" % message . __class__ . __name__ ) if not message . HasField ( "source" ) : message . source . service_name = self . _service_name if not m... | Inserts a message into the Fleetspeak server . |
239,497 | def ListClients ( self , request , timeout = None ) : return self . _RetryLoop ( lambda t : self . _stub . ListClients ( request , timeout = t ) ) | Provides basic information about Fleetspeak clients . |
239,498 | def Send ( self , message ) : if not self . outgoing : raise NotConfigured ( "Send address not provided." ) self . outgoing . InsertMessage ( message ) | Send one message . |
239,499 | def start_naive_bayes ( automated_run , session , path ) : module = functions . import_string_code_as_module ( automated_run . source ) random_state = 8 if not hasattr ( module , 'random_state' ) else module . random_state assert module . metric_to_optimize in automated_run . base_learner_origin . metric_generators bas... | Starts naive bayes automated run |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.