query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Method to expand the neighbor_word_list with synsets, hyponyms and hypernyms. used in get_neighbor_words_set() | def expand_synset(neighbor_word_list, language):
if not expand_synset_activated or not language.__eq__("English"):
return neighbor_word_list
new_neighbor_word_set = set()
for word in neighbor_word_list:
new_neighbor_word_set.add(word)
synsets = wn.synsets(word)
synonyms_lis... | [
"def expandTree(search_terms):\n\n treeneighbors = {}\n\n for word in search_terms:\n synsets = wn.synsets(word)\n\n all_hyponyms = []\n all_hypernyms = []\n\n for synset in synsets:\n hyponyms = synset.hyponyms()\n hypernyms = synset.hypernyms()\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to read the test set, parse the test data, and map each instance into a vector space | def parse_test_data(test_set, training_output, language):
print "Reading test set: " + test_set
xmldoc = minidom.parse(test_set)
data = {}
lex_list = xmldoc.getElementsByTagName('lexelt')
for node in lex_list:
lexelt = node.getAttribute('item') # item "active.v"
data[lexelt] = []
... | [
"def parse_data_set(target_dir, root_dir='data/handwriting/xml_data_root/lineStrokes/',\n testset_spec='data/handwriting/testsetspecs.txt'):\n if testset_spec is not None:\n with open(testset_spec) as f:\n test_dirs = [k.rstrip() for k in f.readlines()]\n else:\n tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This runs a command on the remote host. This returns a pexpect.spawn object. This handles the case when you try to connect to a new host and ssh asks you if you want to accept the public key fingerprint and continue connecting. | def ssh_command (user, host, password, command):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
i = child.expect([ssh_newkey, PASSWORD, pexpect.TIMEOUT])
if i == 0: # First Time access - send yes to connect.
chi... | [
"def ssh_command (user, host, password, command):\n ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'\n child = pexpect.spawn('ssh -tql %s %s %s'%(user, host, command))\n i = child.expect([ssh_newkey, PASSWORD, pexpect.TIMEOUT])\n if i == 0: # First Time access - send yes to connect.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The constructor for reviewsMenuClass. Attributes | def __init__(self):
super().__init__()
self.status = True
self.token = tokensClass()
self.layout = layout.reviewsLayoutClass(self)
self.title = "LMS Reviews GUI"
self.location = (50, 125) | [
"def __init__(self, *args, **kwargs):\n _core_.MenuItem_swiginit(self,_core_.new_MenuItem(*args, **kwargs))",
"def __init__(self, master=None, cnf={}, **kw):\n Widget.__init__(self, master, 'menu', cnf, kw)",
"def __init__(self, name, title, icon=None, desc=None, prop=None, style=None, attr=None,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes a dictionary (asterix) in the EUROCONTROL ASTERIX category. | def encode(asterix):
assert type(asterix) is dict
asterix_record = 0
#priority_asterix_cat = [21, 34]
for k, v in asterix.iteritems():
#for k in priority_asterix_cat:
v = asterix[k]
record = 0
n_octets_data_record = 0
cat = 0
ctf = load_asterix_category_for... | [
"def evaluate_appendix(self):\n # In case the appendix is a string it is being interpreted as already in json format and thus trying to unjson\n if isinstance(self.appendix, bytes):\n try:\n # Attempting to use the encoder to encoder to decode the bytes string\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encodes the record from the given category (cat). | def encode_category(cat, did, tree):
if did == {}:
return 0, 0
mdi = {}
for c in tree.getElementsByTagName('DataItem'):
di = c.getAttribute('id')
if di.isdigit():
di = int(di)
rule = c.getAttribute('rule')
if di in did:
if verbose >= 1:
... | [
"def encode(asterix):\n assert type(asterix) is dict\n\n asterix_record = 0\n\n #priority_asterix_cat = [21, 34]\n for k, v in asterix.iteritems():\n #for k in priority_asterix_cat:\n v = asterix[k]\n record = 0\n n_octets_data_record = 0\n cat = 0\n\n ctf = load_as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the encoded Data Item. Encodes the Data Item in the data field of record according to the rules defined in the XML file. | def encode_dataitem(dfd, tree):
assert type(dfd) is dict or type(dfd) is list
for c in tree.getElementsByTagName('DataItemFormat'):
for d in c.childNodes:
if d.nodeName == 'Fixed':
return encode_fixed(dfd, d)
else:
if d.nodeName == 'Variable':
... | [
"def encode_data(self, data):\n if self.unit == \"char\":\n data = self.char_encoding(data)\n elif self.unit == \"char-ngram\":\n data = self.ngram_encoding(data)\n elif self.unit == \"morpheme\" or self.unit == \"oracle\":\n data = self.morpheme_encoding(data)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Board Path Cloner This function is used to clone the BoardPath object. | def clone(self):
# Run the constructor.
other = BoardPath()
# Copy the object variables
other._current_cost = self._current_cost
other._path = self._path[:]
other._current_loc = self._current_loc
return other | [
"def clone(self):\n joined_function = lambda: dot_joiner(self.path, self.path_type)\n return self.__class__(self.path, self.configuration, self.converters, self.ignore_converters, joined_function=joined_function)",
"def copy(self):\n path_copy = Path(self.graph, self.nodes[:], initialize=Fals... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Current Location Accessor Function to get the current location for this path. | def get_current_location(self):
return self._current_loc | [
"def get_current_location():\n global current_location\n return current_location",
"def get_location(self):\n\t\treturn self.current_coordinate",
"def get_location(self):\n return self.__location",
"def get_location(self):\r\n return self._location",
"def get_location(self):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Distance Calculator Flexible function for calculating the distance. Depending on the specified heuristic (either explicit in call or implicit with class), different distances can be returned for the same functions. | def get_distance(self, heuristic=""):
# If no heuristic is specified, used the default
if(heuristic == ""):
heuristic = BoardPath._heuristic
if(heuristic == "manhattan"):
return self.calculate_manhattan_dist()
elif(heuristic == "euclidean"):
return se... | [
"def distance(obj_1, obj_2):\n # return heuristic(obj_1, obj_2)\n return euclidean(obj_1, obj_2)",
"def getDistanceFunction(self): # real signature unknown; restored from __doc__\n pass",
"def cost_distance(e):\n pass",
"def get_distance(self, node_1, node_2, agent=None):\n #To ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manhattan Distance Calculator Calculates difference between current location and\ the goal location using Manhattan distance. | def calculate_manhattan_dist(self):
return self._current_cost + abs(self._current_loc.get_row() - self._goal_loc.get_row()) +\
abs(self._current_loc.get_column() - self._goal_loc.get_column()) | [
"def manhattan_distance(current_x, current_y, goal_x, goal_y):\n return abs(current_x - goal_x) + abs(current_y - goal_y)",
"def manhattan_distance(self):\n return calculate_manhattan_distance(self.location, self.target_location)",
"def manhattan_distance(self):\n values = {-1: (), 0: (), 1: ()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Euclidean Distance Calculator Calculates difference between current location and\ the goal location using Euclidean distance. | def calculate_euclidean_dist(self):
x_dist = self._current_loc.get_column() - self._goal_loc.get_column()
y_dist = self._current_loc.get_row() - self._goal_loc.get_row()
# Note ** is power operator in Python
return self._current_cost + sqrt(x_dist**2 + y_dist**2) | [
"def euclidean_distance(current_x, current_y, goal_x, goal_y):\n distance = math.sqrt((goal_x - current_x)**2 + (goal_y - current_y)**2)\n return distance",
"def euclideanDistance(loc1, loc2):\n # BEGIN_YOUR_CODE (our solution is 1 line of code, but don't worry if you deviate from this)\n return math.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Direct Blocked Path Checker This function checks whether if all direct next moves from the current location are blocked by an unpassable object or the edge of the board. This can be used to determine a penalty factor when calculating the heuristic. This function is used in the made_up heuristics function. | def _is_all_direct_next_moves_blocked(self, reference_board=None):
# Use untraversed board if none is specified
if reference_board is None:
reference_board = BoardPath._untraversed_board
# Case #1 - Goal and Current Location in the Same Row
if self._current_loc.get_row() == ... | [
"def check_if_safe_is_blocked(self, possible_directions):\r\n safe_positions = { # All possibly safe positions from the bomb\r\n \"UP\": [\r\n (self.pos[0] - 1, self.pos[1] - 2),\r\n (self.pos[0] + 1, self.pos[1] - 2),\r\n ],\r\n \"DOWN\": [\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move Location Calculator Calculates the new location for a move in the specified direction. | def _calculate_move_location(self, direction):
current_row = self._current_loc.get_row()
current_column = self._current_loc.get_column()
# Calculate the new location for a left move
if (direction == "l"):
return Location(current_row, current_column - 1)
# Calculate t... | [
"def next_location(x, y, direction):\n new_x = x\n new_y = y\n\n if direction == \"W\":\n new_x = new_x - 1\n elif direction == \"S\":\n new_y = new_y - 1\n elif direction == \"E\":\n new_x = new_x + 1\n else: # going north\n new_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Goal Setter This function sets the goal for the board. | def set_goal(goal_loc):
BoardPath._goal_loc = goal_loc | [
"def set_goal(self, goal):\n self._reset(self)\n # TODO: Set goal value. \n self.goal = goal",
"def set_goal(self, val):\n self.goal = val",
"def goal(self, goal):\n\n self._goal = goal",
"def set_goal(self, **kwargs):\n return self.env.set_goal(**kwargs)",
"def set_goal(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Untraversed Board Setter This function stores the untraversed board configuration. | def set_untraversed_board(board):
BoardPath._untraversed_board = board | [
"def restore_previous_configuration(self):\n self._marbles_on_board = copy.deepcopy(self._previous_configuration)",
"def reset_board(self):\n\n self.board = np.array(self.initial_board)",
"def resetBoard(self):\n\t\tself.board = np.zeros((self.boardSize,self.boardSize))",
"def set_board(board):"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Heuristic Setter This function stores the board path heuristic | def set_heuristic(heuristic):
BoardPath._heuristic = heuristic | [
"def heuristic(self):\r\n # 1.\r\n blacks, whites = 0, 0\r\n weights = [0 for _ in range(6)]\r\n directions = [[-1, -1], [-1, 1], [1, 1], [1, -1]]\r\n user_dir = directions[:2] if self.current_player == 'n' else directions[2:]\r\n for i in range(8):\r\n for j in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Less Than Operator Less than operator used for the distance of two BoardPath objects. | def __lt__(self, other):
return self.get_distance() < other.get_distance() | [
"def __lt__(self, other):\n if not self._is_valid_operand(other):\n return NotImplemented\n\n return self.distance < other.distance",
"def __lt__(self, distance):\n return self.total < distance.total",
"def test_less_than(self):\n utils.compare_tracing_methods(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Row Number Accessor Accessor to get the row number of this location. | def get_row(self):
return self._row_number | [
"def row_idx(self):\n return self._row_idx",
"def row_counter(self) -> int:\n return self.writer.row_counter",
"def excel_row_position(self):\n if self.is_variable:\n return self._excel_row_position\n raise CellValueError(\"This operation is supported only for variables.\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Column Number Accessor Accessor to get the column number of this location. | def get_column(self):
return self._column_number | [
"def column(self):\n return length(self.__indent[-1]) if self.__col is None else self.__col",
"def get_column(location):\r\n return location[1]",
"def column(self): \r\n\r\n return self._column",
"def columnAt(self, p_int): # real signature unknown; restored from __doc__\n return 0",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read in molecule(s) (and conformers, if present) in insdf file. Create Psi4 input calculations for each structure. | def confs_to_psi(insdf,
method,
basis,
calctype='opt',
memory=None,
via_json=False):
wdir = os.getcwd()
# open molecules
molecules = reader.read_mols(insdf)
### For each molecule: for each conf, generate input
for... | [
"def convert_single_sdf_to_pdb(pdb_subfolder_path, sdf_file_path):\n\n if os.path.exists(sdf_file_path) is True:\n\n file_basename = basename(sdf_file_path)\n file_basename = file_basename.split(\"__input1\")[0]\n\n file_output_name = \"{}{}_\".format(pdb_subfolder_path, file_basename)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract a date from the JSON filing, at the provided path. | def get_date(filing: Dict, path: str) -> date:
try:
raw = dpath.util.get(filing, path)
return date.fromisoformat(raw)
except (IndexError, KeyError, TypeError, ValueError):
return None | [
"def load(self, date=None, path='.'):\n date = datetime.now() if date is None else date\n file = Path(path) / self._generate_filename(date)\n\n with open(file, 'r', encoding='utf8') as f:\n data = json.load(f, )\n\n return data",
"def extract_date_from_fullpath(name):\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract a str from the JSON filing, at the provided path. | def get_str(filing: Dict, path: str) -> str:
try:
raw = dpath.util.get(filing, path)
return str(raw)
except (IndexError, KeyError, TypeError, ValueError):
return None | [
"def get_jsonpath(obj: dict, jsonpath):\n try:\n keys = str(jsonpath).split(\".\")\n val = obj\n\n for key in keys:\n val = val[key]\n\n return val\n\n except (KeyError, TypeError):\n return \"\"",
"def get_json_str(self):\n\n with open(self.path, mode='r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract a boolean from the JSON filing, at the provided path. | def get_bool(filing: Dict, path: str) -> str:
try:
raw = dpath.util.get(filing, path)
return bool(raw)
except (IndexError, KeyError, TypeError, ValueError):
return None | [
"def boolean_value(cls, json_field: str, value: bool) -> \"JsonPattern\":\n return jsii.sinvoke(cls, \"booleanValue\", [json_field, value])",
"def getBool( self, par, path ):\n\n return self.db.getBoolPar( par, path )",
"def is_json_path(location):\n if filetype.is_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
quote src to string | def _quote(src, encoding="utf-8"):
if isinstance(src, unicode):
src = src.encode(encoding)
return urllib.quote(src) | [
"def replacement(self):\n assert (self.src or self.inline) and not (self.src and self.inline)\n if self.src:\n return '<script async type=\"text/javascript\" src=\"%s\"></script>' % urllib.quote(self.src)\n else:\n return '<script>\\n%s\\n</script>' % self.inline",
"def Sourceify(path):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the expected keys for the log entry. | def expected_log_keys(learner: adaptive.BaseLearner) -> list[str]:
# Check if the result contains the expected keys
expected_keys = [
"elapsed_time",
"overhead",
"npoints",
"cpu_usage",
"mem_usage",
]
if not _at_least_adaptive_version("0.16.0", raises=False) and n... | [
"def provideExpectedMetaKeys(self):\n return self.metadataKeys, self.metadataParams",
"def keyValues(self): # real signature unknown; restored from __doc__\n return []",
"def assertKeys(self, data, expected):\r\n self.assertEqual(sorted(data.keys()), sorted(expected))",
"def get_keys(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Spacy processed sentences in which the element is positioned. | def get_processed_sentence(self):
if not hasattr(self, "in_sentence"):
raise AttributeError(f"{self} does not have attribute 'in_sentence'.")
try:
sen_ixs = [sen.element_id for sen in self.in_sentence]
except TypeError as e:
sen_ixs = [self.in_sentence.eleme... | [
"def sentences(self) -> List[str]:\n\t\treturn [self.text[start:end] for start, end in self.tokenizations]",
"def sentences(self):\n return self._sentences",
"def get_sentence_annotations(self):\r\n return self._sentences",
"def sentences(self, tag=False, tag_method=None):\n self.__set_te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the annotation is pronominal by full parsed PoS tag. All tokens should be pronominal (works best for anaphoric pronominal mentions as intended). | def check_pronominal(self):
pronom_tags = ["PRP", "PRP$", "WDT", "WP", "WP$"]
token_procs = self.get_processed_tokens()
all_pronom = all(
t.tag_ in pronom_tags for t in token_procs
) # True if all tokens are pronom_tags
# print(f"{' '.join(t.text + '.' + t.tag_ for t... | [
"def noPronounArgs(self):\n for (a, _) in self.args:\n tokenized_arg = nltk.word_tokenize(a)\n if len(tokenized_arg) == 1:\n _, pos_tag = nltk.pos_tag(tokenized_arg)[0]\n if ('PRP' in pos_tag):\n return False\n return True",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of token objects for the event extent. The extent can be set to include discontiguous_triggers, participants, and/or fillers. Setting this to an empty list will only return the original In the definition of an event nugget we include all of these. | def get_extent_tokens(self, extent=["discontiguous_triggers"], source_order=True):
all_tokens = self.tokens.copy()
core_sen_idx = all_tokens[0].in_sentence.element_id # to ensure discont is in same sentence
for ext in extent:
if getattr(self, ext):
all_tokens.extend(... | [
"def get_extent_tokens(self, extent=[], source_order=True):\n all_tokens = self.tokens.copy()\n\n for ext in extent:\n if getattr(self, ext):\n all_tokens.extend(t for x in getattr(self, ext) for t in x.tokens)\n\n all_tokens = list(\n set(all_tokens)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of token ids for the event extent. Relies on Event.get_extent_tokens() for fetching the tokens. | def get_extent_token_ids(self, **kwargs):
token_span = self.get_extent_tokens(**kwargs)
return [t.index for t in token_span] | [
"def get_extent_tokens(self, extent=[], source_order=True):\n all_tokens = self.tokens.copy()\n\n for ext in extent:\n if getattr(self, ext):\n all_tokens.extend(t for x in getattr(self, ext) for t in x.tokens)\n\n all_tokens = list(\n set(all_tokens)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of token objects for the sentiment expression extent. The extent can be set to include targets. Setting this to an empty list will only return the original tokens. | def get_extent_tokens(self, extent=[], source_order=True):
all_tokens = self.tokens.copy()
for ext in extent:
if getattr(self, ext):
all_tokens.extend(t for x in getattr(self, ext) for t in x.tokens)
all_tokens = list(
set(all_tokens)
) # this i... | [
"def get_extent_tokens(self, extent=[\"discontiguous_triggers\"], source_order=True):\n all_tokens = self.tokens.copy()\n core_sen_idx = all_tokens[0].in_sentence.element_id # to ensure discont is in same sentence\n\n for ext in extent:\n if getattr(self, ext):\n all_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set token id based on document id + token position in text | def get_token_id(self):
return f"{self.document_title}_{self.index}" | [
"def get_id(self, token):\n if token in self.word_dict:\n return self.word_dict[token]\n else:\n return 0",
"def add_tokens_to_word2id(word2id,tokens):\r\n offset = len(word2id.keys())\r\n for t in tokens:\r\n word2id[t] = offset\r\n offset+=1\r\n \r\n return word2id",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append value to attribute list, create the attribute list if does not exist. | def append_attribute(myobj, attrib_k, val):
vals = getattr(myobj, attrib_k, [])
if val not in vals:
vals.append(val)
setattr(myobj, attrib_k, vals) | [
"def _setAttribute(self, attribute, value):\n\n # if multiple values found\n if hasattr(self, attribute):\n\n # make sure attribute is a list\n values = getattr(self, attribute)\n if not isinstance(values, list):\n setattr(self, attribute, [values])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to converts XML attributes into a dictionary | def __convertAttributes__(xml_source):
attributes = {}
for attrName, attrValue in xml_source.attributes.items():
attributes[attrName] = attrValue
return attributes | [
"def _xml_to_dict(xml_to_convert, attr_prefix=''):\n return xmltodict.parse(xml_to_convert, attr_prefix=attr_prefix)",
"def convert_xml_to_dict():\n pass",
"def get_attrs_dict(self, root_element):\n attr_elements = root_element.findall(\"attribute\")\n attrs_dict = {}\n for el in attr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the Spacy processing pipeline on the annotation documents. Add processed docs so they can be accessed. | def process_spacy(self):
def prevent_sentence_boundary_detection(doc):
for token in doc:
# This will entirely disable spaCy's sentence detection
token.is_sent_start = False
return doc
def process_sentence(sen_tokens):
doc = spacy.toke... | [
"def preprocess(self):\n for doc in self.documents:\n doc.preprocess()",
"def process_document(self, doc):\n self.extract(doc)\n self.discover_people(doc)",
"def run(self, mapping={}, *args, **kwargs):\n self.processed = 0\n for batch in self._pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the main corpus and IAA gold standard files and joins them in one WebAnnoProject. | def parse_main_iaa(main_dirp, iaa_dirp, opt_fp):
# moderator_id = "gilles"
# exclude_moderator = lambda x: moderator_id not in Path(x.path).stem
# include_moderator = lambda x: moderator_id in Path(x.path).stem
main_project = WebannoProject(main_dirp)
# # exclude moderator and trial files which st... | [
"def get_duc():\n duc_path = os.getcwd() + \"/dataset/duc_source\"\n docs = []\n summaries = []\n doc_names = []\n # Each directory contains more than one document.\n for dir_name in sorted(os.listdir(duc_path + \"/docs\")):\n for doc_name in sorted(os.listdir(duc_path + \"/docs/\" + dir_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the last times attributes of the AddressStatus and of all the processes running on it. | def update_times(self, remote_time, local_time):
self.remote_time = remote_time
self.local_time = local_time
for process in self.processes.values():
process.update_times(self.address_name, remote_time) | [
"def refresh_status(self):\n what_time_is_now = what_time_is_it()\n for process in Connection.Instance().db.manager.find({\"is_alive\": True}):\n if (not psutil.pid_exists(process['pid'])) or \\\n (psutil.pid_exists(process['pid']) and psutil.Process(process['pid']).statu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the state transition is valid. | def check_transition(self, new_state):
return new_state in self._Transitions[self.state] | [
"def _validate_transition(self, action, allowed_states):\n assert self.state in allowed_states, (\n \"Coding error: invalid state transition detected for %s handling \"\n \"action %s, current state %s, allowed states %s\" %\n (self.name, action, self.state, \", \".join(allowe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new process to the process list. | def add_process(self, process):
self.processes[process.namespec()] = process | [
"def add_process(self, process):\n self.processes[process.pid] = process",
"def add_process(self, process: Process) -> None:\n self.__check_short_section_name(process.short_name())\n self.__processes.append(process)",
"def add_process(self):\n process_id = str(self.processBox.current... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the process running on the address. Here, 'running' means that the process state is in Supervisor RUNNING_STATES. | def running_processes(self):
return [process for process in self.processes.values()
if process.running_on(self.address_name)] | [
"def proc_is_running(name: str) -> int:\n for proc in process_iter(['pid', 'name']):\n if name in proc.info['name']: # type: ignore\n return proc.info['pid'] # type: ignore\n return 0",
"def is_process_running(name):\n if not hasattr(is_process_running, \"proc\"):\n is_process_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the process running on the address and having a pid. Different from running_processes_on because it excludes the states STARTING and BACKOFF | def pid_processes(self):
return [(process.namespec(), process.infos[self.address_name]['pid'])
for process in self.processes.values()
if process.pid_running_on(self.address_name)] | [
"def process_pid(self):\n return self._process_pid",
"def _get_process(self, pid):\n if pid == 0:\n return None\n elif pid in self.process_cache:\n return self.process_cache[pid]\n else:\n return psutil.Process(pid)",
"def proc_is_running(name: str) -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the loading of the address, by summing the declared loading of the processes running on that address | def loading(self):
loading = sum(process.rules.expected_loading
for process in self.running_processes())
self.logger.debug('address={} loading={}'.
format(self.address_name, loading))
return loading | [
"def get_load_data():\n proc_stat = open(\"/proc/stat\", \"r\")\n ret = []\n #times_since_startup = proc_stat.readline().strip().split()[1:]\n for line in proc_stat:\n line_split = line.strip().split()\n if(not (\"cpu\" in line_split[0])): #we have gone past the CPU lines\n brea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns two lists with the ids of grec_seq_rec and seq_reserva | def get_seq_lists(dataframe_bookings):
seq_rec = dataframe_bookings.select('operative_incoming').collect()
seq_reserva = dataframe_bookings.select('booking_id').collect()
seq_rec = [val[0] for val in list(seq_rec)]
seq_reserva = [val[0] for val in list(seq_reserva)]
return seq_rec, seq_reserva | [
"def ids(self):\n return [seq.metadata['id'] for seq in self]",
"def create_recordid_list(rec_ids):\n rec_list = []\n for row in rec_ids:\n rec_list.append(row[0])\n return rec_list",
"def get_recordIds(self):\n record_ids = []\n for item in self.order_items:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It calculates the subquery for the field Tax_Sales_Transfer_pricing | def sub_tax_sales_transfer_pricing(manager, df_fields, seq_recs, seq_reservas):
# df_hotel = manager.get_dataframe(tables['dwc_bok_t_canco_hotel'])
# df_circuit = manager.get_dataframe(tables['dwc_bok_t_canco_hotel_circuit'])
# df_other = manager.get_dataframe(tables['dwc_bok_t_canco_other'])
# df_trans... | [
"def sub_tax_cost_transfer_pricing(manager, df_fields, seq_recs, seq_reservas):\n # df_hotel = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel\"])\n # df_circuit = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel_circuit\"])\n # df_other = manager.get_dataframe(tables[\"dwc_bok_t_canco_other\"])\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It calculates the subquery for the field Tax_Cost_Transfer_pricing | def sub_tax_cost_transfer_pricing(manager, df_fields, seq_recs, seq_reservas):
# df_hotel = manager.get_dataframe(tables["dwc_bok_t_canco_hotel"])
# df_circuit = manager.get_dataframe(tables["dwc_bok_t_canco_hotel_circuit"])
# df_other = manager.get_dataframe(tables["dwc_bok_t_canco_other"])
# df_transf... | [
"def sub_tax_cost_transfer_pricing_eur(manager, df_fields, seq_recs, seq_reservas):\n # df_hotel = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel\"])\n # df_circuit = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel_circuit\"])\n # df_other = manager.get_dataframe(tables[\"dwc_bok_t_canco_other\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It calculates the subquery for the field Tax_Transfer_pricing_EUR | def sub_tax_transfer_pricing_eur(manager, df_fields, seq_recs, seq_reservas):
# df_hotel = manager.get_dataframe(tables["dwc_bok_t_canco_hotel"])
# df_circuit = manager.get_dataframe(tables["dwc_bok_t_canco_hotel_circuit"])
# df_other = manager.get_dataframe(tables["dwc_bok_t_canco_other"])
# df_transfe... | [
"def sub_tax_cost_transfer_pricing_eur(manager, df_fields, seq_recs, seq_reservas):\n # df_hotel = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel\"])\n # df_circuit = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel_circuit\"])\n # df_other = manager.get_dataframe(tables[\"dwc_bok_t_canco_other\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It calculates the subquery for the field Tax_Cost_Transfer_pricing_EUR | def sub_tax_cost_transfer_pricing_eur(manager, df_fields, seq_recs, seq_reservas):
# df_hotel = manager.get_dataframe(tables["dwc_bok_t_canco_hotel"])
# df_circuit = manager.get_dataframe(tables["dwc_bok_t_canco_hotel_circuit"])
# df_other = manager.get_dataframe(tables["dwc_bok_t_canco_other"])
# df_tr... | [
"def sub_tax_cost_transfer_pricing(manager, df_fields, seq_recs, seq_reservas):\n # df_hotel = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel\"])\n # df_circuit = manager.get_dataframe(tables[\"dwc_bok_t_canco_hotel_circuit\"])\n # df_other = manager.get_dataframe(tables[\"dwc_bok_t_canco_other\"])\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function constructs the integrator to be suitable with casadi environment, for the equations of the model and the objective function with variable time step. | def integrator_model(self):
xd, xa, u, uncertainty, ODEeq, Aeq, u_min, u_max, states, algebraics, inputs, nd, na, nu, nmp, modparval \
= self.DAE_system()
dae = {'x': vertcat(xd), 'z': vertcat(xa), 'p': vertcat(u),
'ode': vertcat(*ODEeq), 'alg': vertcat(*Aeq)}
opts =... | [
"def integrator_model(self):\n\n xd, xa, u, uncertainty, ODEeq, Aeq, u_min, u_max, states, algebraics, inputs, nd, na, nu, nmp, modparval \\\n = self.DAE_system()\n ODEeq_ = vertcat(*ODEeq)\n\n self.ODEeq = Function('f', [xd, u], [vertcat(*ODEeq)], ['x0', 'p'], ['xdot'])\n\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function constructs the integrator to be suitable with casadi environment, for the equations of the model and the objective function with variable time step. | def integrator_model(self):
xd, xa, u, uncertainty, ODEeq, Aeq, u_min, u_max, states, algebraics, inputs, nd, na, nu, nmp, modparval \
= self.DAE_system()
ODEeq_ = vertcat(*ODEeq)
self.ODEeq = Function('f', [xd, u], [vertcat(*ODEeq)], ['x0', 'p'], ['xdot'])
dae = {'x': ver... | [
"def integrator_model(self):\n\n xd, xa, u, uncertainty, ODEeq, Aeq, u_min, u_max, states, algebraics, inputs, nd, na, nu, nmp, modparval \\\n = self.DAE_system()\n\n dae = {'x': vertcat(xd), 'z': vertcat(xa), 'p': vertcat(u),\n 'ode': vertcat(*ODEeq), 'alg': vertcat(*Aeq)}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort the 4 corners clockwise of a rectangle so that the topleft corner is the first one. | def sort_corners(self, corners: np.ndarray):
center = np.sum(corners, axis=0) / 4
sorted_corners = sorted(
corners,
key=lambda p: math.atan2(p[0][0] - center[0][0], p[0][1] - center[0][1]),
reverse=True,
)
return np.roll(sorted_corners, 1, axis=... | [
"def sort_corners(corners):\n col_sorted = corners[np.argsort(corners[:, 1])] # sort on the value in column\n\n # sort on the value in rows. a, b are the indexes\n a = np.argsort(col_sorted[:2, 0])\n b = np.argsort(col_sorted[2:, 0]) + 2\n\n return col_sorted[np.hstack((a, b))]",
"def __my_sort(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given 4 sorted corners, compute the homography between the corners and the rectangle's ground truth and return the information on the mapped plane. In other words, this function returns information on a plane (in particular, the desk's or wall's). The plane's origin is in the topleft corner of the rectangle, and the no... | def get_H_R_t(self, corners: np.ndarray) -> Plane:
H = cv.findHomography(self.inner_rectangle, corners)[0]
result = self.K_inv @ H
result /= cv.norm(result[:, 1])
r0, r1, t = np.hsplit(result, 3)
r2 = np.cross(r0.T, r1.T).T
_, u, vt = cv.SVDecomp(np.hstack([r0, r1, ... | [
"def fit_plane(x, y, z):\n basis = principal_axes(x, y, z)\n a, b, c = basis[:, -1]\n d = a * x + b * y + c * z\n return a, b, c, -d.mean()",
"def define_plane(a1, a2, a3):\n p1 = np.array(a1.coords())\n p2 = np.array(a2.coords())\n p3 = np.array(a3.coords())\n cp = np.cross(p3 - p1, p2 - ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an image and a rectangle defining a region, return the laser points in that region. In case we are considering the wall or the desk, require at least 30 points for better accuracy. | def get_laser_points_in_region(
self, image: np.ndarray, region: Rectangle, is_obj: bool = False,
) -> Optional[np.ndarray]:
top_left = region.top_left
bottom_right = region.bottom_right
region_image = image[top_left.y : bottom_right.y, top_left.x : bottom_right.x]
imag... | [
"def get_lane_points(img):\n\n #crop image to use only the bottom half \n bottom_half = img[img.shape[0]//2:,:]\n\n #sum all pixels in a vertical orientation\n histogram = np.sum(bottom_half, axis=0)\n\n #get the middel point from histogram and search for max \n #left and right from that middel po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the DBSCAN clustering algorithm in order to remove possible outliers from the points detected as laser in the object. We are basically enforcing continuity in the laser line on the object, i.e. looking for a dense cluster of pixels. Interesting points are the ones whose label is not 1, i.e. the ones belonging to a ... | def remove_obj_outliers(self, points: np.ndarray) -> Optional[np.ndarray]:
dbscan_result = self.dbscan.fit(points[:, 0])
mask = dbscan_result.labels_ != -1
return np.expand_dims(points[:, 0][mask], axis=1) | [
"def MyDBSCAN(D, eps, MinPts):\n\n # This list will hold the final cluster assignment for each point in D.\n # There are two reserved values:\n # -1 - Indicates a noise point\n # 0 - Means the point hasn't been considered yet.\n # Initially all labels are 0.\n labels = [0] * len(D)\n\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an image and a list of coordinates of shape (n_points, 1, 2), return the RGB colors of those coordinates in the (0...1) range. Notice that OpenCV uses BGR instead of RGB by default, thus we need to flip the columns. | def get_colors(self, image: np.ndarray, coordinates: np.ndarray) -> np.ndarray:
x = coordinates.squeeze(1)
return np.flip(image[x[:, 1], x[:, 0]].astype(np.float64) / 255.0, axis=1) | [
"def get_colors(img):\n return [ c[1] for c in img.getcolors(img.size[0]*img.size[1]) ]",
"def pts_filter_color(points):\n pts = np.array(points).tolist()\n # Get rid of all points behind camera\n pts_fil = []\n for pt in pts:\n if pt[2] > 0: \n pts_fil.append(pt)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given points in the 3D world, save the PLY file representing the point cloud. This function saves both the original file and a version to which an outlier removal process has been applied. | def save_3d_render(
self, points: List[np.ndarray], colors: List[np.ndarray]
) -> None:
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(np.vstack(points).astype(np.float64))
pcd.colors = o3d.utility.Vector3dVector(np.vstack(colors))
if self.debug... | [
"def save_point_cloud(self):\n\n filename = 'cloud_color.ply'\n print('Saving cloud to ', filename)\n pcd = o3d.geometry.PointCloud()\n print('Creating points...')\n xyz = []\n rgb = []\n for p in self.combined_points:\n xyz.append([p[0], p[1], p[2]])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a plane represented by its origin and a normal and a list of rays, compute the intersections between the plane and the rays. | def compute_intersections(
self, plane: Plane, directions: List[np.ndarray]
) -> List[np.ndarray]:
return [
line_plane_intersection(
plane_origin=plane.origin,
plane_normal=plane.normal,
line_direction=direction,
)
... | [
"def intersect_plane(pl, ray, front_only=False):\n \"\"\"\n Distance to plane is defined as\n t = (pd - p0.n) / rd.n\n where:\n rd is the ray direction\n pd is the point on plane . plane normal\n p0 is the ray position\n n is the plane normal\n if rd.n == 0, the ray is parallel to the\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build command string from parameters passed to object. Usage of paramter h in options is going to be ignored. | def build_command_string(self):
if self._regex_helper.search_compiled(W._re_h, self.options):
if self._regex_helper.group("SOLO"):
self.options = self.options.replace('-h', '')
else:
self.options = self.options.replace('h', '')
cmd = "{} {}".f... | [
"def makeCommandString(self):\n\n ### Collect all options into a dictionary mapping option name to option value\n self.command = {'compas_executable' : self.compas_executable} \n\n for boolKey, boolVal in self.booleanChoices.items():\n if boolVal is True:\n self.comman... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse general information in line and update it to GENERAL_INFO dictionary. | def _parse_general_info(self, line):
if self._regex_helper.search_compiled(W._re_general_info, line):
self.current_ret['GENERAL_INFO'].update({
'time': datetime.datetime.strptime(self._regex_helper.group("TIME"), '%H:%M:%S').time(),
'uptime': self._regex_helper.group(... | [
"def parse_basic_info(cls, line, line_parsed):\n\n if line_parsed == 1:\n # sequence\n cls.INFO['sequence'] = line.strip()\n elif line_parsed == 2:\n # Dot-bracket string\n cls.INFO['dot_bracket'] = line.strip()\n elif line_parsed == 3:\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse V option output in line and append it to RESULT list. | def _parse_v_option(self, line):
if self._regex_helper.search_compiled(W._re_v_option, line):
self.current_ret['RESULT'].append(self._regex_helper.group("V_OPTION"))
raise ParsingDone | [
"def processOption (self, line) :\n ll = line.split ('=')\n if len (ll) < 2:\n print \"Cannot parse option \" , line\n sys.exit()\n result = (ll[0].strip() , ll[1].strip())\n return result",
"def parseSolverOutput(self, output):\n\n exp = re.search(r'^v .*$... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse headers and entries in line, create dictionary and append it to RESULT list. | def _parse_header(self, line):
if self._regex_helper.search_compiled(W._re_header, line):
if not self.headers:
for value in re.findall(W._re_header, line):
self.headers.append(value[0])
raise ParsingDone
else:
# Dictiona... | [
"def process_line(self, line):\n find_result = re.findall(LINE_REGEX, line)\n line_data = {r[0]: r[1] for r in find_result}\n self.process_url(line_data.get('request_to'))\n self.process_status_code(line_data.get('response_status'))",
"def create_dict_from_line(header, line):\r\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We need to find the halfedge h that is incident to u and is on the face that contains the diagonal uv. To find it, we test every pair of halfedges incident to u and v until we find a pair belonging to the same face. | def referenceEdge(u,v):
v1 = u
v2 = v
e1 = u.getEdge().getPrev()
e2 = v.getEdge().getPrev()
aux = None #aux is an half-edge incident to u
while aux != e1:
if aux is None: aux = e1
aux2 = None #aux2 is an half-edge incident to v
while aux2 != e2:
if aux2... | [
"def get_halfedge(self, u, v):\r\n return self.edges[(u, v)]",
"def vertex_descendant(self, u, v):\n fkey = self.halfedge[u][v]\n if fkey is not None:\n # the face is on the inside\n return self.face[fkey][v]\n # the face is on the outside\n for nbr in self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FNV1 64bit hash function Implement this, and/or DJB2. | def fnv1(self, key):
# hash = 0xff
hash = 0xcbf29ce484222325
for n in key.encode():
# print(n)
hash = hash ^ n
hash = hash * 0x100000001b3
# print(hash)
return hash | [
"def fnv1(self, key, seed=0):\n # def fnv1(self, key):\n\n # Your code here\n \"\"\"\n Returns: The FNV-1 hash (64-bit) of a given string. \n \"\"\"\n #Constants : Fails the tests\n # FNV_prime = 1099511628211\n # offset_basis = 14695981039346656037\n\n # #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this. | def put(self, key, value):
hi = self.hash_index(key)
if self.storage[hi]:
current = self.storage[hi]
while current.next and current.key != key:
current = current.next
if current.key == key:
current.value = value
else:
... | [
"def put(self, key, value):\n #increment size of hash table\n self.size += 1\n \n #compute index using hash function\n hash_index = self.hash_index(key)\n\n #if bucket at index is empty, create new node and insert\n node = self.storage[hash_index]\n if node is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a program that takes as input a BST and an interger k, and returns the k largest elements in the BST in decreasing order. | def find_k_largest_in_bst_recursively(tree, k):
def find_k_largest_in_bst_helper(tree):
if tree and len(k_largest_elements) < k: # Smart: Recursion iff we don't have K largest elements collected
find_k_largest_in_bst_helper(tree.right)
if len(k_largest_elements) < k:
... | [
"def findKthLargest(self, nums, k):\n nums.sort(reverse=True)\n return nums[k - 1]",
"def findKthLargest(nums, k):\n return sorted(nums)[-k]",
"def findKthLargest(self, nums: List[int], k: int) -> int:\n return sorted(nums)[-k]",
"def _get_k_largest(lst, k):\n sorted_lst = sorted([(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate upper percentile MCP cutoff for avoiding Andor saturation Andor begins saturating at ~5000 for 'signal' value. Set percentile cutoff of incident fluence (mcp) to the percentile where Andor reaches 4000, well before saturation. If that is greater than the 99.9th percentile, set percentile cutoff to 99.9 to eli... | def _calculate_percentile_cutoff(run_numbers):
mcp_values = []
andor_values = []
for run_number in run_numbers:
current_data_path = ''.join([DATA_PATH, 'run', str(run_number), 'allevts.h5'])
f = h5py.File(current_data_path, 'r')
current_phot = _get_photon_energy(f, run_number)
... | [
"def cut_spectrum(input_spectrum, desired_frequency_range):\n channels_ip = []\n for ip in input_spectrum.GetChannels():\n channel_ip = []\n channel_op = []\n for n, i in enumerate(ip):\n if n > desired_frequency_range[0] / input_spectrum.GetResolution() and n < desired_frequen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of actions related to plugin | def get_plugin_actions(self):
return [] | [
"def getActions():\n return getPlugins(IRenamingAction, plugins)",
"def get_actions(self):\n return []",
"def actions(self):\n return self._action_list",
"def list_actions():\n\n return ActionList(integrations=actions_list)",
"def actions_list(self) -> list:\n return self.__action... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register plugin in Spyder's main window | def register_plugin(self):
self.edit_goto.connect(self.main.editor.load)
self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
self.main.add_dockwidget(self)
unittesting_act = create_action(self, _("Run unit tests"),
icon=get_icon('p... | [
"def register_plugin(self):\r\n self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)\r\n self.main.console.shell.refresh.connect(self.refresh_plugin)\r\n iconsize = 24 \r\n self.toolbar.setIconSize(QSize(iconsize, iconsize))\r\n self.main.addToolBar(self.toolbar)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply configuration file's plugin settings | def apply_plugin_settings(self, options):
pass | [
"def apply_plugin_settings(self, options):\r\n pass",
"def plugin_reconfigure():\n\n pass",
"def use_config_file(self):\n self.config_file = self.find_config_file()\n if self.config_file:\n self.apply_config_file(self.config_file)",
"def configure(plugins):\n global __plu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Used to allow a user to edit their own profile. | def edit_profile(request):
user = request.user
profile = Profile.objects.for_user(user)
if request.method != 'POST':
profile_form = ProfileForm(instance=profile)
user_form = UserForm(instance=user)
else:
profile_form = ProfileForm(request.POST, instance=profile)
... | [
"async def edit(self, *args, **kwargs):\n return await self._bot.edit_profile(*args, **kwargs)",
"def edit_profile(request):\n log.debug(\"Edit profile\")\n if request.method == \"POST\":\n form = ProfileEditForm(request.POST, instance=request.user)\n if form.is_valid():\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
输入一个链表,输出该链表中倒数第k个结点。链表的尾节点是倒数第一个节点,比如 [1, 2, 3, 4, 5, 6] 6 个节点,倒数第三个节点是值为 4 的节点。 算法: 题目没有对 k 的大小做出限制,那么这里定义,如果 k 大于链表的长度,那么返回 None。 节点为 None,也返回 None。 双指针,第二个指针比第一个指针后 k 个节点。这样当第二个指针到达 None 时,第一个指针就指向倒数 第 k 个节点。如果第二个指针还没有比第一个后 k 就到了 None,那么说明 k 大于链表的长度,根据上方的定义返回 None。 复杂度分析: 时间复杂度:遍历一次 O(n) 空间复杂度:O(1) | def FindKthToTail(self, head, k):
if not head:
return None
first_index = head
second_index = head
# 第二个指针移动 k 次
for i in range(k):
second_index = second_index.next
# 第二个指针还没有比第一个后 k 就到了 None,那么说明 k 大于链表的长度,返回 None
if second_index ... | [
"def kth_to_last(head, k):\n # Runs in O(N). Runs through list once to count,\n # again to get Kth to last.\n node_count = 0\n for node in head.node_chain():\n node_count += 1\n if k > node_count:\n return None\n countdown = node_count - k\n current_node = head\n while countdow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return three Keras HDF5Matrix instances for the input, groundtruth density map and groundtruth segmentation mask in a compact TrainingSet | def get_matrices(training_set_path):
if os.path.isfile(training_set_path):
X = HDF5Matrix(training_set_path, 'input/input')
y = HDF5Matrix(training_set_path, 'target/target')
y_seg = HDF5Matrix(training_set_path, 'seg_map/seg_map')
return X, y, y_seg
else:
raise Exception... | [
"def get_stacking(config,x_train_picture,x_train_sentence,y_train,x_test_picture,x_test_sentence):\n train_num, test_num,= x_train_picture.shape[0], x_test_picture.shape[0],\n second_level_train_set = np.zeros((train_num, 1))\n test_result = np.zeros((test_num, 3))\n test_nfolds_sets = []\n # for k i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate outputs from a noncompact TrainingSet to use with Keras' 'fit_generator' function. If 'n_crops' is nonzero, the Iterator crops n_crops 20x20 regions from each image before feeding them. | def flow(self, batch_size=32, output='both', crops=0):
while True:
for dataset in self.input_sets:
X = self.training_set['input/'+dataset]
y = self.training_set['target/'+dataset]
y_seg = self.training_set['seg_map/'+dataset]
for i in ... | [
"def crop_generator(batches, crop_length):\n while True:\n batch_x, batch_y = next(batches)\n batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, 3))\n for i in range(batch_x.shape[0]):\n batch_crops[i] = random_crop(batch_x[i], (crop_length, crop_length))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate upstream cherrypick patch files | def generate_patch_files(sha_list: List[str], start_version: int) -> PatchList:
upstream_dir = paths.TOOLCHAIN_LLVM_PATH
fetch_upstream_once()
result = PatchList()
for sha in sha_list:
if len(sha) < 40:
sha = get_full_sha(upstream_dir, sha)
file_path = paths.SCRIPTS_DIR / 'pa... | [
"def do_genpatch(self, argv):\n #TODO:\n # - Would an optional [<files> ...] argument be useful or is\n # that overkill? E.g. 'p4 genpatch ./...' (I think that that\n # would be very useful.\n # - Could add '-f' option to only warn on 'out of sync'.\n # - Coul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print every package as "ignored". | def _print_ignored(packages):
if not packages:
print("## No Rez package was set to be ignored")
print("No data found")
return
print("## Every package in this list was explicitly set to ignored by the user")
for package, pattern in sorted(packages, key=_get_package_name):
p... | [
"def _print_missing(packages, verbose):\n if not packages:\n print(\"## No Rez packages were found.\")\n print(\"No data found\")\n\n return\n\n print(\"## Your command affects these Rez packages.\")\n\n template = \"{package.name}\"\n\n if verbose:\n template = \"{package.na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print all Rez packages that should be run on. | def _print_missing(packages, verbose):
if not packages:
print("## No Rez packages were found.")
print("No data found")
return
print("## Your command affects these Rez packages.")
template = "{package.name}"
if verbose:
template = "{package.name}: {path}"
for line... | [
"def _print_modules():\n packages = ['auditors', 'actives', 'blinds', 'passives']\n\n # print names and descriptions\n for package in packages:\n print(package + ':')\n for name, description in utility.get_package_info(package):\n print(\" {:21s} {}\".format(name, description))\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the Rez packages that were skipped automatically by this tool. Skipped packages differ from "invalid" packages in that they are "valid Rez packages but just don't need the command run on". Ignored packages are Rez packages that the user explicitly said to not process. Skipped packages are packages that the user m... | def _print_skips(skips, verbose):
if not skips:
print("## No packages were skipped")
print("Every found Rez package can be processed by the command.")
return
print("## Packages were skipped from running a command. Here's the full list:")
template = "{issue.package.name}: {issue.re... | [
"def _print_ignored(packages):\n if not packages:\n print(\"## No Rez package was set to be ignored\")\n print(\"No data found\")\n\n return\n\n print(\"## Every package in this list was explicitly set to ignored by the user\")\n\n for package, pattern in sorted(packages, key=_get_pack... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check which help message the user actually wants to print out to the shell. The concept behind this function is a bit weird. Imagine you have 3 calls to ``rez_batch_process`` python m rez_batch_process help python m rez_batch_process run help python m rez_batch_process run shell help The first should print the choices ... | def _process_help(text):
text = copy.copy(text)
found_index = -1
found_text = ""
if "--help" in text:
found_index = text.index("--help")
found_text = "--help"
elif "-h" in text:
found_index = text.index("--h")
found_text = "-h"
if not found_text:
return... | [
"def test_generate_help_text(self):\n self.shell.completer = None\n description, example = self.shell.generate_help_text('')\n self.assertEqual(description, '')\n self.assertEqual(example, '')\n\n self.shell.completer = TestCompleter()\n description, example = self.shell.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does any sequence in sequences have a reflection? A reflection is a fourcharacter sequence that is the same backward as forward and consists of two different characters. | def has_reflection(sequences):
for sequence in sequences:
for i in range(len(sequence) - 3):
subseq = sequence[i:i + 4]
if (len(Counter(subseq)) == 2) and (subseq == subseq[-1::-1]):
return True
return False | [
"def is_reflective(self):\n return self._reflective",
"def _is_sequence(obj):\n return hasattr(obj, \"__iter__\") and not isinstance(obj, str)",
"def _is_sequence(obj):\n return hasattr(obj, '__iter__') and not isinstance(obj, str)",
"def is_sequence(x):\n return (not hasattr(x, 'strip') and\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether address is compatible with protocol. | def is_compatible(address, protocol=1):
bracketed = [word.strip('[]') for word
in re.findall('\[[^\]]*\]', address)]
not_bracketed = re.split('\[[^\]]*?\]', address)
if protocol == 1:
if has_reflection(bracketed):
return False
return has_reflection(not_bracketed)... | [
"def supported_address(cls, address: str) -> bool:\n if '://' not in address:\n return False\n addr_type = address.split(':')[0]\n if addr_type not in ('gsiftp', 'ftp'):\n return False\n return True",
"def can_support_address(self, addr: int) -> bool:\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a list of addresses from a file. | def load_addresses():
with open('addresses.txt') as f:
return [address.strip() for address in f.readlines()] | [
"def read_in_address_file(file):\n address_list = list()\n lines = 0\n valid_ips = 0\n with file as f:\n for n in file:\n lines += 1\n if validate_ip(n.strip()):\n address_list.append(n.strip())\n valid_ips += 1\n if valid_ips < lines:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method fetches the GPS coordinates for a particular address using the TomTom API | def geo(address):
API_PRIVATE = os.environ.get("TOM_TOM_PRIVATE")
encoded = urllib.parse.quote(address)
query ='https://api.tomtom.com/search/2/geocode/' + str(encoded) + \
'.json?limit=1&countrySet=US&lat=42&lon=-72&topLeft=42.886%2C%20-73.508&btmRight=41.237%2C-69.928&key=' \
+ API_P... | [
"def get_coordinates(self, address):\n loc = self.locate(address)\n if loc == None:\n if self.fallback != None:\n loc = self.fallback.locate(address)\n if loc == None:\n raise NotFoundException(address)\n return (loc.latitude, loc.longitude)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search through a course query set for the given query text. | def search_courses(courses, query):
return courses.annotate(
course_id=Concat('subject', Value(' '), 'course_number', Value(' '),
'section', output_field=CharField()),
).annotate(rank=Case(
When(
course_id__istartswith=query,
then=1
),
... | [
"def search_courses(self,terms):\n\n return self.course_search.search_for(terms)",
"def find_matching_course_indexes(self, query):\r\n return self.course_index.find(query)",
"def search_for_query(self, query):\n self.searcher.search_query = query\n results = self.searcher.search_for_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter a course query set based on known filtering parameters. | def filter_courses(courses, params):
if 'notFull' in params and params['notFull'] == 'true':
courses = courses.filter(
Q(enrollment__lt=F('max_enrollment')) | Q(max_enrollment=0)
)
if 'distributions' in params:
ds = int(params['distributions'])
valid = []
if ... | [
"def filter_queryset(self, queryset):\n # TODO: Handle relations and non-existent fields.\n for query_filter, query_value in self.filter_params.items():\n query_filter, query_value = self._process_param(query_filter,\n query_value)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get path to freshclam | def get_freshclam_path(module):
try:
freshclam_binary = module.get_bin_path('freshclam')
if freshclam_binary.endswith('freshclam'):
return freshclam_binary
except AttributeError:
module.fail_json(msg='Error: Could not find path to freshclam binary. Make sure freshclam is inst... | [
"def cf_fpath():\n datadir = os.path.join(os.path.dirname(__file__), 'data/')\n\n cf_fpath = os.path.join(\n datadir, 'reV_gen/naris_rev_wtk_gen_colorado_2007.h5')\n\n return cf_fpath",
"def flatpath(cam):\n return os.path.join(BASEPATH, cam + \"_flats\")",
"def get_GM_ca_path():\n\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run freshclam to update ClamAV signatures | def update_freshclam(module, freshclam_binary):
rc_code, out, err = module.run_command("%s" % (freshclam_binary))
return rc_code, out, err | [
"def sign_update(self):\n # Loads private key\n # Loads version file to memory\n # Signs Version file\n # Writes version file back to disk\n self._add_sig()",
"async def addToFingerPrint(samples, sampleset=, allsampleset=\"all\", workspace=WORKSPACE, sid=, vcf_list=None, \nvcf_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits a heightmap into a source and target. For placement, we just need the source heightmap. | def _split_heightmap(self, height):
half = height.shape[1] // 2
self._half = half
height_s = height[:, half:].copy()
return height_s | [
"def split_contest_to_targets(self, ballot_image, contest, targets):\n\n target_x_pos = [x[0] for x in targets]\n target_x_range = max(target_x_pos)-min(target_x_pos)\n target_y_pos = [x[1] for x in targets]\n target_y_range = max(target_y_pos)-min(target_y_pos)\n l,u,r,d = contes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly samples negative pixel indices. | def _sample_negative(self, positives):
max_val = self._H * self._W
num_pos = len(positives)
num_neg = int(num_pos * self._sample_ratio)
positives = np.round(positives).astype("int")
positives = positives[:, :2]
positives = np.ravel_multi_index((positives[:, 0], positives[... | [
"def _sample_free_negative(self, kit_mask):\n max_val = self._H * self._W\n num_neg = int(100 * self._sample_ratio)\n negative_indices = []\n while len(negative_indices) < num_neg:\n negative_indices.append(np.random.randint(0, max_val))\n negative_indices = np.vstack(n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly samples negative pixel indices. | def _sample_free_negative(self, kit_mask):
max_val = self._H * self._W
num_neg = int(100 * self._sample_ratio)
negative_indices = []
while len(negative_indices) < num_neg:
negative_indices.append(np.random.randint(0, max_val))
negative_indices = np.vstack(np.unravel_i... | [
"def _sample_negative(self, positives):\n max_val = self._H * self._W\n num_pos = len(positives)\n num_neg = int(num_pos * self._sample_ratio)\n positives = np.round(positives).astype(\"int\")\n positives = positives[:, :2]\n positives = np.ravel_multi_index((positives[:, 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns Enclosure Manager configuration information from specified enclosure name. | def get_enclosure_configuration(enclosure_name):
for name in enclosure_configurations:
if enclosure_name == name:
return enclosure_configurations[name]
return None | [
"def config_enclosure() -> dict:\n with open(get_test_file_path('pygeoapi-test-config-enclosure.yml')) as fh:\n return yaml_load(fh)",
"def get_config_descr(self, name):\n return self.configs[name][1]",
"def appliance_config(self, name):\n return self._appliances_config.get(name, {})",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in tokens, marks them by POS, finds NEs, returns consolidated list of NEs | def chunk(tokens):
# Uses NLTK function to pair each token with its Part Of Speech
entity_list = []
pos = nltk.pos_tag(tokens)
named_entities_chunk = nltk.ne_chunk(pos, binary=True)
# Finds named entities in tokens, stores in list of strings
for i in range(0, len(named_entities_chunk)):
... | [
"def extract_entities(tokens_ne_pos):\n persons = extract_entities_from_tagged([(w, t) for w, t, _ in tokens_ne_pos], ['PERSON'])\n locations = extract_entities_from_tagged([(w, t) for w, t, _ in tokens_ne_pos], ['LOCATION'])\n orgs = extract_entities_from_tagged([(w, t) for w, t, _ in tokens_ne_pos], ['OR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in a document, returns the named entities in that document | def add_entities(doc):
# Calls function to tokenize the document, stores as list of strings
tokens = tokenize(doc)
# Calls function to find named entities in the tokens, stores as list of strings
chunks = chunk(tokens)
return chunks | [
"def get_named_entities(data_dict):\n text = data_dict['evidences'][0]['snippet']\n doc = nlp(text)\n return list(doc.ents)",
"def get_named_people_from_sen(sen):\n wordlist = sen['words']\n entities = []\n\n named = []\n for index, word in enumerate(wordlist):\n if word[1]['NamedEntit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function 'match' when given a list of words, finds all indices pairs such that the concatenation of the two words is a palindrome. | def match(list_string):
assert type(list_string)==list
for i in list_string:
assert type(i)==str
assert i.isalpha()
#Loops through all the possible substrings of the list of words to find the word pairs that are palindromes.
my_match = []
for i in range(0,len(list_string)):
f... | [
"def find_pairs(words): \n pass",
"def palindromePairs(lst):\n results = []\n for i, e1 in enumerate(lst):\n for j, e2 in enumerate(lst):\n if i != j:\n if isPalindrome(e1+e2):\n results.append((i, j))\n return results",
"def palindrom():\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string comprising of opening parentheses, closing parentheses and asterix() where could represent an opening parentheses, closing parentheses or an empty string, the function 'isBalanced()' takes in the string and determines if the string is balanced or not. It returns True if it is Balanced and False otherwise... | def isBalanced(string):
assert type(string)==str
if any(a not in '(*)' for a in string):
raise AssertionError
string = list(string) #Converts the inputted list to a string.
#Loops through the list, checks for opening and closing parentheses and removes them from the list.
k = 0
while T... | [
"def has_balanced_parentheses(string: str) -> bool:\n if len(string) == 0:\n return True\n\n stack: Final = Stack()\n open_map: Final = {\n '{': '}',\n '[': ']',\n '(': ')',\n }\n\n close_map: Final = {\n '}': True,\n ']': True,\n ')': True,\n }\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add. Add a new flavor | def add(self, flavor):
# check if the flavor already exist.
# Note: If it does, no LookupError will be raised
try:
self.get(flavor.flavor_id)
except LookupError:
pass
else:
raise ValueError("A flavor with the id '%s' already exists"
... | [
"def add_flavor(self, flavor):\n self.flavor = self.flavors.append(flavor)",
"def flavor_access_add(self, context, flavor_uuid, project_id):",
"def _add_or_modify_flavours(self, flavor, flavor_id, ralph_flavors):\n if flavor_id not in ralph_flavors:\n new_flavor = CloudFlavor(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Differentiate between classes and ids in the way jQuery does (id, .class) | def class_or_id(selector):
if selector[0] == '.':
soup_selector = 'class'
elif selector[0] == '#':
soup_selector = 'id'
else:
soup_selector = ''
return [soup_selector, selector[1:]] | [
"def _hnd_class_id(self, tag, attrs) -> str:\n\n data = ''\n classes = [o[1] for o in attrs if o[0] == 'class']\n id = [o[1] for o in attrs if o[0] == 'id']\n\n if id:\n data += f'#{id[0]}'\n\n for class_group in classes:\n for clazz in class_group.split(' ')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a boolean to a color value. Used in a binding. | def _bool_to_color(value) -> int:
if value is True:
return RED
return BLACK | [
"def colorize_boolean(boolean):\n color = {\n 'html': {\n True: '<font color=\"#33cc33\">%s</font>' % boolean,\n False: '<font color=\"#cc3300\">%s</font>' % boolean\n },\n 'console': {\n True: GREEN + str(boolean) + ENDC,\n False: RED + str(boolea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple integration test for example. | def test_example_runs(self):
run_example(
verbose=False,
testapp=self.testapp,
) | [
"def test_Demo(self):\n self._run(self._example_scenarios, \"Demo\")",
"def test_main(self):\n pass",
"def test_demo_runs(self):\n self.star.run_demo()",
"def example():\n\n # Create exam\n exam = Exam(\"Hard Exam\")\n\n # Add questions to exam\n exam.add_question(\"What is 15... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dummy function to redraw figures in the children classes | def redraw_figures(self):
pass | [
"def redraw(self, **kwargs):\n #src_dict = self.data_sources\n #self.remove_sources(src_dict.keys())\n self.renderers = {}\n #self.renderers = {}\n self.figure = self.draw_figure(**kwargs)\n #self.add_sources(src_dict)\n # todo does the old figure linger on?\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scroll canvas horizontally and redraw the image | def __scroll_x(self, *args, **kwargs):
self.canvas.xview(*args) # scroll horizontally
self.__show_image() # redraw the image | [
"def __scroll_x(self, *args, **kwargs):\n self.canvas_image.xview(*args) # scroll horizontally\n self.__show_image() # redraw the image",
"def scroll(self, dx, dy):\n cam_next = self.camera_rect\n cam_next[0] += dx\n cam_next[1] += dy",
"def scrollDown(self):\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scroll canvas vertically and redraw the image | def __scroll_y(self, *args, **kwargs):
self.canvas.yview(*args) # scroll vertically
self.__show_image() # redraw the image | [
"def __scroll_y(self, *args, **kwargs):\n self.canvas_image.yview(*args) # scroll vertically\n self.__show_image() # redraw the image",
"def scrollDown(self):\r\n\r\n if self.z_stack<self.img.shape[0]-1:\r\n self.z_stack+=1\r\n \r\n #self.pixmap=QtGui.QPixma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |