idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
227,100 | def draw_line2d ( data , obj ) : content = [ ] addplot_options = [ ] # If line is of length 0, do nothing. Otherwise, an empty \addplot table will be # created, which will be interpreted as an external data source in either the file # '' or '.tex'. Instead, render nothing. if len ( obj . get_xdata ( ) ) == 0 : return data , [ ] # get the linewidth (in pt) line_width = mypath . mpl_linewidth2pgfp_linewidth ( data , obj . get_linewidth ( ) ) if line_width : addplot_options . append ( line_width ) # get line color color = obj . get_color ( ) data , line_xcolor , _ = mycol . mpl_color2xcolor ( data , color ) addplot_options . append ( line_xcolor ) alpha = obj . get_alpha ( ) if alpha is not None : addplot_options . append ( "opacity={}" . format ( alpha ) ) linestyle = mypath . mpl_linestyle2pgfplots_linestyle ( obj . get_linestyle ( ) , line = obj ) if linestyle is not None and linestyle != "solid" : addplot_options . append ( linestyle ) marker_face_color = obj . get_markerfacecolor ( ) marker_edge_color = obj . get_markeredgecolor ( ) data , marker , extra_mark_options = _mpl_marker2pgfp_marker ( data , obj . get_marker ( ) , marker_face_color ) if marker : _marker ( obj , data , marker , addplot_options , extra_mark_options , marker_face_color , marker_edge_color , line_xcolor , ) if marker and linestyle is None : addplot_options . append ( "only marks" ) # Check if a line is in a legend and forget it if not. # Fixes <https://github.com/nschloe/matplotlib2tikz/issues/167>. legend_text = get_legend_text ( obj ) if legend_text is None and has_legend ( obj . axes ) : addplot_options . append ( "forget plot" ) # process options content . append ( "\\addplot " ) if addplot_options : content . append ( "[{}]\n" . format ( ", " . join ( addplot_options ) ) ) c , axis_options = _table ( obj , data ) content += c if legend_text is not None : content . append ( "\\addlegendentry{{{}}}\n" . format ( legend_text ) ) return data , content | Returns the PGFPlots code for an Line2D environment . | 603 | 14 |
227,101 | def draw_linecollection ( data , obj ) : content = [ ] edgecolors = obj . get_edgecolors ( ) linestyles = obj . get_linestyles ( ) linewidths = obj . get_linewidths ( ) paths = obj . get_paths ( ) for i , path in enumerate ( paths ) : color = edgecolors [ i ] if i < len ( edgecolors ) else edgecolors [ 0 ] style = linestyles [ i ] if i < len ( linestyles ) else linestyles [ 0 ] width = linewidths [ i ] if i < len ( linewidths ) else linewidths [ 0 ] data , options = mypath . get_draw_options ( data , obj , color , None , style , width ) # TODO what about masks? data , cont , _ , _ = mypath . draw_path ( data , path , draw_options = options , simplify = False ) content . append ( cont + "\n" ) return data , content | Returns Pgfplots code for a number of patch objects . | 222 | 14 |
227,102 | def _mpl_marker2pgfp_marker ( data , mpl_marker , marker_face_color ) : # try default list try : pgfplots_marker = _MP_MARKER2PGF_MARKER [ mpl_marker ] except KeyError : pass else : if ( marker_face_color is not None ) and pgfplots_marker == "o" : pgfplots_marker = "*" data [ "tikz libs" ] . add ( "plotmarks" ) marker_options = None return ( data , pgfplots_marker , marker_options ) # try plotmarks list try : data [ "tikz libs" ] . add ( "plotmarks" ) pgfplots_marker , marker_options = _MP_MARKER2PLOTMARKS [ mpl_marker ] except KeyError : # There's no equivalent for the pixel marker (,) in Pgfplots. pass else : if ( marker_face_color is not None and ( not isinstance ( marker_face_color , str ) or marker_face_color . lower ( ) != "none" ) and pgfplots_marker not in [ "|" , "-" , "asterisk" , "star" ] ) : pgfplots_marker += "*" return ( data , pgfplots_marker , marker_options ) return data , None , None | Translates a marker style of matplotlib to the corresponding style in PGFPlots . | 326 | 20 |
227,103 | def _transform_positioning ( ha , va ) : if ha == "center" and va == "center" : return None ha_mpl_to_tikz = { "right" : "east" , "left" : "west" , "center" : "" } va_mpl_to_tikz = { "top" : "north" , "bottom" : "south" , "center" : "" , "baseline" : "base" , } return "anchor={} {}" . format ( va_mpl_to_tikz [ va ] , ha_mpl_to_tikz [ ha ] ) . strip ( ) | Converts matplotlib positioning to pgf node positioning . Not quite accurate but the results are equivalent more or less . | 148 | 24 |
227,104 | def import_from_json ( filename_or_fobj , encoding = "utf-8" , * args , * * kwargs ) : source = Source . from_file ( filename_or_fobj , mode = "rb" , plugin_name = "json" , encoding = encoding ) json_obj = json . load ( source . fobj , encoding = source . encoding ) field_names = list ( json_obj [ 0 ] . keys ( ) ) table_rows = [ [ item [ key ] for key in field_names ] for item in json_obj ] meta = { "imported_from" : "json" , "source" : source } return create_table ( [ field_names ] + table_rows , meta = meta , * args , * * kwargs ) | Import a JSON file or file - like object into a rows . Table . | 173 | 15 |
227,105 | def export_to_json ( table , filename_or_fobj = None , encoding = "utf-8" , indent = None , * args , * * kwargs ) : # TODO: will work only if table.fields is OrderedDict fields = table . fields prepared_table = prepare_to_export ( table , * args , * * kwargs ) field_names = next ( prepared_table ) data = [ { field_name : _convert ( value , fields [ field_name ] , * args , * * kwargs ) for field_name , value in zip ( field_names , row ) } for row in prepared_table ] result = json . dumps ( data , indent = indent ) if type ( result ) is six . text_type : # Python 3 result = result . encode ( encoding ) if indent is not None : # clean up empty spaces at the end of lines result = b"\n" . join ( line . rstrip ( ) for line in result . splitlines ( ) ) return export_data ( filename_or_fobj , result , mode = "wb" ) | Export a rows . Table to a JSON file or file - like object . | 242 | 15 |
227,106 | def plugin_name_by_uri ( uri ) : # TODO: parse URIs like 'sqlite://' also parsed = urlparse ( uri ) basename = os . path . basename ( parsed . path ) if not basename . strip ( ) : raise RuntimeError ( "Could not identify file format." ) plugin_name = basename . split ( "." ) [ - 1 ] . lower ( ) if plugin_name in FILE_EXTENSIONS : plugin_name = MIME_TYPE_TO_PLUGIN_NAME [ FILE_EXTENSIONS [ plugin_name ] ] return plugin_name | Return the plugin name based on the URI | 133 | 8 |
227,107 | def extension_by_source ( source , mime_type ) : # TODO: should get this information from the plugin extension = source . plugin_name if extension : return extension if mime_type : return mime_type . split ( "/" ) [ - 1 ] | Return the file extension used by this plugin | 59 | 8 |
227,108 | def plugin_name_by_mime_type ( mime_type , mime_name , file_extension ) : return MIME_TYPE_TO_PLUGIN_NAME . get ( normalize_mime_type ( mime_type , mime_name , file_extension ) , None ) | Return the plugin name based on the MIME type | 70 | 10 |
227,109 | def detect_source ( uri , verify_ssl , progress , timeout = 5 ) : # TODO: should also supporte other schemes, like file://, sqlite:// etc. if uri . lower ( ) . startswith ( "http://" ) or uri . lower ( ) . startswith ( "https://" ) : return download_file ( uri , verify_ssl = verify_ssl , timeout = timeout , progress = progress , detect = True ) elif uri . startswith ( "postgres://" ) : return Source ( should_delete = False , encoding = None , plugin_name = "postgresql" , uri = uri , is_file = False , local = None , ) else : return local_file ( uri ) | Return a rows . Source with information for a given URI | 168 | 11 |
227,110 | def import_from_source ( source , default_encoding , * args , * * kwargs ) : # TODO: test open_compressed plugin_name = source . plugin_name kwargs [ "encoding" ] = ( kwargs . get ( "encoding" , None ) or source . encoding or default_encoding ) try : import_function = getattr ( rows , "import_from_{}" . format ( plugin_name ) ) except AttributeError : raise ValueError ( 'Plugin (import) "{}" not found' . format ( plugin_name ) ) table = import_function ( source . uri , * args , * * kwargs ) return table | Import data described in a rows . Source into a rows . Table | 150 | 13 |
227,111 | def import_from_uri ( uri , default_encoding = "utf-8" , verify_ssl = True , progress = False , * args , * * kwargs ) : # TODO: support '-' also # TODO: (optimization) if `kwargs.get('encoding', None) is not None` we can # skip encoding detection. source = detect_source ( uri , verify_ssl = verify_ssl , progress = progress ) return import_from_source ( source , default_encoding , * args , * * kwargs ) | Given an URI detects plugin and encoding and imports into a rows . Table | 124 | 14 |
227,112 | def open_compressed ( filename , mode = "r" , encoding = None ) : # TODO: integrate this function in the library itself, using # get_filename_and_fobj binary_mode = "b" in mode extension = str ( filename ) . split ( "." ) [ - 1 ] . lower ( ) if binary_mode and encoding : raise ValueError ( "encoding should not be specified in binary mode" ) if extension == "xz" : if lzma is None : raise RuntimeError ( "lzma support is not installed" ) fobj = lzma . open ( filename , mode = mode ) if binary_mode : return fobj else : return io . TextIOWrapper ( fobj , encoding = encoding ) elif extension == "gz" : fobj = gzip . GzipFile ( filename , mode = mode ) if binary_mode : return fobj else : return io . TextIOWrapper ( fobj , encoding = encoding ) elif extension == "bz2" : if bz2 is None : raise RuntimeError ( "bzip2 support is not installed" ) if binary_mode : # ignore encoding return bz2 . open ( filename , mode = mode ) else : if "t" not in mode : # For some reason, passing only mode='r' to bzip2 is equivalent # to 'rb', not 'rt', so we force it here. mode += "t" return bz2 . open ( filename , mode = mode , encoding = encoding ) else : if binary_mode : return open ( filename , mode = mode ) else : return open ( filename , mode = mode , encoding = encoding ) | Return a text - based file object from a filename even if compressed | 360 | 13 |
227,113 | def csv_to_sqlite ( input_filename , output_filename , samples = None , dialect = None , batch_size = 10000 , encoding = "utf-8" , callback = None , force_types = None , chunk_size = 8388608 , table_name = "table1" , schema = None , ) : # TODO: automatically detect encoding if encoding == `None` # TODO: should be able to specify fields # TODO: if table_name is "2019" the final name will be "field_2019" - must # be "table_2019" # TODO: if schema is provided and the names are in uppercase, this function # will fail if dialect is None : # Get a sample to detect dialect fobj = open_compressed ( input_filename , mode = "rb" ) sample = fobj . read ( chunk_size ) dialect = rows . plugins . csv . discover_dialect ( sample , encoding = encoding ) elif isinstance ( dialect , six . text_type ) : dialect = csv . get_dialect ( dialect ) if schema is None : # Identify data types fobj = open_compressed ( input_filename , encoding = encoding ) data = list ( islice ( csv . DictReader ( fobj , dialect = dialect ) , samples ) ) schema = rows . import_from_dicts ( data ) . fields if force_types is not None : schema . update ( force_types ) # Create lazy table object to be converted # TODO: this lazyness feature will be incorported into the library soon so # we can call here `rows.import_from_csv` instead of `csv.reader`. reader = csv . reader ( open_compressed ( input_filename , encoding = encoding ) , dialect = dialect ) header = make_header ( next ( reader ) ) # skip header table = rows . Table ( fields = OrderedDict ( [ ( field , schema [ field ] ) for field in header ] ) ) table . _rows = reader # Export to SQLite return rows . export_to_sqlite ( table , output_filename , table_name = table_name , batch_size = batch_size , callback = callback , ) | Export a CSV file to SQLite based on field type detection from samples | 480 | 14 |
227,114 | def sqlite_to_csv ( input_filename , table_name , output_filename , dialect = csv . excel , batch_size = 10000 , encoding = "utf-8" , callback = None , query = None , ) : # TODO: should be able to specify fields # TODO: should be able to specify custom query if isinstance ( dialect , six . text_type ) : dialect = csv . get_dialect ( dialect ) if query is None : query = "SELECT * FROM {}" . format ( table_name ) connection = sqlite3 . Connection ( input_filename ) cursor = connection . cursor ( ) result = cursor . execute ( query ) header = [ item [ 0 ] for item in cursor . description ] fobj = open_compressed ( output_filename , mode = "w" , encoding = encoding ) writer = csv . writer ( fobj , dialect = dialect ) writer . writerow ( header ) total_written = 0 for batch in rows . plugins . utils . ipartition ( result , batch_size ) : writer . writerows ( batch ) written = len ( batch ) total_written += written if callback : callback ( written , total_written ) fobj . close ( ) | Export a table inside a SQLite database to CSV | 262 | 10 |
227,115 | def execute_command ( command ) : command = shlex . split ( command ) try : process = subprocess . Popen ( command , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) except FileNotFoundError : raise RuntimeError ( "Command not found: {}" . format ( repr ( command ) ) ) process . wait ( ) # TODO: may use another codec to decode if process . returncode > 0 : stderr = process . stderr . read ( ) . decode ( "utf-8" ) raise ValueError ( "Error executing command: {}" . format ( repr ( stderr ) ) ) return process . stdout . read ( ) . decode ( "utf-8" ) | Execute a command and return its output | 172 | 8 |
227,116 | def uncompressed_size ( filename ) : quoted_filename = shlex . quote ( filename ) # TODO: get filetype from file-magic, if available if str ( filename ) . lower ( ) . endswith ( ".xz" ) : output = execute_command ( 'xz --list "{}"' . format ( quoted_filename ) ) compressed , uncompressed = regexp_sizes . findall ( output ) value , unit = uncompressed . split ( ) value = float ( value . replace ( "," , "" ) ) return int ( value * MULTIPLIERS [ unit ] ) elif str ( filename ) . lower ( ) . endswith ( ".gz" ) : # XXX: gzip only uses 32 bits to store uncompressed size, so if the # uncompressed size is greater than 4GiB, the value returned will be # incorrect. output = execute_command ( 'gzip --list "{}"' . format ( quoted_filename ) ) lines = [ line . split ( ) for line in output . splitlines ( ) ] header , data = lines [ 0 ] , lines [ 1 ] gzip_data = dict ( zip ( header , data ) ) return int ( gzip_data [ "uncompressed" ] ) else : raise ValueError ( 'Unrecognized file type for "{}".' . format ( filename ) ) | Return the uncompressed size for a file by executing commands | 292 | 11 |
227,117 | def pgimport ( filename , database_uri , table_name , encoding = "utf-8" , dialect = None , create_table = True , schema = None , callback = None , timeout = 0.1 , chunk_size = 8388608 , max_samples = 10000 , ) : fobj = open_compressed ( filename , mode = "r" , encoding = encoding ) sample = fobj . read ( chunk_size ) if dialect is None : # Detect dialect dialect = rows . plugins . csv . discover_dialect ( sample . encode ( encoding ) , encoding = encoding ) elif isinstance ( dialect , six . text_type ) : dialect = csv . get_dialect ( dialect ) if schema is None : # Detect field names reader = csv . reader ( io . StringIO ( sample ) , dialect = dialect ) field_names = [ slug ( field_name ) for field_name in next ( reader ) ] else : field_names = list ( schema . keys ( ) ) if create_table : if schema is None : data = [ dict ( zip ( field_names , row ) ) for row in itertools . islice ( reader , max_samples ) ] table = rows . import_from_dicts ( data ) field_types = [ table . fields [ field_name ] for field_name in field_names ] else : field_types = list ( schema . values ( ) ) columns = [ "{} {}" . format ( name , POSTGRESQL_TYPES . get ( type_ , DEFAULT_POSTGRESQL_TYPE ) ) for name , type_ in zip ( field_names , field_types ) ] create_table = SQL_CREATE_TABLE . format ( table_name = table_name , field_types = ", " . join ( columns ) ) execute_command ( get_psql_command ( create_table , database_uri = database_uri ) ) # Prepare the `psql` command to be executed based on collected metadata command = get_psql_copy_command ( database_uri = database_uri , dialect = dialect , direction = "FROM" , encoding = encoding , header = field_names , table_name = table_name , ) rows_imported , error = 0 , None fobj = open_compressed ( filename , mode = "rb" ) try : process = subprocess . Popen ( shlex . split ( command ) , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) data = fobj . read ( chunk_size ) total_written = 0 while data != b"" : written = process . stdin . write ( data ) total_written += written if callback : callback ( written , total_written ) data = fobj . read ( chunk_size ) stdout , stderr = process . communicate ( ) if stderr != b"" : raise RuntimeError ( stderr . decode ( "utf-8" ) ) rows_imported = int ( stdout . replace ( b"COPY " , b"" ) . strip ( ) ) except FileNotFoundError : raise RuntimeError ( "Command `psql` not found" ) except BrokenPipeError : raise RuntimeError ( process . stderr . read ( ) . decode ( "utf-8" ) ) return { "bytes_written" : total_written , "rows_imported" : rows_imported } | Import data from CSV into PostgreSQL using the fastest method | 756 | 11 |
227,118 | def pgexport ( database_uri , table_name , filename , encoding = "utf-8" , dialect = csv . excel , callback = None , timeout = 0.1 , chunk_size = 8388608 , ) : if isinstance ( dialect , six . text_type ) : dialect = csv . get_dialect ( dialect ) # Prepare the `psql` command to be executed to export data command = get_psql_copy_command ( database_uri = database_uri , direction = "TO" , encoding = encoding , header = None , # Needed when direction = 'TO' table_name = table_name , dialect = dialect , ) fobj = open_compressed ( filename , mode = "wb" ) try : process = subprocess . Popen ( shlex . split ( command ) , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) total_written = 0 data = process . stdout . read ( chunk_size ) while data != b"" : written = fobj . write ( data ) total_written += written if callback : callback ( written , total_written ) data = process . stdout . read ( chunk_size ) stdout , stderr = process . communicate ( ) if stderr != b"" : raise RuntimeError ( stderr . decode ( "utf-8" ) ) except FileNotFoundError : raise RuntimeError ( "Command `psql` not found" ) except BrokenPipeError : raise RuntimeError ( process . stderr . read ( ) . decode ( "utf-8" ) ) return { "bytes_written" : total_written } | Export data from PostgreSQL into a CSV file using the fastest method | 370 | 13 |
227,119 | def load_schema ( filename , context = None ) : table = import_from_uri ( filename ) field_names = table . field_names assert "field_name" in field_names assert "field_type" in field_names context = context or { key . replace ( "Field" , "" ) . lower ( ) : getattr ( rows . fields , key ) for key in dir ( rows . fields ) if "Field" in key and key != "Field" } return OrderedDict ( [ ( row . field_name , context [ row . field_type ] ) for row in table ] ) | Load schema from file in any of the supported formats | 132 | 10 |
227,120 | def slug ( text , separator = "_" , permitted_chars = SLUG_CHARS ) : text = six . text_type ( text or "" ) # Strip non-ASCII characters # Example: u' ÁLVARO justen% ' -> ' ALVARO justen% ' text = normalize ( "NFKD" , text . strip ( ) ) . encode ( "ascii" , "ignore" ) . decode ( "ascii" ) # Replace word boundaries with separator text = REGEXP_WORD_BOUNDARY . sub ( "\\1" + re . escape ( separator ) , text ) # Remove non-permitted characters and put everything to lowercase # Example: u'_ALVARO__justen%_' -> u'_alvaro__justen_' allowed_chars = list ( permitted_chars ) + [ separator ] text = "" . join ( char for char in text if char in allowed_chars ) . lower ( ) # Remove double occurrencies of separator # Example: u'_alvaro__justen_' -> u'_alvaro_justen_' text = ( REGEXP_SEPARATOR if separator == "_" else re . compile ( "(" + re . escape ( separator ) + "+)" ) ) . sub ( separator , text ) # Strip separators # Example: u'_alvaro_justen_' -> u'alvaro_justen' return text . strip ( separator ) | Generate a slug for the text . | 335 | 8 |
227,121 | def make_unique_name ( name , existing_names , name_format = "{name}_{index}" , start = 2 ) : index = start new_name = name while new_name in existing_names : new_name = name_format . format ( name = name , index = index ) index += 1 return new_name | Return a unique name based on name_format and name . | 71 | 12 |
227,122 | def make_header ( field_names , permit_not = False ) : slug_chars = SLUG_CHARS if not permit_not else SLUG_CHARS + "^" header = [ slug ( field_name , permitted_chars = slug_chars ) for field_name in field_names ] result = [ ] for index , field_name in enumerate ( header ) : if not field_name : field_name = "field_{}" . format ( index ) elif field_name [ 0 ] . isdigit ( ) : field_name = "field_{}" . format ( field_name ) if field_name in result : field_name = make_unique_name ( name = field_name , existing_names = result , start = 2 ) result . append ( field_name ) return result | Return unique and slugged field names . | 177 | 8 |
227,123 | def deserialize ( cls , value , * args , * * kwargs ) : if isinstance ( value , cls . TYPE ) : return value elif is_null ( value ) : return None else : return value | Deserialize a value just after importing it | 49 | 9 |
227,124 | def selected_objects ( self ) : return [ obj for obj in self . text_objects if contains_or_overlap ( self . table_bbox , obj . bbox ) ] | Filter out objects outside table boundaries | 40 | 6 |
227,125 | def transform ( row , table ) : data = row . _asdict ( ) data [ "links" ] = " " . join ( extract_links ( row . project ) ) for key , value in data . items ( ) : if isinstance ( value , six . text_type ) : data [ key ] = extract_text ( value ) return data | Extract links from project field and remove HTML from all | 75 | 11 |
227,126 | def transform ( row , table ) : data = row . _asdict ( ) data [ "link" ] = urljoin ( "https://pt.wikipedia.org" , data [ "link" ] ) data [ "name" ] , data [ "state" ] = regexp_city_state . findall ( data [ "name" ] ) [ 0 ] return data | Transform row link into full URL and add state based on name | 80 | 12 |
227,127 | def import_from_parquet ( filename_or_fobj , * args , * * kwargs ) : source = Source . from_file ( filename_or_fobj , plugin_name = "parquet" , mode = "rb" ) # TODO: should look into `schema.converted_type` also types = OrderedDict ( [ ( schema . name , PARQUET_TO_ROWS [ schema . type ] ) for schema in parquet . _read_footer ( source . fobj ) . schema if schema . type is not None ] ) header = list ( types . keys ( ) ) table_rows = list ( parquet . reader ( source . fobj ) ) # TODO: be lazy meta = { "imported_from" : "parquet" , "source" : source } return create_table ( [ header ] + table_rows , meta = meta , force_types = types , * args , * * kwargs ) | Import data from a Parquet file and return with rows . Table . | 213 | 14 |
227,128 | def import_from_dicts ( data , samples = None , * args , * * kwargs ) : data = iter ( data ) cached_rows , headers = [ ] , [ ] for index , row in enumerate ( data , start = 1 ) : cached_rows . append ( row ) for key in row . keys ( ) : if key not in headers : headers . append ( key ) if samples and index == samples : break data_rows = ( [ row . get ( header , None ) for header in headers ] for row in chain ( cached_rows , data ) ) kwargs [ "samples" ] = samples meta = { "imported_from" : "dicts" } return create_table ( chain ( [ headers ] , data_rows ) , meta = meta , * args , * * kwargs ) | Import data from a iterable of dicts | 179 | 9 |
227,129 | def export_to_dicts ( table , * args , * * kwargs ) : field_names = table . field_names return [ { key : getattr ( row , key ) for key in field_names } for row in table ] | Export a rows . Table to a list of dicts | 53 | 11 |
227,130 | def cell_value ( sheet , row , col ) : cell = sheet . cell ( row , col ) field_type = CELL_TYPES [ cell . ctype ] # TODO: this approach will not work if using locale value = cell . value if field_type is None : return None elif field_type is fields . TextField : if cell . ctype != xlrd . XL_CELL_BLANK : return value else : return "" elif field_type is fields . DatetimeField : if value == 0.0 : return None try : time_tuple = xlrd . xldate_as_tuple ( value , sheet . book . datemode ) except xlrd . xldate . XLDateTooLarge : return None value = field_type . serialize ( datetime . datetime ( * time_tuple ) ) return value . split ( "T00:00:00" ) [ 0 ] elif field_type is fields . BoolField : if value == 0 : return False elif value == 1 : return True elif cell . xf_index is None : return value # TODO: test else : book = sheet . book xf = book . xf_list [ cell . xf_index ] fmt = book . format_map [ xf . format_key ] if fmt . format_str . endswith ( "%" ) : # TODO: we may optimize this approach: we're converting to string # and the library is detecting the type when we could just say to # the library this value is PercentField if value is not None : try : decimal_places = len ( fmt . format_str [ : - 1 ] . split ( "." ) [ - 1 ] ) except IndexError : decimal_places = 2 return "{}%" . format ( str ( round ( value * 100 , decimal_places ) ) ) else : return None elif type ( value ) == float and int ( value ) == value : return int ( value ) else : return value | Return the cell value of the table passed by argument based in row and column . | 435 | 16 |
227,131 | def import_from_xls ( filename_or_fobj , sheet_name = None , sheet_index = 0 , start_row = None , start_column = None , end_row = None , end_column = None , * args , * * kwargs ) : source = Source . from_file ( filename_or_fobj , mode = "rb" , plugin_name = "xls" ) source . fobj . close ( ) book = xlrd . open_workbook ( source . uri , formatting_info = True , logfile = open ( os . devnull , mode = "w" ) ) if sheet_name is not None : sheet = book . sheet_by_name ( sheet_name ) else : sheet = book . sheet_by_index ( sheet_index ) # TODO: may re-use Excel data types # Get header and rows # xlrd library reads rows and columns starting from 0 and ending on # sheet.nrows/ncols - 1. rows accepts the same pattern # The xlrd library reads rows and columns starting from 0 and ending on # sheet.nrows/ncols - 1. rows also uses 0-based indexes, so no # transformation is needed min_row , min_column = get_table_start ( sheet ) max_row , max_column = sheet . nrows - 1 , sheet . ncols - 1 # TODO: consider adding a parameter `ignore_padding=True` and when it's # True, consider `start_row` starting from `min_row` and `start_column` # starting from `min_col`. start_row = max ( start_row if start_row is not None else min_row , min_row ) end_row = min ( end_row if end_row is not None else max_row , max_row ) start_column = max ( start_column if start_column is not None else min_column , min_column ) end_column = min ( end_column if end_column is not None else max_column , max_column ) table_rows = [ [ cell_value ( sheet , row_index , column_index ) for column_index in range ( start_column , end_column + 1 ) ] for row_index in range ( start_row , end_row + 1 ) ] meta = { "imported_from" : "xls" , "source" : source , "name" : sheet . name } return create_table ( table_rows , meta = meta , * args , * * kwargs ) | Return a rows . Table created from imported XLS file . | 560 | 12 |
227,132 | def export_to_xls ( table , filename_or_fobj = None , sheet_name = "Sheet1" , * args , * * kwargs ) : workbook = xlwt . Workbook ( ) sheet = workbook . add_sheet ( sheet_name ) prepared_table = prepare_to_export ( table , * args , * * kwargs ) field_names = next ( prepared_table ) for column_index , field_name in enumerate ( field_names ) : sheet . write ( 0 , column_index , field_name ) _convert_row = _python_to_xls ( [ table . fields . get ( field ) for field in field_names ] ) for row_index , row in enumerate ( prepared_table , start = 1 ) : for column_index , ( value , data ) in enumerate ( _convert_row ( row ) ) : sheet . write ( row_index , column_index , value , * * data ) return_result = False if filename_or_fobj is None : filename_or_fobj = BytesIO ( ) return_result = True source = Source . from_file ( filename_or_fobj , mode = "wb" , plugin_name = "xls" ) workbook . save ( source . fobj ) source . fobj . flush ( ) if return_result : source . fobj . seek ( 0 ) result = source . fobj . read ( ) else : result = source . fobj if source . should_close : source . fobj . close ( ) return result | Export the rows . Table to XLS file and return the saved file . | 346 | 15 |
227,133 | def _valid_table_name ( name ) : if name [ 0 ] not in "_" + string . ascii_letters or not set ( name ) . issubset ( "_" + string . ascii_letters + string . digits ) : return False else : return True | Verify if a given table name is valid for rows | 61 | 11 |
227,134 | def _parse_col_positions ( frame_style , header_line ) : separator = re . escape ( FRAMES [ frame_style . lower ( ) ] [ "VERTICAL" ] ) if frame_style == "None" : separator = r"[\s]{2}[^\s]" # Matches two whitespaces followed by a non-whitespace. # Our column headers are serated by 3 spaces by default. col_positions = [ ] # Abuse regexp engine to anotate vertical-separator positions: re . sub ( separator , lambda group : col_positions . append ( group . start ( ) ) , header_line ) if frame_style == "None" : col_positions . append ( len ( header_line ) - 1 ) return col_positions | Find the position for each column separator in the given line | 176 | 12 |
227,135 | def import_from_txt ( filename_or_fobj , encoding = "utf-8" , frame_style = FRAME_SENTINEL , * args , * * kwargs ) : # TODO: (maybe) # enable parsing of non-fixed-width-columns # with old algorithm - that would just split columns # at the vertical separator character for the frame. # (if doing so, include an optional parameter) # Also, this fixes an outstanding unreported issue: # trying to parse tables which fields values # included a Pipe char - "|" - would silently # yield bad results. source = Source . from_file ( filename_or_fobj , mode = "rb" , plugin_name = "txt" , encoding = encoding ) raw_contents = source . fobj . read ( ) . decode ( encoding ) . rstrip ( "\n" ) if frame_style is FRAME_SENTINEL : frame_style = _guess_frame_style ( raw_contents ) else : frame_style = _parse_frame_style ( frame_style ) contents = raw_contents . splitlines ( ) del raw_contents if frame_style != "None" : contents = contents [ 1 : - 1 ] del contents [ 1 ] else : # the table is possibly generated from other source. # check if the line we reserve as a separator is realy empty. if not contents [ 1 ] . strip ( ) : del contents [ 1 ] col_positions = _parse_col_positions ( frame_style , contents [ 0 ] ) table_rows = [ [ row [ start + 1 : end ] . strip ( ) for start , end in zip ( col_positions , col_positions [ 1 : ] ) ] for row in contents ] meta = { "imported_from" : "txt" , "source" : source , "frame_style" : frame_style , } return create_table ( table_rows , meta = meta , * args , * * kwargs ) | Return a rows . Table created from imported TXT file . | 440 | 12 |
227,136 | def export_to_txt ( table , filename_or_fobj = None , encoding = None , frame_style = "ASCII" , safe_none_frame = True , * args , * * kwargs ) : # TODO: will work only if table.fields is OrderedDict frame_style = _parse_frame_style ( frame_style ) frame = FRAMES [ frame_style . lower ( ) ] serialized_table = serialize ( table , * args , * * kwargs ) field_names = next ( serialized_table ) table_rows = list ( serialized_table ) max_sizes = _max_column_sizes ( field_names , table_rows ) dashes = [ frame [ "HORIZONTAL" ] * ( max_sizes [ field ] + 2 ) for field in field_names ] if frame_style != "None" or not safe_none_frame : header = [ field . center ( max_sizes [ field ] ) for field in field_names ] else : header = [ field . replace ( " " , "_" ) . ljust ( max_sizes [ field ] ) for field in field_names ] header = "{0} {1} {0}" . format ( frame [ "VERTICAL" ] , " {} " . format ( frame [ "VERTICAL" ] ) . join ( header ) ) top_split_line = ( frame [ "DOWN AND RIGHT" ] + frame [ "DOWN AND HORIZONTAL" ] . join ( dashes ) + frame [ "DOWN AND LEFT" ] ) body_split_line = ( frame [ "VERTICAL AND RIGHT" ] + frame [ "VERTICAL AND HORIZONTAL" ] . join ( dashes ) + frame [ "VERTICAL AND LEFT" ] ) botton_split_line = ( frame [ "UP AND RIGHT" ] + frame [ "UP AND HORIZONTAL" ] . join ( dashes ) + frame [ "UP AND LEFT" ] ) result = [ ] if frame_style != "None" : result += [ top_split_line ] result += [ header , body_split_line ] for row in table_rows : values = [ value . rjust ( max_sizes [ field_name ] ) for field_name , value in zip ( field_names , row ) ] row_data = " {} " . format ( frame [ "VERTICAL" ] ) . join ( values ) result . append ( "{0} {1} {0}" . format ( frame [ "VERTICAL" ] , row_data ) ) if frame_style != "None" : result . append ( botton_split_line ) result . append ( "" ) data = "\n" . join ( result ) if encoding is not None : data = data . encode ( encoding ) return export_data ( filename_or_fobj , data , mode = "wb" ) | Export a rows . Table to text . | 634 | 8 |
227,137 | def import_from_sqlite ( filename_or_connection , table_name = "table1" , query = None , query_args = None , * args , * * kwargs ) : source = get_source ( filename_or_connection ) connection = source . fobj cursor = connection . cursor ( ) if query is None : if not _valid_table_name ( table_name ) : raise ValueError ( "Invalid table name: {}" . format ( table_name ) ) query = SQL_SELECT_ALL . format ( table_name = table_name ) if query_args is None : query_args = tuple ( ) table_rows = list ( cursor . execute ( query , query_args ) ) # TODO: may be lazy header = [ six . text_type ( info [ 0 ] ) for info in cursor . description ] cursor . close ( ) # TODO: should close connection also? meta = { "imported_from" : "sqlite" , "source" : source } return create_table ( [ header ] + table_rows , meta = meta , * args , * * kwargs ) | Return a rows . Table with data from SQLite database . | 244 | 12 |
227,138 | def _cell_to_python ( cell ) : data_type , value = cell . data_type , cell . value if type ( cell ) is EmptyCell : return None elif data_type == "f" and value == "=TRUE()" : return True elif data_type == "f" and value == "=FALSE()" : return False elif cell . number_format . lower ( ) == "yyyy-mm-dd" : return str ( value ) . split ( " 00:00:00" ) [ 0 ] elif cell . number_format . lower ( ) == "yyyy-mm-dd hh:mm:ss" : return str ( value ) . split ( "." ) [ 0 ] elif cell . number_format . endswith ( "%" ) and isinstance ( value , Number ) : value = Decimal ( str ( value ) ) return "{:%}" . format ( value ) elif value is None : return "" else : return value | Convert a PyOpenXL s Cell object to the corresponding Python object . | 216 | 15 |
227,139 | def import_from_xlsx ( filename_or_fobj , sheet_name = None , sheet_index = 0 , start_row = None , start_column = None , end_row = None , end_column = None , workbook_kwargs = None , * args , * * kwargs ) : workbook_kwargs = workbook_kwargs or { } if "read_only" not in workbook_kwargs : workbook_kwargs [ "read_only" ] = True workbook = load_workbook ( filename_or_fobj , * * workbook_kwargs ) if sheet_name is None : sheet_name = workbook . sheetnames [ sheet_index ] sheet = workbook [ sheet_name ] # The openpyxl library reads rows and columns starting from 1 and ending on # sheet.max_row/max_col. rows uses 0-based indexes (from 0 to N - 1), so we # need to adjust the ranges accordingly. min_row , min_column = sheet . min_row - 1 , sheet . min_column - 1 max_row , max_column = sheet . max_row - 1 , sheet . max_column - 1 # TODO: consider adding a parameter `ignore_padding=True` and when it's # True, consider `start_row` starting from `sheet.min_row` and # `start_column` starting from `sheet.min_col`. start_row = start_row if start_row is not None else min_row end_row = end_row if end_row is not None else max_row start_column = start_column if start_column is not None else min_column end_column = end_column if end_column is not None else max_column table_rows = [ ] is_empty = lambda row : all ( cell is None for cell in row ) selected_rows = sheet . iter_rows ( min_row = start_row + 1 , max_row = end_row + 1 , min_col = start_column + 1 , max_col = end_column + 1 , ) for row in selected_rows : row = [ _cell_to_python ( cell ) for cell in row ] if not is_empty ( row ) : table_rows . append ( row ) source = Source . from_file ( filename_or_fobj , plugin_name = "xlsx" ) source . fobj . close ( ) # TODO: pass a parameter to Source.from_file so it won't open the file metadata = { "imported_from" : "xlsx" , "source" : source , "name" : sheet_name } return create_table ( table_rows , meta = metadata , * args , * * kwargs ) | Return a rows . Table created from imported XLSX file . | 608 | 13 |
227,140 | def export_to_xlsx ( table , filename_or_fobj = None , sheet_name = "Sheet1" , * args , * * kwargs ) : workbook = Workbook ( ) sheet = workbook . active sheet . title = sheet_name prepared_table = prepare_to_export ( table , * args , * * kwargs ) # Write header field_names = next ( prepared_table ) for col_index , field_name in enumerate ( field_names ) : cell = sheet . cell ( row = 1 , column = col_index + 1 ) cell . value = field_name # Write sheet rows _convert_row = _python_to_cell ( list ( map ( table . fields . get , field_names ) ) ) for row_index , row in enumerate ( prepared_table , start = 1 ) : for col_index , ( value , number_format ) in enumerate ( _convert_row ( row ) ) : cell = sheet . cell ( row = row_index + 1 , column = col_index + 1 ) cell . value = value if number_format is not None : cell . number_format = number_format return_result = False if filename_or_fobj is None : filename_or_fobj = BytesIO ( ) return_result = True source = Source . from_file ( filename_or_fobj , mode = "wb" , plugin_name = "xlsx" ) workbook . save ( source . fobj ) source . fobj . flush ( ) if return_result : source . fobj . seek ( 0 ) result = source . fobj . read ( ) else : result = source . fobj if source . should_close : source . fobj . close ( ) return result | Export the rows . Table to XLSX file and return the saved file . | 388 | 16 |
227,141 | def download_organizations ( ) : response = requests . get ( URL ) data = response . json ( ) organizations = [ organization [ "properties" ] for organization in data [ "features" ] ] return rows . import_from_dicts ( organizations ) | Download organizations JSON and extract its properties | 54 | 7 |
227,142 | def import_from_html ( filename_or_fobj , encoding = "utf-8" , index = 0 , ignore_colspan = True , preserve_html = False , properties = False , table_tag = "table" , row_tag = "tr" , column_tag = "td|th" , * args , * * kwargs ) : source = Source . from_file ( filename_or_fobj , plugin_name = "html" , mode = "rb" , encoding = encoding ) html = source . fobj . read ( ) . decode ( source . encoding ) html_tree = document_fromstring ( html ) tables = html_tree . xpath ( "//{}" . format ( table_tag ) ) table = tables [ index ] # TODO: set meta's "name" from @id or @name (if available) strip_tags ( table , "thead" ) strip_tags ( table , "tbody" ) row_elements = table . xpath ( row_tag ) table_rows = [ _get_row ( row , column_tag = column_tag , preserve_html = preserve_html , properties = properties , ) for row in row_elements ] if properties : table_rows [ 0 ] [ - 1 ] = "properties" if preserve_html and kwargs . get ( "fields" , None ) is None : # The field names will be the first table row, so we need to strip HTML # from it even if `preserve_html` is `True` (it's `True` only for rows, # not for the header). table_rows [ 0 ] = list ( map ( _extract_node_text , row_elements [ 0 ] ) ) if ignore_colspan : max_columns = max ( map ( len , table_rows ) ) table_rows = [ row for row in table_rows if len ( row ) == max_columns ] meta = { "imported_from" : "html" , "source" : source } return create_table ( table_rows , meta = meta , * args , * * kwargs ) | Return rows . Table from HTML file . | 464 | 8 |
227,143 | def export_to_html ( table , filename_or_fobj = None , encoding = "utf-8" , caption = False , * args , * * kwargs ) : serialized_table = serialize ( table , * args , * * kwargs ) fields = next ( serialized_table ) result = [ "<table>\n\n" ] if caption and table . name : result . extend ( [ " <caption>" , table . name , "</caption>\n\n" ] ) result . extend ( [ " <thead>\n" , " <tr>\n" ] ) # TODO: set @name/@id if self.meta["name"] is set header = [ " <th> {} </th>\n" . format ( field ) for field in fields ] result . extend ( header ) result . extend ( [ " </tr>\n" , " </thead>\n" , "\n" , " <tbody>\n" , "\n" ] ) for index , row in enumerate ( serialized_table , start = 1 ) : css_class = "odd" if index % 2 == 1 else "even" result . append ( ' <tr class="{}">\n' . format ( css_class ) ) for value in row : result . extend ( [ " <td> " , escape ( value ) , " </td>\n" ] ) result . append ( " </tr>\n\n" ) result . append ( " </tbody>\n\n</table>\n" ) html = "" . join ( result ) . encode ( encoding ) return export_data ( filename_or_fobj , html , mode = "wb" ) | Export and return rows . Table data to HTML file . | 383 | 11 |
227,144 | def _extract_node_text ( node ) : texts = map ( six . text_type . strip , map ( six . text_type , map ( unescape , node . xpath ( ".//text()" ) ) ) ) return " " . join ( text for text in texts if text ) | Extract text from a given lxml node . | 65 | 10 |
227,145 | def count_tables ( filename_or_fobj , encoding = "utf-8" , table_tag = "table" ) : source = Source . from_file ( filename_or_fobj , plugin_name = "html" , mode = "rb" , encoding = encoding ) html = source . fobj . read ( ) . decode ( source . encoding ) html_tree = document_fromstring ( html ) tables = html_tree . xpath ( "//{}" . format ( table_tag ) ) result = len ( tables ) if source . should_close : source . fobj . close ( ) return result | Read a file passed by arg and return your table HTML tag count . | 135 | 14 |
227,146 | def tag_to_dict ( html ) : element = document_fromstring ( html ) . xpath ( "//html/body/child::*" ) [ 0 ] attributes = dict ( element . attrib ) attributes [ "text" ] = element . text_content ( ) return attributes | Extract tag s attributes into a dict . | 62 | 9 |
227,147 | def create_table ( data , meta = None , fields = None , skip_header = True , import_fields = None , samples = None , force_types = None , max_rows = None , * args , * * kwargs ) : table_rows = iter ( data ) force_types = force_types or { } if import_fields is not None : import_fields = make_header ( import_fields ) # TODO: test max_rows if fields is None : # autodetect field types # TODO: may add `type_hints` parameter so autodetection can be easier # (plugins may specify some possible field types). header = make_header ( next ( table_rows ) ) if samples is not None : sample_rows = list ( islice ( table_rows , 0 , samples ) ) table_rows = chain ( sample_rows , table_rows ) else : if max_rows is not None and max_rows > 0 : sample_rows = table_rows = list ( islice ( table_rows , max_rows ) ) else : sample_rows = table_rows = list ( table_rows ) # Detect field types using only the desired columns detected_fields = detect_types ( header , sample_rows , skip_indexes = [ index for index , field in enumerate ( header ) if field in force_types or field not in ( import_fields or header ) ] , * args , * * kwargs ) # Check if any field was added during detecting process new_fields = [ field_name for field_name in detected_fields . keys ( ) if field_name not in header ] # Finally create the `fields` with both header and new field names, # based on detected fields `and force_types` fields = OrderedDict ( [ ( field_name , detected_fields . get ( field_name , TextField ) ) for field_name in header + new_fields ] ) fields . update ( force_types ) # Update `header` and `import_fields` based on new `fields` header = list ( fields . keys ( ) ) if import_fields is None : import_fields = header else : # using provided field types if not isinstance ( fields , OrderedDict ) : raise ValueError ( "`fields` must be an `OrderedDict`" ) if skip_header : # If we're skipping the header probably this row is not trustable # (can be data or garbage). next ( table_rows ) header = make_header ( list ( fields . keys ( ) ) ) if import_fields is None : import_fields = header fields = OrderedDict ( [ ( field_name , fields [ key ] ) for field_name , key in zip ( header , fields ) ] ) diff = set ( import_fields ) - set ( header ) if diff : field_names = ", " . join ( '"{}"' . format ( field ) for field in diff ) raise ValueError ( "Invalid field names: {}" . format ( field_names ) ) fields = OrderedDict ( [ ( field_name , fields [ field_name ] ) for field_name in import_fields ] ) get_row = get_items ( * map ( header . index , import_fields ) ) table = Table ( fields = fields , meta = meta ) if max_rows is not None and max_rows > 0 : table_rows = islice ( table_rows , max_rows ) table . extend ( dict ( zip ( import_fields , get_row ( row ) ) ) for row in table_rows ) source = table . meta . get ( "source" , None ) if source is not None : if source . should_close : source . fobj . close ( ) if source . should_delete and Path ( source . uri ) . exists ( ) : unlink ( source . uri ) return table | Create a rows . Table object based on data rows and some configurations | 841 | 13 |
227,148 | def export_data ( filename_or_fobj , data , mode = "w" ) : if filename_or_fobj is None : return data _ , fobj = get_filename_and_fobj ( filename_or_fobj , mode = mode ) source = Source . from_file ( filename_or_fobj , mode = mode , plugin_name = None ) source . fobj . write ( data ) source . fobj . flush ( ) return source . fobj | Return the object ready to be exported or only data if filename_or_fobj is not passed . | 105 | 21 |
227,149 | def read_sample ( fobj , sample ) : cursor = fobj . tell ( ) data = fobj . read ( sample ) fobj . seek ( cursor ) return data | Read sample bytes from fobj and return the cursor to where it was . | 37 | 15 |
227,150 | def export_to_csv ( table , filename_or_fobj = None , encoding = "utf-8" , dialect = unicodecsv . excel , batch_size = 100 , callback = None , * args , * * kwargs ) : # TODO: will work only if table.fields is OrderedDict # TODO: should use fobj? What about creating a method like json.dumps? return_data , should_close = False , None if filename_or_fobj is None : filename_or_fobj = BytesIO ( ) return_data = should_close = True source = Source . from_file ( filename_or_fobj , plugin_name = "csv" , mode = "wb" , encoding = encoding , should_close = should_close , ) # TODO: may use `io.BufferedWriter` instead of `ipartition` so user can # choose the real size (in Bytes) when to flush to the file system, instead # number of rows writer = unicodecsv . writer ( source . fobj , encoding = encoding , dialect = dialect ) if callback is None : for batch in ipartition ( serialize ( table , * args , * * kwargs ) , batch_size ) : writer . writerows ( batch ) else : serialized = serialize ( table , * args , * * kwargs ) writer . writerow ( next ( serialized ) ) # First, write the header total = 0 for batch in ipartition ( serialized , batch_size ) : writer . writerows ( batch ) total += len ( batch ) callback ( total ) if return_data : source . fobj . seek ( 0 ) result = source . fobj . read ( ) else : source . fobj . flush ( ) result = source . fobj if source . should_close : source . fobj . close ( ) return result | Export a rows . Table to a CSV file . | 410 | 10 |
227,151 | def join ( keys , tables ) : # Make new (merged) Table fields fields = OrderedDict ( ) for table in tables : fields . update ( table . fields ) # TODO: may raise an error if a same field is different in some tables # Check if all keys are inside merged Table's fields fields_keys = set ( fields . keys ( ) ) for key in keys : if key not in fields_keys : raise ValueError ( 'Invalid key: "{}"' . format ( key ) ) # Group rows by key, without missing ordering none_fields = lambda : OrderedDict ( { field : None for field in fields . keys ( ) } ) data = OrderedDict ( ) for table in tables : for row in table : row_key = tuple ( [ getattr ( row , key ) for key in keys ] ) if row_key not in data : data [ row_key ] = none_fields ( ) data [ row_key ] . update ( row . _asdict ( ) ) merged = Table ( fields = fields ) merged . extend ( data . values ( ) ) return merged | Merge a list of Table objects using keys to group rows | 237 | 12 |
227,152 | def transform ( fields , function , * tables ) : new_table = Table ( fields = fields ) for table in tables : for row in filter ( bool , map ( lambda row : function ( row , table ) , table ) ) : new_table . append ( row ) return new_table | Return a new table based on other tables and a transformation function | 61 | 12 |
227,153 | def make_pvc ( name , storage_class , access_modes , storage , labels = None , annotations = None , ) : pvc = V1PersistentVolumeClaim ( ) pvc . kind = "PersistentVolumeClaim" pvc . api_version = "v1" pvc . metadata = V1ObjectMeta ( ) pvc . metadata . name = name pvc . metadata . annotations = ( annotations or { } ) . copy ( ) pvc . metadata . labels = ( labels or { } ) . copy ( ) pvc . spec = V1PersistentVolumeClaimSpec ( ) pvc . spec . access_modes = access_modes pvc . spec . resources = V1ResourceRequirements ( ) pvc . spec . resources . requests = { "storage" : storage } if storage_class : pvc . metadata . annotations . update ( { "volume.beta.kubernetes.io/storage-class" : storage_class } ) pvc . spec . storage_class_name = storage_class return pvc | Make a k8s pvc specification for running a user notebook . | 226 | 14 |
227,154 | def make_ingress ( name , routespec , target , data ) : # move beta imports here, # which are more sensitive to kubernetes version # and will change when they move out of beta from kubernetes . client . models import ( V1beta1Ingress , V1beta1IngressSpec , V1beta1IngressRule , V1beta1HTTPIngressRuleValue , V1beta1HTTPIngressPath , V1beta1IngressBackend , ) meta = V1ObjectMeta ( name = name , annotations = { 'hub.jupyter.org/proxy-data' : json . dumps ( data ) , 'hub.jupyter.org/proxy-routespec' : routespec , 'hub.jupyter.org/proxy-target' : target } , labels = { 'heritage' : 'jupyterhub' , 'component' : 'singleuser-server' , 'hub.jupyter.org/proxy-route' : 'true' } ) if routespec . startswith ( '/' ) : host = None path = routespec else : host , path = routespec . split ( '/' , 1 ) target_parts = urlparse ( target ) target_ip = target_parts . hostname target_port = target_parts . port target_is_ip = re . match ( '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' , target_ip ) is not None # Make endpoint object if target_is_ip : endpoint = V1Endpoints ( kind = 'Endpoints' , metadata = meta , subsets = [ V1EndpointSubset ( addresses = [ V1EndpointAddress ( ip = target_ip ) ] , ports = [ V1EndpointPort ( port = target_port ) ] ) ] ) else : endpoint = None # Make service object if target_is_ip : service = V1Service ( kind = 'Service' , metadata = meta , spec = V1ServiceSpec ( type = 'ClusterIP' , external_name = '' , ports = [ V1ServicePort ( port = target_port , target_port = target_port ) ] ) ) else : service = V1Service ( kind = 'Service' , metadata = meta , spec = V1ServiceSpec ( type = 'ExternalName' , external_name = target_ip , cluster_ip = '' , ports = [ V1ServicePort ( port = target_port , target_port = target_port ) ] , ) , ) # Make Ingress object ingress = V1beta1Ingress ( kind = 'Ingress' , metadata = meta , spec = V1beta1IngressSpec ( rules = [ V1beta1IngressRule ( host = host , http = V1beta1HTTPIngressRuleValue ( paths = [ V1beta1HTTPIngressPath ( path = path , backend = V1beta1IngressBackend ( service_name = name , service_port = target_port ) ) ] ) ) ] ) ) return endpoint , service , ingress | Returns an ingress service endpoint object that ll work for this service | 689 | 13 |
227,155 | def shared_client ( ClientType , * args , * * kwargs ) : kwarg_key = tuple ( ( key , kwargs [ key ] ) for key in sorted ( kwargs ) ) cache_key = ( ClientType , args , kwarg_key ) client = None if cache_key in _client_cache : # resolve cached weakref # client can still be None after this! client = _client_cache [ cache_key ] ( ) if client is None : Client = getattr ( kubernetes . client , ClientType ) client = Client ( * args , * * kwargs ) # cache weakref so that clients can be garbage collected _client_cache [ cache_key ] = weakref . ref ( client ) return client | Return a single shared kubernetes client instance | 165 | 10 |
227,156 | def generate_hashed_slug ( slug , limit = 63 , hash_length = 6 ) : if len ( slug ) < ( limit - hash_length ) : return slug slug_hash = hashlib . sha256 ( slug . encode ( 'utf-8' ) ) . hexdigest ( ) return '{prefix}-{hash}' . format ( prefix = slug [ : limit - hash_length - 1 ] , hash = slug_hash [ : hash_length ] , ) . lower ( ) | Generate a unique name that s within a certain length limit | 110 | 12 |
227,157 | def get_k8s_model ( model_type , model_dict ) : model_dict = copy . deepcopy ( model_dict ) if isinstance ( model_dict , model_type ) : return model_dict elif isinstance ( model_dict , dict ) : # convert the dictionaries camelCase keys to snake_case keys model_dict = _map_dict_keys_to_model_attributes ( model_type , model_dict ) # use the dictionary keys to initialize a model of given type return model_type ( * * model_dict ) else : raise AttributeError ( "Expected object of type 'dict' (or '{}') but got '{}'." . format ( model_type . __name__ , type ( model_dict ) . __name__ ) ) | Returns an instance of type specified model_type from an model instance or represantative dictionary . | 173 | 20 |
227,158 | def _get_k8s_model_dict ( model_type , model ) : model = copy . deepcopy ( model ) if isinstance ( model , model_type ) : return model . to_dict ( ) elif isinstance ( model , dict ) : return _map_dict_keys_to_model_attributes ( model_type , model ) else : raise AttributeError ( "Expected object of type '{}' (or 'dict') but got '{}'." . format ( model_type . __name__ , type ( model ) . __name__ ) ) | Returns a dictionary representation of a provided model type | 127 | 9 |
227,159 | def _list_and_update ( self ) : initial_resources = getattr ( self . api , self . list_method_name ) ( self . namespace , label_selector = self . label_selector , field_selector = self . field_selector , _request_timeout = self . request_timeout , ) # This is an atomic operation on the dictionary! self . resources = { p . metadata . name : p for p in initial_resources . items } # return the resource version so we can hook up a watch return initial_resources . metadata . resource_version | Update current list of resources by doing a full fetch . | 124 | 11 |
227,160 | def _watch_and_update ( self ) : selectors = [ ] log_name = "" if self . label_selector : selectors . append ( "label selector=%r" % self . label_selector ) if self . field_selector : selectors . append ( "field selector=%r" % self . field_selector ) log_selector = ', ' . join ( selectors ) cur_delay = 0.1 self . log . info ( "watching for %s with %s in namespace %s" , self . kind , log_selector , self . namespace , ) while True : self . log . debug ( "Connecting %s watcher" , self . kind ) start = time . monotonic ( ) w = watch . Watch ( ) try : resource_version = self . _list_and_update ( ) if not self . first_load_future . done ( ) : # signal that we've loaded our initial data self . first_load_future . set_result ( None ) watch_args = { 'namespace' : self . namespace , 'label_selector' : self . label_selector , 'field_selector' : self . field_selector , 'resource_version' : resource_version , } if self . request_timeout : # set network receive timeout watch_args [ '_request_timeout' ] = self . request_timeout if self . timeout_seconds : # set watch timeout watch_args [ 'timeout_seconds' ] = self . timeout_seconds # in case of timeout_seconds, the w.stream just exits (no exception thrown) # -> we stop the watcher and start a new one for ev in w . stream ( getattr ( self . api , self . list_method_name ) , * * watch_args ) : cur_delay = 0.1 resource = ev [ 'object' ] if ev [ 'type' ] == 'DELETED' : # This is an atomic delete operation on the dictionary! self . resources . pop ( resource . metadata . name , None ) else : # This is an atomic operation on the dictionary! self . resources [ resource . metadata . name ] = resource if self . _stop_event . is_set ( ) : self . log . info ( "%s watcher stopped" , self . kind ) break watch_duration = time . monotonic ( ) - start if watch_duration >= self . restart_seconds : self . log . debug ( "Restarting %s watcher after %i seconds" , self . kind , watch_duration , ) break except ReadTimeoutError : # network read time out, just continue and restart the watch # this could be due to a network problem or just low activity self . log . warning ( "Read timeout watching %s, reconnecting" , self . kind ) continue except Exception : cur_delay = cur_delay * 2 if cur_delay > 30 : self . log . exception ( "Watching resources never recovered, giving up" ) if self . on_failure : self . on_failure ( ) return self . log . exception ( "Error when watching resources, retrying in %ss" , cur_delay ) time . sleep ( cur_delay ) continue else : # no events on watch, reconnect self . log . debug ( "%s watcher timeout" , self . kind ) finally : w . stop ( ) if self . _stop_event . is_set ( ) : self . log . info ( "%s watcher stopped" , self . kind ) break self . log . warning ( "%s watcher finished" , self . kind ) | Keeps the current list of resources up - to - date | 775 | 12 |
227,161 | def start ( self ) : if hasattr ( self , 'watch_thread' ) : raise ValueError ( 'Thread watching for resources is already running' ) self . _list_and_update ( ) self . watch_thread = threading . Thread ( target = self . _watch_and_update ) # If the watch_thread is only thread left alive, exit app self . watch_thread . daemon = True self . watch_thread . start ( ) | Start the reflection process! | 97 | 5 |
227,162 | def get_pod_manifest ( self ) : if callable ( self . uid ) : uid = yield gen . maybe_future ( self . uid ( self ) ) else : uid = self . uid if callable ( self . gid ) : gid = yield gen . maybe_future ( self . gid ( self ) ) else : gid = self . gid if callable ( self . fs_gid ) : fs_gid = yield gen . maybe_future ( self . fs_gid ( self ) ) else : fs_gid = self . fs_gid if callable ( self . supplemental_gids ) : supplemental_gids = yield gen . maybe_future ( self . supplemental_gids ( self ) ) else : supplemental_gids = self . supplemental_gids if self . cmd : real_cmd = self . cmd + self . get_args ( ) else : real_cmd = None labels = self . _build_pod_labels ( self . _expand_all ( self . extra_labels ) ) annotations = self . _build_common_annotations ( self . _expand_all ( self . extra_annotations ) ) return make_pod ( name = self . pod_name , cmd = real_cmd , port = self . port , image = self . image , image_pull_policy = self . image_pull_policy , image_pull_secret = self . image_pull_secrets , node_selector = self . node_selector , run_as_uid = uid , run_as_gid = gid , fs_gid = fs_gid , supplemental_gids = supplemental_gids , run_privileged = self . privileged , env = self . get_env ( ) , volumes = self . _expand_all ( self . volumes ) , volume_mounts = self . _expand_all ( self . volume_mounts ) , working_dir = self . working_dir , labels = labels , annotations = annotations , cpu_limit = self . cpu_limit , cpu_guarantee = self . cpu_guarantee , mem_limit = self . mem_limit , mem_guarantee = self . mem_guarantee , extra_resource_limits = self . extra_resource_limits , extra_resource_guarantees = self . extra_resource_guarantees , lifecycle_hooks = self . lifecycle_hooks , init_containers = self . _expand_all ( self . init_containers ) , service_account = self . service_account , extra_container_config = self . extra_container_config , extra_pod_config = self . extra_pod_config , extra_containers = self . _expand_all ( self . extra_containers ) , scheduler_name = self . scheduler_name , tolerations = self . tolerations , node_affinity_preferred = self . node_affinity_preferred , node_affinity_required = self . node_affinity_required , pod_affinity_preferred = self . pod_affinity_preferred , pod_affinity_required = self . pod_affinity_required , pod_anti_affinity_preferred = self . pod_anti_affinity_preferred , pod_anti_affinity_required = self . pod_anti_affinity_required , priority_class_name = self . priority_class_name , logger = self . log , ) | Make a pod manifest that will spawn current user s notebook pod . | 771 | 13 |
227,163 | def get_pvc_manifest ( self ) : labels = self . _build_common_labels ( self . _expand_all ( self . storage_extra_labels ) ) labels . update ( { 'component' : 'singleuser-storage' } ) annotations = self . _build_common_annotations ( { } ) return make_pvc ( name = self . pvc_name , storage_class = self . storage_class , access_modes = self . storage_access_modes , storage = self . storage_capacity , labels = labels , annotations = annotations ) | Make a pvc manifest that will spawn current user s pvc . | 129 | 14 |
227,164 | def is_pod_running ( self , pod ) : # FIXME: Validate if this is really the best way is_running = ( pod is not None and pod . status . phase == 'Running' and pod . status . pod_ip is not None and pod . metadata . deletion_timestamp is None and all ( [ cs . ready for cs in pod . status . container_statuses ] ) ) return is_running | Check if the given pod is running | 91 | 7 |
227,165 | def get_env ( self ) : env = super ( KubeSpawner , self ) . get_env ( ) # deprecate image env [ 'JUPYTER_IMAGE_SPEC' ] = self . image env [ 'JUPYTER_IMAGE' ] = self . image return env | Return the environment dict to use for the Spawner . | 66 | 11 |
227,166 | def poll ( self ) : # have to wait for first load of data before we have a valid answer if not self . pod_reflector . first_load_future . done ( ) : yield self . pod_reflector . first_load_future data = self . pod_reflector . pods . get ( self . pod_name , None ) if data is not None : if data . status . phase == 'Pending' : return None ctr_stat = data . status . container_statuses if ctr_stat is None : # No status, no container (we hope) # This seems to happen when a pod is idle-culled. return 1 for c in ctr_stat : # return exit code if notebook container has terminated if c . name == 'notebook' : if c . state . terminated : # call self.stop to delete the pod if self . delete_stopped_pods : yield self . stop ( now = True ) return c . state . terminated . exit_code break # None means pod is running or starting up return None # pod doesn't exist or has been deleted return 1 | Check if the pod is still running . | 238 | 8 |
227,167 | def events ( self ) : if not self . event_reflector : return [ ] events = [ ] for event in self . event_reflector . events : if event . involved_object . name != self . pod_name : # only consider events for my pod name continue if self . _last_event and event . metadata . uid == self . _last_event : # saw last_event marker, ignore any previous events # and only consider future events # only include events *after* our _last_event marker events = [ ] else : events . append ( event ) return events | Filter event - reflector to just our events | 124 | 9 |
227,168 | def _start_reflector ( self , key , ReflectorClass , replace = False , * * kwargs ) : main_loop = IOLoop . current ( ) def on_reflector_failure ( ) : self . log . critical ( "%s reflector failed, halting Hub." , key . title ( ) , ) sys . exit ( 1 ) previous_reflector = self . __class__ . reflectors . get ( key ) if replace or not previous_reflector : self . __class__ . reflectors [ key ] = ReflectorClass ( parent = self , namespace = self . namespace , on_failure = on_reflector_failure , * * kwargs , ) if replace and previous_reflector : # we replaced the reflector, stop the old one previous_reflector . stop ( ) # return the current reflector return self . __class__ . reflectors [ key ] | Start a shared reflector on the KubeSpawner class | 195 | 12 |
227,169 | def _start_watching_events ( self , replace = False ) : return self . _start_reflector ( "events" , EventReflector , fields = { "involvedObject.kind" : "Pod" } , replace = replace , ) | Start the events reflector | 53 | 5 |
227,170 | def _options_form_default ( self ) : if not self . profile_list : return '' if callable ( self . profile_list ) : return self . _render_options_form_dynamically else : return self . _render_options_form ( self . profile_list ) | Build the form template according to the profile_list setting . | 63 | 12 |
227,171 | def options_from_form ( self , formdata ) : if not self . profile_list or self . _profile_list is None : return formdata # Default to first profile if somehow none is provided try : selected_profile = int ( formdata . get ( 'profile' , [ 0 ] ) [ 0 ] ) options = self . _profile_list [ selected_profile ] except ( TypeError , IndexError , ValueError ) : raise web . HTTPError ( 400 , "No such profile: %i" , formdata . get ( 'profile' , None ) ) return { 'profile' : options [ 'display_name' ] } | get the option selected by the user on the form | 137 | 10 |
227,172 | def _load_profile ( self , profile_name ) : # find the profile default_profile = self . _profile_list [ 0 ] for profile in self . _profile_list : if profile . get ( 'default' , False ) : # explicit default, not the first default_profile = profile if profile [ 'display_name' ] == profile_name : break else : if profile_name : # name specified, but not found raise ValueError ( "No such profile: %s. Options include: %s" % ( profile_name , ', ' . join ( p [ 'display_name' ] for p in self . _profile_list ) ) ) else : # no name specified, use the default profile = default_profile self . log . debug ( "Applying KubeSpawner override for profile '%s'" , profile [ 'display_name' ] ) kubespawner_override = profile . get ( 'kubespawner_override' , { } ) for k , v in kubespawner_override . items ( ) : if callable ( v ) : v = v ( self ) self . log . debug ( ".. overriding KubeSpawner value %s=%s (callable result)" , k , v ) else : self . log . debug ( ".. overriding KubeSpawner value %s=%s" , k , v ) setattr ( self , k , v ) | Load a profile by name | 310 | 5 |
227,173 | def load_user_options ( self ) : if self . _profile_list is None : if callable ( self . profile_list ) : self . _profile_list = yield gen . maybe_future ( self . profile_list ( self ) ) else : self . _profile_list = self . profile_list if self . _profile_list : yield self . _load_profile ( self . user_options . get ( 'profile' , None ) ) | Load user options from self . user_options dict | 99 | 10 |
227,174 | def list_motors ( name_pattern = Motor . SYSTEM_DEVICE_NAME_CONVENTION , * * kwargs ) : class_path = abspath ( Device . DEVICE_ROOT_PATH + '/' + Motor . SYSTEM_CLASS_NAME ) return ( Motor ( name_pattern = name , name_exact = True ) for name in list_device_names ( class_path , name_pattern , * * kwargs ) ) | This is a generator function that enumerates all tacho motors that match the provided arguments . | 99 | 18 |
227,175 | def to_native_units ( self , motor ) : assert abs ( self . rotations_per_second ) <= motor . max_rps , "invalid rotations-per-second: {} max RPS is {}, {} was requested" . format ( motor , motor . max_rps , self . rotations_per_second ) return self . rotations_per_second / motor . max_rps * motor . max_speed | Return the native speed measurement required to achieve desired rotations - per - second | 96 | 15 |
227,176 | def to_native_units ( self , motor ) : assert abs ( self . rotations_per_minute ) <= motor . max_rpm , "invalid rotations-per-minute: {} max RPM is {}, {} was requested" . format ( motor , motor . max_rpm , self . rotations_per_minute ) return self . rotations_per_minute / motor . max_rpm * motor . max_speed | Return the native speed measurement required to achieve desired rotations - per - minute | 92 | 15 |
227,177 | def to_native_units ( self , motor ) : assert abs ( self . degrees_per_second ) <= motor . max_dps , "invalid degrees-per-second: {} max DPS is {}, {} was requested" . format ( motor , motor . max_dps , self . degrees_per_second ) return self . degrees_per_second / motor . max_dps * motor . max_speed | Return the native speed measurement required to achieve desired degrees - per - second | 91 | 14 |
227,178 | def to_native_units ( self , motor ) : assert abs ( self . degrees_per_minute ) <= motor . max_dpm , "invalid degrees-per-minute: {} max DPM is {}, {} was requested" . format ( motor , motor . max_dpm , self . degrees_per_minute ) return self . degrees_per_minute / motor . max_dpm * motor . max_speed | Return the native speed measurement required to achieve desired degrees - per - minute | 92 | 14 |
227,179 | def address ( self ) : self . _address , value = self . get_attr_string ( self . _address , 'address' ) return value | Returns the name of the port that this motor is connected to . | 32 | 13 |
227,180 | def commands ( self ) : ( self . _commands , value ) = self . get_cached_attr_set ( self . _commands , 'commands' ) return value | Returns a list of commands that are supported by the motor controller . Possible values are run - forever run - to - abs - pos run - to - rel - pos run - timed run - direct stop and reset . Not all commands may be supported . | 40 | 50 |
227,181 | def driver_name ( self ) : ( self . _driver_name , value ) = self . get_cached_attr_string ( self . _driver_name , 'driver_name' ) return value | Returns the name of the driver that provides this tacho motor device . | 45 | 14 |
227,182 | def duty_cycle ( self ) : self . _duty_cycle , value = self . get_attr_int ( self . _duty_cycle , 'duty_cycle' ) return value | Returns the current duty cycle of the motor . Units are percent . Values are - 100 to 100 . | 40 | 20 |
227,183 | def duty_cycle_sp ( self ) : self . _duty_cycle_sp , value = self . get_attr_int ( self . _duty_cycle_sp , 'duty_cycle_sp' ) return value | Writing sets the duty cycle setpoint . Reading returns the current value . Units are in percent . Valid values are - 100 to 100 . A negative value causes the motor to rotate in reverse . | 48 | 38 |
227,184 | def polarity ( self ) : self . _polarity , value = self . get_attr_string ( self . _polarity , 'polarity' ) return value | Sets the polarity of the motor . With normal polarity a positive duty cycle will cause the motor to rotate clockwise . With inversed polarity a positive duty cycle will cause the motor to rotate counter - clockwise . Valid values are normal and inversed . | 39 | 56 |
227,185 | def position ( self ) : self . _position , value = self . get_attr_int ( self . _position , 'position' ) return value | Returns the current position of the motor in pulses of the rotary encoder . When the motor rotates clockwise the position will increase . Likewise rotating counter - clockwise causes the position to decrease . Writing will set the position to that value . | 32 | 49 |
227,186 | def position_p ( self ) : self . _position_p , value = self . get_attr_int ( self . _position_p , 'hold_pid/Kp' ) return value | The proportional constant for the position PID . | 43 | 8 |
227,187 | def position_i ( self ) : self . _position_i , value = self . get_attr_int ( self . _position_i , 'hold_pid/Ki' ) return value | The integral constant for the position PID . | 43 | 8 |
227,188 | def position_d ( self ) : self . _position_d , value = self . get_attr_int ( self . _position_d , 'hold_pid/Kd' ) return value | The derivative constant for the position PID . | 43 | 8 |
227,189 | def max_speed ( self ) : ( self . _max_speed , value ) = self . get_cached_attr_int ( self . _max_speed , 'max_speed' ) return value | Returns the maximum value that is accepted by the speed_sp attribute . This may be slightly different than the maximum speed that a particular motor can reach - it s the maximum theoretical speed . | 45 | 37 |
227,190 | def ramp_up_sp ( self ) : self . _ramp_up_sp , value = self . get_attr_int ( self . _ramp_up_sp , 'ramp_up_sp' ) return value | Writing sets the ramp up setpoint . Reading returns the current value . Units are in milliseconds and must be positive . When set to a non - zero value the motor speed will increase from 0 to 100% of max_speed over the span of this setpoint . The actual ramp time is the ratio of the difference between the speed_sp and the current speed and max_speed multiplied by ramp_up_sp . | 51 | 84 |
227,191 | def ramp_down_sp ( self ) : self . _ramp_down_sp , value = self . get_attr_int ( self . _ramp_down_sp , 'ramp_down_sp' ) return value | Writing sets the ramp down setpoint . Reading returns the current value . Units are in milliseconds and must be positive . When set to a non - zero value the motor speed will decrease from 0 to 100% of max_speed over the span of this setpoint . The actual ramp time is the ratio of the difference between the speed_sp and the current speed and max_speed multiplied by ramp_down_sp . | 51 | 84 |
227,192 | def speed_p ( self ) : self . _speed_p , value = self . get_attr_int ( self . _speed_p , 'speed_pid/Kp' ) return value | The proportional constant for the speed regulation PID . | 43 | 9 |
227,193 | def speed_i ( self ) : self . _speed_i , value = self . get_attr_int ( self . _speed_i , 'speed_pid/Ki' ) return value | The integral constant for the speed regulation PID . | 43 | 9 |
227,194 | def speed_d ( self ) : self . _speed_d , value = self . get_attr_int ( self . _speed_d , 'speed_pid/Kd' ) return value | The derivative constant for the speed regulation PID . | 43 | 9 |
227,195 | def state ( self ) : self . _state , value = self . get_attr_set ( self . _state , 'state' ) return value | Reading returns a list of state flags . Possible flags are running ramping holding overloaded and stalled . | 32 | 19 |
227,196 | def stop_action ( self ) : self . _stop_action , value = self . get_attr_string ( self . _stop_action , 'stop_action' ) return value | Reading returns the current stop action . Writing sets the stop action . The value determines the motors behavior when command is set to stop . Also it determines the motors behavior when a run command completes . See stop_actions for a list of possible values . | 40 | 49 |
227,197 | def stop_actions ( self ) : ( self . _stop_actions , value ) = self . get_cached_attr_set ( self . _stop_actions , 'stop_actions' ) return value | Returns a list of stop actions supported by the motor controller . Possible values are coast brake and hold . coast means that power will be removed from the motor and it will freely coast to a stop . brake means that power will be removed from the motor and a passive electrical load will be placed on the motor . This is usually done by shorting the motor terminals together . This load will absorb the energy from the rotation of the motors and cause the motor to stop more quickly than coasting . hold does not remove power from the motor . Instead it actively tries to hold the motor at the current position . If an external force tries to turn the motor the motor will push back to maintain its position . | 45 | 138 |
227,198 | def time_sp ( self ) : self . _time_sp , value = self . get_attr_int ( self . _time_sp , 'time_sp' ) return value | Writing specifies the amount of time the motor will run when using the run - timed command . Reading returns the current value . Units are in milliseconds . | 40 | 29 |
227,199 | def run_forever ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_FOREVER | Run the motor until another command is sent . | 50 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.