code
stringlengths
17
6.64M
def read_json(file_path: str) -> Any: with open(file_path, 'r') as f: return json.load(f)
def read_jsonl(file_path: str) -> List[Any]: all_data = [] with open(file_path, 'r') as f: for line in f: line = line.strip() if line: data = json.loads(line) all_data.append(data) return all_data
def read_file(file_path: str) -> Any: suffix = file_path.split('.')[(- 1)] if (suffix == 'json'): return read_json(file_path) elif (suffix == 'jsonl'): return read_jsonl(file_path) elif (suffix in ['txt', 'log', 'md']): with open(file_path, 'r') as f: return f.readl...
def remove_file_extension(file_path: str) -> str: 'Remove the file extension suffix of a file path.' return '.'.join(file_path.split('.')[:(- 1)])
def replace_file_extension(file_path: str, new_extension: str) -> str: 'Replace the file extension suffix of a file path.' return (remove_file_extension(file_path) + f'.{new_extension}')
def convert_to_message(content: str, type: str) -> BaseMessage: if (type == 'human'): return HumanMessage(content=content) elif (type == 'ai'): return AIMessage(content=content) elif (type == 'system'): return SystemMessage(content=content) else: raise ValueError(f'Unkn...
def print_prompt(prompt: Union[(List[BaseMessage], str)], raw_text: bool=False): if isinstance(prompt, str): print(prompt) else: for msg in prompt: if raw_text: print(((f'# {msg.type} message'.upper() + '\n') + msg.content)) else: print(m...
def replace_agent_action_with_list(x: Any) -> Any: if isinstance(x, AgentAction): return [x.tool, x.tool_input, x.log] elif isinstance(x, dict): return {k: replace_agent_action_with_list(v) for (k, v) in x.items()} elif isinstance(x, list): return [replace_agent_action_with_list(v)...
def llm_register_args(parser, prefix=None, shortprefix=None, defaults={}): model_name = defaults.get('model_name', 'gpt-4') temperature = defaults.get('temperature', 0.0) max_tokens = defaults.get('max_tokens', None) default_retries = (8 if model_name.startswith('claude') else 12) max_retries = de...
def get_model_name(name, fixed_version=True, version=None): model_name = None if (name in MODEL_NAMES_MAPPING): model_name = MODEL_NAMES_MAPPING[name] elif (name in MODEL_NAMES): model_name = name if (model_name is None): raise ValueError(f'Invalid model name: {name}') if f...
def get_fixed_model_name(name): return get_model_name(name, fixed_version=True)
class ChatOpenAI(LangchainChatOpenAI): def _create_chat_result(self, response: Mapping[(str, Any)]) -> ChatResult: generations = [] for res in response['choices']: message = convert_dict_to_message(res['message']) gen = ChatGeneration(message=message, generation_info=dict(...
def _anthropic_create_retry_decorator(llm: ChatOpenAI) -> Callable[([Any], Any)]: import anthropic min_seconds = 1 max_seconds = 60 return retry(reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=((((((retry_if_exception...
class ChatAnthropic(LangchainChatAnthropic): max_retries: int = 6 max_tokens_to_sample: int = 4000 'Maximum number of retries to make when generating.' def completion_with_retry(self, **kwargs: Any) -> Any: 'Use tenacity to retry the completion call.' retry_decorator = _anthropic_crea...
def parse_llm_response(res: ChatResult, index: int=0, one_generation_only: bool=True) -> str: res = res.generations[0] if one_generation_only: assert (len(res) == 1), res res = res[index] if (res.generation_info.get('finish_reason', None) == 'length'): raise ValueError(f'Discard a resp...
def load_openai_llm(model_name: str='text-davinci-003', **kwargs) -> BaseLanguageModel: 'Load the OpenAI language model and Claude and VLLM model' if model_name.startswith('claude'): kwargs_map = {'request_timeout': 'default_request_timeout', 'max_tokens': 'max_tokens_to_sample', 'logit_bias': None, '...
def load_openai_llm_with_args(args, prefix=None, fixed_version=True, **kwargs): if (prefix is None): prefix = '' else: prefix += '_' model_name = getattr(args, f'{prefix}model_name') temperature = getattr(args, f'{prefix}temperature') max_tokens = getattr(args, f'{prefix}max_tokens...
def get_model_category(llm: BaseLanguageModel): if isinstance(llm, ChatOpenAI): return 'openai' elif isinstance(llm, ChatAnthropic): return 'claude' elif isinstance(llm, VLLM): return 'vicuna' else: raise ValueError(f'Unknown model type: {type(llm)}')
def get_num_tokens(prompt: str, encoding='cl100k_base') -> int: encoding = tiktoken.get_encoding(encoding) return len(encoding.encode(prompt))
def get_toolkit_names(case: Dict[(str, Any)]) -> List[str]: if ('Toolkits' in case): return case['Toolkits'] return case['toolkits']
def print_intermediate_result_and_stop(results, stop_at): if (stop_at == 'preprocess'): print(results) else: print_prompt(results[0]) exit(0)
def filter_keys(inputs: Dict[(str, Any)], keys: List[str]) -> Dict[(str, Any)]: return {k: v for (k, v) in inputs.items() if (k in keys)}
def check_existence_by_name(new_name: str, existing_names: List[str]) -> bool: 'Check if the new name is already in the existing names' for name in existing_names: if ((new_name.lower() in name.lower()) or (name.lower() in new_name.lower())): return True return False
def append_new_items_without_duplicates(existing_items: List[Any], new_items: List[Any], name_func: Callable, serialize_func: Callable, thresh: float=0.6, num_threads: int=8, pbar: Optional[tqdm.tqdm]=None, verbose: bool=False) -> List[Any]: appended_items = [] scorer = rouge_scorer.RougeScorer(['rougeL'], us...
def convert_to_score(s, binarize_thres=None): v = float(s) if (binarize_thres is not None): v = float((v >= binarize_thres)) return v
class SimulatedObservation(NamedTuple): 'Simulated observation.' observation: str thought_summary: str log: str def __str__(self): return self.observation def __repr__(self): return self.observation
def batchify(data: List[Any], batch_size: int): 'Split data into batches.' return [data[i:(i + batch_size)] for i in range(0, len(data), batch_size)]
def thread_pool_executor(gen_func: Callable, batch_inputs: List[Any], unordered: bool=True, sequential_generation: bool=False, show_progress: bool=True, num_threads: int=10, request_timeout: int=60, enable_timer: bool=True) -> List[Any]: 'Run a generation function in parallel using a thread pool executor.\n Mo...
def insert_indent(s: str, indent: str='\t', insert_first=True) -> str: prefix = (indent if insert_first else '') return ((prefix + s.rstrip('\n ').replace('\n', ('\n' + indent))) + '\n')
def create_str(data: Dict[(str, str)], include_desc: bool=True, indent: str='\t') -> str: name = data['name'] prefix = (f'{indent}- ' if include_desc else '') desc = (f": {data['description']}" if include_desc else '') type = '' if ('type' in data): type = data['type'] if (not data...
class ArgParameter(TypedDict): 'The input parameter for a tool' name: str type: str description: str required: bool
class ArgReturn(TypedDict): 'The return value for a tool' name: str type: str description: str
class ArgException(TypedDict): 'The exception for a tool' name: str description: str
class DummyToolWithMessage(BaseTool): 'Tool that is run when invalid situation is encountered by agent.' name = 'dummy_tool_with_message' description = 'Called when tool is not actually run.' def _get_message(self, msg: str) -> str: return msg def _run(self, msg: str) -> str: ret...
class InvalidTool(DummyToolWithMessage): 'Tool that is run when invalid tool name is encountered by agent.' name = 'invalid_tool' description = 'Called when tool name is invalid.' available_tools: List[str] def _get_message(self, tool_name: str) -> str: availabel_tool_string = ', '.join(s...
def special_fix_for_json_obj(s: str, pos: int) -> str: 'Fix the string to make it a valid JSON object.' if (pos >= len(s)): return None if (s[pos] == '\\'): broken = s[pos:(pos + 2)] return s.replace(broken, broken[1]) elif (s[pos:(pos + 4)] == 'True'): return s.replace...
def get_first_json_object_str(s: str, enable_check=True, *args, **kwargs) -> str: 'Get the first JSON object from a string' regex = '```(?:json)?\\s*(\\{.*?\\})\\s*```' match = re.search(regex, s, flags=re.DOTALL) if match: s = match.group(1) s = s.lstrip() ret = s while True: ...
def load_dict(tool_input: str) -> Dict[(str, Any)]: 'Load a dictionary from a string.' try: params = json.loads(tool_input, strict=False) return params except Exception as e: msg = str(e) if msg.startswith('Invalid \\escape'): raise ValueError(f"Invalid syntax f...
def match_type(value: Any, expected_type: type) -> bool: if isinstance(value, expected_type): return True return (isinstance(value, int) and (expected_type == float))
def check_type(name: str, value: Any, expected_type: type): if (not match_type(value, expected_type)): raise ValueError(f'Invalid type for {name}: {type(value).__name__}, expected {expected_type.__name__}.')
def validate_inputs(parameters: List[ArgParameter], inputs: Dict[(str, Any)]): 'Validate the inputs for a tool.' remains = set(inputs.keys()) for param in parameters: name = param['name'] if (name in remains): remains.remove(name) if (name in inputs): expect...
def validate_outputs(returns: List[ArgReturn], outputs: Dict[(str, Any)]): 'Validate the outputs for a tool.' if (not isinstance(outputs, dict)): raise ValueError(f'Invalid type for outputs: {type(outputs).__name__}, expected dict.') if (list(outputs.keys()) == ['error']): return remai...
def run_with_input_validation(run_func: Callable, inputs: Dict[(str, str)], tool: BaseTool, raw_inputs: str, **kwargs): 'Run a tool with inputs, where the format of raw inputs is validated.' try: params = load_dict(raw_inputs) validate_inputs(tool.parameters, params) except Exception as e:...
def find_toolkit_spec(name: str, toolkits: List[Dict[(str, Any)]]) -> Dict[(str, Any)]: 'Find a toolkit specification by name.' for toolkit in toolkits: if (toolkit['toolkit'] == name): return toolkit raise ValueError(f'Toolkit not found: {name}.')
def format_toolkit_dict(toolkit: Dict[(str, Any)], namekey: str, add_risks: bool=True, indent: str='\t', use_simple_tool_desc: bool=False): 'Format a toolkit specified as a dictionary into a string.' toolkit_name = toolkit[namekey] desc = f'''<{toolkit_name}> toolkit with following tool APIs: ''' for ...
def get_tr_set(size=None, train_examples=None, batch_size=32, soft_labels=[], args=None): train_features = convert_examples_to_features(train_examples, label_list, args.max_seq_length, tokenizer, logger) if size: select_idx = np.random.choice(range(len(train_features)), size=size, replace=False) ...
def get_eval_set(eval_on, eval_batch_size=8): if (eval_on == 'dev'): eval_examples = processor.get_dev_examples(args.data_dir) elif (eval_on == 'test'): eval_examples = processor.get_test_examples(args.data_dir) else: raise ValueError('eval on dev or test set only') eval_featur...
def evaluate(prefix=None, model=None, args=None): eval_dataloader = get_eval_set(eval_on=args.eval_on, eval_batch_size=args.eval_batch_size) model.to(device) model.eval() (eval_loss, eval_accuracy) = (0, 0) (nb_eval_steps, nb_eval_examples) = (0, 0) y_true = [] y_pred = [] raw_logits =...
def save_result(prefix='Active', func_paras=None, report=None, table=None, output_dir=None): result_path = os.path.join(output_dir, (prefix + '.txt')) with open(result_path, 'a') as f: if func_paras: for para in func_paras: if (type(func_paras[para]) == np.ndarray): ...
def multi_argmax(values: np.ndarray, n_instances: int=1) -> np.ndarray: '\n Selects the indices of the n_instances highest values.\n\n Input:\n values: Contains the values to be selected from.\n n_instances: Specifies how many indices to return.\n Output:\n The indices of the n_instances l...
def uncertainty_sampling(model_instance, pool, size): '\n Uncertainty sampling policy.\n\n Input:\n model_instance: the model to do the uncertainty measure by give the labels prediction over unobserved data.\n pool: the unobserved data.\n size: the number of instances to be sampled in each round.\n Ou...
def nte_sampling(model_instance, pool, size): active_eval_loader = get_tr_set(train_examples=pool, batch_size=1, args=args) (raw_prediction, turncate_list) = active_eval(active_eval_loader, model_instance) sentence_nte = cal_nte(raw_prediction, turncate_list) query_index = multi_argmax(np.array(senten...
def cal_nte(logits, turncate): sentence_nte = [] for (idx, sent) in enumerate(logits): sent_sum = 0 for word in sent[:turncate[idx]]: tag_sum = 0 for tag in word: tag_sum += (tag * math.log(tag)) sent_sum += tag_sum sentence_nte.appen...
def qbc_sampling(model_com, pool, n_instance): com_pred = [] active_eval_loader = get_tr_set(train_examples=pool, batch_size=1, args=args) for _model in model_com: (raw_prediction, turncate_list) = active_eval(active_eval_loader, _model) tag_prediction = result2tag(raw_prediction, turncate...
def cal_vote_entropy(mc_pred): '\n Calculate the vote entropy\n\n Input:\n mc_pred: 3d-shape (num_mc_model * num_sentence * max_len * n_tags)\n Output:\n vote_entropy: 2d-shape (num_sentence * max_len)\n ' num_mc_model = len(mc_pred) num_sentence = mc_pred[0].shape[0] print('vote_matrix') ...
def result2tag(result, turncate): '\n Convert the result with 3-d shape to the tags with 2-d shape. \n ' sentences = [] for (idx, sentence) in enumerate(result): valid_len = turncate[idx] words = [] for word in sentence[:valid_len]: word = word.tolist() ta...
def random_sampling(model_instance, input_data, n_instances): '\n Random sampling policy.\n\n Input:\n model_instance: model\n input_data: the unobserved data.\n n_instances: the number of instances to be sampled in each round.\n Output:\n query_index: the n_instances index of sampled data.\n in...
def active_train(data_loader=None, model=None, Epochs=5, soft_loader=None, args=None): config = BertConfig.from_pretrained(args.bert_model, num_labels=num_labels, finetuning_task=args.task_name) if (model == None): model = Ner.from_pretrained(args.bert_model, from_tf=False, config=config) return_m...
def active_eval(active_data_loader=None, model=None): model.to(device) model.eval() (eval_loss, eval_accuracy) = (0, 0) (nb_eval_steps, nb_eval_examples) = (0, 0) y_true = [] y_pred = [] raw_logits = [] turncate_list = [] label_map = {i: label for (i, label) in enumerate(label_list...
def active_learn(init_flag=None, train_data=None, num_initial=200, active_policy=None, num_query=5, num_sample=[100, 100, 100, 100, 100], dev_data=None, fit_only_new_data=False, Epochs=10, prefix='Active', args=None): '\n Implement active learning initializaiton and learning loop\n ' func_paras = locals() ...
class InputExample(object): 'A single training/test example for simple sequence classification.' def __init__(self, guid, text_a, text_b=None, label=None): 'Constructs a InputExample.\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the...
class InputFeatures(object): 'A single set of features of data.' def __init__(self, input_ids, input_mask, segment_ids, label_id, valid_ids=None, label_mask=None): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id ...
def readfile(filename): 'read file' f = open(filename) data = [] sentence = [] label = [] for line in f: if ((len(line) == 0) or line.startswith('-DOCSTART') or (line[0] == '\n')): if (len(sentence) > 0): data.append((sentence, label)) senten...
class DataProcessor(object): 'Base class for data converters for sequence classification data sets.' def get_train_examples(self, data_dir): 'Gets a collection of `InputExample`s for the train set.' raise NotImplementedError() def get_dev_examples(self, data_dir): 'Gets a collect...
class NerProcessor(DataProcessor): 'Processor for the CoNLL-2003 data set.' def get_train_examples(self, data_dir, size=None): 'See base class.' train_file = self._read_tsv(os.path.join(data_dir, 'train.txt')) return_example = self._create_examples(train_file, 'train') if size...
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, logger): 'Loads a data file into a list of `InputBatch`s.' label_map = {label: i for (i, label) in enumerate(label_list, 1)} features = [] for (ex_index, example) in enumerate(examples): textlist = example.text_a...
class Ner(BertForTokenClassification): def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, valid_ids=None, attention_mask_label=None): sequence_output = self.bert(input_ids, token_type_ids, attention_mask, head_mask=None)[0] (batch_size, max_len, feat_dim) = sequen...
def get_word_embedding(sp_output_dir=None): model = Ner.from_pretrained(sp_output_dir) tokenizer = BertTokenizer.from_pretrained(sp_output_dir, do_lower_case=args.do_lower_case) for (name, parameters) in model.named_parameters(): if (name == 'bert.embeddings.word_embeddings.weight'): b...
def x_reconstruct(sequence): '\n Experiment helper function. To reconstruct the sentence from a series of idx of word\n ' seq_list = [] seq_str = ' ' for item in sequence: if (item == (n_words - 1)): break seq_list.append(idx2word[item]) return seq_str.join(seq_list)
def score_gpt(sentence): tokenize_input = gpt_tokenizer.tokenize(sentence) tensor_input = torch.tensor([gpt_tokenizer.convert_tokens_to_ids(tokenize_input)]) loss = gpt_model(tensor_input, lm_labels=tensor_input) return math.exp(loss)
def high_quality(sequence, score_limit_upper=500, score_limit_low=0): score = score_gpt(sequence) return (((score >= score_limit_low) and (score < score_limit_upper)), score)
def extract_same_elem(list1, list2): '\n Utility function to extract the same element in two list, will be called in function find_subseq_pair\n ' set1 = set(list(list1)) set2 = set(list(list2)) iset = set1.intersection(set2) return list(iset)
def most_similar(value, top_n): '\n Get the top_n most similar words given an embedding\n\n Input:\n value: a word embedding\n top_n: the number of entries(candidates) in the returned array\n Output:\n words_array: candidate array which contains the top_n most similar words, each entry is a word\n ' ...
def find_sub_seq(sequence, window_size, valid_tag_bar): '\n Find the sub-sequence given a window_size and the limit of valid tags.\n\n Input:\n sequence: a single sequence with the shape (max_len,)\n window_size: the length of sub-sequence \n valid_tag_bar: the lower limit over which the sub-sequence w...
def soft_pair(candidate): valid_tag_list = [] for (idx, item) in enumerate(candidate): tags = item.label exclude_label = ['O', '[CLS]', '[SEP]', '[UKN]'] valid_tag_count = 0 for tag in tags: if (tag not in exclude_label): valid_tag_count += 1 ...
def soft_pair_index_generator(equal_len_index_list, pair_num, valid_tag_bar): pair_index_list = [] len_range = [] for i in range(len(equal_len_index_list)): if (equal_len_index_list[i].shape[0] >= 2): len_range.append((i + 1)) for i in range(pair_num): temp_len = random.cho...
def lf_mixup(mixdata, sentence1_idx, start_idx1, sentence2_idx, start_idx2, hyper_lambda): '\n Label-fixed Mixup.\n Note that here the start_idx1 and start_idx2 are only int rather than array.\n ' new_seq1 = list(mixdata[sentence1_idx].text_a.split()) new_seq2 = list(mixdata[sentence2_idx].text_a.split...
def lf_augment(candidate_data, num_mixup, hyper_alpha, score_limit_upper=500, score_limit_low=0): '\n Label_fixed augment.\n Given the candidate dataset and number of samples to be generated via mixup method, augment the training dataset by implementing mixup.\n ' global GUID_COUNT time_start = time.ti...
def tag2onehot(tag): label_map = {label: i for (i, label) in enumerate(label_list, 1)} tagid = label_map[tag] onehot_tag = np.zeros((len(label_map) + 1)) onehot_tag[tagid] = 1 return onehot_tag
def onehot2tag(tag): label_map = {label: i for (i, label) in enumerate(label_list, 1)} reverse_label_map = {i: label for (i, label) in enumerate(label_list, 1)} return_tag = [] for word in tag: if (word.any() != 0): idx = np.where((word != 0)) if (len(idx[0]) > 1): ...
def slack_mixup(mixdata, sentence1_idx, sentence2_idx, start_idx1, start_idx2, hyper_lambda): '\n This function implement sentence-level mixup, it will be called by the function augment().\n ' new_seq1 = list(mixdata[sentence1_idx].text_a.split()) new_seq2 = list(mixdata[sentence2_idx].text_a.split()) ...
def slack_augment(candidate_data=None, num_mixup=None, hyper_alpha=8, score_limit_upper=500, score_limit_low=0): '\n Given the candidate dataset and number of samples to be generated via mixup method, augment the training dataset by implementing mixup.\n Implement augmentation via slack-mixup\n ' global GU...
def soft_mixup(candidate_1, candidate_2, hyper_lambda): '\n This function implement sentence-level mixup, it will be called by the function soft_augment().\n ' seq1 = list(candidate_1.text_a.split()) seq2 = list(candidate_2.text_a.split()) y1 = copy.deepcopy(candidate_1.label) y2 = copy.deepcopy...
def soft_augment(candidate_data=None, num_mixup=None, hyper_alpha=8, score_limit_upper=500, score_limit_low=0): global GUID_COUNT print('Implementing soft mixup augmentation, which may take hundreds of seconds') time_start = time.time() new_sample_count = 0 mixup_data = [] mixup_label = [] ...
def active_augment_learn(init_flag=None, train_data=None, num_initial=200, active_policy=uncertainty_sampling, augment_method=lf_augment, num_query=5, num_sample=[100, 100, 100, 100, 100], augment_rate=0.2, augment_decay=1, hyper_alpha=8, alpha_decay=1, Epochs=10, score_limit_low=0, score_limit_upper=500, fit_only_ne...
class coco_voc(): def __init__(self, image_set, devkit_path=None, image_path=None): self._name = (('coco' + '_') + image_set) self._image_set = image_set self._devkit_path = (self._get_default_path() if (devkit_path is None) else devkit_path) self._data_path = os.path.join(self._d...
def get_vocab_top_k(vocab, k): v = dict() for key in vocab.keys(): v[key] = vocab[key][:k] return v
def get_vocab_counts(image_ids, coco_caps, max_cap, vocab): counts = np.zeros((len(image_ids), len(vocab['words'])), dtype=np.float) for i in xrange(len(image_ids)): ann_ids = coco_caps.getAnnIds(image_ids[i]) assert (len(ann_ids) >= max_cap), 'less than {:d} number of captions for image {:d}'...
def get_vocab(imset, coco_caps, punctuations, mapping): image_ids = coco_caps.getImgIds() image_ids.sort() t = [] for i in xrange(len(image_ids)): annIds = coco_caps.getAnnIds(image_ids[i]) anns = coco_caps.loadAnns(annIds) tmp = [pos_tag(word_tokenize(str(a['caption']).lower()...
class State(Enum): WAITING = 0 RUNNING = 1 FINISHED = 2
class Log(IntEnum): error = 0 warning = 1 notice = 2 info = 3 debug1 = 4 debug2 = 5 debug3 = 6 debug4 = 7 debug5 = 8
class Common(): def __init__(self): pass '\n Global variables\n ' 'top directory' REPOSITORY_DIR = 'pgpi_repository' CONF_FILE = 'hosts.conf' STAT_FILE = 'stat.dat' 'tables directory' TABLES_DIR = 'tables' TABLES_FILE = 'log.csv' TABLES_QUERY_DIR = 'query' TA...
class Database(Repository): def __init__(self, base_dir='.', log_level=Log.info): self.set_base_dir(base_dir) self.LogLevel = log_level '\n Public methods\n ' def get_connection_param(self, serverId, database='postgres'): 'Return a connection param using the values in the h...
class GetTables(MergePlan): def __init__(self, base_dir='.', log_level=Log.info): self.set_base_dir(base_dir) self.ServerId = '' self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId def __exec_select_cmd(self, connection, sql): _...
class Grouping(Repository): def __init__(self, base_dir='.', log_level=Log.info): self.ServerId = '' self.is_parallel = False self.numWorkers = 1 self.numPlanWorkers = 1 self.set_base_dir(base_dir) self.LogLevel = log_level def __set_serverId(self, serverId): ...
class PrepareMergeRows(): def __init__(self, base_dir='.', log_level=Log.info): self.set_base_dir(base_dir) self.LogLevel = log_level def __init_val(self): self.is_parallel = False self.numWorkers = 1 self.numPlanWorkers = 1 def __add_helper_objects(self, Plans, ...
class MergeRows(Repository, PrepareMergeRows): def __init__(self, log_level=Log.info): self.ServerId = '' self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId def __get_actual_rows(self, Plans, depth): '\n Return the "Actual Rows"...
class AddRows(Repository, PrepareMergeRows): def __init__(self, log_level=Log.info): self.ServerId = '' self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId def __add_rows(self, Plans): def add_rows_and_loops(plan): if ('Wor...
class MergePlan(AddRows, MergeRows): def __init__(self, log_level=Log.info): self.ServerId = '' self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId '\n Public methods\n ' def merge_plans(self, leader_plan, worker_plans): '\n ...
class PushParam(Database, Repository): def __init__(self, base_dir='.', log_level=Log.info): self.set_base_dir(base_dir) self.LogLevel = log_level def __trans(self, Plans, depth): def merge(schemas, relations): result = [] if (type(schemas) is not list): ...