query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Replace all occurrences of y with x (Exercise 3.29)
def subst(x, y, S): if core.first(S) == y: if len(S) > 1: return core.prefix(x, subst(x, y, core.rest(S))) else: return [x] else: if len(S) > 1: return core.prefix(core.first(S), subst(x, y, core.rest(S))) else: return S
[ "def strReplace( x, idx1, idx2, y):\n\n b0 = x[0:idx1]\n b1 = y\n b2 = x[idx2:]\n b = b0+b1+b2\n return str(b)", "def subst1st(x, y, S):\n if core.first(S) == y:\n return indsubst(x, 0, S)\n else:\n return core.prefix(core.first(S), subst1st(x, y, core.rest(S)))", "def test_replace_with_mark...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace all occurences of y in S with the elements of sequence T (Exercise 3.31)
def lsubst(T, y, S): if core.first(S) == y: if len(S) > 1: return cat(T, lsubst(T, y, core.rest(S))) else: return T else: if len(S) > 1: return core.prefix(core.first(S), lsubst(T, y, core.rest(S))) else: return S
[ "def subst(x, y, S):\n if core.first(S) == y:\n if len(S) > 1:\n return core.prefix(x, subst(x, y, core.rest(S)))\n else:\n return [x]\n else:\n if len(S) > 1:\n return core.prefix(core.first(S), subst(x, y, core.rest(S)))\n else:\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the difference reduction of a sequence (Exercise 3.39)
def seqdif(S): if not S: return 0 elif core.second(S): return core.first(S) - core.second(S) + seqdif(core.rest(core.rest(S))) else: return core.first(S)
[ "def diff(seq):\r\n return standardize([i - j for i, j in zip(seq[1:], seq[:-1])])", "def backward_differences(T):\n\tnumOfTimes = len(T)\n\t#the number of steps in the method\n\tm = numOfTimes - 1\n\t#generate the initial differences, which\n\t#is just the standard basis.\n\tD = np.array([ [np.float64((i+1)==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform the substition pairs of sequence P on sequence S (Exercise 3.41)
def sublis(P, S): if not S or not P: return S else: return sublis(core.rest(P), subst(core.second(core.first(P)), core.first(core.first(P)), S))
[ "def subpair(X, Y, S):\n if not X or not Y or not S:\n return S\n else:\n return subpair(core.rest(X), core.rest(Y), subst(core.first(Y), core.first(X), S))", "def subst(x, y, S):\n if core.first(S) == y:\n if len(S) > 1:\n return core.prefix(x, subst(x, y, core.rest(S)))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform pairwise substition of positional keys in X with positional values in Y on sequence S (Exercise 3.42)
def subpair(X, Y, S): if not X or not Y or not S: return S else: return subpair(core.rest(X), core.rest(Y), subst(core.first(Y), core.first(X), S))
[ "def subst(x, y, S):\n if core.first(S) == y:\n if len(S) > 1:\n return core.prefix(x, subst(x, y, core.rest(S)))\n else:\n return [x]\n else:\n if len(S) > 1:\n return core.prefix(core.first(S), subst(x, y, core.rest(S)))\n else:\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the difference mapping of a sequence (Exercise 3.54)
def map_dif(S): if not S: return [] else: return core.prefix(seqdif(core.first(S)), map_dif(core.rest(S)))
[ "def diff(seq):\r\n return standardize([i - j for i, j in zip(seq[1:], seq[:-1])])", "def interSequence(seq_maps):\n seq_map = {}\n \n return seq_map", "def seqdif(S):\n if not S:\n return 0\n elif core.second(S):\n return core.first(S) - core.second(S) + seqdif(core.rest(core.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a subsequence of S from elements m to n (Exercise 3.63)
def subseq(S, m, n): if m < 0: return subseq(S, len(S) + m, n) elif n < 0: return subseq(S, m, len(S) + n) elif m > len(S): return subseq(S, m - len(S), n) elif n > len(S): return subseq(S, m, n - len(S)) if m == n: return [] elif m > n: if n == 0...
[ "def subseqs(s):\n if len(s)==0:\n return [[]]\n else:\n sub=subseqs(s[1:])\n return insert_into_all(s[0],sub)+sub", "def _slice_a_subsequence(self, seq):\n n = len(seq)\n if n == 1:\n return seq\n else:\n start = random_pick(n)\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Distribute left function (Exercise 3.69)
def seqdistleft(x, S): if not S: return [] else: return core.prefix(core.prefix(x, core.prefix(core.first(S), [])), seqdistleft(x, core.rest(S)))
[ "def rw_generator(N: int, x_0 = 0, p_left=0.5):\n steps = [x_0] + [ 1 if (i>p_left) else -1 for i in np.random.random(N-1)]\n return np.add.accumulate(steps)", "def _do_action_left(state):\n\n height, width = state.shape\n reward = 0\n\n for row in range(height):\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reverse sequence S onto sequence T
def seqreverseaux(S, T): if not S: return T else: return seqreverseaux(core.rest(S), core.prefix(core.first(S), T))
[ "def reversed(seq):\n\n l=list(seq)\n l.reverse()\n return l", "def elements_reversed(seq):\n return seq[::-1]", "def reverse(s):\n r = \"\".join(reversed(s))\n\n return r", "def sg_reverse_seq(tensor, opt):\n # default sequence dimension\n opt += tf.sg_opt(dim=1)\n seq_len = tf.not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a new instance. An instance contains the list of genes and a mapping from gene to place in list
def __init__(self, genes, sort=True): if sort == True: self.genes = sorted(genes) else: self.genes = genes self.ind = {k: i for i, k in enumerate(self.genes)} self.rev_ind = {i: k for i, k in enumerate(self.genes)} self.n = len(genes) self.ind_siz...
[ "def __init__(self, genome):\n self.genome = []", "def __init__(self):\n self.genome = []\n self.fitness = 0", "def __init__(self, genes):\n \"\"\"Конструктор Bot - созданная Пользователем \"последовательность генов\" для отдельного бота\"\"\"\n\n self._genes = genes[:]", "def _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal function, gets a location and calulate the indexes of the genes returns the genes as a tuple
def _calc_pair_genes(self, ind, return_inds=False): i_0 = bisect(self.i0_inds, ind) - 1 i_1 = ind - self.i0_inds[i_0] + i_0 + 1 if return_inds: return (i_0, i_1) return (self.get_genes_solo(i_0), self.get_genes_solo(i_1))
[ "def findGeneIndex(featureGenes, genes):\n indices = []\n missing = []\n for gene in featureGenes:\n if gene in genes:\n indices.append(genes.index(gene))\n else:\n missing.append(gene)\n return indices", "def accession_indices(geno_hdf, mac, locus_indices):\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function convert the multiclass labels into binary labels as healthy and malaria.
def convert_multiclass_lbl_to_binary_lbl(multiclass_labels): binary_label = [] for tempLabel in multiclass_labels: if tempLabel == "healthy": binary_label.append("healthy") else: binary_label.append("malaria") return binary_label
[ "def binary_labels(labels, in_class, column=\"inregister\"):\n\n labels[column] = labels[column].apply(lambda paper: 1 if paper == in_class else 0)\n\n return labels", "def _convert_labels(self, y_user):\n print self._user2classif_lut\n return [self._user2classif_lut[x] for x in y_user]", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get current filename without path (str).
def userFriendlyCurrentFile(self): if self.currentFile: return strippedName(self.currentFile) else: return ""
[ "def current_name():\n return os.path.basename(os.getcwd())", "def current_filename(self):\n return self.dr.fileName()", "def filename(self):\n fname = self.raw_filename\n if not isinstance(fname, text_type):\n fname = fname.decode('utf8', 'ignore')\n fname = normalize('N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create |QAction| that is mapped via methodName to call.
def createMappedAction(self, icon, text, parent, shortcut, methodName): if icon is not None: action = QtGui.QAction(icon, text, parent, shortcut=shortcut, triggered=self._actionMapper.map) else: action = QtGui...
[ "def create_action(self, action_name, action_config):\n action_type = action_config['type']\n clz = Actions.get_action_class(action_type)\n action = clz()\n action.set_info(self.name, action_name, self.config)\n return action", "def addAction(self, *_args) -> Union[None, QAction...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the Window menu.
def updateWindowMenu(self): self._windowMenu.clear() self._windowMenu.addAction(self._closeAct) self._windowMenu.addAction(self._closeAllAct) self._windowMenu.addSeparator() self._windowMenu.addAction(self._tileAct) self._windowMenu.addAction(self._cascadeAct) sel...
[ "def updateMenuAndWindowTitle(self):\n self.updateMenu()\n self.updateWindowTitle()", "def updateMenu(self):\n #logging.debug('Application: updateMenu()')\n if self.mainWindow().startupScreen():\n self.updateStartupScreen()\n # Recent files\n num_recent_files =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create status bar label.
def createStatusBarLabel(self, stretch=0): label = QtGui.QLabel() label.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken) label.setLineWidth(2) self.statusBar().addWidget(label, stretch) return label
[ "def createStatusBar(self):\n # intialize status bar\n self.statusBar().showMessage('')\n self.status_mouse_pos = QLabel('')\n self.statusBar().addPermanentWidget(self.status_mouse_pos)\n # connect the scene pos changed to a function formatting self.status_mouse_pos\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle synchronized subwindow panning.
def toggleSynchPan(self): if self._synchPanAct.isChecked(): self.synchPan(self.activeMdiChild)
[ "def toggle_pan(self, pan_off):\n if pan_off:\n self.pan_image = False\n self.view.toolbar.ToggleTool(self.view.toolbar_ids['Pan Image'], False)\n self.view.canvas.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))\n self.view.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle synchronized subwindow zooming.
def toggleSynchZoom(self): if self._synchZoomAct.isChecked(): self.synchZoom(self.activeMdiChild)
[ "def toggle_zoom(self):\r\n #TODO! zooming\r\n logging.debug('toggle \"single shot\" zoom')\r\n #aktiviraj zoomiranje\r\n self.zoomSelector.set_active(True)\r\n #ako postoji span selector, disable radi konfilikta sa ljevim klikom\r\n if self.spanSelector != None:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activate current subwindow's System Menu.
def activateSubwindowSystemMenu(self): activeSubWindow = self._mdiArea.activeSubWindow() if activeSubWindow: activeSubWindow.showSystemMenu()
[ "def menu(self):\n self.parent.switch_screen(\"Menu\")", "def openMenu(self):\n root = tk.Tk()\n menu = Menu(self, master=root)\n menu.mainloop()", "def show():\n\tif checkOpen()==0:\n\t\tnotify(\"File explorer not open. Say \\\"start\\\" to open a new file explorer or \\\"exit\\\" t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open a recent file.
def openRecentFile(self, filename): self.loadFile(filename)
[ "def open_recent_file(self):\n action = self.sender()\n if action:\n self.load_file(action.data())", "def openRecentFileSlot(self):\n filename = self.sender().data().toString()\n logging.debug('Application: openRecentFileSlot() - ' + filename)\n self.openFile(filename...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle subwindow scrollbar visibility.
def toggleScrollbars(self): checked = self._showScrollbarsAct.isChecked() windows = self._mdiArea.subWindowList() for window in windows: child = window.widget() child.enableScrollBars(checked)
[ "def notebook_visible_toggle_action(self):\n\n self.notebook.Show(not self.notebook.IsShown())\n self.viewmenu.Check(406, self.notebook.IsShown())\n self.SendSizeEvent()", "def toggleSingleBeamPlot(self):\n if self.sb_dock.isVisible(): self.sb_dock.hide()\n else: self.sb_dock.sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle status bar visibility.
def toggleStatusbar(self): self.statusBar().setVisible(self._showStatusbarAct.isChecked())
[ "def status_bar_toggle_action(self):\n\n self.statusbar.Show(not self.statusbar.IsShown())\n self.SendSizeEvent()", "def _hide_status_bar(self):\n\n self._status_frame_outer.place_forget()", "def toggleWindowVisibility(string):\n pass", "def toggle_visibility(self):\n\n if self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle |QMdiSubWindow| activated signal.
def subWindowActivated(self, window): self.updateStatusBar()
[ "def setActiveWin(self, window):\n self.activeWindow = window\n self.controlActivated.emit(self)\n self.updateCommandsAvail()\n filterTextDialog = globalref.mainControl.filterTextDialog\n if filterTextDialog and filterTextDialog.isVisible():\n filterTextDialog.updateAva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch MDI subwindow layout direction.
def switchLayoutDirection(self): if self.layoutDirection() == QtCore.Qt.LeftToRight: QtGui.qApp.setLayoutDirection(QtCore.Qt.RightToLeft) else: QtGui.qApp.setLayoutDirection(QtCore.Qt.LeftToRight)
[ "def set_single_layout(window, box1, box2):\n\truntime_info[\"double_layout\"] = False\n\n\tbox2.place_forget()\n\tbox1.place(height=window.winfo_height(), width=window.winfo_width())", "def switchToOutlinerPerspLayout():\n\n pass", "def layoutAll(self, warp=False):\r\n if self.screen and len(self.win...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Synch panning of all subwindowws to the same as fromViewer.
def synchPan(self, fromViewer): assert isinstance(fromViewer, MdiChild) if not fromViewer: return if self._handlingScrollChangedSignal: return self._handlingScrollChangedSignal = True newState = fromViewer.scrollState changedWindow = fromViewer.pa...
[ "def update(self):\n\t\tfor p in self.panes:\n\t\t\tp.update()", "def layoutAll(self, warp=False):\r\n if self.screen and len(self.windows):\r\n with self.disableMask(xcb.xproto.EventMask.EnterWindow):\r\n normal = [x for x in self.windows if not x.floating]\r\n flo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Synch zoom of all subwindowws to the same as fromViewer.
def synchZoom(self, fromViewer): if not fromViewer: return newZoomFactor = fromViewer.zoomFactor changedWindow = fromViewer.parent() windows = self._mdiArea.subWindowList() for window in windows: if window != changedWindow: window.widget()....
[ "def updateZoomRegionsLimits(self):\n if self.selectedTool != Tools.ZoomTool:\n return\n\n min_limit, max_limit = self.mainCursor.min, self.mainCursor.max\n # set the limits of the zoom regions to the length of the signal\n self.axesOscilogram.gui_user_tool.zoomRegion.setBound...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save dialog state, position & size.
def saveDialogState(self, dialog, groupName): assert isinstance(dialog, QtGui.QDialog) settings = QtCore.QSettings() settings.beginGroup(groupName) settings.setValue('state', dialog.saveState()) settings.setValue('geometry', dialog.saveGeometry()) settings.setValue('fil...
[ "def save_ui_geometry(self):\n if self.viewmanager.MDI_ON:\n Configuration.setSetting(\"PlayerSizes\", self.saveState())\n Configuration.setSetting(\"MainWindowSize\", self.size())\n Configuration.setSetting(\"MainWindowPosition\", self.pos())\n\n else:\n Co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore dialog state, position & size.
def restoreDialogState(self, dialog, groupName): assert isinstance(dialog, QtGui.QDialog) settings = QtCore.QSettings() settings.beginGroup(groupName) dialog.restoreState(settings.value('state')) dialog.restoreGeometry(settings.value('geometry')) dialog.selectNameFilter...
[ "def restore_state(self):\n self._restore_input()\n self._restore_output()", "def restore_main_window(self, e):\n self.frame.max_from_tray(e)", "def restore(self):\n\t\tself.label[\"text\"] = \"ABRA CADABRA, Hello there!!!!!\"\n\t\tself.clearBtn[\"state\"] = \"normal\"\n\t\tself.restoreBtn[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update recent file list setting.
def updateRecentFileSettings(self, filename, delete=False): settings = QtCore.QSettings() files = list(settings.value(SETTING_RECENTFILELIST, [])) try: files.remove(filename) except ValueError: pass if not delete: files.insert(0, filename) ...
[ "def load_files_from_settings(self):\n files = self.settings.value('recent_files_list', [[]])[0]\n self.load_files(files)", "def __loadRecentFiles(self):\n rf = self.rsettings.value(Globals.recentNameFiles)\n if rf is not None:\n for f in rf:\n if QFileInfo(f)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run MDI Image Viewer application.
def main(): import sys app = QtGui.QApplication(sys.argv) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat) app.setOrganizationName(COMPANY) app.setOrganizationDomain(DOMAIN) app.setApplicationName(APPNAME) app.setWindowIcon(QtGui.QIcon(":/icon.png")) mainWin = MDIImageView...
[ "def open_image(self):\r\n image_viewer = {self.__LINUX_SYS: self.__LINUX_IMG_VWR,\r\n self.__WINDOWS_SYS: self.__WINDOWS_IMG_VWR,\r\n self.__APPLE_SYS: self.__APPLE_IMG_VWR}[self._SYS_PLTFRM]\r\n try:\r\n subprocess.run([image_viewer, self.__RC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The data in this frame as an `~astropy.coordinates.MoonLocation` class.
def moon_location(self): from .moon import MoonLocation cart = self.represent_as(CartesianRepresentation) return MoonLocation(x=cart.x, y=cart.y, z=cart.z)
[ "def GetLocationMatrix(self):\n\t\treturn self._LocationMatrix", "def location(self):\n return (self._moment.get(\"latitude\"), self._moment.get(\"longitude\"))", "def get_latlon():\r\n\t\tmagtag.url = get_data_source_url(api=\"forecast5\", location=secrets[\"openweather_location\"])\r\n\t\tmagtag.json_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a list without duplicates that is the intersection of s1 and s2
def intersect(s1, s2): # build a list containing common elements tmp = [] for e1 in s1: for e2 in s2: if e1 == e2: tmp.append(e1) break # drop the duplicates result = [] for e in tmp: if e not in result: result.append(e) ...
[ "def intersection(a,b):\n return [x for x in a if x in a and x in b]", "def intersection(a,b):\n return \"\".join(sorted(set(c for c in a+b)))", "def list_intersection(a, b):\n return [item for item in a if item in b]", "def intersect(seq1, seq2):\n ret = []\n for elem in seq1:\n if elem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to import_modules the forest plant records into the survey
def import_fauna(survey, species_list, infile, format, verbose=None): start = time.time() now = datetime.datetime.now() info_msg = ' Started the import_modules of fauna information {date}'. \ format(date=now.strftime("%Y-%m-%d %H:%M")) logging.info(info_msg) try: version = tools_lib....
[ "def db_imports():\n import_energy_data()", "def load_modules(self, cfg):\n \n if self.did_load_modules:\n return \n \n print('Loading Superglueflow with learned weights')\n #load trian flow\n weights = torch.load(cfg[\"trianflow\"].pretrained)\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the Selenium server
def startSelenium(self): os.chdir(r"../server/") args = self.buildServerStartCommand() self.startSelenium.config(state="disabled") self.seleniumServer = Popen(args) os.chdir(r"../scripts/") # Crude wait to give the server time to start time.sleep(5) self.s...
[ "def start_selenium_server():\n\n seleniumserver_path = find_selenium_server()\n if not seleniumserver_path:\n print('The file \"standalone-server-standalone-x.x.x.jar\" not found.')\n return\n\n cmd = ['java', '-jar', seleniumserver_path]\n subprocess.Popen(cmd, creationflags=subprocess.C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop the Selenium server
def stopSelenium(self): if self.seleniumServer != 0: self.seleniumServer.terminate() self.seleniumServer = 0 self.serverStatus(Event()) return if sys.platform[:5] == "linux": result = os.popen("ps x").readlines() for line in result:...
[ "def stop():\n driver.quit()\n result = status", "def stop_webserver():\r\n _webserver_do('stop')", "def stop_server():\n\n executeCmd(\"./bin/fteproxy --quiet --mode server --stop\")\n\n time.sleep(1)", "def stop_server(self):\n response = requests.post(self._build_url(\"stop\"))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the timeline of an user If since_id is set, will get new tweets instead of the whole timeline
def _get_all_timeline(self, screen_name, since_id=None): if since_id is not None: data = self._twitter_instance.statuses.user_timeline( screen_name=screen_name, count=200, trim_user=True, since_id=since_id) else: data = self._twitter_instance.statuses.user_timelin...
[ "def get_timeline(username, since_id=None, count=0):\n twitter = OAuth1Session(client_key=settings.CLIENT_KEY, client_secret=settings.CLIENT_SECRET,\n resource_owner_key=settings.ACCESS_TOKEN_KEY,\n resource_owner_secret=settings.ACCESS_TOKEN_SECRET)\n url...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute a sketch matrix of input matrix Note that l must be smaller than m
def fd_sketch(mat, l): # number of columns m = mat.shape[1] # Input error handling if l >= m: raise ValueError('Error: ell must be smaller than m') if l >= mat.shape[0]: raise ValueError('Error: ell must not be greater than n') def svd_sketch(mat_b): mat_u, vec_sigma, ...
[ "def lowrank_matricize(self):\n\n\t\tU, l = self.U, self.lmbda\n\t\tdim = self.ndim\n\t\t\n\t\tulst, vlst = [], []\n\t\tL = np.diag(l)\n\t\t\n\t\tfor n in range(dim):\n\t\t\tlst = list(range(n)) + list(range(n + 1, dim))\n\n\t\t\tutemp = [U[l] for l in lst]\n\t\t\tmat = khatrirao(tuple(utemp), reverse = True).conj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the squared Frobenius norm of a matrix
def squaredFrobeniusNorm(mat): return ln.norm(mat, ord = 'fro') ** 2
[ "def frobenius_norm(mat):\n return tf.linalg.trace(tf.matmul(mat, tf.transpose(mat)))", "def forbenius_norm(orig_matrix):\n\n col_Fnorms, row_Fnorms = ([], [])\n\n norm_of_matrix = 0\n no_rows = len(orig_matrix)\n no_cols = len(orig_matrix[0])\n\n\n for i in range(no_rows):\n for j in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies some necessary attributes from original function into decorated function.
def copy_decorator_attrs(original_func, decorated_obj): decorator_name = "to_static" decorated_obj.__name__ = original_func.__name__ decorated_obj._decorator_name = decorator_name decorated_obj.__wrapped__ = original_func decorated_obj.__doc__ = original_func.__doc__ if hasattr(original_func, "...
[ "def copyprops(original_fn, decorated_fn):\n if hasattr(original_fn, '_wsgiwapi_props'):\n decorated_fn._wsgiwapi_props = original_fn._wsgiwapi_props\n if hasattr(original_fn, '__doc__'):\n decorated_fn.__doc__ = original_fn.__doc__", "def include_original(dec):\n def meta_decorator(method)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds modules that ignore transcription. Builtin modules that have been ignored are collections, pdb, copy, inspect, re, numpy, logging, six
def ignore_module(modules: list[Any]): add_ignore_module(modules)
[ "def make_exclude():\n # Simple utility to make IPython paths more readably, we need a lot of\n # these below\n ipjoin = lambda *paths: pjoin('IPython', *paths)\n\n exclusions = [ipjoin('external'),\n ipjoin('quarantine'),\n ipjoin('deathrow'),\n # This...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorates a python function into a ASTStaticFunction object.
def decorated(python_func): nonlocal enable_fallback if enable_fallback is None: flag = os.environ.get("ENABLE_FALL_BACK", None) if flag == "True": enable_fallback = True else: # None or True enable_fallback = False StaticCla...
[ "def make_function_ast(src):\n return python.AstTree(ast.parse(src)).functions()[0]", "def transform(func):\n WalkoffTag.transform.tag(func)\n return func", "def wrap_python_function(cls, fn):\n def wrapped(sass_arg):\n # TODO enforce no units for trig?\n python_arg = sass_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a save prehook for `paddle.jit.save`. This hook will be executed before `save` function has been invoked. hook(layer, input_spec, configs) > None
def _register_save_pre_hook(hook): global _save_pre_hooks_lock global _save_pre_hooks _save_pre_hooks_lock.acquire() if hook not in _save_pre_hooks: _save_pre_hooks.append(hook) _save_pre_hooks_lock.release() return HookRemoveHelper(hook)
[ "def save(layer, path, input_spec=None, **configs):\n\n # 1. input build & check\n prog_translator = ProgramTranslator()\n is_prim_infer = core._is_fwd_prim_enabled() and core._is_bwd_prim_enabled()\n if not prog_translator.enable_to_static:\n raise RuntimeError(\n \"The paddle.jit.sav...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves input Layer or function as ``paddle.jit.TranslatedLayer`` format model, which can be used for inference or finetuning after loading. It will save the translated program and all related persistable variables of input Layer to given ``path`` . ``path`` is the prefix of saved objects, and the saved translated progra...
def save(layer, path, input_spec=None, **configs): # 1. input build & check prog_translator = ProgramTranslator() is_prim_infer = core._is_fwd_prim_enabled() and core._is_bwd_prim_enabled() if not prog_translator.enable_to_static: raise RuntimeError( "The paddle.jit.save doesn't wor...
[ "def save(self, path):\n if path is None:\n return\n\n logger.info(\"Save model to {}\".format(path))\n self.model.save_pretrained(path)\n self.tokenizer.save_pretrained(path)", "def save_model(self, path):\r\n torch.save(self.model.state_dict(), path)", "def save(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the encoding type that matches Python's native strings.
def _get_native_encoding_type(self): if sys.maxunicode == 65535: return 'UTF16' else: return 'UTF32'
[ "def get_encoding(byte_string):\n return detect(byte_string)['encoding']", "def get_encoding(str):\n lookup = ('utf_8', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213',\n 'shift_jis', 'shift_jis_2004','shift_jisx0213',\n 'iso2022jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_3',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the Natural Language API to the document, and collect the detected entities.
def add_entities(self, filename, locale, document): # Apply the Natural Language API to the document. entities = self.nl_detect(document) self.extract_and_save_entity_info(entities, locale, filename)
[ "def detect_document(path):\n from google.cloud import vision\n import io\n #image1 = Image.open('C:\\\\Users\\\\Gabija\\\\Documents\\\\BGN_hackathon\\\\Handwriting\\\\p.jpg').convert('1')\n #image1.save('C:\\\\Users\\\\Gabija\\\\Documents\\\\BGN_hackathon\\\\Handwriting\\\\p2.jpg')\n client = vision...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract information about an entity.
def extract_entity_info(self, entity): type = entity['type'] name = entity['name'].lower() metadata = entity['metadata'] salience = entity['salience'] wiki_url = metadata.get('wikipedia_url', None) return (type, name, salience, wiki_url)
[ "def entity_dict(entity):\n return {'id': entity.key().id(),\n 'url': entity.url,\n 'regex': entity.regex,\n 'phone': entity.phone,\n 'ctime': entity.ctime,\n 'mtime': entity.mtime,\n 'status': entity.status}", "def process_entity(self, entity):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output some info about the entities by querying the generated sqlite3 database.
def output_entity_data(self): with contextlib.closing(sqlite3.connect(self.db_filename)) as conn: # This query finds the number of times each entity name was # detected, in descending order by count, and returns information # about the first 15 names, including the files in...
[ "def info_database(self):\n for x in self.list_databases:\n print(\"%50s: %s\" %( x['definition'], x['entry_id']))", "def show_all():\n command = 'select * from entries'\n c = get_db()\n print c.execute(command).fetchall()", "def print_entities(self) -> None:\n for row in self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group a list into batches of size batch_size. >>> tuple(batch([1, 2, 3, 4, 5], batch_size=2)) ((1, 2), (3, 4), (5))
def batch(list_to_batch, batch_size=BATCH_SIZE): for i in range(0, len(list_to_batch), batch_size): yield tuple(list_to_batch[i:i + batch_size])
[ "def do_batches(alist: List, batch_size: int) -> List:\n for i in range(0, len(alist), batch_size):\n if i + batch_size <= len(alist):\n yield alist[i:i + batch_size]\n else:\n yield alist[i:len(alist)]", "def batcher(iterator, batchsize):\n it = iter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update All Running Statistics Table after raceday Parameter
def Update_Running_Stat(Dataset): for RARID, Race in Dataset.groupby('RARID'): Horse_ELO = [] HNAME_List = '('+str(Race['HNAME'].tolist())[1:-1]+')' JNAME_List = '('+str(Race['JNAME'].tolist())[1:-1]+')' SNAME_List = '('+str(Race['SNAME'].tolist())[1:-1]+')' Dist_ELO = 'HELO_...
[ "def update(self, df: pd.DataFrame):\n for stat in self._statistics.values():\n stat.update(df)", "def update_all():\r\n \r\n # Delete everything in summary table\r\n q_string = \"\"\"\r\n\tTRUNCATE summary;\r\n \"\"\"\r\n try:\r\n cursor.execute(q_string)\r\n except:\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct the rules for parallel processing to generate.
def construct_parallel_rules(self): for jobno, region in enumerate(self.get_regions()): params = dict(self.snakemake.params) params.setdefault("args", {}).update({"intervals": [region.human_readable()]}) output = { key: "job_out.{jobno}.d/out/tmp_{jobno}.{ext}...
[ "def construct_parallel_rules(self):\n for jobno, region in enumerate(self.get_regions()):\n params = dict(self.snakemake.params)\n params.setdefault(\"args\", {}).update({\"intervals\": [region.human_readable()]})\n output = {\n key: \"job_out.{jobno}.d/out/tm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates 'X of Y' style song names. May implement adjectives. If one adjective is chosen, another is highly likely.
def XofYGenerator(): adjective1 = "" adjective2 = "" noun1 = random.choice(nouns) noun2 = random.choice(nouns) # decide if it's going to be adjective-y if random.random() >= 0.625: if random.random() >= 0.5: adjective1 = random.choice(adjectives) if random.rando...
[ "def generateSongName(style=None):\n\n if style:\n generator = generators[style]\n else:\n generator = random.choice(generators.values())\n\n song_title = generator()\n return string.capwords(song_title)", "def generate_lexicon(with_tone=False, with_erhua=False):\n syllables = Ordered...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a Mahavishnu John band name. Optional style argument can be one of 'one word', 'x of y', or 'x y'
def generateSongName(style=None): if style: generator = generators[style] else: generator = random.choice(generators.values()) song_title = generator() return string.capwords(song_title)
[ "def makeChanName(bcateg, taucateg):\n chname = 'XX XX'\n\n ## b part \n if bcateg == 'bb':\n chname = 'bb'\n\n # space\n chname += ' '\n\n # tau part\n if taucateg == 'MuTau' or taucateg == 'mutau':\n chname += '#mu#tau_{h}'\n if taucateg == 'ETau' or taucateg == 'etau':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the unique user manager or create it.
def GetGlobalUserManager(*args, **kwargs): global global_user_manager if global_user_manager is None: global_user_manager = UserManager(*args, **kwargs) return global_user_manager
[ "def get_single_user():", "def get_or_create_user(github_user):\n try:\n return User.objects.get(login=github_user.login)\n except User.DoesNotExist:\n return create_user(github_user)", "def get_or_create_user(self, username, ldap_user):\n return User.objects.get_or_create(username=us...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the user with this uid or None.
def GetUserByUid(self, uid): return self.userDict[uid] if uid in self.userDict else None
[ "def get(uid):\n if uid in User.users:\n return User.users[uid]\n return None", "def user(self):\r\n try:\r\n return User.objects.get(username=self.username)\r\n except User.DoesNotExist:\r\n return None", "def get_single_user():", "def get_user(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store the user dict to the pathToExistingUserFile file.
def StoreUserList(self): with open(self.pathToExistingUserFile, 'w') as o: self.logger.debug('Update existing user file') for user in self.userDict.values(): o.write('{};{};{}\n'.format(user.firstName, user.lastName, ...
[ "def add_user(self, dict_user: dict):\n try:\n with open(self.path, 'a') as file:\n file.write('\\n[{user_name}]\\n'.format(**dict_user))\n file.write('\\tpath = /home/{user_name}/\\n'.format(**dict_user))\n file.write('\\tvalid users = {user_name}\\n'....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns first n rows
def head(self, n=5): col = self.copy() col.query.setLIMIT(n) return col.toPandas()
[ "def top(self, n):\n ttbl = self.order_cols()\n return ttbl.select(range(n+1))", "def head(data, n=3):\n print(data[:n])", "def head(iterable, n ):\n from itertools import islice\n return list(islice(iterable, n))", "def head_table(table: str, cur: psycopg2.extensions.cursor, n: int = 5...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the opcode, a list of values, and a list of locations.
def read(self) -> Tuple[int, List[int], List[int]]: # Read the current instruction. ins = self.mem[self.pc] self.pc += 1 # Determine the opcode. op = ins % 100 # Start two lists, for values and locations. vals: List[int] = [] locs: List[int] = [] #...
[ "def _get_ops(self):\n\n arglist = []\n arg = self.arg\n\n if arg is None:\n op = [(self.opcode, 0)]\n else:\n while arg > 0xff:\n arg = arg >> (8 * len(arglist))\n arglist.append((self.EXTENDED_ARG, arg & 0xff))\n\n arglist ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do these programs correctly compare inputs against values?
def test_input_comparisons() -> None: cases = [ ( # Using position mode, is the input equal to 8? [3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], [(-1, 0), (0, 0), (8, 1), (9, 0)], ), ( # Using position mode, is the input less than 8? [3, 9, ...
[ "def check_inputs(args):\n check_fail = False\n check_fail = check_sample(args.base, args.bSample)\n check_fail = check_sample(args.comp, args.cSample)\n return check_fail", "def test_program5_1(self):\n _, outputs = self.run_program([3, 0, 4, 0, 99], [17])\n self.assertListEqual(outputs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set params for different versions of emulator
def _set_params_by_version(self): pass
[ "def prepare_emulator(self):", "def test_set_system_param(self):\n pass", "def set_model_params(self, params):", "def _setSpecificEmulationOptions(self):\n\n # CondDB usage by L0Muon emulator\n if self.isPropertySet(\"IgnoreL0MuonCondDB\"):\n log.info(\"L0Muon emulator will use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update parent's window rectangle.
def _update_rect_from_parent_hwnd(self): if not self.parent_hwnd: return try: rect = win32gui.GetWindowRect(self.parent_hwnd) self.parent_x = rect[0] self.parent_y = rect[1] self.parent_width = rect[2] - rect[0] self.parent_height =...
[ "def redraw_window(cls):\n lives_font = pg.font.SysFont(Config.font_style, 30)\n score_font = pg.font.SysFont(Config.font_style, 30)\n Game.screen.blit(Game.bg_obj, (0,0))\n lives_label = lives_font.render('Lives: ', 1, 'yellow')\n heart_x = lives_label.get_rect().right + 10\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get child window info.
def _get_emulator_window_info(self, hwnd, wildcard): if self.child_name in win32gui.GetWindowText(hwnd): self.hwnd = hwnd self._update_rect_from_main_hwnd()
[ "def _get_window(self):\r\n pass", "def getspectralwindowinfo(self):\n return _ms.ms_getspectralwindowinfo(self)", "def user32_GetWindowInfo(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"hwnd\", \"pwi\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is emulator's window minimized.
def is_minimized(self): return win32gui.IsIconic(self.parent_hwnd)
[ "def is_visible() -> bool:\n return win.winfo_ismapped()", "def minimized(self) -> bool:\n return False", "def should_show_windows(self) -> bool:\n return self._should_show_windows", "def has_windows(self):\n\n if self.wins.log_win:\n return True\n\n return False", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get screen image from another image.
def get_image_from_image(image, ui_element): image = Image.fromarray(image) box = (ui_element.rect[0] * image.width, ui_element.rect[1] * image.height, ui_element.rect[2] * image.width, ui_element.rect[3] * image.height) screen = image.crop(box) return array(screen)
[ "def get_image(imageboard='danbooru', random=False, page=0):\n if(imageboard == 'danbooru'):\n result = danbooru.get_image(random=random,page=page)\n elif (imageboard == 'konachan'):\n result = konachan.get_image(random=random,page=page)\n elif(imageboard == 'yandere'):\n result = yand...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get color from screen.
def get_screen_color(self, positions, screen=None): screen = screen if screen is not None else self._get_screen() return [screen.getpixel(position) for position in positions]
[ "def get_color(self):\n color = askcolor(color=(self.g, self.r, self.b))\n grb = color[0]\n if grb != None:\n self.g = grb[0]\n self.r = grb[1]\n self.b = grb[2]", "def _getPixelColor(self):\n hdc = windll.user32.GetDC(0)\n\n cursor_pos = self._g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get (x,y) position inside screen rectangle. Using normal distribution position usually will be near rectangle center.
def get_position_inside_screen_rectangle(self, rect, mean_mod=2, sigma_mod=5): if rect[0] == rect[2] and rect[1] == rect[3]: return int(rect[0] * self.width), int(rect[1] * self.height) x, y = get_position_inside_rectangle(rect=rect, mean_mod=mean_mod, sigma_mod=sigma_mod) return int...
[ "def get_position(self):\n return self._rect.x, self._rect.y", "def getCenter(self):\n (left, top), (right, bottom) = self.getCoords()\n x = left + (right - left) / 2\n y = top + (bottom - top) / 2\n return x, y", "def _get_pos(self):\r\n \r\n return (self.rect.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get text from screen.
def get_screen_text(self, ui_element, screen=None): image = screen if screen is not None else self.get_screen_image(ui_element.rect) return get_text_from_image(image=image, threshold=ui_element.threshold, chars=ui_element.chars, save_file=ui_element.save_file, max_heig...
[ "def get_text(self):\n data = self.txtbox.get(1.0, END)\n print(data)", "def get_text(self):\n data = self.txtbox.get(1.0, END)\n test = self.txtbox.selection_get()", "def findText(self, screenText):\n return self.cursesScreen.test_find_text(screenText)", "def get_text(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if image is on screen.
def is_image_on_screen(self, ui_element, screen=None): rect = ui_element.rect if ui_element.rect else ui_element.button screen_image = screen if screen is not None else self.get_screen_image(rect) return is_images_similar(screen_image, ui_element.image, ui_element.threshold, save_file=ui_element...
[ "def is_onscreen(self):\n x, y = self.loc\n w, h = get_screen_size()\n\n screen = Rect(0, 0, w, h)\n actor = Rect(x, y, self.width, self.height)\n\n if screen.colliderect(actor):\n return True\n else:\n return False", "def is_onscreen(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if color in rects on screen is similar to given color.
def is_color_similar(self, color, rects, screen=None): positions = [self.get_position_inside_screen_rectangle(rect) for rect in rects] screen_colors = self.get_screen_color(positions=positions, screen=screen) similar = False for screen_color in screen_colors: similar = simila...
[ "def has_match(self, x, y, color):\n\n if self.pixel_color(x, y) == color:\n return True\n\n for x, y in self.pixels_around(x, y):\n if self.pixel_color(x, y) == color:\n return True\n return False", "def is_similar_color_rgb(color_a, color_b):\n differ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click inside button rectangle.
def click_button(self, button_rect, min_duration=0.1, max_duration=0.25): duration = random.uniform(min_duration, max_duration) r_sleep(duration) x, y = self.get_position_inside_screen_rectangle(button_rect) self.autoit_control_click_by_handle(self.parent_hwnd, self.hwnd, x=x, y=y) ...
[ "def click(widget, view_index=None):\n pos = center(widget, view_index)\n robouser.click(pos)", "def button_press(self, x, y, button):\n base._Widget.button_press(self, x, y, button)\n if button == 1:\n icon = self.get_icon_in_position(x, y)\n if icon is not None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close current opened app in emulator.
def close_current_app(self): raise NotImplementedError
[ "def call_manager_exit(self):\n self.manager.client.close_com()\n self.manager.close_frame()", "def quit_apps():\n os.system(\"osascript -e 'tell app \\\"{}\\\" to quit saving no'\".format(\n MAPLE_CLIENT_APP_NAME\n ))\n os.system(\"osascript -e 'tell app \\\"Automator\\\" to quit sa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to SQLite file at dbfile and yields parsed tokens for each row.
def stream(self, dbfile): # Connection to database file db = sqlite3.connect(dbfile) cur = db.cursor() cur.execute("SELECT Text FROM sections") count = 0 for section in cur: # Tokenize text tokens = Tokenizer.tokenize(section[0]) co...
[ "def parse(file, conn): #formerly main\n global cursor\n cursor = [] #CRITICALLY IMPORTANT\n #TODO: Investigate and understand what the removal of these two lines does to the program. The cursor\n #appears to stay behind after the parser function has completed and pollutes the next call to parser,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over each row in dbfile and writes parsed tokens to a temporary file for processing.
def tokens(dbfile): tokens = None # Stream tokens to temp working file with tempfile.NamedTemporaryFile( mode="w", suffix=".txt", delete=False ) as output: # Save file path tokens = output.name for row in RowIterator(dbfile): ...
[ "def stream(self, dbfile):\n\n # Connection to database file\n db = sqlite3.connect(dbfile)\n cur = db.cursor()\n\n cur.execute(\"SELECT Text FROM sections\")\n\n count = 0\n for section in cur:\n # Tokenize text\n tokens = Tokenizer.tokenize(section[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return all the recipient email addresses
def recipient_addrs(self): tos = self.msg.get_all('to', []) ccs = self.msg.get_all('cc', []) ccs = self.msg.get_all('bcc', []) resent_tos = self.msg.get_all('resent-to', []) resent_ccs = self.msg.get_all('resent-cc', []) recipient_addrs = email.utils.getaddresses(tos + bc...
[ "def email_recipients(self) -> str:\n return self['emailRecipients']", "def get_emails(notification_rec):\n # Use a set instead of list as there could be duplicates.\n ret = []\n\n for recipient in notification_rec.recipients.all():\n ret.append(recipient.email)\n return ret", "def sen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds NP (nounphrase) leaf nodes of a chunk tree.
def leaves(tree): for subtree in tree.subtrees(filter = lambda t: t.label()=='NP'): yield subtree.leaves()
[ "def find_non_clustered_leafs(module, task, msg):\n non_clustered_leafs = []\n cli = pn_cli(module)\n cli += ' cluster-show format cluster-node-1,cluster-node-2 '\n cli += ' no-show-headers '\n clustered_nodes = list(set(run_command(module, cli, task, msg).split()))\n\n for leaf in module.params['...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalises words to lowercase and stems and lemmatizes it.
def normalise(word, stemmer, lemmatizer): word = word.lower() #word = stemmer.stem(word) word = lemmatizer.lemmatize(word) return word
[ "def words_normalize(words):\n normalized_words = []\n for word in words:\n wnormalized = word.lower()\n normalized_words.append((wnormalized))\n return normalized_words", "def spacy_normalizer(text, lemma=None):\n if not str(text).isupper() or not str(text).endswith(\"S\") or not len(te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a trained BDT
def _train_bdt(): target, original = _generate() # Train a BDT to reweight print("train bdt") bdt = hep_ml.reweight.GBReweighter() bdt.fit(original=original, target=target) return bdt
[ "def getTrainingData(self):", "def load_bert_model(output_dir,\n bert_config_file='./model/uncased_L-12_H-768_A-12/bert_config.json',\n init_checkpoint='./tuned_model/model.ckpt-2461',\n num_labels=2,\n attn_processor_fn=None):\n bert_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the empirical fisher informatiom matrix of some distribution. For some distribution p, some M different ddimensional vector of distribution parameters theta, this function calculates the empirical fisher information matrix over k datapoints (x_i, y_i) using the pdf value at theta p(x_i, y_i; theta) and it's ...
def empirical_fisher(p, dp): M = p.shape[0] res = [] for m in range(M): res.append(empirical_fisher_(p[m], dp[m])) return np.array(res)
[ "def compute_fisher_info(p, eta):\n global p_map, eta_map\n\n # Stack columns of p for next step\n p_stack = numpy.repeat(p, eta.size).reshape(p.size, eta.size)\n # Compute Fisher matrix\n fisher = numpy.dot(eta_map, p_stack * p_map) - numpy.outer(eta, eta)\n\n return fisher", "def fisher_inform...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the empirical fisher informatiom matrix of some distribution. For some distribution p, some ddimensional vector of distribution parameters theta, this function calculates the empirical fisher information matrix over k datapoints (x_i, y_i) using the pdf value at theta p(x_i, y_i; theta) and it's derivate d/d...
def empirical_fisher_(p, dp): k = p.size try: d = dp.shape[1] except IndexError: sum = 0 for i in range(k): sum += 1 / p[i] ** 2 * dp[i] ** 2 return np.array([sum / k]) sum = np.zeros((d, d)) for i in range(k): sum += 1 / p[i] ** 2 * np.outer(dp[...
[ "def compute_fisher_info(p, eta):\n global p_map, eta_map\n\n # Stack columns of p for next step\n p_stack = numpy.repeat(p, eta.size).reshape(p.size, eta.size)\n # Compute Fisher matrix\n fisher = numpy.dot(eta_map, p_stack * p_map) - numpy.outer(eta, eta)\n\n return fisher", "def empirical_fis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the empirical normalised fisher informatiom matrix of some distribution. For some distribution p, some M different ddimensional vector of distribution parameters theta, this function calculates the empirical fisher information matrix over k datapoints (x_i, y_i) using the pdf value at theta p(x_i, y_i; theta...
def normalised_fisher(p, dp): M = p.shape[0] d = dp.shape[2] all_fishers = empirical_fisher(p, dp) fisher_trace = np.trace(np.sum(all_fishers, axis=0)) normalisation = d * M / fisher_trace return normalisation * all_fishers
[ "def compute_fisher_info(p, eta):\n global p_map, eta_map\n\n # Stack columns of p for next step\n p_stack = numpy.repeat(p, eta.size).reshape(p.size, eta.size)\n # Compute Fisher matrix\n fisher = numpy.dot(eta_map, p_stack * p_map) - numpy.outer(eta, eta)\n\n return fisher", "def fisher_inform...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Calculates the effective dimension of some distribution. For some distribution p, some M different ddimensional vector of distribution parameters theta, this function calculates the effective dimension over k datapoints (x_i, y_i) using the pdf value at theta p(x_i, y_i; theta) and it's derivate d/dtheta p(x_i, y_i...
def effective_dimension_(p, dp, gamma): M = p.shape[0] k = p.shape[1] d = dp.shape[2] f_hat = normalised_fisher(p, dp) mat = np.eye(d) + gamma * k / (2 * np.pi * np.log(k)) * f_hat # log(sqrt(det)) == log(det) / 2 rootdet = np.linalg.slogdet(mat)[1] / 2 # slogdet is more stable than det ...
[ "def estimate_marginal_entropies(X, k=3):\n marginal_entropies = np.zeros(X.shape[1])\n for i in range(X.shape[1]):\n marginal_entropies[i] = estimate_entropy(X[:,i], k)\n return marginal_entropies", "def pDpk(self, x, k):\n k = np.array(k)\n return 2*c*c*k/(self._omega*self._omega)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the Typed Factory with the field to check and the factory each value corresponds to
def __init__(self, field, valueToFactory): self.field = field self.valueToFactory = valueToFactory
[ "def __init__(self, schema_factory):\n self._initialize()\n self.factory = schema_factory\n self.Input = type(schema_factory.mock_input())\n self.Output = type(schema_factory.mock_output())\n self.model = self._load_model()", "def factory(self, field_type: type[Field]) -> FieldD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the factory to the mapping
def addFactory(self, value, factory): self.valueToFactory[value] = factory
[ "def add_factory(self, node_name, factory):\n self.factories[node_name] = factory", "def add_to_map(self):\n pass", "def set_factory(self, name, factory):\n self.factories[name] = factory", "def add(self, pattern, methods):\n self._mapping.append(RESTMapping(pattern, methods))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect to an SR560 Amplifier.
def connect(self, server, port): print('Connecting to "%s" on port "%s"...' %(server.name, port)) self.server = server self.ctx = server.context() self.port = port p = self.packet() p.open(port) # The following parameters match the default configuration of ...
[ "def sde_connect(self):\n if not self.sde_plugin:\n raise AlmException('Requires initialization')\n try:\n self.sde_plugin.connect()\n except APIError, err:\n raise AlmException('Unable to connect to SD Elements. Please review URL, id,'\n ' an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of user roles scoped to a project or domain.
def roles_for_user(request, user, project=None, domain=None): ksclient = get_admin_ksclient() if keystone.VERSIONS.active < 3: return ksclient.roles.roles_for_user(user, project) else: return ksclient.roles.list(user=user, domain=domain, project=project)
[ "async def get_user_roles_for_domain(\n request: Request, user: UserId, domain: Domain, nocache: bool = False\n) -> typing.Set[int]:\n domain_id = domain if type(domain) is int else Mappings.domain_id_for(domain)\n\n user_roles = await get_all_user_roles(request, user, nocache)\n # Look up the list of r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a role for a group on a domain or project.
def add_gp_role(request, role, group, domain=None, project=None): ksclient = get_admin_ksclient() return ksclient.roles.grant(role=role, group=group, domain=domain, project=project)
[ "def test_add_role_to_ldap_group(self):\n pass", "def role(self, role):\n groups = Group.objects.filter(name__contains=\"| role |\")\n if role is None: self.groups.remove(*groups); return\n if not role in MEMBER_ROLES.keys():\n raise ValueError(\"No role with identifyer '{0}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a role for a group on a domain or project.
def add_gp_role(request, role, group, domain=None, project=None): ksclient = get_admin_ksclient() return ksclient.roles.grant(role=role, group=group, domain=domain, project=project)
[ "def test_add_role_to_ldap_group(self):\n pass", "def role(self, role):\n groups = Group.objects.filter(name__contains=\"| role |\")\n if role is None: self.groups.remove(*groups); return\n if not role in MEMBER_ROLES.keys():\n raise ValueError(\"No role with identifyer '{0}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a given single role for a group from a domain or project.
def remove_group_role(request, role, group, domain=None, project=None): ksclient = get_admin_ksclient() return ksclient.roles.revoke(role=role, group=group, project=project, domain=domain)
[ "def removeRole(self, role):\n pass", "def remove_role(principal, role):\n try:\n if isinstance(principal, User):\n ppr = PrincipalRoleRelation.objects.get(\n user=principal, role=role, content_id=None, content_type=None)\n else:\n ppr = PrincipalRo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a role for a user on a tenant.
def add_user_role_to_tenant(request, project=None, user=None, role=None, group=None, domain=None): ksclient = get_admin_ksclient() if keystone.VERSIONS.active < 3: return ksclient.roles.add_user_role(user, role, project) else: return ksclient.roles.grant(role, user=u...
[ "def add_role_to_user_and_tenant(self, user_id, tenant_id, role_id):\n raise exception.NotImplemented()", "def add_user_role(channel, role, user):\n get_role_model(channel, role).group.user_set.add(user)", "def assign_role(user, role):\n return _assign_or_remove_role(user, role, \"assign_role_to_us...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a given single role for a user from a tenant.
def remove_user_role_frm_tenant(request, project=None, user=None, role=None, group=None, domain=None): ksclient = get_admin_ksclient() if keystone.VERSIONS.active < 3: return ksclient.roles.remove_user_role(user, role, project) else: return ksclient.roles.revoke(r...
[ "def remove_role_from_user_and_tenant(self, user_id, tenant_id, role_id):\n raise exception.NotImplemented()", "def remove_role(user, role):\n return _assign_or_remove_role(user, role, \"remove_role_from_user\")", "def delete_role_from_user(self, role, user):\r\n uri = \"users/%s/roles/OS-KSADM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To see all volumes transfers as an admin pass in a special
def transfer_list_cinder(request, detailed=True, search_opts=None): c_client = get_cinder_client() return [cinder.VolumeTransfer(v) for v in c_client.transfers.list( detailed=detailed, search_opts=search_opts)]
[ "def transfer_list(request, detailed=True, search_opts=None):\n c_client = cinderclient(request)\n try:\n return [VolumeTransfer(v) for v in c_client.transfers.list(\n detailed=detailed, search_opts=search_opts)]\n except cinder_exception.Forbidden as error:\n LOG.error(error)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot KDEs of the same feature and different classes together, so to compare different classes.
def plot_fits(kdes, features, classes, model_dir): values = np.linspace(-3, 2, 100) values = values.reshape(len(values), 1) for feature_name in features: f, ax = plt.subplots(figsize=(FIG_WIDTH, FIG_HEIGHT), dpi=DPI) ax.set_title(feature_name) plt.xlabel(feature_name, fontsize=10) ...
[ "def draw_data(X):\n dist = k_dist(X, k=3)\n plt.plot(dist)\n plt.text(700, dist[700], 'k=3')\n\n dist = k_dist(X, k=7)\n plt.plot(dist)\n plt.text(800, dist[700], 'k=7')\n\n dist = k_dist(X, k=13)\n plt.plot(dist)\n plt.text(900, dist[700], 'k=13')\n plt.title('k-dist plot')\n plt....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a single source document by slug.
def get(self, slug): try: return self._cache[slug] except KeyError: raise SourceFile.DoesNotExist
[ "def get_source(slug):\n from .models import SOURCES\n for cls in SOURCES:\n if cls.slug == slug:\n return cls", "def data_source_from_slug(slug: str) -> Optional[str]:\n if NAMESPACE_DELIMITER in slug:\n splitted = slug.split(NAMESPACE_DELIMITER)\n assert len(splitted) ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use dask to parallelize apply textacy Doc object creation from a dataframe
def dask_df_apply(df, text_col, textacy_col_name='textacy_doc', ncores=None, inplace=False): # If no number of cores to work with, default to max if not ncores: nCores = cpu_count() - 1 nCores # Partition dask dataframe and map textacy doc apply # Sometimes this fails because it can't infe...
[ "def extract_text_features(content_df: pd.DataFrame, pos_file: str, ents_file: str):\n\n start_time = time.time()\n\n # Prepare spaCy model and document pipeline\n nlp = spacy.load(\"en_core_web_lg\")\n review_ids, texts = content_df[\"reviewid\"].values, content_df[\"content\"].values\n doc_generato...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an entity and a textacy corpus, return a list of all the sentences in which this entity occurs
def list_of_entity_statements(corpus, entity): entity_sentences = [list(entity_statements(doc, entity=entity)) for doc in corpus if list(entity_statements(doc, entity=entity))] # If statement that removes null sentences entity_sentences =...
[ "def sentence_entities(sentence):\n\n\n nlp = Rating.nlp_load(sentence)\n return [(ent.text, ent.label_) for ent in nlp.ents]", "def get_texts_from_entities(entities):\n texts = []\n for e in entities:\n texts.append(e.text)\n return texts", "def get_entity_sentences(db: Session, d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function add specific point of timeseries to tree point, parent_ind, max_depth, tree, borders
def _add_point_to_tree(self, point, parent_ind, max_depth, tree, borders): # Stop if point is too deep. if point['depth'] > max_depth: return # Add point to tree curr_ts_name = self._timescales[point['depth']]['name'] tree.append(dict(short_name=point['name_short'], ...
[ "def set_root(self, df):\n\t\tif df.index.name == \"time\":\n\t\t\tpass\n\t\telse:\n\t\t\tdf = df.set_index(\"time\")\n\t\tdf.index = pandas.to_datetime(df.index)\t\t\n\t\tself.root = df\n\t\treturn", "def addParentAddedDagPathCallback(*args, **kwargs):\n \n pass", "def __insert_data(self, plotting=Fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Singleton to create to create the gui if it doesn't exist, or show if it does
def show_gui(): global INSTANCE if not INSTANCE: INSTANCE = TeamSelectorDialog() INSTANCE.show() return INSTANCE
[ "def show_gui(self):\n self.gui = Browser_GUI(self)", "def createGuiWorker() -> ghidra.util.worker.Worker:\n ...", "def init_main_window(self):\r\n gui_main = Tk()\r\n gui_main.geometry(f\"{WIDTH}x{HEIGHT}\")\r\n gui_main.resizable(width=False, height=False)\r\n gui_mai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``read_version()`` takes one or more file path components pointing to a Python source file to parse. The path components will be joined together with ``os.path.join()``, and then, if the path isn't absolute, the path to the directory containing the script calling ``read_version()`` will be prepended to the path. (No mo...
def read_version(*fpath, **kwargs): if not fpath: raise ValueError('No filepath passed to read_version()') fpath = os.path.join(*fpath) if not os.path.isabs(fpath): caller_file = inspect.stack()[1][0].f_globals["__file__"] fpath = os.path.join(os.path.dirname(caller_file), fpath) ...
[ "def get_version():\n with open(VERSION_FILE) as handle:\n lines = handle.read()\n result = VERSION_REGEX.search(lines)\n if result:\n return result.groupdict()[\"version\"]\n else:\n raise ValueError(\"Unable to determine __version__\")", "def get_version(file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a copy of this RequestParser with the same set of arguments
def copy(self): parser_copy = self.__class__(self.schema_class, self.argument_class, self.result_class) parser_copy.args = deepcopy(self.args) parser_copy.trim = self.trim parser_copy.bundel_errors = self.bundle_errors return parser_copy
[ "def copy(self):\n self.make_body_seekable()\n env = self.environ.copy()\n new_req = self.__class__(env)\n new_req.copy_body()\n return new_req", "def duplicate(self):\n return Params(copy.deepcopy(self.params), history=self.history, ext_vars=self.ext_vars)", "def creat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)
def get_exif_location(self, exif_data): lat = None lon = None alt = None gps_latitude = _get_if_exist(exif_data, 'GPS GPSLatitude') gps_latitude_ref = _get_if_exist(exif_data, 'GPS GPSLatitudeRef') gps_longitude = _get_if_exist(exif_data, 'GPS GPSLongitude') gps_...
[ "def get_latitude(filepath):\n image_file = open(filepath, 'rb')\n tags = exifread.process_file(image_file)\n return tags['GPS GPSLatitude']", "def get_gps_dms(exif_data):\n img_gps = {}\n lat_ref = ''\n lat = 0.0\n long_ref = ''\n long = 0.0\n try:\n for key in exif_data['GPSInf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clone a layer and pass its parameters through the function g.
def newlayer(layer, g): layer = copy.deepcopy(layer) layer.weight = torch.nn.Parameter(g(layer.weight)) layer.bias = torch.nn.Parameter(g(layer.bias)) return layer
[ "def _copy_layer(layer):\n if not isinstance(layer, tf.keras.layers.Layer):\n raise TypeError('layer is not a keras layer: %s' % str(layer))\n\n # pylint:disable=unidiomatic-typecheck\n if type(layer) == tf.compat.v1.keras.layers.DenseFeatures:\n raise ValueError('DenseFeatures V1 is not supported. '\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }