idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
39,100
def _create_descriptor_from_property_definition ( self , class_name , property_definition , class_name_to_definition ) : name = property_definition [ 'name' ] type_id = property_definition [ 'type' ] linked_class = property_definition . get ( 'linkedClass' , None ) linked_type = property_definition . get ( 'linkedType'...
Return a PropertyDescriptor corresponding to the given OrientDB property definition .
39,101
def _link_vertex_and_edge_types ( self ) : for edge_class_name in self . _edge_class_names : edge_element = self . _elements [ edge_class_name ] if ( EDGE_SOURCE_PROPERTY_NAME not in edge_element . properties or EDGE_DESTINATION_PROPERTY_NAME not in edge_element . properties ) : if edge_element . abstract : continue el...
For each edge link it to the vertex types it connects to each other .
39,102
def _is_local_filter ( filter_block ) : result = { 'is_local_filter' : True } filter_predicate = filter_block . predicate def visitor_fn ( expression ) : non_local_expression_types = ( ContextField , ContextFieldExistence ) if isinstance ( expression , non_local_expression_types ) : result [ 'is_local_filter' ] = False...
Return True if the Filter block references no non - local fields and False otherwise .
39,103
def _calculate_type_bound_at_step ( match_step ) : current_type_bounds = [ ] if isinstance ( match_step . root_block , QueryRoot ) : current_type_bounds . extend ( match_step . root_block . start_class ) if match_step . coerce_type_block is not None : current_type_bounds . extend ( match_step . coerce_type_block . targ...
Return the GraphQL type bound at the given step or None if no bound is given .
39,104
def _assert_type_bounds_are_not_conflicting ( current_type_bound , previous_type_bound , location , match_query ) : if all ( ( current_type_bound is not None , previous_type_bound is not None , current_type_bound != previous_type_bound ) ) : raise AssertionError ( u'Conflicting type bounds calculated at location {}: {}...
Ensure that the two bounds either are an exact match or one of them is None .
39,105
def _expose_only_preferred_locations ( match_query , location_types , coerced_locations , preferred_locations , eligible_locations ) : preferred_location_types = dict ( ) eligible_location_types = dict ( ) new_match_traversals = [ ] for current_traversal in match_query . match_traversals : new_traversal = [ ] for match...
Return a MATCH query where only preferred locations are valid as query start locations .
39,106
def _expose_all_eligible_locations ( match_query , location_types , eligible_locations ) : eligible_location_types = dict ( ) new_match_traversals = [ ] for current_traversal in match_query . match_traversals : new_traversal = [ ] for match_step in current_traversal : new_step = match_step current_step_location = match...
Return a MATCH query where all eligible locations are valid as query start locations .
39,107
def expose_ideal_query_execution_start_points ( compound_match_query , location_types , coerced_locations ) : new_queries = [ ] for match_query in compound_match_query . match_queries : location_classification = _classify_query_locations ( match_query ) preferred_locations , eligible_locations , _ = location_classifica...
Ensure that OrientDB only considers desirable query start points in query planning .
39,108
def _expression_list_to_conjunction ( expression_list ) : if not isinstance ( expression_list , list ) : raise AssertionError ( u'Expected list. Received {}: ' u'{}' . format ( type ( expression_list ) . __name__ , expression_list ) ) if len ( expression_list ) == 0 : raise AssertionError ( u'Received empty expression_...
Return an Expression that is the && of all the expressions in the given list .
39,109
def _extract_conjuction_elements_from_expression ( expression ) : if isinstance ( expression , BinaryComposition ) and expression . operator == u'&&' : for element in _extract_conjuction_elements_from_expression ( expression . left ) : yield element for element in _extract_conjuction_elements_from_expression ( expressi...
Return a generator for expressions that are connected by && s in the given expression .
39,110
def _construct_field_operator_expression_dict ( expression_list ) : between_operators = ( u'<=' , u'>=' ) inverse_operator = { u'>=' : u'<=' , u'<=' : u'>=' } local_field_to_expressions = { } remaining_expression_list = deque ( [ ] ) for expression in expression_list : if all ( ( isinstance ( expression , BinaryComposi...
Construct a mapping from local fields to specified operators and corresponding expressions .
39,111
def _lower_expressions_to_between ( base_expression ) : expression_list = list ( _extract_conjuction_elements_from_expression ( base_expression ) ) if len ( expression_list ) == 0 : raise AssertionError ( u'Received empty expression_list {} from base_expression: ' u'{}' . format ( expression_list , base_expression ) ) ...
Return a new expression with any eligible comparisons lowered to between clauses .
39,112
def lower_comparisons_to_between ( match_query ) : new_match_traversals = [ ] for current_match_traversal in match_query . match_traversals : new_traversal = [ ] for step in current_match_traversal : if step . where_block : expression = step . where_block . predicate new_where_block = Filter ( _lower_expressions_to_bet...
Return a new MatchQuery with all eligible comparison filters lowered to between clauses .
39,113
def _ensure_arguments_are_provided ( expected_types , arguments ) : expected_arg_names = set ( six . iterkeys ( expected_types ) ) provided_arg_names = set ( six . iterkeys ( arguments ) ) if expected_arg_names != provided_arg_names : missing_args = expected_arg_names - provided_arg_names unexpected_args = provided_arg...
Ensure that all arguments expected by the query were actually provided .
39,114
def insert_arguments_into_query ( compilation_result , arguments ) : _ensure_arguments_are_provided ( compilation_result . input_metadata , arguments ) if compilation_result . language == MATCH_LANGUAGE : return insert_arguments_into_match_query ( compilation_result , arguments ) elif compilation_result . language == G...
Insert the arguments into the compiled GraphQL query to form a complete query .
39,115
def validate ( self ) : if not ( isinstance ( self . start_class , set ) and all ( isinstance ( x , six . string_types ) for x in self . start_class ) ) : raise TypeError ( u'Expected set of string start_class, got: {} {}' . format ( type ( self . start_class ) . __name__ , self . start_class ) ) for cls in self . star...
Ensure that the QueryRoot block is valid .
39,116
def validate ( self ) : if not ( isinstance ( self . target_class , set ) and all ( isinstance ( x , six . string_types ) for x in self . target_class ) ) : raise TypeError ( u'Expected set of string target_class, got: {} {}' . format ( type ( self . target_class ) . __name__ , self . target_class ) ) for cls in self ....
Ensure that the CoerceType block is valid .
39,117
def validate ( self ) : if not isinstance ( self . fields , dict ) : raise TypeError ( u'Expected dict fields, got: {} {}' . format ( type ( self . fields ) . __name__ , self . fields ) ) for key , value in six . iteritems ( self . fields ) : validate_safe_string ( key ) if not isinstance ( value , Expression ) : raise...
Ensure that the ConstructResult block is valid .
39,118
def validate ( self ) : if not isinstance ( self . predicate , Expression ) : raise TypeError ( u'Expected Expression predicate, got: {} {}' . format ( type ( self . predicate ) . __name__ , self . predicate ) )
Ensure that the Filter block is valid .
39,119
def validate ( self ) : validate_marked_location ( self . location ) if not isinstance ( self . optional , bool ) : raise TypeError ( u'Expected bool optional, got: {} {}' . format ( type ( self . optional ) . __name__ , self . optional ) )
Ensure that the Backtrack block is valid .
39,120
def to_gremlin ( self ) : self . validate ( ) if self . optional : operation = u'optional' else : operation = u'back' mark_name , _ = self . location . get_location_name ( ) return u'{operation}({mark_name})' . format ( operation = operation , mark_name = safe_quoted_string ( mark_name ) )
Return a unicode object with the Gremlin representation of this BasicBlock .
39,121
def validate ( self ) : if not isinstance ( self . fold_scope_location , FoldScopeLocation ) : raise TypeError ( u'Expected a FoldScopeLocation for fold_scope_location, got: {} ' u'{}' . format ( type ( self . fold_scope_location ) , self . fold_scope_location ) )
Ensure the Fold block is valid .
39,122
def lower_ir ( ir_blocks , query_metadata_table , type_equivalence_hints = None ) : _validate_all_blocks_supported ( ir_blocks , query_metadata_table ) construct_result = _get_construct_result ( ir_blocks ) query_path_to_location_info = _map_query_path_to_location_info ( query_metadata_table ) query_path_to_output_fiel...
Lower the IR blocks into a form that can be represented by a SQL query .
39,123
def _validate_all_blocks_supported ( ir_blocks , query_metadata_table ) : if len ( ir_blocks ) < 3 : raise AssertionError ( u'Unexpectedly attempting to validate IR blocks with fewer than 3 blocks. A minimal ' u'query is expected to have at least a QueryRoot, GlobalOperationsStart, and ' u'ConstructResult block. The qu...
Validate that all IR blocks and ConstructResult fields passed to the backend are supported .
39,124
def _get_construct_result ( ir_blocks ) : last_block = ir_blocks [ - 1 ] if not isinstance ( last_block , blocks . ConstructResult ) : raise AssertionError ( u'The last IR block {} for IR blocks {} was unexpectedly not ' u'a ConstructResult block.' . format ( last_block , ir_blocks ) ) return last_block
Return the ConstructResult block from a list of IR blocks .
39,125
def _map_query_path_to_location_info ( query_metadata_table ) : query_path_to_location_info = { } for location , location_info in query_metadata_table . registered_locations : if not isinstance ( location , Location ) : continue if location . query_path in query_path_to_location_info : equivalent_location_info = query_...
Create a map from each query path to a LocationInfo at that path .
39,126
def _location_infos_equal ( left , right ) : if not isinstance ( left , LocationInfo ) or not isinstance ( right , LocationInfo ) : raise AssertionError ( u'Unsupported LocationInfo comparison between types {} and {} ' u'with values {}, {}' . format ( type ( left ) , type ( right ) , left , right ) ) optional_scopes_de...
Return True if LocationInfo objects are equivalent for the SQL backend False otherwise .
39,127
def _map_query_path_to_outputs ( construct_result , query_path_to_location_info ) : query_path_to_output_fields = { } for output_name , field in six . iteritems ( construct_result . fields ) : field_name = field . location . field output_query_path = field . location . query_path output_field_info = constants . SqlOutp...
Assign the output fields of a ConstructResult block to their respective query_path .
39,128
def _map_block_index_to_location ( ir_blocks ) : block_index_to_location = { } current_block_ixs = [ ] for num , ir_block in enumerate ( ir_blocks ) : if isinstance ( ir_block , blocks . GlobalOperationsStart ) : if len ( current_block_ixs ) > 0 : unassociated_blocks = [ ir_blocks [ ix ] for ix in current_block_ixs ] r...
Associate each IR block with its corresponding location by index .
39,129
def lower_unary_transformations ( ir_blocks ) : def visitor_fn ( expression ) : if not isinstance ( expression , expressions . UnaryTransformation ) : return expression raise NotImplementedError ( u'UnaryTransformation expression "{}" encountered with IR blocks {} is unsupported by ' u'the SQL backend.' . format ( expr...
Raise exception if any unary transformation block encountered .
39,130
def lower_unsupported_metafield_expressions ( ir_blocks ) : def visitor_fn ( expression ) : if not isinstance ( expression , expressions . LocalField ) : return expression if expression . field_name not in constants . UNSUPPORTED_META_FIELDS : return expression raise NotImplementedError ( u'Encountered unsupported meta...
Raise exception if an unsupported metafield is encountered in any LocalField expression .
39,131
def get_graphql_schema_from_orientdb_schema_data ( schema_data , class_to_field_type_overrides = None , hidden_classes = None ) : if class_to_field_type_overrides is None : class_to_field_type_overrides = dict ( ) if hidden_classes is None : hidden_classes = set ( ) schema_graph = SchemaGraph ( schema_data ) return get...
Construct a GraphQL schema from an OrientDB schema .
39,132
def start ( self , host = '127.0.0.1' , port = None , debug = False , ** kwargs ) : self . server . run ( host = host , port = port , debug = debug , ** kwargs )
Start the built in webserver bound to the host and port you d like . Default host is 127 . 0 . 0 . 1 and port 8080 .
39,133
def login ( request ) : serializer_class = registration_settings . LOGIN_SERIALIZER_CLASS serializer = serializer_class ( data = request . data ) serializer . is_valid ( raise_exception = True ) user = serializer . get_authenticated_user ( ) if not user : raise BadRequest ( 'Login or password invalid.' ) extra_data = p...
Logs in the user via given login and password .
39,134
def logout ( request ) : user = request . user serializer = LogoutSerializer ( data = request . data ) serializer . is_valid ( raise_exception = True ) data = serializer . validated_data if should_authenticate_session ( ) : auth . logout ( request ) if should_retrieve_token ( ) and data [ 'revoke_token' ] : try : user ...
Logs out the user . returns an error if the user is not authenticated .
39,135
def get_object_or_404 ( queryset , * filter_args , ** filter_kwargs ) : try : return _get_object_or_404 ( queryset , * filter_args , ** filter_kwargs ) except ( TypeError , ValueError , ValidationError ) : raise Http404
Same as Django s standard shortcut but make sure to also raise 404 if the filter_kwargs don t match the required types .
39,136
def profile ( request ) : serializer_class = registration_settings . PROFILE_SERIALIZER_CLASS if request . method in [ 'POST' , 'PUT' , 'PATCH' ] : partial = request . method == 'PATCH' serializer = serializer_class ( instance = request . user , data = request . data , partial = partial , ) serializer . is_valid ( rais...
Get or set user profile .
39,137
def register ( request ) : serializer_class = registration_settings . REGISTER_SERIALIZER_CLASS serializer = serializer_class ( data = request . data ) serializer . is_valid ( raise_exception = True ) kwargs = { } if registration_settings . REGISTER_VERIFICATION_ENABLED : verification_flag_field = get_user_setting ( 'V...
Register new user .
39,138
def verify_registration ( request ) : user = process_verify_registration_data ( request . data ) extra_data = None if registration_settings . REGISTER_VERIFICATION_AUTO_LOGIN : extra_data = perform_login ( request , user ) return get_ok_response ( 'User verified successfully' , extra_data = extra_data )
Verify registration via signature .
39,139
def get_requirements ( requirements_filepath ) : requirements = [ ] with open ( os . path . join ( ROOT_DIR , requirements_filepath ) , 'rt' ) as f : for line in f : if line . startswith ( '#' ) : continue line = line . rstrip ( ) if not line : continue requirements . append ( line ) return requirements
Return list of this package requirements via local filepath .
39,140
def send_reset_password_link ( request ) : if not registration_settings . RESET_PASSWORD_VERIFICATION_ENABLED : raise Http404 ( ) serializer = SendResetPasswordLinkSerializer ( data = request . data ) serializer . is_valid ( raise_exception = True ) login = serializer . validated_data [ 'login' ] user = None for login_...
Send email with reset password link .
39,141
def register_email ( request ) : user = request . user serializer = RegisterEmailSerializer ( data = request . data ) serializer . is_valid ( raise_exception = True ) email = serializer . validated_data [ 'email' ] template_config = ( registration_settings . REGISTER_EMAIL_VERIFICATION_EMAIL_TEMPLATES ) if registration...
Register new email .
39,142
def _is_colorbar_heuristic ( obj ) : try : aspect = float ( obj . get_aspect ( ) ) except ValueError : return False limit_ratio = 5.0 return ( aspect >= limit_ratio and len ( obj . get_xticks ( ) ) == 0 ) or ( aspect <= 1.0 / limit_ratio and len ( obj . get_yticks ( ) ) == 0 )
Find out if the object is in fact a color bar .
39,143
def _mpl_cmap2pgf_cmap ( cmap , data ) : if isinstance ( cmap , mpl . colors . LinearSegmentedColormap ) : return _handle_linear_segmented_color_map ( cmap , data ) assert isinstance ( cmap , mpl . colors . ListedColormap ) , "Only LinearSegmentedColormap and ListedColormap are supported" return _handle_listed_color_ma...
Converts a color map as given in matplotlib to a color map as represented in PGFPlots .
39,144
def _scale_to_int ( X , max_val = None ) : if max_val is None : X = X / _gcd_array ( X ) else : X = X / max ( 1 / max_val , _gcd_array ( X ) ) return [ int ( entry ) for entry in X ]
Scales the array X such that it contains only integers .
39,145
def _gcd_array ( X ) : greatest_common_divisor = 0.0 for x in X : greatest_common_divisor = _gcd ( greatest_common_divisor , x ) return greatest_common_divisor
Return the largest real value h such that all elements in x are integer multiples of h .
39,146
def new_filename ( data , file_kind , ext ) : nb_key = file_kind + "number" if nb_key not in data . keys ( ) : data [ nb_key ] = - 1 if not data [ "override externals" ] : file_exists = True while file_exists : data [ nb_key ] = data [ nb_key ] + 1 filename , name = _gen_filename ( data , nb_key , ext ) file_exists = o...
Returns an available filename .
39,147
def mpl_linestyle2pgfplots_linestyle ( line_style , line = None ) : if isinstance ( line_style , tuple ) : if line_style [ 0 ] is None : return None if len ( line_style [ 1 ] ) == 2 : return "dash pattern=on {}pt off {}pt" . format ( * line_style [ 1 ] ) assert len ( line_style [ 1 ] ) == 4 return "dash pattern=on {}pt...
Translates a line style of matplotlib to the corresponding style in PGFPlots .
39,148
def draw_quadmesh ( data , obj ) : content = [ ] filename , rel_filepath = files . new_filename ( data , "img" , ".png" ) dpi = data [ "dpi" ] fig_dpi = obj . figure . get_dpi ( ) obj . figure . set_dpi ( dpi ) from matplotlib . backends . backend_agg import RendererAgg cbox = obj . get_clip_box ( ) width = int ( round...
Returns the PGFPlots code for an graphics environment holding a rendering of the object .
39,149
def mpl_color2xcolor ( data , matplotlib_color ) : my_col = numpy . array ( mpl . colors . ColorConverter ( ) . to_rgba ( matplotlib_color ) ) if my_col [ - 1 ] == 0.0 : return data , "none" , my_col xcol = None available_colors = { "white" : numpy . array ( [ 1 , 1 , 1 ] ) , "lightgray" : numpy . array ( [ 0.75 , 0.75...
Translates a matplotlib color specification into a proper LaTeX xcolor .
39,150
def draw_patch ( data , obj ) : data , draw_options = mypath . get_draw_options ( data , obj , obj . get_edgecolor ( ) , obj . get_facecolor ( ) , obj . get_linestyle ( ) , obj . get_linewidth ( ) , ) if isinstance ( obj , mpl . patches . Rectangle ) : return _draw_rectangle ( data , obj , draw_options ) elif isinstanc...
Return the PGFPlots code for patches .
39,151
def _draw_rectangle ( data , obj , draw_options ) : label = obj . get_label ( ) if label == "" : return data , [ ] handles , labels = obj . axes . get_legend_handles_labels ( ) labelsFound = [ label for h , label in zip ( handles , labels ) if obj in h . get_children ( ) ] if len ( labelsFound ) == 1 : label = labelsFo...
Return the PGFPlots code for rectangles .
39,152
def _draw_ellipse ( data , obj , draw_options ) : if isinstance ( obj , mpl . patches . Circle ) : return _draw_circle ( data , obj , draw_options ) x , y = obj . center ff = data [ "float format" ] if obj . angle != 0 : fmt = "rotate around={{" + ff + ":(axis cs:" + ff + "," + ff + ")}}" draw_options . append ( fmt . ...
Return the PGFPlots code for ellipses .
39,153
def _draw_circle ( data , obj , draw_options ) : x , y = obj . center ff = data [ "float format" ] cont = ( "\\draw[{}] (axis cs:" + ff + "," + ff + ") circle (" + ff + ");\n" ) . format ( "," . join ( draw_options ) , x , y , obj . get_radius ( ) ) return data , cont
Return the PGFPlots code for circles .
39,154
def draw_image ( data , obj ) : content = [ ] filename , rel_filepath = files . new_filename ( data , "img" , ".png" ) img_array = obj . get_array ( ) dims = img_array . shape if len ( dims ) == 2 : clims = obj . get_clim ( ) mpl . pyplot . imsave ( fname = filename , arr = img_array , cmap = obj . get_cmap ( ) , vmin ...
Returns the PGFPlots code for an image environment .
39,155
def get_legend_text ( obj ) : leg = obj . axes . get_legend ( ) if leg is None : return None keys = [ l . get_label ( ) for l in leg . legendHandles if l is not None ] values = [ l . get_text ( ) for l in leg . texts ] label = obj . get_label ( ) d = dict ( zip ( keys , values ) ) if label in d : return d [ label ] ret...
Check if line is in legend .
39,156
def _get_color_definitions ( data ) : definitions = [ ] fmt = "\\definecolor{{{}}}{{rgb}}{{" + "," . join ( 3 * [ data [ "float format" ] ] ) + "}}" for name , rgb in data [ "custom colors" ] . items ( ) : definitions . append ( fmt . format ( name , rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] ) ) return definitions
Returns the list of custom color definitions for the TikZ file .
39,157
def _print_pgfplot_libs_message ( data ) : pgfplotslibs = "," . join ( list ( data [ "pgfplots libs" ] ) ) tikzlibs = "," . join ( list ( data [ "tikz libs" ] ) ) print ( 70 * "=" ) print ( "Please add the following lines to your LaTeX preamble:\n" ) print ( "\\usepackage[utf8]{inputenc}" ) print ( "\\usepackage{fontsp...
Prints message to screen indicating the use of PGFPlots and its libraries .
39,158
def extend ( self , content , zorder ) : if zorder not in self . _content : self . _content [ zorder ] = [ ] self . _content [ zorder ] . extend ( content )
Extends with a list and a z - order
39,159
def draw_line2d ( data , obj ) : content = [ ] addplot_options = [ ] if len ( obj . get_xdata ( ) ) == 0 : return data , [ ] line_width = mypath . mpl_linewidth2pgfp_linewidth ( data , obj . get_linewidth ( ) ) if line_width : addplot_options . append ( line_width ) color = obj . get_color ( ) data , line_xcolor , _ = ...
Returns the PGFPlots code for an Line2D environment .
39,160
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 = line...
Returns Pgfplots code for a number of patch objects .
39,161
def _mpl_marker2pgfp_marker ( data , mpl_marker , marker_face_color ) : 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 retu...
Translates a marker style of matplotlib to the corresponding style in PGFPlots .
39,162
def draw_text ( data , obj ) : content = [ ] properties = [ ] style = [ ] if isinstance ( obj , mpl . text . Annotation ) : _annotation ( obj , data , content ) pos = obj . get_position ( ) text = obj . get_text ( ) if text in [ "" , data [ "current axis title" ] ] : return data , content size = obj . get_size ( ) bbox...
Paints text on the graph .
39,163
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 ] , h...
Converts matplotlib positioning to pgf node positioning . Not quite accurate but the results are equivalent more or less .
39,164
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...
Import a JSON file or file - like object into a rows . Table .
39,165
def export_to_json ( table , filename_or_fobj = None , encoding = "utf-8" , indent = None , * args , ** kwargs ) : 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 , *...
Export a rows . Table to a JSON file or file - like object .
39,166
def plugin_name_by_uri ( uri ) : "Return the plugin name based on the URI" 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_...
Return the plugin name based on the URI
39,167
def extension_by_source ( source , mime_type ) : "Return the file extension used by this 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
39,168
def plugin_name_by_mime_type ( mime_type , mime_name , file_extension ) : "Return the plugin name based on the MIME type" 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
39,169
def detect_source ( uri , verify_ssl , progress , timeout = 5 ) : 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://" ) : retu...
Return a rows . Source with information for a given URI
39,170
def import_from_source ( source , default_encoding , * args , ** kwargs ) : "Import data described in a `rows.Source` into a `rows.Table`" plugin_name = source . plugin_name kwargs [ "encoding" ] = ( kwargs . get ( "encoding" , None ) or source . encoding or default_encoding ) try : import_function = getattr ( rows , "...
Import data described in a rows . Source into a rows . Table
39,171
def import_from_uri ( uri , default_encoding = "utf-8" , verify_ssl = True , progress = False , * args , ** kwargs ) : "Given an URI, detects plugin and encoding and imports into a `rows.Table`" source = detect_source ( uri , verify_ssl = verify_ssl , progress = progress ) return import_from_source ( source , default_e...
Given an URI detects plugin and encoding and imports into a rows . Table
39,172
def open_compressed ( filename , mode = "r" , encoding = None ) : "Return a text-based file object from a filename, even if compressed" 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 ...
Return a text - based file object from a filename even if compressed
39,173
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 , ) : "Export a CSV file to SQLite, based on field type detection from samples" if dialec...
Export a CSV file to SQLite based on field type detection from samples
39,174
def sqlite_to_csv ( input_filename , table_name , output_filename , dialect = csv . excel , batch_size = 10000 , encoding = "utf-8" , callback = None , query = None , ) : if isinstance ( dialect , six . text_type ) : dialect = csv . get_dialect ( dialect ) if query is None : query = "SELECT * FROM {}" . format ( table_...
Export a table inside a SQLite database to CSV
39,175
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 . w...
Execute a command and return its output
39,176
def uncompressed_size ( filename ) : quoted_filename = shlex . quote ( filename ) 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 ...
Return the uncompressed size for a file by executing commands
39,177
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 ) ...
Import data from CSV into PostgreSQL using the fastest method
39,178
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 ) command = get_psql_copy_command ( database_uri = database_uri , direction ...
Export data from PostgreSQL into a CSV file using the fastest method
39,179
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 ...
Load schema from file in any of the supported formats
39,180
def slug ( text , separator = "_" , permitted_chars = SLUG_CHARS ) : text = six . text_type ( text or "" ) text = normalize ( "NFKD" , text . strip ( ) ) . encode ( "ascii" , "ignore" ) . decode ( "ascii" ) text = REGEXP_WORD_BOUNDARY . sub ( "\\1" + re . escape ( separator ) , text ) allowed_chars = list ( permitted_c...
Generate a slug for the text .
39,181
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 .
39,182
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_{}" ....
Return unique and slugged field names .
39,183
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
39,184
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
39,185
def transform ( row , table ) : 'Extract links from "project" field and remove HTML from all' 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
39,186
def transform ( row , table ) : 'Transform row "link" into full URL and add "state" based on "name"' 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
39,187
def import_from_parquet ( filename_or_fobj , * args , ** kwargs ) : source = Source . from_file ( filename_or_fobj , plugin_name = "parquet" , mode = "rb" ) types = OrderedDict ( [ ( schema . name , PARQUET_TO_ROWS [ schema . type ] ) for schema in parquet . _read_footer ( source . fobj ) . schema if schema . type is n...
Import data from a Parquet file and return with rows . Table .
39,188
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 : br...
Import data from a iterable of dicts
39,189
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
39,190
def cell_value ( sheet , row , col ) : cell = sheet . cell ( row , col ) field_type = CELL_TYPES [ cell . ctype ] 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 . DatetimeF...
Return the cell value of the table passed by argument based in row and column .
39,191
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 (...
Return a rows . Table created from imported XLS file .
39,192
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 enumera...
Export the rows . Table to XLS file and return the saved file .
39,193
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
39,194
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]" col_positions = [ ] re . sub ( separator , lambda group : col_positions . append ( group . start ( ) ) , header_line ) if frame_st...
Find the position for each column separator in the given line
39,195
def import_from_txt ( filename_or_fobj , encoding = "utf-8" , frame_style = FRAME_SENTINEL , * args , ** kwargs ) : 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...
Return a rows . Table created from imported TXT file .
39,196
def export_to_txt ( table , filename_or_fobj = None , encoding = None , frame_style = "ASCII" , safe_none_frame = True , * args , ** kwargs ) : frame_style = _parse_frame_style ( frame_style ) frame = FRAMES [ frame_style . lower ( ) ] serialized_table = serialize ( table , * args , ** kwargs ) field_names = next ( ser...
Export a rows . Table to text .
39,197
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 ( "...
Return a rows . Table with data from SQLite database .
39,198
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 ( valu...
Convert a PyOpenXL s Cell object to the corresponding Python object .
39,199
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" ] =...
Return a rows . Table created from imported XLSX file .