signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def __del__(self): | self.setInactive()<EOL> | disconnect from output and error signal | f7772:c0:m6 |
def contextMenuEvent(self, event): | menu = QtWidgets.QTextEdit.createStandardContextMenu(self)<EOL>w = QtWidgets.QWidget()<EOL>l = QtWidgets.QHBoxLayout()<EOL>w.setLayout(l)<EOL>e = QtWidgets.QSpinBox()<EOL>e.setRange(<NUM_LIT:1>, <NUM_LIT>)<EOL>e.setValue(self.MAXLINES)<EOL>e.valueChanged.connect(self.document().setMaximumBlockCount)<EOL>l.addWidget(QtW... | Add menu action:
* 'Show line numbers'
* 'Save to file' | f7772:c0:m7 |
def findMenu(self, title): | <EOL>for menu in self.iter_menus():<EOL><INDENT>if menu.title() == title:<EOL><INDENT>return menu<EOL><DEDENT>for innerMenu in self.iter_inner_menus(menu):<EOL><INDENT>if innerMenu.title() == title:<EOL><INDENT>return innerMenu<EOL><DEDENT><DEDENT><DEDENT> | find a menu with a given title
@type title: string
@param title: English title of the menu
@rtype: QMenu
@return: None if no menu was found, else the menu with title | f7774:c0:m3 |
def insertMenuBefore(self, before_menu, new_menu): | if isinstance(before_menu, string_types):<EOL><INDENT>before_menu = self.findMenu(before_menu)<EOL><DEDENT>before_action = self.actionForMenu(before_menu)<EOL>new_action = self.insertMenu(before_action, new_menu)<EOL>return new_action<EOL> | Insert a menu after another menu in the menubar
@type: before_menu QMenu instance or title string of menu
@param before_menu: menu which should be after the newly inserted menu
@rtype: QAction instance
@return: action for inserted menu | f7774:c0:m5 |
def addEmptyTab(self, text='<STR_LIT>'): | tab = self.defaultTabWidget()<EOL>c = self.count()<EOL>self.addTab(tab, text)<EOL>self.setCurrentIndex(c)<EOL>if not text:<EOL><INDENT>self.tabBar().editTab(c)<EOL><DEDENT>self.sigTabAdded.emit(tab)<EOL>return tab<EOL> | Add a new DEFAULT_TAB_WIDGET, open editor to set text if no text is given | f7775:c0:m3 |
def _mkAddBtnVisible(self): | if not self._btn_add_height:<EOL><INDENT>self._btn_add_height = self.cornerWidget().height()<EOL> | Ensure that the Add button is visible also when there are no tabs | f7775:c0:m4 |
def removeTab(self, tab): | if not isinstance(tab, int):<EOL><INDENT>tab = self.indexOf(tab)<EOL><DEDENT>return super(FwTabWidget, self).removeTab(tab)<EOL> | allows to remove a tab directly -not only by giving its index | f7775:c0:m8 |
def tabText(self, tab): | if not isinstance(tab, int):<EOL><INDENT>tab = self.indexOf(tab)<EOL><DEDENT>return super(FwTabWidget, self).tabText(tab)<EOL> | allow index or tab widget instance | f7775:c0:m9 |
def addGlobals(self, g): | self.editor._globals.update(g)<EOL>pass<EOL> | g ==> {name:description,...} | f7776:c0:m1 |
def contextMenuEvent(self, event): | menu = QtWidgets.QPlainTextEdit.createStandardContextMenu(self)<EOL>mg = self.getGlobalsMenu()<EOL>a0 = menu.actions()[<NUM_LIT:0>]<EOL>menu.insertMenu(a0, mg)<EOL>menu.insertSeparator(a0)<EOL>menu.addSeparator()<EOL>a = QtWidgets.QAction('<STR_LIT>', menu)<EOL>l = self.codeEditor.lineNumbers<EOL>a.setCheckable(True)<E... | Add menu action:
* 'Show line numbers'
* 'Save to file' | f7776:c1:m9 |
def saveToFile(self): | filename = self.codeEditor.dialog.getSaveFileName()<EOL>if filename and filename != '<STR_LIT:.>':<EOL><INDENT>with open(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(self.toPlainText())<EOL><DEDENT>print('<STR_LIT>' % filename)<EOL><DEDENT> | Save the current text to file | f7776:c1:m10 |
def toPlainText(self): | txt = QtWidgets.QPlainTextEdit.toPlainText(self)<EOL>return txt.replace('<STR_LIT:\t>', '<STR_LIT:U+0020>')<EOL> | replace [tab] with 4 spaces | f7776:c1:m11 |
def _syncHScrollBar(self, val): | self.verticalScrollBar().setValue(val)<EOL> | Synchronize the view with the code editor | f7776:c2:m1 |
def _updateNumbers(self, linenumers): | b = self.blockCount()<EOL>c = b - linenumers<EOL>if c > <NUM_LIT:0>:<EOL><INDENT>for _ in range(c):<EOL><INDENT>self.setFocus()<EOL>storeCursorPos = self.textCursor()<EOL>self.moveCursor(<EOL>QtGui.QTextCursor.End,<EOL>QtGui.QTextCursor.MoveAnchor)<EOL>self.moveCursor(<EOL>QtGui.QTextCursor.StartOfLine,<EOL>QtGui.QText... | add/remove line numbers | f7776:c2:m2 |
def save(self): | self.saveAs(self._path)<EOL> | save to file - override last saved file | f7777:c0:m4 |
def saveAs(self, path): | if not path:<EOL><INDENT>path = self._dialogs.getSaveFileName(filter='<STR_LIT>')<EOL><DEDENT>if path:<EOL><INDENT>self._setPath(path)<EOL>with open(str(self._path), '<STR_LIT:wb>') as stream:<EOL><INDENT>writer = csv.writer(stream)<EOL>table = self.table()<EOL>for row in table:<EOL><INDENT>writer.writerow(row)<EOL><DE... | save to file under given name | f7777:c0:m6 |
def _textToTable(self, text, separator='<STR_LIT:\t>'): | table = None<EOL>if text.startswith('<STR_LIT>') or text.startswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>t = eval(text)<EOL>if isinstance(t, list) and isinstance(t[<NUM_LIT:0>], list):<EOL><INDENT>table = t<EOL><DEDENT><DEDENT>except SyntaxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not table:<EOL><INDENT>tabl... | format csv, [[...]], ((..)) strings to a 2d table | f7777:c0:m17 |
def __init__(self, title, argdict, stayOpen=False, saveLoadButton=False,<EOL>savePath='<STR_LIT>', loadPath='<STR_LIT>',<EOL>introduction=None, unpackDict=False): | QtWidgets.QDialog.__init__(self)<EOL>self._wantToClose = False<EOL>self.unpackDict = unpackDict<EOL>if stayOpen:<EOL><INDENT>self.finished.connect(self.stayOpen)<EOL><DEDENT>self.setWindowTitle(title)<EOL>layout = QtWidgets.QGridLayout()<EOL>self.setLayout(layout)<EOL>if introduction:<EOL><INDENT>pass<EOL><DEDENT>self.... | ==================== =========================================================
Argument Comment
==================== =========================================================
title title of the window
argdict a dict of all arguments to set up:
e.g... | f7781:c0:m0 |
def show(self): | self.btn_done.clicked.connect(lambda: self.btn_done.setText('<STR_LIT>'))<EOL>QtWidgets.QDialog.show(self)<EOL> | if the dialog is showed again or is not started with exec_
naming the done button to 'update' make more sense
because now the dialog doesn't block (anymore) | f7781:c0:m7 |
def check(self): | for name, valItem, dtype in self.values:<EOL><INDENT>val = valItem.text()<EOL>if dtype:<EOL><INDENT>try:<EOL><INDENT>val = dtype(val)<EOL><DEDENT>except:<EOL><INDENT>msgBox = QtWidgets.QMessageBox()<EOL>msgBox.setText(<EOL>'<STR_LIT>' %<EOL>(name, str(dtype)))<EOL>msgBox.exec_()<EOL><DEDENT><DEDENT>self.args[name] = va... | check whether all attributes are setted and have the right dtype | f7781:c0:m10 |
def done(self, result): | self._geometry = self.geometry()<EOL>QtWidgets.QDialog.done(self, result)<EOL> | save the geometry before dialog is close to restore it later | f7781:c0:m12 |
def stayOpen(self): | if not self._wantToClose:<EOL><INDENT>self.show()<EOL>self.setGeometry(self._geometry)<EOL><DEDENT> | optional dialog restore | f7781:c0:m13 |
def saveState(self): | <INDENT>p = PathStr(path).join('<STR_LIT>')<EOL>with open(p, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(self.opts))<EOL><DEDENT><DEDENT>return self.opts<EOL> | save options to file 'dialogs.conf' | f7782:c0:m1 |
def restoreState(self, state): | <INDENT>p = PathStr(path).join('<STR_LIT>')<EOL>with open(p, '<STR_LIT:r>') as f:<EOL><DEDENT>self.opts.update(state)<EOL> | restore options from file 'dialogs.conf' | f7782:c0:m2 |
def getSaveFileName(self, *args, **kwargs): | if '<STR_LIT>' not in kwargs:<EOL><INDENT>if self.opts['<STR_LIT>']:<EOL><INDENT>if self.opts['<STR_LIT>']:<EOL><INDENT>kwargs['<STR_LIT>'] = self.opts['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT>fname = QtWidgets.QFileDialog.getSaveFileName(**kwargs)<EOL>if fname:<EOL><INDENT>if type(fname) == tuple:<EOL><INDENT>if not f... | analogue to QtWidgets.QFileDialog.getSaveFileNameAndFilter
but returns the filename + chosen file ending even if not typed in gui | f7782:c0:m3 |
def highlightBlock(self, text): | <EOL>cb = self.currentBlock()<EOL>p = cb.position()<EOL>text = str(self.document().toPlainText()) + '<STR_LIT:\n>'<EOL>highlight(text, self.lexer, self.formatter)<EOL>for i in range(len(str(text))):<EOL><INDENT>try:<EOL><INDENT>self.setFormat(i, <NUM_LIT:1>, self.formatter.data[p + i])<EOL><DEDENT>except IndexError:<EO... | Takes a block, applies format to the document.
according to what's in it. | f7783:c1:m1 |
def setWidget(self, widget, index=<NUM_LIT:0>, row=None,<EOL>col=<NUM_LIT:0>, rowspan=<NUM_LIT:1>, colspan=<NUM_LIT:1>): | if row is None:<EOL><INDENT>row = self.currentRow<EOL><DEDENT>self.currentRow = max(row + <NUM_LIT:1>, self.currentRow)<EOL>if index > len(self.widgets) - <NUM_LIT:1>:<EOL><INDENT>self.widgets.append(widget)<EOL><DEDENT>else: <EOL><INDENT>self.layout.removeWidget(self.widgets[index])<EOL>self.widgets[index] = widget<E... | Add new widget inside dock, remove old one if existent | f7788:c0:m5 |
def makeWidget(self): | opts = self.param.opts<EOL>t = opts['<STR_LIT:type>']<EOL>if t == '<STR_LIT:int>':<EOL><INDENT>defs = {<EOL>'<STR_LIT:value>': <NUM_LIT:0>, '<STR_LIT>': None, '<STR_LIT>': None, '<STR_LIT:int>': True,<EOL>'<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': False,<EOL>'<STR_LIT>': False, '<STR_LIT>': '<... | Return a single widget that should be placed in the second tree column.
The widget must be given three attributes:
========== ============================================================
sigChanged a signal that is emitted when the widget's value is changed
value a function that returns the value
setValue a... | f7793:c0:m1 |
def updateDisplayLabel(self, value=None): | if value is None:<EOL><INDENT>value = self.param.value()<EOL><DEDENT>opts = self.param.opts<EOL>if isinstance(self.widget, QtWidgets.QAbstractSpinBox):<EOL><INDENT>text = asUnicode(self.widget.lineEdit().text())<EOL><DEDENT>elif isinstance(self.widget, QtWidgets.QComboBox):<EOL><INDENT>text = self.widget.currentText()<... | Update the display label to reflect the value of the parameter. | f7793:c0:m7 |
def widgetValueChanging(self, *args): | <EOL>self.param.sigValueChanging.emit(self.param, args[-<NUM_LIT:1>])<EOL> | Called when the widget's value is changing, but not finalized.
For example: editing text before pressing enter or changing focus. | f7793:c0:m9 |
def selected(self, sel): | ParameterItem.selected(self, sel)<EOL>if self.widget is None:<EOL><INDENT>return<EOL><DEDENT>if sel and self.param.writable():<EOL><INDENT>self.showEditor()<EOL><DEDENT>elif self.hideWidget:<EOL><INDENT>self.hideEditor()<EOL><DEDENT> | Called when this item has been selected (sel=True) OR deselected (sel=False) | f7793:c0:m10 |
def limitsChanged(self, param, limits): | ParameterItem.limitsChanged(self, param, limits)<EOL>t = self.param.opts['<STR_LIT:type>']<EOL>if t == '<STR_LIT:int>' or t == '<STR_LIT:float>':<EOL><INDENT>self.widget.setOpts(bounds=limits)<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT> | Called when the parameter's limits have changed | f7793:c0:m13 |
def treeWidgetChanged(self): | ParameterItem.treeWidgetChanged(self)<EOL>if self.widget is not None:<EOL><INDENT>tree = self.treeWidget()<EOL>if tree is None:<EOL><INDENT>return<EOL><DEDENT>tree.setItemWidget(self, <NUM_LIT:1>, self.layoutWidget)<EOL>self.displayLabel.hide()<EOL>self.selected(False)<EOL><DEDENT> | Called when this item is added or removed from a tree. | f7793:c0:m15 |
def optsChanged(self, param, opts): | <EOL>ParameterItem.optsChanged(self, param, opts)<EOL>w = self.widget<EOL>if '<STR_LIT>' in opts:<EOL><INDENT>self.updateDefaultBtn()<EOL>if isinstance(w, (QtWidgets.QCheckBox, ColorButton)):<EOL><INDENT>w.setEnabled(not opts['<STR_LIT>'])<EOL><DEDENT><DEDENT>if isinstance(self.widget, SpinBox):<EOL><INDENT>if '<STR_LI... | Called when any options are changed that are not
name, value, default, or limits | f7793:c0:m17 |
def addClicked(self): | self.param.addNew()<EOL> | Called when "add new" button is clicked
The parameter MUST have an 'addNew' method defined. | f7793:c3:m2 |
def addChanged(self): | if self.addWidget.currentIndex() == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>typ = asUnicode(self.addWidget.currentText())<EOL>self.param.addNew(typ)<EOL>self.addWidget.setCurrentIndex(<NUM_LIT:0>)<EOL> | Called when "add new" combo is changed
The parameter MUST have an 'addNew' method defined. | f7793:c3:m3 |
def addNew(self, typ=None): | raise Exception("<STR_LIT>")<EOL> | This method is called when the user has requested to add a new item to the group. | f7793:c4:m0 |
def setAddList(self, vals): | self.setOpts(addList=vals)<EOL> | Change the list of options available for the user to add to the group. | f7793:c4:m1 |
def nameChanged(self, name): | pass<EOL> | Pass method, otherwise name is additionally set in tableView | f7793:c7:m1 |
def blockSignals(self, boolean): | pgParameter.blockSignals(self, boolean)<EOL>try:<EOL><INDENT>item = self.items[<NUM_LIT:0>]<EOL>if item.key:<EOL><INDENT>item.key.blockSignals(boolean)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT> | add block/unblock of keyboard shortcut | f7796:c0:m2 |
def replaceWith(self, param): | i = self.parent().children().index(self)<EOL>p = self.parent()<EOL>self.parent().removeChild(self)<EOL>p.insertChild(i, param)<EOL>self = param<EOL> | replace this parameter with another | f7796:c0:m5 |
def read(*paths): | try:<EOL><INDENT>f_name = os.path.join(*paths)<EOL>with open(f_name, '<STR_LIT:r>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT><DEDENT>except IOError:<EOL><INDENT>print('<STR_LIT>' % f_name)<EOL>return '<STR_LIT>'<EOL><DEDENT> | Build a file path from *paths* and return the contents. | f7801:m0 |
def template_to_base_path(template, google_songs): | if template == os.getcwd() or template == '<STR_LIT>':<EOL><INDENT>base_path = os.getcwd()<EOL><DEDENT>else:<EOL><INDENT>template = os.path.abspath(template)<EOL>song_paths = [template_to_filepath(template, song) for song in google_songs]<EOL>base_path = os.path.dirname(os.path.commonprefix(song_paths))<EOL><DEDENT>ret... | Get base output path for a list of songs for download. | f7803:m0 |
@classmethod<EOL><INDENT>def _connect(cls):<DEDENT> | return connect(**cls._conn_info)<EOL> | Connects to vertica.
:return: a connection to vertica. | f7818:c0:m2 |
@classmethod<EOL><INDENT>def _get_node_num(cls):<DEDENT> | with cls._connect() as conn:<EOL><INDENT>cur = conn.cursor()<EOL>cur.execute("<STR_LIT>")<EOL>return cur.fetchone()[<NUM_LIT:0>]<EOL><DEDENT> | Executes a query to get the number of nodes in the database
:return: the number of database nodes | f7818:c0:m3 |
def _query_and_fetchall(self, query): | with self._connect() as conn:<EOL><INDENT>cur = conn.cursor()<EOL>cur.execute(query)<EOL>results = cur.fetchall()<EOL><DEDENT>return results<EOL> | Creates a new connection, executes a query and fetches all the results.
:param query: query to execute
:return: all fetched results as returned by cursor.fetchall() | f7818:c0:m5 |
def _query_and_fetchone(self, query): | with self._connect() as conn:<EOL><INDENT>cur = conn.cursor()<EOL>cur.execute(query)<EOL>result = cur.fetchone()<EOL><DEDENT>return result<EOL> | Creates a new connection, executes a query and fetches one result.
:param query: query to execute
:return: the first result fetched by cursor.fetchone() | f7818:c0:m6 |
def as_bytes(bytes_or_text, encoding='<STR_LIT:utf-8>'): | if isinstance(bytes_or_text, _six.text_type):<EOL><INDENT>return bytes_or_text.encode(encoding)<EOL><DEDENT>elif isinstance(bytes_or_text, bytes):<EOL><INDENT>return bytes_or_text<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' %<EOL>(bytes_or_text,))<EOL><DEDENT> | Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.
Returns:
A `bytes` object.
Raises:
TypeError: If `bytes_or_text` is not a binary or ... | f7825:m0 |
def as_text(bytes_or_text, encoding='<STR_LIT:utf-8>'): | if isinstance(bytes_or_text, _six.text_type):<EOL><INDENT>return bytes_or_text<EOL><DEDENT>elif isinstance(bytes_or_text, bytes):<EOL><INDENT>return bytes_or_text.decode(encoding)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % bytes_or_text)<EOL><DEDENT> | Returns the given argument as a unicode string.
Args:
bytes_or_text: A `bytes`, `str, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.
Returns:
A `unicode` (Python 2) or `str` (Python 3) object.
Raises:
TypeError: If `bytes_or_text` is not a binary... | f7825:m1 |
def as_str_any(value): | if isinstance(value, bytes):<EOL><INDENT>return as_str(value)<EOL><DEDENT>else:<EOL><INDENT>return str(value)<EOL><DEDENT> | Converts to `str` as `str(value)`, but use `as_str` for `bytes`.
Args:
value: A object that can be converted to `str`.
Returns:
A `str` object. | f7825:m2 |
def getTypeName(data_type_oid, type_modifier): | if data_type_oid == VerticaType.BOOL:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.INT8:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.FLOAT8:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.CHAR:<EOL><INDENT>return "<STR_LIT>"<... | Returns the base type name according to data_type_oid and type_modifier | f7826:m7 |
def getIntervalRange(data_type_oid, type_modifier): | if data_type_oid not in (VerticaType.INTERVAL, VerticaType.INTERVALYM):<EOL><INDENT>raise ValueError("<STR_LIT>".format(data_type_oid))<EOL><DEDENT>if type_modifier == -<NUM_LIT:1>: <EOL><INDENT>if data_type_oid == VerticaType.INTERVALYM:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.IN... | Extracts an interval's range from the bits set in its type_modifier | f7826:m8 |
def getIntervalLeadingPrecision(data_type_oid, type_modifier): | interval_range = getIntervalRange(data_type_oid, type_modifier)<EOL>if interval_range in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif interval_range in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><IND... | Returns the leading precision for an interval, which is the largest number
of digits that can fit in the leading field of the interval.
All Year/Month intervals are defined in terms of months, even if the
type_modifier forbids months to be specified (i.e. INTERVAL YEAR).
Similarly, all Day/Time intervals are defined a... | f7826:m9 |
def getPrecision(data_type_oid, type_modifier): | if data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>if type_modifier == -<NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>return ((type_modifier - <NUM_LIT:4>) >> <NUM_LIT:16>) & <NUM_LIT><EOL><DEDENT>elif data_type_oid in (VerticaType.TIME, VerticaType.TIMETZ,<EOL>VerticaType.TIMESTAMP, VerticaType.TIMESTAMPTZ,<... | Returns the precision for the given Vertica type with consideration of
the type modifier.
For numerics, precision is the total number of digits (in base 10) that can
fit in the type.
For intervals, time and timestamps, precision is the number of digits to the
right of the decimal point in the seconds portion of the t... | f7826:m10 |
def getScale(data_type_oid, type_modifier): | if data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>return <NUM_LIT:15> if type_modifier == -<NUM_LIT:1> else (type_modifier - <NUM_LIT:4>) & <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Returns the scale for the given Vertica type with consideration of
the type modifier. | f7826:m11 |
def getDisplaySize(data_type_oid, type_modifier): | if data_type_oid == VerticaType.BOOL:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif data_type_oid == VerticaType.INT8:<EOL><INDENT>return <NUM_LIT:20><EOL><DEDENT>elif data_type_oid == VerticaType.FLOAT8:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>return getPrecisi... | Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form. | f7826:m12 |
def connect(**kwargs): | return Connection(kwargs)<EOL> | Opens a new connection to a Vertica database. | f7828:m0 |
def __init__(self, host, port, backup_nodes, logger): | self._logger = logger<EOL>self.address_deque = deque()<EOL>self._append(host, port)<EOL>if not isinstance(backup_nodes, list):<EOL><INDENT>err_msg = '<STR_LIT>'<EOL>self._logger.error(err_msg)<EOL>raise TypeError(err_msg)<EOL><DEDENT>for node in backup_nodes:<EOL><INDENT>if isinstance(node, string_types):<EOL><INDENT>s... | Creates a new deque with the primary host first, followed by any backup hosts | f7828:c0:m0 |
@classmethod<EOL><INDENT>def ensure_dir_exists(cls, filepath):<DEDENT> | directory = os.path.dirname(filepath)<EOL>if directory != '<STR_LIT>' and not os.path.exists(directory):<EOL><INDENT>try:<EOL><INDENT>os.makedirs(directory)<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT> | Ensure that a directory exists
If it doesn't exist, try to create it and protect against a race condition
if another process is doing the same. | f7829:c0:m1 |
def date_parse(s): | s = as_str(s)<EOL>if s.endswith('<STR_LIT>'):<EOL><INDENT>raise errors.NotSupportedError('<STR_LIT>'.format(s))<EOL><DEDENT>return date(*map(lambda x: min(int(x), <NUM_LIT>), s.split('<STR_LIT:->')))<EOL> | Parses value of a DATE type.
:param s: string to parse into date
:return: an instance of datetime.date
:raises NotSupportedError when a date Before Christ is encountered | f7830:m4 |
def nextset(self): | <EOL>self.flush_to_end_of_result()<EOL>if self._message is None:<EOL><INDENT>return False<EOL><DEDENT>elif isinstance(self._message, END_OF_RESULT_RESPONSES):<EOL><INDENT>self._message = self.connection.read_message()<EOL>if isinstance(self._message, messages.RowDescription):<EOL><INDENT>self.description = [Column(fd, ... | Skip to the next available result set, discarding any remaining rows
from the current result set.
If there are no more result sets, this method returns False. Otherwise,
it returns a True and subsequent calls to the fetch*() methods will
return rows from the next result set. | f7831:c0:m12 |
def copy(self, sql, data, **kwargs): | sql = as_text(sql)<EOL>if self.closed():<EOL><INDENT>raise errors.InterfaceError('<STR_LIT>')<EOL><DEDENT>self.flush_to_query_ready()<EOL>if isinstance(data, binary_type):<EOL><INDENT>stream = BytesIO(data)<EOL><DEDENT>elif isinstance(data, text_type):<EOL><INDENT>stream = StringIO(data)<EOL><DEDENT>elif isinstance(dat... | EXAMPLE:
>> with open("/tmp/file.csv", "rb") as fs:
>> cursor.copy("COPY table(field1,field2) FROM STDIN DELIMITER ',' ENCLOSED BY ''''",
>> fs, buffer_size=65536) | f7831:c0:m17 |
def _execute_simple_query(self, query): | self._logger.info(u'<STR_LIT>'.format(query))<EOL>self.connection.write(messages.Query(query))<EOL>self._message = self.connection.read_message()<EOL>if isinstance(self._message, messages.ErrorResponse):<EOL><INDENT>raise errors.QueryError.from_error_response(self._message, query)<EOL><DEDENT>elif isinstance(self._mess... | Send the query to the server using the simple query protocol.
Return True if this query contained no SQL (e.g. the string "--comment") | f7831:c0:m24 |
def _prepare(self, query): | self._logger.info(u'<STR_LIT>'.format(query))<EOL>self.connection.write(messages.Parse(self.prepared_name, query, param_types=()))<EOL>self.connection.write(messages.Describe('<STR_LIT>', self.prepared_name))<EOL>self.connection.write(messages.Flush())<EOL>self._message = self.connection.read_expected_message(messages.... | Send the query to be prepared to the server. The server will parse the
query and return some metadata. | f7831:c0:m26 |
def _execute_prepared_statement(self, list_of_parameter_values): | portal_name = "<STR_LIT>"<EOL>parameter_type_oids = [metadata['<STR_LIT>'] for metadata in self._param_metadata]<EOL>parameter_count = len(self._param_metadata)<EOL>try:<EOL><INDENT>if len(list_of_parameter_values) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for parameter_values in list_of_par... | Send multiple statement parameter sets to the server using the extended
query protocol. The server would bind and execute each set of parameter
values.
This function should not be called without first calling _prepare() to
prepare a statement. | f7831:c0:m27 |
def _close_prepared_statement(self): | self.prepared_sql = None<EOL>self.flush_to_query_ready()<EOL>self.connection.write(messages.Close('<STR_LIT>', self.prepared_name))<EOL>self.connection.write(messages.Flush())<EOL>self._message = self.connection.read_expected_message(messages.CloseComplete)<EOL>self.connection.write(messages.Sync())<EOL> | Close the prepared statement on the server. | f7831:c0:m28 |
def fetch_message(self): | raise NotImplementedError("<STR_LIT>")<EOL> | Generator for getting the message's content | f7854:c2:m0 |
def __setkey(key): | global C, D, KS, E<EOL>shifts = (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>)<EOL>for i in range(<NUM_LIT>):<EOL><INDENT>C[i] = key[PC1_C[i] - <NUM_LIT:1>]<E... | Set up the key schedule from the encryption key. | f7870:m0 |
@fixture<EOL>def environ(): | current_environ = os.environ.copy()<EOL>yield os.environ<EOL>os.environ = current_environ<EOL> | Enforce restoration of current shell environment after modifications.
Yields the ``os.environ`` dict after snapshotting it; restores the original
value (wholesale) during fixture teardown. | f7879:m0 |
def transform_name(self, name): | <EOL>name = re.sub(TEST_PREFIX, "<STR_LIT>", name)<EOL>name = re.sub(TEST_SUFFIX, "<STR_LIT>", name)<EOL>name = name.replace("<STR_LIT:_>", "<STR_LIT:U+0020>")<EOL>return name<EOL> | Take a test class/module/function name and make it human-presentable. | f7880:c0:m5 |
def trap(func): | @wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>sys.stdall = CarbonCopy()<EOL>my_stdout, sys.stdout = sys.stdout, CarbonCopy(cc=sys.stdall)<EOL>my_stderr, sys.stderr = sys.stderr, CarbonCopy(cc=sys.stdall)<EOL>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout = my_stdo... | Replace sys.std(out|err) with a wrapper during execution, restored after.
In addition, a new combined-streams output (another wrapper) will appear at
``sys.stdall``. This stream will resemble what a user sees at a terminal,
i.e. both out/err streams intermingled. | f7882:m0 |
def __init__(self, buffer=b"<STR_LIT>", cc=None): | IO.__init__(self, buffer)<EOL>if cc is None:<EOL><INDENT>cc = []<EOL><DEDENT>elif hasattr(cc, "<STR_LIT>"):<EOL><INDENT>cc = [cc]<EOL><DEDENT>self.cc = cc<EOL> | If ``cc`` is given and is a file-like object or an iterable of same,
it/they will be written to whenever this instance is written to. | f7882:c0:m0 |
@task<EOL>def coverage(c, html=True): | <EOL>c.run("<STR_LIT>")<EOL>if html:<EOL><INDENT>c.run("<STR_LIT>")<EOL>c.run("<STR_LIT>")<EOL><DEDENT> | Run coverage with coverage.py. | f7887:m0 |
def data_source_from_info(info): | if info.db:<EOL><INDENT>return "<STR_LIT>" % info.db<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % info.logdir<EOL><DEDENT> | Format the data location for the given TensorBoardInfo.
Args:
info: A TensorBoardInfo value.
Returns:
A human-readable string describing the logdir or database connection
used by the server: e.g., "logdir /tmp/logs". | f7891:m0 |
def _info_to_string(info): | for key in _TENSORBOARD_INFO_FIELDS:<EOL><INDENT>field_type = _TENSORBOARD_INFO_FIELDS[key]<EOL>if not isinstance(getattr(info, key), field_type.runtime_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(key, field_type.runtime_type, getattr(info, key))<EOL>)<EOL><DEDENT><DEDENT>if info.version != version.VERS... | Convert a `TensorBoardInfo` to string form to be stored on disk.
The format returned by this function is opaque and should only be
interpreted by `_info_from_string`.
Args:
info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the correct type.
... | f7891:m1 |
def _info_from_string(info_string): | try:<EOL><INDENT>json_value = json.loads(info_string)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>" % (info_string,))<EOL><DEDENT>if not isinstance(json_value, dict):<EOL><INDENT>raise ValueError("<STR_LIT>" % (json_value,))<EOL><DEDENT>if json_value.get("<STR_LIT:version>") != version.VERSION... | Parse a `TensorBoardInfo` object from its string representation.
Args:
info_string: A string representation of a `TensorBoardInfo`, as
produced by a previous call to `_info_to_string`.
Returns:
A `TensorBoardInfo` value.
Raises:
ValueError: If the provided string is not valid JS... | f7891:m2 |
def cache_key(working_directory, arguments, configure_kwargs): | if not isinstance(arguments, (list, tuple)):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (arguments,)<EOL>)<EOL><DEDENT>datum = {<EOL>"<STR_LIT>": working_directory,<EOL>"<STR_LIT>": arguments,<EOL>"<STR_LIT>": configure_kwargs,<EOL>}<EOL>raw = base64.b64encode(<EOL>json.dumps(datum, sort_keys=Tr... | Compute a `TensorBoardInfo.cache_key` field.
The format returned by this function is opaque. Clients may only
inspect it by comparing it for equality with other results from this
function.
Args:
working_directory: The directory from which TensorBoard was launched
and relative to which pa... | f7891:m3 |
def _get_info_dir(): | path = os.path.join(tempfile.gettempdir(), "<STR_LIT>")<EOL>try:<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno == errno.EEXIST and os.path.isdir(path):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>os.chmod(path, <NUM_LIT>)<EOL><DEDENT... | Get path to directory in which to store info files.
The directory returned by this function is "owned" by this module. If
the contents of the directory are modified other than via the public
functions of this module, subsequent behavior is undefined.
The directory will be created if it does not exist. | f7891:m4 |
def _get_info_file_path(): | return os.path.join(_get_info_dir(), "<STR_LIT>" % os.getpid())<EOL> | Get path to info file for the current process.
As with `_get_info_dir`, the info directory will be created if it does
not exist. | f7891:m5 |
def write_info_file(tensorboard_info): | payload = "<STR_LIT>" % _info_to_string(tensorboard_info)<EOL>with open(_get_info_file_path(), "<STR_LIT:w>") as outfile:<EOL><INDENT>outfile.write(payload)<EOL><DEDENT> | Write TensorBoardInfo to the current process's info file.
This should be called by `main` once the server is ready. When the
server shuts down, `remove_info_file` should be called.
Args:
tensorboard_info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not ... | f7891:m6 |
def remove_info_file(): | try:<EOL><INDENT>os.unlink(_get_info_file_path())<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno == errno.ENOENT:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT> | Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised. | f7891:m7 |
def get_all(): | info_dir = _get_info_dir()<EOL>results = []<EOL>for filename in os.listdir(info_dir):<EOL><INDENT>filepath = os.path.join(info_dir, filename)<EOL>try:<EOL><INDENT>with open(filepath) as infile:<EOL><INDENT>contents = infile.read()<EOL><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>if e.errno == errno.EACCES:<EOL><IND... | Return TensorBoardInfo values for running TensorBoard processes.
This function may not provide a perfect snapshot of the set of running
processes. Its result set may be incomplete if the user has cleaned
their /tmp/ directory while TensorBoard processes are running. It may
contain extraneous entries if... | f7891:m8 |
def start(arguments, timeout=datetime.timedelta(seconds=<NUM_LIT>)): | match = _find_matching_instance(<EOL>cache_key(<EOL>working_directory=os.getcwd(),<EOL>arguments=arguments,<EOL>configure_kwargs={},<EOL>),<EOL>)<EOL>if match:<EOL><INDENT>return StartReused(info=match)<EOL><DEDENT>(stdout_fd, stdout_path) = tempfile.mkstemp(prefix="<STR_LIT>")<EOL>(stderr_fd, stderr_path) = tempfile.m... | Start a new TensorBoard instance, or reuse a compatible one.
If the cache key determined by the provided arguments and the current
working directory (see `cache_key`) matches the cache key of a running
TensorBoard process (see `get_all`), that process will be reused.
Otherwise, a new TensorBoard proce... | f7891:m9 |
def _find_matching_instance(cache_key): | infos = get_all()<EOL>candidates = [info for info in infos if info.cache_key == cache_key]<EOL>for candidate in sorted(candidates, key=lambda x: x.port):<EOL><INDENT>return candidate<EOL><DEDENT>return None<EOL> | Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key. | f7891:m10 |
def _maybe_read_file(filename): | try:<EOL><INDENT>with open(filename) as infile:<EOL><INDENT>return infile.read()<EOL><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>if e.errno == errno.ENOENT:<EOL><INDENT>return None<EOL><DEDENT><DEDENT> | Read the given file, if it exists.
Args:
filename: A path to a file.
Returns:
A string containing the file contents, or `None` if the file does
not exist. | f7891:m11 |
def setup_environment(): | absl.logging.set_verbosity(absl.logging.WARNING)<EOL>serving.WSGIRequestHandler.protocol_version = '<STR_LIT>'<EOL> | Makes recommended modifications to the environment.
This functions changes global state in the Python process. Calling
this function is a good idea, but it can't appropriately be called
from library routines. | f7897:m0 |
def get_default_assets_zip_provider(): | path = os.path.join(os.path.dirname(inspect.getfile(sys._getframe(<NUM_LIT:1>))),<EOL>'<STR_LIT>')<EOL>if not os.path.exists(path):<EOL><INDENT>logger.warning('<STR_LIT>', path)<EOL>return None<EOL><DEDENT>return lambda: open(path, '<STR_LIT:rb>')<EOL> | Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callback returns must be closed. The
paths inside the zip fi... | f7897:m1 |
def with_port_scanning(cls): | def init(wsgi_app, flags):<EOL><INDENT>should_scan = flags.port is None<EOL>base_port = core_plugin.DEFAULT_PORT if flags.port is None else flags.port<EOL>max_attempts = <NUM_LIT:10> if should_scan else <NUM_LIT:1><EOL>if base_port > <NUM_LIT>:<EOL><INDENT>raise TensorBoardServerException(<EOL>'<STR_LIT>' % (base_port,... | Create a server factory that performs port scanning.
This function returns a callable whose signature matches the
specification of `TensorBoardServer.__init__`, using `cls` as an
underlying implementation. It passes through `flags` unchanged except
in the case that `flags.port is None`, in which case i... | f7897:m2 |
def __init__(self,<EOL>plugins=None,<EOL>assets_zip_provider=None,<EOL>server_class=None): | if plugins is None:<EOL><INDENT>from tensorboard import default<EOL>plugins = default.get_plugins()<EOL><DEDENT>if assets_zip_provider is None:<EOL><INDENT>assets_zip_provider = get_default_assets_zip_provider()<EOL><DEDENT>if server_class is None:<EOL><INDENT>server_class = create_port_scanning_werkzeug_server<EOL><DE... | Creates new instance.
Args:
plugins: A list of TensorBoard plugins to load, as TBLoader instances or
TBPlugin classes. If not specified, defaults to first-party plugins.
assets_zip_provider: Delegates to TBContext or uses default if None.
server_class: An optional fact... | f7897:c0:m0 |
def configure(self, argv=('<STR_LIT>',), **kwargs): | parser = argparse_flags.ArgumentParser(<EOL>prog='<STR_LIT>',<EOL>description=('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'))<EOL>for loader in self.plugin_loaders:<EOL><INDENT>loader.define_flags(parser)<EOL><DEDENT>arg0 = argv[<NUM_LIT:0>] if argv else '<STR_LIT>'<EOL>flags = parser.parse_args(argv[<NUM_LIT:1>:]) <EO... | Configures TensorBoard behavior via flags.
This method will populate the "flags" property with an argparse.Namespace
representing flag values parsed from the provided argv list, overridden by
explicit flags from remaining keyword arguments.
Args:
argv: Can be set to CLI args ... | f7897:c0:m1 |
def main(self, ignored_argv=('<STR_LIT>',)): | self._install_signal_handler(signal.SIGTERM, "<STR_LIT>")<EOL>if self.flags.inspect:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>event_file = os.path.expanduser(self.flags.event_file)<EOL>efi.inspect(self.flags.logdir, event_file, self.flags.tag)<EOL>return <NUM_LIT:0><EOL><DEDENT>if self.flags.version_tb:<EOL><INDENT>pri... | Blocking main function for TensorBoard.
This method is called by `tensorboard.main.run_main`, which is the
standard entrypoint for the tensorboard command line program. The
configure() method must be called first.
Args:
ignored_argv: Do not pass. Required for Abseil compatibi... | f7897:c0:m2 |
def launch(self): | <EOL>server = self._make_server()<EOL>thread = threading.Thread(target=server.serve_forever, name='<STR_LIT>')<EOL>thread.daemon = True<EOL>thread.start()<EOL>return server.get_url()<EOL> | Python API for launching TensorBoard.
This method is the same as main() except it launches TensorBoard in
a separate permanent thread. The configure() method must be called
first.
Returns:
The URL of the TensorBoard web server.
:rtype: str | f7897:c0:m3 |
def _register_info(self, server): | server_url = urllib.parse.urlparse(server.get_url())<EOL>info = manager.TensorBoardInfo(<EOL>version=version.VERSION,<EOL>start_time=int(time.time()),<EOL>port=server_url.port,<EOL>pid=os.getpid(),<EOL>path_prefix=self.flags.path_prefix,<EOL>logdir=self.flags.logdir,<EOL>db=self.flags.db,<EOL>cache_key=self.cache_key,<... | Write a TensorBoardInfo file and arrange for its cleanup.
Args:
server: The result of `self._make_server()`. | f7897:c0:m4 |
def _install_signal_handler(self, signal_number, signal_name): | old_signal_handler = None <EOL>def handler(handled_signal_number, frame):<EOL><INDENT>signal.signal(signal_number, signal.SIG_DFL)<EOL>sys.stderr.write("<STR_LIT>" % signal_name)<EOL>if old_signal_handler not in (signal.SIG_IGN, signal.SIG_DFL):<EOL><INDENT>old_signal_handler(handled_signal_number, frame)<EOL><DEDENT>... | Set a signal handler to gracefully exit on the given signal.
When this process receives the given signal, it will run `atexit`
handlers and then exit with `0`.
Args:
signal_number: The numeric code for the signal to handle, like
`signal.SIGTERM`.
signal_name: Th... | f7897:c0:m5 |
def _make_server(self): | app = application.standard_tensorboard_wsgi(self.flags,<EOL>self.plugin_loaders,<EOL>self.assets_zip_provider)<EOL>return self.server_class(app, self.flags)<EOL> | Constructs the TensorBoard WSGI app and instantiates the server. | f7897:c0:m6 |
@abstractmethod<EOL><INDENT>def __init__(self, wsgi_app, flags):<DEDENT> | raise NotImplementedError()<EOL> | Create a flag-configured HTTP server for TensorBoard's WSGI app.
Args:
wsgi_app: The TensorBoard WSGI application to create a server for.
flags: argparse.Namespace instance of TensorBoard flags. | f7897:c1:m0 |
@abstractmethod<EOL><INDENT>def serve_forever(self):<DEDENT> | raise NotImplementedError()<EOL> | Blocking call to start serving the TensorBoard server. | f7897:c1:m1 |
@abstractmethod<EOL><INDENT>def get_url(self):<DEDENT> | raise NotImplementedError()<EOL> | Returns a URL at which this server should be reachable. | f7897:c1:m2 |
def _get_wildcard_address(self, port): | fallback_address = '<STR_LIT>' if socket.has_ipv6 else '<STR_LIT>'<EOL>if hasattr(socket, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>addrinfos = socket.getaddrinfo(None, port, socket.AF_UNSPEC,<EOL>socket.SOCK_STREAM, socket.IPPROTO_TCP,<EOL>socket.AI_PASSIVE)<EOL><DEDENT>except socket.gaierror as e:<EOL><INDENT>logger... | Returns a wildcard address for the port in question.
This will attempt to follow the best practice of calling getaddrinfo() with
a null host and AI_PASSIVE to request a server-side socket wildcard address.
If that succeeds, this returns the first IPv6 address found, or if none,
then ret... | f7897:c4:m1 |
def server_bind(self): | socket_is_v6 = (<EOL>hasattr(socket, '<STR_LIT>') and self.socket.family == socket.AF_INET6)<EOL>has_v6only_option = (<EOL>hasattr(socket, '<STR_LIT>') and hasattr(socket, '<STR_LIT>'))<EOL>if self._auto_wildcard and socket_is_v6 and has_v6only_option:<EOL><INDENT>try:<EOL><INDENT>self.socket.setsockopt(socket.IPPROTO_... | Override to enable IPV4 mapping for IPV6 sockets when desired.
The main use case for this is so that when no host is specified, TensorBoard
can listen on all interfaces for both IPv4 and IPv6 connections, rather than
having to choose v4 or v6 and hope the browser didn't choose the other one. | f7897:c4:m2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.