id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
164,797 | from typing import List
from uie.extraction.record_schema import RecordSchema
from uie.extraction.predict_parser import get_predict_parser, PredictParser
from uie.extraction.scorer import Metric, RecordMetric, OrderedRecordMetric
def eval_pred(predict_parser: PredictParser, gold_list, pred_list, text_list=None, raw_lis... | null |
164,798 |
The provided code snippet includes necessary dependencies for implementing the `convert_spot_asoc` function. Write a Python function `def convert_spot_asoc(spot_asoc_instance, structure_maker)` to solve the following problem:
将一个 Spot-Asoc 实例转换成目标字符串 Args: spot_asoc_instance ([type]): [description] structure_maker ([... | 将一个 Spot-Asoc 实例转换成目标字符串 Args: spot_asoc_instance ([type]): [description] structure_maker ([type]): [description] Returns: [type]: [description] |
164,799 |
The provided code snippet includes necessary dependencies for implementing the `convert_spot_asoc_name` function. Write a Python function `def convert_spot_asoc_name(spot_asoc_instance, structure_maker)` to solve the following problem:
将一个 Spot-Asoc-Name 实例转换成目标字符串 Args: spot_asoc_instance ([type]): [description] str... | 将一个 Spot-Asoc-Name 实例转换成目标字符串 Args: spot_asoc_instance ([type]): [description] structure_maker ([type]): [description] Returns: [type]: [description] |
164,800 | from typing import Dict
def list_dictionary(d, n_tab=-1):
if isinstance(d, list):
for i in d:
list_dictionary(i, n_tab)
elif isinstance(d, dict):
n_tab += 1
for key, value in d.items():
if key == '<end>':
print("{}{}".format(" " * n_tab, key))
... | null |
164,801 | from typing import Dict
def get_label_name_tree(label_name_list, tokenizer, end_symbol='<end>'):
sub_token_tree = dict()
label_tree = dict()
for typename in label_name_list:
after_tokenized = tokenizer.encode(typename, add_special_tokens=False)
# label_tree[typename] = tokenizer.convert_id... | null |
164,802 | from collections import defaultdict
from copy import deepcopy
from typing import Dict, List
import sys
def tuple_offset(offset):
if isinstance(offset, tuple):
return offset
else:
return tuple(offset) | null |
164,803 | from collections import defaultdict
from copy import deepcopy
from typing import Dict, List
import sys
def warning_tp_increment(gold, pred, prefix):
sys.stderr.write(f"{prefix} TP Increment Warning, Gold Offset: {gold['offset']}\n")
sys.stderr.write(f"{prefix} TP Increment Warning, Pred Offset: {pred['offset']... | null |
164,804 | import re
def fix_unk_from_text(span, text, unk='<unk>'):
"""
Find span from the text to fix unk in the generated span
从 text 中找到 span,修复span
Example:
span = "<unk> colo e Bengo"
text = "At 159 meters above sea level , Angola International Airport is located at Ícolo e Bengo , part of Luanda Pro... | null |
164,805 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | null |
164,806 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | null |
164,807 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | null |
164,808 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | null |
164,809 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | add right bracket to fill ill-formed :param tree_str: :return: |
164,810 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | get str from event tree :param tree: :return: |
164,811 | from collections import Counter
import logging
from nltk.tree import ParentedTree
import re
from typing import Tuple, List, Dict
from uie.extraction.constants import (
null_span,
type_start,
type_end,
span_start,
)
from uie.extraction.predict_parser.predict_parser import PredictParser
from uie.extractio... | null |
164,812 | import json
from collections import defaultdict
from typing import List
class RecordSchema:
def __init__(self, type_list, role_list, type_role_dict):
self.type_list = type_list
self.role_list = role_list
self.type_role_dict = type_role_dict
def __repr__(self) -> str:
return f"Typ... | null |
164,813 | from collections import defaultdict, OrderedDict
import os
from uie.extraction.record_schema import RecordSchema
from uie.extraction.predict_parser import get_predict_parser
from uie.sel2record.record import EntityRecord, MapConfig, RelationRecord, EventRecord
import logging
The provided code snippet includes necessar... | Mapping generated spot-asoc result to Entity/Relation/Event 将抽取的Spot-Asoc结构,根据不同的 Schema 转换成 Entity/Relation/Event 结果 |
164,814 | from asyncio.log import logger
import sys
from typing import Tuple
import numpy
import logging
The provided code snippet includes necessary dependencies for implementing the `match_sublist` function. Write a Python function `def match_sublist(the_list, to_match)` to solve the following problem:
:param the_list: [1, 2,... | :param the_list: [1, 2, 3, 4, 5, 6, 1, 2, 4, 5] :param to_match: [1, 2] :return: [(0, 1), (6, 7)] |
164,815 | from asyncio.log import logger
import sys
from typing import Tuple
import numpy
import logging
def check_overlap(x, y):
if x[0] > y[1] or y[0] > x[1]:
return False
else:
return True | null |
164,816 | from asyncio.log import logger
import sys
from typing import Tuple
import numpy
import logging
def get_index_tuple(matched: Tuple[int, int]):
return tuple(range(matched[0], matched[1] + 1)) | null |
164,817 | from asyncio.log import logger
import sys
from typing import Tuple
import numpy
import logging
def span_to_token(text, span_to_token_strategy='space'):
if span_to_token_strategy == 'space':
return text.split(' ')
elif span_to_token_strategy == 'list':
return list(text)
else:
raise N... | null |
164,818 | import json
import re
from tqdm import tqdm
import transformers as huggingface_transformers
from uie.extraction.record_schema import RecordSchema
from uie.sel2record.record import MapConfig
from uie.extraction.scorer import *
from uie.sel2record.sel2record import SEL2Record
import math
import os
def read_json_file(fil... | null |
164,819 | import json
import re
from tqdm import tqdm
import transformers as huggingface_transformers
from uie.extraction.record_schema import RecordSchema
from uie.sel2record.record import MapConfig
from uie.extraction.scorer import *
from uie.sel2record.sel2record import SEL2Record
import math
import os
class RecordSchema:
... | null |
164,820 | import json
import re
from tqdm import tqdm
import transformers as huggingface_transformers
from uie.extraction.record_schema import RecordSchema
from uie.sel2record.record import MapConfig
from uie.extraction.scorer import *
from uie.sel2record.sel2record import SEL2Record
import math
import os
special_to_remove = {'<... | null |
164,821 | import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoTokenizer,
DataCollatorForSeq2Seq,
HfArgumentParser,
... | null |
164,822 | from tensorboard.backend.event_processing import event_accumulator
import matplotlib.pyplot as plt
def read_tensorboard_data(tensorboard_log_path, val_name):
ea = event_accumulator.EventAccumulator(tensorboard_log_path)
ea.Reload()
print("All scalers:")
print(ea.scalars.Keys())
val = ea.scala... | null |
164,823 | from tensorboard.backend.event_processing import event_accumulator
import matplotlib.pyplot as plt
def plot(vals, val_names, max_step=None):
plt.figure()
for val, val_name in zip(vals, val_names):
x = [i.step for i in val]
y = [i.value for i in val]
if max_step is not None:
... | null |
164,824 | import json
import os
from collections import OrderedDict
import numpy as np
from tabulate import tabulate
def align_float(x):
return '%.2f' % x if isinstance(x, float) else x | null |
164,825 | import json
import os
from collections import OrderedDict
import numpy as np
from tabulate import tabulate
def parse_trainer_state(filename):
trainer_state = json.load(open(filename))
if trainer_state['best_model_checkpoint'] is not None:
return trainer_state['best_model_checkpoint'].split('/')[-1].rep... | null |
164,826 | import json
import os
from collections import OrderedDict
import numpy as np
from tabulate import tabulate
def parse_global_step(filename):
return str(json.load(open(filename))['global_step']) | null |
164,827 | import json
import os
from collections import OrderedDict
import numpy as np
from tabulate import tabulate
def check_out_of_memory(filename):
if os.path.exists(filename):
try:
with open(filename) as fin:
for line in fin:
if 'CUDA out of memory' in line:
... | null |
164,828 | import json
import os
from collections import OrderedDict
import numpy as np
from tabulate import tabulate
def get_run_name(folder_name, prefix):
split_list = folder_name.replace('/', '_').split('_') \
if prefix == 'run' \
else folder_name.split('_')[1:]
new_att_list = list()
for att in spl... | null |
164,829 | import argparse
import json
import os
from collections import Counter, defaultdict
from transformers import AutoTokenizer
from tabulate import tabulate
from tqdm import tqdm
from uie.seq2seq.t5_bert_tokenizer import T5BertTokenizer
from uie.extraction.dataset_processer import PrefixGenerator
from uie.extraction.record_... | null |
164,830 | import argparse
import json
import os
import sys
import numpy as np
from pprint import pprint
from uie.extraction.scorer import EntityScorer, RelationScorer, EventScorer
def read_file(file_name):
return [line for line in open(file_name).readlines()] | null |
164,831 | import argparse
import json
import os
import sys
import numpy as np
from pprint import pprint
from uie.extraction.scorer import EntityScorer, RelationScorer, EventScorer
def write_to_file(result, output_filename, prefix=None):
with open(output_filename, 'w') as output:
for key, value in result.items():
... | null |
164,832 | import json
import os
import random
import argparse
from collections import OrderedDict
from tqdm import tqdm
import pdb
visited_type = set()
def get_visited_type(instance_id_list, instance_type_dict):
visited_type = set()
for i, instance_id in enumerate(instance_id_list):
if i == 0:
visite... | null |
164,833 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
random.seed(seed)
np.random.seed(seed)
THRESHOLD = 0.8
def noise_entity_type(entity_list):
entity_type_list = []
for entity in entity_list:
entity_type_list.append(entity["t... | null |
164,834 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
random.seed(seed)
np.random.seed(seed)
NOISE_OFFSET_RANGE = list(range(NOISE_OFFSET_THRESHOLD))
NOISE_OFFSET_WEIGHT = np.exp(- DECAY_COEF * np.array(NOISE_OFFSET_RANGE))
NOISE_OFFSET_WEIGHT ... | null |
164,835 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
random.seed(seed)
np.random.seed(seed)
THRESHOLD = 0.8
def noise_entity_with_other_entity(entity_list):
type_entity_mapping = {}
for entity in entity_list:
entity_type = ent... | null |
164,836 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
random.seed(seed)
np.random.seed(seed)
THRESHOLD = 0.8
def noise_relation_type(triple_list):
relation_type_list = []
for triple in triple_list:
relation_type_list.append(tri... | null |
164,837 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
random.seed(seed)
np.random.seed(seed)
TRIPLE_THRESHOLD = [0.6, 0.8]
def noise_triple_num(triple_list, entity_list):
noised_triple_list = []
for triple in triple_list:
p = n... | null |
164,838 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
def build_entity_dict(entity_list):
entity_dict = {}
for entity in entity_list:
entity_uri = entity["uri"]
entity_dict[entity_uri] = entity
return entity_dict | null |
164,839 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
def update_relation_triple_by_noised_entity(triple_list, noised_entity_dict):
noised_triple_list = []
for triple in triple_list:
noised_triple = deepcopy(triple)
hea... | null |
164,840 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
def create_spot_asoc_field(instance_entity_list, instance_triple_list):
instance_spot_asoc_list = []
for entity in instance_entity_list:
instance_spot_asoc = {
"... | null |
164,841 | import json
import os
import random
import argparse
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import pdb
def create_record_field(instance_spot_asoc_list):
instance_record = "<extra_id_0> "
for instance_spot_asoc in instance_spot_asoc_list:
instance_record += "<extra_id_0> "
... | null |
164,842 | import json
import os
import random
import argparse
from tqdm import tqdm
import pdb
def create_spot_asoc_field(instance_entity_list, instance_triple_list):
instance_spot_asoc_list = []
for entity in instance_entity_list:
instance_spot_asoc = {
"span": entity["text"],
"label": en... | null |
164,843 | import os
import json
import math
import time
import argparse
from tqdm import tqdm
import networkx as nx
import pdb
def score(x_label, y_label, add_coef=True):
x_label = set(x_label)
y_label = set(y_label)
y2x_score = len(x_label & y_label) / len(x_label)
if add_coef:
y2x_score += 1 / len(y_l... | null |
164,844 | import json
import os
import random
import argparse
from tqdm import tqdm
from nltk.tokenize import WordPunctTokenizer
import numpy as np
import pdb
ALL_ENTITY_CNT = 0
NOMATCH_ENTITY_CNT = 0
NON_OFFSET_ENTITY_CNT = 0
def word_tokenize(text):
return word_tokenizer.tokenize(text)
text_length_list = []
relation_list =... | null |
164,845 | from collections import Counter
import os
import json
from typing import Dict, List
from tqdm import tqdm
from universal_ie.generation_format.generation_format import GenerationFormat
from universal_ie.generation_format import generation_format_dict
from universal_ie.generation_format.structure_marker import BaseStruct... | null |
164,846 | from collections import Counter
import os
import json
from typing import Dict, List
from tqdm import tqdm
from universal_ie.generation_format.generation_format import GenerationFormat
from universal_ie.generation_format import generation_format_dict
from universal_ie.generation_format.structure_marker import BaseStruct... | null |
164,847 | from typing import List
import os
import sys
def tokens_to_str(tokens: List[str], language: str = 'en') -> str:
if language == 'en':
return ' '.join(tokens)
elif language == 'zh':
return ''.join(tokens)
else:
raise NotImplementedError('Language %s not supported' % language) | null |
164,848 | from typing import List
import os
import sys
def label_format(s):
import re
def uncamelize(s):
re_outer = re.compile(r'([^A-Z ])([A-Z])')
re_inner = re.compile(r'\b[A-Z]+(?=[A-Z][a-z])')
sub = re_inner.sub(r'\g<0> ', re_outer.sub(r'\1 \2', s)).lower()
return sub
def remove(s)... | null |
164,849 | from typing import List
import os
import sys
The provided code snippet includes necessary dependencies for implementing the `change_ptb_token_back` function. Write a Python function `def change_ptb_token_back(token)` to solve the following problem:
将 PTBTokenized 的 Token 转换会原始字符串 Args: token (str): PTBTokenize 后的 Toke... | 将 PTBTokenized 的 Token 转换会原始字符串 Args: token (str): PTBTokenize 后的 Token 字符串 Returns: str: 原始 Token 字符串 |
164,850 | from typing import List
import os
import sys
global_mislabel_log = set()
def change_name_using_label_mapper(label_name, label_mapper):
if label_mapper is None or len(label_mapper) == 0:
return label_name
if label_name not in label_mapper:
print(f"{label_name} not found in mapper")
globa... | null |
164,851 | from collections import Counter
import json
from typing import List, Optional, Tuple, Set
from tqdm import tqdm
from universal_ie.task_format.task_format import TaskFormat
from universal_ie.utils import tokens_to_str
from universal_ie.ie_format import Entity, Label, Sentence, Span
The provided code snippet includes ne... | Given a sequence corresponding to BIO tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"), as otherwise it is possible to get a perfect precision score whilst still predicting ill-formed ... |
164,852 | from collections import Counter
import json
from typing import List, Optional, Tuple, Set
from tqdm import tqdm
from universal_ie.task_format.task_format import TaskFormat
from universal_ie.utils import tokens_to_str
from universal_ie.ie_format import Entity, Label, Sentence, Span
def _iob1_start_of_chunk(
prev_bio... | Given a sequence corresponding to IOB1 tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also included (i.e., those where "B-LABEL" is not preceded by "I-LABEL" or "B-LABEL"). # Parameters tag_sequence : `List[str]`, required. The integer class la... |
164,853 | from collections import Counter
import json
from typing import List, Optional, Tuple, Set
from tqdm import tqdm
from universal_ie.task_format.task_format import TaskFormat
from universal_ie.utils import tokens_to_str
from universal_ie.ie_format import Entity, Label, Sentence, Span
The provided code snippet includes ne... | Given a sequence corresponding to BMES tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"), as otherwise it is possible to get a perfect precision score whilst still predicting ill-formed... |
164,854 | from collections import Counter
import json
from typing import List, Optional, Tuple, Set
from tqdm import tqdm
from universal_ie.task_format.task_format import TaskFormat
from universal_ie.utils import tokens_to_str
from universal_ie.ie_format import Entity, Label, Sentence, Span
def bioul_tags_to_spans(
tag_seque... | bmeso -> bioul B = Beginning I/M = Inside / Middle L/E = Last / End O = Outside U/W/S = Unit-length / Whole / Singleton |
164,855 | from collections import Counter
import json
from typing import List, Optional, Tuple, Set
from tqdm import tqdm
from universal_ie.task_format.task_format import TaskFormat
from universal_ie.utils import tokens_to_str
from universal_ie.ie_format import Entity, Label, Sentence, Span
def bioul_tags_to_spans(
tag_seque... | bmeso -> bioul B = Beginning I/M = Inside / Middle L/E = Last / End O = Outside U/W/S = Unit-length / Whole / Singleton |
164,856 | from collections import defaultdict
from typing import List, Dict
from universal_ie.utils import tokens_to_str
from universal_ie.generation_format.generation_format import GenerationFormat, StructureMarker
from universal_ie.ie_format import Entity, Event, Label, Relation, Span
def convert_spot_asoc(spot_asoc_instance,... | null |
164,857 | import json
from collections import defaultdict
from typing import List
class RecordSchema:
def __init__(self, type_list, role_list, type_role_dict):
self.type_list = type_list
self.role_list = role_list
self.type_role_dict = type_role_dict
def read_from_file(filename):
lines = o... | null |
164,858 | import os
import math
import shutil
import random
import argparse
def split_ratio_file(in_filename, out_filename, ratio=0.1, seed=None):
lines = open(in_filename).readlines()
if seed:
random.seed(seed)
random.shuffle(lines)
lines = lines[:math.ceil(len(lines) * ratio)]
with open(out_fil... | null |
164,859 | import os
import shutil
import random
import argparse
from collections import defaultdict
import json
import sys
from universal_ie.record_schema import RecordSchema
def n_shot_smaple(source_filename, target_filename, record_schema,
spot_asoc_key='spot', num_shot=5, min_len=None, seed=None):
trai... | null |
164,860 | import json
import os
import sys
from collections import Counter
import tabulate
def count_line_in_file(filename):
return sum([1 for _ in open(filename)])
def count_record_in_file(filename, key):
counter = Counter()
for line in open(filename):
instance = json.loads(line)
counter.update([key ... | null |
164,861 | import json
import os
import sys
from collections import Counter
import tabulate
def walk_dir(folder_name):
for root, dirs, files in os.walk(folder_name):
for file in dirs:
folder_name = os.path.join(root, file)
if os.path.exists(f"{os.path.join(root, file)}/record.schema"):
... | null |
164,863 | import sys
import logging
import pdb
import os
import json
from pathlib import Path
import pickle
from contextlib import nullcontext
from dataclasses import asdict, fields
from transformers.hf_argparser import HfArgumentParser
from transformers.training_args_seq2seq import Seq2SeqTrainingArguments
from transformers.mod... | null |
164,864 | import sys
import logging
import pdb
import os
import json
from pathlib import Path
import pickle
from contextlib import nullcontext
from dataclasses import asdict, fields
from transformers.hf_argparser import HfArgumentParser
from transformers.training_args_seq2seq import Seq2SeqTrainingArguments
from transformers.mod... | null |
164,865 | import copy
import math
import os
import warnings
import torch.nn.functional as F
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.utils.checkpoint import checkpoint
from transformers.activations import ACT2FN
from transformers.file_utils import (
DUMMY_INPUTS,
DUMMY_MASK,
... | Load tf checkpoints in a pytorch model. |
164,866 | import importlib
from collections import OrderedDict
from transformers.configuration_utils import PretrainedConfig
from transformers.dynamic_module_utils import get_class_from_dynamic_module
from transformers.file_utils import copy_func
from transformers.utils import logging
from transformers.models.auto.configuration_... | null |
164,867 | import importlib
from collections import OrderedDict
from transformers.configuration_utils import PretrainedConfig
from transformers.dynamic_module_utils import get_class_from_dynamic_module
from transformers.file_utils import copy_func
from transformers.utils import logging
from transformers.models.auto.configuration_... | null |
164,868 | import importlib
from collections import OrderedDict
from transformers.configuration_utils import PretrainedConfig
from transformers.dynamic_module_utils import get_class_from_dynamic_module
from transformers.file_utils import copy_func
from transformers.utils import logging
from transformers.models.auto.configuration_... | null |
164,869 | import importlib
from collections import OrderedDict
from transformers.configuration_utils import PretrainedConfig
from transformers.dynamic_module_utils import get_class_from_dynamic_module
from transformers.file_utils import copy_func
from transformers.utils import logging
from transformers.models.auto.configuration_... | null |
164,880 | import json
from typing import Callable, Tuple
import logging
import datasets.load
from datasets.dataset_dict import DatasetDict
from datasets.metric import Metric
from datasets.arrow_dataset import Dataset, concatenate_datasets
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
from transformers.... | null |
164,881 | from dataclasses import dataclass
from typing import Union, List, Dict, Optional
from transformers.pipelines.text2text_generation import ReturnType, Text2TextGenerationPipeline
from transformers.tokenization_utils import TruncationStrategy
from transformers.tokenization_utils_base import BatchEncoding
from third_party.... | null |
164,882 | from copy import deepcopy
from typing import Optional, Union, Any, Callable, AsyncContextManager, List, Dict
from dataclasses import dataclass, field
import collections
import asyncio
import sys
import subprocess
import warnings
import time
from tenacity import retry, wait_random_exponential, stop_after_delay, before_s... | null |
164,883 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
The provided code snippet includes necessary dependencies for implementing the `quote_normalization` function. Write a Python function `def quote_normalization(question)` to solve the f... | Normalize all usage of quotation marks into a separate \" |
164,885 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
def question_subword_matrix(processed_question_toks, relations, tokenizer):
# question: a str of question
# relations: matrix of relations
# return: new subword-based relati... | null |
164,886 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
def subword_dict(input_ids):
word_subword_mapping = defaultdict()
for sub_idx, word_idx in enumerate(input_ids):
if word_idx is None:
break
if word_id... | null |
164,887 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
def _add_prefix(prefix_num, new_mapping):
new_col_seq = []
for col_idx in new_mapping:
new_col_seq.append(prefix_num + col_idx)
return new_col_seq
The provided code ... | load new_mapping_zip |
164,888 | import json
import pickle
import pdb
import argparse
dummy_relations = ['question-table-nomatch', 'question-column-nomatch', 'column-question-nomatch', 'table-question-nomatch']
def flatten_fk(foreign_keys_lst):
final_lst = []
for fk_pairs in foreign_keys_lst:
for columns in fk_pairs:
final_... | null |
164,889 | import json
import pdb
from map_subword_serialize import schema_linking_subword
import argparse
from transformers import AutoTokenizer
import pickle
def merge_graph_pedia(graph_pedia_train, graph_pedia_dev, graph_all_output_path=None):
# keep the index of train set as original.
graph_pedia_all = pickle.load(op... | null |
164,890 | import re
ex = example.replace('t1', 'concert')
ex = ex.replace('t2', 'stadium')
def map_alias(example):
alias_map = {}
example_list = example.split(' ')
for i, ex in enumerate(example_list):
if ex in ['as', 'AS']:
alias_map[example_list[i + 1]] = example_list[i - 1]
return alias_ma... | null |
164,891 | import re
ex = example.replace('t1', 'concert')
ex = ex.replace('t2', 'stadium')
def replace_alias(example, mapping):
ex = example
for k, v in mapping.items():
ex = ex.replace(k, v)
if 'as' in example:
ex = ex.replace(' as ' + v, '')
elif 'AS' in example:
ex = ex... | null |
164,892 | import json
import argparse
def merge_train(train_spider, train_others, output_path=None):
total_train = train_spider + train_others
if output_path:
json.dump(total_train, open(output_path, "w"), indent=4) | null |
164,893 | import os, json, pickle, argparse, sys, time
import pdb
import math, dgl, torch
import numpy as np
import os, sys
from collections import defaultdict
from transformers import AutoTokenizer
def process_subgraph_datasets(processer, seq2seq_dataset, output_path = None, graph_output_path = None, graph_pedia=None, train_le... | null |
164,896 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
def subword_dict(input_ids):
word_subword_mapping = defaultdict()
for sub_idx, word_idx in enumerate(input_ids):
if word_idx is None:
break
if word_id... | null |
164,897 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
def schema_linking_subword(question_subword_dict: dict, schema_2_ids: dict, schema_linking: tuple, question_subword_len: int, schema_subword_len: int, schema_idx_ori=None):
# assert... | null |
164,898 | import os, json, pickle, argparse, sys, time
import pdb
import torch
from collections import defaultdict
import numpy as np
import re
def schema_linking_subword_sampled(question_subword_dict: dict, schema_2_ids: dict, schema_linking: tuple, question_subword_len: int, schema_subword_len: int, schema_idx_ori=None):
... | null |
164,899 | from map_function import question_subword_matrix
from transformers import AutoTokenizer
import pickle
import argparse
def question_subword_matrix(processed_question_toks, relations, tokenizer):
def question_subword_dataset(dataset, tokenizer, output_path=None):
for i, data in enumerate(dataset):
processe... | null |
164,901 | import os, json, pickle, argparse, sys, time
import pdb
from supar import Parser
The provided code snippet includes necessary dependencies for implementing the `quote_normalization` function. Write a Python function `def quote_normalization(question)` to solve the following problem:
Normalize all usage of quotation ma... | Normalize all usage of quotation marks into a separate \" |
164,902 | import os, json, pickle, argparse, sys, time
import pdb
from supar import Parser
def inject_syntax_dataset(processor, dataset, output_path=None):
syntax_dataset = []
for idx, data in enumerate(dataset):
entry = processor.inject_syntax(data)
syntax_dataset.append(entry)
if idx % 100 == ... | null |
164,903 | import os, json, pickle, argparse, sys, time
import pdb
from supar import Parser
def inject_syntax_dataset_json(processor, dataset, mode='train', output_path=None):
syntax_dataset = []
for idx, data in enumerate(dataset):
entry = processor.inject_syntax(data)
if mode == 'dev':
# ple... | null |
164,904 | import os, json, pickle, argparse, sys, time
from preprocess.common_utils import Preprocessor
def process_tables(processor, tables_list, output_path=None, verbose=False):
tables = {}
for each in tables_list:
if verbose:
print('*************** Processing database %s **************' % (each['... | null |
164,905 | import os, json, pickle, argparse, sys, time
from preprocess.common_utils import Preprocessor
def process_example(processor, entry, db, trans, verbose=False):
# preprocess raw tokens
entry = processor.pipeline(entry, db, verbose=verbose)
return entry
def process_dataset(processor, dataset, tables, output_p... | null |
164,906 | import os, sqlite3
import numpy as np
import stanza, torch
from nltk.corpus import stopwords
from itertools import product, combinations
def is_number(s):
try:
float(s)
return True
except ValueError:
return False | null |
164,907 | import os, sqlite3
import numpy as np
import stanza, torch
from nltk.corpus import stopwords
from itertools import product, combinations
The provided code snippet includes necessary dependencies for implementing the `quote_normalization` function. Write a Python function `def quote_normalization(question)` to solve th... | Normalize all usage of quotation marks into a separate \" |
164,910 | import os, sqlite3
import numpy as np
import stanza, torch
from nltk.corpus import stopwords
from itertools import product, combinations
import torch.nn.functional as F
from transformers import AutoModel, AutoConfig, AutoTokenizer
import geoopt as gt
def is_number(s):
try:
float(s)
return True
... | null |
164,911 | import os, sqlite3
import numpy as np
import stanza, torch
from nltk.corpus import stopwords
from itertools import product, combinations
import torch.nn.functional as F
from transformers import AutoModel, AutoConfig, AutoTokenizer
import geoopt as gt
def agg(input):
# if input.size(0)==1:
# return input.sq... | null |
164,912 | import os, sqlite3
import numpy as np
import stanza, torch
from nltk.corpus import stopwords
from itertools import product, combinations
import torch.nn.functional as F
from transformers import AutoModel, AutoConfig, AutoTokenizer
import geoopt as gt
The provided code snippet includes necessary dependencies for implem... | Normalize all usage of quotation marks into a separate \" |
164,916 | import json
import pdb
from map_subword_serialize import question_subword_matrix
import argparse
from transformers import AutoTokenizer
import pickle
def question_subword_matrix(processed_question_toks, relations, tokenizer):
def question_subword_dataset(seq2seq_dataset, syntax_dataset, tokenizer, output_path = None)... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.