query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Unselect the specified `Card`.
def UnselectCard(self, card): self.selec.UnselectCard(card)
[ "def UnselectCard(self, card):\n if card in self.cards:\n self.cards.remove(card)\n card.Unselect()", "def UnselectAll(self):\n while len(self.cards) > 0:\n c = self.cards[0]\n self.UnselectCard(c)", "def deselect(self, *args):\n return _coin.SoSe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies every `Card` currently selected to `wx.TheClipboard`.
def CopySelected(self): # get the data data = [] for c in self.GetSelection(): data.append(c.Dump()) # create our own custom data object obj = wx.CustomDataObject("CardList") obj.SetData(str([json.dumps(d) for d in data])) # write the data to the cli...
[ "def PasteFromClipboard(self, pos=wx.DefaultPosition):\n if wx.TheClipboard.Open():\n # get data\n obj = wx.CustomDataObject(\"CardList\")\n wx.TheClipboard.GetData(obj)\n\n # don't use eval()! Use ast.literal_eval() instead\n data = [json.loads(d) for d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pastes every `Card` currently in `wx.TheClipboard`.
def PasteFromClipboard(self, pos=wx.DefaultPosition): if wx.TheClipboard.Open(): # get data obj = wx.CustomDataObject("CardList") wx.TheClipboard.GetData(obj) # don't use eval()! Use ast.literal_eval() instead data = [json.loads(d) for d in ast.litera...
[ "def CopySelected(self):\n # get the data\n data = []\n for c in self.GetSelection():\n data.append(c.Dump())\n\n # create our own custom data object\n obj = wx.CustomDataObject(\"CardList\")\n obj.SetData(str([json.dumps(d) for d in data]))\n\n # write th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of every `CardGroup` that contains `card`.
def GetContainingGroups(self, card): return [g for g in self.groups if card in g.GetMembers()]
[ "def get_same_month_cards(self, card: Card) -> List[Card]:\n object_month = card.month\n cards = []\n for field_card in self.cards:\n if field_card.month == object_month:\n cards.append(field_card)\n return cards", "def get_cards():\n Card = namedtuple('Car...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new `CardGroup` with `cards` as members.
def NewGroup(self, cards=[]): self.groups.append(card.CardGroup(label=len(self.groups), members=cards))
[ "def create_Deck(self):\n print('Creating Deck')\n for a in [\"Heart\", \"Diamond\", \"Club\", \"Spade\"]:\n for x in range(2, 11):\n self.cards.append(Card(a, x, x))\n self.cards.append(Card(a, \"A\", 11))\n self.cards.append(Card(a, \"J\", 10))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scroll in both direction so that `card` is fully in view.
def ScrollToCard(self, card): rect = card.GetRect() pt = rect.GetBottomRight() pt = self.CalcUnscrolledPosition(pt) self.ScrollToPoint(pt) # call rect again since we may have scrolled the window rect = card.GetRect() pt = rect.GetTopLeft() pt = se...
[ "def scrolls(self , scroll):\n if(scroll.scroll_y <= MainWindow.distance):\n operations.load_more() \n scroll.scroll_to(content.ArticlesContainerCopy.articles_container_copy.children[content.Data.limit] , padding=0, animate=True)", "def scroll(self, dx, dy):\n self._Camera_Rec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scroll in both direction so that `pt` is in view. `Deck.ScrollToCard` basically just calls this function twice, on a `Card`'s corner points.
def ScrollToPoint(self, pt): step = self.SCROLL_STEP # get the current rect in view, in pixels # coordinates relative to underlying content size view = [k * step for k in self.GetViewStart()] sz = self.GetClientSize() rect = wx.Rect(view[0], view[1], sz.width, sz.height)...
[ "def ScrollToCard(self, card):\n rect = card.GetRect()\n pt = rect.GetBottomRight()\n pt = self.CalcUnscrolledPosition(pt)\n self.ScrollToPoint(pt)\n\n # call rect again since we may have scrolled the window\n rect = card.GetRect()\n pt = rect.GetTopLeft() \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Arranges the selected cards according to `orient`.
def ArrangeSelection(self, orient): if orient == Deck.HORIZONTAL: self.HArrangeSelectedCards() elif orient == Deck.VERTICAL: self.VArrangeSelectedCards()
[ "def HArrangeSelectedCards(self):\n if len(self.GetSelection()) < 1: return\n\n # we unselect first so that we erase the selection rectangles correctly\n arrange = self.GetSelection()[:]\n self.UnselectAll() \n\n lefts = [c.GetRect().left for c in arrange]\n left = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same as `Deck.ArrangeSelection(Deck.HORIZONTAL)`. Arranges `Card`s in a horizontal row, to the right of the leftmost selected card.
def HArrangeSelectedCards(self): if len(self.GetSelection()) < 1: return # we unselect first so that we erase the selection rectangles correctly arrange = self.GetSelection()[:] self.UnselectAll() lefts = [c.GetRect().left for c in arrange] left = min(lefts) ...
[ "def ArrangeSelection(self, orient):\n if orient == Deck.HORIZONTAL:\n self.HArrangeSelectedCards()\n elif orient == Deck.VERTICAL:\n self.VArrangeSelectedCards()", "def horizontal(self):\n self.__arrangement = 'horizontal'\n return self", "def flip_horizontal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to every `Card.EVT_DELETE`.
def OnCardDelete(self, ev): card = ev.GetEventObject() self.cards.remove(card) self.UnselectCard(card)
[ "def DeleteSelected(self):\n # store the number of cards we're deleting to raise the event\n number = len(self.cards)\n \n # remember to use while instead of for, since in every\n # iteration self.cards is growing shorter\n while len(self.cards) > 0:\n c = self.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `SelectionManager.EVT_MGR_DELETE`, which is raised on every delete action. `Deck.DeleteSelected` calls every selected `Card`'s `Delete` method, which raises many `Card.EVT_DELETE`, and then raises only one `SelectionManager.EVT_MGR_DELETE` event.
def OnMgrDelete(self, ev): self.selec.Deactivate() # raise the event again, with event object = self event = self.DeleteEvent(id=wx.ID_ANY, number=ev.number) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event)
[ "def DeleteSelected(self):\n # store the number of cards we're deleting to raise the event\n number = len(self.cards)\n \n # remember to use while instead of for, since in every\n # iteration self.cards is growing shorter\n while len(self.cards) > 0:\n c = self.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `Card.EVT_REQUEST_VIEW` and raises `Deck.EVT_REQUEST_VIEW` with the same card as event object. The difference is that now a `Box` can `Bind` only once to `EVT_REQUEST_VIEW` events coming from this `Deck`, instead of having to bind to every individual card.
def OnCardRequest(self, ev): event = Deck.ReqViewEvent(id=wx.ID_ANY) event.SetEventObject(ev.GetEventObject()) self.GetEventHandler().ProcessEvent(event)
[ "def testF_view_request(self):\n _, _, requestIds = self._inject(15) # creates x docs/requests\n requestView = self._getViewResults(\"request\")\n self.assertEqual(len(requestView), 15)\n for reqView in requestView:\n self.failUnless(reqView[u\"key\"] in requestIds)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `wx.EVT_LEFT_DOWN` events on every `Card`'s child window.
def OnCardChildLeftDown(self, ev): self.UnselectAll() ev.Skip()
[ "def OnCardLeftDown(self, ev):\n card = ev.GetEventObject()\n\n # bring to front and select\n card.Raise()\n self.selec.SelectCard(card)\n\n # initiate moving\n self.CaptureMouse()\n self.Bind(wx.EVT_LEFT_UP, self.OnCardLeftUp)\n self.Bind(wx.EVT_MOTION, self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `wx.EVT_LEFT_DOWN` events from every `Card`.
def OnCardLeftDown(self, ev): card = ev.GetEventObject() # bring to front and select card.Raise() self.selec.SelectCard(card) # initiate moving self.CaptureMouse() self.Bind(wx.EVT_LEFT_UP, self.OnCardLeftUp) self.Bind(wx.EVT_MOTION, self.OnMovingCard) ...
[ "def OnCardLeftUp(self, ev):\n # terminate moving\n if self.on_motion:\n self.on_motion = False\n for c, orig, pos in self.moving_cards_pos:\n self.EraseCardRect(c, pos)\n \n if self.moving_cards_pos:\n for c, orig, pos in s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `wx.EVT_CHILD_FOCUS` from every `Card`.
def OnCardChildFocus(self, ev): self.UnselectAll() ev.Skip()
[ "def OnChildFocus( self, evt ):\n def SetSelection( ctrl ):\n try:\n ctrl.SetSelection( -1, -1 )\n except:\n pass\n \n ctrl = evt.GetEventObject()\n self.GetGrid().SetFocusedProperty( self )\n self.GetGrid().SetFocusedPropert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `wx.EVT_MOTION` events from `Card`s only while a `Card` is being clickdragged.
def OnMovingCard(self, ev): if ev.Dragging() and self.moving_cards_pos: # draw a rectangle while moving # order is important self.on_motion = True for c, orig, pos in self.moving_cards_pos: self.EraseCardRect(c, pos, refresh = False) ...
[ "def OnCardLeftDown(self, ev):\n card = ev.GetEventObject()\n\n # bring to front and select\n card.Raise()\n self.selec.SelectCard(card)\n\n # initiate moving\n self.CaptureMouse()\n self.Bind(wx.EVT_LEFT_UP, self.OnCardLeftUp)\n self.Bind(wx.EVT_MOTION, self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `wx.EVT_LEFT_UP` events from `Card`s only while a `Card` is being clickdragged.
def OnCardLeftUp(self, ev): # terminate moving if self.on_motion: self.on_motion = False for c, orig, pos in self.moving_cards_pos: self.EraseCardRect(c, pos) if self.moving_cards_pos: for c, orig, pos in self.moving_ca...
[ "def OnCardLeftDown(self, ev):\n card = ev.GetEventObject()\n\n # bring to front and select\n card.Raise()\n self.selec.SelectCard(card)\n\n # initiate moving\n self.CaptureMouse()\n self.Bind(wx.EVT_LEFT_UP, self.OnCardLeftUp)\n self.Bind(wx.EVT_MOTION, self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to `wx.EVT_MOUSE_CAPTURE_LOST` events from this object.
def OnMouseCaptureLost(self, ev): self.ReleaseMouse()
[ "def on_mouse_leave (self, event):\n\t\tprint 'mouse leave'", "def glfw_mouse_event_callback(self, window, xpos, ypos):\r\n xpos, ypos = int(xpos), int(ypos)\r\n dx, dy = self._calc_mouse_delta(xpos, ypos)\r\n\r\n if self.mouse_states.any:\r\n self._mouse_drag_event_func(xpos, ypos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to the "Paste" `wx.EVT_MENU` event from the context menu.
def OnPaste(self, ev): self.PasteFromClipboard(self.menu_position)
[ "def context_menu(self) -> None:\n menu = QMenu(self)\n if platform.system() == \"Darwin\":\n copy_keys = QKeySequence(Qt.CTRL + Qt.Key_C)\n paste_keys = QKeySequence(Qt.CTRL + Qt.Key_V)\n else:\n copy_keys = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_C)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to the "Insert Content" `wx.EVT_MENU` event from the context menu.
def OnInsertContent(self, ev): self.PlaceNewCard("Content", pos=self.menu_position)
[ "def contentsContextMenuEvent(self,ev):\n return", "def add_content(self):\n self._image_widget = self.menu.add_image(\n image_path=self.selector_modes()[1][\"image\"]\n )\n self._backstory_widget = self.menu.add_label(\n title=self.selector_modes()[1][\"backstory...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to the "Insert Header" `wx.EVT_MENU` event from the context menu.
def OnInsertHeader(self, ev): self.PlaceNewCard("Header", pos=self.menu_position)
[ "def add_menu_header(stdscr):\n main_header(stdscr)\n stdscr.addstr(SUB_MENU_START[Y], SUB_MENU_START[X], \"Add coin:\")\n stdscr.refresh()", "def changeHeader(self):\n col = self.table_widget.currentColumn()\n\n text, ok = QInputDialog.getText(self, \"Enter Header\", \"Header text:\")\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listens to the "Insert Image" `wx.EVT_MENU` event from the context menu.
def OnInsertImg(self, ev): self.PlaceNewCard("Image", pos=self.menu_position)
[ "def prepareContextMenu(self, position):\n # Get the selected item (only one, no multiple selection allowed):\n\t\tcurr = self.treeWidget.selectedItems()[0]\n\n\t\t# Get the corresponding name in the HDF5 file:\n\t\th5Item = self.HDF5File[str(curr.data(0, Qt.UserRole))]\n\t\tkey = str(h5Item.name)\n\n\t\t# C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paints a rectangle just big enough to encircle `card`.
def PaintCardRect(self, card, pos, thick=MOVING_RECT_THICKNESS, style=wx.SOLID, refresh=True): x, y, w, h = card.GetRect() rect = wx.Rect(pos[0], pos[1], w, h) rect = rect.Inflate(2 * thick, 2 * thick) self.PaintRect(rect, thick=thick, style=style, refresh=refresh)
[ "def draw(self):\n # check the current 'unit' value\n u = int(min(float(self.width) / 10.0, float(self.height) / 15.0))\n\n # draw the background\n self.canvas_before.add(Color(constant_color_background))\n self.canvas_before.add(Rectangle(0, 0, self.width, self.height))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Erases a rectangle drawn by PaintCardRect().
def EraseCardRect(self, card, pos, thick=MOVING_RECT_THICKNESS, refresh=True): # Brush is for background, Pen is for foreground x, y, w, h = card.GetRect() rect = wx.Rect(pos[0], pos[1], w, h) rect = rect.Inflate(2 * thick, 2 * thick) self.PaintRect(rect, thick=thick, sty...
[ "def deleteRectangle(self, canvas):", "def _erase (self):\n self.screen.blit_background (self._rect)", "def updateEraseRect(self):\n\t\treturn", "def updateEraseRect(self):\n\t\tx0, y0, x1, y1 = self.getMinMaxXY()\n\t\tx0 += self._xpos\n\t\ty0 += self._ypos\n\t\tx1 += self._xpos\n\t\ty1 += self._ypos\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dumps all the `Card`s' info in a `dict`.
def DumpCards(self): carddict = {} # we put the scrollbars at the origin, to get the real positions shown = self.IsShown() if shown: self.Hide() view_start = self.GetViewStart() self.Scroll(0, 0) # with the scrollbars at the origin, dump the cards ...
[ "def Dump(self):\n return {\"cards\": self.DumpCards(), \"groups\": self.DumpGroups()}", "def card_to_dict(card):\n jcard = {'id': card.id}\n if card.number:\n jcard['number'] = card.number\n if card.event:\n jcard['event'] = card.event\n if card.contracts:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dumps all the `CardGroup`s' info in a `dict`.
def DumpGroups(self): d = {} for g in self.groups: d[g.GetLabel()] = g.Dump() return d
[ "def Dump(self):\n return {\"cards\": self.DumpCards(), \"groups\": self.DumpGroups()}", "def group_info(self):\n groups = {}\n for group in self.store.keys():\n groups[group] = {\n 'metadata': self.store.get_storer(group).attrs.metadata,\n 'size': sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a `dict` with all the info contained in this `Deck`.
def Dump(self): return {"cards": self.DumpCards(), "groups": self.DumpGroups()}
[ "def DumpCards(self):\n carddict = {}\n\n # we put the scrollbars at the origin, to get the real positions\n shown = self.IsShown()\n if shown: self.Hide()\n view_start = self.GetViewStart()\n self.Scroll(0, 0)\n\n # with the scrollbars at the origin, dump the cards ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the selected `Card`s.
def GetSelection(self): return self.cards
[ "def get_selected_cards(self):\n\t\tselected_cards = []\n\t\tfor i in range(len(self.cards)):\n\t\t\tif self.cards[i] is not None:\n\t\t\t\tif self.cards[i]._state is CardState.SELECTED:\n\t\t\t\t\tselected_cards.append(i)\n\t\treturn selected_cards", "def cards(self):\n\t\treturn [btn.card for btn in self._butto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes `card` from the current selection.
def UnselectCard(self, card): if card in self.cards: self.cards.remove(card) card.Unselect()
[ "def UnselectCard(self, card):\n self.selec.UnselectCard(card)", "def discard(self, card):\n \n self.hand.pop(self.hand.index(card))\n self.cardList.append(card)", "def OnCardDelete(self, ev):\n card = ev.GetEventObject()\n self.cards.remove(card)\n self.UnselectCard...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unselects all cards. Be sure to call this method instead of `Unselect` on every card for proper cleanup.
def UnselectAll(self): while len(self.cards) > 0: c = self.cards[0] self.UnselectCard(c)
[ "def unselect_boxes(self):\n for box in self._sel_boxes:\n box.unselect()\n self._sel_boxes = []", "def UnselectCard(self, card):\n self.selec.UnselectCard(card)", "def UnselectCard(self, card):\n if card in self.cards:\n self.cards.remove(card)\n car...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select every `Card` in `group`.
def SelectGroup(self, group, new_sel=True): # in case we are coming from a card that's inside the group, # we may want to return to that card after selection ends # so we select the group but restore the last card after if self.last and self.last in group.GetMembers(): crd = ...
[ "def GetContainingGroups(self, card):\n return [g for g in self.groups if card in g.GetMembers()]", "def get_cards(self):\n for c in sorted(self.cards, key=lambda card: card.data['house']):\n for i in range(self.data['_links']['cards'].count(c.key)):\n c.data['is_legacy'] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes every `Card` currently selected.
def DeleteSelected(self): # store the number of cards we're deleting to raise the event number = len(self.cards) # remember to use while instead of for, since in every # iteration self.cards is growing shorter while len(self.cards) > 0: c = self.cards[-1] ...
[ "def delete_cards(self):\n self._stage = []\n self._hand = []", "def UnselectAll(self):\n while len(self.cards) > 0:\n c = self.cards[0]\n self.UnselectCard(c)", "def OnCardDelete(self, ev):\n card = ev.GetEventObject()\n self.cards.remove(card)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects next `Card` in the specified direction.
def SelectNext(self, direc, new_sel=False): nxt = self.GetParent().GetNextCard(self.last, direc) if nxt: self.SelectCard(nxt, new_sel)
[ "def GetNextCard(self, card, direc):\n # depending on the direction we compare a different side\n # of the cards, as well as get the points whose distance\n # we're going to calculate in a different way\n if direc == Deck.LEFT:\n side = lambda x: x.right\n getp1 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move all selected `Card`s.
def MoveSelected(self, dx, dy): for c in self.GetSelection(): self.GetParent().MoveCard(c, dx, dy)
[ "def move_all_cards(self, destination_list):\n\n self.client.fetch_json(\n '/lists/' + self.id + '/moveAllCards',\n http_method='POST',\n post_args = {\n \"idBoard\": destination_list.board.id,\n \"idList\": destination_list.id,\n })",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Plot the output versus continuous label figures for each session.
def save_output_vs_continuous_label_plot(self): for (trial, output_record), (_, label_record) in zip(self.trialwise_output_dict.items(), self.trialwise_continuous_label_dict.items()): complete_directory = self.complete_directory_to_save_plot() plot_filename = trial ...
[ "def _plot_separated_group(self, data, output, name):\n\n if len(data)>1:\n fig, ax = plt.subplots()\n ax.set_xlabel('Session number')\n ax.set_ylabel(name)\n temp = data.reset_index()\n l1 = self._plot_second_axis(ax, x = temp.session_number, y = temp.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The centering is done by directly average the shifted and weighted data.
def perform_centering(self): centered_data = self.data - np.repeat(self.mean_data[:, np.newaxis], self.data.shape[1], axis=1) + self.weight return centered_data
[ "def recalculate_center(self):\n # if we don't have any assigned inputs after this K-Means epoch, leave\n # the center where it was\n if self.assigned_inputs:\n new_center = []\n for dimension in xrange(len(self.assigned_inputs[0])):\n total = reduce(operato...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the Cn2 matrix. The jth column of the matrix records all the possible candidate to the jth rater. So that for the jth column, we can acquire all the possible unrepeated combination for the jth rater.
def generate_cnk_matrix(self): total = self.rator_number cnk_matrix = np.zeros((total - 1, total)) for column in range(total): cnk_matrix[:, column] = np.concatenate((np.where(self.combination_list[:, 0] == column)[0], np.whe...
[ "def generateMatrix(self, n: int) -> List[List[int]]:\n i, j, curr = 0, 0, 1\n direction = (0, 0)\n visited = set()\n matrix = [[1] * n for _ in range(n)]\n\n while len(visited) < n ** 2:\n y, x = i + direction[0], j + direction[1]\n if 0 <= y < n and 0 <= x < n and (y, x) not in visited:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the CCC for all the pairs from the combination list.
def calculate_paired_ccc(self): ccc = np.zeros((self.combination_list.shape[0])) for index in range(len(self.combination_list)): ccc[index] = self.calculate_ccc(self.data[self.combination_list[index, 0], :], self.data[self.combination_list[inde...
[ "def combo_sums(numlist, c):\n comb_list = combinations(numlist, c) \n comb_sums = [sum(comb) for comb in comb_list]\n return comb_sums\n # return list(set(comb_sums))", "def combo_sums(numlist, c):\n comb_list = combinations(numlist, c)\n comb_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the interrater CCC agreement.
def calculate_rator_wise_agreement(self): ccc_agreement = np.zeros(self.rator_number) for index in range(self.rator_number): ccc_agreement[index] = np.mean(self.ccc[self.cnk_matrix[:, index]]) return ccc_agreement
[ "def calculate_paired_ccc(self):\r\n ccc = np.zeros((self.combination_list.shape[0]))\r\n for index in range(len(self.combination_list)):\r\n ccc[index] = self.calculate_ccc(self.data[self.combination_list[index, 0], :],\r\n self.data[self.combinat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get landmark with dlib
def get_landmark(filepath, predictor): detector = dlib.get_frontal_face_detector() img = dlib.load_rgb_image(filepath) dets = detector(img, 1) for k, d in enumerate(dets): shape = predictor(img, d) t = list(shape.parts()) a = [] for tt in t: a.append([tt.x, tt.y]) lm =...
[ "def _get_landmarks(input, show_image=False):\n if type(input) == str:\n im = cv2.imread(input)\n if im.shape[2] == 3:\n image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n else:\n image = im\n elif isinstance(input, np.ndarray):\n im = input\n if im.shape[2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a user's unfollowing.
def get_unfollowers(followers: list, following: list): print (f'Followers: \n{followers}') print (f'Following: \n{following}')
[ "def unfollow_all_non_friends(self):\n followings = set(self.bot.following)\n unfollows = [x for x in followings if x not in self.friends.list]\n print(f'\\nGoing to unfollow {len(unfollows)} \"friends\".')\n for u in unfollows:\n self.unfollow(u)", "def unfollow(self, user)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns float of the number of seconds to wait before the request limit will no longer be exceeded. Also clears out any requests older than a minute. This makes an important asssumption that your program will actually honor the block time. If you don't, you will rocket past the courtesy rate limit. This is also the mos...
def _get_block_time_seconds(self): if self.rate_limit == 0: return 0 call_time = time.time() remove_time = call_time - 60 for idx, request in enumerate(self.request_log): if request >= remove_time: self.request_log = self.request_log[idx:] ...
[ "def _http_lock_wait_time(self):\r\n if self._http_lock_wait_begin == 0:\r\n return 0\r\n if self._http_lock_wait_end == 0:\r\n return time.time() - self._http_lock_wait_begin\r\n return self._http_lock_wait_end - self._http_lock_wait_begin", "def apply_limit(self, elaps...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts a new timestamp into the request log, marked block_time seconds in the future.
def _insert_request_to_log(self, block_time=0): if self.rate_limit == 0: return self.request_log.append(time.time() + block_time)
[ "def time_block(self, message):\n tic = time.time()\n yield\n dt = time.time() - tic\n log = app_log.info if dt > 1 else app_log.debug\n log(\"%s in %.2f ms\", message, 1e3 * dt)", "def _get_block_time_seconds(self):\n\n if self.rate_limit == 0:\n return 0\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the first (and only) doc in the result set, otherwise raises an exception.
def one(self): self._get() if len(self.result.get('collection', [])) != 1: raise ValueError('query did not return exactly one result') return self.result['collection'][0]
[ "def one(self):\n try:\n return self.results[0]\n except IndexError:\n return None", "def one(self, *args, **kwargs):\n bson_obj = self.find(*args, **kwargs)\n count = bson_obj.count()\n if count > 1:\n raise MultipleResultsFound(\"%s results fou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add one or many new matching filters to the filter set using kwargs. These aren't what go in the actual 'filter' URL parameter. These are used to match against the db, like name=Zoulas. This can be used to pass through any query parameters that do not have their own dedicated chainable methods.
def match(self, **kwargs): for filter_name, filter_value in kwargs.iteritems(): self._match[filter_name] = filter_value return self
[ "def filter(self, **kwargs):\n\n for filter_name, filter_value in kwargs.iteritems():\n self._filters[filter_name] = filter_value\n return self", "def set_filters(filter_list):", "def filter(self, _filter: \"Filter\" = None, **kwargs) -> \"Query\":\n\n if _filter and kwargs:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add one or many new matching filters to the filter set using kwargs.
def filter(self, **kwargs): for filter_name, filter_value in kwargs.iteritems(): self._filters[filter_name] = filter_value return self
[ "def match(self, **kwargs):\n\n for filter_name, filter_value in kwargs.iteritems():\n self._match[filter_name] = filter_value\n return self", "def addFilterSet(credentials, filter_set, **opts):\n\n return filter_set.save(credentials, new=True, **opts)", "def set_filters(filter_list)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that number of keys is equal to number of values in dict
def test_dict_key_value(): my_dict = {a: a ** 2 for a in range(7)} keys_count = my_dict.keys() values_count = my_dict.values() print(keys_count) print(values_count) assert len(keys_count) == len(values_count)
[ "def number_keys(a_dictionary):\n\n return len(a_dictionary)", "def check_results_dict_dimensions(result_dict: dict):\n check_list = []\n error_message = []\n for key, value in result_dict.items():\n error_message.append(f'{key}: {\", \".join([str(item) for item in value])}\\n')\n check_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use ruleset function on data and update data.
def apply_rule(self): def relative_to_absolute_coord(cur_x, cur_y): return [(cur_x + xi, cur_y + yi) for xi, yi in self.rule.indices] def coordinates_in_bounds(x, y): if min(x, y) < 0: return False if x >= self.data.shape[0]: return F...
[ "def PBH_RULE_update():\n\n pass", "def update_rules(self):\n print(\"Checking existing rules and subscription for (phedex) dataset %s \" %\n self.phedex_dataset)\n\n for block, sub in self.subscriptions.items():\n if 'request' not in sub:\n print(\"subscrip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the x/y position of the char
def get_char_position(char): i = CHAR_SET.index(char) if args.vertical: y = i % SHEET_HEIGHT x = i // SHEET_HEIGHT else: x = i % SHEET_WIDTH y = i // SHEET_WIDTH return (x, y)
[ "def get_char_coords(x, y):\n\n x = MARGIN_X + (x * (FONT_WIDTH + CHAR_SPACING_X))\n y = MARGIN_Y + (y * (FONT_HEIGHT + CHAR_SPACING_Y))\n\n return (x, y)", "def get_char(self, coord):\n\t\tassert coord.x >= 0 and coord.x < self.width, \"X Coordinate out of range\"\n\t\tassert coord.y >= 0 and coord.y < ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the x/y position of the char in pixels
def get_char_coords(x, y): x = MARGIN_X + (x * (FONT_WIDTH + CHAR_SPACING_X)) y = MARGIN_Y + (y * (FONT_HEIGHT + CHAR_SPACING_Y)) return (x, y)
[ "def get_char_position(char):\n i = CHAR_SET.index(char)\n if args.vertical:\n y = i % SHEET_HEIGHT\n x = i // SHEET_HEIGHT\n else:\n x = i % SHEET_WIDTH\n y = i // SHEET_WIDTH\n return (x, y)", "def pixel_to_position(self, pixel):\n x, y = pixel\n return y //...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a symbolic expression for the Meijer Gfunction encapsulated in the class.
def expression(self): x = Symbol('x', real=True) self.expr = hyperexpand(meijerg(self.a_p, self.b_q, self._const * x)) return self.expr
[ "def to_matlab_expr(self, data_name='X', function_name_prefix='') -> str:\n raise NotImplementedError()", "def expression(self):\n return", "def Expression(self) -> _n_4_t_1:", "def f(self):\r\n return self.g()", "def vm_impl_exp(self):\n\n def vm_impl(x):\n x = x.asnumpy()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Property used on composite classes to find all leafobjects. Just returns [self] for a leaf (this class)
def leafObjs(self): return [self]
[ "def get_leaf(self) -> List:\n if self.is_leaf():\n return [self]\n else:\n temp = []\n for tree in self.subtrees:\n temp += tree.get_leaf()\n return temp", "def _get_leaves(self):\n if self:\n leaves = []\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Property used on composite classes to find all leafobjects. Just returns [self] for a leaf (this class)
def leafObjs(self): return [self]
[ "def get_leaf(self) -> List:\n if self.is_leaf():\n return [self]\n else:\n temp = []\n for tree in self.subtrees:\n temp += tree.get_leaf()\n return temp", "def _get_leaves(self):\n if self:\n leaves = []\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse out organism name for each genome.
def _assembly_organism_name(self, refseq_archaea_assembly_file, refseq_bacteria_assembly_file, genbank_archaea_assembly_file, genbank_bacteria_assembly_file, output_organism_name_file): fout = open(output_organism_name_file, 'w') for assembly_file in [refseq_archaea_asse...
[ "def parse_organism(self):\n string = self.organism\n name, host_genus = \\\n basic.parse_names_from_record_field(string)\n self._organism_name = name\n self._organism_host_genus = host_genus", "def init_name_maps(self):\n map_1 = {}\n with open(self.organisms_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine taxonomic identifier for each assembly. Returns
def _assembly_to_tax_id(self, refseq_archaea_assembly_file, refseq_bacteria_assembly_file, genbank_archaea_assembly_file, genbank_bacteria_assembly_file): d = {} for assembly_file in [refseq_archaea_assembly_file, refseq_bacteria_assembly_file, ...
[ "def get_tax_id(species):\n species = species.replace(\" \", \"+\").strip()\n search = Entrez.esearch(term = species, db = \"taxonomy\", retmode = \"xml\")\n record = Entrez.read(search)\n return record['IdList'][0]", "def getTaxid(namelist): \n accessid = []\n for i in namelist:\n nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if species name is a valid binomial name.
def _valid_species_name(self, species_name, require_full=True, require_prefix=True): if species_name == 's__': return True, None # remove single quotes as sometimes given for # candidatus species names species_name = species_name.replace("'", "") # test for prefix ...
[ "def is_legal_bag_name(name):\n for pat in (BAGNAME04_RE, BAGNAME02_RE):\n if pat.match(name):\n return True\n return False", "def check_libname(name):\n # name = <str>\n # ch = <str>\n # return <int>|<bool>\n name = str(name)\n if not name:\n return 0\n return (na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produce standardized 7rank taxonomy file from NCBI taxonomy strings.
def standardize_taxonomy(self, ncbi_taxonomy_file, output_consistent): fout_consistent = open(output_consistent, 'w') failed_filters = set() for line in open(ncbi_taxonomy_file): line_split = line.strip().split('\t') gid = line_split[0] taxonomy = line_split...
[ "def create_taxonomy(genome_record):\n # Get taxonomy object from NCBI\n rec = Entrez.read(Entrez.elink(db='taxonomy', dbfrom='nuccore',\n id=genome_record.annotations['gi'],\n linkname='nuccore_taxonomy'))\n tax_id = rec[0]['LinkSetDb'][0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read NCBI taxonomy information and create summary output files.
def parse_ncbi_taxonomy(self, taxonomy_dir, refseq_archaea_assembly_file, refseq_bacteria_assembly_file, genbank_archaea_assembly_file, genbank_bacteria_assembly_file, output_prefix): # parse organism name self._assembly_organism_n...
[ "def collapse_tax(self):\n try:\n for level in self.inputs['levels']:\n if level != 'otu':\n for x in list(self.levels['otu']):\n self.levels[level][x] = _data_bin(self.otu[x], self.n[level], level + '_' + x)\n self.write_bioms()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger condition is matched or not. This class object should pass the data whenever received any data, so return True always.
def _is_condition(self, data): return True
[ "def _is_condition(self, data):\n ret = False\n current_charge_value = data[\"data\"][\"Charge Current\"][\"value\"]\n\n if self.pre_current_ is None:\n if self.high_current_ <= current_charge_value:\n ret = True\n self.pre_current_ = current_charge_value\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if battery voltage getting low and run over the limit of lowest voltage setting. _run_in_condition() method run if this method returns True.
def _is_condition(self, data): ret = False current_voltage = data["data"]["Battery Voltage"]["value"] if self.pre_voltage_ is None: if self.lowest_voltage_ > current_voltage: ret = True self.pre_voltage_ = current_voltage # If the battery volate ...
[ "def _is_condition(self, data):\n ret = False\n current_voltage = data[\"data\"][\"Battery Voltage\"][\"value\"]\n\n if self.pre_voltage_ is None:\n if self.full_voltage_ <= current_voltage:\n ret = True\n self.pre_voltage_ = current_voltage\n\n # If ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if battery voltage getting high and run over the limit of highest voltage setting. _run_in_condition() method run if this method returns True.
def _is_condition(self, data): ret = False current_voltage = data["data"]["Battery Voltage"]["value"] if self.pre_voltage_ is None: if self.full_voltage_ <= current_voltage: ret = True self.pre_voltage_ = current_voltage # If the battery volate r...
[ "def _is_condition(self, data):\n ret = False\n current_voltage = data[\"data\"][\"Battery Voltage\"][\"value\"]\n\n if self.pre_voltage_ is None:\n if self.lowest_voltage_ > current_voltage:\n ret = True\n self.pre_voltage_ = current_voltage\n\n # If...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if charge current getting high and run over the limit of highest current setting. _run_in_condition() method run if this method returns True.
def _is_condition(self, data): ret = False current_charge_value = data["data"]["Charge Current"]["value"] if self.pre_current_ is None: if self.high_current_ <= current_charge_value: ret = True self.pre_current_ = current_charge_value # If the ch...
[ "def within_limits(self):\n within_limit = True\n\n for lux_sensor, limit in self.lightlevel.items():\n current_lightlevel = float(self.get_state(lux_sensor))\n if current_lightlevel > limit:\n within_limit = False\n self.log('Light level beyond limi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a sentiment analysis request on text within a passed filename.
def analyze(movie_review_filename): client = language.LanguageServiceClient() with open(movie_review_filename, 'r') as review_file: # Instantiates a plain text document. content = review_file.read() print(content) document = types.Document( content=content, type=enu...
[ "def get_sentiment(text):\n response = requests.post(settings.SENTIMENT_ANALYSIS_API, data={\n 'text': text\n })\n return response.json()", "def _extract_sentiment_from_text(self, corpus_list, doc_name_to_id_dict):\n vader = SentimentIntensityAnalyzer()\n '''\n Go through the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate over all layout entity spaces.
def __iter__(self): return iter(self._layout_spaces.values())
[ "def handles(self):\n for entity_space in self:\n for handle in entity_space:\n yield handle", "def delete_all_entities(self):\n # Do not delete the entity space objects itself, just remove all entities from all entity spaces.\n for entity_space in self._layout_space...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get layout entity space by key.
def __getitem__(self, key): return self._layout_spaces[key]
[ "def get_entity_space(self, key):\n try:\n entity_space = self._layout_spaces[key]\n except KeyError: # create new entity space; internal exception\n entity_space = EntitySpace(self._entitydb)\n self.set_entity_space(key, entity_space)\n return entity_space", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate over all handles in all entity spaces.
def handles(self): for entity_space in self: for handle in entity_space: yield handle
[ "def iter_item_handles(self):\n raise(NotImplementedError())", "def system_iter(self):\n for system in self.systems:\n yield self.systems[system]", "def iter_sys(self):\n names = self.sys_names()\n for name in names:\n osys = self.GetOverallSys(name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get entity space by key or create new entity space.
def get_entity_space(self, key): try: entity_space = self._layout_spaces[key] except KeyError: # create new entity space; internal exception entity_space = EntitySpace(self._entitydb) self.set_entity_space(key, entity_space) return entity_space
[ "def space(self, datastore):\n return self._get('/datastores/%s/space' % base.getid(datastore),\n 'datastore')", "def getSpace(self, space):\n if isinstance(space, self.connection.space._ROOTOBJECTTYPE): #pylint: disable=W0212\n return space\n\n space = self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store tags in associated layout entity space.
def store_tags(self, tags): # AC1018: if entities have no owner tag (330) (thanks Autodesk for making the owner tag not mandatory), store # this entities in a temporary model space with layout_key = 0 # this will be resolved later in LayoutSpaces.repair_owner_tags() entity_space = self.g...
[ "def _store_tags(self):\n file = None\n try:\n rospy.loginfo(\"--- Storeing tags ---\")\n # open the file\n file = open(self.abs_file_path, \"w\")\n\n count = 0\n # write all entries in tag_list to the file\n for (y, x) in self.tag_list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write all entity spaces to stream. If keys is not None, write only entity spaces defined in keys.
def write(self, tagwriter, keys=None): layout_spaces = self._layout_spaces if keys is None: keys = set(layout_spaces.keys()) for key in keys: layout_spaces[key].write(tagwriter)
[ "def delete_all_entities(self):\n # Do not delete the entity space objects itself, just remove all entities from all entity spaces.\n for entity_space in self._layout_spaces.values():\n entity_space.delete_all_entities()", "def all_spaces(self, **kwargs):\n kwargs['_return_http_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete entity from associated layout entity space. Type of entity has to be DXFEntity() or inherited.
def delete_entity(self, entity): key = self._get_key(entity.tags) try: entity_space = self._layout_spaces[key] except KeyError: # ignore; internal exception pass else: entity_space.delete_entity(entity)
[ "def delete_entity(self, entity: 'DXFEntity') -> None:\n self.entitydb.delete_entity(entity) # 1. delete from drawing database\n self.unlink_entity(entity) # 2. unlink from entity space", "def delete(self, entity):", "def delete_entity_space(self, key):\n entity_space = self._layout_space...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete layout entity space key.
def delete_entity_space(self, key): entity_space = self._layout_spaces[key] entity_space.delete_all_entities() del self._layout_spaces[key]
[ "def delete_entity(self, entity):\n key = self._get_key(entity.tags)\n try:\n entity_space = self._layout_spaces[key]\n except KeyError: # ignore; internal exception\n pass\n else:\n entity_space.delete_entity(entity)", "def delete(self, entity):", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all entities from all layout entity spaces.
def delete_all_entities(self): # Do not delete the entity space objects itself, just remove all entities from all entity spaces. for entity_space in self._layout_spaces.values(): entity_space.delete_all_entities()
[ "def delete_all_entities(self) -> None:\n # noinspection PyTypeChecker\n for entity in list(self): # temp list, because delete modifies the base data structure of the iterator\n self.delete_entity(entity)", "def delete_entity_space(self, key):\n entity_space = self._layout_spaces[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The phylip path for the MSA used in RAxML
def get_raxml_phylippath(dir): nick = get_msa_nickname(dir) return dir + "/" + ap.params["geneid"] + SEP + nick + SEP + "raxml" + SEP + "phylip"
[ "def trip_path(self):\n path = [self.fm_town.alpha]\n path += [t.alpha for t in self.via]\n path += [self.to_town.alpha]\n return '-'.join(path)", "def triangular_prism():\n return nx.read_gml(abs_path('gml/triangular_prism.gml'))", "def getPath(self):\n # print(\"I'm serio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The fasta path for the MSA used in RAxML
def get_raxml_fastapath(dir): nick = get_msa_nickname(dir) return dir + "/" + ap.params["geneid"] + SEP + nick + SEP + "raxml" + SEP + "fasta"
[ "def get_raxml_phylippath(dir):\n nick = get_msa_nickname(dir)\n return dir + \"/\" + ap.params[\"geneid\"] + SEP + nick + SEP + \"raxml\" + SEP + \"phylip\"", "def get_sequence(msapath, taxa):\n fin = open(msapath, \"r\")\n for l in fin.readlines():\n if l.startswith(taxa):\n tokens...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the Newickformatted string with the cladogram of ancestral nodes for the given alignment method (msaid) and model (phylomodelid)
def get_anc_cladogram(con, msaid, phylomodelid): cur = con.cursor() sql = "select newick from AncestralCladogram where unsupportedmltreeid in" sql += "(select id from UnsupportedMlPhylogenies where almethod=" + \ msaid.__str__() + " and phylomodelid=" + phylomodelid.__str__() + ")" cur.execute(s...
[ "def make_cograph(tree, alist):\n #first find number of verts in cograph\n ord = 1\n for a in alist:\n ord = ord*a\n #initialize a matrix of the right size to be all 0s\n adj = np.zeros((ord, ord))\n #bubble up the tree\n #for each leaf\n leaves = get_vertices_of_depth(tree, len(alist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide a newick string, this method will reroot the tree based on the 'outgroup' setting.
def reroot_newick(con, newick): cur = con.cursor() dendrotree = Tree() dendrotree.read_from_string(newick, "newick") sql = "select shortname from Taxa where id in (select taxonid from GroupsTaxa where groupid in (select id from TaxaGroups where name='outgroup'))" cur.execute(sql) rrr = cur.fetch...
[ "def init_newick(self):\n with open(self.newick_path, 'r') as myfile:\n tree_str = myfile.read().replace('\\n', '')\n\n return tree_str", "def ntree_parse(matchObj, argv):\n tree = matchObj.group('tree')\n out = ''\n out += \"\\n\\\\begin{tikzpicture}[nodes={circle, draw}]\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
msapath must be a phylip file. Returns the seed sequence.
def get_sequence(msapath, taxa): fin = open(msapath, "r") for l in fin.readlines(): if l.startswith(taxa): tokens = l.split() return tokens[1]
[ "def genRandomSequence(numDoms):\n files = ls(DATAPATH)\n f = list(open(DATAPATH + choice(files)))[1::2]\n sequence = choice(f).strip()\n sequence.translate(None, '-')\n \n starts, ends, seqs = findDomains(sequence, hmmfile)\n if len(starts) < numDoms:\n return genRandomSequence(numDoms)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the hashtable; key = site, value = tuple of (mlstate, mlpp)
def get_site_ml(con, ancid, skip_indels=True): cur = con.cursor() sql = "select site, state, pp from AncestralStates" + ancid.__str__() cur.execute(sql) x = cur.fetchall() site_tuple = {} site_mlpp = {} for ii in x: site = int(ii[0]) state = ii[1] pp = float(ii[2]) ...
[ "def build_site_dictionary(page, site):\n headers, cookies, word_count = get_data_from(page)\n return {\n \"site_name\": site,\n \"headers\": headers,\n \"cookies\": cookies,\n \"word_count\": word_count}", "def get_sites_dict(self):\n return self.sites_to_dict(self.bsites...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a bin number for the given probability value.
def binForProb(p): return int(p / 0.05)
[ "def probForBin(b):\n x = float(b * 5) / float(100)\n if x == 1.00:\n return x\n return x + 0.025", "def get_bin(self, n):\n return self.bins[n]", "def bin_index(self, x):\n return int((np.log(x / self.bin_start[0]) / np.log(self.ratio)))", "def binVal( self, val ):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the probability value for the floor of the given bin number
def probForBin(b): x = float(b * 5) / float(100) if x == 1.00: return x return x + 0.025
[ "def binForProb(p):\n return int(p / 0.05)", "def _opacity_from_bin(bin, n_bins):\n if n_bins <= 0:\n return 0.35\n ratio = bin/float(n_bins)\n if ratio < 0.2:\n return 0.6\n elif ratio < 0.3:\n return 0.85\n elif ratio < 0.5:\n return 1.0\n return 1.0", "def bin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
By default the start/end are the boundaries of the provided sequence. But if motifs were provided, then we'll refine these boundaries.
def get_boundary_sites(seq, start_motif=None, end_motif=None): startsite = 1 endsite = seq.__len__() if start_motif is not None: if start_motif.__len__() > 0: for i in range(0, seq.__len__()): # print "258:", i, seq[i], start_motif[0] if seq[i] == start_m...
[ "def find_breakpoint_variants(my_bg, ref, supercontig, start, end,\n min_overlap=70, max_anchors=10000, max_steps=100000,\n skip_ambiguous=False, buf_len=300):\n if start >= end:\n raise RuntimeError(\"start must be < end\")\n\n # find_ranges woul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps the codon sequence to the aligned (may contain indels) aa seq.
def align_codon_to_aaseq(con, aaseq, codonseq): # ret is the returned aligned codon sequence. ret = "" """Quick sanity check: do we have exactly 3x more nucleotides than amino acids?""" aa_no_indels = re.sub("-", "", aaseq) nt_no_indels = re.sub("-", "", codonseq) """Remove stop codon in the ...
[ "def translateSequence(seq):\n aa = ''\n for i in xrange(0, len(seq), 3):\n aa += codonToAminoAcid(seq[i:i+3])\n return aa", "def align_sequences(dic):\n\n\t##Function to calculate the percentaje of identity inside the alignment function\n\tdef calculate_identity(seqA, seqB):\n\t\t\"\"\"\n\t\tReturns the pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Throws exception when class have not been initialised before Otherwise, returns blockchain instance
def get_instance(): if not Blockchain.__instance__: raise Exception("Create your instance of blockchain with the respective properties") return Blockchain.__instance__
[ "def __init__(self):\n this = _coin.new_SoError()\n try:\n self.this.append(this)\n except __builtin__.Exception:\n self.this = this", "def __init__(self, database, contract=None, hash_value=None, testnet=False):\n self.db = database\n self.keychain = KeyCh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return latest block in chain
def get_latest_block(self): return self.chain[-1]
[ "def last_block(self) -> Block:\r\n return self.chain[-1]", "def get_last_block(self):\r\n\r\n if len(self.chain) == 0:\r\n return None\r\n return self.chain[-1]", "def latest_block(self) -> Block:\n return Block(self.latest_header(), self.chain[self.latest_header()])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds transactions into the waiting list to be mined
def add_new_pending_data(self, transaction): self.pending_transaction.append(transaction)
[ "def _cleanup_pending_transactions(self) -> None:\n queue = self._last_update_for_transactions\n timeout = datetime.timedelta(0, self.pending_transaction_timeout)\n\n if len(queue) == 0:\n return\n\n next_date, next_item = queue[0]\n\n while datetime.datetime.now() - ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mining the transaction in pending list. Increases difficulty if successful mine in time shorter than set POW. Miners reward (not implemented yet) Implementation depends on individual. For demo convenience, loops through all pending transaction in one call
def mine_pending_data(self, miner_pk): while len(self.pending_transaction) != 0: transaction = self.pending_transaction[0] mine_block = Block(transaction, self.get_latest_block().hash) start_time = time() mine_block.mine_block(self.__class__.difficulty) ...
[ "def mine(self):\n if not self.unconfirmedTxs: # No txs to add?...\n return False # Then there's no need to work\n\n lastBlock = self.lastBlock # Grb the most recent block\n\n newBlock = Block(index=lastBlock.index + 1, # A new block\n txs=self.unconfirmedT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify if blockchain is valid Returns true if valid and false otherwise
def verify_blockchain(self): for i in range(1, len(self.chain)): current_block = self.chain[i] previous_block = self.chain[i - 1] if current_block.previous_hash != previous_block.hash: return False return True
[ "def is_valid():\n \n # Get validity of blockchain\n is_valid = blockchain.is_chain_valid(blockchain.chain)\n \n if is_valid: response = {'message': 'The blockchain is valid!'}\n else: response = {'message': 'Error, the blockchain is invalid!'}\n\n return jsonify(response), 200", "def is_chai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to print entire blockchain for demo
def print_blockchain(self): print() print("-------------") print("Blockchain") print("-------------") for block in self.chain: print("-------------") print('Timestamp: ', block.timestamp) print('Transaction: ', block.transaction.__dict__) ...
[ "def view_blockchain():\n response = {\n 'chain': blockchain_db_manager.get_all_blocks(),\n 'length': blockchain_db_manager.get_length(),\n 'header': 'Full chain'\n }\n return render_template('chain.html', data=response)", "async def view_blockchain(request: Request):\n response =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a link to test case failure in GitHub The link generated by this method should highlight the line that caused the failure
def github_testlog_failure_link(self, test_log): try: if self._mediator.ci_environment == 'asc': # for Molecule repo of repos pattern path = "/{}/{}/tree/{}/molecule/{}/{}".format(self._repo_fork, self._rep...
[ "def github_link(self):\n if self.test_type == TestType.commit:\n test_type = 'commit'\n test_id = self.commit\n else:\n test_type = 'pull'\n test_id = self.pr_nr\n\n return \"{base}/{test_type}/{test_id}\".format(\n base=self.fork.github_u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a GitHub compare link based on the attributes of this facade This method would be used when we have a last known pass of a given test We are making an assumption that the attributes of this facade are children of upstream_fork and upstream_base GitHub docs describing the compare view
def github_diff_link(self, upstream_fork, upstream_base): try: # These variable names are the language used by GitHub base_fork = self._repo_fork base = self._git_sha head_fork = upstream_fork compare = upstream_base path = "/{}/{}/compare/...
[ "def github_link(self):\n if self.test_type == TestType.commit:\n test_type = 'commit'\n test_id = self.commit\n else:\n test_type = 'pull'\n test_id = self.pr_nr\n\n return \"{base}/{test_type}/{test_id}\".format(\n base=self.fork.github_u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to pull the failure line number from failure output
def _get_line_number_from_failure_output(self, test_log): regex = re.escape(test_log.test_file) + r':(\d+)' match = re.search(regex, test_log.full_failure_output) if match: return match.group(1) else: return ''
[ "def parse_error_output(err) -> tuple:\n lines = err.split(\"\\n\")[:-1]\n line = lines[5]\n split_line = line.split(\" \")\n cursor_line = int(split_line[-3][:-1])\n cursor_column = int(split_line[-1][:-1])\n return cursor_line, cursor_column", "def __find_first_error_line(log_lines: typing.Lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A helper to remove .git from the end of a string if found
def _strip_git_ending(self, path): if path.endswith('.git'): path = path[:-4] return path
[ "def remove_ext(string):\n index = string.rfind('.')\n if index == -1 or index == len(string)-1:\n print(\"Can't find extension in {}!\".format(string))\n return None\n return string[:index]", "def remove_filext(s):\n dot = s.rfind('.')\n if dot == -1: return s\n return s[:dot]", "def _strip_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the git_sha found by this facade
def git_sha(self): return self._git_sha
[ "def repo_get_sha(self):\n raise NotImplementedError('Method repo_get_sha not implemented in root(Git*Connect) class')", "def get_commit_hash():\n return git.Repo().head.object.hexsha", "def sha(self):\n return self._commit.hexsha", "def get_git_commit_sha():\n\n return os.getenv(\"GIT_COMMI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inexact Augmented Lagrange Multiplier
def inexact_augmented_lagrange_multiplier(X, lmbda=.01, tol=1e-3, maxiter=100, verbose=True): Y = X norm_two = norm(Y.ravel(), 2) norm_inf = norm(Y.ravel(), np.inf) / lmbda dual_norm = np.max([norm_two, norm_inf]) Y = Y / dual_norm A = np.zeros(Y.shape) ...
[ "def GN_integral(b2, Lspan, a_dB, gam, f_ch, rs, roll_off, power, Nch, model_param):\n alpha_lin = a_dB / 20.0 / np.log10(np.e) # Conversion in linear units 1/km\n min_FWM_inv = np.power(10, model_param['min_FWM_inv'] / 10) # Conversion in linear units\n n_grid = model_param['n_grid']\n n_grid_min = m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if item is missing (not cloned)
def _is_missing(self, item): dst = '{}/{}'.format(self._data_list[item], item.split()[0]) if os.path.exists(dst): # it is bare repo who knows return 'maybe' return True
[ "def _missing(self, album):\n item_mbids = [x.mb_trackid for x in album.items()]\n if len(list(album.items())) < album.albumtotal:\n # fetch missing items\n # TODO: Implement caching that without breaking other stuff\n album_info = hooks.album_for_mbid(album.mb_albumid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a AddressBase. If the source is not None, then object is initialized from values of the source object.
def __init__(self, source=None): self.address_list = list(map(Address, source.address_list)) if source else []
[ "def test_BridgeAddressBase_init(self):\n self.assertIsNone(self.bab._address)\n self.assertIsNone(self.bab._fingerprint)", "def __init__(self, strict=True, **kwargs):\n # Only common fields are allowed to be set directly.\n unknown_fields = set(kwargs).difference(self.BASE_FIELD_IDS)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge the list of addresses from acquisition with our own.
def _merge_address_list(self, acquisition): address_list = self.address_list[:] for addendum in acquisition.get_address_list(): for address in address_list: equi = address.is_equivalent(addendum) if equi == IDENTICAL: break ...
[ "def nextAddresses(self) -> List[ghidra.program.model.address.Address]:\n ...", "def __init__(self, source=None):\n self.address_list = list(map(Address, source.address_list)) if source else []", "def merge(self, acquisition):\n # TODO what to do with sort and display?\n self._merge_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Access the parameters of the layer. Returns Tuple[mygrad.Tensor] The slope of the PReLU unit.
def parameters(self): return (self.slope,)
[ "def LMLgrad(self):\n return _core.CGPkronSum_LMLgrad(self)", "def LMLgrad(self):\n return _core.CGPSum_LMLgrad(self)", "def LMLgrad_X(self):\n return _core.CGPbase_LMLgrad_X(self)", "def gradient(self):\n gx, gy = np.gradient(self.zz)\n return gx, gy", "def GetGradient(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that get_metrics goes ok with an empty index
def test_get_default_metrics_empty(tmpdir): config = DEFAULT_CONFIG tmppath = pathlib.Path(tmpdir) / ".wily" config.cache_path = str(tmppath) tmppath.mkdir() (tmppath / "git").mkdir() with open(tmppath / "git" / "index.json", "w+") as f: f.write("[]") metrics = cache.get_default_met...
[ "def test_get_metrics(self):\n pass", "def test_metrics_are_zero(self):\n verifier = MetricVerifier(self.impalad_test_service)\n verifier.verify_metrics_are_zero()", "def testGetEmptyStats(self):\n print(\"--------------\")\n print(\"Test getStats with no elements\")\n expected...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether the user has permission for this report.
def check_permission(self, user): return user.has_perms(self.permissions_required)
[ "def authorized_for_reports(self):\n if self.userobject is None:\n return False\n return self.userobject.may_run_reports or self.userobject.superuser", "def is_user_granted_access(self, context):\n\n # Does user not have VIEW permissions?\n if not context['has_view_permissio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }