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,000 | def _transform_filter_to_sql ( filter_block , node , context ) : expression = filter_block . predicate return _expression_to_sql ( expression , node , context ) | Transform a Filter block to its corresponding SQLAlchemy expression . | 40 | 12 |
227,001 | def _expression_to_sql ( expression , node , context ) : _expression_transformers = { expressions . LocalField : _transform_local_field_to_expression , expressions . Variable : _transform_variable_to_expression , expressions . Literal : _transform_literal_to_expression , expressions . BinaryComposition : _transform_binary_composition_to_expression , } expression_type = type ( expression ) if expression_type not in _expression_transformers : raise NotImplementedError ( u'Unsupported compiler expression "{}" of type "{}" cannot be converted to SQL ' u'expression.' . format ( expression , type ( expression ) ) ) return _expression_transformers [ expression_type ] ( expression , node , context ) | Recursively transform a Filter block predicate to its SQLAlchemy expression representation . | 163 | 16 |
227,002 | def _transform_binary_composition_to_expression ( expression , node , context ) : if expression . operator not in constants . SUPPORTED_OPERATORS : raise NotImplementedError ( u'Filter operation "{}" is not supported by the SQL backend.' . format ( expression . operator ) ) sql_operator = constants . SUPPORTED_OPERATORS [ expression . operator ] left = _expression_to_sql ( expression . left , node , context ) right = _expression_to_sql ( expression . right , node , context ) if sql_operator . cardinality == constants . CARDINALITY_UNARY : left , right = _get_column_and_bindparam ( left , right , sql_operator ) clause = getattr ( left , sql_operator . name ) ( right ) return clause elif sql_operator . cardinality == constants . CARDINALITY_BINARY : clause = getattr ( sql_expressions , sql_operator . name ) ( left , right ) return clause elif sql_operator . cardinality == constants . CARDINALITY_LIST_VALUED : left , right = _get_column_and_bindparam ( left , right , sql_operator ) # ensure that SQLAlchemy treats the right bind parameter as list valued right . expanding = True clause = getattr ( left , sql_operator . name ) ( right ) return clause raise AssertionError ( u'Unreachable, operator cardinality {} for compiler expression {} is ' u'unknown' . format ( sql_operator . cardinality , expression ) ) | Transform a BinaryComposition compiler expression into a SQLAlchemy expression . | 333 | 14 |
227,003 | def _transform_variable_to_expression ( expression , node , context ) : variable_name = expression . variable_name if not variable_name . startswith ( u'$' ) : raise AssertionError ( u'Unexpectedly received variable name {} that is not ' u'prefixed with "$"' . format ( variable_name ) ) return bindparam ( variable_name [ 1 : ] ) | Transform a Variable compiler expression into its SQLAlchemy expression representation . | 88 | 13 |
227,004 | def _transform_local_field_to_expression ( expression , node , context ) : column_name = expression . field_name column = sql_context_helpers . get_column ( column_name , node , context ) return column | Transform a LocalField compiler expression into its SQLAlchemy expression representation . | 51 | 14 |
227,005 | def lower_context_field_existence ( ir_blocks , query_metadata_table ) : def regular_visitor_fn ( expression ) : """Expression visitor function that rewrites ContextFieldExistence expressions.""" if not isinstance ( expression , ContextFieldExistence ) : return expression location_type = query_metadata_table . get_location_info ( expression . location ) . type # Since this function is only used in blocks that aren't ConstructResult, # the location check is performed using a regular ContextField expression. return BinaryComposition ( u'!=' , ContextField ( expression . location , location_type ) , NullLiteral ) def construct_result_visitor_fn ( expression ) : """Expression visitor function that rewrites ContextFieldExistence expressions.""" if not isinstance ( expression , ContextFieldExistence ) : return expression location_type = query_metadata_table . get_location_info ( expression . location ) . type # Since this function is only used in ConstructResult blocks, # the location check is performed using the special OutputContextVertex expression. return BinaryComposition ( u'!=' , OutputContextVertex ( expression . location , location_type ) , NullLiteral ) new_ir_blocks = [ ] for block in ir_blocks : new_block = None if isinstance ( block , ConstructResult ) : new_block = block . visit_and_update_expressions ( construct_result_visitor_fn ) else : new_block = block . visit_and_update_expressions ( regular_visitor_fn ) new_ir_blocks . append ( new_block ) return new_ir_blocks | Lower ContextFieldExistence expressions into lower - level expressions . | 357 | 12 |
227,006 | def optimize_boolean_expression_comparisons ( ir_blocks ) : operator_inverses = { u'=' : u'!=' , u'!=' : u'=' , } def visitor_fn ( expression ) : """Expression visitor function that performs the above rewriting.""" if not isinstance ( expression , BinaryComposition ) : return expression left_is_binary_composition = isinstance ( expression . left , BinaryComposition ) right_is_binary_composition = isinstance ( expression . right , BinaryComposition ) if not left_is_binary_composition and not right_is_binary_composition : # Nothing to rewrite, return the expression as-is. return expression identity_literal = None # The boolean literal for which we just use the inner expression. inverse_literal = None # The boolean literal for which we negate the inner expression. if expression . operator == u'=' : identity_literal = TrueLiteral inverse_literal = FalseLiteral elif expression . operator == u'!=' : identity_literal = FalseLiteral inverse_literal = TrueLiteral else : return expression expression_to_rewrite = None if expression . left == identity_literal and right_is_binary_composition : return expression . right elif expression . right == identity_literal and left_is_binary_composition : return expression . left elif expression . left == inverse_literal and right_is_binary_composition : expression_to_rewrite = expression . right elif expression . right == inverse_literal and left_is_binary_composition : expression_to_rewrite = expression . left if expression_to_rewrite is None : # We couldn't find anything to rewrite, return the expression as-is. return expression elif expression_to_rewrite . operator not in operator_inverses : # We can't rewrite the inner expression since we don't know its inverse operator. return expression else : return BinaryComposition ( operator_inverses [ expression_to_rewrite . operator ] , expression_to_rewrite . left , expression_to_rewrite . right ) new_ir_blocks = [ ] for block in ir_blocks : new_block = block . visit_and_update_expressions ( visitor_fn ) new_ir_blocks . append ( new_block ) return new_ir_blocks | Optimize comparisons of a boolean binary comparison expression against a boolean literal . | 522 | 14 |
227,007 | def extract_simple_optional_location_info ( ir_blocks , complex_optional_roots , location_to_optional_roots ) : # Simple optional roots are a subset of location_to_optional_roots.values() (all optional roots) # We filter out the ones that are also present in complex_optional_roots. location_to_preceding_optional_root_iteritems = six . iteritems ( { location : optional_root_locations_stack [ - 1 ] for location , optional_root_locations_stack in six . iteritems ( location_to_optional_roots ) } ) simple_optional_root_to_inner_location = { optional_root_location : inner_location for inner_location , optional_root_location in location_to_preceding_optional_root_iteritems if optional_root_location not in complex_optional_roots } simple_optional_root_locations = set ( simple_optional_root_to_inner_location . keys ( ) ) # Blocks within folded scopes should not be taken into account in this function. _ , non_folded_ir_blocks = extract_folds_from_ir_blocks ( ir_blocks ) simple_optional_root_info = { } preceding_location = None for current_block in non_folded_ir_blocks : if isinstance ( current_block , MarkLocation ) : preceding_location = current_block . location elif isinstance ( current_block , Traverse ) and current_block . optional : if preceding_location in simple_optional_root_locations : # The current optional Traverse is "simple" # i.e. it does not contain any Traverses within. inner_location = simple_optional_root_to_inner_location [ preceding_location ] inner_location_name , _ = inner_location . get_location_name ( ) simple_optional_info_dict = { 'inner_location_name' : inner_location_name , 'edge_field' : current_block . get_field_name ( ) , } simple_optional_root_info [ preceding_location ] = simple_optional_info_dict return simple_optional_root_info | Construct a map from simple optional locations to their inner location and traversed edge . | 479 | 16 |
227,008 | def remove_end_optionals ( ir_blocks ) : new_ir_blocks = [ ] for block in ir_blocks : if not isinstance ( block , EndOptional ) : new_ir_blocks . append ( block ) return new_ir_blocks | Return a list of IR blocks as a copy of the original with EndOptional blocks removed . | 55 | 18 |
227,009 | def validate ( self ) : super ( OutputContextVertex , self ) . validate ( ) if self . location . field is not None : raise ValueError ( u'Expected location at a vertex, but got: {}' . format ( self . location ) ) | Validate that the OutputContextVertex is correctly representable . | 55 | 13 |
227,010 | def lower_has_substring_binary_compositions ( ir_blocks ) : def visitor_fn ( expression ) : """Rewrite BinaryComposition expressions with "has_substring" into representable form.""" # The implementation of "has_substring" must use the LIKE operator in MATCH, and must # prepend and append "%" symbols to the substring being matched. # We transform any structures that resemble the following: # BinaryComposition(u'has_substring', X, Y) # into the following: # BinaryComposition( # u'LIKE', # X, # BinaryComposition( # u'+', # Literal("%"), # BinaryComposition( # u'+', # Y, # Literal("%") # ) # ) # ) if not isinstance ( expression , BinaryComposition ) or expression . operator != u'has_substring' : return expression return BinaryComposition ( u'LIKE' , expression . left , BinaryComposition ( u'+' , Literal ( '%' ) , BinaryComposition ( u'+' , expression . right , Literal ( '%' ) ) ) ) new_ir_blocks = [ block . visit_and_update_expressions ( visitor_fn ) for block in ir_blocks ] return new_ir_blocks | Lower Filter blocks that use the has_substring operation into MATCH - representable form . | 285 | 19 |
227,011 | def truncate_repeated_single_step_traversals ( match_query ) : # Such traversals frequently happen as side-effects of the lowering process # of Backtrack blocks, and needlessly complicate the executed queries. new_match_traversals = [ ] visited_locations = set ( ) for current_match_traversal in match_query . match_traversals : ignore_traversal = False if len ( current_match_traversal ) == 1 : # Single-step traversal detected. If its location was visited already, ignore it. single_step = current_match_traversal [ 0 ] if single_step . as_block is None : raise AssertionError ( u'Unexpectedly found a single-step traversal with no as_block:' u' {} {}' . format ( current_match_traversal , match_query ) ) if single_step . as_block . location in visited_locations : # This location was visited before, omit the traversal. ignore_traversal = True if not ignore_traversal : # For each step in this traversal, mark its location as visited. for step in current_match_traversal : if step . as_block is not None : visited_locations . add ( step . as_block . location ) new_match_traversals . append ( current_match_traversal ) return match_query . _replace ( match_traversals = new_match_traversals ) | Truncate one - step traversals that overlap a previous traversal location . | 328 | 16 |
227,012 | def _flatten_location_translations ( location_translations ) : sources_to_process = set ( six . iterkeys ( location_translations ) ) def _update_translation ( source ) : """Return the proper (fully-flattened) translation for the given location.""" destination = location_translations [ source ] if destination not in location_translations : # "destination" cannot be translated, no further flattening required. return destination else : # "destination" can itself be translated -- do so, # and then flatten "source" to the final translation as well. sources_to_process . discard ( destination ) final_destination = _update_translation ( destination ) location_translations [ source ] = final_destination return final_destination while sources_to_process : _update_translation ( sources_to_process . pop ( ) ) | If location A translates to B and B to C then make A translate directly to C . | 188 | 18 |
227,013 | def lower_folded_coerce_types_into_filter_blocks ( folded_ir_blocks ) : new_folded_ir_blocks = [ ] for block in folded_ir_blocks : if isinstance ( block , CoerceType ) : new_block = convert_coerce_type_to_instanceof_filter ( block ) else : new_block = block new_folded_ir_blocks . append ( new_block ) return new_folded_ir_blocks | Lower CoerceType blocks into INSTANCEOF Filter blocks . Indended for folded IR blocks . | 109 | 21 |
227,014 | def remove_backtrack_blocks_from_fold ( folded_ir_blocks ) : new_folded_ir_blocks = [ ] for block in folded_ir_blocks : if not isinstance ( block , Backtrack ) : new_folded_ir_blocks . append ( block ) return new_folded_ir_blocks | Return a list of IR blocks with all Backtrack blocks removed . | 72 | 13 |
227,015 | def truncate_repeated_single_step_traversals_in_sub_queries ( compound_match_query ) : lowered_match_queries = [ ] for match_query in compound_match_query . match_queries : new_match_query = truncate_repeated_single_step_traversals ( match_query ) lowered_match_queries . append ( new_match_query ) return compound_match_query . _replace ( match_queries = lowered_match_queries ) | For each sub - query remove one - step traversals that overlap a previous traversal location . | 115 | 19 |
227,016 | def _prune_traverse_using_omitted_locations ( match_traversal , omitted_locations , complex_optional_roots , location_to_optional_roots ) : new_match_traversal = [ ] for step in match_traversal : new_step = step if isinstance ( step . root_block , Traverse ) and step . root_block . optional : current_location = step . as_block . location optional_root_locations_stack = location_to_optional_roots . get ( current_location , None ) optional_root_location = optional_root_locations_stack [ - 1 ] if optional_root_location is None : raise AssertionError ( u'Found optional Traverse location {} that was not present ' u'in location_to_optional_roots dict: {}' . format ( current_location , location_to_optional_roots ) ) elif optional_root_location in omitted_locations : # Add filter to indicate that the omitted edge(s) shoud not exist field_name = step . root_block . get_field_name ( ) new_predicate = filter_edge_field_non_existence ( LocalField ( field_name ) ) old_filter = new_match_traversal [ - 1 ] . where_block if old_filter is not None : new_predicate = BinaryComposition ( u'&&' , old_filter . predicate , new_predicate ) new_match_step = new_match_traversal [ - 1 ] . _replace ( where_block = Filter ( new_predicate ) ) new_match_traversal [ - 1 ] = new_match_step # Discard all steps following the omitted @optional traverse new_step = None elif optional_root_location in complex_optional_roots : # Any non-omitted @optional traverse (that expands vertex fields) # becomes a normal mandatory traverse (discard the optional flag). new_root_block = Traverse ( step . root_block . direction , step . root_block . edge_name ) new_step = step . _replace ( root_block = new_root_block ) else : # The current optional traverse is a "simple optional" (one that does not # expand vertex fields). No further action is required since MATCH supports it. pass # If new_step was set to None, # we have encountered a Traverse that is within an omitted location. # We discard the remainder of the match traversal (everything following is also omitted). if new_step is None : break else : new_match_traversal . append ( new_step ) return new_match_traversal | Return a prefix of the given traverse excluding any blocks after an omitted optional . | 583 | 15 |
227,017 | def convert_optional_traversals_to_compound_match_query ( match_query , complex_optional_roots , location_to_optional_roots ) : tree = construct_optional_traversal_tree ( complex_optional_roots , location_to_optional_roots ) rooted_optional_root_location_subsets = tree . get_all_rooted_subtrees_as_lists ( ) omitted_location_subsets = [ set ( complex_optional_roots ) - set ( subset ) for subset in rooted_optional_root_location_subsets ] sorted_omitted_location_subsets = sorted ( omitted_location_subsets ) compound_match_traversals = [ ] for omitted_locations in reversed ( sorted_omitted_location_subsets ) : new_match_traversals = [ ] for match_traversal in match_query . match_traversals : location = match_traversal [ 0 ] . as_block . location optional_root_locations_stack = location_to_optional_roots . get ( location , None ) if optional_root_locations_stack is not None : optional_root_location = optional_root_locations_stack [ - 1 ] else : optional_root_location = None if optional_root_location is None or optional_root_location not in omitted_locations : new_match_traversal = _prune_traverse_using_omitted_locations ( match_traversal , set ( omitted_locations ) , complex_optional_roots , location_to_optional_roots ) new_match_traversals . append ( new_match_traversal ) else : # The root_block is within an omitted scope. # Discard the entire match traversal (do not append to new_match_traversals) pass compound_match_traversals . append ( new_match_traversals ) match_queries = [ MatchQuery ( match_traversals = match_traversals , folds = match_query . folds , output_block = match_query . output_block , where_block = match_query . where_block , ) for match_traversals in compound_match_traversals ] return CompoundMatchQuery ( match_queries = match_queries ) | Return 2^n distinct MatchQuery objects in a CompoundMatchQuery . | 509 | 15 |
227,018 | def _get_present_locations ( match_traversals ) : present_locations = set ( ) present_non_optional_locations = set ( ) for match_traversal in match_traversals : for step in match_traversal : if step . as_block is not None : location_name , _ = step . as_block . location . get_location_name ( ) present_locations . add ( location_name ) if isinstance ( step . root_block , Traverse ) and not step . root_block . optional : present_non_optional_locations . add ( location_name ) if not present_non_optional_locations . issubset ( present_locations ) : raise AssertionError ( u'present_non_optional_locations {} was not a subset of ' u'present_locations {}. THis hould never happen.' . format ( present_non_optional_locations , present_locations ) ) return present_locations , present_non_optional_locations | Return the set of locations and non - optional locations present in the given match traversals . | 229 | 18 |
227,019 | def prune_non_existent_outputs ( compound_match_query ) : if len ( compound_match_query . match_queries ) == 1 : return compound_match_query elif len ( compound_match_query . match_queries ) == 0 : raise AssertionError ( u'Received CompoundMatchQuery with ' u'an empty list of MatchQuery objects.' ) else : match_queries = [ ] for match_query in compound_match_query . match_queries : match_traversals = match_query . match_traversals output_block = match_query . output_block present_locations_tuple = _get_present_locations ( match_traversals ) present_locations , present_non_optional_locations = present_locations_tuple new_output_fields = { } for output_name , expression in six . iteritems ( output_block . fields ) : if isinstance ( expression , OutputContextField ) : # An OutputContextField as an output Expression indicates that we are not # within an @optional scope. Therefore, the location this output uses must # be in present_locations, and the output is never pruned. location_name , _ = expression . location . get_location_name ( ) if location_name not in present_locations : raise AssertionError ( u'Non-optional output location {} was not found in ' u'present_locations: {}' . format ( expression . location , present_locations ) ) new_output_fields [ output_name ] = expression elif isinstance ( expression , FoldedContextField ) : # A FoldedContextField as an output Expression indicates that we are not # within an @optional scope. Therefore, the location this output uses must # be in present_locations, and the output is never pruned. base_location = expression . fold_scope_location . base_location location_name , _ = base_location . get_location_name ( ) if location_name not in present_locations : raise AssertionError ( u'Folded output location {} was found in ' u'present_locations: {}' . format ( base_location , present_locations ) ) new_output_fields [ output_name ] = expression elif isinstance ( expression , TernaryConditional ) : # A TernaryConditional indicates that this output is within some optional scope. # This may be pruned away based on the contents of present_locations. location_name , _ = expression . if_true . location . get_location_name ( ) if location_name in present_locations : if location_name in present_non_optional_locations : new_output_fields [ output_name ] = expression . if_true else : new_output_fields [ output_name ] = expression else : raise AssertionError ( u'Invalid expression of type {} in output block: ' u'{}' . format ( type ( expression ) . __name__ , output_block ) ) match_queries . append ( MatchQuery ( match_traversals = match_traversals , folds = match_query . folds , output_block = ConstructResult ( new_output_fields ) , where_block = match_query . where_block , ) ) return CompoundMatchQuery ( match_queries = match_queries ) | Remove non - existent outputs from each MatchQuery in the given CompoundMatchQuery . | 736 | 18 |
227,020 | def _construct_location_to_filter_list ( match_query ) : # For each location, all filters for that location should be applied at the first instance. # This function collects a list of all filters corresponding to each location # present in the given MatchQuery. location_to_filters = { } for match_traversal in match_query . match_traversals : for match_step in match_traversal : current_filter = match_step . where_block if current_filter is not None : current_location = match_step . as_block . location location_to_filters . setdefault ( current_location , [ ] ) . append ( current_filter ) return location_to_filters | Return a dict mapping location - > list of filters applied at that location . | 156 | 15 |
227,021 | def _filter_list_to_conjunction_expression ( filter_list ) : if not isinstance ( filter_list , list ) : raise AssertionError ( u'Expected `list`, Received: {}.' . format ( filter_list ) ) if any ( ( not isinstance ( filter_block , Filter ) for filter_block in filter_list ) ) : raise AssertionError ( u'Expected list of Filter objects. Received: {}' . format ( filter_list ) ) expression_list = [ filter_block . predicate for filter_block in filter_list ] return expression_list_to_conjunction ( expression_list ) | Convert a list of filters to an Expression that is the conjunction of all of them . | 142 | 18 |
227,022 | def _apply_filters_to_first_location_occurrence ( match_traversal , location_to_filters , already_filtered_locations ) : new_match_traversal = [ ] newly_filtered_locations = set ( ) for match_step in match_traversal : # Apply all filters for a location to the first occurence of that location current_location = match_step . as_block . location if current_location in newly_filtered_locations : raise AssertionError ( u'The same location {} was encountered twice in a single ' u'match traversal: {}. This should never happen.' . format ( current_location , match_traversal ) ) if all ( ( current_location in location_to_filters , current_location not in already_filtered_locations ) ) : where_block = Filter ( _filter_list_to_conjunction_expression ( location_to_filters [ current_location ] ) ) # No further filters needed for this location. If the same location is found in # another call to this function, no filters will be added. newly_filtered_locations . add ( current_location ) else : where_block = None new_match_step = MatchStep ( root_block = match_step . root_block , coerce_type_block = match_step . coerce_type_block , where_block = where_block , as_block = match_step . as_block ) new_match_traversal . append ( new_match_step ) return new_match_traversal , newly_filtered_locations | Apply all filters for a specific location into its first occurrence in a given traversal . | 361 | 17 |
227,023 | def collect_filters_to_first_location_occurrence ( compound_match_query ) : new_match_queries = [ ] # Each MatchQuery has a different set of locations, and associated Filters. # Hence, each of them is processed independently. for match_query in compound_match_query . match_queries : # Construct mapping from location -> list of filter predicates applied at that location location_to_filters = _construct_location_to_filter_list ( match_query ) already_filtered_locations = set ( ) new_match_traversals = [ ] for match_traversal in match_query . match_traversals : result = _apply_filters_to_first_location_occurrence ( match_traversal , location_to_filters , already_filtered_locations ) new_match_traversal , newly_filtered_locations = result new_match_traversals . append ( new_match_traversal ) already_filtered_locations . update ( newly_filtered_locations ) new_match_queries . append ( MatchQuery ( match_traversals = new_match_traversals , folds = match_query . folds , output_block = match_query . output_block , where_block = match_query . where_block , ) ) return CompoundMatchQuery ( match_queries = new_match_queries ) | Collect all filters for a particular location to the first instance of the location . | 317 | 15 |
227,024 | def _update_context_field_binary_composition ( present_locations , expression ) : if not any ( ( isinstance ( expression . left , ContextField ) , isinstance ( expression . right , ContextField ) ) ) : raise AssertionError ( u'Received a BinaryComposition {} without any ContextField ' u'operands. This should never happen.' . format ( expression ) ) if isinstance ( expression . left , ContextField ) : context_field = expression . left location_name , _ = context_field . location . get_location_name ( ) if location_name not in present_locations : return TrueLiteral if isinstance ( expression . right , ContextField ) : context_field = expression . right location_name , _ = context_field . location . get_location_name ( ) if location_name not in present_locations : return TrueLiteral return expression | Lower BinaryCompositions involving non - existent ContextFields to True . | 196 | 16 |
227,025 | def _simplify_non_context_field_binary_composition ( expression ) : if any ( ( isinstance ( expression . left , ContextField ) , isinstance ( expression . right , ContextField ) ) ) : raise AssertionError ( u'Received a BinaryComposition {} with a ContextField ' u'operand. This should never happen.' . format ( expression ) ) if expression . operator == u'||' : if expression . left == TrueLiteral or expression . right == TrueLiteral : return TrueLiteral else : return expression elif expression . operator == u'&&' : if expression . left == TrueLiteral : return expression . right if expression . right == TrueLiteral : return expression . left else : return expression else : return expression | Return a simplified BinaryComposition if either operand is a TrueLiteral . | 169 | 17 |
227,026 | def _update_context_field_expression ( present_locations , expression ) : no_op_blocks = ( ContextField , Literal , LocalField , UnaryTransformation , Variable ) if isinstance ( expression , BinaryComposition ) : if isinstance ( expression . left , ContextField ) or isinstance ( expression . right , ContextField ) : return _update_context_field_binary_composition ( present_locations , expression ) else : return _simplify_non_context_field_binary_composition ( expression ) elif isinstance ( expression , TernaryConditional ) : return _simplify_ternary_conditional ( expression ) elif isinstance ( expression , BetweenClause ) : lower_bound = expression . lower_bound upper_bound = expression . upper_bound if isinstance ( lower_bound , ContextField ) or isinstance ( upper_bound , ContextField ) : raise AssertionError ( u'Found BetweenClause with ContextFields as lower/upper bounds. ' u'This should never happen: {}' . format ( expression ) ) return expression elif isinstance ( expression , ( OutputContextField , FoldedContextField ) ) : raise AssertionError ( u'Found unexpected expression of type {}. This should never happen: ' u'{}' . format ( type ( expression ) . __name__ , expression ) ) elif isinstance ( expression , no_op_blocks ) : return expression raise AssertionError ( u'Found unhandled expression of type {}. This should never happen: ' u'{}' . format ( type ( expression ) . __name__ , expression ) ) | Lower Expressions involving non - existent ContextFields to TrueLiteral and simplify result . | 355 | 20 |
227,027 | def _lower_non_existent_context_field_filters ( match_traversals , visitor_fn ) : new_match_traversals = [ ] for match_traversal in match_traversals : new_match_traversal = [ ] for step in match_traversal : if step . where_block is not None : new_filter = step . where_block . visit_and_update_expressions ( visitor_fn ) if new_filter . predicate == TrueLiteral : new_filter = None new_step = step . _replace ( where_block = new_filter ) else : new_step = step new_match_traversal . append ( new_step ) new_match_traversals . append ( new_match_traversal ) return new_match_traversals | Return new match traversals lowering filters involving non - existent ContextFields . | 182 | 16 |
227,028 | def lower_context_field_expressions ( compound_match_query ) : if len ( compound_match_query . match_queries ) == 0 : raise AssertionError ( u'Received CompoundMatchQuery {} with no MatchQuery objects.' . format ( compound_match_query ) ) elif len ( compound_match_query . match_queries ) == 1 : # All ContextFields exist if there is only one MatchQuery # becuase none of the traverses were omitted, and all locations exist (are defined). return compound_match_query else : new_match_queries = [ ] for match_query in compound_match_query . match_queries : match_traversals = match_query . match_traversals present_locations , _ = _get_present_locations ( match_traversals ) current_visitor_fn = partial ( _update_context_field_expression , present_locations ) new_match_traversals = _lower_non_existent_context_field_filters ( match_traversals , current_visitor_fn ) new_match_queries . append ( MatchQuery ( match_traversals = new_match_traversals , folds = match_query . folds , output_block = match_query . output_block , where_block = match_query . where_block , ) ) return CompoundMatchQuery ( match_queries = new_match_queries ) | Lower Expressons involving non - existent ContextFields . | 321 | 12 |
227,029 | def _validate_edges_do_not_have_extra_links ( class_name , properties ) : for property_name , property_descriptor in six . iteritems ( properties ) : if property_name in { EDGE_SOURCE_PROPERTY_NAME , EDGE_DESTINATION_PROPERTY_NAME } : continue if property_descriptor . type_id == PROPERTY_TYPE_LINK_ID : raise IllegalSchemaStateError ( u'Edge class "{}" has a property of type Link that is ' u'not an edge endpoint, this is not allowed: ' u'{}' . format ( class_name , property_name ) ) | Validate that edges do not have properties of Link type that aren t the edge endpoints . | 151 | 19 |
227,030 | def _validate_property_names ( class_name , properties ) : for property_name in properties : if not property_name or property_name . startswith ( ILLEGAL_PROPERTY_NAME_PREFIXES ) : raise IllegalSchemaStateError ( u'Class "{}" has a property with an illegal name: ' u'{}' . format ( class_name , property_name ) ) | Validate that properties do not have names that may cause problems in the GraphQL schema . | 92 | 18 |
227,031 | def _validate_collections_have_default_values ( class_name , property_name , property_descriptor ) : # We don't want properties of collection type having "null" values, since that may cause # unexpected errors during GraphQL query execution and other operations. if property_descriptor . type_id in COLLECTION_PROPERTY_TYPES : if property_descriptor . default is None : raise IllegalSchemaStateError ( u'Class "{}" has a property "{}" of collection type with ' u'no default value.' . format ( class_name , property_name ) ) | Validate that if the property is of collection type it has a specified default value . | 134 | 17 |
227,032 | def get_superclasses_from_class_definition ( class_definition ) : # New-style superclasses definition, supporting multiple-inheritance. superclasses = class_definition . get ( 'superClasses' , None ) if superclasses : return list ( superclasses ) # Old-style superclass definition, single inheritance only. superclass = class_definition . get ( 'superClass' , None ) if superclass : return [ superclass ] # No superclasses are present. return [ ] | Extract a list of all superclass names from a class definition dict . | 106 | 15 |
227,033 | def freeze ( self ) : self . in_connections = frozenset ( self . in_connections ) self . out_connections = frozenset ( self . out_connections ) | Make the SchemaElement s connections immutable . | 42 | 9 |
227,034 | def get_default_property_values ( self , classname ) : schema_element = self . get_element_by_class_name ( classname ) result = { property_name : property_descriptor . default for property_name , property_descriptor in six . iteritems ( schema_element . properties ) } if schema_element . is_edge : # Remove the source/destination properties for edges, if they exist. result . pop ( EDGE_SOURCE_PROPERTY_NAME , None ) result . pop ( EDGE_DESTINATION_PROPERTY_NAME , None ) return result | Return a dict with default values for all properties declared on this class . | 134 | 14 |
227,035 | def _get_property_values_with_defaults ( self , classname , property_values ) : # To uphold OrientDB semantics, make a new dict with all property values set # to their default values, which are None if no default was set. # Then, overwrite its data with the supplied property values. final_values = self . get_default_property_values ( classname ) final_values . update ( property_values ) return final_values | Return the property values for the class with default values applied where needed . | 97 | 14 |
227,036 | def get_element_by_class_name_or_raise ( self , class_name ) : if class_name not in self . _elements : raise InvalidClassError ( u'Class does not exist: {}' . format ( class_name ) ) return self . _elements [ class_name ] | Return the SchemaElement for the specified class name asserting that it exists . | 67 | 15 |
227,037 | def get_vertex_schema_element_or_raise ( self , vertex_classname ) : schema_element = self . get_element_by_class_name_or_raise ( vertex_classname ) if not schema_element . is_vertex : raise InvalidClassError ( u'Non-vertex class provided: {}' . format ( vertex_classname ) ) return schema_element | Return the schema element with the given name asserting that it s of vertex type . | 88 | 16 |
227,038 | def get_edge_schema_element_or_raise ( self , edge_classname ) : schema_element = self . get_element_by_class_name_or_raise ( edge_classname ) if not schema_element . is_edge : raise InvalidClassError ( u'Non-edge class provided: {}' . format ( edge_classname ) ) return schema_element | Return the schema element with the given name asserting that it s of edge type . | 85 | 16 |
227,039 | def validate_is_non_abstract_vertex_type ( self , vertex_classname ) : element = self . get_vertex_schema_element_or_raise ( vertex_classname ) if element . abstract : raise InvalidClassError ( u'Expected a non-abstract vertex class, but {} is abstract' . format ( vertex_classname ) ) | Validate that a vertex classname corresponds to a non - abstract vertex class . | 82 | 16 |
227,040 | def validate_is_non_abstract_edge_type ( self , edge_classname ) : element = self . get_edge_schema_element_or_raise ( edge_classname ) if element . abstract : raise InvalidClassError ( u'Expected a non-abstract vertex class, but {} is abstract' . format ( edge_classname ) ) | Validate that a edge classname corresponds to a non - abstract edge class . | 80 | 16 |
227,041 | def validate_properties_exist ( self , classname , property_names ) : schema_element = self . get_element_by_class_name ( classname ) requested_properties = set ( property_names ) available_properties = set ( schema_element . properties . keys ( ) ) non_existent_properties = requested_properties - available_properties if non_existent_properties : raise InvalidPropertyError ( u'Class "{}" does not have definitions for properties "{}": ' u'{}' . format ( classname , non_existent_properties , property_names ) ) | Validate that the specified property names are indeed defined on the given class . | 124 | 15 |
227,042 | def _split_classes_by_kind ( self , class_name_to_definition ) : for class_name in class_name_to_definition : inheritance_set = self . _inheritance_sets [ class_name ] is_vertex = ORIENTDB_BASE_VERTEX_CLASS_NAME in inheritance_set is_edge = ORIENTDB_BASE_EDGE_CLASS_NAME in inheritance_set if is_vertex and is_edge : raise AssertionError ( u'Class {} appears to be both a vertex and an edge class: ' u'{}' . format ( class_name , inheritance_set ) ) elif is_vertex : self . _vertex_class_names . add ( class_name ) elif is_edge : self . _edge_class_names . add ( class_name ) else : self . _non_graph_class_names . add ( class_name ) # Freeze the classname sets so they cannot be modified again. self . _vertex_class_names = frozenset ( self . _vertex_class_names ) self . _edge_class_names = frozenset ( self . _edge_class_names ) self . _non_graph_class_names = frozenset ( self . _non_graph_class_names ) | Assign each class to the vertex edge or non - graph type sets based on its kind . | 291 | 19 |
227,043 | 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' , None ) qualifier = None validate_supported_property_type_id ( name , type_id ) if type_id == PROPERTY_TYPE_LINK_ID : if class_name not in self . _edge_class_names : raise AssertionError ( u'Found a property of type Link on a non-edge class: ' u'{} {}' . format ( name , class_name ) ) if name not in { EDGE_SOURCE_PROPERTY_NAME , EDGE_DESTINATION_PROPERTY_NAME } : raise AssertionError ( u'Found a property of type Link with an unexpected name: ' u'{} {}' . format ( name , class_name ) ) if linked_class is None : raise AssertionError ( u'Property "{}" is declared with type Link but has no ' u'linked class: {}' . format ( name , property_definition ) ) if linked_class not in self . _vertex_class_names : is_linked_class_abstract = class_name_to_definition [ linked_class ] [ 'abstract' ] all_subclasses_are_vertices = True for subclass in self . _subclass_sets [ linked_class ] : if subclass != linked_class and subclass not in self . vertex_class_names : all_subclasses_are_vertices = False break if not ( is_linked_class_abstract and all_subclasses_are_vertices ) : raise AssertionError ( u'Property "{}" is declared as a Link to class {}, but ' u'that class is neither a vertex nor is it an ' u'abstract class whose subclasses are all vertices!' . format ( name , linked_class ) ) qualifier = linked_class elif type_id in COLLECTION_PROPERTY_TYPES : if linked_class is not None and linked_type is not None : raise AssertionError ( u'Property "{}" unexpectedly has both a linked class and ' u'a linked type: {}' . format ( name , property_definition ) ) elif linked_type is not None and linked_class is None : # No linked class, must be a linked native OrientDB type. validate_supported_property_type_id ( name + ' inner type' , linked_type ) qualifier = linked_type elif linked_class is not None and linked_type is None : # No linked type, must be a linked non-graph user-defined type. if linked_class not in self . _non_graph_class_names : raise AssertionError ( u'Property "{}" is declared as the inner type of ' u'an embedded collection, but is not a non-graph class: ' u'{}' . format ( name , linked_class ) ) qualifier = linked_class else : raise AssertionError ( u'Property "{}" is an embedded collection but has ' u'neither a linked class nor a linked type: ' u'{}' . format ( name , property_definition ) ) default_value = None default_value_string = property_definition . get ( 'defaultValue' , None ) if default_value_string is not None : default_value = parse_default_property_value ( name , type_id , default_value_string ) descriptor = PropertyDescriptor ( type_id = type_id , qualifier = qualifier , default = default_value ) # Sanity-check the descriptor before returning it. _validate_collections_have_default_values ( class_name , name , descriptor ) return descriptor | Return a PropertyDescriptor corresponding to the given OrientDB property definition . | 868 | 15 |
227,044 | 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 else : raise AssertionError ( u'Found a non-abstract edge class with undefined ' u'endpoint types: {}' . format ( edge_element ) ) from_class_name = edge_element . properties [ EDGE_SOURCE_PROPERTY_NAME ] . qualifier to_class_name = edge_element . properties [ EDGE_DESTINATION_PROPERTY_NAME ] . qualifier edge_schema_element = self . _elements [ edge_class_name ] # Link from_class_name with edge_class_name for from_class in self . _subclass_sets [ from_class_name ] : from_schema_element = self . _elements [ from_class ] from_schema_element . out_connections . add ( edge_class_name ) edge_schema_element . in_connections . add ( from_class ) # Link edge_class_name with to_class_name for to_class in self . _subclass_sets [ to_class_name ] : to_schema_element = self . _elements [ to_class ] edge_schema_element . out_connections . add ( to_class ) to_schema_element . in_connections . add ( edge_class_name ) | For each edge link it to the vertex types it connects to each other . | 383 | 15 |
227,045 | def _is_local_filter ( filter_block ) : # We need the "result" value of this function to be mutated within the "visitor_fn". # Since we support both Python 2 and Python 3, we can't use the "nonlocal" keyword here: # https://www.python.org/dev/peps/pep-3104/ # Instead, we use a dict to store the value we need mutated, since the "visitor_fn" # can mutate state in the parent scope, but not rebind variables in it without "nonlocal". # TODO(predrag): Revisit this if we drop support for Python 2. result = { 'is_local_filter' : True } filter_predicate = filter_block . predicate def visitor_fn ( expression ) : """Expression visitor function that looks for uses of non-local fields.""" non_local_expression_types = ( ContextField , ContextFieldExistence ) if isinstance ( expression , non_local_expression_types ) : result [ 'is_local_filter' ] = False # Don't change the expression. return expression filter_predicate . visit_and_update ( visitor_fn ) return result [ 'is_local_filter' ] | Return True if the Filter block references no non - local fields and False otherwise . | 267 | 16 |
227,046 | def _calculate_type_bound_at_step ( match_step ) : current_type_bounds = [ ] if isinstance ( match_step . root_block , QueryRoot ) : # The QueryRoot start class is a type bound. current_type_bounds . extend ( match_step . root_block . start_class ) if match_step . coerce_type_block is not None : # The CoerceType target class is also a type bound. current_type_bounds . extend ( match_step . coerce_type_block . target_class ) if current_type_bounds : # A type bound exists. Assert that there is exactly one bound, defined in precisely one way. return get_only_element_from_collection ( current_type_bounds ) else : # No type bound exists at this MATCH step. return None | Return the GraphQL type bound at the given step or None if no bound is given . | 191 | 18 |
227,047 | 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 {}: {} vs {} ' u'for query {}' . format ( location , previous_type_bound , current_type_bound , match_query ) ) | Ensure that the two bounds either are an exact match or one of them is None . | 122 | 18 |
227,048 | 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_step . as_block . location if current_step_location in eligible_locations : # This location is eligible. We need to make sure it has an associated type bound, # so that it produces a "class:" clause that will make it a valid query start # location. It either already has such a type bound, or we can use the type # implied by the GraphQL query structure to add one. current_type_bound = _calculate_type_bound_at_step ( match_step ) previous_type_bound = eligible_location_types . get ( current_step_location , None ) if current_type_bound is None : current_type_bound = location_types [ current_step_location ] . name new_coerce_type_block = CoerceType ( { current_type_bound } ) new_step = match_step . _replace ( coerce_type_block = new_coerce_type_block ) else : # There is a type bound here. We simply ensure that the bound is not conflicting # with any other type bound at a different MATCH step with the same location. _assert_type_bounds_are_not_conflicting ( current_type_bound , previous_type_bound , current_step_location , match_query ) # Record the deduced type bound, so that if we encounter this location again, # we ensure that we again infer the same type bound. eligible_location_types [ current_step_location ] = current_type_bound else : # This function may only be called if there are no preferred locations. Since this # location cannot be preferred, and is not eligible, it must be ineligible. # No action is necessary in this case. pass new_traversal . append ( new_step ) new_match_traversals . append ( new_traversal ) return match_query . _replace ( match_traversals = new_match_traversals ) | Return a MATCH query where all eligible locations are valid as query start locations . | 519 | 16 |
227,049 | 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_classification if preferred_locations : # Convert all eligible locations into non-eligible ones, by removing # their "class:" clause. The "class:" clause is provided either by having # a QueryRoot block or a CoerceType block in the MatchStep corresponding # to the location. We remove it by converting the class check into # an "INSTANCEOF" Filter block, which OrientDB is unable to optimize away. new_query = _expose_only_preferred_locations ( match_query , location_types , coerced_locations , preferred_locations , eligible_locations ) elif eligible_locations : # Make sure that all eligible locations have a "class:" clause by adding # a CoerceType block that is a no-op as guaranteed by the schema. This merely # ensures that OrientDB is able to use each of these locations as a query start point, # and will choose the one whose class is of lowest cardinality. new_query = _expose_all_eligible_locations ( match_query , location_types , eligible_locations ) else : raise AssertionError ( u'This query has no preferred or eligible query start locations. ' u'This is almost certainly a bug: {}' . format ( match_query ) ) new_queries . append ( new_query ) return compound_match_query . _replace ( match_queries = new_queries ) | Ensure that OrientDB only considers desirable query start points in query planning . | 390 | 15 |
227,050 | 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_list ' u'(function should never be called with empty list): ' u'{}' . format ( expression_list ) ) elif len ( expression_list ) == 1 : return expression_list [ 0 ] else : remaining_conjunction = _expression_list_to_conjunction ( expression_list [ 1 : ] ) return BinaryComposition ( u'&&' , expression_list [ 0 ] , remaining_conjunction ) | Return an Expression that is the && of all the expressions in the given list . | 188 | 16 |
227,051 | 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 ( expression . right ) : yield element else : yield expression | Return a generator for expressions that are connected by && s in the given expression . | 93 | 16 |
227,052 | 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 , BinaryComposition ) , expression . operator in between_operators , isinstance ( expression . left , LocalField ) or isinstance ( expression . right , LocalField ) ) ) : if isinstance ( expression . right , LocalField ) : new_operator = inverse_operator [ expression . operator ] new_expression = BinaryComposition ( new_operator , expression . right , expression . left ) else : new_expression = expression field_name = new_expression . left . field_name expressions_dict = local_field_to_expressions . setdefault ( field_name , { } ) expressions_dict . setdefault ( new_expression . operator , [ ] ) . append ( new_expression ) else : remaining_expression_list . append ( expression ) return local_field_to_expressions , remaining_expression_list | Construct a mapping from local fields to specified operators and corresponding expressions . | 269 | 13 |
227,053 | 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 ) ) elif len ( expression_list ) == 1 : return base_expression else : between_operators = ( u'<=' , u'>=' ) local_field_to_expressions , new_expression_list = _construct_field_operator_expression_dict ( expression_list ) lowering_occurred = False for field_name in local_field_to_expressions : expressions_dict = local_field_to_expressions [ field_name ] if all ( operator in expressions_dict and len ( expressions_dict [ operator ] ) == 1 for operator in between_operators ) : field = LocalField ( field_name ) lower_bound = expressions_dict [ u'>=' ] [ 0 ] . right upper_bound = expressions_dict [ u'<=' ] [ 0 ] . right new_expression_list . appendleft ( BetweenClause ( field , lower_bound , upper_bound ) ) lowering_occurred = True else : for expression in expressions_dict . values ( ) : new_expression_list . extend ( expression ) if lowering_occurred : return _expression_list_to_conjunction ( list ( new_expression_list ) ) else : return base_expression | Return a new expression with any eligible comparisons lowered to between clauses . | 348 | 13 |
227,054 | 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_between ( expression ) ) new_traversal . append ( step . _replace ( where_block = new_where_block ) ) else : new_traversal . append ( step ) new_match_traversals . append ( new_traversal ) return match_query . _replace ( match_traversals = new_match_traversals ) | Return a new MatchQuery with all eligible comparison filters lowered to between clauses . | 175 | 15 |
227,055 | def _ensure_arguments_are_provided ( expected_types , arguments ) : # This function only checks that the arguments were specified, # and does not check types. Type checking is done as part of the actual formatting step. 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_names - expected_arg_names raise GraphQLInvalidArgumentError ( u'Missing or unexpected arguments found: ' u'missing {}, unexpected ' u'{}' . format ( missing_args , unexpected_args ) ) | Ensure that all arguments expected by the query were actually provided . | 168 | 13 |
227,056 | 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 == GREMLIN_LANGUAGE : return insert_arguments_into_gremlin_query ( compilation_result , arguments ) elif compilation_result . language == SQL_LANGUAGE : return insert_arguments_into_sql_query ( compilation_result , arguments ) else : raise AssertionError ( u'Unrecognized language in compilation result: ' u'{}' . format ( compilation_result ) ) | Insert the arguments into the compiled GraphQL query to form a complete query . | 172 | 15 |
227,057 | 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 . start_class : validate_safe_string ( cls ) | Ensure that the QueryRoot block is valid . | 107 | 10 |
227,058 | 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 . target_class : validate_safe_string ( cls ) | Ensure that the CoerceType block is valid . | 107 | 12 |
227,059 | 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 TypeError ( u'Expected Expression values in the fields dict, got: ' u'{} -> {}' . format ( key , value ) ) | Ensure that the ConstructResult block is valid . | 119 | 10 |
227,060 | 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 . | 53 | 9 |
227,061 | 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 . | 63 | 10 |
227,062 | 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 . | 85 | 15 |
227,063 | 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 . | 75 | 8 |
227,064 | 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_fields = _map_query_path_to_outputs ( construct_result , query_path_to_location_info ) block_index_to_location = _map_block_index_to_location ( ir_blocks ) # perform lowering steps ir_blocks = lower_unary_transformations ( ir_blocks ) ir_blocks = lower_unsupported_metafield_expressions ( ir_blocks ) # iteratively construct SqlTree query_path_to_node = { } query_path_to_filters = { } tree_root = None for index , block in enumerate ( ir_blocks ) : if isinstance ( block , constants . SKIPPABLE_BLOCK_TYPES ) : continue location = block_index_to_location [ index ] if isinstance ( block , ( blocks . QueryRoot , ) ) : query_path = location . query_path if tree_root is not None : raise AssertionError ( u'Encountered QueryRoot {} but tree root is already set to {} during ' u'construction of SQL query tree for IR blocks {} with query ' u'metadata table {}' . format ( block , tree_root , ir_blocks , query_metadata_table ) ) tree_root = SqlNode ( block = block , query_path = query_path ) query_path_to_node [ query_path ] = tree_root elif isinstance ( block , blocks . Filter ) : query_path_to_filters . setdefault ( query_path , [ ] ) . append ( block ) else : raise AssertionError ( u'Unsupported block {} unexpectedly passed validation for IR blocks ' u'{} with query metadata table {} .' . format ( block , ir_blocks , query_metadata_table ) ) return SqlQueryTree ( tree_root , query_path_to_location_info , query_path_to_output_fields , query_path_to_filters , query_path_to_node ) | Lower the IR blocks into a form that can be represented by a SQL query . | 535 | 16 |
227,065 | 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 query metadata table is {}.' . format ( query_metadata_table ) ) construct_result = _get_construct_result ( ir_blocks ) unsupported_blocks = [ ] unsupported_fields = [ ] for block in ir_blocks [ : - 1 ] : if isinstance ( block , constants . SUPPORTED_BLOCK_TYPES ) : continue if isinstance ( block , constants . SKIPPABLE_BLOCK_TYPES ) : continue unsupported_blocks . append ( block ) for field_name , field in six . iteritems ( construct_result . fields ) : if not isinstance ( field , constants . SUPPORTED_OUTPUT_EXPRESSION_TYPES ) : unsupported_fields . append ( ( field_name , field ) ) elif field . location . field in constants . UNSUPPORTED_META_FIELDS : unsupported_fields . append ( ( field_name , field ) ) if len ( unsupported_blocks ) > 0 or len ( unsupported_fields ) > 0 : raise NotImplementedError ( u'Encountered unsupported blocks {} and unsupported fields {} during construction of ' u'SQL query tree for IR blocks {} with query metadata table {}.' . format ( unsupported_blocks , unsupported_fields , ir_blocks , query_metadata_table ) ) | Validate that all IR blocks and ConstructResult fields passed to the backend are supported . | 362 | 17 |
227,066 | 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 . | 83 | 12 |
227,067 | 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 : # make sure the stored location information equals the new location information # for the fields the SQL backend requires. equivalent_location_info = query_path_to_location_info [ location . query_path ] if not _location_infos_equal ( location_info , equivalent_location_info ) : raise AssertionError ( u'Differing LocationInfos at query_path {} between {} and {}. Expected ' u'parent_location.query_path, optional_scopes_depth, recursive_scopes_depth ' u'and types to be equal for LocationInfos sharing the same query path.' . format ( location . query_path , location_info , equivalent_location_info ) ) query_path_to_location_info [ location . query_path ] = location_info return query_path_to_location_info | Create a map from each query path to a LocationInfo at that path . | 260 | 15 |
227,068 | 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_depth_equal = ( left . optional_scopes_depth == right . optional_scopes_depth ) parent_query_paths_equal = ( ( left . parent_location is None and right . parent_location is None ) or ( left . parent_location . query_path == right . parent_location . query_path ) ) recursive_scopes_depths_equal = ( left . recursive_scopes_depth == right . recursive_scopes_depth ) types_equal = left . type == right . type return all ( [ optional_scopes_depth_equal , parent_query_paths_equal , recursive_scopes_depths_equal , types_equal , ] ) | Return True if LocationInfo objects are equivalent for the SQL backend False otherwise . | 236 | 15 |
227,069 | 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 . SqlOutput ( field_name = field_name , output_name = output_name , graphql_type = query_path_to_location_info [ output_query_path ] . type ) output_field_mapping = query_path_to_output_fields . setdefault ( output_query_path , [ ] ) output_field_mapping . append ( output_field_info ) return query_path_to_output_fields | Assign the output fields of a ConstructResult block to their respective query_path . | 187 | 17 |
227,070 | def _map_block_index_to_location ( ir_blocks ) : block_index_to_location = { } # MarkLocation blocks occur after the blocks related to that location. # The core approach here is to buffer blocks until their MarkLocation is encountered # after which all buffered blocks can be associated with the encountered MarkLocation.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 ] raise AssertionError ( u'Unexpectedly encountered global operations before mapping blocks ' u'{} to their respective locations.' . format ( unassociated_blocks ) ) break current_block_ixs . append ( num ) if isinstance ( ir_block , blocks . MarkLocation ) : for ix in current_block_ixs : block_index_to_location [ ix ] = ir_block . location current_block_ixs = [ ] return block_index_to_location | Associate each IR block with its corresponding location by index . | 257 | 12 |
227,071 | def lower_unary_transformations ( ir_blocks ) : def visitor_fn ( expression ) : """Raise error if current expression is a UnaryTransformation.""" 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 ( expression , ir_blocks ) ) new_ir_blocks = [ block . visit_and_update_expressions ( visitor_fn ) for block in ir_blocks ] return new_ir_blocks | Raise exception if any unary transformation block encountered . | 130 | 11 |
227,072 | def lower_unsupported_metafield_expressions ( ir_blocks ) : def visitor_fn ( expression ) : """Visitor function raising exception for any unsupported metafield.""" 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 metafield {} in LocalField {} during construction of ' u'SQL query tree for IR blocks {}.' . format ( constants . UNSUPPORTED_META_FIELDS [ expression . field_name ] , expression , ir_blocks ) ) new_ir_blocks = [ block . visit_and_update_expressions ( visitor_fn ) for block in ir_blocks ] return new_ir_blocks | Raise exception if an unsupported metafield is encountered in any LocalField expression . | 180 | 17 |
227,073 | 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_graphql_schema_from_schema_graph ( schema_graph , class_to_field_type_overrides , hidden_classes ) | Construct a GraphQL schema from an OrientDB schema . | 136 | 11 |
227,074 | 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 . | 56 | 31 |
227,075 | 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 = perform_login ( request , user ) return get_ok_response ( 'Login successful' , extra_data = extra_data ) | Logs in the user via given login and password . | 112 | 11 |
227,076 | 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 . auth_token . delete ( ) except Token . DoesNotExist : raise BadRequest ( 'Cannot remove non-existent token' ) return get_ok_response ( 'Logout successful' ) | Logs out the user . returns an error if the user is not authenticated . | 131 | 16 |
227,077 | 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 . | 71 | 26 |
227,078 | 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 ( raise_exception = True ) serializer . save ( ) else : # request.method == 'GET': serializer = serializer_class ( instance = request . user ) return Response ( serializer . data ) | Get or set user profile . | 131 | 6 |
227,079 | 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 ( 'VERIFICATION_FLAG_FIELD' ) kwargs [ verification_flag_field ] = False email_field = get_user_setting ( 'EMAIL_FIELD' ) if ( email_field not in serializer . validated_data or not serializer . validated_data [ email_field ] ) : raise BadRequest ( "User without email cannot be verified" ) user = serializer . save ( * * kwargs ) output_serializer_class = registration_settings . REGISTER_OUTPUT_SERIALIZER_CLASS # noqa: E501 output_serializer = output_serializer_class ( instance = user ) user_data = output_serializer . data if registration_settings . REGISTER_VERIFICATION_ENABLED : signer = RegisterSigner ( { 'user_id' : user . pk , } , request = request ) template_config = ( registration_settings . REGISTER_VERIFICATION_EMAIL_TEMPLATES ) send_verification_notification ( user , signer , template_config ) return Response ( user_data , status = status . HTTP_201_CREATED ) | Register new user . | 335 | 4 |
227,080 | 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 . | 81 | 6 |
227,081 | 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 . | 82 | 11 |
227,082 | 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_field in get_login_fields ( ) : user = get_user_by_lookup_dict ( { login_field : login } , default = None , require_verified = False ) if user : break if not user : raise UserNotFound ( ) signer = ResetPasswordSigner ( { 'user_id' : user . pk , } , request = request ) template_config = ( registration_settings . RESET_PASSWORD_VERIFICATION_EMAIL_TEMPLATES ) send_verification_notification ( user , signer , template_config ) return get_ok_response ( 'Reset link sent' ) | Send email with reset password link . | 229 | 7 |
227,083 | 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_settings . REGISTER_EMAIL_VERIFICATION_ENABLED : signer = RegisterEmailSigner ( { 'user_id' : user . pk , 'email' : email , } , request = request ) send_verification_notification ( user , signer , template_config , email = email ) else : email_field = get_user_setting ( 'EMAIL_FIELD' ) setattr ( user , email_field , email ) user . save ( ) return get_ok_response ( 'Register email link email sent' ) | Register new email . | 203 | 4 |
227,084 | def _is_colorbar_heuristic ( obj ) : # TODO come up with something more accurate here # Might help: # TODO Are the colorbars exactly the l.collections.PolyCollection's? try : aspect = float ( obj . get_aspect ( ) ) except ValueError : # e.g., aspect == 'equal' return False # Assume that something is a colorbar if and only if the ratio is above 5.0 # and there are no ticks on the corresponding axis. This isn't always true, # though: The ratio of a color can be freely adjusted by the aspect # keyword, e.g., # # plt.colorbar(im, aspect=5) # 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 . | 208 | 12 |
227,085 | 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_map ( cmap , data ) | Converts a color map as given in matplotlib to a color map as represented in PGFPlots . | 110 | 23 |
227,086 | 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 . | 70 | 12 |
227,087 | 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 . | 56 | 19 |
227,088 | 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" ] : # Make sure not to overwrite anything. file_exists = True while file_exists : data [ nb_key ] = data [ nb_key ] + 1 filename , name = _gen_filename ( data , nb_key , ext ) file_exists = os . path . isfile ( filename ) else : data [ nb_key ] = data [ nb_key ] + 1 filename , name = _gen_filename ( data , nb_key , ext ) if data [ "rel data path" ] : rel_filepath = posixpath . join ( data [ "rel data path" ] , name ) else : rel_filepath = name return filename , rel_filepath | Returns an available filename . | 215 | 5 |
227,089 | def mpl_linestyle2pgfplots_linestyle ( line_style , line = None ) : # linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) where onoffseq # is an even length tuple of on and off ink in points. # # solid: [(None, None), (None, None), ..., (None, None)] # dashed: (0, (6.0, 6.0)) # dotted: (0, (1.0, 3.0)) # dashdot: (0, (3.0, 5.0, 1.0, 5.0)) 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 off {}pt on {}pt off {}pt" . format ( * line_style [ 1 ] ) if isinstance ( line , mpl . lines . Line2D ) and line . is_dashed ( ) : # see matplotlib.lines.Line2D.set_dashes # get defaults default_dashOffset , default_dashSeq = mpl . lines . _get_dash_pattern ( line_style ) # get dash format of line under test dashSeq = line . _us_dashSeq dashOffset = line . _us_dashOffset lst = list ( ) if dashSeq != default_dashSeq : # generate own dash sequence format_string = " " . join ( len ( dashSeq ) // 2 * [ "on {}pt off {}pt" ] ) lst . append ( "dash pattern=" + format_string . format ( * dashSeq ) ) if dashOffset != default_dashOffset : lst . append ( "dash phase={}pt" . format ( dashOffset ) ) if len ( lst ) > 0 : return ", " . join ( lst ) return { "" : None , "None" : None , "none" : None , # happens when using plt.boxplot() "-" : "solid" , "solid" : "solid" , ":" : "dotted" , "--" : "dashed" , "-." : "dash pattern=on 1pt off 3pt on 3pt off 3pt" , } [ line_style ] | Translates a line style of matplotlib to the corresponding style in PGFPlots . | 561 | 20 |
227,090 | def draw_quadmesh ( data , obj ) : content = [ ] # Generate file name for current object filename , rel_filepath = files . new_filename ( data , "img" , ".png" ) # Get the dpi for rendering and store the original dpi of the figure dpi = data [ "dpi" ] fig_dpi = obj . figure . get_dpi ( ) obj . figure . set_dpi ( dpi ) # Render the object and save as png file from matplotlib . backends . backend_agg import RendererAgg cbox = obj . get_clip_box ( ) width = int ( round ( cbox . extents [ 2 ] ) ) height = int ( round ( cbox . extents [ 3 ] ) ) ren = RendererAgg ( width , height , dpi ) obj . draw ( ren ) # Generate a image from the render buffer image = Image . frombuffer ( "RGBA" , ren . get_canvas_width_height ( ) , ren . buffer_rgba ( ) , "raw" , "RGBA" , 0 , 1 ) # Crop the image to the actual content (removing the the regions otherwise # used for axes, etc.) # 'image.crop' expects the crop box to specify the left, upper, right, and # lower pixel. 'cbox.extents' gives the left, lower, right, and upper # pixel. box = ( int ( round ( cbox . extents [ 0 ] ) ) , 0 , int ( round ( cbox . extents [ 2 ] ) ) , int ( round ( cbox . extents [ 3 ] - cbox . extents [ 1 ] ) ) , ) cropped = image . crop ( box ) cropped . save ( filename ) # Restore the original dpi of the figure obj . figure . set_dpi ( fig_dpi ) # write the corresponding information to the TikZ file extent = obj . axes . get_xlim ( ) + obj . axes . get_ylim ( ) # Explicitly use \pgfimage as includegrapics command, as the default # \includegraphics fails unexpectedly in some cases ff = data [ "float format" ] content . append ( ( "\\addplot graphics [includegraphics cmd=\\pgfimage," "xmin=" + ff + ", xmax=" + ff + ", " "ymin=" + ff + ", ymax=" + ff + "] {{{}}};\n" ) . format ( * ( extent + ( rel_filepath , ) ) ) ) return data , content | Returns the PGFPlots code for an graphics environment holding a rendering of the object . | 562 | 18 |
227,091 | def draw_patch ( data , obj ) : # Gather the draw options. 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 ) : # rectangle specialization return _draw_rectangle ( data , obj , draw_options ) elif isinstance ( obj , mpl . patches . Ellipse ) : # ellipse specialization return _draw_ellipse ( data , obj , draw_options ) # regular patch data , path_command , _ , _ = mypath . draw_path ( data , obj . get_path ( ) , draw_options = draw_options ) return data , path_command | Return the PGFPlots code for patches . | 189 | 10 |
227,092 | def _draw_rectangle ( data , obj , draw_options ) : # Objects with labels are plot objects (from bar charts, etc). Even those without # labels explicitly set have a label of "_nolegend_". Everything else should be # skipped because they likely correspong to axis/legend objects which are handled by # PGFPlots label = obj . get_label ( ) if label == "" : return data , [ ] # Get actual label, bar charts by default only give rectangles labels of # "_nolegend_". See <https://stackoverflow.com/q/35881290/353337>. 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 = labelsFound [ 0 ] left_lower_x = obj . get_x ( ) left_lower_y = obj . get_y ( ) ff = data [ "float format" ] cont = ( "\\draw[{}] (axis cs:" + ff + "," + ff + ") " "rectangle (axis cs:" + ff + "," + ff + ");\n" ) . format ( "," . join ( draw_options ) , left_lower_x , left_lower_y , left_lower_x + obj . get_width ( ) , left_lower_y + obj . get_height ( ) , ) if label != "_nolegend_" and label not in data [ "rectangle_legends" ] : data [ "rectangle_legends" ] . add ( label ) cont += "\\addlegendimage{{ybar,ybar legend,{}}};\n" . format ( "," . join ( draw_options ) ) cont += "\\addlegendentry{{{}}}\n\n" . format ( label ) return data , cont | Return the PGFPlots code for rectangles . | 433 | 11 |
227,093 | def _draw_ellipse ( data , obj , draw_options ) : if isinstance ( obj , mpl . patches . Circle ) : # circle specialization 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 . format ( obj . angle , x , y ) ) cont = ( "\\draw[{}] (axis cs:" + ff + "," + ff + ") ellipse (" + ff + " and " + ff + ");\n" ) . format ( "," . join ( draw_options ) , x , y , 0.5 * obj . width , 0.5 * obj . height ) return data , cont | Return the PGFPlots code for ellipses . | 198 | 12 |
227,094 | 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 . | 95 | 10 |
227,095 | def draw_image ( data , obj ) : content = [ ] filename , rel_filepath = files . new_filename ( data , "img" , ".png" ) # store the image as in a file img_array = obj . get_array ( ) dims = img_array . shape if len ( dims ) == 2 : # the values are given as one real number: look at cmap clims = obj . get_clim ( ) mpl . pyplot . imsave ( fname = filename , arr = img_array , cmap = obj . get_cmap ( ) , vmin = clims [ 0 ] , vmax = clims [ 1 ] , origin = obj . origin , ) else : # RGB (+alpha) information at each point assert len ( dims ) == 3 and dims [ 2 ] in [ 3 , 4 ] # convert to PIL image if obj . origin == "lower" : img_array = numpy . flipud ( img_array ) # Convert mpl image to PIL image = PIL . Image . fromarray ( numpy . uint8 ( img_array * 255 ) ) # If the input image is PIL: # image = PIL.Image.fromarray(img_array) image . save ( filename , origin = obj . origin ) # write the corresponding information to the TikZ file extent = obj . get_extent ( ) # the format specification will only accept tuples if not isinstance ( extent , tuple ) : extent = tuple ( extent ) # Explicitly use \pgfimage as includegrapics command, as the default # \includegraphics fails unexpectedly in some cases ff = data [ "float format" ] content . append ( ( "\\addplot graphics [includegraphics cmd=\\pgfimage," "xmin=" + ff + ", xmax=" + ff + ", " "ymin=" + ff + ", ymax=" + ff + "] {{{}}};\n" ) . format ( * ( extent + ( rel_filepath , ) ) ) ) return data , content | Returns the PGFPlots code for an image environment . | 448 | 12 |
227,096 | 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 ] return None | Check if line is in legend . | 103 | 7 |
227,097 | 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 . | 99 | 13 |
227,098 | 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{fontspec} % This line only for XeLaTeX and LuaLaTeX" ) print ( "\\usepackage{pgfplots}" ) if tikzlibs : print ( "\\usetikzlibrary{" + tikzlibs + "}" ) if pgfplotslibs : print ( "\\usepgfplotslibrary{" + pgfplotslibs + "}" ) print ( 70 * "=" ) return | Prints message to screen indicating the use of PGFPlots and its libraries . | 212 | 17 |
227,099 | 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 | 45 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.