idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,000
def cos_r ( self , N = None ) : if not hasattr ( self , 'F' ) or self . F . shape [ 1 ] < self . rank : self . fs_r ( N = self . rank ) self . dr = norm ( self . F , axis = 1 ) ** 2 return apply_along_axis ( lambda _ : _ / self . dr , 0 , self . F [ : , : N ] ** 2 )
Return the squared cosines for each row .
241,001
def cos_c ( self , N = None ) : if not hasattr ( self , 'G' ) or self . G . shape [ 1 ] < self . rank : self . fs_c ( N = self . rank ) self . dc = norm ( self . G , axis = 1 ) ** 2 return apply_along_axis ( lambda _ : _ / self . dc , 0 , self . G [ : , : N ] ** 2 )
Return the squared cosines for each column .
241,002
def cont_r ( self , percent = 0.9 , N = None ) : if not hasattr ( self , 'F' ) : self . fs_r ( N = self . rank ) return apply_along_axis ( lambda _ : _ / self . L [ : N ] , 1 , apply_along_axis ( lambda _ : _ * self . r , 0 , self . F [ : , : N ] ** 2 ) )
Return the contribution of each row .
241,003
def cont_c ( self , percent = 0.9 , N = None ) : if not hasattr ( self , 'G' ) : self . fs_c ( N = self . rank ) return apply_along_axis ( lambda _ : _ / self . L [ : N ] , 1 , apply_along_axis ( lambda _ : _ * self . c , 0 , self . G [ : , : N ] ** 2 ) )
Return the contribution of each column .
241,004
def fs_r_sup ( self , DF , N = None ) : if not hasattr ( self , 'G' ) : self . fs_c ( N = self . rank ) if N and ( not isinstance ( N , int ) or N <= 0 ) : raise ValueError ( "ncols should be a positive integer." ) s = - sqrt ( self . E ) if self . cor else self . s N = min ( N , self . rank ) if N else self . rank S_i...
Find the supplementary row factor scores .
241,005
def fs_c_sup ( self , DF , N = None ) : if not hasattr ( self , 'F' ) : self . fs_r ( N = self . rank ) if N and ( not isinstance ( N , int ) or N <= 0 ) : raise ValueError ( "ncols should be a positive integer." ) s = - sqrt ( self . E ) if self . cor else self . s N = min ( N , self . rank ) if N else self . rank S_i...
Find the supplementary column factor scores .
241,006
def data_recognise ( self , data = None ) : data = data or self . data data_lower = data . lower ( ) if data_lower . startswith ( u"http://" ) or data_lower . startswith ( u"https://" ) : return u'url' elif data_lower . startswith ( u"mailto:" ) : return u'email' elif data_lower . startswith ( u"matmsg:to:" ) : return ...
Returns an unicode string indicating the data type of the data paramater
241,007
def data_to_string ( self ) : if self . data_type == 'text' : return BOM_UTF8 + self . __class__ . data_encode [ self . data_type ] ( self . data ) . encode ( 'utf-8' ) else : return self . __class__ . data_encode [ self . data_type ] ( self . data ) . encode ( 'utf-8' )
Returns a UTF8 string with the QR Code s data
241,008
def split_six ( series = None ) : if pd is None : raise ImportError ( 'The Pandas package is required' ' for this functionality' ) if np is None : raise ImportError ( 'The NumPy package is required' ' for this functionality' ) def base ( x ) : if x > 0 : base = pow ( 10 , math . floor ( math . log10 ( x ) ) ) return ro...
Given a Pandas Series get a domain of values from zero to the 90% quantile rounded to the nearest order - of - magnitude integer . For example 2100 is rounded to 2000 2790 to 3000 .
241,009
def to_linear ( self , index = None ) : if index is None : n = len ( self . index ) - 1 index = [ self . index [ i ] * ( 1. - i / ( n - 1. ) ) + self . index [ i + 1 ] * i / ( n - 1. ) for i in range ( n ) ] colors = [ self . rgba_floats_tuple ( x ) for x in index ] return LinearColormap ( colors , index = index , vmin...
Transforms the StepColormap into a LinearColormap .
241,010
def add_to ( self , parent , name = None , index = None ) : parent . add_child ( self , name = name , index = index ) return self
Add element to a parent .
241,011
def to_json ( self , depth = - 1 , ** kwargs ) : return json . dumps ( self . to_dict ( depth = depth , ordered = True ) , ** kwargs )
Returns a JSON representation of the object .
241,012
def save ( self , outfile , close_file = True , ** kwargs ) : if isinstance ( outfile , text_type ) or isinstance ( outfile , binary_type ) : fid = open ( outfile , 'wb' ) else : fid = outfile root = self . get_root ( ) html = root . render ( ** kwargs ) fid . write ( html . encode ( 'utf8' ) ) if close_file : fid . cl...
Saves an Element into a file .
241,013
def get_code ( self ) : if self . code is None : self . code = urlopen ( self . url ) . read ( ) return self . code
Opens the link and returns the response s content .
241,014
def _repr_html_ ( self , ** kwargs ) : html = self . render ( ** kwargs ) html = "data:text/html;charset=utf-8;base64," + base64 . b64encode ( html . encode ( 'utf8' ) ) . decode ( 'utf8' ) if self . height is None : iframe = ( '<div style="width:{width};">' '<div style="position:relative;width:100%;height:0;padding-bo...
Displays the Figure in a Jupyter notebook .
241,015
def add_subplot ( self , x , y , n , margin = 0.05 ) : width = 1. / y height = 1. / x left = ( ( n - 1 ) % y ) * width top = ( ( n - 1 ) // y ) * height left = left + width * margin top = top + height * margin width = width * ( 1 - 2. * margin ) height = height * ( 1 - 2. * margin ) div = Div ( position = 'absolute' , ...
Creates a div child subplot in a matplotlib . figure . add_subplot style .
241,016
def _elapsed ( self ) : self . last_time = time . time ( ) return self . last_time - self . start
Returns elapsed time at update .
241,017
def _calc_eta ( self ) : elapsed = self . _elapsed ( ) if self . cnt == 0 or elapsed < 0.001 : return None rate = float ( self . cnt ) / elapsed self . eta = ( float ( self . max_iter ) - float ( self . cnt ) ) / rate
Calculates estimated time left until completion .
241,018
def _print_title ( self ) : if self . title : self . _stream_out ( '{}\n' . format ( self . title ) ) self . _stream_flush ( )
Prints tracking title at initialization .
241,019
def _cache_eta ( self ) : self . _calc_eta ( ) self . _cached_output += ' | ETA: ' + self . _get_time ( self . eta )
Prints the estimated time left .
241,020
def _adjust_width ( self ) : if self . bar_width > self . max_iter : self . bar_width = int ( self . max_iter )
Shrinks bar if number of iterations is less than the bar width
241,021
def _print ( self , force_flush = False ) : self . _stream_flush ( ) next_perc = self . _calc_percent ( ) if self . update_interval : do_update = time . time ( ) - self . last_time >= self . update_interval elif force_flush : do_update = True else : do_update = next_perc > self . last_progress if do_update and self . a...
Prints formatted percentage and tracked time to the screen .
241,022
def next ( self ) : try : line = self . _get_next_line ( ) except StopIteration : if self . _is_new_file ( ) : self . _rotated_logfile = None self . _fh . close ( ) self . _offset = 0 try : line = self . _get_next_line ( ) except StopIteration : self . _update_offset_file ( ) raise else : self . _update_offset_file ( )...
Return the next line in the file updating the offset .
241,023
def read ( self ) : lines = self . readlines ( ) if lines : try : return '' . join ( lines ) except TypeError : return '' . join ( force_text ( line ) for line in lines ) else : return None
Read in all unread lines and return them as a single string .
241,024
def _filehandle ( self ) : if not self . _fh or self . _is_closed ( ) : filename = self . _rotated_logfile or self . filename if filename . endswith ( '.gz' ) : self . _fh = gzip . open ( filename , 'r' ) else : self . _fh = open ( filename , "r" , 1 ) if self . read_from_end and not exists ( self . _offset_file ) : se...
Return a filehandle to the file being tailed with the position set to the current offset .
241,025
def _update_offset_file ( self ) : if self . on_update : self . on_update ( ) offset = self . _filehandle ( ) . tell ( ) inode = stat ( self . filename ) . st_ino fh = open ( self . _offset_file , "w" ) fh . write ( "%s\n%s\n" % ( inode , offset ) ) fh . close ( ) self . _since_update = 0
Update the offset file with the current inode and offset .
241,026
def _determine_rotated_logfile ( self ) : rotated_filename = self . _check_rotated_filename_candidates ( ) if rotated_filename and exists ( rotated_filename ) : if stat ( rotated_filename ) . st_ino == self . _offset_file_inode : return rotated_filename if stat ( self . filename ) . st_ino == self . _offset_file_inode ...
We suspect the logfile has been rotated so try to guess what the rotated filename is and return it .
241,027
def _check_rotated_filename_candidates ( self ) : candidate = "%s.0" % self . filename if ( exists ( candidate ) and exists ( "%s.1.gz" % self . filename ) and ( stat ( candidate ) . st_mtime > stat ( "%s.1.gz" % self . filename ) . st_mtime ) ) : return candidate candidate = "%s.1" % self . filename if exists ( candid...
Check for various rotated logfile filename patterns and return the first match we find .
241,028
def create_s3_session ( ) : sess = requests . Session ( ) retries = Retry ( total = 3 , backoff_factor = .5 , status_forcelist = [ 500 , 502 , 503 , 504 ] ) sess . mount ( 'https://' , HTTPAdapter ( max_retries = retries ) ) return sess
Creates a session with automatic retries on 5xx errors .
241,029
def load_module ( self , fullname ) : mod = sys . modules . setdefault ( fullname , imp . new_module ( fullname ) ) mod . __file__ = self . _path mod . __loader__ = self mod . __path__ = [ ] mod . __package__ = fullname return mod
Returns an empty module .
241,030
def load_module ( self , fullname ) : mod = sys . modules . get ( fullname ) if mod is not None : return mod mod = _from_core_node ( self . _store , self . _root ) sys . modules [ fullname ] = mod return mod
Returns an object that lazily looks up tables and groups .
241,031
def find_module ( self , fullname , path = None ) : if not fullname . startswith ( self . _module_name + '.' ) : return None submodule = fullname [ len ( self . _module_name ) + 1 : ] parts = submodule . split ( '.' ) if self . _teams : team = parts . pop ( 0 ) else : team = None if len ( parts ) == 2 : store , pkg = P...
Looks up the table based on the module path .
241,032
def _have_pyspark ( ) : if _have_pyspark . flag is None : try : if PackageStore . get_parquet_lib ( ) is ParquetLib . SPARK : import pyspark _have_pyspark . flag = True else : _have_pyspark . flag = False except ImportError : _have_pyspark . flag = False return _have_pyspark . flag
Check if we re running Pyspark
241,033
def _path_hash ( path , transform , kwargs ) : sortedargs = [ "%s:%r:%s" % ( key , value , type ( value ) ) for key , value in sorted ( iteritems ( kwargs ) ) ] srcinfo = "{path}:{transform}:{{{kwargs}}}" . format ( path = os . path . abspath ( path ) , transform = transform , kwargs = "," . join ( sortedargs ) ) retur...
Generate a hash of source file path + transform + args
241,034
def _gen_glob_data ( dir , pattern , child_table ) : dir = pathlib . Path ( dir ) matched = False used_names = set ( ) for filepath in sorted ( dir . glob ( pattern ) ) : if filepath . is_dir ( ) : continue else : matched = True node_table = { } if child_table is None else child_table . copy ( ) filepath = filepath . r...
Generates node data by globbing a directory for a pattern
241,035
def _remove_keywords ( d ) : return { k : v for k , v in iteritems ( d ) if k not in RESERVED }
copy the dict filter_keywords
241,036
def build_package ( team , username , package , subpath , yaml_path , checks_path = None , dry_run = False , env = 'default' ) : def find ( key , value ) : if isinstance ( value , Iterable ) and not isinstance ( value , string_types ) : for k , v in iteritems ( value ) : if k == key : yield v elif isinstance ( v , dict...
Builds a package from a given Yaml file and installs it locally .
241,037
def send_comment_email ( email , package_owner , package_name , commenter ) : link = '{CATALOG_URL}/package/{owner}/{pkg}/comments' . format ( CATALOG_URL = CATALOG_URL , owner = package_owner , pkg = package_name ) subject = "New comment on {package_owner}/{package_name}" . format ( package_owner = package_owner , pac...
Send email to owner of package regarding new comment
241,038
def hash_contents ( contents ) : assert isinstance ( contents , GroupNode ) result = hashlib . sha256 ( ) def _hash_int ( value ) : result . update ( struct . pack ( ">L" , value ) ) def _hash_str ( string ) : assert isinstance ( string , string_types ) _hash_int ( len ( string ) ) result . update ( string . encode ( )...
Creates a hash of key names and hashes in a package dictionary .
241,039
def find_object_hashes ( root , meta_only = False ) : stack = [ root ] while stack : obj = stack . pop ( ) if not meta_only and isinstance ( obj , ( TableNode , FileNode ) ) : for objhash in obj . hashes : yield objhash stack . extend ( itervalues ( obj . get_children ( ) ) ) if obj . metadata_hash is not None : yield ...
Iterator that returns hashes of all of the file and table nodes .
241,040
def _send_event_task ( args ) : endpoint = args [ 'endpoint' ] json_message = args [ 'json_message' ] _consumer_impl . send ( endpoint , json_message )
Actually sends the MixPanel event . Runs in a uwsgi worker process .
241,041
def send ( self , endpoint , json_message ) : _send_event_task . spool ( endpoint = endpoint , json_message = json_message )
Queues the message to be sent .
241,042
def main ( args = None ) : parser = argument_parser ( ) args = parser . parse_args ( args ) if not hasattr ( args , 'func' ) : args = parser . parse_args ( [ 'help' ] ) kwargs = vars ( args ) if kwargs . pop ( 'dev' ) or os . environ . get ( 'QUILT_DEV_MODE' , '' ) . strip ( ) . lower ( ) == 'true' : quilt . _DEV_MODE ...
Build and run parser
241,043
def is_identifier ( string ) : matched = PYTHON_IDENTIFIER_RE . match ( string ) return bool ( matched ) and not keyword . iskeyword ( string )
Check if string could be a valid python identifier
241,044
def fs_link ( path , linkpath , linktype = 'soft' ) : global WIN_SOFTLINK global WIN_HARDLINK WIN_NO_ERROR = 22 assert linktype in ( 'soft' , 'hard' ) path , linkpath = pathlib . Path ( path ) , pathlib . Path ( linkpath ) if not path . exists ( ) : raise QuiltException ( "Path to link to does not exist: {}" . format (...
Create a hard or soft link of path at linkpath
241,045
def read ( self , size = - 1 ) : buf = self . _fd . read ( size ) self . _progress_cb ( len ( buf ) ) return buf
Read bytes and update the progress bar .
241,046
def create_dirs ( self ) : if not os . path . isdir ( self . _path ) : os . makedirs ( self . _path ) for dir_name in [ self . OBJ_DIR , self . TMP_OBJ_DIR , self . PKG_DIR , self . CACHE_DIR ] : path = os . path . join ( self . _path , dir_name ) if not os . path . isdir ( path ) : os . mkdir ( path ) if not os . path...
Creates the store directory and its subdirectories .
241,047
def find_store_dirs ( cls ) : store_dirs = [ default_store_location ( ) ] extra_dirs_str = os . getenv ( 'QUILT_PACKAGE_DIRS' ) if extra_dirs_str : store_dirs . extend ( extra_dirs_str . split ( ':' ) ) return store_dirs
Returns the primary package directory and any additional ones from QUILT_PACKAGE_DIRS .
241,048
def find_package ( cls , team , user , package , pkghash = None , store_dir = None ) : cls . check_name ( team , user , package ) dirs = cls . find_store_dirs ( ) for store_dir in dirs : store = PackageStore ( store_dir ) pkg = store . get_package ( team , user , package , pkghash = pkghash ) if pkg is not None : retur...
Finds an existing package in one of the package directories .
241,049
def get_package ( self , team , user , package , pkghash = None ) : self . check_name ( team , user , package ) path = self . package_path ( team , user , package ) if not os . path . isdir ( path ) : return None if pkghash is None : latest_tag = os . path . join ( path , self . TAGS_DIR , self . LATEST ) if not os . p...
Gets a package from this store .
241,050
def install_package ( self , team , user , package , contents ) : self . check_name ( team , user , package ) assert contents is not None self . create_dirs ( ) path = self . package_path ( team , user , package ) try : os . remove ( path ) except OSError : pass
Creates a new package in the default package store and allocates a per - user directory if needed .
241,051
def create_package_node ( self , team , user , package , dry_run = False ) : contents = RootNode ( dict ( ) ) if dry_run : return contents self . check_name ( team , user , package ) assert contents is not None self . create_dirs ( ) path = self . package_path ( team , user , package ) try : os . remove ( path ) except...
Creates a new package and initializes its contents . See install_package .
241,052
def iterpackages ( self ) : pkgdir = os . path . join ( self . _path , self . PKG_DIR ) if not os . path . isdir ( pkgdir ) : return for team in sub_dirs ( pkgdir ) : for user in sub_dirs ( self . team_path ( team ) ) : for pkg in sub_dirs ( self . user_path ( team , user ) ) : pkgpath = self . package_path ( team , us...
Return an iterator over all the packages in the PackageStore .
241,053
def ls_packages ( self ) : packages = [ ] pkgdir = os . path . join ( self . _path , self . PKG_DIR ) if not os . path . isdir ( pkgdir ) : return [ ] for team in sub_dirs ( pkgdir ) : for user in sub_dirs ( self . team_path ( team ) ) : for pkg in sub_dirs ( self . user_path ( team , user ) ) : pkgpath = self . packag...
List packages in this store .
241,054
def team_path ( self , team = None ) : if team is None : team = DEFAULT_TEAM return os . path . join ( self . _path , self . PKG_DIR , team )
Returns the path to directory with the team s users package repositories .
241,055
def user_path ( self , team , user ) : return os . path . join ( self . team_path ( team ) , user )
Returns the path to directory with the user s package repositories .
241,056
def package_path ( self , team , user , package ) : return os . path . join ( self . user_path ( team , user ) , package )
Returns the path to a package repository .
241,057
def object_path ( self , objhash ) : return os . path . join ( self . _path , self . OBJ_DIR , objhash )
Returns the path to an object file based on its hash .
241,058
def prune ( self , objs = None ) : if objs is None : objdir = os . path . join ( self . _path , self . OBJ_DIR ) objs = os . listdir ( objdir ) remove_objs = set ( objs ) for pkg in self . iterpackages ( ) : remove_objs . difference_update ( find_object_hashes ( pkg ) ) for obj in remove_objs : path = self . object_pat...
Clean up objects not referenced by any packages . Try to prune all objects by default .
241,059
def save_dataframe ( self , dataframe ) : storepath = self . temporary_object_path ( str ( uuid . uuid4 ( ) ) ) parqlib = self . get_parquet_lib ( ) if isinstance ( dataframe , pd . DataFrame ) : import pyarrow as pa from pyarrow import parquet table = pa . Table . from_pandas ( dataframe ) parquet . write_table ( tabl...
Save a DataFrame to the store .
241,060
def load_numpy ( self , hash_list ) : assert len ( hash_list ) == 1 self . _check_hashes ( hash_list ) with open ( self . object_path ( hash_list [ 0 ] ) , 'rb' ) as fd : return np . load ( fd , allow_pickle = False )
Loads a numpy array .
241,061
def get_file ( self , hash_list ) : assert len ( hash_list ) == 1 self . _check_hashes ( hash_list ) return self . object_path ( hash_list [ 0 ] )
Returns the path of the file - but verifies that the hash is actually present .
241,062
def save_metadata ( self , metadata ) : if metadata in ( None , { } ) : return None if SYSTEM_METADATA in metadata : raise StoreException ( "Not allowed to store %r in metadata" % SYSTEM_METADATA ) path = self . temporary_object_path ( str ( uuid . uuid4 ( ) ) ) with open ( path , 'w' ) as fd : try : json . dump ( meta...
Save metadata to the store .
241,063
def save_package_contents ( self , root , team , owner , pkgname ) : assert isinstance ( root , RootNode ) instance_hash = hash_contents ( root ) pkg_path = self . package_path ( team , owner , pkgname ) if not os . path . isdir ( pkg_path ) : os . makedirs ( pkg_path ) os . mkdir ( os . path . join ( pkg_path , self ....
Saves the in - memory contents to a file in the local package repository .
241,064
def _move_to_store ( self , srcpath , objhash ) : destpath = self . object_path ( objhash ) if os . path . exists ( destpath ) : os . chmod ( destpath , S_IWUSR ) os . remove ( destpath ) os . chmod ( srcpath , S_IRUSR | S_IRGRP | S_IROTH ) move ( srcpath , destpath )
Make the object read - only and move it to the store .
241,065
def add_to_package_numpy ( self , root , ndarray , node_path , target , source_path , transform , custom_meta ) : filehash = self . save_numpy ( ndarray ) metahash = self . save_metadata ( custom_meta ) self . _add_to_package_contents ( root , node_path , [ filehash ] , target , source_path , transform , metahash )
Save a Numpy array to the store .
241,066
def add_to_package_package_tree ( self , root , node_path , pkgnode ) : if node_path : ptr = root for node in node_path [ : - 1 ] : ptr = ptr . children . setdefault ( node , GroupNode ( dict ( ) ) ) ptr . children [ node_path [ - 1 ] ] = pkgnode else : if root . children : raise PackageException ( "Attempting to overw...
Adds a package or sub - package tree from an existing package to this package s contents .
241,067
def _install_interrupt_handler ( ) : import os import sys import signal import pkg_resources from . tools import const quilt = pkg_resources . get_distribution ( 'quilt' ) executable = os . path . basename ( sys . argv [ 0 ] ) entry_points = quilt . get_entry_map ( ) . get ( 'console_scripts' , [ ] ) if executable == '...
Suppress KeyboardInterrupt traceback display in specific situations
241,068
def _data_keys ( self ) : return [ name for name , child in iteritems ( self . _children ) if not isinstance ( child , GroupNode ) ]
every child key referencing a dataframe
241,069
def _group_keys ( self ) : return [ name for name , child in iteritems ( self . _children ) if isinstance ( child , GroupNode ) ]
every child key referencing a group that is not a dataframe
241,070
def _data ( self , asa = None ) : hash_list = [ ] stack = [ self ] alldfs = True store = None while stack : node = stack . pop ( ) if isinstance ( node , GroupNode ) : stack . extend ( child for _ , child in sorted ( node . _items ( ) , reverse = True ) ) else : if node . _target ( ) != TargetType . PANDAS : alldfs = F...
Merges all child dataframes . Only works for dataframes stored on disk - not in memory .
241,071
def _set ( self , path , value , build_dir = '' ) : assert isinstance ( path , list ) and len ( path ) > 0 if isinstance ( value , pd . DataFrame ) : metadata = { SYSTEM_METADATA : { 'target' : TargetType . PANDAS . value } } elif isinstance ( value , np . ndarray ) : metadata = { SYSTEM_METADATA : { 'target' : TargetT...
Create and set a node by path
241,072
def handle_api_exception ( error ) : _mp_track ( type = "exception" , status_code = error . status_code , message = error . message , ) response = jsonify ( dict ( message = error . message ) ) response . status_code = error . status_code return response
Converts an API exception into an error response .
241,073
def api ( require_login = True , schema = None , enabled = True , require_admin = False , require_anonymous = False ) : if require_admin : require_login = True if schema is not None : Draft4Validator . check_schema ( schema ) validator = Draft4Validator ( schema ) else : validator = None assert not ( require_login and ...
Decorator for API requests . Handles auth and adds the username as the first argument .
241,074
def _private_packages_allowed ( ) : if not HAVE_PAYMENTS or TEAM_ID : return True customer = _get_or_create_customer ( ) plan = _get_customer_plan ( customer ) return plan != PaymentPlan . FREE
Checks if the current user is allowed to create private packages .
241,075
def _create_auth ( team , timeout = None ) : url = get_registry_url ( team ) contents = _load_auth ( ) auth = contents . get ( url ) if auth is not None : if auth [ 'expires_at' ] < time . time ( ) + 60 : try : auth = _update_auth ( team , auth [ 'refresh_token' ] , timeout ) except CommandException as ex : raise Comma...
Reads the credentials updates the access token if necessary and returns it .
241,076
def _create_session ( team , auth ) : session = requests . Session ( ) session . hooks . update ( dict ( response = partial ( _handle_response , team ) ) ) session . headers . update ( { "Content-Type" : "application/json" , "Accept" : "application/json" , "User-Agent" : "quilt-cli/%s (%s %s) %s/%s" % ( VERSION , platf...
Creates a session object to be used for push install etc .
241,077
def _get_session ( team , timeout = None ) : global _sessions session = _sessions . get ( team ) if session is None : auth = _create_auth ( team , timeout ) _sessions [ team ] = session = _create_session ( team , auth ) assert session is not None return session
Creates a session or returns an existing session .
241,078
def _check_team_login ( team ) : contents = _load_auth ( ) for auth in itervalues ( contents ) : existing_team = auth . get ( 'team' ) if team and team != existing_team : raise CommandException ( "Can't log in as team %r; log out first." % team ) elif not team and existing_team : raise CommandException ( "Can't log in ...
Disallow simultaneous public cloud and team logins .
241,079
def _check_team_exists ( team ) : if team is None : return hostname = urlparse ( get_registry_url ( team ) ) . hostname try : socket . gethostbyname ( hostname ) except IOError : try : socket . gethostbyname ( 'quiltdata.com' ) except IOError : message = "Can't find quiltdata.com. Check your internet connection." else ...
Check that the team registry actually exists .
241,080
def login_with_token ( refresh_token , team = None ) : _check_team_id ( team ) auth = _update_auth ( team , refresh_token ) url = get_registry_url ( team ) contents = _load_auth ( ) contents [ url ] = auth _save_auth ( contents ) _clear_session ( team )
Authenticate using an existing token .
241,081
def generate ( directory , outfilename = DEFAULT_BUILDFILE ) : try : buildfilepath = generate_build_file ( directory , outfilename = outfilename ) except BuildException as builderror : raise CommandException ( str ( builderror ) ) print ( "Generated build-file %s." % ( buildfilepath ) )
Generate a build - file for quilt build from a directory of source files .
241,082
def build ( package , path = None , dry_run = False , env = 'default' , force = False , build_file = False ) : team , _ , _ , subpath = parse_package ( package , allow_subpath = True ) _check_team_id ( team ) logged_in_team = _find_logged_in_team ( ) if logged_in_team is not None and team is None and force is False : a...
Compile a Quilt data package either from a build file or an existing package node .
241,083
def build_from_node ( package , node ) : team , owner , pkg , subpath = parse_package ( package , allow_subpath = True ) _check_team_id ( team ) store = PackageStore ( ) pkg_root = get_or_create_package ( store , team , owner , pkg , subpath ) if not subpath and not isinstance ( node , nodes . GroupNode ) : raise Comma...
Compile a Quilt data package from an existing package node .
241,084
def build_from_path ( package , path , dry_run = False , env = 'default' , outfilename = DEFAULT_BUILDFILE ) : team , owner , pkg , subpath = parse_package ( package , allow_subpath = True ) if not os . path . exists ( path ) : raise CommandException ( "%s does not exist." % path ) try : if os . path . isdir ( path ) :...
Compile a Quilt data package from a build file . Path can be a directory in which case the build file will be generated automatically .
241,085
def log ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) response = session . get ( "{url}/api/log/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) ) table = [ ( "Hash" , "Pushed" , "Author" , "Tags" , "Versions" ) ] for entry in revers...
List all of the changes to a package on the server .
241,086
def push ( package , is_public = False , is_team = False , reupload = False , hash = None ) : team , owner , pkg , subpath = parse_package ( package , allow_subpath = True ) _check_team_id ( team ) session = _get_session ( team ) store , pkgroot = PackageStore . find_package ( team , owner , pkg , pkghash = hash ) if p...
Push a Quilt data package to the server
241,087
def version_list ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) response = session . get ( "{url}/api/version/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) ) for version in response . json ( ) [ 'versions' ] : print ( "%s: %s" % ( ...
List the versions of a package .
241,088
def version_add ( package , version , pkghash , force = False ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) try : Version ( version ) except ValueError : url = "https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes" raise CommandException ( "Invalid version...
Add a new version for a given package hash .
241,089
def tag_list ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) response = session . get ( "{url}/api/tag/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) ) for tag in response . json ( ) [ 'tags' ] : print ( "%s: %s" % ( tag [ 'tag' ] , ...
List the tags of a package .
241,090
def tag_add ( package , tag , pkghash ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) session . put ( "{url}/api/tag/{owner}/{pkg}/{tag}" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg , tag = tag ) , data = json . dumps ( dict ( hash = _match_hash ( package , ...
Add a new tag for a given package hash .
241,091
def install_via_requirements ( requirements_str , force = False ) : if requirements_str [ 0 ] == '@' : path = requirements_str [ 1 : ] if os . path . isfile ( path ) : yaml_data = load_yaml ( path ) if 'packages' not in yaml_data . keys ( ) : raise CommandException ( 'Error in {filename}: missing "packages" node' . for...
Download multiple Quilt data packages via quilt . xml requirements file .
241,092
def access_list ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) lookup_url = "{url}/api/access/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) response = session . get ( lookup_url ) data = response . json ( ) users = data [ 'users' ]...
Print list of users who can access a package .
241,093
def delete ( package ) : team , owner , pkg = parse_package ( package ) answer = input ( "Are you sure you want to delete this package and its entire history? " "Type '%s' to confirm: " % package ) if answer != package : print ( "Not deleting." ) return 1 session = _get_session ( team ) session . delete ( "%s/api/packa...
Delete a package from the server .
241,094
def search ( query , team = None ) : if team is None : team = _find_logged_in_team ( ) if team is not None : session = _get_session ( team ) response = session . get ( "%s/api/search/" % get_registry_url ( team ) , params = dict ( q = query ) ) print ( "* Packages in team %s" % team ) packages = response . json ( ) [ '...
Search for packages
241,095
def ls ( ) : for pkg_dir in PackageStore . find_store_dirs ( ) : print ( "%s" % pkg_dir ) packages = PackageStore ( pkg_dir ) . ls_packages ( ) for package , tag , pkghash in sorted ( packages ) : print ( "{0:30} {1:20} {2}" . format ( package , tag , pkghash ) )
List all installed Quilt data packages
241,096
def inspect ( package ) : team , owner , pkg = parse_package ( package ) store , pkgroot = PackageStore . find_package ( team , owner , pkg ) if pkgroot is None : raise CommandException ( "Package {package} not found." . format ( package = package ) ) def _print_children ( children , prefix , path ) : for idx , ( name ...
Inspect package details
241,097
def load ( pkginfo , hash = None ) : node , pkgroot , info = _load ( pkginfo , hash ) for subnode_name in info . subpath : node = node [ subnode_name ] return node
functional interface to from quilt . data . USER import PKG
241,098
def c_ideal_gas ( T , k , MW ) : r Rspecific = R * 1000. / MW return ( k * Rspecific * T ) ** 0.5
r Calculates speed of sound c in an ideal gas at temperature T .
241,099
def Reynolds ( V , D , rho = None , mu = None , nu = None ) : r if rho and mu : nu = mu / rho elif not nu : raise Exception ( 'Either density and viscosity, or dynamic viscosity, \ is needed' ) return V * D / nu
r Calculates Reynolds number or Re for a fluid with the given properties for the specified velocity and diameter .