query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Reindex to include missing timestamps and create new column for actual rain from cumulative rain | def preprocessing(df):
logger.debug("Fill in missing timestamps by reindexing")
min_time = min(df.index)
max_time = max(df.index)
rng = pd.date_range(min_time, max_time, freq='15Min')
df = df.reindex(rng)
logger.debug("Convert cumulative rain to actual rain")
df['rain'] = df['cum_rai... | [
"def fill_gaps(df):\n idx = pd.period_range(df.index.min(), df.index.max(), freq=\"D\")\n # idx_forecast = pd.period_range(start_datetime, end_datetime, freq=\"H\")\n ts = pd.DataFrame({\"empty\": [0 for i in range(idx.shape[0])]}, index=idx)\n ts = ts.to_timestamp()\n df_filled = pd.concat([df, ts],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload json file to webpage via ftp and then force fb to update cache | def upload_export(testing, output):
filename = "dart.json"
with open(os.path.join(FDIR, '../' + filename), 'w') as f:
json.dump(output, f, indent=4)
from local_info import ftp_url, ftp_pass, ftp_user, ftp_dir
ftp = ftplib.FTP(ftp_url)
ftp.login(ftp_user, ftp_pass)
if ftp_dir is not None... | [
"def make_cached_file(url, fname):\n response = fetch_url(url)\n lfile = open(fname, \"w\")\n lfile.write(json.dumps(response, indent=2))\n lfile.close()",
"def upload(self, filename, contents):\n if not self.__enabled:\n return\n\n self.__cache[filename] = {}\n self.__cache[fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine what kls this group inherits from If default kls should be used, then None is returned | def super_kls(self):
if not self.kls and self.parent and self.parent.name:
return self.parent.kls_name
return self.kls | [
"def default_windows_group(self):\n return self._default_windows_group",
"def available_groups(cls):\n raise NotImplementedError",
"def get_group(self): # real signature unknown; restored from __doc__\n return \"\"",
"def inherit_cert_keychain(self) -> Optional[pulumi.Input[str]]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate color depth of image pixel. | def __calc_color_depth(self):
self.color_depth = 2**(8 * self.data.dtype.itemsize) | [
"def _get_bit_depth(color_count):\n for i in [1, 2, 4, 8]:\n if color_count <= 2**i:\n return i",
"def screen_color_depth(self):\n return self._screen_color_depth",
"def getBitDepth(im=None, numpy=False):\n import error\n if im==None: im=getImage()\n bd=im.getBitDepth() \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply LUT to the image. | def __apply_lut(self, lut):
if self.is_grayscale():
for w in range(self.data.shape[0]):
for h in range(self.data.shape[1]):
self.data[w][h] = lut[self.data[w][h]]
else:
for w in range(self.data.shape[0]):
for h in range(self.da... | [
"def apply_lut(band, lut):\n\n # if lut.dtype != band.dtype:\n # msg = \"Band ({}) and lut ({}) must be the same data type.\".format(band.dtype, lut.dtype)\n # raise LUTException(msg)\n\n return np.take(lut, band, mode='clip')",
"def _perturb_image(self, x: np.ndarray, img: np.ndarray) -> np.n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change image data type. | def change_type(self, img_type):
self.change_color_depth_2_uint8()
self.data = cvtColor(self.data, COLOR_CONVERSION_CODES[img_type]) | [
"def setType(self, imageType):\t\t\t \n\t\tself.imageType = imageType",
"def change_img_type(\n filepath,\n img_type):\n dirpath = os.path.dirname(filepath)\n info = parse_filename(os.path.basename(filepath))\n info['type'] = img_type\n filepath = to_filename(info, dirpath)\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a histogram plot window of the image. | def create_hist_window(self):
self.histogram_graphical.create_histogram_plot(self.calc_histogram()) | [
"def plot_histogram(img):\n hist = cv2.calcHist([img],[0],None,[256],[0,256])\n\n plt.hist(hist,facecolor='green')\n plt.title('Histogram'), plt.xlabel(\"Scale\"), plt.ylabel(\"Quantity\")\n plt.grid(True)\n\n plt.show()",
"def _draw_histogram(self):\n self.range = npy.arange(0, 100)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open rename dialog window to change the image name. | def rename(self):
dialog_rename = Rename(self.name)
if dialog_rename.exec():
self.__update_image_name(dialog_rename.new_name) | [
"def renameUI():\n pass",
"def change_image_name(self, img, newname):\r\n return self.update(img, {\"name\": newname})",
"def set_name(self, new_name):\n\n self.img.attrib['Name'] = new_name",
"def click_rename_icon(self, file_name):\n return self",
"def Rename(self, event):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute image dialog for object features. | def run_features_dialod(self):
dialog_features = ObjectFeatures(self)
if dialog_features.exec():
return | [
"def image_chooser(self):\n self.__image = pg.image.load(\"res/ghost/\" + Ghost.image_names[self.__id] + \"/start.png\")",
"def photoProcessed(self):\n # set up initial window features\n self.photoProcessedScreen.setWindowTitle(\"Unique Facial Feature Detection\")\n self.photoProcessed... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute specified operation dialog. | def run_operation_dialog(self, operation):
operation_dialog = self.DIALOG_OPERATIONS[operation](self)
if operation_dialog.exec():
self.data = operation_dialog.img_data | [
"def littleDialog():\r\n psm = uno.getComponentContext().ServiceManager\r\n dp = psm.createInstance(\"com.sun.star.awt.DialogProvider\")\r\n dlg = dp.createDialog(\"vnd.sun.star.script:Standard.Dialog1?location=application\")\r\n dlg.execute()\r\n return None",
"def dialog_handler(self, command, value=None):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open panorama dialog window to perform image stitching. | def run_panorama_dialog(images):
images = {img.name: img.data for img in images}
panorama = ImagePanorama(images.copy())
if panorama.exec():
return panorama.pano_data, panorama.pano_name | [
"def main_show():\n variant = sys.argv[2]\n if variant == 'original':\n obj = view.Original()\n cmap=None\n elif variant == 'aligned':\n obj = view.Aligned()\n cmap=glumpy.colormap.Grey\n elif variant == 'funneled':\n obj = view.Funneled()\n cmap=None\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate the given point. Make sure point coordinates aren't beyond the corners of the image. | def __validate_point(self, point):
if point.x() < 0:
point.setX(0)
if point.y() < 0:
point.setY(0)
img_width = self._data.shape[1] - 1
if point.x() > img_width:
point.setX(img_width)
img_height = self._data.shape[0] - 1
if point.y()... | [
"def is_valid_point(map_grid, point):\n x = point[0]\n y = point[1]\n width = map_grid.info.width\n height = map_grid.info.height\n return 0 <= x < width and 0 <= y < height",
"def sanity_check_point(cls, gridmap: np.array, point: Tuple[int, int]) -> None:\n rows, cols = gridmap.shape\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the image is grayscale. ``True`` if the image has one channel, otherwise ``False``. | def _is_grayscale(self):
return len(self._data.shape) == 2 | [
"def is_img_gray(image):\n is_gray = True\n for i in range(image.size[0]):\n c = image.getpixel((i,image.size[1] / 2))\n c = np.asarray(c)\n mean = np.mean(c)\n tmp = True\n for b in c: tmp = tmp and (b == mean)\n if not tmp:\n is_gray = False\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set an image data and update the image window | def set_img_data(self, img_data):
self._data = img_data
self.update_window()
self.update_icon() | [
"def update_image(window: tk.Tk, img: Image):\r\n\r\n window.display_image(img)",
"def set_img(arr):\n global tkImg, canvasImg, canvas\n tkImg = tk_img(arr)\n canvasImg = tk_imshow(canvas, tkImg)",
"def updateImage(self):\n self.image = self.getImage(self.location, self.name, self.imageType)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the image window scale depending on the mode. | def zoom(self, mode):
if mode == "out":
self.scale -= 0.1
elif mode == "in":
self.scale += 0.1
else:
self.scale = 1
self.scale = round(self.scale, 1)
self.update_window() | [
"def windowEvent(self, *args, **kwargs):\n super().windowEvent(*args, **kwargs)\n\n for win, cam, pixel2d in self.forcedAspectWins:\n aspectRatio = self.getAspectRatio(win)\n cam.node().getLens().setAspectRatio(aspectRatio)\n\n # Fix pixel2d scale for new window size\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update icon for image window. Grayscale image has grayscale picture, color image has color one. | def update_icon(self):
icon = QIcon()
if self._is_grayscale():
icon.addPixmap(QPixmap("icons/picture_gray.png"), QIcon.Normal, QIcon.Off)
else:
icon.addPixmap(QPixmap("icons/picture_color.png"), QIcon.Normal, QIcon.Off)
self.setWindowIcon(icon) | [
"def update_icon(active, window):\n\tif active:\n\t\twindow.tk.call('wm', 'iconphoto', window._w, green_icon)\n\telse:\n\t\twindow.tk.call('wm', 'iconphoto', window._w, red_icon)",
"def update_icon(self):\n fn = self.icon_filename[self.state]\n path = os.path.join(self.location, fn)\n assert ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create intensity profile window. | def create_profile(self):
self.intensity_profile.create_profile(self.points, self._data) | [
"def create_picture_gui(self):\n self.screen.fill((255, 255, 255)) # asd\n self.display_author()\n self.display_title()\n # Getting width, height and steps from input boxes.\n w, h, s, _ = self.display_creating_picture_boxes()\n # Checking data validate\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert OGM property names/values to DB property names/values | def map_props_to_db(element, mapping):
property_tuples = []
props = mapping.ogm_properties
for ogm_name, (db_name, data_type) in props.items():
val = getattr(element, ogm_name, None)
if val and isinstance(val, (list, set)):
card = None
for v in val:
me... | [
"def translate_db_fields(cls, data):\n dst_data = data.copy()\n for name, col in cls._columns.items():\n key = col.db_field or name\n if key in dst_data:\n dst_data[name] = dst_data.pop(key)\n\n return dst_data",
"def test_to_dict_hybrid_property(self):\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map a vertex returned by DB to OGM vertex | def map_vertex_to_ogm(result, props, element, *, mapping=None):
props.pop('id')
label = props.pop('label')
for db_name, value in props.items():
metaprops = []
if len(value) > 1:
values = []
for v in value:
if isinstance(v, dict):
va... | [
"def get_vertex(self, id_num):",
"def graph_vertex( g, i, add_if_necessary = False ):\n if add_if_necessary and i not in g.id_to_vertex:\n v = g.add_vertex()\n g.id_to_vertex[ i ] = v\n g.vertex_properties[ 'vertex_id' ][ v ] = i\n return g.id_to_vertex[ i ]",
"def get_or_create_verte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map an edge returned by DB to OGM edge | def map_edge_to_ogm(result, props, element, *, mapping=None):
props.pop('id')
label = props.pop('label')
for db_name, value in props.items():
name, data_type = mapping.db_properties.get(db_name, (db_name, None))
if data_type:
value = data_type.to_ogm(value)
setattr(elemen... | [
"def edge_to_dict(graph, edge):\n e_id = edge.id.get('@value').get('relationId')\n properties = graph.E(e_id).valueMap().toList()[0]\n return {\n 'id': e_id,\n 'label': edge.label,\n 'properties': properties\n }",
"def remapped_edge(self, remap, v0, v1):\n self_v0 = remap[v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a user's favourite number and store it in a json file. | def get_fav_number():
number = int(input("What is your favourite number? "))
filename = 'c10_11_number.json'
with open(filename, 'w') as f:
json.dump(number, f)
return number | [
"def get_stored_number():\n filename = 'fav_num.json'\n try:\n with open(filename) as f_obj:\n fav_num = json.load(f_obj)\n except FileNotFoundError:\n return None\n else:\n return fav_num",
"def print_fav_number():\n filename = 'c10_11_number.json'\n with open(fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a user's favourite number and print it. | def print_fav_number():
filename = 'c10_11_number.json'
with open(filename, 'r') as f:
number_loaded = json.load(f)
print(f"I know your favourite number! It's {number_loaded}") | [
"def favorite_number():\r\n\tfavorite_number = load_favorite_number()\r\n\tif favorite_number:\r\n\t\tprint(f\"I know your favorite number, it is {favorite_number}!\")\r\n\telse:\r\n\t\tfavorite_number = get_favorite_number()\r\n\t\tprint(f\"I'll remember your favorite number of {favorite_number} when you come back... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns how many numbers lie within `maximum` and `minimum` in a given `row` | def howmany_within_range2(i, row, minimum, maximum):
count = 0
for n in row:
if minimum <= n <= maximum:
count = count + 1
return (i, count) | [
"def max_connected_cells(matrix):\n max_region = 0\n for row in range(len(matrix)):\n for col in range(len(matrix[0])):\n if matrix[row][col]:\n count = count_cells_in_region(matrix, row, col)\n if count > max_region:\n max_region = count\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the memory mappings of the currentlyrunning process using PANDA's operating system introspection. | def get_mappings(self):
l.debug("getting the vmmap of the concrete process")
mapping_output = self.panda.get_mappings(self.panda.get_cpu())
vmmap = []
for mapping in mapping_output:
if mapping.file == self.panda.ffi.NULL:
continue # Unknown name
f... | [
"def memory_maps(pid: int) -> Iterable[MemoryMapRegion]:\n\n maps = []\n\n # if we can't access the process' memory, this will\n # raise a PermissionError\n with open('/proc/{}/maps'.format(pid), 'rb') as f:\n for line in f:\n range, perms, *_ = line.split()\n start, end = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that tokenize_by_sentence function can handle ideal two sentence input | def test_tokenize_by_sentence_ideal(self):
text = 'She is happy. He is happy.'
expected = (
(('_', 's', 'h', 'e', '_'), ('_', 'i', 's', '_'), ('_', 'h', 'a', 'p', 'p', 'y', '_')),
(('_', 'h', 'e', '_'), ('_', 'i', 's', '_'), ('_', 'h', 'a', 'p', 'p', 'y', '_'))
)
... | [
"def test_tokenize_by_sentence_complex(self):\n text = 'Mar#y wa$nted, to swim. However, she was afraid of sharks.'\n expected = (\n (('_', 'm', 'a', 'r', 'y', '_'), ('_', 'w', 'a', 'n', 't', 'e', 'd', '_'),\n ('_', 't', 'o', '_'), ('_', 's', 'w', 'i', 'm', '_')),\n (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that tokenize_by_sentence function can process and ignore different punctuation marks | def test_tokenize_by_sentence_punctuation_marks(self):
text = 'The, first sentence - nice. The second sentence: bad!'
expected = (
(('_', 't', 'h', 'e', '_'), ('_', 'f', 'i', 'r', 's', 't', '_'),
('_', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '_'), ('_', 'n', 'i', 'c', 'e', '_'))... | [
"def test_tokenize_by_sentence_inappropriate_sentence(self):\n text = '$#&*@#$*#@)'\n\n expected = ()\n actual = tokenize_by_sentence(text)\n self.assertEqual(expected, actual)",
"def test_tokenize_by_sentence_ideal(self):\n text = 'She is happy. He is happy.'\n expected ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that tokenize_by_sentence function can handle incorrect input cases | def test_tokenize_by_sentence_incorrect_input(self):
bad_inputs = [[], {}, (), None, 9, 9.34, True]
expected = ()
for bad_input in bad_inputs:
actual = tokenize_by_sentence(bad_input)
self.assertEqual(expected, actual) | [
"def test_tokenize_by_sentence_inappropriate_sentence(self):\n text = '$#&*@#$*#@)'\n\n expected = ()\n actual = tokenize_by_sentence(text)\n self.assertEqual(expected, actual)",
"def test_tokenize_by_sentence_ideal(self):\n text = 'She is happy. He is happy.'\n expected ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that tokenize_by_sentence function can handle complex split case | def test_tokenize_by_sentence_complex(self):
text = 'Mar#y wa$nted, to swim. However, she was afraid of sharks.'
expected = (
(('_', 'm', 'a', 'r', 'y', '_'), ('_', 'w', 'a', 'n', 't', 'e', 'd', '_'),
('_', 't', 'o', '_'), ('_', 's', 'w', 'i', 'm', '_')),
(('_', 'h',... | [
"def test_tokenize_by_sentence_ideal(self):\n text = 'She is happy. He is happy.'\n expected = (\n (('_', 's', 'h', 'e', '_'), ('_', 'i', 's', '_'), ('_', 'h', 'a', 'p', 'p', 'y', '_')),\n (('_', 'h', 'e', '_'), ('_', 'i', 's', '_'), ('_', 'h', 'a', 'p', 'p', 'y', '_'))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that tokenize_by_sentence function can handle empty sentence input | def test_tokenize_by_sentence_empty_sentence(self):
text = ''
expected = ()
actual = tokenize_by_sentence(text)
self.assertEqual(expected, actual) | [
"def test_tokenize_by_sentence_inappropriate_sentence(self):\n text = '$#&*@#$*#@)'\n\n expected = ()\n actual = tokenize_by_sentence(text)\n self.assertEqual(expected, actual)",
"def test_tokenize_by_sentence_incorrect_input(self):\n bad_inputs = [[], {}, (), None, 9, 9.34, Tru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that tokenize_by_sentence function can handle inappropriate sentence input | def test_tokenize_by_sentence_inappropriate_sentence(self):
text = '$#&*@#$*#@)'
expected = ()
actual = tokenize_by_sentence(text)
self.assertEqual(expected, actual) | [
"def test_tokenize_by_sentence_ideal(self):\n text = 'She is happy. He is happy.'\n expected = (\n (('_', 's', 'h', 'e', '_'), ('_', 'i', 's', '_'), ('_', 'h', 'a', 'p', 'p', 'y', '_')),\n (('_', 'h', 'e', '_'), ('_', 'i', 's', '_'), ('_', 'h', 'a', 'p', 'p', 'y', '_'))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets index of the dimension corresponding to height. | def get_height_dim(layout: str):
return layout.find('H') | [
"def height( self, pyArgs, index, wrappedOperation ):\n return self.arrayType.dimensions( pyArgs[self.pixelsIndex] )[1]",
"def get_dimension_index(self, dim):\n if isinstance(dim, Dimension): dim = dim.name\n if isinstance(dim, int):\n if (dim < (self.ndims + len(self.vdims)) or\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets index of the dimension corresponding to width. | def get_width_dim(layout: str):
return layout.find('W') | [
"def get_dimension_index(self, dim):\n if isinstance(dim, Dimension): dim = dim.name\n if isinstance(dim, int):\n if (dim < (self.ndims + len(self.vdims)) or\n dim < len(self.dimensions())):\n return dim\n else:\n return IndexError('Di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates the given forwardfunction on batches from the given dataloader, and prints progress along the way. | def _foreach_batch(dl: DataLoader,
forward_fn: Callable[[Any], BatchResult],
verbose=True, max_batches=None) -> EpochResult:
losses = []
num_correct = 0
num_samples = len(dl.sampler)
num_batches = len(dl.batch_sampler)
if max_batches... | [
"def _forward_with_dataloader(\n self,\n batched_perturbed_feature_indices: Tensor,\n dataloader: torch.utils.data.DataLoader,\n input_roles: Tuple[int],\n baselines: Tuple[Union[int, float, Tensor], ...],\n feature_mask: Tuple[Tensor, ...],\n reduce: Callable,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute an aggregate embedding vector for an input str or iterable of str | def transform_sentence(self, text: Union[Iterable, str]) -> np.array:
def preprocess_text(raw_text: str) -> List[str]:
""" Prepare text for the model, excluding unknown words"""
if not isinstance(raw_text, list):
if not isinstance(raw_text, str):
raise... | [
"def words_embedding(words: list, glove):\n\n word_embeddings = map(partial(get_word_vec, glove=glove), words)\n concat_words_embedding = np.concatenate(list(word_embeddings))\n return concat_words_embedding",
"def compute_vector(word, model):\n return sum([model.wv.get_vector(x) for x in [word[i:i + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes the created test project(s) on github | def clean_github(self):
# set url on project to be able to delete
dbsession = db_session()
dbsession.query(Project).filter(Project.id == self.pjid) \
.first().repo_url = GITHUB_URL + "/" + GITHUB_USER + "/" + REMOTE_REPO_NAME
dbsession.commit()
# Clean github reposito... | [
"def test_delete_projects(self, logger, rbac_test_data, rw_conman_proxy):\n projects_test_data = rbac_test_data['projects']\n\n # Delete the projects\n for project in projects_test_data:\n logger.debug('Deleting project {}'.format(project))\n rift.auto.mano.delete_project(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a stack of orthographic plots with optional overlays. Use mask_image and/or threshold_image to preprocess images to be be overlaid and display the overlays in a given range. See the wiki examples. Example >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> ch2 = ants.image_read(ants.get_data('ch2... | def plot_ortho_stack(
images,
overlays=None,
reorient=True,
# xyz arguments
xyz=None,
xyz_lines=False,
xyz_color="red",
xyz_alpha=0.6,
xyz_linewidth=2,
xyz_pad=5,
# base image arguments
cmap="Greys_r",
alpha=1,
# overlay arguments
overlay_cmap="jet",
overl... | [
"def plot_ortho(\n image,\n overlay=None,\n reorient=True,\n blend=False,\n # xyz arguments\n xyz=None,\n xyz_lines=True,\n xyz_color=\"red\",\n xyz_alpha=0.6,\n xyz_linewidth=2,\n xyz_pad=5,\n orient_labels=True,\n # base image arguments\n alpha=1,\n cmap=\"Greys_r\",\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a pair of orthographic plots with overlays. Use mask_image and/or threshold_image to preprocess images to be be overlaid and display the overlays in a given range. See the wiki examples. Example >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> ch2 = ants.image_read(ants.get_data('ch2')) >>> an... | def plot_ortho_double(
image,
image2,
overlay=None,
overlay2=None,
reorient=True,
# xyz arguments
xyz=None,
xyz_lines=True,
xyz_color="red",
xyz_alpha=0.6,
xyz_linewidth=2,
xyz_pad=5,
# base image arguments
cmap="Greys_r",
alpha=1,
cmap2="Greys_r",
alp... | [
"def plot_ortho(\n image,\n overlay=None,\n reorient=True,\n blend=False,\n # xyz arguments\n xyz=None,\n xyz_lines=True,\n xyz_color=\"red\",\n xyz_alpha=0.6,\n xyz_linewidth=2,\n xyz_pad=5,\n orient_labels=True,\n # base image arguments\n alpha=1,\n cmap=\"Greys_r\",\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot an orthographic view of a 3D image Use mask_image and/or threshold_image to preprocess images to be be overlaid and display the overlays in a given range. See the wiki examples. | def plot_ortho(
image,
overlay=None,
reorient=True,
blend=False,
# xyz arguments
xyz=None,
xyz_lines=True,
xyz_color="red",
xyz_alpha=0.6,
xyz_linewidth=2,
xyz_pad=5,
orient_labels=True,
# base image arguments
alpha=1,
cmap="Greys_r",
# overlay arguments
... | [
"def plot_ortho_stack(\n images,\n overlays=None,\n reorient=True,\n # xyz arguments\n xyz=None,\n xyz_lines=False,\n xyz_color=\"red\",\n xyz_alpha=0.6,\n xyz_linewidth=2,\n xyz_pad=5,\n # base image arguments\n cmap=\"Greys_r\",\n alpha=1,\n # overlay arguments\n overl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and save an ANTsPy plot for every image matching a given regular expression in a directory, optionally recursively. This is a good function for quick visualize exploration of all of images in a directory | def plot_directory(
directory,
recursive=False,
regex="*",
save_prefix="",
save_suffix="",
axis=None,
**kwargs
):
def has_acceptable_suffix(fname):
suffixes = {".nii.gz"}
return sum([fname.endswith(sx) for sx in suffixes]) > 0
if directory.startswith("~"):
d... | [
"def save_analyzed_image(self, filename, **kwargs):\n self.plot_analyzed_image(show=False)\n\n plt.savefig(filename, **kwargs)",
"def main():\n\n\n args = sys.argv\n if '-h' in args:\n print main.__doc__\n sys.exit()\n dataframe = extractor.command_line_dataframe([['f', False,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds cookie XSRFTOKEN to current response. | def add_cookie(self):
self.handler.response.set_cookie(
'XSRF-TOKEN', self.token.generate_token_string()) | [
"async def add_csrf_token_cookie(request, response):\n token = await generate_token()\n\n # Set secure httponly csrf token\n response.cookies['t'] = token\n response.cookies['t']['httponly'] = True\n response.cookies['t']['secure'] = app.config.get('SECURE_COOKIE')\n\n # Set public csrf token for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifys if request has a valid XXSRFTOKEN token. Raises HTTPForbidden else. | def verify(self):
token_str = self.handler.request.headers.get('X-XSRF-TOKEN')
if not token_str:
raise HTTPForbidden('no XSRF header')
try:
self.token.verify_token_string(token_str)
except xsrf.XSRFException:
raise HTTPForbidden('invalid XSRF token') | [
"def _csrf_token_valid(request):\r\n # TODO: rename this header to WWWHISPER_CRSFTOKEN.\r\n header_token = request.META.get('HTTP_X_CSRFTOKEN', '')\r\n cookie_token = request.COOKIES.get(settings.CSRF_COOKIE_NAME, '')\r\n if (len(header_token) != csrf.CSRF_KEY_LENGTH or\r\n not constant_time_comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns True on Dev and testing environment | def is_dev():
return os.environ.get('SERVER_SOFTWARE', '').startswith('Development/') | [
"def is_dev_env() -> bool:\n if os.getenv(\"APP_ENV\") == \"dev\":\n return True\n return False",
"def _is_local():\n return (bool(os.getenv('LOCAL_DEVELOPMENT')) or\n os.getenv('SERVER_SOFTWARE', '').startswith('Development/'))",
"def is_dev():\n\treturn os.environ['SERVER_SOFTWARE'].sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
allows method to run only if a given gae header is present | def _require_header(func, header):
@wraps(func)
def decorated(self, *args, **kwargs):
if self.request.headers.get(header) or is_dev():
return func(self, *args, **kwargs)
else:
raise HTTPForbidden()
return decorated | [
"def verify_cron_header(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n if request.headers.get('X-Appengine-Cron') is None:\n abort(403)\n return f(*args, **kwargs)\n return wrapper",
"def require_email_http_header() -> str:\n return True",
"def build_header(app):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1 Base Case Have visited all digits. Store the path. self.res.append("".join(self.path)) 2 Search the letters associated with the current digit. digit = digits[path_len] arr = dic[digit] 3 Loop its children. | def DFS(self, digits, path_len):
if path_len >= len(digits): # search completed
self.res.append("".join(self.path)) # arr to str - s = "".join(arr)
return
digit = digits[path_len]
if digit not in self.dic: # invalid input protection
raise Exception("Inval... | [
"def recursive_method(self, digits):\n if not digits:\n return []\n # Build hashmap\n phone_dict = {\n '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',\n '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'\n }\n res = []\n\n def search(s, digits... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the given time to a datetime object, then looks for the weather forecast for that given time rounded to the nearest 3 hours. Builds the full tuple of weather + time tuples, then uses that to predict on the model loaded based on the given station. Html string is returned | def predict_func(time, station):
given_time = datetime.datetime.strptime(time, "%d %B %Y %I:%M %p")
weather_tuple = [8, 0, 1, 0, 0, 0, 0]#default values
icon = "02d"
try:
observation = owm.three_hours_forecast('Dublin,IE')
w = observation.get_forecast()
rounded_time = roundTime(g... | [
"def weather_update(place,hour=0,minute=0,shuffle_urls=False,return_extreme=False,ignore_print=False):\n # Step 0) If program isnt run as __main__, must check that [hour] and [minute] are acceptable\n if not isinstance(hour, (int, long)) or not isinstance(minute, (int, long)):\n print \"[Hour] and/or [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getter for list of lesson logs for the student | def lesson_logs(self):
all_lessons = models.storage.all(LessonLog)
for lesson in all_lessons.values():
if lesson.student_id == self.id:
self.lesson_logs.append(lesson)
return self.lesson_logs | [
"def list_logs_by_student(student_id):\n\n student = crud.get_student_by_id(student_id)\n student_logs = student.logs\n\n if \"teacher_id\" in session:\n teacher = crud.get_teacher_by_id(session[\"teacher_id\"]) \n else:\n teacher = None\n\n return render_template('charts.html', student... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decrements the bet from the player's bank. | def bet(self, bet):
self.bank -= bet | [
"def lose_bet(self, bet):\n self.total -= bet",
"def pay_bet(self):\n self.wallet -= self.bet\n self.bet = 0",
"def win_no_blackjack(self, bet):\n self.bank += bet * 2",
"def debit(self, amount):\n if self._is_asset_or_expenses:\n self.balance += amount\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Increments nonblackjack winnings to the player's bank. | def win_no_blackjack(self, bet):
self.bank += bet * 2 | [
"def win_blackjack(self, bet):\n self.bank += bet * 2.5",
"def __payoutSideBet(self):\n dealer_card = self.dealer.getVisibleCard()\n for player in self.players:\n if player.balance > 0:\n player_first_card = player.hands[0][0]\n player_second_card = pl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Increments blackjack winnings to the player's bank. | def win_blackjack(self, bet):
self.bank += bet * 2.5 | [
"def win_no_blackjack(self, bet):\n self.bank += bet * 2",
"def update_credits(self, winner, is_blackjack):\n if winner == 1 and is_blackjack:\n self.player.credits = self.player.credits + (2.5 * self.player.bet)\n if winner == 1 and (not is_blackjack):\n self.player.cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return's the player's bet when the result is a push. | def push(self, bet):
self.bank += bet | [
"def show_push_msg(player):\n print(\"Push! {} and the dealer have the same hand.\".format(player.name))",
"async def bet(ctx, bet_str, bet_value):\n\n uid = ctx.author.id\n\n if not is_user(uid):\n await error(ctx, \"You are not registered and cannot bet.\")\n return\n\n if not is_game_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1. Start at parent 2a. If node.cargo == value, return cargo. 2a. If value is less than root value, grab left child. 2b. If value is greater than root value, grab right child. 3a. If node is None, raise ValueError. 3b. If node exists, repeat recursive step. | def _traverse(self, value, parent=self.root, node=None):
if self.root is None:
raise ValueError("This binary tree is empty!")
currentNode = node
if currentNode.cargo == value:
return currentNode
else:
if value < currentNode.cargo:
ret... | [
"def search_pre(self, value, node):\n if (node is not None):\n\n # Check the parent node\n if (node.get_value() == value):\n return node\n\n # Check the left branch\n left_branch = self.search_pre(value, node.get_left())\n if (left_branch ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override the typical runner with an instance of `PyunitConsumer`. | def run_suite(self, suite, **kwargs):
return PyunitConsumer(
verbosity=self.verbosity,
failfast=self.failfast,
).run(suite) | [
"def __init__(self, command_line_args=None):\n command_line_args = command_line_args or sys.argv[1:]\n\n runner_action, test_path, test_runner_args, other_opts = parse_test_runner_command_line_args(command_line_args)\n \n self.setup_logging(other_opts)\n \n runner = TestRun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the module exists, and satisfies the minimum version requirement. Raises ImportError and AssertionError. | def check_module(name, min_version=None):
name = '{}'.format(name)
try:
the_module = importlib.import_module(name)
except ImportError:
tf.logging.info(
'Optional Python module %s not found, '
'please install %s and retry if the application fails.',
name, ... | [
"def check_install(module, at_least_version=None, debug=False):\n try:\n module_version = __import__(module).__version__\n is_module = True\n except ImportError as e:\n is_module = False\n if is_module:\n if at_least_version is not None:\n if parse_version(at_least_ve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update an amenity if not error 404 | def updateAmenity(amenity_id):
flag = 0
amenity = request.get_json()
text_final = "{}.{}".format('Amenity', amenity_id)
if not amenity:
abort(400, {'Not a JSON'})
amen = storage.get('Amenity', amenity_id)
if not amen:
abort(404)
ignore = ['id', 'created_at', 'updated_at']
... | [
"def update_amenity(amenity_id):\n amenity_data = request.get_json()\n if amenity_data is None:\n return jsonify({'error': \"Not a JSON\"}), 400\n amenity_update = storage.get(\"Amenity\", amenity_id)\n if amenity_update is None:\n abort(404)\n no_updates = ['id', 'created_at', 'updated... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the orbital parameters compute the RV at times t. Input | def RV_model(t, p):
(period, ttran, ecosomega, esinomega, K, gamma, gamma_offset, sigma_jitter1_sqrd, sigma_jitter2_sqrd) = p
e = np.sqrt(ecosomega**2. + esinomega**2.)
omega = np.arctan2(esinomega, ecosomega)
#mean motion: n = 2pi/period
n = 2. * np.pi / period
# Sudarsky 2005 Eq. 9 to convert between center ... | [
"def rv(t, orbits, acc=1.e-12):\n\n # handle just one orbit\n if isinstance(orbits, Norbit):\n orbits = [orbits]\n \n # Three minus signs combine to give the final sign: z points towards \n # Earth which gives one minus sign. Another comes because we are \n # considering reflex motion. A th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns datetime.datetime for the photo collection time | def get_photo_datetime(image_name):
image = Image.open(image_name)
info = image._getexif()
photo_datetime = None
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "DateTimeOriginal":
photo_datetime = value
return pho... | [
"def get_date_picture_taken(self):\n return self.get_tag('DateTime')",
"def datetime():\n return _get_rtc().datetime()",
"def _get_time(self) -> datetime:\n return datetime.fromtimestamp(int(self._raw_meta['time']) / 1e3)",
"def creation_datetime(self):\n return super()._to_datetime(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a camera make and model from the exif data of an PIL Image item. | def get_camera_makemodel(image_name):
image = Image.open(image_name)
info = image._getexif()
if info:
make = None
model = None
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "Model":
model = value.strip()
... | [
"def camera_exif(self):\n\n tags = [\n 'ExifImageHeight',\n 'ExifImageWidth',\n 'ExifOffset',\n 'FNumber',\n 'Flash',\n 'FocalLength',\n 'ISOSpeedRatings',\n 'Make',\n 'MeteringMode',\n 'Model',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Align 1000 curated tracks based on division events | def make_division_adjusted_tracks():
curated_tracks = sorted(pd.read_csv(DATA_ROOT / 'curated_tracks.csv', header=None).astype(int).values.flatten())
df = pd.read_csv(DATA_ROOT / 'Spots in tracks statistics nq.csv', na_values='None').dropna()
df = df[df['TRACK_ID'].isin(curated_tracks)]
div_frames = d... | [
"def makeTracks(self):\n\n # Geometry preliminaries\n w = self.geometry.width # Width of 2D domain\n h = self.geometry.height # Height of 2D domain\n self.div = 2 # Azimuthal angle subdivision, e.g. div=2 is (0,pi)\n nangle = self.nangle/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add frame average and standard deviation columns for each channel Using curated tracks averages | def add_mean_std(df, verbose=False):
channels = ['GFP', 'Cy3', 'DAPI', 'BF']
print(f'Adding averages and standard deviations for {", ".join(channels)} channels')
curated_tracks = sorted(pd.read_csv(DATA_ROOT / 'curated_tracks.csv', header=None).astype(int).values.flatten())
df_curated_tracks = df[df[... | [
"def frame_mean ( frame , expression , cuts = '' ) : \n return frame_moment ( frame , order = 1 , expression = expression , cuts = cuts )",
"def make_division_adjusted_tracks():\n\n curated_tracks = sorted(pd.read_csv(DATA_ROOT / 'curated_tracks.csv', header=None).astype(int).values.flatten())\n df = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add cell intensities for GFP and Cy3 channels | def add_intensities(df, sz=20, n_frames=None, verbose=False):
print('Adding cell intensities for GFP and Cy3 channels')
df['GFP_nq'] = df['GFP_cmdn'] - df['GFP_average']
df['Cy3_nq'] = df['Cy3_cmdn'] - df['Cy3_average']
del df['GFP_cmdn']
del df['Cy3_cmdn']
del df['DAPI_cmdn']
del df['BF_c... | [
"def ens_CM1_C2A(ens, var = 'ALL'):\n \n# Copy data from cell centered surrogate, then average the staggered fields to the centers\n \n t0 = timer()\n \n nx = ens.nx\n ny = ens.ny\n nz = ens.nz\n \n if var.upper() == \"U\" or var.upper() == \"ALL\":\n\n fstate.xyz3d[ens.u_ptr,:,:,:,0] = 0.5*(fstat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert Employee into the DB | def insert_employee(self, employee_id, first_name, last_name, min_shifts):
if not self.check_for_db(): # if DB doesn't exist create it
self.create_db()
connection = sqlite3.connect(self.name)
crsr = connection.cursor()
insret_query = """INSERT INTO Employee
... | [
"def insertNewEmployee(self):\n try:\n self.takeUserInput()\n self.insertNewEmployeeinDB(self.empId,self.empName,self.jobName,self.managerId,self.hireDate,self.salary,self.commission,self.deptId)\n except Exception as e:\n print(\"Error inserting New Employee,\", e)",
"def insert (self, anObj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
log done shifts into DB | def log_shift(self, employee_id, date, start_hour, end_hour):
try:
if not self.logged_shift_exists(employee_id,date):
if not self.check_for_db(): # if DB doesn't exist create it
self.create_db()
connection = sqlite3.connect(self.name)
... | [
"def updatedb(zone):\n con = framework.lite.connect('/etc/SmartHome/Databases/Security.sqlite')\n cur = con.cursor()\n cur.execute(\"INSERT INTO Log(Time, Zone, State) VALUES(?, ?, ?)\", [zone.lastevent, zone.name, zone.state])\n con.commit()\n con.close()",
"def commit(self):\n if self._dblog:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert the arrangement request by the Employee to DB, Employee_Times table | def insert_employee_times(self,employee_id,date, start_time="NULL", end_time="NULL"):
try:
if not self.employee_time_exists(employee_id, date):
if not self.check_for_db(): # if DB doesn't exist create it
self.create_db()
connection = sqlite3.conne... | [
"def insert_employee(self, employee_id, first_name, last_name, min_shifts):\n if not self.check_for_db(): # if DB doesn't exist create it\n self.create_db()\n connection = sqlite3.connect(self.name)\n crsr = connection.cursor()\n insret_query = \"\"\"INSERT INTO Employee\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets positions of employee by id | def get_employee_positions(self, employee_id):
try:
if self.check_for_db(): # check fot DB existence
connection = sqlite3.connect(self.name)
crsr = connection.cursor()
query = """SELECT position,seniority
FROM Employee_Posit... | [
"def _retrieve_employee_id(response, id):\n id = int(id)\n if id == 0:\n return None, response\n for employee in response:\n if employee['id'] == id:\n return None, [employee]\n return None, []",
"def get_position(employee):\n if employee.sudo().job_id:\n return empl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method to get all bartenders | def get_bartenders(self):
try:
if self.check_for_db(): # check fot DB existence
connection = sqlite3.connect(self.name)
crsr = connection.cursor()
query = """SELECT E.employee_id, first_name, last_name, seniority
FROM Employee E JOIN ... | [
"def get_all_bodegas():\n bodegas = Bodega.objects.all()\n return bodegas",
"def get_beers():\n\n with engine.connect() as con:\n rs = con.execute('SELECT name, Manufacturer FROM Beers;')\n return [dict(row) for row in rs]",
"def get_beers():\n\n with engine.connect() as con:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method to get employees between eligible dates | def get_employees_by_date_range(self, org_id, start_date, end_date):
try:
if self.check_for_db(): # check fot DB existence
connection = sqlite3.connect(self.name)
crsr = connection.cursor()
query = """SELECT E.employee_id, first_name, last_name, ET.da... | [
"def get_holidays_between_dates(self, start_date, end_date):",
"def _check_dates(self, cr, uid, ids):\n for employee in self.browse(cr, uid, ids):\n message= \"The %s must be anterior or equal to the current date!\"\n message1= \"The %s must be anterior to the employment date!\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get shifts between given dates | def get_shifts_by_date_range(self, org_id, start_date, end_date): # in use
try:
if self.check_for_db(): # check fot DB existence
connection = sqlite3.connect(self.name)
crsr = connection.cursor()
query = """SELECT shift_id, S.date, start_time
... | [
"def shift(ts1, ts2, compare_start, compare_end, hours_forward, hours_backward, seconds_forward, seconds_backward):\r\n\r\n dets_time = []\r\n print(\"Started shifting...\")\r\n # We do not need to check every second. just +/- 60 seconds for all hours\r\n for h in range(-hours_backward, hours_forward + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
register solution to DB (Employees_in_Shifts table) | def register_arrangement(self, solution, sol_num=1):
connection = sqlite3.connect(self.name)
crsr = connection.cursor()
for shift in solution:
shift_id = shift.get_shift_id()
employees_in_shift = shift.get_bartenders() + shift.get_waitresses()
for employee in ... | [
"def insert_employee(self, employee_id, first_name, last_name, min_shifts):\n if not self.check_for_db(): # if DB doesn't exist create it\n self.create_db()\n connection = sqlite3.connect(self.name)\n crsr = connection.cursor()\n insret_query = \"\"\"INSERT INTO Employee\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines the smart start state The smart start is determined using the UCB1 algorithm. The UCB1 algorithm is a well known exploration strategy for multiarm bandit problems. The smart start is chosen according to smart_start = \arg\max\limits_s\left(alpha \max\limits_a Q(s, a) + \sqrt{\frac{beta \log |D| }{C(s}} \righ... | def get_smart_start_path(self):
if len(self.replay_buffer) == 0: # if buffer is emtpy, nothing to evaluate
return None
possible_start_indices = self.replay_buffer.get_possible_smart_start_indices(self.n_ss)
if possible_start_indices is None: # no valid states then return None
... | [
"def start_new_episode(self, state):\n self.smart_start_pathing = False\n self.smart_start_path = None\n\n if np.random.rand() <= self.eta: #eta is probability of using smartStart\n start_time = time.time()\n self.smart_start_path = self.get_smart_start_path() # new state ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Record observation to replay buffer, Allow the base agent to observe the transition If smart start pathing is on, check if the goal is reached | def observe(self, state, action, reward, new_state, done):
# new_state added (maybe) to buffer
self.replay_buffer.add(self, state, action, reward, done, new_state)
# agent observation
self.agent.observe(state, action, reward, new_state, done)
# check if smart_start_state has be... | [
"def observe(self, pre_observation, action, reward, post_observation, done):",
"def observe(self, observation):\n if observation.get('reward') is not None:\n reward = observation['reward']\n for log_prob in self.log_probs:\n loss = - log_prob * reward\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FIRST reset smart start pathing stuffs Then check if smart start will randomly happen, if so set it up (don't return) Finally tell the base_agent that a new episode is happening | def start_new_episode(self, state):
self.smart_start_pathing = False
self.smart_start_path = None
if np.random.rand() <= self.eta: #eta is probability of using smartStart
start_time = time.time()
self.smart_start_path = self.get_smart_start_path() # new state to navigate... | [
"def episode_start(self, parameters=None):\n\n # reset internal initial state\n self.goal_count = 0\n self.value = randint(self.min, self.max)\n\n # print out a message for our first episode\n if not self.started:\n self.started = True\n print('started.')\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simulate growth for a set of community models. | def grow(
models: CommunityModelDirectory,
medium: pd.DataFrame,
tradeoff: float = 0.5,
threads: int = 1,
strategy: str = "pFBA",
) -> mw.core.GrowthResults:
if strategy == "minimal uptake":
strategy = "minimal imports"
model_folder = str(models.model_files.path_maker(model_id="blub"... | [
"def grow(self, rate=1, years=1):\n\n for y in range(1, years+1):\n r = rate\n\n # all trees age one year\n self.age()\n\n # aging means root growth, check for new connections\n for t in self.trees:\n t.getnewneighbors()\n\n # b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetConsumerAction. Get details about a specific consumer action. | def get_consumer_action(self, consumer_id, consumer_action_id, publisher_id=None):
route_values = {}
if consumer_id is not None:
route_values['consumerId'] = self._serialize.url('consumer_id', consumer_id, 'str')
if consumer_action_id is not None:
route_values['consumerAc... | [
"def list_consumer_actions(self, consumer_id, publisher_id=None):\n route_values = {}\n if consumer_id is not None:\n route_values['consumerId'] = self._serialize.url('consumer_id', consumer_id, 'str')\n query_parameters = {}\n if publisher_id is not None:\n query_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ListConsumerActions. Get a list of consumer actions for a specific consumer. | def list_consumer_actions(self, consumer_id, publisher_id=None):
route_values = {}
if consumer_id is not None:
route_values['consumerId'] = self._serialize.url('consumer_id', consumer_id, 'str')
query_parameters = {}
if publisher_id is not None:
query_parameters['... | [
"def list_consumers(self):\n endpoint = self.build_url(\"/consumers\")\n return self.request('get', endpoint)",
"def get_consumer_action(self, consumer_id, consumer_action_id, publisher_id=None):\n route_values = {}\n if consumer_id is not None:\n route_values['consumerId'] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetConsumer. Get a specific consumer service. Optionally filter out consumer actions that do not support any event types for the specified publisher. | def get_consumer(self, consumer_id, publisher_id=None):
route_values = {}
if consumer_id is not None:
route_values['consumerId'] = self._serialize.url('consumer_id', consumer_id, 'str')
query_parameters = {}
if publisher_id is not None:
query_parameters['publisher... | [
"def get_consumer_action(self, consumer_id, consumer_action_id, publisher_id=None):\n route_values = {}\n if consumer_id is not None:\n route_values['consumerId'] = self._serialize.url('consumer_id', consumer_id, 'str')\n if consumer_action_id is not None:\n route_values['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ListConsumers. Get a list of available service hook consumer services. Optionally filter by consumers that support at least one event type from the specific publisher. | def list_consumers(self, publisher_id=None):
query_parameters = {}
if publisher_id is not None:
query_parameters['publisherId'] = self._serialize.query('publisher_id', publisher_id, 'str')
response = self._send(http_method='GET',
location_id='4301c514-5f... | [
"def list_consumers(self):\n endpoint = self.build_url(\"/consumers\")\n return self.request('get', endpoint)",
"def get_all_consumers(self):\n return self.consumers",
"def get_consumers(self):\n pass",
"def list_vhost_consumers(self, *, vhost: str = None):\n vhost = vhost i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ListEventTypes. Get the event types for a specific publisher. | def list_event_types(self, publisher_id):
route_values = {}
if publisher_id is not None:
route_values['publisherId'] = self._serialize.url('publisher_id', publisher_id, 'str')
response = self._send(http_method='GET',
location_id='db4777cd-8e08-4a84-8ba3-... | [
"def list_event_types():\n print('\\nValid event types:')\n for etype in EVENT_TYPES:\n print(' {0}'.format(etype))",
"def get_notification_event_types(self):\n return []",
"def get_events_by_genus_type(self, event_genus_type):\n return # osid.calendaring.EventList",
"def eventr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetNotification. Get a specific notification for a subscription. | def get_notification(self, subscription_id, notification_id):
route_values = {}
if subscription_id is not None:
route_values['subscriptionId'] = self._serialize.url('subscription_id', subscription_id, 'str')
if notification_id is not None:
route_values['notificationId'] =... | [
"def get_notification(self, notification_id):\r\n return self._notification_manager.get(notification_id)",
"def get_notification(self, notification_id):\n\n response = self._query_api(\"/rest/notifications/\" + str(notification_id))\n if response is None:\n return None\n eli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetNotifications. Get a list of notifications for a specific subscription. A notification includes details about the event, the request to and the response from the consumer service. | def get_notifications(self, subscription_id, max_results=None, status=None, result=None):
route_values = {}
if subscription_id is not None:
route_values['subscriptionId'] = self._serialize.url('subscription_id', subscription_id, 'str')
query_parameters = {}
if max_results is ... | [
"def get_notifications(self, context):\n module_context.init()\n LOG.info(\"Received RPC GET NOTIFICATIONS \")\n events = self.sc.get_stashed_events()\n notifications = []\n for event in events:\n notification = event.data\n msg = (\"Notification Data: %r\" %... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
QueryNotifications. Query for notifications. A notification includes details about the event, the request to and the response from the consumer service. | def query_notifications(self, query):
content = self._serialize.body(query, 'NotificationsQuery')
response = self._send(http_method='POST',
location_id='1a57562f-160a-4b5c-9185-905e95b39d36',
version='5.1',
content... | [
"def get_notifications(self, context):\n module_context.init()\n LOG.info(\"Received RPC GET NOTIFICATIONS \")\n events = self.sc.get_stashed_events()\n notifications = []\n for event in events:\n notification = event.data\n msg = (\"Notification Data: %r\" %... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetPublisher. Get a specific service hooks publisher. | def get_publisher(self, publisher_id):
route_values = {}
if publisher_id is not None:
route_values['publisherId'] = self._serialize.url('publisher_id', publisher_id, 'str')
response = self._send(http_method='GET',
location_id='1e83a210-5b53-43bc-90f0-d47... | [
"def publisher(self):\n if \"publisher\" in self._prop_dict:\n return self._prop_dict[\"publisher\"]\n else:\n return None",
"def get_live_publisher():\n\n live_publisher_class = get_setting_or_raise(\n setting=\"WAGTAIL_LIVE_PUBLISHER\", setting_str=\"live publisher\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ListPublishers. Get a list of publishers. | def list_publishers(self):
response = self._send(http_method='GET',
location_id='1e83a210-5b53-43bc-90f0-d476a4e5d731',
version='5.1')
return self._deserialize('[Publisher]', self._unwrap_collection(response)) | [
"def publishers(self):\n\n base = self.get_part(self.__BASE_PART, must_exist=True)\n if base is None:\n # Catalog contains nothing.\n return set()\n return set(p for p in base.publishers())",
"def list_distributions(self, p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
QueryPublishers. Query for service hook publishers. | def query_publishers(self, query):
content = self._serialize.body(query, 'PublishersQuery')
response = self._send(http_method='POST',
location_id='99b44a8a-65a8-4670-8f3e-e7f7842cce64',
version='5.1',
content=conte... | [
"def publishers(self):\n\n base = self.get_part(self.__BASE_PART, must_exist=True)\n if base is None:\n # Catalog contains nothing.\n return set()\n return set(p for p in base.publishers())",
"def list_publishers(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CreateSubscription. Create a subscription. | def create_subscription(self, subscription):
content = self._serialize.body(subscription, 'Subscription')
response = self._send(http_method='POST',
location_id='fc50d02a-849f-41fb-8af1-0a5216103269',
version='5.1',
... | [
"def create_subscription(self, subscription_info, **kwargs):\n kwargs['_return_http_data_only'] = True\n if kwargs.get('callback'):\n return self.create_subscription_with_http_info(subscription_info, **kwargs)\n else:\n (data) = self.create_subscription_with_http_info(subs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ReplaceSubscription. Update a subscription. ID for a subscription that you wish to update. | def replace_subscription(self, subscription, subscription_id=None):
route_values = {}
if subscription_id is not None:
route_values['subscriptionId'] = self._serialize.url('subscription_id', subscription_id, 'str')
content = self._serialize.body(subscription, 'Subscription')
r... | [
"def update_subscription(self, id: UUID, data: Dict):\n subscriptions.update().where(subscriptions.c.id == id).values(data).execute()\n return data",
"async def update_subscription(\n self,\n topic_name: str,\n subscription: Union[SubscriptionProperties, Mapping[str, Any]],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CreateSubscriptionsQuery. Query for service hook subscriptions. | def create_subscriptions_query(self, query):
content = self._serialize.body(query, 'SubscriptionsQuery')
response = self._send(http_method='POST',
location_id='c7c3c1cf-9e05-4c0d-a425-a0f922c2c6ed',
version='5.1',
... | [
"def getSubscriptions(state=None):",
"def getSubscriptions(entity):",
"def getUserSubscriptions(user, request):\n subscriptions = user.get('subscribedTo', [])\n\n search_params = searchParams(request)\n tags = set(search_params.pop('tags', []))\n\n # XXX Whhen refactoring subscriptions storage to a ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CreateTestNotification. Sends a test notification. This is useful for verifying the configuration of an updated or new service hooks subscription. | def create_test_notification(self, test_notification, use_real_data=None):
query_parameters = {}
if use_real_data is not None:
query_parameters['useRealData'] = self._serialize.query('use_real_data', use_real_data, 'bool')
content = self._serialize.body(test_notification, 'Notificati... | [
"def send_test_event_notification(Notification=None, TestEventType=None):\n pass",
"def test_notification(self, notification=None, notification_type=None,\r\n details=None):\r\n if notification:\r\n # Test an existing notification\r\n uri = \"/%s/%s/test\" % (self.uri_ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Task to seed the database. | def seed_db():
Seed().run() | [
"def run(self):\n self.call(ClienteTableSeeder)\n self.call(ProductoTableSeeder)\n self.call(PedidoTableSeeder)",
"def test_database_seed(self):\n\n sys.stdout.write('Testing database seed process...')\n user = User.query.filter_by(user_id=1).one()\n house = House.query.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
djangoclite by Leo Neto A CLI to handle the creation and management of your Django projects. The CLI has some opinions about how your project should be structured in order for it to maximize the amount of automatic configuration it can provide you. Since Django itself is highly configurable, you are free to bypass conv... | def cli(ctx, dry, force, verbose, debug):
ctx.ensure_object(dict)
ctx.obj['dry'] = dry
ctx.obj['force'] = force
ctx.obj['verbose'] = verbose
ctx.obj['debug'] = debug
ctx.obj['project_files'] = FileHandler.find_files(path=os.getcwd(), patterns=['manage.py', 'wsgi.py', 'apps.py'])
# Note fo... | [
"def autoconfigure(\n repo_url: str = typer.Argument(..., help=\"url of remote git repository of your django project\"),\n domain_name: str = typer.Option(\n \"your-username.pythonanywhere.com\",\n \"-d\",\n \"--domain\",\n help=\"Domain name, eg www.mydomain.com\",\n ),\n py... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the algorithm, salt and password and uses Python's hashlib to produce the hash. Currently only supports bcrypt. | def gen_hexdigest(raw_password, algorithm=BCRYPT, salt=None):
if raw_password is None:
raise ValueError('No empty passwords, fool')
if algorithm == BCRYPT:
# bcrypt has a special salt
if salt is None:
salt = bcrypt.gensalt()
return (algorithm, salt, bcrypt.hashpw(raw_... | [
"def get_hexdigest(algorithm, salt, raw_password):\r\n raw_password, salt = smart_str(raw_password), smart_str(salt)\r\n if algorithm == 'crypt':\r\n try:\r\n import crypt\r\n except ImportError:\r\n raise ValueError('\"crypt\" password algorithm not supported in this environment')\r\n return c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a password line and returns the line split by PASSWD_DELIM | def split_passwd_line(password_line):
return password_line.split(PASSWD_DELIM) | [
"def retrieve_password(username):\r\n return open('passfile').readlines()[find_password_line(username)].strip()",
"def getUsernamePassword(file):\n\n username=linecache.getline(file,1) #username on 1st line\n password=linecache.getline(file,2) #password on 2nd line\n return username.strip(),password.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The authenticated user for this message. Determined by either get_current_user, which you can override to set the user based on, e.g., a cookie. If that method is not overridden, this method always returns None. We lazyload the current user the first time this method is called and cache the result after that. | def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = self.get_current_user()
return self._current_user | [
"def get_current_user(self):\n return self.graph.users.get(int(self.get_secure_cookie('eid')))",
"def get_current_user(self):\n admin_cookie = self.get_secure_cookie(COOKIE_NAME)\n try:\n if admin_cookie:\n try:\n (user, expires) = json.loads(admin_cookie)\n except ValueEr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look up a word in the CMU dictionary, return a list of syllables | def get_syllables(word):
try:
return CMU[word.lower()]
except KeyError:
return [[]] | [
"def syllabify_word(self, word):\n word_syllables = self.syllable.findall(word)\n if word_syllables:\n return [s for s in word_syllables]\n else:\n return [word]",
"def lookup(self, word):",
"def getSyllables(word):\n\tsyllables = []\n\tsyl = []\n\texp = Base.explode(w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Represent strong and weak stress of a word with a series of 1's and 0's | def stress(word, variant = "primary"):
syllables = get_syllables(word)
if syllables:
# TODO: Implement a more advanced way of handling multiple pronunciations than just picking the first
if variant == "primary" or variant not in ["all", "min", "max"]:
return stress_from_syllables(s... | [
"def stress(word, SECONDARY=True):\n def extract_stress(s):\n n = int(s[-1])\n if not SECONDARY and n > 0:\n return 1\n return n\n syllables = filter(lambda x: x[-1].isdigit(), cmu_lookup(word))\n return map(extract_stress, syllables)",
"def to_true_stress(true_stress, str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get stress notation for every line in the poem | def scanscion(tokenized_poem):
line_stresses = []
currline = 0
for line in tokenized_poem:
line_stresses.append([])
[line_stresses[currline].append(stress(word)) for word in line if word]
currline += 1
return line_stresses | [
"def stresses_for_line(line):\n\n\tparts = line.split('\\t')\n\n\tif len(parts) == 2:\n\t\ttext, info = parts\n\t\tstresses_string = get_property(info, 'stress')\n\t\tstresses = ''.join(stresses_string.split())\n\t\treturn list(stresses)\n\telif len(parts) == 1:\n\t\treturn stresses_for_text(parts[0])",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the rhyme level n and a syllable (phone) list, count backward witin the list to find the nth vowel. Return the (negative) index where it can be located. | def get_nth_last_vowel(phones, n):
vowel_count = 0
for i in range(1, len(phones) + 1):
if phones[-i][-1].isdigit():
vowel_count += 1
if vowel_count == n:
return -i | [
"def _last_vowel(syllable):\n for i in range(len(syllable) - 1, -1, -1):\n if syllable[i] in _SHORT_VOWELS or syllable[i] in _LONG_VOWELS:\n return i\n return -1",
"def count_syllables(word):\n word_lower = word.lower () #make function non-case sensetive\n vowels = 'aeiouy'\n vowels_position = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each word, get a list of various syllabic pronunications. Then check whether the last level number of syllables is pronounced the same. If so, the words probably rhyme | def rhymes(word1, word2, level=2):
pronunciations = get_syllables(word1)
pronunciations2 = get_syllables(word2)
if not (pronunciations and pronunciations2):
return False
# Work around some limitations of CMU
equivalents = {"ER0": "R"}
def replace_syllables(syllables):
return ... | [
"def doesRhyme(self, word1, word2):\n\t\tif word1 == word2:\n\t\t\treturn 0\n\n\t\tpron1 = []\n\t\tpron2 = []\n\t\tif word1 in self.pronDict:\n\t\t\tpron1 = self.pronDict[word1][0]\n\t\t\tpron1 = [filter(lambda x: re.sub(\"[^a-zA-Z]\", '', x), str(lex)) for lex in pron1]\n\t\telse:\n\t\t\ti = 0\n\t\t\twhile i < len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a rhyme scheme for the poem. For each line, lookahead to the future lines of the poem and see whether last words rhyme. | def rhyme_scheme(tokenized_poem):
num_lines = len(tokenized_poem)
# By default, nothing rhymes
scheme = ['X'] * num_lines
rhyme_notation = list(ascii_lowercase)
currrhyme = -1 # Index into the rhyme_notation
for lineno in range(0, num_lines):
matched = False
for futurelineno ... | [
"def getRhymes(self):\n # Before checking for rhymes, remove sentence final punctuation\n # and blank lines to ensure correct rhyme detection\n punctuation = \"[^0-9A-Za-z]\"\n i = 0\n self.stanzas = 1\n # Use while to iterate over the verses since the deletion of lines\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a commadelimited string of stanza lengths | def stanza_lengths(tokenized_poem):
stanzas = []
i = 0
for line in tokenized_poem:
if line != ['']:
i += 1
else:
stanzas.append(str(i))
i = 0
if i != 0:
stanzas.append(str(i))
joined = ','.join(stanzas)
return joined | [
"def format_length(length, size):\n\t\tformatted = hex(int(length)).split('0x')[1]\n\t\twhile len(formatted) < size:\n\t\t\tformatted = '0' + formatted\n\t\treturn formatted",
"def item_length(self):\n return 4 + self.ts_sub_item.total_length()",
"def order_by_length(*items):\n sorted_items = sorted(ite... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare a string's Levenshtein distance to each candidate in a dictionary. Returns the name of the closest match | def levenshtein(string, candidates):
distances = defaultdict(int)
num_lines = len(string)
for k, v in candidates.items():
expanded = False
# Expands the length of each candidate to match the length of the compared string
if len(v) != len(string):
v = (v * (num_lines // ... | [
"def levenshtein_distance_using_lexical_tree(lexical_tree, input_string, strategy=0, case_sensitive=0):",
"def levenshtein_distance(str_1, str_2):\n return textdistance.levenshtein.normalized_similarity(str_1, str_2)",
"def lev_distance(self,b):\n str1 = self.name\n str2 = b.name\n d=dic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |