_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q10600
acoustic_similarity_directories
train
def acoustic_similarity_directories(directories, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True): """ Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed """ files = [] if call_back is not None: call_back('Mapping directories...') call_back(0, len(directories)) cur = 0 for d in directories: if not os.path.isdir(d): continue if stop_check is not None and stop_check(): return if call_back is not None: cur += 1 if cur % 3 == 0: call_back(cur) files += [os.path.join(d, x) for x in os.listdir(d) if x.lower().endswith('.wav')] if len(files) == 0: raise (ConchError("The directories specified do not contain any wav files")) if call_back is not None: call_back('Mapping directories...') call_back(0, len(files) * len(files)) cur = 0 path_mapping = list() for x in files: for y in files:
python
{ "resource": "" }
q10601
dtw_distance
train
def dtw_distance(rep_one, rep_two, norm=True): """Computes the distance between two representations with the same number of filters using Dynamic Time Warping. Parameters ---------- rep_one : 2D array First representation to compare. First dimension is time in frames or samples and second dimension is the features. rep_two : 2D array Second representation to compare. First dimension is time in frames or samples and second dimension is the features. Returns ------- float Distance of dynamically time warping `rep_one` to `rep_two`. """
python
{ "resource": "" }
q10602
generate_distance_matrix
train
def generate_distance_matrix(source, target, weights=None): """Generates a local distance matrix for use in dynamic time warping. Parameters ---------- source : 2D array Source matrix with features in the second dimension. target : 2D array Target matrix with features in
python
{ "resource": "" }
q10603
regularDTW
train
def regularDTW(distMat, norm=True): """Use a local distance matrix to perform dynamic time warping. Parameters ---------- distMat : 2D array Local distance matrix. Returns ------- float Total unweighted distance of the optimal path through the local distance matrix. """ sLen, tLen = distMat.shape totalDistance = zeros((sLen, tLen)) totalDistance[0:sLen, 0:tLen] = distMat minDirection = zeros((sLen, tLen)) for i in range(1, sLen): totalDistance[i, 0] = totalDistance[i, 0] + totalDistance[i - 1, 0] for j in range(1, tLen): totalDistance[0, j] = totalDistance[0, j] + totalDistance[0, j - 1] for i in range(1, sLen): for j in range(1, tLen): # direction,minPrevDistance = min(enumerate([totalDistance[i,j],totalDistance[i,j+1],totalDistance[i+1,j]]), key=operator.itemgetter(1))
python
{ "resource": "" }
q10604
preproc
train
def preproc(path, sr=16000, alpha=0.95): """Preprocess a .wav file for later processing. Currently assumes a 16-bit PCM input. Only returns left channel of stereo files. Parameters ---------- path : str Full path to .wav file to load. sr : int, optional Sampling rate to resample at, if specified. alpha : float, optional Alpha for preemphasis, defaults to 0.97. Returns ------- int Sampling rate. array Processed PCM. """ oldsr, sig = wavfile.read(path) try:
python
{ "resource": "" }
q10605
fftfilt
train
def fftfilt(b, x, *n): """Filter the signal x with the FIR filter described by the coefficients in b using the overlap-add method. If the FFT length n is not specified, it and the overlap-add block length are selected so as to minimize the computational cost of the filtering operation.""" N_x = len(x) N_b = len(b) # Determine the FFT length to use: if len(n): # Use the specified FFT length (rounded up to the nearest # power of 2), provided that it is no less than the filter # length: n = n[0] if n != int(n) or n <= 0: raise ValueError('n must be a nonnegative integer') if n < N_b: n = N_b N_fft = 2 ** nextpow2(n) else: if N_x > N_b: # When the filter length is smaller than the signal, # choose the FFT length and block size that minimize the # FLOPS cost. Since the cost for a length-N FFT is # (N/2)*log2(N) and the filtering operation of each block # involves 2 FFT operations and N multiplications, the # cost of the overlap-add method for 1 length-N block is # N*(1+log2(N)). For the sake of efficiency, only FFT # lengths that are powers of 2 are considered:
python
{ "resource": "" }
q10606
construct_filterbank
train
def construct_filterbank(num_filters, nfft, sr, min_freq, max_freq): """Constructs a mel-frequency filter bank. Parameters ---------- nfft : int Number of points in the FFT. Returns ------- array Filter bank to multiply an FFT spectrum to create a mel-frequency spectrum. """ min_mel = freq_to_mel(min_freq) max_mel = freq_to_mel(max_freq) mel_points = np.linspace(min_mel, max_mel, num_filters + 2) bin_freqs = mel_to_freq(mel_points) # bins = round((nfft - 1) * bin_freqs / sr) fftfreqs = np.arange(int(nfft / 2 + 1)) / nfft * sr fbank = np.zeros((num_filters, int(nfft / 2 + 1))) for
python
{ "resource": "" }
q10607
ItemViewLooper.windowed_iterable
train
def windowed_iterable(self): """ That returns only the window """ # Seek to offset effective_offset = max(0,self.item_view.iterable_index) for i,item in enumerate(self.iterable): if i<effective_offset:
python
{ "resource": "" }
q10608
ItemViewLooper.refresh_items
train
def refresh_items(self): """ Refresh the items of the pattern. This method destroys the old items and creates and initializes the new items. """ old_items = self.items[:]# if self._dirty else [] old_iter_data = self._iter_data# if self._dirty else {} iterable = self.windowed_iterable pattern_nodes = self.pattern_nodes new_iter_data = sortedmap() new_items = [] if iterable is not None and len(pattern_nodes) > 0: for loop_index, loop_item in enumerate(iterable): iteration = old_iter_data.get(loop_item) if iteration is not None: new_iter_data[loop_item] = iteration new_items.append(iteration) old_items.remove(iteration) continue iteration = [] new_iter_data[loop_item] = iteration new_items.append(iteration) for nodes, key, f_locals in pattern_nodes: with new_scope(key, f_locals) as f_locals: f_locals['loop_index'] = loop_index f_locals['loop_item'] = loop_item for node in nodes: child = node(None) if isinstance(child, list):
python
{ "resource": "" }
q10609
QtDoubleSpinBox.create_widget
train
def create_widget(self): """ Create the underlying QDoubleSpinBox widget. """ widget = QDoubleSpinBox(self.parent_widget())
python
{ "resource": "" }
q10610
QtTableViewItem._update_index
train
def _update_index(self): """ Update the reference to the index within the table """ d = self.declaration self.index = self.view.model.index(d.row, d.column) if self.delegate:
python
{ "resource": "" }
q10611
QtTableViewItem._update_delegate
train
def _update_delegate(self): """ Update the delegate cell widget. This is deferred so it does not get called until the user is done scrolling. """ self._refresh_count -= 1 if self._refresh_count != 0: return try: delegate = self.delegate if not self.is_visible(): return # The table destroys when it goes out of view # so we always have
python
{ "resource": "" }
q10612
QtTableViewItem.data_changed
train
def data_changed(self, change): """ Notify the model that data has changed in this cell! """ index = self.index
python
{ "resource": "" }
q10613
QtBaseViewer.GetHandle
train
def GetHandle(self): ''' returns an the identifier of the GUI widget. It must be an integer ''' win_id = self.winId() # this returns either an int or voitptr if "%s"%type(win_id) == "<type 'PyCObject'>": # PySide ### with PySide, self.winId() does not return an integer if sys.platform == "win32": ## Be careful, this hack is py27 specific ## does not work with python31 or higher ## since the PyCObject api was changed import ctypes ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p
python
{ "resource": "" }
q10614
Topology._map_shapes_and_ancestors
train
def _map_shapes_and_ancestors(self, topoTypeA, topoTypeB, topologicalEntity): ''' using the same method @param topoTypeA: @param topoTypeB: @param topologicalEntity: ''' topo_set = set() _map = TopTools_IndexedDataMapOfShapeListOfShape() topexp_MapShapesAndAncestors(self.myShape, topoTypeA, topoTypeB, _map) results = _map.FindFromKey(topologicalEntity) if results.IsEmpty(): yield None topology_iterator = TopTools_ListIteratorOfListOfShape(results) while topology_iterator.More(): topo_entity = self.topoFactory[topoTypeB](topology_iterator.Value()) # return the entity if not in set # to assure we're not returning entities several times
python
{ "resource": "" }
q10615
OccDependentShape.init_layout
train
def init_layout(self): """ Initialize the layout of the toolkit shape. This method is called during the bottom-up pass. This method should initialize the layout of the widget. The child widgets will
python
{ "resource": "" }
q10616
QtKeyEvent.init_widget
train
def init_widget(self): """ The KeyEvent uses the parent_widget as it's widget """ super(QtKeyEvent, self).init_widget() d = self.declaration
python
{ "resource": "" }
q10617
QtKeyEvent.set_keys
train
def set_keys(self, keys): """ Parse all the key codes and save them """ codes = {} for key in keys: parts = [k.strip().lower() for k in key.split("+")] code = KEYS.get(parts[-1]) modifier = Qt.KeyboardModifiers() if code is None: raise KeyError("Invalid key code '{}'".format(key)) if len(parts) > 1: for mod in parts[:-1]: mod_code = MODIFIERS.get(mod)
python
{ "resource": "" }
q10618
FeatureMixin._setup_features
train
def _setup_features(self): """ Setup the advanced widget feature handlers. """ features = self._features = self.declaration.features if not features: return if features & Feature.FocusTraversal: self.hook_focus_traversal() if features & Feature.FocusEvents: self.hook_focus_events() if features & Feature.DragEnabled: self.hook_drag() if features & Feature.DropEnabled:
python
{ "resource": "" }
q10619
FeatureMixin._teardown_features
train
def _teardown_features(self): """ Teardowns the advanced widget feature handlers. """ features = self._features if not features: return if features & Feature.FocusTraversal: self.unhook_focus_traversal() if features & Feature.FocusEvents:
python
{ "resource": "" }
q10620
FeatureMixin.tab_focus_request
train
def tab_focus_request(self, reason): """ Handle a custom tab focus request. This method is called when focus is being set on the proxy as a result of a user-implemented focus traversal handler. This can be reimplemented by subclasses as needed. Parameters ---------- reason : Qt.FocusReason The reason value for the focus request. Returns ------- result : bool True if focus was set, False otherwise.
python
{ "resource": "" }
q10621
FeatureMixin.hook_focus_events
train
def hook_focus_events(self): """ Install the hooks for focus events. This method may be overridden by subclasses
python
{ "resource": "" }
q10622
FeatureMixin.focusNextPrevChild
train
def focusNextPrevChild(self, next_child): """ The default 'focusNextPrevChild' implementation. """ fd = focus_registry.focused_declaration() if next_child: child = self.declaration.next_focus_child(fd)
python
{ "resource": "" }
q10623
FeatureMixin.focusInEvent
train
def focusInEvent(self, event): """ The default 'focusInEvent' implementation. """ widget
python
{ "resource": "" }
q10624
FeatureMixin.focusOutEvent
train
def focusOutEvent(self, event): """ The default 'focusOutEvent' implementation. """
python
{ "resource": "" }
q10625
FeatureMixin.hook_drag
train
def hook_drag(self): """ Install the hooks for drag operations. """ widget = self.widget widget.mousePressEvent = self.mousePressEvent
python
{ "resource": "" }
q10626
FeatureMixin.unhook_drag
train
def unhook_drag(self): """ Remove the hooks for drag operations. """ widget = self.widget del widget.mousePressEvent
python
{ "resource": "" }
q10627
FeatureMixin.hook_drop
train
def hook_drop(self): """ Install hooks for drop operations. """ widget = self.widget widget.setAcceptDrops(True) widget.dragEnterEvent = self.dragEnterEvent
python
{ "resource": "" }
q10628
FeatureMixin.unhook_drop
train
def unhook_drop(self): """ Remove hooks for drop operations. """ widget = self.widget widget.setAcceptDrops(False) del
python
{ "resource": "" }
q10629
FeatureMixin.draw
train
def draw(self, painter, options, widget): """ Handle the draw event for the widget. """
python
{ "resource": "" }
q10630
FeatureMixin.get_action
train
def get_action(self, create=False): """ Get the shared widget action for this widget. This API is used to support widgets in tool bars and menus. Parameters ---------- create : bool, optional Whether to create the action if it doesn't already exist. The default is False. Returns ------- result : QWidgetAction or None The cached widget action or None, depending on arguments.
python
{ "resource": "" }
q10631
QtGraphicsView.set_renderer
train
def set_renderer(self, renderer): """ Set the viewport widget. """ viewport = None if renderer == 'opengl': from enaml.qt.QtWidgets import QOpenGLWidget viewport = QOpenGLWidget()
python
{ "resource": "" }
q10632
QtGraphicsView.on_selection_changed
train
def on_selection_changed(self): """ Callback invoked one the selection has changed. """ d = self.declaration selection = self.scene.selectedItems()
python
{ "resource": "" }
q10633
QtGraphicsView.set_background
train
def set_background(self, background): """ Set the background color of the widget. """
python
{ "resource": "" }
q10634
QtGraphicsView.scale_view
train
def scale_view(self, x, y): """ Scale the zoom but keep in in the min and max zoom bounds. """ d = self.declaration
python
{ "resource": "" }
q10635
QtGraphicsItem.destroy
train
def destroy(self): """ Destroy the underlying QWidget object. """ self._teardown_features() focus_registry.unregister(self.widget) widget = self.widget if widget is not None: del self.widget super(QtGraphicsItem, self).destroy() # If a QWidgetAction was created for this widget, then it has # taken ownership of the widget and
python
{ "resource": "" }
q10636
QtGraphicsItem.parent_widget
train
def parent_widget(self): """ Reimplemented to only return GraphicsItems """ parent = self.parent() if parent
python
{ "resource": "" }
q10637
QtGraphicsWidget.init_layout
train
def init_layout(self): """ Create the widget in the layout pass after the child widget has been created and intialized. We do this so the child widget does not attempt to use this proxy widget as its parent and because repositioning must be done after the widget is set. """ self.widget =
python
{ "resource": "" }
q10638
OccOperation._dequeue_update
train
def _dequeue_update(self,change): """ Only update when all changes are done """ self._update_count -=1
python
{ "resource": "" }
q10639
GraphicsItem.show
train
def show(self): """ Ensure the widget is shown. Calling this method will also set the widget visibility to True. """
python
{ "resource": "" }
q10640
GraphicsItem.hide
train
def hide(self): """ Ensure the widget is hidden. Calling this method will also set the widget visibility to False. """
python
{ "resource": "" }
q10641
GraphicsView.get_item_at
train
def get_item_at(self, *args, **kwargs): """ Return the items at the given position """
python
{ "resource": "" }
q10642
GraphicsView.center_on
train
def center_on(self, item): """ Center on the given item or point. """ if not isinstance(item, GraphicsItem):
python
{ "resource": "" }
q10643
_custom_token_stream
train
def _custom_token_stream(self): """ A wrapper for the BaseEnamlLexer's make_token_stream which allows the stream to be customized by adding "token_stream_processors". A token_stream_processor is a generator function which takes the token_stream as it's single input argument and yields each processed token as it's output. Each token will be an instance of `ply.lex.LexToken`.
python
{ "resource": "" }
q10644
QtConsole.init_signal
train
def init_signal(self): """allow clean shutdown on sigint""" signal.signal(signal.SIGINT, lambda sig, frame: self.exit(-2)) # need a timer, so that QApplication doesn't block until a real # Qt event fires (can require mouse movement) # timer trick from http://stackoverflow.com/q/4938723/938949 timer = QtCore.QTimer()
python
{ "resource": "" }
q10645
Shape._update_position
train
def _update_position(self, change): """ Keep position in sync with x,y,z """ if change['type']!='update': return
python
{ "resource": "" }
q10646
Shape._update_xyz
train
def _update_xyz(self, change): """ Keep x,y,z in sync with position """
python
{ "resource": "" }
q10647
Shape._update_state
train
def _update_state(self, change): """ Keep position and direction in sync with axis """ self._block_updates = True try: self.position = self.axis.Location()
python
{ "resource": "" }
q10648
AbstractQtPlotItem._refresh_multi_axis
train
def _refresh_multi_axis(self): """ If linked axis' are used, setup and link them """ d = self.declaration #: Create a separate viewbox self.viewbox = pg.ViewBox() #: If this is the first nested plot, use the parent right axis _plots = [c for c in self.parent().children() if isinstance(c,AbstractQtPlotItem)] i = _plots.index(self) if i==0: self.axis = self.widget.getAxis('right') self.widget.showAxis('right') else: self.axis = pg.AxisItem('right') self.axis.setZValue(-10000)
python
{ "resource": "" }
q10649
AbstractQtPlotItem.on_resized
train
def on_resized(self): """ Update linked views """ d = self.declaration if not self.is_root and d.parent.multi_axis: if self.viewbox:
python
{ "resource": "" }
q10650
TreeViewItem._get_columns
train
def _get_columns(self): """ List of child TreeViewColumns including this item as the first column """
python
{ "resource": "" }
q10651
TreeViewItem._update_rows
train
def _update_rows(self): """ Update the row and column numbers of child items. """ for row, item in enumerate(self._items): item.row = row # Row is the Parent item item.column = 0
python
{ "resource": "" }
q10652
QAbstractAtomItemModel.setDeclaration
train
def setDeclaration(self, declaration): """ Set the declaration this model will use for rendering the the headers. """ assert isinstance(declaration.proxy, ProxyAbstractItemView), \
python
{ "resource": "" }
q10653
QAbstractAtomItemModel.data
train
def data(self, index, role): """ Retrieve the data for the item at the given index """ item = self.itemAt(index) if not item: return None d = item.declaration if role == Qt.DisplayRole: return d.text elif role == Qt.ToolTipRole: return d.tool_tip elif role == Qt.CheckStateRole and d.checkable: return d.checked and Qt.Checked or Qt.Unchecked elif role == Qt.DecorationRole and d.icon: return get_cached_qicon(d.icon) elif role == Qt.EditRole and d.editable: return d.text elif role == Qt.StatusTipRole: return d.status_tip
python
{ "resource": "" }
q10654
QAbstractAtomItemModel.setData
train
def setData(self, index, value, role=Qt.EditRole): """ Set the data for the item at the given index to the given value. """ item = self.itemAt(index) if not item: return False d = item.declaration if role == Qt.CheckStateRole: checked = value == Qt.Checked if checked != d.checked: d.checked = checked d.toggled(checked)
python
{ "resource": "" }
q10655
QtAbstractItemView.set_items
train
def set_items(self, items): """ Defer until later so the view is only updated after all items are added. """
python
{ "resource": "" }
q10656
QtAbstractItemView._refresh_layout
train
def _refresh_layout(self): """ This queues and batches model changes so that the layout is only refreshed after the `_pending_timeout` expires. This prevents the UI from refreshing when inserting or removing a large number of items until the operation is complete. """ self._pending_view_refreshes -= 1 if self._pending_view_refreshes == 0: try:
python
{ "resource": "" }
q10657
QAtomTreeModel.index
train
def index(self, row, column, parent): """ The index should point to the corresponding QtControl in the enaml object hierarchy. """ item = parent.internalPointer() #: If the parent is None d = self.declaration if item is None else item.declaration if row < len(d._items):
python
{ "resource": "" }
q10658
QtTreeViewItem._default_view
train
def _default_view(self): """ If this is the root item, return the parent which must be a TreeView, otherwise return the parent Item's view. """ parent =
python
{ "resource": "" }
q10659
BaseModel.read
train
def read(cls, five9, external_id): """Return a record singleton for the ID. Args: five9 (five9.Five9): The authenticated Five9 remote. external_id (mixed): The identified on Five9. This should be the value that is in the ``__uid_field__`` field on the record.
python
{ "resource": "" }
q10660
BaseModel.update
train
def update(self, data): """Update the current memory record with the given data dict. Args: data (dict): Data dictionary to update the record
python
{ "resource": "" }
q10661
BaseModel._call_and_serialize
train
def _call_and_serialize(cls, method, data, refresh=False): """Call the remote method with data, and optionally refresh. Args: method (callable): The method on the Authenticated Five9 object that should be called. data (dict): A data dictionary that will be passed as the first and only position argument to ``method``. refresh (bool, optional): Set to ``True`` to get the record data from Five9 before returning the record. Returns: BaseModel: The newly created record.
python
{ "resource": "" }
q10662
BaseModel._get_name_filters
train
def _get_name_filters(cls, filters): """Return a regex filter for the UID column only.""" filters = filters.get(cls.__uid_field__) if not filters: filters = '.*' elif not
python
{ "resource": "" }
q10663
BaseModel._get_non_empty_list
train
def _get_non_empty_list(cls, iter): """Return a list of the input, excluding all ``None`` values.""" res = [] for value in iter: if hasattr(value, 'items'): value =
python
{ "resource": "" }
q10664
BaseModel._name_search
train
def _name_search(cls, method, filters): """Helper for search methods that use name filters. Args: method (callable): The Five9 API method to call with the name filters. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]:
python
{ "resource": "" }
q10665
BaseModel._zeep_to_dict
train
def _zeep_to_dict(cls, obj): """Convert a zeep object to a dictionary.""" res = serialize_object(obj)
python
{ "resource": "" }
q10666
BaseModel.__check_field
train
def __check_field(self, key): """Raises a KeyError if the field doesn't exist.""" if not self._props.get(key): raise KeyError( 'The field "%s" does not exist
python
{ "resource": "" }
q10667
Five9.supervisor
train
def supervisor(self): """Return an authenticated connection for use, open new if required. Returns: SupervisorWebService: New or existing session with the Five9 Statistics API. """ supervisor = self._cached_client('supervisor')
python
{ "resource": "" }
q10668
Five9.create_mapping
train
def create_mapping(record, keys): """Create a field mapping for use in API updates and creates. Args: record (BaseModel): Record that should be mapped. keys (list[str]): Fields that should be mapped as keys. Returns: dict: Dictionary with keys: * ``field_mappings``: Field mappings as required by API. * ``data``: Ordered data dictionary for input record. """ ordered = OrderedDict() field_mappings = [] for key, value in record.items():
python
{ "resource": "" }
q10669
Five9.parse_response
train
def parse_response(fields, records): """Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ 'number1', 'number2', 'number3', 'first_name', 'last_name', 'company', 'street', 'city', 'state', 'zip', ] records (list[dict]): A really crappy data structure representing records as returned by Five9:: [ { 'values': { 'data': [ '8881234567', None, None, 'Dave',
python
{ "resource": "" }
q10670
Five9.create_criteria
train
def create_criteria(cls, query): """Return a criteria from a dictionary containing a query. Query should be a dictionary, keyed by field name. If the value is a list, it will be divided into multiple criteria as required. """ criteria = [] for name, value in query.items(): if isinstance(value, list): for inner_value in value: criteria += cls.create_criteria({name: inner_value})
python
{ "resource": "" }
q10671
Five9._get_authenticated_client
train
def _get_authenticated_client(self, wsdl): """Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client. """ return zeep.Client( wsdl % quote(self.username),
python
{ "resource": "" }
q10672
Five9._get_authenticated_session
train
def _get_authenticated_session(self): """Return an authenticated requests session. Returns:
python
{ "resource": "" }
q10673
Five9.__create_supervisor_session
train
def __create_supervisor_session(self, supervisor): """Create a new session on the supervisor service. This is required in order to use most methods for the supervisor, so it is called implicitly when generating a supervisor session. """ session_params = { 'forceLogoutSession':
python
{ "resource": "" }
q10674
Api.model
train
def model(method): """Use this to decorate methods that expect a model.""" def wrapper(self, *args, **kwargs): if self.__model__ is None: raise ValidationError(
python
{ "resource": "" }
q10675
Api.recordset
train
def recordset(method): """Use this to decorate methods that expect a record set.""" def wrapper(self, *args, **kwargs): if self.__records__ is None: raise ValidationError(
python
{ "resource": "" }
q10676
Environment.create
train
def create(self, data, refresh=False): """Create the data on the remote, optionally refreshing.""" self.__model__.create(self.__five9__, data) if refresh:
python
{ "resource": "" }
q10677
Environment.new
train
def new(self, data): """Create a new memory record, but do not create on the remote.""" data = self.__model__._get_non_empty_dict(data) return self.__class__(
python
{ "resource": "" }
q10678
Environment.search
train
def search(self, filters): """Search Five9 given a filter. Args: filters (dict): A dictionary of search strings, keyed by the name of the field to search. Returns: Environment: An environment representing the recordset.
python
{ "resource": "" }
q10679
Disposition.create
train
def create(cls, five9, data, refresh=False): """Create a record on Five9. Args: five9 (five9.Five9): The authenticated Five9 remote. data (dict): A data dictionary that can be fed to ``deserialize``. refresh (bool, optional): Set to ``True`` to get the record data from Five9 before returning the record. Returns: BaseModel: The newly created record. If ``refresh`` is ``True``,
python
{ "resource": "" }
q10680
authentication_required
train
def authentication_required(meth): """Simple class method decorator. Checks if the client is currently connected. :param meth: the original called
python
{ "resource": "" }
q10681
Client.__read_block
train
def __read_block(self, size): """Read a block of 'size' bytes from the server. An internal buffer is used to read data from the server. If enough data is available from it, we return that data. Eventually, we try to grab the missing part from the server for Client.read_timeout seconds. If no data can be retrieved, it is considered as a fatal error and an 'Error' exception is raised. :param size: number of bytes to read
python
{ "resource": "" }
q10682
Client.__read_line
train
def __read_line(self): """Read one line from the server. An internal buffer is used to read data from the server (blocks of Client.read_size bytes). If the buffer is not empty, we try to find an entire line to return. If we failed, we try to read new content from the server for Client.read_timeout seconds. If no data can be retrieved, it is considered as a fatal error and an 'Error' exception is raised. :rtype: string :return: the read line """ ret = b"" while True: try: pos = self.__read_buffer.index(CRLF) ret = self.__read_buffer[:pos] self.__read_buffer = self.__read_buffer[pos + len(CRLF):] break except ValueError: pass try: nval = self.sock.recv(self.read_size) self.__dprint(nval)
python
{ "resource": "" }
q10683
Client.__read_response
train
def __read_response(self, nblines=-1): """Read a response from the server. In the usual case, we read lines until we find one that looks like a response (OK|NO|BYE\s*(.+)?). If *nblines* > 0, we read excactly nblines before returning. :param nblines: number of lines to read (default : -1) :rtype: tuple :return: a tuple of the form (code, data, response). If nblines is provided, code and data can be equal to None. """ resp, code, data = (b"", None, None) cpt = 0 while True: try: line = self.__read_line() except Response as inst: code = inst.code data = inst.data
python
{ "resource": "" }
q10684
Client.__prepare_args
train
def __prepare_args(self, args): """Format command arguments before sending them. Command arguments of type string must be quoted, the only exception concerns size indication (of the form {\d\+?}). :param args: list of arguments :return: a list for transformed arguments """ ret = [] for a in args: if isinstance(a, six.binary_type):
python
{ "resource": "" }
q10685
Client.__parse_error
train
def __parse_error(self, text): """Parse an error received from the server. if text corresponds to a size indication, we grab the remaining content from the server. Otherwise, we try to match an error of the form \(\w+\)?\s*".+" On succes, the two public members errcode and errmsg are filled with the parsing results. :param text: the response to parse """ m = self.__size_expr.match(text) if m is not None: self.errcode = b""
python
{ "resource": "" }
q10686
Client._plain_authentication
train
def _plain_authentication(self, login, password, authz_id=b""): """SASL PLAIN authentication :param login: username :param password: clear password :return: True on success, False otherwise. """ if isinstance(login, six.text_type): login = login.encode("utf-8") if isinstance(password, six.text_type):
python
{ "resource": "" }
q10687
Client._login_authentication
train
def _login_authentication(self, login, password, authz_id=""): """SASL LOGIN authentication :param login: username :param password: clear password :return: True on success, False otherwise. """ extralines = [b'"%s"' % base64.b64encode(login.encode("utf-8")), b'"%s"'
python
{ "resource": "" }
q10688
Client._digest_md5_authentication
train
def _digest_md5_authentication(self, login, password, authz_id=""): """SASL DIGEST-MD5 authentication :param login: username :param password: clear password :return: True on success, False otherwise. """ code, data, challenge = \ self.__send_command("AUTHENTICATE", [b"DIGEST-MD5"], withcontent=True, nblines=1) dmd5 = DigestMD5(challenge, "sieve/%s" % self.srvaddr) code, data, challenge = self.__send_command( '"%s"' % dmd5.response(login, password, authz_id), withcontent=True, nblines=1 )
python
{ "resource": "" }
q10689
Client.get_sieve_capabilities
train
def get_sieve_capabilities(self): """Returns the SIEVE extensions supported by the server. They're read from server capabilities. (see the CAPABILITY command) :rtype: string """
python
{ "resource": "" }
q10690
Client.connect
train
def connect( self, login, password, authz_id=b"", starttls=False, authmech=None): """Establish a connection with the server. This function must be used. It read the server capabilities and wraps calls to STARTTLS and AUTHENTICATE commands. :param login: username :param password: clear password :param starttls: use a TLS connection or not :param authmech: prefered authenticate mechanism :rtype: boolean """ try: self.sock = socket.create_connection((self.srvaddr, self.srvport)) self.sock.settimeout(Client.read_timeout) except socket.error as
python
{ "resource": "" }
q10691
Client.capability
train
def capability(self): """Ask server capabilities. See MANAGESIEVE specifications, section 2.4 This command does not affect capabilities recorded by this client. :rtype: string """ code, data, capabilities =
python
{ "resource": "" }
q10692
Client.havespace
train
def havespace(self, scriptname, scriptsize): """Ask for available space. See MANAGESIEVE specifications, section 2.5 :param scriptname: script's name :param scriptsize: script's size :rtype: boolean """
python
{ "resource": "" }
q10693
Client.listscripts
train
def listscripts(self): """List available scripts. See MANAGESIEVE specifications, section 2.7 :returns: a 2-uple (active script, [script1, ...]) """ code, data, listing = self.__send_command( "LISTSCRIPTS", withcontent=True) if code == "NO": return None ret = [] active_script = None for l in listing.splitlines(): if self.__size_expr.match(l): continue m = re.match(br'"([^"]+)"\s*(.+)', l)
python
{ "resource": "" }
q10694
Client.getscript
train
def getscript(self, name): """Download a script from the server See MANAGESIEVE specifications, section 2.9 :param name: script's name :rtype: string :returns: the script's content on succes, None otherwise """ code, data, content = self.__send_command( "GETSCRIPT", [name.encode("utf-8")], withcontent=True)
python
{ "resource": "" }
q10695
Client.putscript
train
def putscript(self, name, content): """Upload a script to the server See MANAGESIEVE specifications, section 2.6 :param name: script's name :param content: script's content :rtype: boolean """ content = tools.to_bytes(content) content = tools.to_bytes("{%d+}" %
python
{ "resource": "" }
q10696
Client.deletescript
train
def deletescript(self, name): """Delete a script from the server See MANAGESIEVE specifications, section 2.10 :param name: script's name :rtype: boolean """ code, data = self.__send_command(
python
{ "resource": "" }
q10697
Client.renamescript
train
def renamescript(self, oldname, newname): """Rename a script on the server See MANAGESIEVE specifications, section 2.11.1 As this command is optional, we emulate it if the server does not support it. :param oldname: current script's name :param newname: new script's name :rtype: boolean """ if "VERSION" in self.__capabilities: code, data = self.__send_command( "RENAMESCRIPT", [oldname.encode("utf-8"), newname.encode("utf-8")]) if code == "OK": return True return False (active_script, scripts) = self.listscripts() condition = ( oldname != active_script and (scripts is None or oldname not in scripts) ) if condition: self.errmsg = b"Old script does not exist"
python
{ "resource": "" }
q10698
Client.setactive
train
def setactive(self, scriptname): """Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean
python
{ "resource": "" }
q10699
Client.checkscript
train
def checkscript(self, content): """Check whether a script is valid See MANAGESIEVE specifications, section 2.12 :param name: script's content :rtype: boolean """ if "VERSION" not in self.__capabilities: raise NotImplementedError( "server does not support CHECKSCRIPT command")
python
{ "resource": "" }