idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
33,500 | def standard_stream_redirector ( stream ) : import sys genuine_stdout , genuine_stderr = sys . stdout , sys . stderr sys . stdout , sys . stderr = stream , stream try : yield finally : sys . stdout , sys . stderr = genuine_stdout , genuine_stderr | Temporarily redirect stdout and stderr to another stream . |
33,501 | def search ( self , q = "yellow flower" , lang = "en" , video_type = "all" , category = "" , min_width = 0 , min_height = 0 , editors_choice = "false" , safesearch = "false" , order = "popular" , page = 1 , per_page = 20 , callback = "" , pretty = "false" , ) : payload = { "key" : self . api_key , "q" : q , "lang" : la... | returns videos API data in dict |
33,502 | def quoted ( arg ) : if isinstance ( arg , str ) : arg = arg . replace ( '\\' , '\\\\' ) arg = arg . replace ( '"' , '\\"' ) q = '"' else : arg = arg . replace ( b'\\' , b'\\\\' ) arg = arg . replace ( b'"' , b'\\"' ) q = b'"' return q + arg + q | Given a string return a quoted string as per RFC 3501 section 9 . |
33,503 | def int2ap ( num ) : val = '' ap = 'ABCDEFGHIJKLMNOP' num = int ( abs ( num ) ) while num : num , mod = divmod ( num , 16 ) val += ap [ mod : mod + 1 ] return val | Convert integer to A - P string representation . |
33,504 | def time2internaldate ( date_time ) : if isinstance ( date_time , ( int , float ) ) : dt = datetime . fromtimestamp ( date_time , timezone . utc ) . astimezone ( ) elif isinstance ( date_time , tuple ) : try : gmtoff = date_time . tm_gmtoff except AttributeError : if time . daylight : dst = date_time [ 8 ] if dst == - ... | Convert date_time to IMAP4 INTERNALDATE representation . |
33,505 | def _send_tasks_and_stop_queuing ( ** kwargs ) : log . info ( 'Stopping queueing tasks and sending already queued ones.' ) _stop_queuing_tasks ( ) task_queue = _get_task_queue ( ) while task_queue : task , args , kwargs , extrakw = task_queue . pop ( 0 ) task . original_apply_async ( args = args , kwargs = kwargs , ** ... | Sends all delayed Celery tasks and stop queuing new ones for now . |
33,506 | def _append_task ( t ) : task_queue = _get_task_queue ( ) if t not in task_queue : log . debug ( 'Appended new task to the queue: %s.' , t ) task_queue . append ( t ) else : log . debug ( 'Did not append duplicate task to the queue: %s.' , t ) return None | Append a task to the queue . |
33,507 | def create_from_tuple ( cls , tube , the_tuple ) : if the_tuple is None : return if not the_tuple . rowcount : raise Queue . ZeroTupleException ( "Error creating task" ) row = the_tuple [ 0 ] return cls ( tube , task_id = row [ 0 ] , state = row [ 1 ] , data = row [ 2 ] ) | Create task from tuple . |
33,508 | def update_from_tuple ( self , the_tuple ) : if not the_tuple . rowcount : raise Queue . ZeroTupleException ( "Error updating task" ) row = the_tuple [ 0 ] if self . task_id != row [ 0 ] : raise Queue . BadTupleException ( "Wrong task: id's are not match" ) self . state = row [ 1 ] self . data = row [ 2 ] | Update task from tuple . |
33,509 | async def peek ( self ) : the_tuple = await self . queue . peek ( self . tube , self . task_id ) self . update_from_tuple ( the_tuple ) return True | Look at a task without changing its state . |
33,510 | def cmd ( self , cmd_name ) : return "{0}.tube.{1}:{2}" . format ( self . queue . lua_queue_name , self . name , cmd_name ) | Returns tarantool queue command name for current tube . |
33,511 | async def ack ( self , tube , task_id ) : cmd = tube . cmd ( "ack" ) args = ( task_id , ) res = await self . tnt . call ( cmd , args ) return res | Report task successful execution . |
33,512 | def tube ( self , name ) : tube = self . tubes . get ( name ) if tube is None : tube = Tube ( self , name ) self . tubes [ name ] = tube return tube | Create tube object if not created before . |
33,513 | def post ( self , endpoint = '' , url = '' , data = None , use_api_key = False , omit_api_version = False ) : return self . _request ( 'post' , endpoint , url , data = data , use_api_key = use_api_key , omit_api_version = omit_api_version ) | Perform a post to an API endpoint . |
33,514 | def _request ( self , request_method , endpoint = '' , url = '' , data = None , params = None , use_api_key = False , omit_api_version = False ) : if not data : data = { } if not params : params = { } if endpoint and omit_api_version and not url : url = '%s/%s' % ( self . base_url , endpoint ) if endpoint and not url :... | Perform a http request via the specified method to an API endpoint . |
33,515 | def change_participation_status ( self , calendar_id , event_uid , status ) : data = { 'status' : status } self . request_handler . post ( 'calendars/%s/events/%s/participation_status' % ( calendar_id , event_uid ) , data = data ) | Changes the participation status for a calendar event |
33,516 | def create_notification_channel ( self , callback_url , calendar_ids = ( ) ) : data = { 'callback_url' : callback_url } if calendar_ids : data [ 'filters' ] = { 'calendar_ids' : calendar_ids } return self . request_handler . post ( 'channels' , data = data ) . json ( ) [ 'channel' ] | Create a new channel for receiving push notifications . |
33,517 | def delete_all_events ( self , calendar_ids = ( ) ) : params = { 'delete_all' : True } if calendar_ids : params = { 'calendar_ids[]' : calendar_ids } self . request_handler . delete ( endpoint = 'events' , params = params ) | Deletes all events managed through Cronofy from the all of the user s calendars . |
33,518 | def delete_event ( self , calendar_id , event_id ) : self . request_handler . delete ( endpoint = 'calendars/%s/events' % calendar_id , data = { 'event_id' : event_id } ) | Delete an event from the specified calendar . |
33,519 | def delete_external_event ( self , calendar_id , event_uid ) : self . request_handler . delete ( endpoint = 'calendars/%s/events' % calendar_id , data = { 'event_uid' : event_uid } ) | Delete an external event from the specified calendar . |
33,520 | def elevated_permissions ( self , permissions , redirect_uri = None ) : body = { 'permissions' : permissions } if redirect_uri : body [ 'redirect_uri' ] = redirect_uri return self . request_handler . post ( 'permissions' , data = body ) . json ( ) [ 'permissions_request' ] | Requests elevated permissions for a set of calendars . |
33,521 | def get_smart_invite ( self , smart_invite_id , recipient_email ) : params = { 'smart_invite_id' : smart_invite_id , 'recipient_email' : recipient_email } return self . request_handler . get ( 'smart_invites' , params = params , use_api_key = True ) . json ( ) | Gets the details for a smart invite . |
33,522 | def application_calendar ( self , application_calendar_id ) : response = self . request_handler . post ( endpoint = 'application_calendar' , data = { 'client_id' : self . auth . client_id , 'client_secret' : self . auth . client_secret , 'application_calendar_id' : application_calendar_id , } ) data = response . json (... | Creates and Retrieves authorization for an application calendar |
33,523 | def refresh_authorization ( self ) : response = self . request_handler . post ( endpoint = 'oauth/token' , omit_api_version = True , data = { 'grant_type' : 'refresh_token' , 'client_id' : self . auth . client_id , 'client_secret' : self . auth . client_secret , 'refresh_token' : self . auth . refresh_token , } ) data ... | Refreshes the authorization tokens . |
33,524 | def revoke_authorization ( self ) : self . request_handler . post ( endpoint = 'oauth/token/revoke' , omit_api_version = True , data = { 'client_id' : self . auth . client_id , 'client_secret' : self . auth . client_secret , 'token' : self . auth . access_token , } ) self . auth . update ( token_expiration = None , acc... | Revokes Oauth authorization . |
33,525 | def upsert_event ( self , calendar_id , event ) : event [ 'start' ] = format_event_time ( event [ 'start' ] ) event [ 'end' ] = format_event_time ( event [ 'end' ] ) self . request_handler . post ( endpoint = 'calendars/%s/events' % calendar_id , data = event ) | Inserts or updates an event for the specified calendar . |
33,526 | def authorize_with_service_account ( self , email , scope , callback_url , state = None ) : params = { 'email' : email , 'scope' : scope , 'callback_url' : callback_url } if state is not None : params [ 'state' ] = state self . request_handler . post ( endpoint = "service_account_authorizations" , data = params ) None | Attempts to authorize the email with impersonation from a service account |
33,527 | def real_time_scheduling ( self , availability , oauth , event , target_calendars = ( ) ) : args = { 'oauth' : oauth , 'event' : event , 'target_calendars' : target_calendars } if availability : options = { } options [ 'participants' ] = self . map_availability_participants ( availability . get ( 'participants' , None ... | Generates an real time scheduling link to start the OAuth process with an event to be automatically upserted |
33,528 | def real_time_sequencing ( self , availability , oauth , event , target_calendars = ( ) ) : args = { 'oauth' : oauth , 'event' : event , 'target_calendars' : target_calendars } if availability : options = { } options [ 'sequence' ] = self . map_availability_sequence ( availability . get ( 'sequence' , None ) ) if avail... | Generates an real time sequencing link to start the OAuth process with an event to be automatically upserted |
33,529 | def user_auth_link ( self , redirect_uri , scope = '' , state = '' , avoid_linking = False ) : if not scope : scope = ' ' . join ( settings . DEFAULT_OAUTH_SCOPE ) self . auth . update ( redirect_uri = redirect_uri ) url = '%s/oauth/authorize' % self . app_base_url params = { 'response_type' : 'code' , 'client_id' : se... | Generates a URL to send the user for OAuth 2 . 0 |
33,530 | def validate ( self , method , * args , ** kwargs ) : validate ( method , self . auth , * args , ** kwargs ) | Validate authentication and values passed to the specified method . Raises a PyCronofyValidationError on error . |
33,531 | def all ( self ) : results = self . data [ self . data_type ] while self . current < self . total : self . fetch_next_page ( ) results . extend ( self . data [ self . data_type ] ) return results | Return all results as a list by automatically fetching all pages . |
33,532 | def fetch_next_page ( self ) : result = self . request_handler . get ( url = self . next_page_url ) . json ( ) self . __init__ ( self . request_handler , result , self . data_type , self . automatic_pagination ) | Retrieves the next page of data and refreshes Pages instance . |
33,533 | def check_datetime ( method , dictionary , fields , label = None ) : improperly_formatted = [ ] values = [ ] for field in fields : if field in dictionary and dictionary [ field ] is not None : if type ( dictionary [ field ] ) not in ( datetime . datetime , datetime . date ) and not ISO_8601_REGEX . match ( dictionary [... | Checks if the specified fields are formatted correctly if they have a value . Throws an exception on incorrectly formatted fields . |
33,534 | def validate ( method , auth , * args , ** kwargs ) : if method not in METHOD_RULES : raise PyCronofyValidationError ( 'Method "%s" not found.' % method , method ) m = METHOD_RULES [ method ] arguments = { } number_of_args = len ( args ) for i , key in enumerate ( m [ 'args' ] ) : if i < number_of_args : arguments [ ke... | Validate a method based on the METHOD_RULES above . |
33,535 | def release ( part = 'patch' ) : bumpver = subprocess . check_output ( [ 'bumpversion' , part , '--dry-run' , '--verbose' ] , stderr = subprocess . STDOUT ) m = re . search ( r'New version will be \'(\d+\.\d+\.\d+)\'' , bumpver . decode ( 'utf-8' ) ) version = m . groups ( 0 ) [ 0 ] bv_args = [ 'bumpversion' , part ] b... | Automated software release workflow |
33,536 | def make_thumbnail_name ( image_name , extension ) : file_name , _ = os . path . splitext ( image_name ) return file_name + '.' + clean_extension ( extension ) | Return name of the downloaded thumbnail based on the extension . |
33,537 | def get_thumbnail_of_file ( image_name , width ) : hdr = { 'User-Agent' : 'Python urllib2' } url = make_thumb_url ( image_name , width ) req = urllib2 . Request ( url , headers = hdr ) try : logging . debug ( "Retrieving %s" , url ) opened = urllib2 . urlopen ( req ) extension = opened . headers . subtype return opened... | Return the file contents of the thumbnail of the given file . |
33,538 | def get_exception_based_on_api_message ( message , image_name = "" ) : msg_bigger_than_source = re . compile ( 'Image was not scaled, is the requested width bigger than the source?' ) msg_does_not_exist = re . compile ( 'The source file .* does not exist' ) msg_does_not_exist_bis = re . compile ( '<div class="error"><p... | Return the exception matching the given API error message . |
33,539 | def download_file ( image_name , output_path , width = DEFAULT_WIDTH ) : image_name = clean_up_filename ( image_name ) logging . info ( "Downloading %s with width %s" , image_name , width ) try : contents , output_file_name = get_thumbnail_of_file ( image_name , width ) except RequestedWidthBiggerThanSourceException : ... | Download a given Wikimedia Commons file . |
33,540 | def get_category_files_from_api ( category_name ) : import mwclient site = mwclient . Site ( 'commons.wikimedia.org' ) category = site . Categories [ category_name ] return ( x . page_title . encode ( 'utf-8' ) for x in category . members ( namespace = 6 ) ) | Yield the file names of a category by querying the MediaWiki API . |
33,541 | def download_from_category ( category_name , output_path , width ) : file_names = get_category_files_from_api ( category_name ) files_to_download = izip_longest ( file_names , [ ] , fillvalue = width ) download_files_if_not_in_manifest ( files_to_download , output_path ) | Download files of a given category . |
33,542 | def get_files_from_textfile ( textfile_handler ) : for line in textfile_handler : line = line . rstrip ( ) try : ( image_name , width ) = line . rsplit ( ',' , 1 ) width = int ( width ) except ValueError : image_name = line width = None yield ( image_name , width ) | Yield the file names and widths by parsing a text file handler . |
33,543 | def download_from_files ( files , output_path , width ) : files_to_download = get_files_from_arguments ( files , width ) download_files_if_not_in_manifest ( files_to_download , output_path ) | Download files from a given file list . |
33,544 | def read_local_manifest ( output_path ) : local_manifest_path = get_local_manifest_path ( output_path ) try : with open ( local_manifest_path , 'r' ) as f : manifest = dict ( get_files_from_textfile ( f ) ) logging . debug ( 'Retrieving %s elements from manifest' , len ( manifest ) ) return manifest except IOError : lo... | Return the contents of the local manifest as a dictionary . |
33,545 | def write_file_to_manifest ( file_name , width , manifest_fh ) : manifest_fh . write ( "%s,%s\n" % ( file_name , str ( width ) ) ) logging . debug ( "Wrote file %s to manifest" , file_name ) | Write the given file in manifest . |
33,546 | def download_files_if_not_in_manifest ( files_iterator , output_path ) : local_manifest = read_local_manifest ( output_path ) with open ( get_local_manifest_path ( output_path ) , 'a' ) as manifest_fh : for ( file_name , width ) in files_iterator : if is_file_in_manifest ( file_name , width , local_manifest ) : logging... | Download the given files to the given path unless in manifest . |
33,547 | def main ( ) : from argparse import ArgumentParser description = "Download a bunch of thumbnails from Wikimedia Commons" parser = ArgumentParser ( description = description ) source_group = parser . add_mutually_exclusive_group ( ) source_group . add_argument ( "-l" , "--list" , metavar = "LIST" , dest = "file_list" , ... | Main method entry point of the script . |
33,548 | def ordered_load ( self , stream , Loader = yaml . Loader , object_pairs_hook = OrderedDict ) : class OrderedLoader ( Loader ) : pass def construct_mapping ( loader , node ) : loader . flatten_mapping ( node ) return object_pairs_hook ( loader . construct_pairs ( node ) ) OrderedLoader . add_constructor ( yaml . resolv... | Allows you to use pyyaml to load as OrderedDict . |
33,549 | def send ( self , send_string , newline = None ) : self . current_send_string = send_string newline = newline if newline is not None else self . newline self . channel . send ( send_string + newline ) | Saves and sends the send string provided . |
33,550 | def tail ( self , line_prefix = None , callback = None , output_callback = None , stop_callback = lambda x : False , timeout = None ) : output_callback = output_callback if output_callback else self . output_callback timeout = timeout if timeout else 2 ** ( struct . Struct ( str ( 'i' ) ) . size * 8 - 1 ) - 1 self . ch... | This function takes control of an SSH channel and displays line by line of output as \ n is recieved . This function is specifically made for tail - like commands . |
33,551 | def take_control ( self ) : if has_termios : original_tty = termios . tcgetattr ( sys . stdin ) try : tty . setraw ( sys . stdin . fileno ( ) ) tty . setcbreak ( sys . stdin . fileno ( ) ) self . channel . settimeout ( 0 ) while True : select_read , select_write , select_exception = ( select . select ( [ self . channel... | This function is a better documented and touched up version of the posix_shell function found in the interactive . py demo script that ships with Paramiko . |
33,552 | def _get_access_from_refresh ( self ) -> Tuple [ str , float ] : headers = self . _get_authorization_headers ( ) data = { 'grant_type' : 'refresh_token' , 'refresh_token' : self . refresh_token } r = self . session . post ( self . TOKEN_URL , headers = headers , data = data ) response_data = r . json ( ) return ( respo... | Uses the stored refresh token to get a new access token . |
33,553 | def _get_authorization_headers ( self ) -> dict : auth = base64 . encodestring ( ( self . client_id + ':' + self . client_secret ) . encode ( 'latin-1' ) ) . decode ( 'latin-1' ) auth = auth . replace ( '\n' , '' ) . replace ( ' ' , '' ) auth = 'Basic {}' . format ( auth ) headers = { 'Authorization' : auth } return he... | Constructs and returns the Authorization header for the client app . |
33,554 | def _try_refresh_access_token ( self ) -> None : if self . refresh_token : if not self . access_token or self . _is_access_token_expired ( ) : self . access_token , self . access_expiration = self . _get_access_from_refresh ( ) self . access_expiration = time . time ( ) + self . access_expiration | Attempts to get a new access token using the refresh token if needed . |
33,555 | def authenticate ( self , code : str ) -> 'Preston' : headers = self . _get_authorization_headers ( ) data = { 'grant_type' : 'authorization_code' , 'code' : code } r = self . session . post ( self . TOKEN_URL , headers = headers , data = data ) if not r . status_code == 200 : raise Exception ( f'Could not authenticate... | Authenticates using the code from the EVE SSO . |
33,556 | def _get_spec ( self ) -> dict : if self . spec : return self . spec self . spec = requests . get ( self . SPEC_URL . format ( self . version ) ) . json ( ) return self . spec | Fetches the OpenAPI spec from the server . |
33,557 | def _get_path_for_op_id ( self , id : str ) -> Optional [ str ] : for path_key , path_value in self . _get_spec ( ) [ 'paths' ] . items ( ) : for method in self . METHODS : if method in path_value : if self . OPERATION_ID_KEY in path_value [ method ] : if path_value [ method ] [ self . OPERATION_ID_KEY ] == id : return... | Searches the spec for a path matching the operation id . |
33,558 | def _insert_vars ( self , path : str , data : dict ) -> str : data = data . copy ( ) while True : match = re . search ( self . VAR_REPLACE_REGEX , path ) if not match : return path replace_from = match . group ( 0 ) replace_with = str ( data . get ( match . group ( 1 ) ) ) path = path . replace ( replace_from , replace... | Inserts variables into the ESI URL path . |
33,559 | def whoami ( self ) -> dict : if not self . access_token : return { } self . _try_refresh_access_token ( ) return self . session . get ( self . WHOAMI_URL ) . json ( ) | Returns the basic information about the authenticated character . |
33,560 | def get_path ( self , path : str , data : dict ) -> Tuple [ dict , dict ] : path = self . _insert_vars ( path , data ) path = self . BASE_URL + path data = self . cache . check ( path ) if data : return data self . _try_refresh_access_token ( ) r = self . session . get ( path ) self . cache . set ( r ) return r . json ... | Queries the ESI by an endpoint URL . |
33,561 | def get_op ( self , id : str , ** kwargs : str ) -> dict : path = self . _get_path_for_op_id ( id ) return self . get_path ( path , kwargs ) | Queries the ESI by looking up an operation id . |
33,562 | def post_path ( self , path : str , path_data : Union [ dict , None ] , post_data : Any ) -> dict : path = self . _insert_vars ( path , path_data or { } ) path = self . BASE_URL + path self . _try_refresh_access_token ( ) return self . session . post ( path , json = post_data ) . json ( ) | Modifies the ESI by an endpoint URL . |
33,563 | def post_op ( self , id : str , path_data : Union [ dict , None ] , post_data : Any ) -> dict : path = self . _get_path_for_op_id ( id ) return self . post_path ( path , path_data , post_data ) | Modifies the ESI by looking up an operation id . |
33,564 | def _get_expiration ( self , headers : dict ) -> int : expiration_str = headers . get ( 'expires' ) if not expiration_str : return 0 expiration = datetime . strptime ( expiration_str , '%a, %d %b %Y %H:%M:%S %Z' ) delta = ( expiration - datetime . utcnow ( ) ) . total_seconds ( ) return math . ceil ( abs ( delta ) ) | Gets the expiration time of the data from the response headers . |
33,565 | def set ( self , response : 'requests.Response' ) -> None : self . data [ response . url ] = SavedEndpoint ( response . json ( ) , self . _get_expiration ( response . headers ) ) | Adds a response to the cache . |
33,566 | def _check_expiration ( self , url : str , data : 'SavedEndpoint' ) -> 'SavedEndpoint' : if data . expires_after < time . time ( ) : del self . data [ url ] data = None return data | Checks the expiration time for data for a url . |
33,567 | def check ( self , url : str ) -> Optional [ dict ] : data = self . data . get ( url ) if data : data = self . _check_expiration ( url , data ) return data . data if data else None | Check if data for a url has expired . |
33,568 | def eigvalsh ( a , eigvec = False ) : if eigvec == True : val , vec = eigh ( a , eigvec = True ) return val , gvar . mean ( vec ) else : return eigh ( a , eigvec = False ) | Eigenvalues of Hermitian matrix a . |
33,569 | def eigh ( a , eigvec = True , rcond = None ) : a = numpy . asarray ( a ) if a . dtype != object : val , vec = numpy . linalg . eigh ( a ) return ( val , vec ) if eigvec else val amean = gvar . mean ( a ) if amean . ndim != 2 or amean . shape [ 0 ] != amean . shape [ 1 ] : raise ValueError ( 'bad matrix shape: ' + str ... | Eigenvalues and eigenvectors of symmetric matrix a . |
33,570 | def svd ( a , compute_uv = True , rcond = None ) : a = numpy . asarray ( a ) if a . dtype != object : return numpy . linalg . svd ( a , compute_uv = compute_uv ) amean = gvar . mean ( a ) if amean . ndim != 2 : raise ValueError ( 'matrix must have dimension 2: actual shape = ' + str ( a . shape ) ) if rcond is None : r... | svd decomposition of matrix a containing |GVar| \ s . |
33,571 | def inv ( a ) : amean = gvar . mean ( a ) if amean . ndim != 2 or amean . shape [ 0 ] != amean . shape [ 1 ] : raise ValueError ( 'bad matrix shape: ' + str ( a . shape ) ) da = a - amean ainv = numpy . linalg . inv ( amean ) return ainv - ainv . dot ( da . dot ( ainv ) ) | Inverse of matrix a . |
33,572 | def ranseed ( seed = None ) : if seed is None : seed = numpy . random . randint ( 1 , int ( 2e9 ) , size = 3 ) try : seed = tuple ( seed ) except TypeError : pass numpy . random . seed ( seed ) ranseed . seed = seed return seed | Seed random number generators with tuple seed . |
33,573 | def erf ( x ) : try : return math . erf ( x ) except TypeError : pass if isinstance ( x , GVar ) : f = math . erf ( x . mean ) dfdx = 2. * math . exp ( - x . mean ** 2 ) / math . sqrt ( math . pi ) return gvar_function ( x , f , dfdx ) else : x = numpy . asarray ( x ) ans = numpy . empty ( x . shape , x . dtype ) for i... | Error function . |
33,574 | def make_fake_data ( g , fac = 1.0 ) : if hasattr ( g , 'keys' ) : if not isinstance ( g , BufferDict ) : g = BufferDict ( g ) return BufferDict ( g , buf = make_fake_data ( g . buf , fac ) ) else : g_shape = numpy . shape ( g ) g_flat = numpy . array ( g ) . flat zero = numpy . zeros ( len ( g_flat ) , float ) dg = ( ... | Make fake data based on g . |
33,575 | def p2x ( self , p ) : if hasattr ( p , 'keys' ) : dp = BufferDict ( p , keys = self . g . keys ( ) ) . _buf [ : self . meanflat . size ] - self . meanflat else : dp = numpy . asarray ( p ) . reshape ( - 1 ) - self . meanflat return self . vec_isig . dot ( dp ) | Map parameters p to vector in x - space . |
33,576 | def count ( self , data ) : if isinstance ( data , float ) or isinstance ( data , int ) : hist = numpy . zeros ( self . nbin + 2 , float ) if data > self . bins [ - 1 ] : hist [ - 1 ] = 1. elif data < self . bins [ 0 ] : hist [ 0 ] = 1. elif data == self . bins [ - 1 ] : if self . nbin > 1 : hist [ - 2 ] = 1. else : hi... | Compute histogram of data . |
33,577 | def gaussian_pdf ( x , g ) : return ( numpy . exp ( - ( x - g . mean ) ** 2 / 2. / g . var ) / numpy . sqrt ( g . var * 2 * numpy . pi ) ) | Gaussian probability density function at x for |GVar| g . |
33,578 | def verify_checksum ( * lines ) : for line in lines : checksum = line [ 68 : 69 ] if not checksum . isdigit ( ) : continue checksum = int ( checksum ) computed = compute_checksum ( line ) if checksum != computed : complaint = ( 'TLE line gives its checksum as {}' ' but in fact tallies to {}:\n{}' ) raise ValueError ( c... | Verify the checksum of one or more TLE lines . |
33,579 | def compute_checksum ( line ) : return sum ( ( int ( c ) if c . isdigit ( ) else c == '-' ) for c in line [ 0 : 68 ] ) % 10 | Compute the TLE checksum for the given line . |
33,580 | def propagate ( self , year , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 ) : j = jday ( year , month , day , hour , minute , second ) m = ( j - self . jdsatepoch ) * minutes_per_day r , v = sgp4 ( self , m ) return r , v | Return a position and velocity vector for a given date and time . |
33,581 | def name ( self ) : with self . _bt_interface . connect ( self . _mac ) as connection : name = connection . read_handle ( _HANDLE_READ_NAME ) if not name : raise BluetoothBackendException ( "Could not read NAME using handle %s" " from Mi Temp sensor %s" % ( hex ( _HANDLE_READ_NAME ) , self . _mac ) ) return '' . join (... | Return the name of the sensor . |
33,582 | def handleNotification ( self , handle , raw_data ) : if raw_data is None : return data = raw_data . decode ( "utf-8" ) . strip ( ' \n\t' ) self . _cache = data self . _check_data ( ) if self . cache_available ( ) : self . _last_read = datetime . now ( ) else : self . _last_read = datetime . now ( ) - self . _cache_tim... | gets called by the bluepy backend when using wait_for_notification |
33,583 | def add_journal ( self , data ) : journal = self . dispatcher ( 'add_journal' , data , self . _admintoken ) return json . loads ( journal ) | This method include new journals to the ArticleMeta . |
33,584 | def watermark_process ( ) : if not request . method == 'POST' : abort ( 403 ) if 'pdf' not in request . files : abort ( 403 ) file = request . files [ 'pdf' ] if file . filename == '' : abort ( 403 ) if not allowed_file ( file . filename ) : abort ( 403 ) params = { 'address' : request . form [ 'address' ] , 'town' : r... | Apply a watermark to a PDF file . |
33,585 | def slicer ( document , first_page = None , last_page = None , suffix = 'sliced' , tempdir = None ) : if tempdir : with NamedTemporaryFile ( suffix = '.pdf' , dir = tempdir , delete = False ) as temp : output = temp . name elif suffix : output = os . path . join ( os . path . dirname ( document ) , add_suffix ( documen... | Slice a PDF document to remove pages . |
33,586 | def _reader ( path , password , prompt ) : pdf = PdfFileReader ( path ) if not isinstance ( path , PdfFileReader ) else path if pdf . isEncrypted : if not password : pdf . decrypt ( '' ) if pdf . isEncrypted and prompt : print ( 'No password has been given for encrypted PDF ' , path ) password = input ( 'Enter Password... | Read PDF and decrypt if encrypted . |
33,587 | def _resolved_objects ( pdf , xobject ) : return [ pdf . getPage ( i ) . get ( xobject ) for i in range ( pdf . getNumPages ( ) ) ] [ 0 ] | Retrieve rotatation info . |
33,588 | def resources ( self ) : return [ self . pdf . getPage ( i ) for i in range ( self . pdf . getNumPages ( ) ) ] | Retrieve contents of each page of PDF |
33,589 | def security ( self ) : return { k : v for i in self . pdf . resolvedObjects . items ( ) for k , v in i [ 1 ] . items ( ) } | Print security object information for a pdf document |
33,590 | def _make_request ( self , url , params = None , opener = None ) : args = [ i for i in [ url , params ] if i ] request = urllib . request . Request ( * args ) if self . username and self . password : credentials = '%s:%s' % ( self . username , self . password ) encoded_credentials = base64 . encodestring ( credentials ... | Configure a HTTP request fire it off and return the response . |
33,591 | def put ( self , method , params ) : params [ '_method' ] = 'put' if params . get ( "document_ids" , None ) : document_ids = params . get ( "document_ids" ) del params [ 'document_ids' ] params = urllib . parse . urlencode ( params , doseq = True ) params += "" . join ( [ '&document_ids[]=%s' % id for id in document_id... | Post changes back to DocumentCloud |
33,592 | def fetch ( self , method , params = None ) : if params : params = urllib . parse . urlencode ( params , doseq = True ) . encode ( "utf-8" ) content = self . _make_request ( self . BASE_URI + method , params , ) return json . loads ( content . decode ( "utf-8" ) ) | Fetch an url . |
33,593 | def _get_search_page ( self , query , page , per_page = 1000 , mentions = 3 , data = False , ) : if mentions > 10 : raise ValueError ( "You cannot search for more than 10 mentions" ) params = { 'q' : query , 'page' : page , 'per_page' : per_page , 'mentions' : mentions , } if data : params [ 'data' ] = 'true' response ... | Retrieve one page of search results from the DocumentCloud API . |
33,594 | def search ( self , query , page = None , per_page = 1000 , mentions = 3 , data = False ) : if page : document_list = self . _get_search_page ( query , page = page , per_page = per_page , mentions = mentions , data = data , ) else : page = 1 document_list = [ ] while True : results = self . _get_search_page ( query , p... | Retrieve all objects that make a search query . |
33,595 | def get ( self , id ) : data = self . fetch ( 'documents/%s.json' % id ) . get ( "document" ) data [ '_connection' ] = self . _connection return Document ( data ) | Retrieve a particular document using it s unique identifier . |
33,596 | def upload ( self , pdf , title = None , source = None , description = None , related_article = None , published_url = None , access = 'private' , project = None , data = None , secure = False , force_ocr = False ) : if hasattr ( pdf , 'read' ) : try : size = os . fstat ( pdf . fileno ( ) ) . st_size except Exception :... | Upload a PDF or other image file to DocumentCloud . |
33,597 | def upload_directory ( self , path , source = None , description = None , related_article = None , published_url = None , access = 'private' , project = None , data = None , secure = False , force_ocr = False ) : path_list = [ ] for ( dirpath , dirname , filenames ) in os . walk ( path ) : path_list . extend ( [ os . p... | Uploads all the PDFs in the provided directory . |
33,598 | def all ( self ) : project_list = self . fetch ( 'projects.json' ) . get ( "projects" ) obj_list = [ ] for proj in project_list : proj [ '_connection' ] = self . _connection proj = Project ( proj ) obj_list . append ( proj ) return obj_list | Retrieve all your projects . Requires authentication . |
33,599 | def get ( self , id = None , title = None ) : if id and title : raise ValueError ( "You can only retrieve a Project by id or \ title, not by both" ) elif not id and not title : raise ValueError ( "You must provide an id or a title to \ make a request." ) if id : hit_list = [ i for i in sel... | Retrieve a particular project using its unique identifier or it s title . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.