query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Helper method that returns the corresponding enum value for the training algorithm in the model_metadata json of the model selected. | def get_training_algorithm(model_metatdata_json):
try:
training_algorithm = None
err_msg = ""
if constants.ModelMetadataKeys.TRAINING_ALGORITHM in model_metatdata_json:
training_algorithm_value = model_metatdata_json[constants.ModelMetadataKeys.TRAINING_ALGORITHM]
if constants.TrainingAlgorithms.has_member(training_algorithm_value):
training_algorithm = constants.TrainingAlgorithms[training_algorithm_value]
else:
return 2, "The training algorithm value is incorrect", ""
else:
# To handle DeepRacer models with no training_algorithm key
print("No training algorithm key in model_metadata_file. Defaulting to clipped_ppo.")
training_algorithm = constants.TrainingAlgorithms.CLIPPED_PPO.value
return 0, err_msg, training_algorithm
except Exception as exc:
return 1, f"Error while getting training algorithm model_metadata.json: {exc}", "" | [
"def model_training_mode(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"model_training_mode\")",
"def AlgorithmEnum(self):\n\n return self._GetMessage('StudySpec').AlgorithmValueValuesEnum",
"def get_model_training_status(self, name):\n crds = kubernetes.client.CustomObjectsA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce the root of the tree in a "dict" state. hashname is one of the names in hashlib.algorithms. sequence_class is the type of PRNG to be returned by .sequence(). The default is treeprng.Hash_PRNG using hashname. | def __init__(self, hashname="sha1", sequence_class=None):
self.hashname = hashname
self.sequence_class = sequence_class
self.__hash = hashlib.new(hashname)
self.is_dict = True # The root is always a dict. | [
"def generate_tree(\n g: \"Generator\",\n assembly: str,\n class_name: str,\n namespace: str,\n unity_version=[2018, 4, 3, 1],\n) -> Dict[str, Dict]:\n # C# System\n from System import Array\n\n unity_version_cs = Array[int](unity_version)\n\n # fetch all type definitions\n def_iter = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
t.__getitem__(key) t[key] Given a TreePRNG t, t[key] Creates an uncommitted daughter TreePRNG object. This commits t to be a dict, but otherwise doesn't change t. key can be any picklable object, but if you want repeatability across runs of a program, see help(pickle_key). | def __getitem__(self, key):
assert self.__hash, \
"Tried to use as a dict after spent. See:\n" \
+ TREEPRNG_DOC_URL + "#the-treeprng-life-cycle"
self.is_dict = True
child = copy.copy(self)
child.__hash = self.__hash.copy()
child.is_dict = False
child.__hash.update("k" + pickle_key(key))
return child | [
"def __getitem__(self, key):\n if self.vec is None:\n return None\n\n if type(key) == int or type(key) == slice:\n return self.vec[key]\n return P4Node({'node_type': '<vec>'}, [node for node in self.vec if type(node) is P4Node if node.node_type == key])",
"def __getitem_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a PRNG seeded from this TreePRNG object. prng_class is an optional random.Random subclass; the default is self.sequence_class (see __init__()). self becomes spent. | def sequence(self, prng_class=None):
self.__check_state("sequence")
seed = long(self.__hash.hexdigest(), 16)
self.__hash = None # Spent.
prng_class = prng_class or self.sequence_class
if prng_class:
return prng_class(seed)
else:
return Hash_PRNG(seed, hashname=self.hashname) | [
"def get_prng(seed=None):\n if seed is not None and not (isinstance(seed, numbers.Integral) and seed >= 0):\n raise ValueError('Seed must be a non-negative integer or omitted, not {}'.format(seed))\n\n prng = np.random.RandomState()\n seed = create_seed(seed)\n seed = _int_list_from_bigint(hash_seed(seed))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hash() can be used on an uncommitted or dict TreePRNG. It commits self to be a dict. | def hash(self):
assert self.__hash, \
"Tried to use hash() after spent. See:\n" \
+ TREEPRNG_DOC_URL + "#the-treeprng-life-cycle"
hash = self.__hash.copy()
hash.update("h")
self.is_dict = True
return long(hash.hexdigest(), 16) | [
"def __hash__(self) -> hash:\n if self.empty:\n return hash(())\n else:\n return hash((self.data, self.left, self.right))",
"def __hash__(self):\n # see if there is an available hash value\n # if you are seeing cache bugs this is the thing\n # to try elimin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If hasattr(seed, "hexdigest"), assume seed is a hashlib object that no one will update(). else create a hashlib.new(self.hashname) object and update with the pickled seed. | def seed(self, seed):
if hasattr(seed, "hexdigest"):
self.base_hash = seed
else:
self.base_hash = hashlib.new(self.hashname)
self.base_hash.update("s" + pickle_key(seed))
# Note: this is the digest of the base_hash itself, while later
# chunks of bits (if any) are based on updated copies. That's okay,
# digest(base) doesn't let you predict digest(base + morebytes).
self.bits = long(self.base_hash.hexdigest(), 16)
self.nbits = self.base_hash.digest_size * 8
self.i = 1 | [
"def setseed(self, seed):\n self.hashseed = seed\n if not os.environ.get('PYTHONHASHSEED'):\n os.environ['PYTHONHASHSEED'] = str(seed)\n os.execv(sys.executable, ['python3'] + sys.argv)",
"def __hash__(self):\n # see if there is an available hash value\n # if you ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a shorted UUID or the original name. | def to_humanreadable_name(name: str) -> str:
return name[:8] if (is_valid_uuid(name) is True) else name | [
"def get_uuid(self): # real signature unknown; restored from __doc__\n return \"\"",
"def get_uuid():\n return str(UUID(int=random.randint(0, 2**128 - 1))) # nosec",
"def get_uuid(limit=10):\n uuid_sample = str(uuid.uuid4()).replace('-', '')\n if limit and limit <= len(uuid_sample):\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse user input. uses parse_bool() to partially return Boolean and None values All other types as returned asis >>> parse_user_input("YES") True >>> parse_user_input("false") False >>> parse_user_input("notfalse") 'notfalse' >>> parse_user_input(8.4) 8.4 >>> parse_user_input(dict(ioc=123)) | def parse_user_input(
data: typing.Optional[typing.Union[str, bool]]
) -> typing.Optional[typing.Union[str, bool]]:
try:
return parse_bool(data)
except TypeError:
pass
try:
parse_none(data)
return None
except TypeError:
pass
return data | [
"def userinput():\r\n var_dict = {}\r\n print('Input the variable names and their associated truth values \\n'\r\n ' Use the format: Letter:Truth Value \\n'\r\n ' Use T for True and F for False \\n'\r\n ' Example: P:F \\n'\r\n ' After each variable press return \\n'\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a JSON string from the input data. | def to_json(data: typing.Dict[str, typing.Any]) -> str:
output_data = _normalize_data(data)
return str(json.dumps(output_data, sort_keys=True, indent=4)) | [
"def encode_data(self, data):\r\n return json.dumps(data)",
"def write_json_string(data):\r\n raise NotImplementedError()",
"def _encode_data(self, data, **kwargs):\n return json.dumps(data, cls=JSONEncoder, **kwargs)",
"def format_json(data, dense):\n buf = io.StringIO()\n write_json(buf, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unmount a mountpoint using libc. | def umount(
mountpoint: typing.Optional[typing.Union[
libioc.Types.AbsolutePath,
typing.List[libioc.Types.AbsolutePath],
]]=None,
options: typing.Optional[typing.List[str]]=None,
force: bool=False,
ignore_error: bool=False,
logger: typing.Optional['libioc.Logger.Logger']=None
) -> None:
if isinstance(mountpoint, list) is True:
for entry in typing.cast(
typing.List[libioc.Types.AbsolutePath],
mountpoint
):
try:
umount(
mountpoint=entry,
options=options,
force=force,
ignore_error=ignore_error,
logger=logger
)
except (
libioc.errors.UnmountFailed,
libioc.errors.InvalidMountpoint
):
if force is False:
raise
return
mountpoint_path = libioc.Types.AbsolutePath(mountpoint)
if force is False:
umount_flags = ctypes.c_ulonglong(0)
else:
umount_flags = ctypes.c_ulonglong(0x80000)
if os.path.ismount(str(mountpoint_path)) is False:
raise libioc.errors.InvalidMountpoint(
mountpoint=mountpoint,
logger=logger
)
_mountpoint = str(mountpoint_path).encode("utf-8")
if libjail.dll.unmount(_mountpoint, umount_flags) == 0:
if logger is not None:
logger.debug(
f"Jail mountpoint {mountpoint} umounted"
)
else:
if logger is not None:
logger.spam(
f"Jail mountpoint {mountpoint} not unmounted"
)
if ignore_error is False:
raise libioc.errors.UnmountFailed(
mountpoint=mountpoint,
logger=logger
) | [
"def unmount(path='/sd'):\n import uos\n uos.unmount(path)",
"def unmount(mount_dir: str):\n logging.info(f\"{mount_dir}: unmounting\")\n\n try:\n subprocess.run([\"fusermount\", \"-u\", mount_dir], check=True)\n except Exception as e:\n logging.error(f\"{mount_dir}: {e}\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of basedirs according to the host distribution. | def get_basedir_list(distribution_name: str="FreeBSD") -> typing.List[str]:
basedirs = [
"bin",
"boot",
"lib",
"libexec",
"rescue",
"sbin",
"usr/bin",
"usr/include",
"usr/lib",
"usr/libexec",
"usr/sbin",
"usr/share",
"usr/libdata",
]
if distribution_name == "FreeBSD":
basedirs.append("usr/lib32")
return basedirs | [
"def _getdirs(self):\n dirs = [\"/\"] + self.dirs\n for name in self.zf.namelist():\n dirpath = os.path.dirname(name)\n if dirpath not in dirs:\n dirs.append(dirpath)\n return dirs",
"def auto_detect_base_directories():\n auto_rootdirs = None\n if PL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a generator for all cog files that aren't in do_not_use. | def extensions_generator():
cog_path = "./cogs"
do_not_use = ["__init__.py", "__pycache__", "xp.py"]
for cog in os.listdir(cog_path):
if cog not in do_not_use:
yield f"cogs.{cog[:-3]}" | [
"def extensions_generator():\n cog_path = \"./cogs\"\n do_not_use = ['errors', 'helper', 'managers', '__pycache__']\n for cog in os.listdir(cog_path):\n if cog not in do_not_use:\n yield f\"cogs.{cog[:-3]}\"",
"def iter_dists_excl(dists, exclude_fn):\n for dist in dists:\n fn ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a generator for all submodule addons. | def submodules_generator():
sub_path = "./subs"
do_not_use = ["solver"]
for item in os.listdir(sub_path):
path = os.path.join(sub_path, item)
if item not in do_not_use:
for sub in os.listdir(path):
if sub == f"{item}.py" and sub not in do_not_use:
yield f"subs.{item}.{sub[:-3]}" | [
"def extensions_generator():\n cog_path = \"./cogs\"\n do_not_use = ['errors', 'helper', 'managers', '__pycache__']\n for cog in os.listdir(cog_path):\n if cog not in do_not_use:\n yield f\"cogs.{cog[:-3]}\"",
"def submodules(self) -> Iterable[str]:\n exit_code, stdout, _ = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a specified extension into the bot. | async def load(self, ctx, extension):
try:
self.load_extension(extension)
await ctx.send(f"Successfully loaded extension {extension}.")
except Exception:
await ctx.send(f'Failed to load extension {extension}.')
logging.exception(f'Failed to load extension {extension}.') | [
"async def load(self, ctx, ext):\n ext_folder = \"extensions\"\n ext_dir = os.path.join(os.path.dirname(__file__), \"..\", ext_folder)\n ext_files = [name for _, name, _ in pkgutil.iter_modules([ext_dir])]\n if ext not in ext_files:\n await ctx.error(f\"{ext} extension not fou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the original dataset with bssoup xml extractor | def read_data(self):
with open(self.data_path, encoding="utf8",
errors="ignore") as fl:
fle = fl.read()
bs_data = BeautifulSoup(fle, "xml")
return bs_data | [
"def readXMLData(xmldoc: 'cc_xml_doc *') -> \"ScXMLDocument *\":\n return _coin.ScXMLDocument_readXMLData(xmldoc)",
"def ScXMLDocument_readXMLData(xmldoc: 'cc_xml_doc *') -> \"ScXMLDocument *\":\n return _coin.ScXMLDocument_readXMLData(xmldoc)",
"def get_description_data(xml_file):\n soup = bs4.Bea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter for the paperdefined time interval(19942010) Separate the title and the document description | def filter_data(self):
dataset = self.data_read.find_all(True)
filtered_docs = {}
for tag in dataset:
try:
# Filter the years
date = int(tag.find('year').text)
if 1994 < date < 2010:
doc_text = tag.find('docText').text
doc_splitted = doc_text.split('\n')
# Fitler if multiple linebreaks separate the title and the text
doc_splitted = [d for d in doc_splitted if len(d) > 0]
# Extract the title
title = doc_splitted[0]
# Assign the text to the title in the dictionary
filtered_docs[title] = doc_splitted[1]
except:
pass
return filtered_docs | [
"def is_time_sensitive(title):\n count = 0\n number = 0\n timestop = ['weekly digest', 'webinar', 'conference', 'summit', 'upcoming']\n years = ['2010', '2011', '2012', '2013']\n months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', \\\n 'september', 'october', 'novem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build the bag of words model from the cleaned data And the dictionary of the unique words | def build_bag_of_words_model(self):
lda_dictionary = Dictionary(self.cleaned_data.values())
lda_bag_of_words = [lda_dictionary.doc2bow(c, allow_update=True) for c in self.cleaned_data.values()]
return lda_dictionary, lda_bag_of_words | [
"def build_bag(data):\n\tbag = []\n\tfor sample in data:\n\n\t\tbag += [word.lower() for word in sample[0] if word not in bag and len(word) > 0]\n\n\t# Set the list to insure all dupes are removed\n\tbag = list(set(bag))\n\tbag.sort()\n\treturn bag",
"def bag_of_words(self):\t\n\t\tprint 'Building bag of words mo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extract all the word probabilities from the lda model for each cluster | def get_word_probabilities(self):
word_probs = {}
for i in range(self.num_of_clusters):
topic_id = i
word_probs[topic_id] = []
for l in self.lda_model.get_topic_terms(i, topn=len(self.lda_dict)):
word_probs[topic_id].append((self.lda_dict[l[0]], l[1]))
return word_probs | [
"def perplexity(ldamodel, testset, dictionary, size_dictionary, num_topics):\r\n # dictionary : {7822:'deferment', 1841:'circuitry',19202:'fabianism'...]\r\n # print ('the info of this ldamodel: \\n')\r\n # print ('num of testset: %s; size_dictionary: %s; num of topics: %s'%(len(testset), size_dictionary, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build pandas dataframe for the paralell coordinates view | def get_parall_coord_df(self):
parall_coords = {}
for i, b in zip(self.cleaned_data.keys(), self.lda_bag_of_words):
parall_coords[i] = self.lda_model[b]
parall_coord_df = pd.DataFrame.from_dict({k: dict(v) for k, v in parall_coords.items()})
parall_coord_df = parall_coord_df.replace(np.nan, 0)
parall_coord_df = parall_coord_df.transpose()
parall_coord_df = parall_coord_df.reindex(sorted(parall_coord_df.columns), axis=1)
parall_coord_df['Dominant_Topic'] = parall_coord_df.idxmax(axis="columns")
return parall_coord_df | [
"def create_dataframe(self):\n self.df = pd.DataFrame.from_records(self.all_residues)\n # add code to give meaningful columns names, including the one base on win_size, here\n # TODO\n window_size = self.half_window_size\n new_columns = [\"center\"]\n # For negative values\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assign color to topics with opacity | def color_assign_to_topic_with_opacity(self, x):
color_with_opacity = list(mcolors.to_rgba(self.colors[x]))
color_with_opacity[3] = 0.3
rgba = f'rgba({color_with_opacity[0] * 255}, {color_with_opacity[1] * 255}, {color_with_opacity[2] * 255}, {color_with_opacity[3]})'
return rgba | [
"def add_color(tweets):\n colors = list(Color(\"red\").range_to(Color(\"green\"), 100))\n for t in tweets:\n print t\n score = t['score']\n colorscore = (score + 1) / 2 * 100\n color = colors[int(colorscore)]\n t['color'] = color\n\n return tweets",
"def tubeColor(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build dictionary for the topics which will be input for the cytoscape node, generate a random position as well | def get_topic_nodes(self):
topic_dict = {}
for k, v in self.lda_most_rel_topics.items():
#random position
pos = np.random.randint(900, size=2)
topic_id = f'Cluster {k}'
# key: topic id, value: [top terms for the topic with linebreak, color assigned to topic, position of the
# topic node]
topic_dict[topic_id] = (' '.join(v).replace(' ', '\n'), self.colors[k], pos)
return topic_dict | [
"def get_network(cso, found_topics):\n\n if type(found_topics) is dict:\n list_of_topics = []\n for key, value in found_topics.items():\n list_of_topics += value\n\n list_of_topics = list(set(list_of_topics))\n elif type(found_topics) is list:\n list_of_topics = found_to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build dictionary for document nodes to the cytoscape network visualization | def get_document_nodes(self):
doc_nodes = {}
if self.filtered_topic_df is None:
iterable_df = self.topic_df.copy()
else:
iterable_df = self.filtered_topic_df.copy()
for idx, d in iterable_df.iterrows():
cluster_id = 'Cluster ' + str(d['Dominant_Topic'])
doc_nodes[str(d['Document_No'])] = (d['Title'], d['color'], cluster_id)
return doc_nodes | [
"def buildCoauthorNodesEdges(authorColabDict, majorKeywords = ['bioinformatics',\n 'network', 'cancer', 'aging', 'circadian', 'omics', 'neuro', 'computer',\n 'genetics', 'microbiome', 'computational', 'cardio', 'social', 'epidemic',\n 'sleep', 'pharamcology', 'mitochondria', 'metabolism', 'inflammation',\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate Cosine similarity between the documents with sklearn implementation Also removing the duplicities (taking only the upper trinagle elements from the result) In order to avoid duplicate edges on the graph | def calculate_cosine_similarity(self):
data = []
#prepare input for the sklearn cosine similarity function
for k in sorted(self.node_dict.keys()):
data.append(" ".join(self.cleaned_data[self.node_dict[k]]))
vec = TfidfVectorizer()
x = vec.fit_transform(
data)
# Calculate the pairwise cosine similarities (depending on the amount of data that you are going to have this
# could take a while)
matrix_similarity = cosine_similarity(x)
# Remove duplicates + diagonal: cosine similarity returns a symmetric matrix, where the diagonal and the
# lower or upper triangular is irrelevant
tril_ind = np.tril_indices(matrix_similarity.shape[0])
mat_sim_upper = matrix_similarity.copy()
mat_sim_upper[tril_ind] = -1
return mat_sim_upper | [
"def compute_similarity():\n movie_data = pd.read_csv(\"movie_recsys/datasets/movie_data.csv\")\n\n # Compute TF-IDF representation.\n tfidf = TfidfVectorizer(stop_words=\"english\")\n tfidf_matrix = tfidf.fit_transform(movie_data[\"story\"])\n\n # Compute Cosine Similarity.\n cosine_sim_scores = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the visible edges (edges between document nodes over the cosine sim threshold | def get_filtered_edges(self):
#filter edges based on the given threshold
filtered_edges = np.argwhere(self.cos_sim >= self.cosine_sim_threshold)
# get the document ids -> since document removal is also a function, simply returning the index at the matching
# points are not enough, since then the graph might attempt to create edge with a non-existing document,
# which throws an error
doc_ids = sorted(self.node_dict.keys())
cos_sim_edges = []
if self.filtered_topic_df is None:
available_docs = set(self.topic_df['Document_No'].tolist())
else:
available_docs = set(self.filtered_topic_df['Document_No'].tolist())
for f in filtered_edges:
idx_0 = doc_ids[f[0]]
idx_1 = doc_ids[f[1]]
if idx_0 in available_docs and idx_1 in available_docs:
cos_sim_edges.append((idx_0, idx_1, self.cos_sim[f[0], f[1]]))
return cos_sim_edges | [
"def determine_special_faces(graph, dist):\n return [node for node in graph.nodes() if graph.nodes[node]['distance'] >= dist]",
"def edges(gray):\n return cv2.Canny(gray, 50, 150)",
"def get_edge_nodes(self, graph):\n return eccentricity(graph)",
"def out_edge_count(self):",
"def edge_features(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the the view and the lda class itself with the original cluster number | def reset_settings(self):
self.__init__(self.orig_clust_num, self.data_path) | [
"def test_fully_reset_cluster(self):\n self.reset_cluster()",
"def reset(self):\n self.ensemble = []\n self.i = -1\n self.X_batch = None\n self.y_batch = None\n return self",
"def cluster_reinitialize (self, i_fold): \n if i_fold == self.cv_folds -1: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
filter paralell coordinates based on the input value (>value has to be kept) filtering also the documenttopic df to filter in cytoscape | def filter_parall_coords_topic_contribution(self, value):
self.filtered_paarcord_topics_df = self.get_topics_df().copy()
#get_indexed_topic_node_df
self.filtered_paarcord_topics_df = self.filtered_paarcord_topics_df[self.filtered_paarcord_topics_df['Topic_Perc_Contrib'] >= value]
remained_docs = self.filtered_paarcord_topics_df['Document_No'].tolist()
self.filtered_topic_df = self.topic_df[self.topic_df['Document_No'].isin(remained_docs)] | [
"def filter(self, df):\n pass",
"def filter_coords(df):\n lon_l, lon_r = -74.1, -73.7\n lat_l, lat_r = 40.65, 40.85\n\n for c in filter(lambda c: c.endswith('_Lon'), df.columns):\n df = df[(df[c] <= lon_r) & (df[c] >= lon_l)]\n\n for c in filter(lambda c: c.endswith('_Lat'), df.columns):\n df = d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the time tag's position in the given variable name. | def findTimeTagPos(self, varName):
for i in xrange(1, len(varName)):
if varName[-i] == "_":
return i | [
"def __locate_time_params(self):\n\n time_id, time_lsw, time_msw = 0, 0, 0\n long_names = self.__get_ch_attr('long')\n for name, long_name in zip(self.names, long_names):\n name_id = self.id_map.get(name)\n if long_name:\n keywords = (name.casefold(), long_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add time tag to the end of the variable name in the given tuple | def addTimeTag(self, tup, time):
return (tup[0] + "_T" + str(time), tup[1]) | [
"def add_timestamp(name):\n return '{0}_{1}'.format(name, time.strftime(\"%Y%m%d-%H%M%S\"))",
"def addAutoTimeMarker(time, name):",
"def _add_time_variable(root, time, **kwds):\n units = kwds.get(\"units\", \"days\")\n reference = kwds.get(\"reference\", \"00:00:00 UTC\")\n\n netcdf_vars = root.vari... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the action, PositionRow, and PositoinCol from a example | def getCoordAction(self, data):
row, col, action = None, None, None
for d in data[1:]:
if 'Row' in d[0]:
row = d
if 'Col' in d[0]:
col = d
if 'Action' in d[0]:
action = d
return row, col, action | [
"def get_position(event):\n\tline, column = text.index('insert').split('.')\n\ts = \"line=%s column=%s\" % (line, column)\n\tprint \"Karthik\",\n\tprint s",
"def where_is(piece, state):\n for row_index, row in enumerate(state):\n for col_index, current_piece in enumerate(row):\n if current_pi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert data to tuple, excluding the time tag e.g. 1 PositionRow_1=5 PositionCol_1=6 Action_1=MoveEast => (1, ("PositionRow, "5"), ("PositionCol", "6"), ("Action", "MoveEast")) | def convertExampleToTuple(self, ex):
splitEX = map(lambda e: e.split("="), ex)
output = [(e[0][:-self.findTimeTagPos(e[0])], e[1]) for e in splitEX[1:]]
output.insert(0, int(splitEX[0][0]))
return tuple(output) | [
"def str_to_tuple(tuple_str):\r\n return tuple(tuple_str.strip('() ').split(','))",
"def _key_to_tuple(cls, data, section):\n if section not in data:\n return\n temp = {}\n for key in data[section]:\n item_list = key.split(\"-\")\n if len(item_list) != 2:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Join API endpoints from two other modules These will be at ``/part1`` and ``/part2``, the paths being automatically generated from function names. | def with_other_apis():
return [part_1, part_2] | [
"def combine(self, part1, part2):\n part1 = part1.rstrip('/')\n part2 = part2.lstrip('/')\n return part1 + '/' + part2",
"def join_paths(*parts: str) -> str:\n return \".\".join(str(p).strip(\".\") for p in parts if p)",
"def join(base, *parts):\n path = base\n if not parts:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a target for a set of parameters. fp_mk file object of the Makefile. index numeric index of the simulation run. (Used to generate the output filename of the simulation run.) kv set of parameter values for this target conf_in_dir location of the conf.in directory to deduce configuration from. target_dir the target directory for all the simulation outputs. | def gen_mk_target_and_conf(fp_mk, index, kv, conf_in_dir, target_dir):
# We wrap the name with commas on both ends to make it easier to extract
# keys and values from the name with regular expressions. For
# example, the regular expression ,example_([^,]*), will then match
# the parameter/variable example, and the parenthesis subexpression
# its value.
outdir = "run%sparams_%05d" % (os.sep, index)
# Create the directories
os.makedirs(os.sep.join([target_dir, outdir, 'conf']), exist_ok=True)
conf_dir = os.sep.join([outdir, 'conf'])
# Create the configuration
genconf.apply_template(conf_in_dir,
os.sep.join([target_dir, conf_dir]),
kv)
# Create params file in outdir
fp = open(os.sep.join([target_dir, outdir, "params.txt"]), 'w')
for (k, v) in sorted(kv.items()):
fp.write("%-15s %s\n" % (k, v))
fp.close()
# Create makefile rules
fp_mk.write("%s/done_sim:\n" % (outdir,))
fp_mk.write(("\t/usr/bin/time -v ${MESH_SIM} `cat \"%s/cmdline_args.txt\"` "
+ "\"%s\" \"%s\" > \"%s/stdout.txt\" 2> \"%s/stderr.txt\"\n")
% (conf_dir, conf_dir, outdir, outdir, outdir))
fp_mk.write(("\tif find \"%s\"/*.pcap -maxdepth 0 >/dev/null 2>&1 ; then "
+ "gzip \"%s\"/*.pcap ; fi\n") % (outdir, outdir,))
fp_mk.write("\tdate > \"%s/done_sim\"\n" % (outdir,))
fp_mk.write("all: %s/done_sim\n" % (outdir,))
fp_mk.write(".PHONY: clean_%s\n" % (outdir,))
fp_mk.write("clean_%s:\n" % (outdir,))
fp_mk.write("\trm -f \"%s/done_sim\"\n" % (outdir,))
fp_mk.write("\trm -f \"%s\"/*.pcap.gz\n" % (outdir,))
fp_mk.write("clean: clean_%s\n" % (outdir,))
fp_mk.write("\n")
return True | [
"def generate(self, target_dir: Optional[str]):\n for config_file in self.config_files:\n config_file.write(target_dir)",
"def write_make_config(model_name, annotated_sequence, pairs_info, \n out_name='make_config.py'):\n data = make_config_template.format(model_name=mode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the reverse lookup fails on nonexistent energy group bounds. | def test_invalidGroupStructureType(self):
modifier = 1e-5
for groupStructureType in units.GROUP_STRUCTURE.keys():
energyBounds = units.getGroupStructure(groupStructureType)
energyBounds[0] = energyBounds[0] * modifier
with self.assertRaises(ValueError):
units.getGroupStructureType(energyBounds) | [
"def test_unused_locality_near_stops_has_nptg_entries():\n assert unused()",
"def test_get_fail_invalid_range(self):\n namespace = 'kytos.kronos.telemetry.switches.1.interfaces.232.bytes_in'\n start = None\n end = None\n\n influx.validate_timestamp.return_value = False\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the reverse lookup of the energy group structures work. Notes Several group structures point to the same energy group structure so the reverse lookup will fail to get the correct group structure type. | def test_consistenciesBetweenGroupStructureAndGroupStructureType(self):
for groupStructureType in units.GROUP_STRUCTURE.keys():
self.assertEqual(
groupStructureType,
units.getGroupStructureType(
units.getGroupStructure(groupStructureType)
),
) | [
"def test_invalidGroupStructureType(self):\n modifier = 1e-5\n for groupStructureType in units.GROUP_STRUCTURE.keys():\n energyBounds = units.getGroupStructure(groupStructureType)\n energyBounds[0] = energyBounds[0] * modifier\n with self.assertRaises(ValueError):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain filename of the composition based on known program number and slug | def get_comp_filename(program_no, slug, lang):
curr_path= os.path.dirname(os.path.realpath(__file__)) # Save current path
result= {'comp_'+lang: '', 'mix_'+lang: '', 'seq_'+lang: ''}
# Try to get program number.
try:
no= "%05d" % int(program_no)
except:
return result # If program number can't be obtained, the rest doesn't make sense
# Try to comp filename.
os.chdir(conf.COMP_OUT)
comp_lang_file= glob.glob("%s*%s*%s.nk" % (no, slug, lang))
if comp_lang_file:
result.update({'comp_'+lang: comp_lang_file[0]})
# Try to get file of sound mix.
mix_lang_file= None
try:
os.chdir("%s%s_%s/sound" % (conf.ROOT_OUT, no, lang))
mix_lang_file= glob.glob("%s*%s*%s_mix.wav" % (no, slug, lang))
except:
pass
if mix_lang_file:
result.update({'mix_'+lang: mix_lang_file[0]})
# Try to get number of files in seq folder.
seq_lang= None
try:
path, dirs, files= os.walk('%s%s_%s/seq/' % (
conf.ROOT_OUT, no, lang)).next()
seq_lang= len(files)
except Exception as e:
print e
if seq_lang:
result.update({'seq_'+lang: seq_lang})
os.chdir(curr_path) # Restore current path
return result | [
"def program_name():\n return os.path.basename(sys.argv[0])",
"def get_filename(self):\n\n return \"-\".join([\n str(self.paper.module.code),\n str(self.paper.year_start),\n str(self.paper.year_stop),\n str(self.paper.sitting),\n PaperPDF.period_map... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill language specific data for a Celebrity | def fill_lang_data(slug, lang):
celeb_lang_uri= '%s%s/%s/?all=1' % (conf.CELEBRITY_URI_TEMPL, slug, lang)
try:
celeb_lang_request= HttpObject().get_data_from_http_response('GET',
conf.HOST, celeb_lang_uri)
except Exception as e:
print "WARNING! Cannot get script data from http://%s%s\nThe error is: %s" % (
conf.HOST, celeb_lang_uri, e)
return None
celeb_lang_data= celeb_lang_request['celebrity'][lang]
script= celeb_lang_data.pop('script')
# Rename keys.
celeb_lang_data['name_'+lang]= celeb_lang_data.pop('name')
celeb_lang_data['duration_'+lang]= celeb_lang_data.pop('total_dur')
celeb_lang_data['scenes_'+lang]= celeb_lang_data.pop('total_scenes')
celeb_lang_data['user_'+lang]= celeb_lang_data.pop('user')
return celeb_lang_data | [
"def fill_language_data(lang, fields):\r\n lang.code_aliases = fields['code_aliases']\r\n lang.name = fields['name']\r\n lang.description = fields['description']\r\n lang.specialchars = fields['specialchars']\r\n lang.nplurals = fields['nplurals']\r\n lang.pluralequation = fields['pluralequation']... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill the list of Celebrities with language specific data | def fill_celebrity_list(celebrity_list):
for celebrity in celebrity_list:
print '...processing %s' % celebrity['slug']
celeb_langs_uri= '%s%s/?all=1' % (conf.CELEBRITY_URI_TEMPL, celebrity['slug'])
# Data obtained from the db
try:
celeb_langs_request= HttpObject().get_data_from_http_response('GET',
conf.HOST, celeb_langs_uri)
except Exception as e:
print "WARNING! Cannot get the list of languages from http://%s%s\nThe error is: %s" % (
conf.HOST, celeb_langs_uri, e)
return None
# Try to obtain data about program and number in it
prog_data= fill_prog_data(celebrity['slug'])
celebrity.update(prog_data)
if celeb_langs_request['status'] == 'OK':
langs= celeb_langs_request['celebrity']['language']
slug= celebrity['slug']
for lang in langs:
celebrity.update({'completed_'+lang['title']: lang['completed']})
celebrity_lang_details= fill_lang_data(slug, lang['title'])
if celebrity_lang_details:
celebrity.update(celebrity_lang_details)
# Data obtained from filesystem
celebrity_voice_data= fill_voice_data(slug, lang['title'])
if celebrity_voice_data:
celebrity.update(celebrity_voice_data)
# Try to get filename of the composition
comp_filename= get_comp_filename(
prog_data['program_no'], celebrity['slug'], lang['title'])
celebrity.update(comp_filename)
else:
print "ERROR! The response from http://%s%s is %s" % (
conf.HOST, celeb_lang_uri, celeb_request['celebrity'])
return None
return celebrity_list | [
"def allCountries():",
"def populate_languages(db: SQLAlchemy):\n resp = translator.get_languages()\n\n for short in resp:\n lang = Language()\n lang.microsoft_name = short\n try:\n lang.name = MICROSOFT_SHORT_TO_FULL_LANGUAGE_STRING[short]\n except KeyError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.SetPoint(float, float, float) > int | def SetPoint(self, p_float, p_float_1, p_float_2):
... | [
"def setPoint(self, *args) -> \"void\":\n return _coin.SoPrimitiveVertex_setPoint(self, *args)",
"def SetVectorVariableValue(self, string, p_float, p_float_1, p_float_2):\n ...",
"def SetPoint(self, *args):\n return _itkPointSetPython.itkPointSetD2S_SetPoint(self, *args)",
"def SetPoint(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if adding an argument that already exists to a parser raises an AlreadyAddedArgumentException | def test_add_argument_to_cli_parser_that_already_exist_raise_an_exception():
parser_manager = RootConfigParsingManager()
parser_manager.add_argument('a')
with pytest.raises(AlreadyAddedArgumentException):
parser_manager.add_argument('a')
with pytest.raises(AlreadyAddedArgumentException):
parser_manager.add_argument('help')
assert len(parser_manager.cli_parser.arguments) == 3 # help argument + a argument | [
"def is_argparse_add_argument(node):\n return (\n isinstance(node, Expr)\n and isinstance(node.value, Call)\n and isinstance(node.value.func, Attribute)\n and node.value.func.attr == \"add_argument\"\n and isinstance(node.value.func.value, Name)\n and node.value.func.val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that adding flag arguments with a short name to cli parser modified short_arg string | def test_add_flag_arguments_with_short_name_to_cli_parser():
parser_manager = RootConfigParsingManager()
assert parser_manager.cli_parser.short_arg == 'h'
parser_manager.add_argument('a', is_flag=True)
parser_manager.add_argument('x', is_flag=True)
assert parser_manager.cli_parser.short_arg == 'hax' | [
"def test_add_flag_arguments_and_no_flag_arguments_with_short_name_to_cli_parser():\n parser_manager = RootConfigParsingManager()\n assert parser_manager.cli_parser.short_arg == 'h'\n parser_manager.add_argument('a', is_flag=True)\n assert parser_manager.cli_parser.short_arg == 'ha'\n parser_manager.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if adding arguments (flag and no flag) to the parser modified short_arg string. long_arg list is not changed | def test_add_flag_arguments_and_no_flag_arguments_with_short_name_to_cli_parser():
parser_manager = RootConfigParsingManager()
assert parser_manager.cli_parser.short_arg == 'h'
parser_manager.add_argument('a', is_flag=True)
assert parser_manager.cli_parser.short_arg == 'ha'
parser_manager.add_argument('b')
assert parser_manager.cli_parser.short_arg == 'hab:'
parser_manager.add_argument('c', is_flag=True)
assert parser_manager.cli_parser.short_arg == 'hab:c'
assert len(parser_manager.cli_parser.long_arg) == 1 # Only help is arg argument
assert parser_manager.cli_parser.long_arg == ["help"] # Only help is arg argument | [
"def test_add_flag_arguments_with_long_name_to_cli_parser():\n parser_manager = RootConfigParsingManager()\n assert parser_manager.cli_parser.long_arg == ['help']\n parser_manager.add_argument('aaa', is_flag=True)\n assert parser_manager.cli_parser.long_arg == ['help', 'aaa']\n parser_manager.add_arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if adding arguments with long name to cli parser modifies long_arg list. short_arg string is not changed | def test_add_arguments_with_long_name_to_cli_parser():
parser_manager = RootConfigParsingManager()
assert parser_manager.cli_parser.long_arg == ['help']
parser_manager.add_argument('aaa')
assert parser_manager.cli_parser.long_arg == ['help', 'aaa=']
parser_manager.add_argument('xx')
assert parser_manager.cli_parser.long_arg == ['help', 'aaa=', 'xx=']
assert parser_manager.cli_parser.short_arg == 'h' | [
"def test_add_flag_arguments_with_long_name_to_cli_parser():\n parser_manager = RootConfigParsingManager()\n assert parser_manager.cli_parser.long_arg == ['help']\n parser_manager.add_argument('aaa', is_flag=True)\n assert parser_manager.cli_parser.long_arg == ['help', 'aaa']\n parser_manager.add_arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if adding a flag arguments with long to the parser modifies the long_arg list. short_arg string is not changed | def test_add_flag_arguments_with_long_name_to_cli_parser():
parser_manager = RootConfigParsingManager()
assert parser_manager.cli_parser.long_arg == ['help']
parser_manager.add_argument('aaa', is_flag=True)
assert parser_manager.cli_parser.long_arg == ['help', 'aaa']
parser_manager.add_argument('tttt', is_flag=True)
assert parser_manager.cli_parser.long_arg == ['help', 'aaa', 'tttt']
assert parser_manager.cli_parser.short_arg == 'h' | [
"def remove_long_internal():\n try:\n index = args.index(long_option_name)\n # Handle the exact match case.\n if takes_arg:\n removal_count = 2\n else:\n removal_count = 1\n del args[index:index+removal_count]\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to parse arguments with a parsing manager containing a subgroup parser. It must retrieve the following | def test_arguments_string_parsing_with_subgroup_parser_in_subgroup_parsing_manager(root_config_parsing_manager):
subparser = SubgroupConfigParsingManager('toto')
subparser.add_argument('b', is_flag=True, action=store_true)
subparser.add_argument('n', 'name')
root_config_parsing_manager.add_subgroup_parser('sub', subparser)
check_parse_cli_result(root_config_parsing_manager, "", {})
with pytest.raises(UnknownArgException):
check_parse_cli_result(root_config_parsing_manager, "-z", {})
check_parse_cli_result(root_config_parsing_manager, '-a', {'a': True})
with pytest.raises(NoNameSpecifiedForSubgroupException):
check_parse_cli_result(root_config_parsing_manager, '-a --sub toto -b', {})
check_parse_cli_result(root_config_parsing_manager, '-a --sub toto -b --name titi',
{'a': True, 'sub': {'titi': {'type': 'toto', 'b': True}}})
with pytest.raises(BadContextException):
check_parse_cli_result(root_config_parsing_manager, "-b", {}) | [
"def test_parsing_of_arguments_string_with_subgroup_parser_with_long_and_short_arguments_names_in_root_parsing_manager():\n parser_manager = RootConfigParsingManager()\n parser_manager.add_subgroup(name='sub')\n subparser = SubgroupConfigParsingManager('titi')\n subparser.add_argument('a', 'aaa', is_fla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to validate arguments with a parsing manager containing a subgroup parser. It must retrieve the following | def test_arguments_dict_validation_with_subgroup_parser_in_subgroup_parsing_manager(root_config_parsing_manager):
subparser = SubgroupConfigParsingManager('toto')
subparser.add_argument('b', is_flag=True, action=store_true)
subparser.add_argument('type', is_flag=True, action=store_true)
subparser.add_argument('n', 'name')
root_config_parsing_manager.add_subgroup_parser('sub', subparser)
dic_a = {'a': True}
dic_z = {
"z": True
}
dic_b = {
'b': "type"
}
dic_a_sub = {
'a': True,
'sub': {
'titi':
{
'type': 'toto',
'b': "type"
}
}
}
with pytest.raises(UnknownArgException):
root_config_parsing_manager.validate(dic_z)
with pytest.raises(UnknownArgException):
root_config_parsing_manager.validate(dic_b)
assert root_config_parsing_manager.validate(dic_a) == dic_a
assert root_config_parsing_manager.validate(dic_a_sub) == dic_a_sub
assert root_config_parsing_manager.validate({}) == {} | [
"def test_arguments_string_parsing_with_subgroup_parser_in_subgroup_parsing_manager(root_config_parsing_manager):\n\n subparser = SubgroupConfigParsingManager('toto')\n subparser.add_argument('b', is_flag=True, action=store_true)\n subparser.add_argument('n', 'name')\n root_config_parsing_manager.add_su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the type of argument is correctly checked by the parsing manager when a string is used as input | def test_arguments_string_parsing_type_checking_in_root_parsing_manager(root_config_parsing_manager):
root_config_parsing_manager.add_argument('c', argument_type=int)
with pytest.raises(BadTypeException):
check_parse_cli_result(root_config_parsing_manager, '-c string', {'c': 'string'})
check_parse_cli_result(root_config_parsing_manager, '-c 1', {'c': 1}) | [
"def input_type_check(data: object) -> None:\n if not isinstance(data, str):\n raise TypeError(\"Input data must be a 'str' object.\")",
"def __expectString(val):\n if type(val) != str:\n raise Exception('Expected string, received {}'.format(type(val)))",
"def test_parsing_of_arguments_strin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the argument type is correctly validated by the parser when a dict is used as input | def test_validation_of_arguments_dict_type_checking_in_root_parsing_manager(root_config_parsing_manager):
root_config_parsing_manager.add_argument('c', argument_type=int)
str_dic = {'c': 'string'}
int_dic = {'c': 42}
with pytest.raises(BadTypeException):
root_config_parsing_manager.validate(str_dic)
assert root_config_parsing_manager.validate(int_dic) == int_dic | [
"def test_valchk_dict_value_type():\n\n allowed = {\"test\": str, \"test2\": int, \"test3\": bool}\n passed = badparams(allowed)\n ep = Endpoint()\n\n assert ep.__valchk__(passed, allowed) is False",
"def test_transformer_input_dict_error():\n msg = \"`user_item_dict` must be a dict\"\n with pyt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that arguments parsing only relates parsing result to long name in arguments with long and short names | def test_arguments_string_parsing_with_long_and_short_names_in_root_parsing_manager(root_config_parsing_manager):
root_config_parsing_manager.add_argument('c', 'coco')
root_config_parsing_manager.add_argument('d', 'xx', argument_type=int)
check_parse_cli_result(root_config_parsing_manager, '-c 1', {'coco': '1'})
check_parse_cli_result(root_config_parsing_manager, '-d 555', {'xx': 555}) | [
"def test_add_arguments_with_long_name_to_cli_parser():\n parser_manager = RootConfigParsingManager()\n assert parser_manager.cli_parser.long_arg == ['help']\n parser_manager.add_argument('aaa')\n assert parser_manager.cli_parser.long_arg == ['help', 'aaa=']\n parser_manager.add_argument('xx')\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if adding arguments to a parser with two short names raise a SameLengthArgumentNamesException The arguments are not added | def test_add_arguments_with_two_short_names_raise_an_exception_in_root_parsing_manager(root_config_parsing_manager):
with pytest.raises(SameLengthArgumentNamesException):
root_config_parsing_manager.add_argument('c', 'd')
with pytest.raises(SameLengthArgumentNamesException):
root_config_parsing_manager.add_argument('t', 's')
assert len(root_config_parsing_manager.cli_parser.arguments) == 4 # --help, -h and sub
assert root_config_parsing_manager.cli_parser.long_arg == ['help', 'sub=']
assert root_config_parsing_manager.cli_parser.short_arg == 'ha' | [
"def test_add_arguments_with_two_long_names_raise_an_exception_in_root_parsing_manager(root_config_parsing_manager):\n with pytest.raises(SameLengthArgumentNamesException):\n root_config_parsing_manager.add_argument('coco', 'dodo')\n\n with pytest.raises(SameLengthArgumentNamesException):\n root... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if adding arguments to a parser with long names raise a SameLengthArgumentNamesException. The arguments are not added | def test_add_arguments_with_two_long_names_raise_an_exception_in_root_parsing_manager(root_config_parsing_manager):
with pytest.raises(SameLengthArgumentNamesException):
root_config_parsing_manager.add_argument('coco', 'dodo')
with pytest.raises(SameLengthArgumentNamesException):
root_config_parsing_manager.add_argument('ddddd', 'plplp')
assert len(root_config_parsing_manager.cli_parser.arguments) == 4 # -a, --help, -h and sub
assert root_config_parsing_manager.cli_parser.long_arg == ['help', 'sub=']
assert root_config_parsing_manager.cli_parser.short_arg == 'ha' | [
"def test_add_arguments_with_two_short_names_raise_an_exception_in_root_parsing_manager(root_config_parsing_manager):\n with pytest.raises(SameLengthArgumentNamesException):\n root_config_parsing_manager.add_argument('c', 'd')\n\n with pytest.raises(SameLengthArgumentNamesException):\n root_conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that parsing arguments with a wrong value type raises a BadTypeException | def test_parsing_of_arguments_string_with_wrong_type_raise_an_exception_in_root_parsing_manager():
parser_manager = RootConfigParsingManager()
parser_manager.add_argument('a', argument_type=int)
with pytest.raises(BadTypeException):
parser_manager._parse_cli('-a a'.split()) | [
"def test_arguments_string_parsing_type_checking_in_root_parsing_manager(root_config_parsing_manager):\n root_config_parsing_manager.add_argument('c', argument_type=int)\n\n with pytest.raises(BadTypeException):\n check_parse_cli_result(root_config_parsing_manager, '-c string', {'c': 'string'})\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that adding a subgroup parser that already exists raises an AlreadyAddedSubparserException | def test_add_subgroup_parser_that_already_exists_raises_an_exception_in_root_parsing_manager():
parser_manager = RootConfigParsingManager()
parser_manager.add_subgroup(name='toto')
subparser = SubgroupConfigParsingManager('titi')
subparser.add_argument('n', 'name')
parser_manager.add_subgroup_parser('toto', subparser)
repeated_subparser = SubgroupConfigParsingManager('titi')
repeated_subparser.add_argument('n', 'name')
with pytest.raises(AlreadyAddedSubparserException):
parser_manager.add_subgroup_parser('toto', repeated_subparser) | [
"def test_add_subgroup_parser_without_name_argument_raise_an_exception_in_root_parsing_manager():\n parser = RootConfigParsingManager()\n subparser = SubgroupConfigParsingManager('titi')\n\n with pytest.raises(SubgroupParserWithoutNameArgumentException):\n parser.add_subgroup_parser('toto', subparse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that parsing arguments of a subgroup parser with long and short names arguments only binds parser results to the long name | def test_parsing_of_arguments_string_with_subgroup_parser_with_long_and_short_arguments_names_in_root_parsing_manager():
parser_manager = RootConfigParsingManager()
parser_manager.add_subgroup(name='sub')
subparser = SubgroupConfigParsingManager('titi')
subparser.add_argument('a', 'aaa', is_flag=True, action=store_true, default_value=False)
subparser.add_argument('c', 'ttt', is_flag=False, action=store_val, argument_type=int)
subparser.add_argument('n', 'name')
parser_manager.add_subgroup_parser('sub', subparser)
check_parse_cli_result(parser_manager, '--sub titi -a --name tutu -c 15',
{'sub': {'tutu': {'aaa': True, 'type': 'titi', 'ttt': 15}}}) | [
"def test_arguments_string_parsing_with_subgroup_parser_in_subgroup_parsing_manager(root_config_parsing_manager):\n\n subparser = SubgroupConfigParsingManager('toto')\n subparser.add_argument('b', is_flag=True, action=store_true)\n subparser.add_argument('n', 'name')\n root_config_parsing_manager.add_su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that adding a subgroup parser with no argument 'name' raises a SubgroupParserWithoutNameArgumentException | def test_add_subgroup_parser_without_name_argument_raise_an_exception_in_root_parsing_manager():
parser = RootConfigParsingManager()
subparser = SubgroupConfigParsingManager('titi')
with pytest.raises(SubgroupParserWithoutNameArgumentException):
parser.add_subgroup_parser('toto', subparser) | [
"def test_add_subgroup_parser_that_already_exists_raises_an_exception_in_root_parsing_manager():\n parser_manager = RootConfigParsingManager()\n parser_manager.add_subgroup(name='toto')\n subparser = SubgroupConfigParsingManager('titi')\n subparser.add_argument('n', 'name')\n parser_manager.add_subgr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the result of parsing an empty dict is a dict of arguments with their default value | def test_validate_empty_dict_return_default_values_of_arguments_in_root_parsing_manager():
parser_manager = RootConfigParsingManager()
parser_manager.add_argument('c', argument_type=int, default_value=1)
parser_manager.add_argument('hello', argument_type=str, default_value="world")
default_dic = {}
expected_dic = {'c': 1, 'hello': 'world'}
assert parser_manager.validate(default_dic) == expected_dic | [
"def test_falsy_default_argument_values():\n arguments = [\n {\n \"name\": \"nonrequired\",\n \"type\": \"str\",\n \"default\": None\n },\n ]\n parser = reading.build_template_argparser(arguments)\n values = parser.parse_args([])\n assert values.nonrequi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a json file containing a configuration with long and short names for arguments is correctly parsed | def test_parsing_configuration_file_with_long_and_short_names_for_arguments_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):
config_file = 'root_manager_basic_configuration_with_long_and_short_names.json'
expected_dict = load_configuration_from_json_file(config_file)
expected_dict['argumento2'] = expected_dict.pop('2')
expected_dict['arg5'] = expected_dict.pop('5')
result = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse(args=('--config-file ' +
test_files_path +
'/' + config_file).split())
assert result == expected_dict | [
"def test_arguments_string_parsing_with_long_and_short_names_in_root_parsing_manager(root_config_parsing_manager):\n root_config_parsing_manager.add_argument('c', 'coco')\n root_config_parsing_manager.add_argument('d', 'xx', argument_type=int)\n\n check_parse_cli_result(root_config_parsing_manager, '-c 1',... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a json file containing a configuration with no values for arguments with default values is correctly parsed | def test_parsing_configuration_file_with_no_argument_with_default_value_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):
config_file = 'root_manager_basic_configuration_with_no_argument_with_default_value.json'
expected_dict = load_configuration_from_json_file(config_file)
expected_dict['arg5'] = 'default value'
result = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse(args=('--config-file ' +
test_files_path + '/' +
config_file).split())
assert result == expected_dict | [
"def test_falsy_default_argument_values():\n arguments = [\n {\n \"name\": \"nonrequired\",\n \"type\": \"str\",\n \"default\": None\n },\n ]\n parser = reading.build_template_argparser(arguments)\n values = parser.parse_args([])\n assert values.nonrequi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the parsing of a configuration defined via environment variables missing arguments with default values results in a dict with the default values for those arguments | def test_parsing_environment_variables_with_no_argument_with_default_value_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments):
config_file = 'root_manager_basic_configuration_with_no_argument_with_default_value.json'
created_environment_variables = define_environment_variables_configuration_from_json_file(
file_name=config_file,
simple_argument_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
arguments_prefix[0],
group_arguments_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
get_groups_prefixes())
expected_dict = load_configuration_from_json_file(config_file)
expected_dict['arg5'] = 'default value'
result = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse()
assert result == expected_dict
remove_environment_variables_configuration(variables_names=created_environment_variables) | [
"def test_validate_empty_dict_return_default_values_of_arguments_in_root_parsing_manager():\n parser_manager = RootConfigParsingManager()\n parser_manager.add_argument('c', argument_type=int, default_value=1)\n parser_manager.add_argument('hello', argument_type=str, default_value=\"world\")\n\n default_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a configuration defined via environment variables with subgroups is correctly parsed | def test_parsing_environment_variables_with_subgroups_and_long_and_short_names_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):
config_file = 'root_manager_configuration_with_subgroups_and_long_and_short_names.json'
created_environment_variables = define_environment_variables_configuration_from_json_file(
file_name=config_file,
simple_argument_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
arguments_prefix[0],
group_arguments_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
get_groups_prefixes())
expected_dict = load_configuration_from_json_file('root_manager_configuration_with_subgroups.json')
expected_dict['input']['in1']['name'] = 'i1_name'
expected_dict['output']['o1']['model'] = 'o1_model_x'
result = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse()
assert result == expected_dict
remove_environment_variables_configuration(variables_names=created_environment_variables) | [
"def test_nested(self):\n env = {\"APP_X\": \"nope\", \"XYZ_X\": \"foo\", \"XYZ_SUB_Y\": \"bar\"}\n cfg = environ.to_config(Nested, environ=env)\n\n assert Nested(x=\"foo\", sub=Nested.Sub(y=\"bar\")) == cfg",
"def test_config_priority_between_environ_variables_and_configuration_file_with_sub... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a configuration defined via environment variables with subgroups and unknown arguments terminates the execution | def test_parsing_environment_variables_with_subgroups_and_unknown_arguments_terminate_execution_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):
config_file = 'root_manager_configuration_with_subgroups_and_unknown_arguments.json'
created_environment_variables = define_environment_variables_configuration_from_json_file(
file_name=config_file,
simple_argument_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
arguments_prefix[0],
group_arguments_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
get_groups_prefixes())
result = None
with pytest.raises(SystemExit) as result:
_ = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse()
assert result.type == SystemExit
assert result.value.code == -1
remove_environment_variables_configuration(variables_names=created_environment_variables) | [
"def test_parsing_environment_variables_with_subgroups_and_wrong_type_terminate_execution_in_root_parsing_manager(\n root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):\n config_file = 'root_manager_configuration_with_subgroups_and_wrong_argument_type_value.json'\n crea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a configuration defined via environment variables with subgroups without variables with default values is correctly parsed | def test_parsing_environment_variables_with_subgroups_and_no_arguments_with_default_value_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):
config_file = 'root_manager_configuration_with_subgroups_and_no_argument_default_value.json'
created_environment_variables = define_environment_variables_configuration_from_json_file(
file_name=config_file,
simple_argument_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
arguments_prefix[0],
group_arguments_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
get_groups_prefixes())
expected_dict = load_configuration_from_json_file(config_file)
expected_dict['input']['in1']['name'] = 'my_i1_instance'
expected_dict['output']['o1']['name'] = 'my_o1_instance'
expected_dict['output']['o2']['name'] = 'my_o2_instance'
result = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse()
assert result == expected_dict
remove_environment_variables_configuration(variables_names=created_environment_variables) | [
"def test_parsing_environment_variables_with_no_argument_with_default_value_in_root_parsing_manager(\n root_config_parsing_manager_with_mandatory_and_optional_arguments):\n config_file = 'root_manager_basic_configuration_with_no_argument_with_default_value.json'\n created_environment_variables = define... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a configuration defined via environment variables with subgroups and wrong argument type terminates the execution | def test_parsing_environment_variables_with_subgroups_and_wrong_type_terminate_execution_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):
config_file = 'root_manager_configuration_with_subgroups_and_wrong_argument_type_value.json'
created_environment_variables = define_environment_variables_configuration_from_json_file(
file_name=config_file,
simple_argument_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
arguments_prefix[0],
group_arguments_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
get_groups_prefixes())
result = None
with pytest.raises(SystemExit) as result:
_ = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse()
assert result.type == SystemExit
assert result.value.code == -1
remove_environment_variables_configuration(variables_names=created_environment_variables) | [
"def test_arguments_dict_validation_with_subgroup_parser_in_subgroup_parsing_manager(root_config_parsing_manager):\n subparser = SubgroupConfigParsingManager('toto')\n subparser.add_argument('b', is_flag=True, action=store_true)\n subparser.add_argument('type', is_flag=True, action=store_true)\n subpars... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that arguments values defined via the environment variables are preserved regarding values defined via a config file with subgroups in configuration | def test_config_priority_between_environ_variables_and_configuration_file_with_subgroups_in_root_parsing_manager(
root_config_parsing_manager_with_mandatory_and_optional_arguments,
test_files_path):
config_file_environment_variables = 'root_manager_configuration_with_subgroups_and_no_argument_default_value.json'
created_environment_variables = define_environment_variables_configuration_from_json_file(
file_name=config_file_environment_variables,
simple_argument_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
arguments_prefix[0],
group_arguments_prefix=root_config_parsing_manager_with_mandatory_and_optional_arguments.cli_parser.
get_groups_prefixes())
sys.argv.append('--config-file')
sys.argv.append(test_files_path + '/root_manager_configuration_with_subgroups_and_long_and_short_names.json')
expected_dict = load_configuration_from_json_file(config_file_environment_variables)
expected_dict['input']['in1']['name'] = 'i1_name'
expected_dict['output']['o1']['name'] = 'o1_name'
expected_dict['output']['o2']['name'] = 'o2_name'
result = root_config_parsing_manager_with_mandatory_and_optional_arguments.parse()
assert result == expected_dict
sys.argv = []
remove_environment_variables_configuration(variables_names=created_environment_variables) | [
"def test_parsing_environment_variables_with_subgroups_and_no_arguments_with_default_value_in_root_parsing_manager(\n root_config_parsing_manager_with_mandatory_and_optional_arguments, test_files_path):\n config_file = 'root_manager_configuration_with_subgroups_and_no_argument_default_value.json'\n cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a subgroup is correctly added to a parsing manager | def test_add_subgroup_in_root_parsing_manager():
parser_manager = RootConfigParsingManager()
assert len(parser_manager.cli_parser.subgroup_parsers) == 0
parser_manager.add_subgroup(name='sub')
assert len(parser_manager.cli_parser.subgroup_parsers) == 1
parser_manager.add_subgroup(name='sub1')
assert len(parser_manager.cli_parser.subgroup_parsers) == 2
parser_manager.add_subgroup(name='sub3')
assert len(parser_manager.cli_parser.subgroup_parsers) == 3 | [
"def test_add_subgroup_parser_that_already_exists_raises_an_exception_in_root_parsing_manager():\n parser_manager = RootConfigParsingManager()\n parser_manager.add_subgroup(name='toto')\n subparser = SubgroupConfigParsingManager('titi')\n subparser.add_argument('n', 'name')\n parser_manager.add_subgr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrapper around getIbvCounters() to expand arguments so that we can use it with multiprocessing.map() | def getIbvCountersWrapper(args):
return getIbvCounters(*args) | [
"def _cx_counters_psutil(self):\n for iface, counters in psutil.net_io_counters(pernic=True).iteritems():\n metrics = {\n 'bytes_rcvd': counters.bytes_recv,\n 'bytes_sent': counters.bytes_sent,\n 'packets_in.count': counters.packets_recv,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the progress bar character | def set_bar_character(self, char):
self.bar_char = char | [
"def set_bar_char(self, char):\n \n self._bar_char = char",
"def set_empty_bar_character(self, char):\n self.empty_bar_char = char",
"def bar_done(self):\n\t\tself.cursor += self.width",
"def set_char(self, coord, char):\n\t\tassert coord.x >= 0 and coord.x < self.width, \"X Coordinate ou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the empty bar character | def set_empty_bar_character(self, char):
self.empty_bar_char = char | [
"def set_bar_character(self, char):\n self.bar_char = char",
"def set_bar_char(self, char):\n \n self._bar_char = char",
"def clear(self):\n return \"\\x1b[0m\"",
"def render_blank_note_in_ascii(self):\n return \" \" * 4",
"def blank(self):\n self.lines.append('')",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the progress character | def set_progress_character(self, char):
self.progress_char = char | [
"def set_bar_character(self, char):\n self.bar_char = char",
"def set_bar_char(self, char):\n \n self._bar_char = char",
"def setChar(*args, **kwargs):\n \n pass",
"def set_empty_bar_character(self, char):\n self.empty_bar_char = char",
"def SetSpecialChar ( self, num, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the redraw frequency | def set_redraw_frequency(self, freq):
self.bar_char = freq | [
"def set_speed(self):\n\n sender = self.sender()\n speed = 1\n if sender is self.speed_x05:\n speed = 0.5\n if sender is self.speed_x025:\n speed = 0.25\n if sender is self.speed_x0125:\n speed = 0.125\n self.highlight_selected_speed(sender)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrites a previous message to the output. | def overwrite(self, output_, messages):
# carriage return
output_.write('\x0D')
if self.last_messages_length is not None:
# clear the line with the text of the last message
output_.write('\x20' * self.last_messages_length)
# carriage return
output_.write('\x0D')
output_.write(messages)
self.last_messages_length = len(messages) | [
"def _overwrite(self, message):\n if self._output.is_decorated():\n self._output.write('\\x0D\\x1B[2K')\n self._output.write(message)\n else:\n self._output.writeln(message)",
"def message_reset(self):\n self.message = \"\"",
"def finalizeMessage(self, same,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Crea una revolucion de un croquis con respecto a un eje (Primer linea del croquis) para crear una operacion solida | def revolucionAditiva(self, doc, croquis = None, nombreExtrusion = "Revolucion", angulo = 360, invertido = 0, planoMedio = 0 ):
self.nombre = nombreExtrusion
self.doc = doc
self.tipo = "revolucionAditiva"
#Se extrae el string de la base y de su padre mediante metodos que aceptan varios tipos de clases
stringCroquis = extraerString(croquis)
if type(croquis) is str:
croquis = self.doc.seleccionarObjeto(croquis)
stringPadreCroquis = extraerStringPadre(croquis)
self.doc.contLineasReferencia += 1
stringEjeRevolucion = f"EjeRevolucion{str(self.doc.contLineasReferencia).zfill(2)}"
#EJE DE REVOLUCION
self.doc.base.getObject(stringPadreCroquis).newObject('PartDesign::Line',stringEjeRevolucion)
self.doc.base.getObject(stringEjeRevolucion).AttachmentOffset = FreeCAD.Placement(
FreeCAD.Vector(0.0000000000, 0.0000000000, 0.0000000000),
FreeCAD.Rotation(0.0000000000, 0.0000000000, 0.0000000000)
)
self.doc.base.getObject(stringEjeRevolucion).MapReversed = False
self.doc.base.getObject(stringEjeRevolucion).Support = [(self.doc.base.getObject(stringCroquis),'Edge1')]
self.doc.base.getObject(stringEjeRevolucion).MapPathParameter = 0.000000
self.doc.base.getObject(stringEjeRevolucion).MapMode = 'TwoPointLine'
#REVOLUCION
self.doc.base.getObject(stringPadreCroquis).newObject('PartDesign::Revolution',nombreExtrusion)
self.base = self.doc.base.getObject(nombreExtrusion)
self.base.Profile = self.doc.base.getObject(stringCroquis)
self.base.ReferenceAxis = (self.doc.base.getObject(stringEjeRevolucion), [''])
self.base.Angle = angulo
self.base.Reversed = invertido
self.base.Midplane = planoMedio
self.doc.extrusiones[nombreExtrusion] = self
self.doc.addExtern("Extrusion", nombreExtrusion)
return self | [
"def revolucionDeVaciado(self, doc, croquis = None, nombreExtrusion = \"RevolucionDeVaciado\", angulo = 360, invertido = 0, planoMedio = 0 ):\n \n self.nombre = nombreExtrusion\n self.doc = doc\n self.tipo = \"revolucionDeVaciado\"\n\n #Se extrae el string de la base y de su padre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Corta un solido a traves de la revolucion de un croquis con respecto a un eje (Primer linea del croquis) | def revolucionDeVaciado(self, doc, croquis = None, nombreExtrusion = "RevolucionDeVaciado", angulo = 360, invertido = 0, planoMedio = 0 ):
self.nombre = nombreExtrusion
self.doc = doc
self.tipo = "revolucionDeVaciado"
#Se extrae el string de la base y de su padre mediante metodos que aceptan varios tipos de clases
stringCroquis = extraerString(croquis)
if type(croquis) is str:
croquis = self.doc.seleccionarObjeto(croquis)
stringPadreCroquis = extraerStringPadre(croquis)
self.doc.contLineasReferencia += 1
stringEjeRevolucion = f"EjeRevolucion{str(self.doc.contLineasReferencia).zfill(2)}"
#EJE DE REVOLUCION
self.doc.base.getObject(stringPadreCroquis).newObject('PartDesign::Line',stringEjeRevolucion)
self.doc.base.getObject(stringEjeRevolucion).AttachmentOffset = FreeCAD.Placement(
FreeCAD.Vector(0.0000000000, 0.0000000000, 0.0000000000),
FreeCAD.Rotation(0.0000000000, 0.0000000000, 0.0000000000)
)
self.doc.base.getObject(stringEjeRevolucion).MapReversed = False
self.doc.base.getObject(stringEjeRevolucion).Support = [(self.doc.base.getObject(stringCroquis),'Edge1')]
self.doc.base.getObject(stringEjeRevolucion).MapPathParameter = 0.000000
self.doc.base.getObject(stringEjeRevolucion).MapMode = 'TwoPointLine'
#REVOLUCION
self.doc.base.getObject(stringPadreCroquis).newObject('PartDesign::Groove',nombreExtrusion)
self.base = self.doc.base.getObject(nombreExtrusion)
self.base.Profile = self.doc.base.getObject(stringCroquis)
self.base.ReferenceAxis = (self.doc.base.getObject(stringEjeRevolucion), [''])
self.base.Angle = angulo
self.base.Reversed = invertido
self.base.Midplane = planoMedio
self.doc.extrusiones[nombreExtrusion] = self
self.doc.addExtern("Extrusion", nombreExtrusion)
return self | [
"def revolucionAditiva(self, doc, croquis = None, nombreExtrusion = \"Revolucion\", angulo = 360, invertido = 0, planoMedio = 0 ):\n \n self.nombre = nombreExtrusion\n self.doc = doc\n self.tipo = \"revolucionAditiva\"\n\n #Se extrae el string de la base y de su padre mediante met... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a Cache Item representing the specified key. | def get_item(self, key):
cPickle_key = self.normalize_key(key)
md5_key = hashlib.md5(cPickle_key).hexdigest()
document = self.collection.find_one({"md5":md5_key, "key": cPickle_key})
if document != None:
item = cPickle.loads(str(document['item']))
item.isHit = True
return item
else:
item = CacheItem()
item.key = key
return item | [
"def get(self, key):\n #return none if the item isn't in the cache\n if key not in self.items:\n return None\n\n #retrieve the item from the dictionary\n item = self.items[key]\n\n #move it to the front of the list since it is the\n #most recently accessed item\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add Builders and construction variables for protoc to an Environment. | def generate(env):
try:
bld = env['BUILDERS']['Protoc']
except KeyError:
bld = ProtocBuilder
env['BUILDERS']['Protoc'] = bld
env['PROTOC'] = env.Detect(protocs) or 'protoc'
env['PROTOCFLAGS'] = SCons.Util.CLVar('')
env['PROTOCPROTOPATH'] = SCons.Util.CLVar('')
env['PROTOCCOM'] = '$PROTOC $PROTOCFLAGS ${PROTOCPYTHONOUTDIR and ("--python_out="+PROTOCPYTHONOUTDIR) or ""} ${PROTOCFDSOUT and ("-o"+PROTOCFDSOUT) or ""} ${SOURCES}'
env['PROTOCSRCSUFFIX'] = '.proto'
env['PROTOCPYTHONOUTDIR'] = '.' | [
"def setup_environment():",
"def base_setup(env, prereqs=None):\n\n if GetOption('help') or GetOption('clean'):\n return\n\n compiler = env['CC']\n\n build_type = env['BUILD_TYPE']\n print('Setting up compile environment for {}'.format(compiler))\n print(\"Build type is '{}'\".format(build_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the inode of parent directory. Raises error if on root. | def __get_parent_inode(self, path):
if path == "/":
raise FileSystemError("No parent directory.")
parent_dir = Inode.selectBy(inode_num=0).orderBy("-rev_id")[0]
for fn in split_path(path)[:-1]:
tmp = Dentry.selectBy(parent=parent_dir, filename=fn)
if tmp.count() == 0:
raise FileSystemError("file not found.")
parent_dir = Inode.selectBy(inode_num=tmp[0].inode_num).\
orderBy("-rev_id")[0]
return parent_dir.inode_num | [
"def get_parent_dir(path):\n\treturn os.path.dirname(os.path.abspath(path))",
"def inode(self):\n return self._dir_info[\"file_id\"].get_value()",
"def __get_inode(self, path):\n if path == \"/\":\n return 0\n parent_dir = Inode.selectBy(inode_num=self.__get_parent_inode(path)).\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the inode of the object (file/directory). Raises an error if the object doesn't exist. | def __get_inode(self, path):
if path == "/":
return 0
parent_dir = Inode.selectBy(inode_num=self.__get_parent_inode(path)).\
orderBy("-rev_id")[0]
tmp = Dentry.selectBy(parent=parent_dir,
filename=split_path(path)[-1])
if tmp.count() == 0:
raise FileSystemError("file not found.:",path)
ret = Inode.selectBy(inode_num=tmp[0].inode_num).orderBy("-rev_id")[0]
return ret.inode_num | [
"def inode(self):\n return self._dir_info[\"file_id\"].get_value()",
"def inode(filesystem, mode=\"total\", host_os=detect_host_os()):\n validate_mode(mode, SIZE_CONVERSION_MODES)\n\n free, total = host_os.fs_inodes(filesystem)\n\n return convert_size(free, total, mode)",
"def find_by_inode(root... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the selected file. If the file is from the server it is downloaded and read without being saved locally. If it is a local file, it is read locally. | def read(self, path, length, offset):
#Create a list of available files
T = atpy.Table(SERVER_LOCATION + 'QUERY?query=files_list&format=list',type='ascii')
#Check is file is local
if not (path[1:] in T['col3']):
if not path in self.__openfiles:
self.open(path, 0)
return self.__openfiles[path].read(length, offset)
#File is not local so open and read from server
else:
urlString = SERVER_LOCATION + 'RETRIEVE?file_id=' + path[1:]
ht = None
ht = urllib2.urlopen(urlString)
return ht.read(length) | [
"def _read_file(self):\n with open(self.file, 'r') as the_file:\n content = the_file.read()\n return content",
"def read_file( self, url ):\n return urlopen( url ).read()",
"def _read(url):\n if os.path.exists(url): \n file_obj = open(url, 'r') \n file_body = fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes an object from oldPath and places it on newPath | def rename(self, oldPath, newPath):
conn = sqlhub.getConnection()
trans = conn.transaction()
now = time.time()
i_num = self.__get_inode(oldPath)
parent_i_num = self.__get_parent_inode(oldPath)
parent_i = Inode.selectBy(inode_num=parent_i_num).orderBy("-rev_id")[0]
dl = Dentry.selectBy(parent=parent_i)
new_i = Inode(inode_num=parent_i.inode_num,
rev_id=parent_i.rev_id+1,
uid=parent_i.uid, gid=parent_i.gid,
atime=now, mtime=parent_i.mtime,
ctime=parent_i.ctime, size=parent_i.size,
mode=parent_i.mode, connection=trans)
for de in dl:
if de.inode_num != i_num:
Dentry(parent=new_i, filename=de.filename,
inode_num=de.inode_num, connection=trans)
parent_i_num = self.__get_parent_inode(newPath)
parent_i = Inode.selectBy(inode_num=parent_i_num).orderBy("-rev_id")[0]
Dentry(parent=new_i, filename=split_path(newPath)[-1],
inode_num=i_num, connection=trans)
old_i = Inode.selectBy(inode_num=i_num).orderBy("-rev_id")[0]
Inode(inode_num=old_i.inode_num,
rev_id=old_i.rev_id+1,
uid=old_i.uid, gid=old_i.gid,
atime=now, mtime=old_i.mtime,
ctime=old_i.ctime, size=old_i.size,
mode=old_i.mode, connection=trans)
trans.commit()
if oldPath in self.__openfiles:
while not self.__openfiles[oldPath].is_close():
self.__openfiles[oldPath].close()
del self.__openfiles[oldPath] | [
"def removed(object, oldParent=None, oldName=None):",
"def update_path(self, new_path):\n self.ui.systemTreeWidget.clear()\n self.ui.selectedTreeWidget.clear()\n clear_list(self.widgets)\n self.ui.pathLineEdit.setText(new_path)\n self.fb.set_current_path(new_path)\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a link from the object at oldPath to an object at newPath. | def link(self, oldPath, newPath):
conn = sqlhub.getConnection()
trans = conn.transaction()
now = time.time()
i_num = self.__get_inode(oldPath)
parent_i_num = self.__get_parent_inode(newPath)
parent_i = Inode.selectBy(inode_num=parent_i_num).orderBy("-rev_id")[0]
dl = Dentry.selectBy(parent=parent_i)
new_i = Inode(inode_num=parent_i.inode_num,
rev_id=parent_i.rev_id+1,
uid=parent_i.uid, gid=parent_i.gid,
atime=now, mtime=parent_i.mtime,
ctime=parent_i.ctime, size=parent_i.size,
mode=parent_i.mode, connection=trans)
for de in dl:
Dentry(parent=new_i, filename=de.filename,
inode_num=de.inode_num, connection=trans)
Dentry(parent=new_i, filename=split_path(newPath)[-1],
inode_num=i_num, connection=trans)
trans.commit() | [
"def symlink(self, oldPath, newPath):\n mode = 0o644|stat.S_IFLNK\n i_num = self.mknod(newPath, mode, 0)\n self.write(newPath, oldPath, 0)",
"def rename(self, oldPath, newPath):\n \n conn = sqlhub.getConnection()\n trans = conn.transaction()\n now = time.time()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a symbolic link from oldPath to newPath. | def symlink(self, oldPath, newPath):
mode = 0o644|stat.S_IFLNK
i_num = self.mknod(newPath, mode, 0)
self.write(newPath, oldPath, 0) | [
"def create_symlink(from_path='', to_path=''):\n\n try:\n os.symlink(from_path, to_path)\n except Exception as exc:\n logger.warning('failed to create symlink from %s to %s: %s', from_path, to_path, exc)\n else:\n logger.debug('created symlink from %s to %s', from_path, to_path)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses FUSE to mount the sqliteFS to the mount point. | def main():
usage = Fuse.fusage
sdfs = SqliteDumpFS(version="%prog"+fuse.__version__,
usage=usage,
dash_s_do='setsingle')
sdfs.parser.add_option(mountopt="db_path", metavar="PATH",default="")
sdfs.parse(values=sdfs, errex=1)
sdfs.main() | [
"def mount_ss(self):\n if match_fs(self.mp, ['nilfs', 'nilfs2']):\n self.mount_tmpfs()\n if not self.passive:\n self.thin_out_snapshots()\n self.do_mount_ss(False)",
"def __init__(self, *args, **kwargs):\n q.logger.log(\"Mounting file system\")\n super(MemF... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The plotly figure use to render the scene. Returns ~plotly.graph_objects.Figure The plotly ``Figure`` representing the scene. | def figure(self):
return self.scene | [
"def figure(self) -> Figure:\r\n assert len(self._visualizations) == 1\r\n motor_dashboard = self._visualizations[0]\r\n assert len(motor_dashboard._figures) == 1\r\n return motor_dashboard._figures[0]",
"def get_plotly_object(self):\n pass",
"def create_fig(self):\n fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The plotly layout of the figure. Returns ~plotly.graph_objects.Layout The plotly ``Layout`` object linked to the figure. | def layout(self):
return self._layout | [
"def create_layout(self):\n graph = Gui.Graph(canvas_size=(500, 500), graph_bottom_left=(0, 0), graph_top_right=(500, 500),\n background_color=None, pad=None, change_submits=False, drag_submits=False,\n enable_events=False,\n key=\"Gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the layout of the figure scene. | def update_layout(self, layout):
self.figure.update_layout(layout) | [
"def refresh_layout(self):\n if self.__container:\n self.__container._needs_layout(self)",
"def update(self, system):\n update_cellview(self.ax[0, 0], system)\n update_rdfview(self.ax[1, 1], system, self.average_rdf, self.r)\n update_energyview(self.ax[0, 1], system)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the required list of colors if orbit trail is desired. | def _get_colors(self, color, trail):
color = color or next(self._color_cycle)
return [color] | [
"def _get_colors(self, color, trail):\n if color is None:\n # HACK: https://stackoverflow.com/a/13831816/554319\n color = next(self.ax._get_lines.prop_cycler)[\"color\"]\n\n colors = [color, to_rgba(color, 0)] if trail else [color]\n return colors",
"def colors(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the attractor from the scene. | def undraw_attractor(self):
pass | [
"def undraw_attractor(self):\n for attractor in self.ax.findobj(match=mpl_patches.Circle):\n attractor.remove()",
"def remove(self):\n self.layers.pop()",
"def remove_highlight_actor(self):\n gui = self.win_parent\n remove_actors_from_gui(gui, self.actors, render=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw an impulse into the scene. | def draw_impulse(self, position, *, color, label, size):
return self.draw_marker(
position, color=color, label=label, marker_symbol="x", size=size
) | [
"def apply_impulse(self, p):\n\t\tself.force=p",
"def impulse(t: float) -> float:\n return 1. if t >= 1. and t < 2. else 0.",
"def draw_velocity(self):\n vect = vector.scalar_multiply(self.velocity, 10)\n endpos = vector.add(self.rect.center, vect)\n return pygame.draw.line(self.level.sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the legend of the scene. | def update_legend(self):
pass | [
"def update_legend(self, *args):\n legend = self.axes.get_legend()\n if legend is not None:\n self._update_legend_visual(legend)\n self.redraw()",
"def legend(self, **kwargs):\n raise NotImplementedError",
"def __onpick(self, event):\n self.logger.debug(\"running\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the labels for coordinates and position. | def generate_labels(self, label, has_coordinates, has_position):
return (label, None) | [
"def generate_labels(self, label, has_coordinates, has_position):\n return (None, label) if has_position else (label, None)",
"def labels(self):\n xlabel=''\n ylabel=''\n if 'calculation' in self.variables[self.xy[0]]:\n xlabel+=self.variables[self.xy[0]]['calculation']+' '\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a marker into the scene. | def draw_marker(self, position, *, color, marker_symbol, label, size):
marker_style = dict(size=size, color=color, symbol=marker_symbol)
marker_trace = go.Scatter3d(
x=position[0],
y=position[1],
z=position[2],
marker=marker_style,
name=label,
showlegend=False if label is None else True,
)
self.figure.add_trace(marker_trace)
return marker_trace | [
"def drawMarker(self, id, sidePixels, _img=..., borderBits=...) -> _img:\n ...",
"def mark(self, x,y,z):\n sphere = vtk.vtkSphereSource()\n sphere.SetRadius(3)\n res = 20\n sphere.SetThetaResolution(res)\n sphere.SetPhiResolution(res)\n sphere.SetCenter(x,y,z)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw an sphere into the scene. | def draw_sphere(self, position, *, color, label, radius):
xx, yy, zz = generate_sphere(radius, position)
sphere = go.Surface(
x=xx,
y=yy,
z=zz,
colorscale=[[0, color], [1, color]],
cauto=False,
cmin=1,
cmax=1,
showscale=False,
name=label,
showlegend=False if label is None else True,
)
self.figure.add_trace(sphere)
return sphere | [
"def make_sphere(sides, rings, width):\n FreeCAD.newDocument()\n generated_sphere = sphere(sides, rings, width)\n Part.show(generated_sphere)",
"def add_sphere(self, centre, radius, material_data):\n self.scene.add(Sphere(centre, radius, material_from_data(material_data)))",
"def add_sphere(pos_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Classify each line with what it contains using a naive, rule based classifier | def _classify_lines(self, receipt):
labels = []
for i, line in enumerate(receipt):
line = str(line)
a_chars = count(line, string.ascii_letters)
num_chars = count(line, string.digits)
punct_chars = count(line, string.punctuation)
if 'bon fiscal' in line.lower():
labels.append('unknown')
#if 'subtotal' in line.lower():
# labels.append('unknown')
elif (re.search('S\.?C\.?(.+?)(S.?R.?L.?)|(S[:.,]?A[:.,]?)', line, re.IGNORECASE) or\
any(x in line.lower() for x in ['kaufland'])) and i < 5 and 'shop' not in labels:
labels.append('shop')
elif (re.search('(C[^\w]?U[^\w]?I[^\w]?)|(C[^\w]?F[^\w]?)|(C[^\w]?I[^\w]?F[^\w]?)|(COD FISCAL).+? (\d){4,}', line) or\
re.search('\d{8}', line)) and i < 6:
labels.append('cui')
elif (re.search('(STR)|(CALEA)|(B-DUL).(.+?)', line, re.IGNORECASE) and i < 7) or\
(re.search('(NR).(\d+)', line, re.IGNORECASE) and i < 3):
labels.append('address')
elif 'TVA' in line:
labels.append('tva')
elif 'TOTAL' in line and 'SUBTOTAL' not in line:
labels.append('total')
elif re.search('DATA?.+?\d{2,4}[.\\-]\d{2,4}[.\\-]\d{2,4}', line, re.IGNORECASE) or\
re.search('\d{2}[./\\-]\d{2}[./\\-]\d{2,4}', line, re.IGNORECASE):
labels.append('data')
elif a_chars > 0 and num_chars/a_chars > 1 and 2 < i < len(receipt) - 7 and \
all(x not in line.lower() for x in ['tel', 'fax']) and 'total' not in labels:
labels.append('price')
elif 3 < i < len(receipt) - 8 and a_chars+punct_chars > 5 and 'total' not in labels and ((\
all(not re.search('(\W|^)'+x, line.lower()) for x in ['tel', 'fax', 'subtotal', 'numerar', 'brut', 'net'] +
days)\
and not re.search('\d{5}', line)) or labels[-1] == 'price'):
labels.append('name')
else:
labels.append('unknown')
return labels | [
"def classifying_func(features):\n return classify_line(features, model, encoder)",
"def classify(training=sample_file):\n\n input = sc.textFile(args.input).map(lambda word: word.lower().split(\" \")).collect()[0] # Input tweet converted into list of words\n total_tweets = total_number_of_tweets(tra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dada una ``Ruta`` (Path) a una subcoleccion, retorna esa subcoleccion. | def subcoleccion_desde_ruta(self, ruta):
parts = ruta.split(".")
coleccion = self
while parts:
coleccion = coleccion.colecciones[parts.pop(0)]
return coleccion | [
"def existing_sub_paths(self, sub_paths):\n paths_to_subs = [self / _ for _ in sub_paths]\n return [_ for _ in paths_to_subs if _.exists()]",
"def _isSubpathInPath(self, path, subpath):\n path = self._getAbsPath(path)\n subpath = self._getAbsPath(subpath)\n\n # If the parent pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devuelve todos los artefactos y subartefactos(acciones) contenidos como una lista de contextos del analizador. | def a_contextos(self):
resultado = []
for principal, alias in six.iteritems(self.nombres_de_artefactos):
artefacto = self[principal]
resultado.append(
AnalizadorDeContexto(
nombre=principal, alias=alias, args=artefacto.obtener_argumentos()
)
)
return resultado | [
"def get_acls(self):\n return self.access_list_manager.get_objects()",
"def get_dobj_acl(self, root_token):\n objects = []\n acls = []\n \n objects = [token for token in root_token.children if token.dep in SYMBOLS_FOR_OBJECTS]\n # get associated acl\n for obj in ob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toma un Lexicon y apliqua ".transformar" a sus claves y alias. | def _transformar_con_lexicon(self, viejo):
nuevo_ = Lexicon()
# Los léxicos exhiben solo sus claves reales en la mayoría de los lugares,
# por lo que esto solo tomará esos, no los alias.
for clave, valor in six.iteritems(viejo):
# Realice una Deepcopy (copia profunda) del valor para que no solo estemos
# copiando una referencia
nuevo_[self.transformar(clave)] = copy.deepcopy(valor)
# Copie también todos los alias, que son asignaciones de teclas de cadena_a_cadena
for clave, valor in six.iteritems(viejo.alias):
nuevo_.alias(from_=self.transformar(clave), to=self.transformar(valor))
return nuevo_ | [
"def transform(self, translate, scale, theta):\n return self.rotate(theta).scale(scale).translate(translate)",
"def transform(self, verbose=1, **kwargs):\n self.current = self.tokens.copy()\n transformation_selection = self.transformation_selection.copy()\n for kw in kwargs:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getReviewersAndWatchers(db, commits=None, changesets=None) > tuple Returns a tuple containing two dictionaries, each mapping file IDs to dictionaries mapping user IDs to sets of changeset IDs. The first dictionary defines the reviwers of each file, the second dictionary defines the watchers of each file. For any changes in a file for which no reviewer is identified, None is used as a key in the dictionary instead of a real user ID. | def getReviewersAndWatchers(db, repository, commits=None, changesets=None, reviewfilters=None,
applyfilters=True, applyparentfilters=False):
if changesets is None:
changesets = []
changeset_utils.createChangesets(db, repository, commits)
for commit in commits:
changesets.extend(changeset_utils.createChangeset(db, None, repository, commit, do_highlight=False))
cursor = db.cursor()
filters = Filters()
filters.setFiles(db, list(getFileIdsFromChangesets(changesets)))
if applyfilters:
filters.load(db, repository=repository, recursive=applyparentfilters)
if reviewfilters:
filters.addFilters(reviewfilters)
reviewers = {}
watchers = {}
for changeset in changesets:
author_user_ids = changeset.child.author.getUserIds(db) if changeset.child else set()
cursor.execute("SELECT DISTINCT file FROM fileversions WHERE changeset=%s", (changeset.id,))
for (file_id,) in cursor:
reviewers_found = False
for user_id, (filter_type, delegate) in filters.listUsers(file_id).items():
if filter_type == 'reviewer':
if user_id not in author_user_ids:
reviewer_user_ids = [user_id]
elif delegate:
reviewer_user_ids = []
for delegate_user_name in delegate.split(","):
delegate_user = dbutils.User.fromName(db, delegate_user_name)
reviewer_user_ids.append(delegate_user.id)
else:
reviewer_user_ids = []
for reviewer_user_id in reviewer_user_ids:
reviewers.setdefault(file_id, {}).setdefault(reviewer_user_id, set()).add(changeset.id)
reviewers_found = True
else:
watchers.setdefault(file_id, {}).setdefault(user_id, set()).add(changeset.id)
if not reviewers_found:
reviewers.setdefault(file_id, {}).setdefault(None, set()).add(changeset.id)
return reviewers, watchers | [
"def getReviewedReviewers(db, review):\n\n cursor = db.cursor()\n\n cursor.execute(\"\"\"SELECT reviewfiles.reviewer, reviewfiles.changeset, reviewfiles.file\n FROM reviewfiles\n WHERE reviewfiles.review=%s\n AND reviewfiles.state='reviewed'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getReviewedReviewers(db, review) > dictionary Returns a dictionary, like the ones returned by getReviewersAndWatchers(), but with details about all reviewed changes in the review. | def getReviewedReviewers(db, review):
cursor = db.cursor()
cursor.execute("""SELECT reviewfiles.reviewer, reviewfiles.changeset, reviewfiles.file
FROM reviewfiles
WHERE reviewfiles.review=%s
AND reviewfiles.state='reviewed'""",
(review.id,))
reviewers = {}
for user_id, changeset_id, file_id in cursor.fetchall():
reviewers.setdefault(file_id, {}).setdefault(user_id, set()).add(changeset_id)
return reviewers | [
"def getPendingReviewers(db, review):\n\n cursor = db.cursor()\n\n cursor.execute(\"\"\"SELECT reviewuserfiles.uid, reviewfiles.changeset, reviewfiles.file\n FROM reviewfiles\n LEFT OUTER JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id)\n W... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getPendingReviewers(db, review) > dictionary Returns a dictionary, like the ones returned by getReviewersAndWatchers(), but with details about remaining unreviewed changes in the review. Changes not assigned to a reviewer are handled the same way. | def getPendingReviewers(db, review):
cursor = db.cursor()
cursor.execute("""SELECT reviewuserfiles.uid, reviewfiles.changeset, reviewfiles.file
FROM reviewfiles
LEFT OUTER JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id)
WHERE reviewfiles.review=%s
AND reviewfiles.state='pending'""",
(review.id,))
reviewers = {}
for user_id, changeset_id, file_id in cursor.fetchall():
reviewers.setdefault(file_id, {}).setdefault(user_id, set()).add(changeset_id)
return reviewers | [
"def getReviewedReviewers(db, review):\n\n cursor = db.cursor()\n\n cursor.execute(\"\"\"SELECT reviewfiles.reviewer, reviewfiles.changeset, reviewfiles.file\n FROM reviewfiles\n WHERE reviewfiles.review=%s\n AND reviewfiles.state='reviewed'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
collectReviewTeams(reviewers) > dictionary Takes a dictionary as returned by getReviewersAndWatchers() or getPendingReviewers() and transform into a dictionary mapping sets of users to sets of files that those groups of users share review responsibilities for. The same user may appear in number of sets, as may the same file. If None appears as a key in the returned dictionary, the set of files it is mapped to have changes in them with no assigned reviewers. | def collectReviewTeams(reviewers):
teams = {}
for file_id, file_reviewers in reviewers.items():
if None in file_reviewers:
teams.setdefault(None, set()).add(file_id)
team = frozenset(filter(None, file_reviewers.keys()))
if team: teams.setdefault(team, set()).add(file_id)
return teams | [
"def getReviewedReviewers(db, review):\n\n cursor = db.cursor()\n\n cursor.execute(\"\"\"SELECT reviewfiles.reviewer, reviewfiles.changeset, reviewfiles.file\n FROM reviewfiles\n WHERE reviewfiles.review=%s\n AND reviewfiles.state='reviewed'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator to add a Task to the given list, for registering with argparse. | def register_task(choices):
def decorator(cls):
instantiated_task = cls()
choices.append(instantiated_task)
logging.debug(f"Registered {instantiated_task.name} task with argparse choices")
return cls
return decorator | [
"def addtask(self, func, *args, **kwargs):\n if not iscoroutinefunction(func):\n async_f = self.func2async(func)\n else:\n async_f = func\n\n _t = tuple([async_f, args, kwargs])\n self.tasklist.append(_t)",
"def alm_add_task(self, task):\n pass",
"def add... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |