_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q15500
line_starts_subpgm
train
def line_starts_subpgm(line: str) -> Tuple[bool, Optional[str]]: """ Indicates whether a line in the program is the first line of a subprogram definition. Args: line Returns: (True, f_name) if line begins a definition for subprogram f_name; (False, None) if line does not begin...
python
{ "resource": "" }
q15501
program_unit_name
train
def program_unit_name(line:str) -> str: """Given a line that starts a program unit, i.e., a program, module, subprogram, or function, this function returns the name associated with that program unit.""" match = RE_PGM_UNIT_START.match(line) assert match != None return match.group(2)
python
{ "resource": "" }
q15502
prepend
train
def prepend(x: T, xs: Iterable[T]) -> Iterator[T]: """ Prepend a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields *x* followed by elements of *xs*. Exa...
python
{ "resource": "" }
q15503
append
train
def append(x: T, xs: Iterable[T]) -> Iterator[T]: """ Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*. Exa...
python
{ "resource": "" }
q15504
flatten
train
def flatten(xs: Union[List, Tuple]) -> List: """ Flatten a nested list or tuple. """ return ( sum(map(flatten, xs), []) if (isinstance(xs, list) or isinstance(xs, tuple)) else [xs] )
python
{ "resource": "" }
q15505
iterate
train
def iterate(f: Callable[[T], T], x: T) -> Iterator[T]: """ Makes infinite iterator that returns the result of successive applications of a function to an element .. math:: iterate(f, x) = [x, f(x), f(f(x)), f(f(f(x))), ...] Examples -------- >>> from delphi.utils.fp import iterate, tak...
python
{ "resource": "" }
q15506
ptake
train
def ptake(n: int, xs: Iterable[T]) -> Iterable[T]: """ take with a tqdm progress bar. """ return tqdm(take(n, xs), total=n)
python
{ "resource": "" }
q15507
ltake
train
def ltake(n: int, xs: Iterable[T]) -> List[T]: """ A non-lazy version of take. """ return list(take(n, xs))
python
{ "resource": "" }
q15508
compose
train
def compose(*fs: Any) -> Callable: """ Compose functions from left to right. e.g. compose(f, g)(x) = f(g(x)) """ return foldl1(lambda f, g: lambda *x: f(g(*x)), fs)
python
{ "resource": "" }
q15509
rcompose
train
def rcompose(*fs: Any) -> Callable: """ Compose functions from right to left. e.g. rcompose(f, g)(x) = g(f(x)) """ return foldl1(lambda f, g: lambda *x: g(f(*x)), fs)
python
{ "resource": "" }
q15510
flatMap
train
def flatMap(f: Callable, xs: Iterable) -> List: """ Map a function onto an iterable and flatten the result. """ return flatten(lmap(f, xs))
python
{ "resource": "" }
q15511
process_climis_crop_production_data
train
def process_climis_crop_production_data(data_dir: str): """ Process CliMIS crop production data """ climis_crop_production_csvs = glob( "{data_dir}/Climis South Sudan Crop Production Data/" "Crops_EstimatedProductionConsumptionBalance*.csv" ) state_county_df = pd.read_csv( f"{da...
python
{ "resource": "" }
q15512
AnalysisGraph.assign_uuids_to_nodes_and_edges
train
def assign_uuids_to_nodes_and_edges(self): """ Assign uuids to nodes and edges. """ for node in self.nodes(data=True): node[1]["id"] = str(uuid4()) for edge in self.edges(data=True): edge[2]["id"] = str(uuid4())
python
{ "resource": "" }
q15513
AnalysisGraph.from_statements_file
train
def from_statements_file(cls, file: str): """ Construct an AnalysisGraph object from a pickle file containing a list of INDRA statements. """ with open(file, "rb") as f: sts = pickle.load(f) return cls.from_statements(sts)
python
{ "resource": "" }
q15514
AnalysisGraph.from_text
train
def from_text(cls, text: str): """ Construct an AnalysisGraph object from text, using Eidos to perform machine reading. """ eidosProcessor = process_text(text) return cls.from_statements(eidosProcessor.statements)
python
{ "resource": "" }
q15515
AnalysisGraph.from_uncharted_json_file
train
def from_uncharted_json_file(cls, file): """ Construct an AnalysisGraph object from a file containing INDRA statements serialized exported by Uncharted's CauseMos webapp. """ with open(file, "r") as f: _dict = json.load(f) return cls.from_uncharted_json_serialized_dic...
python
{ "resource": "" }
q15516
AnalysisGraph.from_uncharted_json_serialized_dict
train
def from_uncharted_json_serialized_dict( cls, _dict, minimum_evidence_pieces_required: int = 1 ): """ Construct an AnalysisGraph object from a dict of INDRA statements exported by Uncharted's CauseMos webapp. """ sts = _dict["statements"] G = nx.DiGraph() for s in sts...
python
{ "resource": "" }
q15517
AnalysisGraph.sample_observed_state
train
def sample_observed_state(self, s: pd.Series) -> Dict: """ Sample observed state vector. This is the implementation of the emission function. Args: s: Latent state vector. Returns: Observed state vector. """ return { n[0]: { ...
python
{ "resource": "" }
q15518
AnalysisGraph.sample_from_likelihood
train
def sample_from_likelihood(self, n_timesteps=10): """ Sample a collection of observed state sequences from the likelihood model given a collection of transition matrices. Args: n_timesteps: The number of timesteps for the sequences. """ self.latent_state_sequences =...
python
{ "resource": "" }
q15519
AnalysisGraph.get_timeseries_values_for_indicators
train
def get_timeseries_values_for_indicators( self, resolution: str = "month", months: Iterable[int] = range(6, 9) ): """ Attach timeseries to indicators, for performing Bayesian inference. """ if resolution == "month": funcs = [ partial(get_indicator_value, ...
python
{ "resource": "" }
q15520
AnalysisGraph.sample_from_posterior
train
def sample_from_posterior(self, A: pd.DataFrame) -> None: """ Run Bayesian inference - sample from the posterior distribution.""" self.sample_from_proposal(A) self.set_latent_state_sequence(A) self.update_log_prior(A) self.update_log_likelihood() candidate_log_joint_prob...
python
{ "resource": "" }
q15521
AnalysisGraph.create_bmi_config_file
train
def create_bmi_config_file(self, filename: str = "bmi_config.txt") -> None: """ Create a BMI config file to initialize the model. Args: filename: The filename with which the config file should be saved. """ s0 = self.construct_default_initial_state() s0.to_csv(filena...
python
{ "resource": "" }
q15522
AnalysisGraph.export_node
train
def export_node(self, n) -> Dict[str, Union[str, List[str]]]: """ Return dict suitable for exporting to JSON. Args: n: A dict representing the data in a networkx AnalysisGraph node. Returns: The node dict with additional fields for name, units, dtype, and ar...
python
{ "resource": "" }
q15523
AnalysisGraph.map_concepts_to_indicators
train
def map_concepts_to_indicators( self, n: int = 1, min_temporal_res: Optional[str] = None ): """ Map each concept node in the AnalysisGraph instance to one or more tangible quantities, known as 'indicators'. Args: n: Number of matches to keep min_temporal_res:...
python
{ "resource": "" }
q15524
AnalysisGraph.parameterize
train
def parameterize( self, country: Optional[str] = "South Sudan", state: Optional[str] = None, year: Optional[int] = None, month: Optional[int] = None, unit: Optional[str] = None, fallback_aggaxes: List[str] = ["year", "month"], aggfunc: Callable = np.mean, ...
python
{ "resource": "" }
q15525
AnalysisGraph.delete_nodes
train
def delete_nodes(self, nodes: Iterable[str]): """ Iterate over a set of nodes and remove the ones that are present in the graph. """ for n in nodes: if self.has_node(n): self.remove_node(n)
python
{ "resource": "" }
q15526
AnalysisGraph.delete_node
train
def delete_node(self, node: str): """ Removes a node if it is in the graph. """ if self.has_node(node): self.remove_node(node)
python
{ "resource": "" }
q15527
AnalysisGraph.delete_edge
train
def delete_edge(self, source: str, target: str): """ Removes an edge if it is in the graph. """ if self.has_edge(source, target): self.remove_edge(source, target)
python
{ "resource": "" }
q15528
AnalysisGraph.delete_edges
train
def delete_edges(self, edges: Iterable[Tuple[str, str]]): """ Iterate over a set of edges and remove the ones that are present in the graph. """ for edge in edges: if self.has_edge(*edge): self.remove_edge(*edge)
python
{ "resource": "" }
q15529
AnalysisGraph.merge_nodes
train
def merge_nodes(self, n1: str, n2: str, same_polarity: bool = True): """ Merge node n1 into node n2, with the option to specify relative polarity. Args: n1 n2 same_polarity """ for p in self.predecessors(n1): for st in self[p][n1]...
python
{ "resource": "" }
q15530
AnalysisGraph.get_subgraph_for_concept
train
def get_subgraph_for_concept( self, concept: str, depth: int = 1, reverse: bool = False ): """ Returns a new subgraph of the analysis graph for a single concept. Args: concept: The concept that the subgraph will be centered around. depth: The depth to which the depth...
python
{ "resource": "" }
q15531
create_pgm_dict
train
def create_pgm_dict( lambdaFile: str, asts: List, file_name: str, mode_mapper_dict: dict, save_file=False, ) -> Dict: """ Create a Python dict representing the PGM, with additional metadata for JSON output. """ lambdaStrings = ["import math\n\n"] state = PGMState(lambdaStrings) ...
python
{ "resource": "" }
q15532
filter_and_process_statements
train
def filter_and_process_statements( sts, grounding_score_cutoff: float = 0.8, belief_score_cutoff: float = 0.85, concepts_of_interest: List[str] = [], ): """ Filter preassembled statements according to certain rules. """ filtered_sts = [] counters = {} def update_counter(counter_name): ...
python
{ "resource": "" }
q15533
create_CAG_with_indicators
train
def create_CAG_with_indicators(input, output, filename="CAG_with_indicators.pdf"): """ Create a CAG with mapped indicators """ with open(input, "rb") as f: G = pickle.load(f) G.map_concepts_to_indicators(min_temporal_res="month") G.set_indicator("UN/events/weather/precipitation", "Historical Ave...
python
{ "resource": "" }
q15534
ComputationalGraph.run
train
def run( self, inputs: Dict[str, Union[float, Iterable]], torch_size: Optional[int] = None, ) -> Union[float, Iterable]: """Executes the GrFN over a particular set of inputs and returns the result. Args: inputs: Input set where keys are the names of input...
python
{ "resource": "" }
q15535
GroundedFunctionNetwork.traverse_nodes
train
def traverse_nodes(self, node_set, depth=0): """BFS traversal of nodes that returns name traversal as large string. Args: node_set: Set of input nodes to begin traversal. depth: Current traversal depth for child node viewing. Returns: type: String containing...
python
{ "resource": "" }
q15536
GroundedFunctionNetwork.from_json_and_lambdas
train
def from_json_and_lambdas(cls, file: str, lambdas): """Builds a GrFN from a JSON object. Args: cls: The class variable for object creation. file: Filename of a GrFN JSON file. Returns: type: A GroundedFunctionNetwork object. """ with open(fi...
python
{ "resource": "" }
q15537
GroundedFunctionNetwork.from_python_file
train
def from_python_file( cls, python_file, lambdas_path, json_filename: str, stem: str ): """Builds GrFN object from Python file.""" with open(python_file, "r") as f: pySrc = f.read() return cls.from_python_src(pySrc, lambdas_path, json_filename, stem)
python
{ "resource": "" }
q15538
GroundedFunctionNetwork.from_python_src
train
def from_python_src( cls, pySrc, lambdas_path, json_filename: str, stem: str, save_file: bool = False, ): """Builds GrFN object from Python source code.""" asts = [ast.parse(pySrc)] pgm_dict = genPGM.create_pgm_dict( lambdas_path, ...
python
{ "resource": "" }
q15539
GroundedFunctionNetwork.from_fortran_file
train
def from_fortran_file(cls, fortran_file: str, tmpdir: str = "."): """Builds GrFN object from a Fortran program.""" stem = Path(fortran_file).stem if tmpdir == "." and "/" in fortran_file: tmpdir = Path(fortran_file).parent preprocessed_fortran_file = f"{tmpdir}/{stem}_preproc...
python
{ "resource": "" }
q15540
GroundedFunctionNetwork.from_fortran_src
train
def from_fortran_src(cls, fortran_src: str, dir: str = "."): """ Create a GroundedFunctionNetwork instance from a string with raw Fortran code. Args: fortran_src: A string with Fortran source code. dir: (Optional) - the directory in which the temporary Fortran file ...
python
{ "resource": "" }
q15541
GroundedFunctionNetwork.clear
train
def clear(self): """Clear variable nodes for next computation.""" for n in self.nodes(): if self.nodes[n]["type"] == "variable": self.nodes[n]["value"] = None elif self.nodes[n]["type"] == "function": self.nodes[n]["func_visited"] = False
python
{ "resource": "" }
q15542
GroundedFunctionNetwork.to_FIB
train
def to_FIB(self, other): """ Creates a ForwardInfluenceBlanket object representing the intersection of this model with the other input model. Args: other: The GroundedFunctionNetwork object to compare this model to. Returns: A ForwardInfluenceBlanket object to u...
python
{ "resource": "" }
q15543
GroundedFunctionNetwork.to_agraph
train
def to_agraph(self): """ Export to a PyGraphviz AGraph object. """ A = nx.nx_agraph.to_agraph(self) A.graph_attr.update( {"dpi": 227, "fontsize": 20, "fontname": "Menlo", "rankdir": "TB"} ) A.node_attr.update({"fontname": "Menlo"}) def build_tree(cluster_name...
python
{ "resource": "" }
q15544
GroundedFunctionNetwork.to_CAG_agraph
train
def to_CAG_agraph(self): """Returns a variable-only view of the GrFN in the form of an AGraph. Returns: type: A CAG constructed via variable influence in the GrFN object. """ CAG = self.to_CAG() A = nx.nx_agraph.to_agraph(CAG) A.graph_attr.update({"dpi": 227...
python
{ "resource": "" }
q15545
GroundedFunctionNetwork.to_call_agraph
train
def to_call_agraph(self): """ Build a PyGraphviz AGraph object corresponding to a call graph of functions. """ A = nx.nx_agraph.to_agraph(self.call_graph) A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"}) A.node_attr.update( {"shape": "rectangle"...
python
{ "resource": "" }
q15546
ForwardInfluenceBlanket.S2_surface
train
def S2_surface(self, sizes, bounds, presets, covers, use_torch=False, num_samples = 10): """Calculates the sensitivity surface of a GrFN for the two variables with the highest S2 index. Args: num_samples: Number of samples for sensitivity analysis. sizes: Tup...
python
{ "resource": "" }
q15547
XMLToJSONTranslator.process_direct_map
train
def process_direct_map(self, root, state) -> List[Dict]: """Handles tags that are mapped directly from xml to IR with no additional processing other than recursive translation of any child nodes.""" val = {"tag": root.tag, "args": []} for node in root: val["args"] +=...
python
{ "resource": "" }
q15548
XMLToJSONTranslator.parseTree
train
def parseTree(self, root, state: ParseState) -> List[Dict]: """ Parses the XML ast tree recursively to generate a JSON AST which can be ingested by other scripts to generate Python scripts. Args: root: The current root of the tree. state: The current stat...
python
{ "resource": "" }
q15549
XMLToJSONTranslator.loadFunction
train
def loadFunction(self, root): """ Loads a list with all the functions in the Fortran File Args: root: The root of the XML ast tree. Returns: None Does not return anything but populates a list (self.functionList) that contains all the functions i...
python
{ "resource": "" }
q15550
XMLToJSONTranslator.analyze
train
def analyze( self, trees: List[ET.ElementTree], comments: OrderedDict ) -> Dict: outputDict = {} ast = [] # Parse through the ast once to identify and grab all the functions # present in the Fortran file. for tree in trees: self.loadFunction(tree) ...
python
{ "resource": "" }
q15551
construct_FAO_ontology
train
def construct_FAO_ontology(): """ Construct FAO variable ontology for use with Eidos. """ df = pd.read_csv("south_sudan_data_fao.csv") gb = df.groupby("Element") d = [ { "events": [ { k: [ {e: [process_variable_name(k, e)]}...
python
{ "resource": "" }
q15552
inspect_edge
train
def inspect_edge(G: AnalysisGraph, source: str, target: str): """ 'Drill down' into an edge in the analysis graph and inspect its provenance. This function prints the provenance. Args: G source target """ return create_statement_inspection_table( G[source][target]["...
python
{ "resource": "" }
q15553
_get_edge_sentences
train
def _get_edge_sentences( G: AnalysisGraph, source: str, target: str ) -> List[str]: """ Return the sentences that led to the construction of a specified edge. Args: G source: The source of the edge. target: The target of the edge. """ return chain.from_iterable( [ ...
python
{ "resource": "" }
q15554
get_node_type
train
def get_node_type(type_str): """Returns the NodeType given a name of a JSON function object.""" if type_str == "container": return NodeType.CONTAINER elif type_str == "loop_plate": return NodeType.LOOP elif type_str == "assign": return NodeType.ASSIGN elif type_str == "condit...
python
{ "resource": "" }
q15555
list_output_formats
train
def list_output_formats(type_list): """This function takes a list of type names and returns a list of format specifiers for list-directed output of values of those types.""" out_format_list = [] for type_item in type_list: item_format = default_output_format(type_item) out_format_list.ap...
python
{ "resource": "" }
q15556
list_data_type
train
def list_data_type(type_list): """This function takes a list of format specifiers and returns a list of data types represented by the format specifiers.""" data_type = [] for item in type_list: match = re.match(r"(\d+)(.+)", item) if not match: reps = 1 if item[0]...
python
{ "resource": "" }
q15557
Format.read_line
train
def read_line(self, line): """ Match a line of input according to the format specified and return a tuple of the resulting values """ if not self._read_line_init: self.init_read_line() match = self._re.match(line) assert match is not None, f"Format m...
python
{ "resource": "" }
q15558
Format.write_line
train
def write_line(self, values): """ Process a list of values according to the format specified to generate a line of output. """ if not self._write_line_init: self.init_write_line() if len(self._out_widths) > len(values): raise For2PyError(f"ERROR:...
python
{ "resource": "" }
q15559
get_variable_and_source
train
def get_variable_and_source(x: str): """ Process the variable name to make it more human-readable. """ xs = x.replace("\/", "|").split("/") xs = [x.replace("|", "/") for x in xs] if xs[0] == "FAO": return " ".join(xs[2:]), xs[0] else: return xs[-1], xs[0]
python
{ "resource": "" }
q15560
construct_concept_to_indicator_mapping
train
def construct_concept_to_indicator_mapping(n: int = 1) -> Dict[str, List[str]]: """ Create a dictionary mapping high-level concepts to low-level indicators Args: n: Number of indicators to return Returns: Dictionary that maps concept names to lists of indicator names. """ df = pd....
python
{ "resource": "" }
q15561
Mortality.base_mortality_rate
train
def base_mortality_rate(self, index: pd.Index) -> pd.Series: """Computes the base mortality rate for every individual. Parameters ---------- index : A representation of the simulants to compute the base mortality rate for. Returns ------- ...
python
{ "resource": "" }
q15562
Mortality.determine_deaths
train
def determine_deaths(self, event: Event): """Determines who dies each time step. Parameters ---------- event : An event object emitted by the simulation containing an index representing the simulants affected by the event and timing information. ...
python
{ "resource": "" }
q15563
_prep_components
train
def _prep_components(component_list: Sequence[str]) -> List[Tuple[str, Tuple[str]]]: """Transform component description strings into tuples of component paths and required arguments. Parameters ---------- component_list : The component descriptions to transform. Returns ------- Lis...
python
{ "resource": "" }
q15564
ComponentConfigurationParser.get_components
train
def get_components(self, component_config: Union[ConfigTree, List]) -> List: """Extracts component specifications from configuration information and returns initialized components. Parameters ---------- component_config : A hierarchical component specification blob. This con...
python
{ "resource": "" }
q15565
ComponentConfigurationParser.parse_component_config
train
def parse_component_config(self, component_config: Dict[str, Union[Dict, List]]) -> List[str]: """Parses a hierarchical component specification into a list of standardized component definitions. This default parser expects component configurations as a list of dicts. Each dict at the top level ...
python
{ "resource": "" }
q15566
_next_state
train
def _next_state(index, event_time, transition_set, population_view): """Moves a population between different states using information from a `TransitionSet`. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp ...
python
{ "resource": "" }
q15567
_groupby_new_state
train
def _groupby_new_state(index, outputs, decisions): """Groups the simulants in the index by their new output state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. outputs : iterable A list of possible output states. decisions : `pa...
python
{ "resource": "" }
q15568
State.next_state
train
def next_state(self, index, event_time, population_view): """Moves a population between different states using information this state's `transition_set`. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pand...
python
{ "resource": "" }
q15569
State.transition_effect
train
def transition_effect(self, index, event_time, population_view): """Updates the simulation state and triggers any side-effects associated with entering this state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_t...
python
{ "resource": "" }
q15570
State.add_transition
train
def add_transition(self, output, probability_func=lambda index: np.ones(len(index), dtype=float), triggered=Trigger.NOT_TRIGGERED): """Builds a transition from this state to the given state. output : State The end state after the transition. ...
python
{ "resource": "" }
q15571
TransitionSet.choose_new_state
train
def choose_new_state(self, index): """Chooses a new state for each simulant in the index. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. Returns ------- outputs : list The possible end stat...
python
{ "resource": "" }
q15572
TransitionSet._normalize_probabilities
train
def _normalize_probabilities(self, outputs, probabilities): """Normalize probabilities to sum to 1 and add a null transition if desired. Parameters ---------- outputs : iterable List of possible end states corresponding to this containers transitions. probabilities :...
python
{ "resource": "" }
q15573
Machine.transition
train
def transition(self, index, event_time): """Finds the population in each state and moves them to the next state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp The time at whic...
python
{ "resource": "" }
q15574
Machine.to_dot
train
def to_dot(self): """Produces a ball and stick graph of this state machine. Returns ------- `graphviz.Digraph` A ball and stick visualization of this state machine. """ from graphviz import Digraph dot = Digraph(format='png') for state in self...
python
{ "resource": "" }
q15575
ComponentManager.setup_components
train
def setup_components(self, builder, configuration): """Apply component level configuration defaults to the global config and run setup methods on the components registering and setting up any child components generated in the process. Parameters ---------- builder: I...
python
{ "resource": "" }
q15576
field_to_markdown
train
def field_to_markdown(field): """Genera texto en markdown a partir de los metadatos de un `field`. Args: field (dict): Diccionario con metadatos de un `field`. Returns: str: Texto que describe un `field`. """ if "title" in field: field_title = "**{}**".format(field["title"]...
python
{ "resource": "" }
q15577
DataJson._build_index
train
def _build_index(self): """Itera todos los datasets, distribucioens y fields indexandolos.""" datasets_index = {} distributions_index = {} fields_index = {} # recorre todos los datasets for dataset_index, dataset in enumerate(self.datasets): if "identifier" ...
python
{ "resource": "" }
q15578
import_by_path
train
def import_by_path(path: str) -> Callable: """Import a class or function given it's absolute path. Parameters ---------- path: Path to object to import """ module_path, _, class_name = path.rpartition('.') return getattr(import_module(module_path), class_name)
python
{ "resource": "" }
q15579
_set_default_value
train
def _set_default_value(dict_obj, keys, value): """Setea valor en diccionario anidado, siguiendo lista de keys. Args: dict_obj (dict): Un diccionario anidado. keys (list): Una lista de keys para navegar el diccionario. value (any): Un valor para reemplazar. """ variable = dict_ob...
python
{ "resource": "" }
q15580
_make_contact_point
train
def _make_contact_point(dataset): """De estar presentes las claves necesarias, genera el diccionario "contactPoint" de un dataset.""" keys = [k for k in ["contactPoint_fn", "contactPoint_hasEmail"] if k in dataset] if keys: dataset["contactPoint"] = { key.replace("contact...
python
{ "resource": "" }
q15581
_read_csv_table
train
def _read_csv_table(path): """Lee un CSV a una lista de diccionarios.""" with open(path, 'rb') as csvfile: reader = csv.DictReader(csvfile) table = list(reader) return table
python
{ "resource": "" }
q15582
_read_xlsx_table
train
def _read_xlsx_table(path): """Lee la hoja activa de un archivo XLSX a una lista de diccionarios.""" workbook = pyxl.load_workbook(path) worksheet = workbook.active table = helpers.sheet_to_table(worksheet) return table
python
{ "resource": "" }
q15583
validate_model_specification_file
train
def validate_model_specification_file(file_path: str) -> str: """Ensures the provided file is a yaml file""" if not os.path.isfile(file_path): raise ConfigurationError('If you provide a model specification file, it must be a file. ' f'You provided {file_path}') exte...
python
{ "resource": "" }
q15584
ConfigNode.get_value_with_source
train
def get_value_with_source(self, layer=None): """Returns a tuple of the value's source and the value at the specified layer. If no layer is specified then the outer layer is used. Parameters ---------- layer : str Name of the layer to use. If None then the outermost w...
python
{ "resource": "" }
q15585
ConfigNode.metadata
train
def metadata(self): """Returns all values and associated metadata for this node as a dict. The value which would be selected if the node's value was requested is indicated by the `default` flag. """ result = [] for layer in self._layers: if layer in self._valu...
python
{ "resource": "" }
q15586
ConfigNode.set_value
train
def set_value(self, value, layer=None, source=None): """Set a value for a particular layer with optional metadata about source. Parameters ---------- value : str Data to store in the node. layer : str Name of the layer to use. If None then the outermost w...
python
{ "resource": "" }
q15587
ConfigTree.freeze
train
def freeze(self): """Causes the ConfigTree to become read only. This is useful for loading and then freezing configurations that should not be modified at runtime. """ self.__dict__['_frozen'] = True for child in self._children.values(): child.freeze()
python
{ "resource": "" }
q15588
ConfigTree.get_from_layer
train
def get_from_layer(self, name, layer=None): """Get a configuration value from the named layer. Parameters ---------- name : str The name of the value to retrieve layer: str The name of the layer to retrieve the value from. If it is not supplied ...
python
{ "resource": "" }
q15589
ConfigTree._set_with_metadata
train
def _set_with_metadata(self, name, value, layer=None, source=None): """Set a value in the named layer with the given source. Parameters ---------- name : str The name of the value value The value to store layer : str, optional The name...
python
{ "resource": "" }
q15590
ConfigTree.update
train
def update(self, data: Union[Mapping, str, bytes], layer: str=None, source: str=None): """Adds additional data into the ConfigTree. Parameters ---------- data : source data layer : layer to load data into. If none is supplied the outermost one is used ...
python
{ "resource": "" }
q15591
ConfigTree._read_dict
train
def _read_dict(self, data_dict, layer=None, source=None): """Load a dictionary into the ConfigTree. If the dict contains nested dicts then the values will be added recursively. See module docstring for example code. Parameters ---------- data_dict : dict source data ...
python
{ "resource": "" }
q15592
ConfigTree._loads
train
def _loads(self, data_string, layer=None, source=None): """Load data from a yaml formatted string. Parameters ---------- data_string : str yaml formatted string. The root element of the document should be an associative array layer : str layer...
python
{ "resource": "" }
q15593
ConfigTree._load
train
def _load(self, f, layer=None, source=None): """Load data from a yaml formatted file. Parameters ---------- f : str or file like object If f is a string then it is interpreted as a path to the file to load If it is a file like object then data is read directly fr...
python
{ "resource": "" }
q15594
ConfigTree.metadata
train
def metadata(self, name): """Return value and metadata associated with the named value Parameters ---------- name : str name to retrieve. If the name contains '.'s it will be retrieved recursively Raises ------ KeyError if name is not def...
python
{ "resource": "" }
q15595
ConfigTree.unused_keys
train
def unused_keys(self): """Lists all keys which are present in the ConfigTree but which have not been accessed.""" unused = set() for k, c in self._children.items(): if isinstance(c, ConfigNode): if not c.has_been_accessed(): unused.add(k) ...
python
{ "resource": "" }
q15596
create_validator
train
def create_validator(schema_filename=None, schema_dir=None): """Crea el validador necesario para inicializar un objeto DataJson. Para poder resolver referencias inter-esquemas, un Validador requiere que se especifique un RefResolver (Resolvedor de Referencias) con el directorio base (absoluto) y el arc...
python
{ "resource": "" }
q15597
initialize_simulation
train
def initialize_simulation(components: List, input_config: Mapping=None, plugin_config: Mapping=None) -> InteractiveContext: """Construct a simulation from a list of components, component configuration, and a plugin configuration. The simulation context returned by this method stil...
python
{ "resource": "" }
q15598
setup_simulation
train
def setup_simulation(components: List, input_config: Mapping=None, plugin_config: Mapping=None) -> InteractiveContext: """Construct a simulation from a list of components and call its setup method. Parameters ---------- components A list of initialized simulation compon...
python
{ "resource": "" }
q15599
initialize_simulation_from_model_specification
train
def initialize_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext: """Construct a simulation from a model specification file. The simulation context returned by this method still needs to be setup by calling its setup method. It is mostly useful for testing and debuggi...
python
{ "resource": "" }