_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q228200 | Builder.add_from_file | train | def add_from_file(self, fpath):
"""Load ui definition from file."""
if self.tree is None:
base, name = os.path.split(fpath)
self.add_resource_path(base)
self.tree = tree = ET.parse(fpath)
self.root = tree.getroot()
self.objects = {}
els... | python | {
"resource": ""
} |
q228201 | Builder.add_from_string | train | def add_from_string(self, strdata):
"""Load ui definition from string."""
if self.tree is None:
self.tree = tree = ET.ElementTree(ET.fromstring(strdata))
self.root = tree.getroot()
self.objects = {}
else:
# TODO: append to current tree
... | python | {
"resource": ""
} |
q228202 | Builder.add_from_xmlnode | train | def add_from_xmlnode(self, element):
"""Load ui definition from xml.etree.Element node."""
if self.tree is None:
root = ET.Element('interface')
root.append(element)
self.tree = tree = ET.ElementTree(root)
self.root = tree.getroot()
self.objects... | python | {
"resource": ""
} |
q228203 | Builder.get_object | train | def get_object(self, name, master=None):
"""Find and create the widget named name.
Use master as parent. If widget was already created, return
that instance."""
widget = None
if name in self.objects:
widget = self.objects[name].widget
else:
xpath =... | python | {
"resource": ""
} |
q228204 | Builder._realize | train | def _realize(self, master, element):
"""Builds a widget from xml element using master as parent."""
data = data_xmlnode_to_dict(element, self.translator)
cname = data['class']
uniqueid = data['id']
if cname not in CLASS_MAP:
self._import_class(cname)
if cna... | python | {
"resource": ""
} |
q228205 | Builder.connect_callbacks | train | def connect_callbacks(self, callbacks_bag):
"""Connect callbacks specified in callbacks_bag with callbacks
defined in the ui definition.
Return a list with the name of the callbacks not connected.
"""
notconnected = []
for wname, builderobj in self.objects.items():
... | python | {
"resource": ""
} |
q228206 | SelectTool._start_selecting | train | def _start_selecting(self, event):
"""Comienza con el proceso de seleccion."""
self._selecting = True
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
self._sstart = (x, y)
if not self._sobject:
self._sobject = canvas.creat... | python | {
"resource": ""
} |
q228207 | SelectTool._keep_selecting | train | def _keep_selecting(self, event):
"""Continua con el proceso de seleccion.
Crea o redimensiona el cuadro de seleccion de acuerdo con
la posicion del raton."""
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
canvas.coords(self._sobject... | python | {
"resource": ""
} |
q228208 | SelectTool._finish_selecting | train | def _finish_selecting(self, event):
"""Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion."""
self._selecting = False
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
... | python | {
"resource": ""
} |
q228209 | matrix_coords | train | def matrix_coords(rows, cols, rowh, colw, ox=0, oy=0):
"Generate coords for a matrix of rects"
for i, f, c in rowmajor(rows, cols):
x = ox + c * colw
y = oy + f * rowh
x1 = x + colw
y1 = y + rowh
yield (i, x, y, x1, y1) | python | {
"resource": ""
} |
q228210 | ArrayVar.get | train | def get(self):
'''Return a dictionary that represents the Tcl array'''
value = {}
for (elementname, elementvar) in self._elementvars.items():
value[elementname] = elementvar.get()
return value | python | {
"resource": ""
} |
q228211 | EditableTreeview.yview | train | def yview(self, *args):
"""Update inplace widgets position when doing vertical scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.yview(self, *args) | python | {
"resource": ""
} |
q228212 | EditableTreeview.xview | train | def xview(self, *args):
"""Update inplace widgets position when doing horizontal scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.xview(self, *args) | python | {
"resource": ""
} |
q228213 | EditableTreeview.__check_focus | train | def __check_focus(self, event):
"""Checks if the focus has changed"""
#print('Event:', event.type, event.x, event.y)
changed = False
if not self._curfocus:
changed = True
elif self._curfocus != self.focus():
self.__clear_inplace_widgets()
chang... | python | {
"resource": ""
} |
q228214 | EditableTreeview.__focus | train | def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inpla... | python | {
"resource": ""
} |
q228215 | EditableTreeview.__clear_inplace_widgets | train | def __clear_inplace_widgets(self):
"""Remove all inplace edit widgets."""
cols = self.__get_display_columns()
#print('Clear:', cols)
for c in cols:
if c in self._inplace_widgets:
widget = self._inplace_widgets[c]
widget.place_forget()
... | python | {
"resource": ""
} |
q228216 | CustomInstall.run | train | def run(self):
"""Run parent install, and then save the install dir in the script."""
install.run(self)
#
# Remove old pygubu.py from scripts path if exists
spath = os.path.join(self.install_scripts, 'pygubu')
for ext in ('.py', '.pyw'):
filename = spath + ex... | python | {
"resource": ""
} |
q228217 | PropertiesEditor.hide_all | train | def hide_all(self):
"""Hide all properties from property editor."""
self.current = None
for _v, (label, widget) in self._propbag.items():
label.grid_remove()
widget.grid_remove() | python | {
"resource": ""
} |
q228218 | BuilderObject._get_init_args | train | def _get_init_args(self):
"""Creates dict with properties marked as readonly"""
args = {}
for rop in self.ro_properties:
if rop in self.properties:
args[rop] = self.properties[rop]
return args | python | {
"resource": ""
} |
q228219 | OnCanvasMenuPreview._calculate_menu_wh | train | def _calculate_menu_wh(self):
""" Calculate menu widht and height."""
w = iw = 50
h = ih = 0
# menu.index returns None if there are no choices
index = self._menu.index(tk.END)
index = index if index is not None else 0
count = index + 1
# First calculate u... | python | {
"resource": ""
} |
q228220 | PreviewHelper._over_resizer | train | def _over_resizer(self, x, y):
"Returns True if mouse is over a resizer"
over_resizer = False
c = self.canvas
ids = c.find_overlapping(x, y, x, y)
if ids:
o = ids[0]
tags = c.gettags(o)
if 'resizer' in tags:
over_resizer = True... | python | {
"resource": ""
} |
q228221 | PreviewHelper.resize_preview | train | def resize_preview(self, dw, dh):
"Resizes preview that is currently dragged"
# identify preview
if self._objects_moving:
id_ = self._objects_moving[0]
tags = self.canvas.gettags(id_)
for tag in tags:
if tag.startswith('preview_'):
... | python | {
"resource": ""
} |
q228222 | PreviewHelper.move_previews | train | def move_previews(self):
"Move previews after a resize event"
# calculate new positions
min_y = self._calc_preview_ypos()
for idx, (key, p) in enumerate(self.previews.items()):
new_dy = min_y[idx] - p.y
self.previews[key].move_by(0, new_dy)
self._update_c... | python | {
"resource": ""
} |
q228223 | PreviewHelper._calc_preview_ypos | train | def _calc_preview_ypos(self):
"Calculates the previews positions on canvas"
y = 10
min_y = [y]
for k, p in self.previews.items():
y += p.height() + self.padding
min_y.append(y)
return min_y | python | {
"resource": ""
} |
q228224 | PreviewHelper._get_slot | train | def _get_slot(self):
"Returns the next coordinates for a preview"
x = y = 10
for k, p in self.previews.items():
y += p.height() + self.padding
return x, y | python | {
"resource": ""
} |
q228225 | StockImage.clear_cache | train | def clear_cache(cls):
"""Call this before closing tk root"""
#Prevent tkinter errors on python 2 ??
for key in cls._cached:
cls._cached[key] = None
cls._cached = {} | python | {
"resource": ""
} |
q228226 | StockImage.register | train | def register(cls, key, filename):
"""Register a image file using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'custom', 'filename': filename}
logger.info('%s registered as %s' % (filename, key)) | python | {
"resource": ""
} |
q228227 | StockImage.register_from_data | train | def register_from_data(cls, key, format, data):
"""Register a image data using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'data', 'data': data, 'format': format }
logger.info('%s registered as %s' % ('data',... | python | {
"resource": ""
} |
q228228 | StockImage.register_created | train | def register_created(cls, key, image):
"""Register an already created image using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'created', 'image': image}
logger.info('%s registered as %s' % ('data', key)) | python | {
"resource": ""
} |
q228229 | StockImage._load_image | train | def _load_image(cls, rkey):
"""Load image from file or return the cached instance."""
v = cls._stock[rkey]
img = None
itype = v['type']
if itype in ('stock', 'data'):
img = tk.PhotoImage(format=v['format'], data=v['data'])
elif itype == 'created':
... | python | {
"resource": ""
} |
q228230 | StockImage.get | train | def get(cls, rkey):
"""Get image previously registered with key rkey.
If key not exist, raise StockImageException
"""
if rkey in cls._cached:
logger.info('Resource %s is in cache.' % rkey)
return cls._cached[rkey]
if rkey in cls._stock:
img = ... | python | {
"resource": ""
} |
q228231 | WidgetsTreeEditor.config_treeview | train | def config_treeview(self):
"""Sets treeview columns and other params"""
tree = self.treeview
tree.bind('<Double-1>', self.on_treeview_double_click)
tree.bind('<<TreeviewSelect>>', self.on_treeview_select, add='+') | python | {
"resource": ""
} |
q228232 | WidgetsTreeEditor.get_toplevel_parent | train | def get_toplevel_parent(self, treeitem):
"""Returns the top level parent for treeitem."""
tv = self.treeview
toplevel_items = tv.get_children()
item = treeitem
while not (item in toplevel_items):
item = tv.parent(item)
return item | python | {
"resource": ""
} |
q228233 | WidgetsTreeEditor.draw_widget | train | def draw_widget(self, item):
"""Create a preview of the selected treeview item"""
if item:
self.filter_remove(remember=True)
selected_id = self.treedata[item]['id']
item = self.get_toplevel_parent(item)
widget_id = self.treedata[item]['id']
wcl... | python | {
"resource": ""
} |
q228234 | WidgetsTreeEditor.on_treeview_delete_selection | train | def on_treeview_delete_selection(self, event=None):
"""Removes selected items from treeview"""
tv = self.treeview
selection = tv.selection()
# Need to remove filter
self.filter_remove(remember=True)
toplevel_items = tv.get_children()
parents_to_redraw = set()
... | python | {
"resource": ""
} |
q228235 | WidgetsTreeEditor.tree_to_xml | train | def tree_to_xml(self):
"""Traverses treeview and generates a ElementTree object"""
# Need to remove filter or hidden items will not be saved.
self.filter_remove(remember=True)
tree = self.treeview
root = ET.Element('interface')
items = tree.get_children()
for it... | python | {
"resource": ""
} |
q228236 | WidgetsTreeEditor.tree_node_to_xml | train | def tree_node_to_xml(self, parent, item):
"""Converts a treeview item and children to xml nodes"""
tree = self.treeview
data = self.treedata[item]
node = data.to_xml_node()
children = tree.get_children(item)
for child in children:
cnode = ET.Element('child')... | python | {
"resource": ""
} |
q228237 | WidgetsTreeEditor._insert_item | train | def _insert_item(self, root, data, from_file=False):
"""Insert a item on the treeview and fills columns from data"""
tree = self.treeview
treelabel = data.get_id()
row = col = ''
if root != '' and 'layout' in data:
row = data.get_layout_property('row')
co... | python | {
"resource": ""
} |
q228238 | WidgetsTreeEditor.copy_to_clipboard | train | def copy_to_clipboard(self):
"""
Copies selected items to clipboard.
"""
tree = self.treeview
# get the selected item:
selection = tree.selection()
if selection:
self.filter_remove(remember=True)
root = ET.Element('selection')
f... | python | {
"resource": ""
} |
q228239 | WidgetsTreeEditor.add_widget | train | def add_widget(self, wclass):
"""Adds a new item to the treeview."""
tree = self.treeview
# get the selected item:
selected_item = ''
tsel = tree.selection()
if tsel:
selected_item = tsel[0]
# Need to remove filter if set
self.filter_remove... | python | {
"resource": ""
} |
q228240 | WidgetsTreeEditor.load_file | train | def load_file(self, filename):
"""Load file into treeview"""
self.counter.clear()
# python2 issues
try:
etree = ET.parse(filename)
except ET.ParseError:
parser = ET.XMLParser(encoding='UTF-8')
etree = ET.parse(filename, parser)
eroot =... | python | {
"resource": ""
} |
q228241 | WidgetsTreeEditor.populate_tree | train | def populate_tree(self, master, parent, element,from_file=False):
"""Reads xml nodes and populates tree item"""
data = WidgetDescr(None, None)
data.from_xml_node(element)
cname = data.get_class()
uniqueid = self.get_unique_id(cname, data.get_id())
data.set_property('id',... | python | {
"resource": ""
} |
q228242 | WidgetsTreeEditor.update_event | train | def update_event(self, hint, obj):
"""Updates tree colums when itemdata is changed."""
tree = self.treeview
data = obj
item = self.get_item_by_data(obj)
if item:
if data.get_id() != tree.item(item, 'text'):
tree.item(item, text=data.get_id())
... | python | {
"resource": ""
} |
q228243 | WidgetsTreeEditor._reatach | train | def _reatach(self):
"""Reinsert the hidden items."""
for item, p, idx in self._detached:
# The item may have been deleted.
if self.treeview.exists(item) and self.treeview.exists(p):
self.treeview.move(item, p, idx)
self._detached = [] | python | {
"resource": ""
} |
q228244 | WidgetsTreeEditor._detach | train | def _detach(self, item):
"""Hide items from treeview that do not match the search string."""
to_detach = []
children_det = []
children_match = False
match_found = False
value = self.filtervar.get()
txt = self.treeview.item(item, 'text').lower()
if value i... | python | {
"resource": ""
} |
q228245 | PygubuUI.load_file | train | def load_file(self, filename):
"""Load xml into treeview"""
self.tree_editor.load_file(filename)
self.project_name.configure(text=filename)
self.currentfile = filename
self.is_changed = False | python | {
"resource": ""
} |
q228246 | lower_ir | train | def lower_ir(ir_blocks, query_metadata_table, type_equivalence_hints=None):
"""Lower the IR into an IR form that can be represented in Gremlin queries.
Args:
ir_blocks: list of IR blocks to lower into Gremlin-compatible form
query_metadata_table: QueryMetadataTable object containing all metadat... | python | {
"resource": ""
} |
q228247 | lower_coerce_type_block_type_data | train | def lower_coerce_type_block_type_data(ir_blocks, type_equivalence_hints):
"""Rewrite CoerceType blocks to explicitly state which types are allowed in the coercion."""
allowed_key_type_spec = (GraphQLInterfaceType, GraphQLObjectType)
allowed_value_type_spec = GraphQLUnionType
# Validate that the type_eq... | python | {
"resource": ""
} |
q228248 | lower_coerce_type_blocks | train | def lower_coerce_type_blocks(ir_blocks):
"""Lower CoerceType blocks into Filter blocks with a type-check predicate."""
new_ir_blocks = []
for block in ir_blocks:
new_block = block
if isinstance(block, CoerceType):
predicate = BinaryComposition(
u'contains', Liter... | python | {
"resource": ""
} |
q228249 | rewrite_filters_in_optional_blocks | train | def rewrite_filters_in_optional_blocks(ir_blocks):
"""In optional contexts, add a check for null that allows non-existent optional data through.
Optional traversals in Gremlin represent missing optional data by setting the current vertex
to null until the exit from the optional scope. Therefore, filtering ... | python | {
"resource": ""
} |
q228250 | lower_folded_outputs | train | def lower_folded_outputs(ir_blocks):
"""Lower standard folded output fields into GremlinFoldedContextField objects."""
folds, remaining_ir_blocks = extract_folds_from_ir_blocks(ir_blocks)
if not remaining_ir_blocks:
raise AssertionError(u'Expected at least one non-folded block to remain: {} {} '
... | python | {
"resource": ""
} |
q228251 | GremlinFoldedContextField.validate | train | def validate(self):
"""Validate that the GremlinFoldedContextField is correctly representable."""
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(
type(self.fold_scope_locatio... | python | {
"resource": ""
} |
q228252 | GremlinFoldedTraverse.from_traverse | train | def from_traverse(cls, traverse_block):
"""Create a GremlinFoldedTraverse block as a copy of the given Traverse block."""
if isinstance(traverse_block, Traverse):
return cls(traverse_block.direction, traverse_block.edge_name)
else:
raise AssertionError(u'Tried to initiali... | python | {
"resource": ""
} |
q228253 | _get_referenced_type_equivalences | train | def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints):
"""Filter union types with no edges from the type equivalence hints dict."""
referenced_types = set()
for graphql_type in graphql_types.values():
if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)):
... | python | {
"resource": ""
} |
q228254 | _get_inherited_field_types | train | def _get_inherited_field_types(class_to_field_type_overrides, schema_graph):
"""Return a dictionary describing the field type overrides in subclasses."""
inherited_field_type_overrides = dict()
for superclass_name, field_type_overrides in class_to_field_type_overrides.items():
for subclass_name in s... | python | {
"resource": ""
} |
q228255 | _validate_overriden_fields_are_not_defined_in_superclasses | train | def _validate_overriden_fields_are_not_defined_in_superclasses(class_to_field_type_overrides,
schema_graph):
"""Assert that the fields we want to override are not defined in superclasses."""
for class_name, field_type_overrides in six.iteritems(clas... | python | {
"resource": ""
} |
q228256 | _property_descriptor_to_graphql_type | train | def _property_descriptor_to_graphql_type(property_obj):
"""Return the best GraphQL type representation for an OrientDB property descriptor."""
property_type = property_obj.type_id
scalar_types = {
PROPERTY_TYPE_BOOLEAN_ID: GraphQLBoolean,
PROPERTY_TYPE_DATE_ID: GraphQLDate,
PROPERTY_... | python | {
"resource": ""
} |
q228257 | _get_union_type_name | train | def _get_union_type_name(type_names_to_union):
"""Construct a unique union type name based on the type names being unioned."""
if not type_names_to_union:
raise AssertionError(u'Expected a non-empty list of type names to union, received: '
u'{}'.format(type_names_to_union))
... | python | {
"resource": ""
} |
q228258 | _get_fields_for_class | train | def _get_fields_for_class(schema_graph, graphql_types, field_type_overrides, hidden_classes,
cls_name):
"""Return a dict from field name to GraphQL field type, for the specified graph class."""
properties = schema_graph.get_element_by_class_name(cls_name).properties
# Add leaf Gra... | python | {
"resource": ""
} |
q228259 | _create_field_specification | train | def _create_field_specification(schema_graph, graphql_types, field_type_overrides,
hidden_classes, cls_name):
"""Return a function that specifies the fields present on the given type."""
def field_maker_func():
"""Create and return the fields for the given GraphQL type.""... | python | {
"resource": ""
} |
q228260 | _create_interface_specification | train | def _create_interface_specification(schema_graph, graphql_types, hidden_classes, cls_name):
"""Return a function that specifies the interfaces implemented by the given type."""
def interface_spec():
"""Return a list of GraphQL interface types implemented by the type named 'cls_name'."""
abstract... | python | {
"resource": ""
} |
q228261 | _create_union_types_specification | train | def _create_union_types_specification(schema_graph, graphql_types, hidden_classes, base_name):
"""Return a function that gives the types in the union type rooted at base_name."""
# When edges point to vertices of type base_name, and base_name is both non-abstract and
# has subclasses, we need to represent t... | python | {
"resource": ""
} |
q228262 | get_graphql_schema_from_schema_graph | train | def get_graphql_schema_from_schema_graph(schema_graph, class_to_field_type_overrides,
hidden_classes):
"""Return a GraphQL schema object corresponding to the schema of the given schema graph.
Args:
schema_graph: SchemaGraph
class_to_field_type_overrides:... | python | {
"resource": ""
} |
q228263 | workaround_lowering_pass | train | def workaround_lowering_pass(ir_blocks, query_metadata_table):
"""Extract locations from TernaryConditionals and rewrite their Filter blocks as necessary."""
new_ir_blocks = []
for block in ir_blocks:
if isinstance(block, Filter):
new_block = _process_filter_block(query_metadata_table, ... | python | {
"resource": ""
} |
q228264 | _process_filter_block | train | def _process_filter_block(query_metadata_table, block):
"""Rewrite the provided Filter block if necessary."""
# For a given Filter block with BinaryComposition predicate expression X,
# let L be the set of all Locations referenced in any TernaryConditional
# predicate expression enclosed in X.
# For... | python | {
"resource": ""
} |
q228265 | _create_tautological_expression_for_location | train | def _create_tautological_expression_for_location(query_metadata_table, location):
"""For a given location, create a BinaryComposition that always evaluates to 'true'."""
location_type = query_metadata_table.get_location_info(location).type
location_exists = BinaryComposition(
u'!=', ContextField(lo... | python | {
"resource": ""
} |
q228266 | get_only_element_from_collection | train | def get_only_element_from_collection(one_element_collection):
"""Assert that the collection has exactly one element, then return that element."""
if len(one_element_collection) != 1:
raise AssertionError(u'Expected a collection with exactly one element, but got: {}'
.format(... | python | {
"resource": ""
} |
q228267 | get_ast_field_name | train | def get_ast_field_name(ast):
"""Return the normalized field name for the given AST node."""
replacements = {
# We always rewrite the following field names into their proper underlying counterparts.
TYPENAME_META_FIELD_NAME: '@class'
}
base_field_name = ast.name.value
normalized_name ... | python | {
"resource": ""
} |
q228268 | get_field_type_from_schema | train | def get_field_type_from_schema(schema_type, field_name):
"""Return the type of the field in the given type, accounting for field name normalization."""
if field_name == '@class':
return GraphQLString
else:
if field_name not in schema_type.fields:
raise AssertionError(u'Field {} p... | python | {
"resource": ""
} |
q228269 | get_vertex_field_type | train | def get_vertex_field_type(current_schema_type, vertex_field_name):
"""Return the type of the vertex within the specified vertex field name of the given type."""
# According to the schema, the vertex field itself is of type GraphQLList, and this is
# what get_field_type_from_schema returns. We care about wha... | python | {
"resource": ""
} |
q228270 | get_edge_direction_and_name | train | def get_edge_direction_and_name(vertex_field_name):
"""Get the edge direction and name from a non-root vertex field name."""
edge_direction = None
edge_name = None
if vertex_field_name.startswith(OUTBOUND_EDGE_FIELD_PREFIX):
edge_direction = OUTBOUND_EDGE_DIRECTION
edge_name = vertex_fie... | python | {
"resource": ""
} |
q228271 | is_vertex_field_type | train | def is_vertex_field_type(graphql_type):
"""Return True if the argument is a vertex field type, and False otherwise."""
# This will need to change if we ever support complex embedded types or edge field types.
underlying_type = strip_non_null_from_type(graphql_type)
return isinstance(underlying_type, (Gr... | python | {
"resource": ""
} |
q228272 | ensure_unicode_string | train | def ensure_unicode_string(value):
"""Ensure the value is a string, and return it as unicode."""
if not isinstance(value, six.string_types):
raise TypeError(u'Expected string value, got: {}'.format(value))
return six.text_type(value) | python | {
"resource": ""
} |
q228273 | get_uniquely_named_objects_by_name | train | def get_uniquely_named_objects_by_name(object_list):
"""Return dict of name -> object pairs from a list of objects with unique names.
Args:
object_list: list of objects, each X of which has a unique name accessible as X.name.value
Returns:
dict, { X.name.value: X for x in object_list }
... | python | {
"resource": ""
} |
q228274 | validate_safe_string | train | def validate_safe_string(value):
"""Ensure the provided string does not have illegal characters."""
# The following strings are explicitly allowed, despite having otherwise-illegal chars.
legal_strings_with_special_chars = frozenset({'@rid', '@class', '@this', '%'})
if not isinstance(value, six.string_... | python | {
"resource": ""
} |
q228275 | validate_edge_direction | train | def validate_edge_direction(edge_direction):
"""Ensure the provided edge direction is either "in" or "out"."""
if not isinstance(edge_direction, six.string_types):
raise TypeError(u'Expected string edge_direction, got: {} {}'.format(
type(edge_direction), edge_direction))
if... | python | {
"resource": ""
} |
q228276 | validate_marked_location | train | def validate_marked_location(location):
"""Validate that a Location object is safe for marking, and not at a field."""
if not isinstance(location, (Location, FoldScopeLocation)):
raise TypeError(u'Expected Location or FoldScopeLocation location, got: {} {}'.format(
type(location).__name__, l... | python | {
"resource": ""
} |
q228277 | invert_dict | train | def invert_dict(invertible_dict):
"""Invert a dict. A dict is invertible if values are unique and hashable."""
inverted = {}
for k, v in six.iteritems(invertible_dict):
if not isinstance(v, Hashable):
raise TypeError(u'Expected an invertible dict, but value at key {} has type {}'.format(... | python | {
"resource": ""
} |
q228278 | read_file | train | def read_file(filename):
"""Read package file as text to get name and version"""
# intentionally *not* adding an encoding option to open
# see here:
# https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.joi... | python | {
"resource": ""
} |
q228279 | find_version | train | def find_version():
"""Only define version in one place"""
version_file = read_file('__init__.py')
version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']',
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to ... | python | {
"resource": ""
} |
q228280 | find_name | train | def find_name():
"""Only define name in one place"""
name_file = read_file('__init__.py')
name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']',
name_file, re.M)
if name_match:
return name_match.group(1)
raise RuntimeError('Unable to find name string.') | python | {
"resource": ""
} |
q228281 | workaround_type_coercions_in_recursions | train | def workaround_type_coercions_in_recursions(match_query):
"""Lower CoerceType blocks into Filter blocks within Recurse steps."""
# This step is required to work around an OrientDB bug that causes queries with both
# "while:" and "class:" in the same query location to fail to parse correctly.
#
# Thi... | python | {
"resource": ""
} |
q228282 | main | train | def main():
"""Read a GraphQL query from standard input, and output it pretty-printed to standard output."""
query = ' '.join(sys.stdin.readlines())
sys.stdout.write(pretty_print_graphql(query)) | python | {
"resource": ""
} |
q228283 | _safe_gremlin_string | train | def _safe_gremlin_string(value):
"""Sanitize and represent a string argument in Gremlin."""
if not isinstance(value, six.string_types):
if isinstance(value, bytes): # should only happen in py3
value = value.decode('utf-8')
else:
raise GraphQLInvalidArgumentError(u'Attemp... | python | {
"resource": ""
} |
q228284 | _safe_gremlin_list | train | def _safe_gremlin_list(inner_type, argument_value):
"""Represent the list of "inner_type" objects in Gremlin form."""
if not isinstance(argument_value, list):
raise GraphQLInvalidArgumentError(u'Attempting to represent a non-list as a list: '
u'{}'.format(argume... | python | {
"resource": ""
} |
q228285 | _safe_gremlin_argument | train | def _safe_gremlin_argument(expected_type, argument_value):
"""Return a Gremlin string representing the given argument value."""
if GraphQLString.is_same_type(expected_type):
return _safe_gremlin_string(argument_value)
elif GraphQLID.is_same_type(expected_type):
# IDs can be strings or number... | python | {
"resource": ""
} |
q228286 | insert_arguments_into_gremlin_query | train | def insert_arguments_into_gremlin_query(compilation_result, arguments):
"""Insert the arguments into the compiled Gremlin query to form a complete query.
The GraphQL compiler attempts to use single-quoted string literals ('abc') in Gremlin output.
Double-quoted strings allow inline interpolation with the $... | python | {
"resource": ""
} |
q228287 | _get_vertex_location_name | train | def _get_vertex_location_name(location):
"""Get the location name from a location that is expected to point to a vertex."""
mark_name, field_name = location.get_location_name()
if field_name is not None:
raise AssertionError(u'Location unexpectedly pointed to a field: {}'.format(location))
retu... | python | {
"resource": ""
} |
q228288 | _first_step_to_match | train | def _first_step_to_match(match_step):
"""Transform the very first MATCH step into a MATCH query string."""
parts = []
if match_step.root_block is not None:
if not isinstance(match_step.root_block, QueryRoot):
raise AssertionError(u'Expected None or QueryRoot root block, received: '
... | python | {
"resource": ""
} |
q228289 | _represent_match_traversal | train | def _represent_match_traversal(match_traversal):
"""Emit MATCH query code for an entire MATCH traversal sequence."""
output = []
output.append(_first_step_to_match(match_traversal[0]))
for step in match_traversal[1:]:
output.append(_subsequent_step_to_match(step))
return u''.join(output) | python | {
"resource": ""
} |
q228290 | _represent_fold | train | def _represent_fold(fold_location, fold_ir_blocks):
"""Emit a LET clause corresponding to the IR blocks for a @fold scope."""
start_let_template = u'$%(mark_name)s = %(base_location)s'
traverse_edge_template = u'.%(direction)s("%(edge_name)s")'
base_template = start_let_template + traverse_edge_template... | python | {
"resource": ""
} |
q228291 | _construct_output_to_match | train | def _construct_output_to_match(output_block):
"""Transform a ConstructResult block into a MATCH query string."""
output_block.validate()
selections = (
u'%s AS `%s`' % (output_block.fields[key].to_match(), key)
for key in sorted(output_block.fields.keys()) # Sort keys for deterministic out... | python | {
"resource": ""
} |
q228292 | _construct_where_to_match | train | def _construct_where_to_match(where_block):
"""Transform a Filter block into a MATCH query string."""
if where_block.predicate == TrueLiteral:
raise AssertionError(u'Received WHERE block with TrueLiteral predicate: {}'
.format(where_block))
return u'WHERE ' + where_block... | python | {
"resource": ""
} |
q228293 | emit_code_from_multiple_match_queries | train | def emit_code_from_multiple_match_queries(match_queries):
"""Return a MATCH query string from a list of MatchQuery namedtuples."""
optional_variable_base_name = '$optional__'
union_variable_name = '$result'
query_data = deque([u'SELECT EXPAND(', union_variable_name, u')', u' LET '])
optional_variab... | python | {
"resource": ""
} |
q228294 | emit_code_from_ir | train | def emit_code_from_ir(compound_match_query, compiler_metadata):
"""Return a MATCH query string from a CompoundMatchQuery."""
# If the compound match query contains only one match query,
# just call `emit_code_from_single_match_query`
# If there are multiple match queries, construct the query string for ... | python | {
"resource": ""
} |
q228295 | _serialize_date | train | def _serialize_date(value):
"""Serialize a Date object to its proper ISO-8601 representation."""
if not isinstance(value, date):
raise ValueError(u'The received object was not a date: '
u'{} {}'.format(type(value), value))
return value.isoformat() | python | {
"resource": ""
} |
q228296 | _serialize_datetime | train | def _serialize_datetime(value):
"""Serialize a DateTime object to its proper ISO-8601 representation."""
if not isinstance(value, (datetime, arrow.Arrow)):
raise ValueError(u'The received object was not a datetime: '
u'{} {}'.format(type(value), value))
return value.isoforma... | python | {
"resource": ""
} |
q228297 | _parse_datetime_value | train | def _parse_datetime_value(value):
"""Deserialize a DateTime object from its proper ISO-8601 representation."""
if value.endswith('Z'):
# Arrow doesn't support the "Z" literal to denote UTC time.
# Strip the "Z" and add an explicit time zone instead.
value = value[:-1] + '+00:00'
ret... | python | {
"resource": ""
} |
q228298 | insert_meta_fields_into_existing_schema | train | def insert_meta_fields_into_existing_schema(graphql_schema):
"""Add compiler-specific meta-fields into all interfaces and types of the specified schema.
It is preferable to use the EXTENDED_META_FIELD_DEFINITIONS constant above to directly inject
the meta-fields during the initial process of building the s... | python | {
"resource": ""
} |
q228299 | validate_context_for_visiting_vertex_field | train | def validate_context_for_visiting_vertex_field(parent_location, vertex_field_name, context):
"""Ensure that the current context allows for visiting a vertex field."""
if is_in_fold_innermost_scope(context):
raise GraphQLCompilationError(
u'Traversing inside a @fold block after filtering on {... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.