_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q235700
_issubclass_Mapping_covariant
train
def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass, a.k.a pytypes.issubtype. This subclass-check treats Mapping-values as covariant. """ if is_Generic(subclass): ...
python
{ "resource": "" }
q235701
_issubclass_Union_rec
train
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass_Union. """ # this function is partly based on code from typing module 3.5.2.2 super_args = get_Union_params(superclass) if...
python
{ "resource": "" }
q235702
_isinstance
train
def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): """Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object...
python
{ "resource": "" }
q235703
generator_checker_py3
train
def generator_checker_py3(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Builds a typechecking wrapper around a Python 3 style generator object. """ initialized = False sn = None try: while True: a = gen.s...
python
{ "resource": "" }
q235704
generator_checker_py2
train
def generator_checker_py2(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Builds a typechecking wrapper around a Python 2 style generator object. """ initialized = False sn = None while True: a = gen.send(sn) i...
python
{ "resource": "" }
q235705
annotations_func
train
def annotations_func(func): """Works like annotations, but is only applicable to functions, methods and properties. """ if not has_type_hints(func): # What about defaults? func.__annotations__ = {} func.__annotations__ = _get_type_hints(func, infer_defaults = False) ...
python
{ "resource": "" }
q235706
annotations_class
train
def annotations_class(cls): """Works like annotations, but is only applicable to classes. """ assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use insp...
python
{ "resource": "" }
q235707
dump_cache
train
def dump_cache(path=None, python2=False, suffix=None): """Writes cached observations by @typelogged into stubfiles. Files will be created in the directory provided as 'path'; overwrites existing files without notice. Uses 'pyi2' suffix if 'python2' flag is given else 'pyi'. Resulting files will be P...
python
{ "resource": "" }
q235708
get_indentation
train
def get_indentation(func): """Extracts a function's indentation as a string, In contrast to an inspect.indentsize based implementation, this function preserves tabs if present. """ src_lines = getsourcelines(func)[0] for line in src_lines: if not (line.startswith('@') or line.startswith(...
python
{ "resource": "" }
q235709
typelogged_func
train
def typelogged_func(func): """Works like typelogged, but is only applicable to functions, methods and properties. """ if not pytypes.typelogging_enabled: return func if hasattr(func, 'do_logging'): func.do_logging = True return func elif hasattr(func, 'do_typecheck'): ...
python
{ "resource": "" }
q235710
typelogged_class
train
def typelogged_class(cls): """Works like typelogged, but is only applicable to classes. """ if not pytypes.typelogging_enabled: return cls assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't us...
python
{ "resource": "" }
q235711
typelogged_module
train
def typelogged_module(md): """Works like typelogged, but is only applicable to modules by explicit call). md must be a module or a module name contained in sys.modules. """ if not pytypes.typelogging_enabled: return md if isinstance(md, str): if md in sys.modules: md = sy...
python
{ "resource": "" }
q235712
enable_global_typechecked_decorator
train
def enable_global_typechecked_decorator(flag = True, retrospective = True): """Enables or disables global typechecking mode via decorators. See flag global_typechecked_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will ...
python
{ "resource": "" }
q235713
enable_global_auto_override_decorator
train
def enable_global_auto_override_decorator(flag = True, retrospective = True): """Enables or disables global auto_override mode via decorators. See flag global_auto_override_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this ...
python
{ "resource": "" }
q235714
enable_global_annotations_decorator
train
def enable_global_annotations_decorator(flag = True, retrospective = True): """Enables or disables global annotation mode via decorators. See flag global_annotations_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will al...
python
{ "resource": "" }
q235715
enable_global_typelogged_decorator
train
def enable_global_typelogged_decorator(flag = True, retrospective = True): """Enables or disables global typelog mode via decorators. See flag global_typelogged_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also ...
python
{ "resource": "" }
q235716
enable_global_typechecked_profiler
train
def enable_global_typechecked_profiler(flag = True): """Enables or disables global typechecking mode via a profiler. See flag global_typechecked_profiler. Does not work if checking_enabled is false. """ global global_typechecked_profiler, _global_type_agent, global_typelogged_profiler global_typ...
python
{ "resource": "" }
q235717
enable_global_typelogged_profiler
train
def enable_global_typelogged_profiler(flag = True): """Enables or disables global typelogging mode via a profiler. See flag global_typelogged_profiler. Does not work if typelogging_enabled is false. """ global global_typelogged_profiler, _global_type_agent, global_typechecked_profiler global_typ...
python
{ "resource": "" }
q235718
typechecked_func
train
def typechecked_func(func, force = False, argType = None, resType = None, prop_getter = False): """Works like typechecked, but is only applicable to functions, methods and properties. """ if not pytypes.checking_enabled and not pytypes.do_logging_in_typechecked: return func assert(_check_as_func...
python
{ "resource": "" }
q235719
typechecked_class
train
def typechecked_class(cls, force = False, force_recursive = False): """Works like typechecked, but is only applicable to classes. """ return _typechecked_class(cls, set(), force, force_recursive)
python
{ "resource": "" }
q235720
auto_override_class
train
def auto_override_class(cls, force = False, force_recursive = False): """Works like auto_override, but is only applicable to classes. """ if not pytypes.checking_enabled: return cls assert(isclass(cls)) if not force and is_no_type_check(cls): return cls # To play it safe we avoid...
python
{ "resource": "" }
q235721
is_no_type_check
train
def is_no_type_check(memb): """Checks if an object was annotated with @no_type_check (from typing or pytypes.typechecker). """ try: return hasattr(memb, '__no_type_check__') and memb.__no_type_check__ or \ memb in _not_type_checked except TypeError: return False
python
{ "resource": "" }
q235722
check_argument_types
train
def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0): """Can be called from within a function or method to apply typechecking to the arguments that were passed in by the caller. Checking is applied w.r.t. type hints of the function or method hosting the call to check_arg...
python
{ "resource": "" }
q235723
check_return_type
train
def check_return_type(value, cllable = None, clss = None, caller_level = 0): """Can be called from within a function or method to apply typechecking to the value that is going to be returned. Checking is applied w.r.t. type hints of the function or method hosting the call to check_return_type. """ r...
python
{ "resource": "" }
q235724
BpmnDiagramGraphCSVImport.load_diagram_from_csv
train
def load_diagram_from_csv(filepath, bpmn_diagram): """ Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of Bp...
python
{ "resource": "" }
q235725
BpmnDiagramGraphImport.load_diagram_from_xml
train
def load_diagram_from_xml(filepath, bpmn_diagram): """ Reads an XML file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of Bp...
python
{ "resource": "" }
q235726
BpmnDiagramGraphImport.import_collaboration_element
train
def import_collaboration_element(diagram_graph, collaboration_element, collaboration_dict): """ Method that imports information from 'collaboration' element. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param collaboration_element: XML doument element, ...
python
{ "resource": "" }
q235727
BpmnDiagramGraphImport.import_participant_element
train
def import_participant_element(diagram_graph, participants_dictionary, participant_element): """ Adds 'participant' element to the collaboration dictionary. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param participants_dictionary: dictionary with particip...
python
{ "resource": "" }
q235728
BpmnDiagramGraphImport.import_process_elements
train
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element): """ Method for importing all 'process' elements in diagram. :param document: XML document, :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param...
python
{ "resource": "" }
q235729
BpmnDiagramGraphImport.import_child_lane_set_element
train
def import_child_lane_set_element(child_lane_set_element, plane_element): """ Method for importing 'childLaneSet' element from diagram file. :param child_lane_set_element: XML document element, :param plane_element: object representing a BPMN XML 'plane' element. """ lan...
python
{ "resource": "" }
q235730
BpmnDiagramGraphImport.import_task_to_graph
train
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element): """ Adds to graph the new element that represents BPMN task. In our representation tasks have only basic attributes and elements, inherited from Activity type, so this method only needs to call add_flo...
python
{ "resource": "" }
q235731
BpmnDiagramGraphImport.import_data_object_to_graph
train
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element): """ Adds to graph the new element that represents BPMN data object. Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node. :param d...
python
{ "resource": "" }
q235732
BpmnDiagramGraphImport.import_parallel_gateway_to_graph
train
def import_parallel_gateway_to_graph(diagram_graph, process_id, process_attributes, element): """ Adds to graph the new element that represents BPMN parallel gateway. Parallel gateway doesn't have additional attributes. Separate method is used to improve code readability. :param diagram...
python
{ "resource": "" }
q235733
BpmnDiagramGraphExport.export_task_info
train
def export_task_info(node_params, output_element): """ Adds Task node attributes to exported XML element :param node_params: dictionary with given task parameters, :param output_element: object representing BPMN XML 'task' element. """ if consts.Consts.default in node_pa...
python
{ "resource": "" }
q235734
BpmnDiagramGraphExport.export_subprocess_info
train
def export_subprocess_info(bpmn_diagram, subprocess_params, output_element): """ Adds Subprocess node attributes to exported XML element :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram, :param subprocess_params: dictionary with given subprocess...
python
{ "resource": "" }
q235735
BpmnDiagramGraphExport.export_data_object_info
train
def export_data_object_info(bpmn_diagram, data_object_params, output_element): """ Adds DataObject node attributes to exported XML element :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram, :param data_object_params: dictionary with given subproc...
python
{ "resource": "" }
q235736
BpmnDiagramGraphExport.export_complex_gateway_info
train
def export_complex_gateway_info(node_params, output_element): """ Adds ComplexGateway node attributes to exported XML element :param node_params: dictionary with given complex gateway parameters, :param output_element: object representing BPMN XML 'complexGateway' element. """ ...
python
{ "resource": "" }
q235737
BpmnDiagramGraphExport.export_event_based_gateway_info
train
def export_event_based_gateway_info(node_params, output_element): """ Adds EventBasedGateway node attributes to exported XML element :param node_params: dictionary with given event based gateway parameters, :param output_element: object representing BPMN XML 'eventBasedGateway' element....
python
{ "resource": "" }
q235738
BpmnDiagramGraphExport.export_inclusive_exclusive_gateway_info
train
def export_inclusive_exclusive_gateway_info(node_params, output_element): """ Adds InclusiveGateway or ExclusiveGateway node attributes to exported XML element :param node_params: dictionary with given inclusive or exclusive gateway parameters, :param output_element: object representing...
python
{ "resource": "" }
q235739
BpmnDiagramGraphExport.export_parallel_gateway_info
train
def export_parallel_gateway_info(node_params, output_element): """ Adds parallel gateway node attributes to exported XML element :param node_params: dictionary with given parallel gateway parameters, :param output_element: object representing BPMN XML 'parallelGateway' element. ...
python
{ "resource": "" }
q235740
BpmnDiagramGraphExport.export_start_event_info
train
def export_start_event_info(node_params, output_element): """ Adds StartEvent attributes to exported XML element :param node_params: dictionary with given intermediate catch event parameters, :param output_element: object representing BPMN XML 'intermediateCatchEvent' element. "...
python
{ "resource": "" }
q235741
BpmnDiagramGraphExport.export_throw_event_info
train
def export_throw_event_info(node_params, output_element): """ Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThr...
python
{ "resource": "" }
q235742
BpmnDiagramGraphExport.export_boundary_event_info
train
def export_boundary_event_info(node_params, output_element): """ Adds IntermediateCatchEvent attributes to exported XML element :param node_params: dictionary with given intermediate catch event parameters, :param output_element: object representing BPMN XML 'intermediateCatchEvent' ele...
python
{ "resource": "" }
q235743
BpmnDiagramGraphExport.export_process_element
train
def export_process_element(definitions, process_id, process_attributes_dictionary): """ Creates process element for exported BPMN XML file. :param process_id: string object. ID of exported process element, :param definitions: an XML element ('definitions'), root element of BPMN 2.0 docu...
python
{ "resource": "" }
q235744
BpmnDiagramGraphExport.export_lane_set
train
def export_lane_set(process, lane_set, plane_element): """ Creates 'laneSet' element for exported BPMN XML file. :param process: an XML element ('process'), from exported BPMN 2.0 document, :param lane_set: dictionary with exported 'laneSet' element attributes and child elements, ...
python
{ "resource": "" }
q235745
BpmnDiagramGraphExport.export_child_lane_set
train
def export_child_lane_set(parent_xml_element, child_lane_set, plane_element): """ Creates 'childLaneSet' element for exported BPMN XML file. :param parent_xml_element: an XML element, parent of exported 'childLaneSet' element, :param child_lane_set: dictionary with exported 'childLaneSe...
python
{ "resource": "" }
q235746
BpmnDiagramGraphExport.export_lane
train
def export_lane(parent_xml_element, lane_id, lane_attr, plane_element): """ Creates 'lane' element for exported BPMN XML file. :param parent_xml_element: an XML element, parent of exported 'lane' element, :param lane_id: string object. ID of exported lane element, :param lane_at...
python
{ "resource": "" }
q235747
BpmnDiagramGraphExport.export_node_di_data
train
def export_node_di_data(node_id, params, plane): """ Creates a new BPMNShape XML element for given node parameters and adds it to 'plane' element. :param node_id: string representing ID of given flow node, :param params: dictionary with node parameters, :param plane: object of E...
python
{ "resource": "" }
q235748
BpmnDiagramGraphExport.export_flow_process_data
train
def export_flow_process_data(params, process): """ Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element. :param params: dictionary with edge parameters, :param process: object of Element class, representing BPMN XML 'process' element (root fo...
python
{ "resource": "" }
q235749
BpmnDiagramGraphExport.export_flow_di_data
train
def export_flow_di_data(params, plane): """ Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element. :param params: dictionary with edge parameters, :param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI dat...
python
{ "resource": "" }
q235750
BpmnDiagramGraphExport.indent
train
def indent(elem, level=0): """ Helper function, adds indentation to XML output. :param elem: object of Element class, representing element to which method adds intendation, :param level: current level of intendation. """ i = "\n" + level * " " j = "\n" + (level ...
python
{ "resource": "" }
q235751
BpmnImportUtils.generate_nodes_clasification
train
def generate_nodes_clasification(bpmn_diagram): """ Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of BPMN Processes". Assigns a classification to the diagram element according to specific element parameters. - Element - ...
python
{ "resource": "" }
q235752
BpmnImportUtils.split_join_classification
train
def split_join_classification(element, classification_labels, nodes_classification): """ Add the "Split", "Join" classification, if the element qualifies for. :param element: an element from BPMN diagram, :param classification_labels: list of labels attached to the element, :par...
python
{ "resource": "" }
q235753
get_all_gateways
train
def get_all_gateways(bpmn_graph): """ Returns a list with all gateways in diagram :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: a list with all gateways in diagram """ gateways = filter(lambda node: node[1]['type'] in GATEWAY_TYPES, bpmn_graph.get_nodes())...
python
{ "resource": "" }
q235754
all_control_flow_elements_count
train
def all_control_flow_elements_count(bpmn_graph): """ Returns the total count of all control flow elements in the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: total count of the control flow elements in the BPMNDiagramGraph inst...
python
{ "resource": "" }
q235755
BpmnDiagramGraphCsvExport.export_process_to_csv
train
def export_process_to_csv(bpmn_diagram, directory, filename): """ Root method of CSV export functionality. :param bpmn_diagram: an instance of BpmnDiagramGraph class, :param directory: a string object, which is a path of output directory, :param filename: a string object, which ...
python
{ "resource": "" }
q235756
BpmnDiagramGraphCsvExport.export_node
train
def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="", add_join=False): """ General method for node exporting :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary ob...
python
{ "resource": "" }
q235757
BpmnDiagramGraphCsvExport.export_start_event
train
def export_start_event(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who=""): """ Start event export :param bpmn_graph: an instance of BpmnDiagramGraph class, :param export_elements: a dictionary object. The key is ...
python
{ "resource": "" }
q235758
BpmnDiagramGraphCsvExport.export_end_event
train
def export_end_event(export_elements, node, order=0, prefix="", condition="", who=""): """ End event export :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CSV document, :param node: netw...
python
{ "resource": "" }
q235759
BpmnDiagramGraphCsvExport.write_export_node_to_file
train
def write_export_node_to_file(file_object, export_elements): """ Exporting process to CSV file :param file_object: object of File class, :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that will be used in exported CS...
python
{ "resource": "" }
q235760
visualize_diagram
train
def visualize_diagram(bpmn_diagram): """ Shows a simple visualization of diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class. """ g = bpmn_diagram.diagram_graph pos = bpmn_diagram.get_nodes_positions() nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white', ...
python
{ "resource": "" }
q235761
bpmn_diagram_to_png
train
def bpmn_diagram_to_png(bpmn_diagram, file_name): """ Create a png picture for given diagram :param bpmn_diagram: an instance of BPMNDiagramGraph class, :param file_name: name of generated file. """ g = bpmn_diagram.diagram_graph graph = pydotplus.Dot() for node in g.nodes(data=True): ...
python
{ "resource": "" }
q235762
BpmnDiagramGraph.get_node_by_id
train
def get_node_by_id(self, node_id): """ Gets a node with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param node_id: string with ID of node. """ tmp_nodes = self.diagram_graph.nodes(data=True) for node...
python
{ "resource": "" }
q235763
BpmnDiagramGraph.get_nodes_id_list_by_type
train
def get_nodes_id_list_by_type(self, node_type): """ Get a list of node's id by requested type. Returns a list of ids :param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow'). """ tmp_nodes = self.diagram_graph.nodes(data=True) id_list =...
python
{ "resource": "" }
q235764
BpmnDiagramGraph.add_process_to_diagram
train
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False, process_type="None"): """ Adds a new process to diagram and corresponding participant process, diagram and plane Accepts a user-defined values for f...
python
{ "resource": "" }
q235765
BpmnDiagramGraph.add_flow_node_to_diagram
train
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None): """ Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type. Adds a basic information inherited from Flow Node type. :param process_id: string object. ID of parent...
python
{ "resource": "" }
q235766
BpmnDiagramGraph.add_start_event_to_diagram
train
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None, parallel_multiple=False, is_interrupting=True, node_id=None): """ Adds a StartEvent element to BPMN diagram. User-defined attributes: - name - p...
python
{ "resource": "" }
q235767
BpmnDiagramGraph.add_inclusive_gateway_to_diagram
train
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", default=None, node_id=None): """ Adds an inclusiveGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :p...
python
{ "resource": "" }
q235768
BpmnDiagramGraph.add_parallel_gateway_to_diagram
train
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", node_id=None): """ Adds an parallelGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :param gateway_name...
python
{ "resource": "" }
q235769
BpmnDiagramGraph.get_nodes_positions
train
def get_nodes_positions(self): """ Getter method for nodes positions. :return: A dictionary with nodes as keys and positions as values """ nodes = self.get_nodes() output = {} for node in nodes: output[node[0]] = (float(node[1][consts.Consts.x]), floa...
python
{ "resource": "" }
q235770
create_tree
train
def create_tree(path, depth=DEPTH): """Create a directory tree at path with given depth, and NUM_DIRS and NUM_FILES at each level. """ os.mkdir(path) for i in range(NUM_FILES): filename = os.path.join(path, 'file{0:03}.txt'.format(i)) with open(filename, 'wb') as f: f.wri...
python
{ "resource": "" }
q235771
get_tree_size
train
def get_tree_size(path): """Return total size of all files in directory tree at path.""" size = 0 try: for entry in scandir.scandir(path): if entry.is_symlink(): pass elif entry.is_dir(): size += get_tree_size(os.path.join(path, entry.name)) ...
python
{ "resource": "" }
q235772
unfold
train
def unfold(tensor, mode): """Returns the mode-`mode` unfolding of `tensor`. Parameters ---------- tensor : ndarray mode : int Returns ------- ndarray unfolded_tensor of shape ``(tensor.shape[mode], -1)`` Author ------ Jean Kossaifi <https://github.com/tensorly> ...
python
{ "resource": "" }
q235773
khatri_rao
train
def khatri_rao(matrices): """Khatri-Rao product of a list of matrices. Parameters ---------- matrices : list of ndarray Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices])`` i.e. the product of the ...
python
{ "resource": "" }
q235774
soft_cluster_factor
train
def soft_cluster_factor(factor): """Returns soft-clustering of data based on CP decomposition results. Parameters ---------- data : ndarray, N x R matrix of nonnegative data Datapoints are held in rows, features are held in columns Returns ------- cluster_ids : ndarray, vector of N...
python
{ "resource": "" }
q235775
hclust_linearize
train
def hclust_linearize(U): """Sorts the rows of a matrix by hierarchical clustering. Parameters: U (ndarray) : matrix of data Returns: prm (ndarray) : permutation of the rows """ from scipy.cluster import hierarchy Z = hierarchy.ward(U) return hierarchy.leaves_list(hierarchy...
python
{ "resource": "" }
q235776
reverse_segment
train
def reverse_segment(path, n1, n2): """Reverse the nodes between n1 and n2. """ q = path.copy() if n2 > n1: q[n1:(n2+1)] = path[n1:(n2+1)][::-1] return q else: seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1] brk = len(q) - n1 q[n1:] = seg[:brk] q[:(n2...
python
{ "resource": "" }
q235777
KTensor.full
train
def full(self): """Converts KTensor to a dense ndarray.""" # Compute tensor unfolding along first mode unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T) # Inverse unfolding along first mode return sci.reshape(unf, self.shape)
python
{ "resource": "" }
q235778
KTensor.rebalance
train
def rebalance(self): """Rescales factors across modes so that all norms match. """ # Compute norms along columns for each factor matrix norms = [sci.linalg.norm(f, axis=0) for f in self.factors] # Multiply norms across all modes lam = sci.multiply.reduce(norms) ** (1/se...
python
{ "resource": "" }
q235779
KTensor.permute
train
def permute(self, idx): """Permutes the columns of the factor matrices inplace """ # Check that input is a true permutation if set(idx) != set(range(self.rank)): raise ValueError('Invalid permutation specified.') # Update factors self.factors = [f[:, idx] fo...
python
{ "resource": "" }
q235780
kruskal_align
train
def kruskal_align(U, V, permute_U=False, permute_V=False): """Aligns two KTensors and returns a similarity score. Parameters ---------- U : KTensor First kruskal tensor to align. V : KTensor Second kruskal tensor to align. permute_U : bool If True, modifies 'U' to align ...
python
{ "resource": "" }
q235781
plot_objective
train
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): """Plots objective function as a function of model rank. Parameters ---------- ensemble : Ensemble object holds optimization results across a range of model ranks part...
python
{ "resource": "" }
q235782
plot_similarity
train
def plot_similarity(ensemble, ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): """Plots similarity across optimization runs as a function of model rank. Parameters ---------- ensemble : Ensemble object holds optimization results across a range of model ranks ax :...
python
{ "resource": "" }
q235783
_broadcast_arg
train
def _broadcast_arg(U, arg, argtype, name): """Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg...
python
{ "resource": "" }
q235784
_check_cpd_inputs
train
def _check_cpd_inputs(X, rank): """Checks that inputs to optimization function are appropriate. Parameters ---------- X : ndarray Tensor used for fitting CP decomposition. rank : int Rank of low rank decomposition. Raises ------ ValueError: If inputs are not suited for ...
python
{ "resource": "" }
q235785
_check_random_state
train
def _check_random_state(random_state): """Checks and processes user input for seeding random numbers. Parameters ---------- random_state : int, RandomState instance or None If int, a RandomState instance is created with this integer seed. If RandomState instance, random_state is returne...
python
{ "resource": "" }
q235786
randn_ktensor
train
def randn_ktensor(shape, rank, norm=None, random_state=None): """ Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor n...
python
{ "resource": "" }
q235787
Ensemble.fit
train
def fit(self, X, ranks, replicates=1, verbose=True): """ Fits CP tensor decompositions for different choices of rank. Parameters ---------- X : array_like Real tensor ranks : int, or iterable iterable specifying number of components in each model ...
python
{ "resource": "" }
q235788
Ensemble.objectives
train
def objectives(self, rank): """Returns objective values of models with specified rank. """ self._check_rank(rank) return [result.obj for result in self.results[rank]]
python
{ "resource": "" }
q235789
Ensemble.similarities
train
def similarities(self, rank): """Returns similarity scores for models with specified rank. """ self._check_rank(rank) return [result.similarity for result in self.results[rank]]
python
{ "resource": "" }
q235790
Ensemble.factors
train
def factors(self, rank): """Returns KTensor factors for models with specified rank. """ self._check_rank(rank) return [result.factors for result in self.results[rank]]
python
{ "resource": "" }
q235791
Environment._create_model_class
train
def _create_model_class(self, model): """Generate the model proxy class. :return: a :class:`odoorpc.models.Model` class """ cls_name = model.replace('.', '_') # Hack for Python 2 (no need to do this for Python 3) if sys.version_info[0] < 3: if isinstance(cls_...
python
{ "resource": "" }
q235792
get_all
train
def get_all(rc_file='~/.odoorpcrc'): """Return all session configurations from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get_all()) # doctest: +SKIP {'foo': {'database': 'db_name', 'host': 'localhost', 'passwd': '...
python
{ "resource": "" }
q235793
get
train
def get(name, rc_file='~/.odoorpcrc'): """Return the session configuration identified by `name` from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get('foo')) # doctest: +SKIP {'database': 'db_name', 'host': 'localhost', 'passwd':...
python
{ "resource": "" }
q235794
save
train
def save(name, data, rc_file='~/.odoorpcrc'): """Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeou...
python
{ "resource": "" }
q235795
remove
train
def remove(name, rc_file='~/.odoorpcrc'): """Remove the session configuration identified by `name` from the `rc_file` file. >>> import odoorpc >>> odoorpc.session.remove('foo') # doctest: +SKIP .. doctest:: :hide: >>> import odoorpc >>> session = '%s_session' % DB ...
python
{ "resource": "" }
q235796
get_json_log_data
train
def get_json_log_data(data): """Returns a new `data` dictionary with hidden params for log purpose. """ log_data = data for param in LOG_HIDDEN_JSON_PARAMS: if param in data['params']: if log_data is data: log_data = copy.deepcopy(data) log_data['param...
python
{ "resource": "" }
q235797
ODOO.http
train
def http(self, url, data=None, headers=None): """Low level method to execute raw HTTP queries. .. note:: For low level JSON-RPC queries, see the more convenient :func:`odoorpc.ODOO.json` method instead. You have to know the names of each POST parameter required by the ...
python
{ "resource": "" }
q235798
ODOO._check_logged_user
train
def _check_logged_user(self): """Check if a user is logged. Otherwise, an error is raised.""" if not self._env or not self._password or not self._login: raise error.InternalError("Login required")
python
{ "resource": "" }
q235799
ODOO.login
train
def login(self, db, login='admin', password='admin'): """Log in as the given `user` with the password `passwd` on the database `db`. .. doctest:: :options: +SKIP >>> odoo.login('db_name', 'admin', 'admin') >>> odoo.env.user.name 'Administrator' ...
python
{ "resource": "" }