id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
10,600
mmcauliffe/Conch-sounds
conch/main.py
acoustic_similarity_directories
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: if stop_check is not None and stop_check(): return if call_back is not None: cur += 1 if cur % 20 == 0: call_back(cur) if not x.lower().endswith('.wav'): continue if not y.lower().endswith('.wav'): continue if x == y: continue path_mapping.append((x, y)) result = acoustic_similarity_mapping(path_mapping, analysis_function, distance_function, stop_check, call_back, multiprocessing) return result
python
def acoustic_similarity_directories(directories, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True): 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: if stop_check is not None and stop_check(): return if call_back is not None: cur += 1 if cur % 20 == 0: call_back(cur) if not x.lower().endswith('.wav'): continue if not y.lower().endswith('.wav'): continue if x == y: continue path_mapping.append((x, y)) result = acoustic_similarity_mapping(path_mapping, analysis_function, distance_function, stop_check, call_back, multiprocessing) return result
[ "def", "acoustic_similarity_directories", "(", "directories", ",", "analysis_function", ",", "distance_function", ",", "stop_check", "=", "None", ",", "call_back", "=", "None", ",", "multiprocessing", "=", "True", ")", ":", "files", "=", "[", "]", "if", "call_ba...
Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed
[ "Analyze", "many", "directories", "." ]
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/main.py#L76-L130
10,601
mmcauliffe/Conch-sounds
conch/distance/dtw.py
dtw_distance
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`. """ if not isinstance(rep_one, np.ndarray): rep_one = rep_one.to_array() if not isinstance(rep_two, np.ndarray): rep_two = rep_two.to_array() assert (rep_one.shape[1] == rep_two.shape[1]) distMat = generate_distance_matrix(rep_one, rep_two) return regularDTW(distMat, norm=norm)
python
def dtw_distance(rep_one, rep_two, norm=True): if not isinstance(rep_one, np.ndarray): rep_one = rep_one.to_array() if not isinstance(rep_two, np.ndarray): rep_two = rep_two.to_array() assert (rep_one.shape[1] == rep_two.shape[1]) distMat = generate_distance_matrix(rep_one, rep_two) return regularDTW(distMat, norm=norm)
[ "def", "dtw_distance", "(", "rep_one", ",", "rep_two", ",", "norm", "=", "True", ")", ":", "if", "not", "isinstance", "(", "rep_one", ",", "np", ".", "ndarray", ")", ":", "rep_one", "=", "rep_one", ".", "to_array", "(", ")", "if", "not", "isinstance", ...
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`.
[ "Computes", "the", "distance", "between", "two", "representations", "with", "the", "same", "number", "of", "filters", "using", "Dynamic", "Time", "Warping", "." ]
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/distance/dtw.py#L16-L41
10,602
mmcauliffe/Conch-sounds
conch/distance/dtw.py
generate_distance_matrix
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 the second dimension. Returns ------- 2D array Local distance matrix. """ if weights is None: weights = ones((source.shape[1], 1)) sLen = source.shape[0] tLen = target.shape[0] distMat = zeros((sLen, tLen)) for i in range(sLen): for j in range(tLen): distMat[i, j] = euclidean(source[i, :], target[j, :]) return distMat
python
def generate_distance_matrix(source, target, weights=None): if weights is None: weights = ones((source.shape[1], 1)) sLen = source.shape[0] tLen = target.shape[0] distMat = zeros((sLen, tLen)) for i in range(sLen): for j in range(tLen): distMat[i, j] = euclidean(source[i, :], target[j, :]) return distMat
[ "def", "generate_distance_matrix", "(", "source", ",", "target", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "weights", "=", "ones", "(", "(", "source", ".", "shape", "[", "1", "]", ",", "1", ")", ")", "sLen", "=", "s...
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 the second dimension. Returns ------- 2D array Local distance matrix.
[ "Generates", "a", "local", "distance", "matrix", "for", "use", "in", "dynamic", "time", "warping", "." ]
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/distance/dtw.py#L44-L68
10,603
mmcauliffe/Conch-sounds
conch/distance/dtw.py
regularDTW
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)) # totalDistance[i+1,j+1] = totalDistance[i+1,j+1] + minPrevDistance # minDirection[i,j] = direction minDirection[i, j], totalDistance[i, j] = min( enumerate([totalDistance[i - 1, j - 1] + 2 * totalDistance[i, j], totalDistance[i - 1, j] + totalDistance[i, j], totalDistance[i, j - 1] + totalDistance[i, j]]), key=operator.itemgetter(1)) if norm: return totalDistance[sLen - 1, tLen - 1] / (sLen + tLen) return totalDistance[sLen - 1, tLen - 1]
python
def regularDTW(distMat, norm=True): 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)) # totalDistance[i+1,j+1] = totalDistance[i+1,j+1] + minPrevDistance # minDirection[i,j] = direction minDirection[i, j], totalDistance[i, j] = min( enumerate([totalDistance[i - 1, j - 1] + 2 * totalDistance[i, j], totalDistance[i - 1, j] + totalDistance[i, j], totalDistance[i, j - 1] + totalDistance[i, j]]), key=operator.itemgetter(1)) if norm: return totalDistance[sLen - 1, tLen - 1] / (sLen + tLen) return totalDistance[sLen - 1, tLen - 1]
[ "def", "regularDTW", "(", "distMat", ",", "norm", "=", "True", ")", ":", "sLen", ",", "tLen", "=", "distMat", ".", "shape", "totalDistance", "=", "zeros", "(", "(", "sLen", ",", "tLen", ")", ")", "totalDistance", "[", "0", ":", "sLen", ",", "0", ":...
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.
[ "Use", "a", "local", "distance", "matrix", "to", "perform", "dynamic", "time", "warping", "." ]
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/distance/dtw.py#L71-L109
10,604
mmcauliffe/Conch-sounds
conch/analysis/helper.py
preproc
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: sig = sig[:, 0] except IndexError: pass if False and sr != oldsr: t = len(sig) / oldsr numsamp = int(t * sr) proc = resample(sig, numsamp) else: proc = sig sr = oldsr # proc = proc / 32768 if alpha is not None and alpha != 0: proc = lfilter([1., -alpha], 1, proc) return sr, proc
python
def preproc(path, sr=16000, alpha=0.95): oldsr, sig = wavfile.read(path) try: sig = sig[:, 0] except IndexError: pass if False and sr != oldsr: t = len(sig) / oldsr numsamp = int(t * sr) proc = resample(sig, numsamp) else: proc = sig sr = oldsr # proc = proc / 32768 if alpha is not None and alpha != 0: proc = lfilter([1., -alpha], 1, proc) return sr, proc
[ "def", "preproc", "(", "path", ",", "sr", "=", "16000", ",", "alpha", "=", "0.95", ")", ":", "oldsr", ",", "sig", "=", "wavfile", ".", "read", "(", "path", ")", "try", ":", "sig", "=", "sig", "[", ":", ",", "0", "]", "except", "IndexError", ":"...
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.
[ "Preprocess", "a", ".", "wav", "file", "for", "later", "processing", ".", "Currently", "assumes", "a", "16", "-", "bit", "PCM", "input", ".", "Only", "returns", "left", "channel", "of", "stereo", "files", "." ]
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/analysis/helper.py#L29-L67
10,605
mmcauliffe/Conch-sounds
conch/analysis/helper.py
fftfilt
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: N = 2 ** np.arange(np.ceil(np.log2(N_b)), np.floor(np.log2(N_x))) cost = np.ceil(N_x / (N - N_b + 1)) * N * (np.log2(N) + 1) if len(cost) > 0: N_fft = N[np.argmin(cost)] else: N_fft = 2 ** nextpow2(N_b + N_x - 1) else: # When the filter length is at least as long as the signal, # filter the signal using a single block: N_fft = 2 ** nextpow2(N_b + N_x - 1) N_fft = int(N_fft) # Compute the block length: L = int(N_fft - N_b + 1) # Compute the transform of the filter: H = fft(b, N_fft) y = np.zeros(N_x, np.float32) i = 0 while i <= N_x: il = np.min([i + L, N_x]) k = np.min([i + N_fft, N_x]) yt = ifft(fft(x[i:il], N_fft) * H, N_fft) # Overlap.. y[i:k] = y[i:k] + yt[:k - i] # and add i += L return y
python
def fftfilt(b, x, *n): 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: N = 2 ** np.arange(np.ceil(np.log2(N_b)), np.floor(np.log2(N_x))) cost = np.ceil(N_x / (N - N_b + 1)) * N * (np.log2(N) + 1) if len(cost) > 0: N_fft = N[np.argmin(cost)] else: N_fft = 2 ** nextpow2(N_b + N_x - 1) else: # When the filter length is at least as long as the signal, # filter the signal using a single block: N_fft = 2 ** nextpow2(N_b + N_x - 1) N_fft = int(N_fft) # Compute the block length: L = int(N_fft - N_b + 1) # Compute the transform of the filter: H = fft(b, N_fft) y = np.zeros(N_x, np.float32) i = 0 while i <= N_x: il = np.min([i + L, N_x]) k = np.min([i + N_fft, N_x]) yt = ifft(fft(x[i:il], N_fft) * H, N_fft) # Overlap.. y[i:k] = y[i:k] + yt[:k - i] # and add i += L return y
[ "def", "fftfilt", "(", "b", ",", "x", ",", "*", "n", ")", ":", "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 nea...
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.
[ "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", ...
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/analysis/helper.py#L121-L184
10,606
mmcauliffe/Conch-sounds
conch/analysis/mfcc/rastamat.py
construct_filterbank
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 i in range(num_filters): fs = bin_freqs[i + np.arange(3)] fs = fs[1] + (fs - fs[1]) loslope = (fftfreqs - fs[0]) / (fs[1] - fs[0]) highslope = (fs[2] - fftfreqs) / (fs[2] - fs[1]) fbank[i, :] = np.maximum(np.zeros(loslope.shape), np.minimum(loslope, highslope)) return fbank.transpose()
python
def construct_filterbank(num_filters, nfft, sr, min_freq, max_freq): 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 i in range(num_filters): fs = bin_freqs[i + np.arange(3)] fs = fs[1] + (fs - fs[1]) loslope = (fftfreqs - fs[0]) / (fs[1] - fs[0]) highslope = (fs[2] - fftfreqs) / (fs[2] - fs[1]) fbank[i, :] = np.maximum(np.zeros(loslope.shape), np.minimum(loslope, highslope)) return fbank.transpose()
[ "def", "construct_filterbank", "(", "num_filters", ",", "nfft", ",", "sr", ",", "min_freq", ",", "max_freq", ")", ":", "min_mel", "=", "freq_to_mel", "(", "min_freq", ")", "max_mel", "=", "freq_to_mel", "(", "max_freq", ")", "mel_points", "=", "np", ".", "...
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.
[ "Constructs", "a", "mel", "-", "frequency", "filter", "bank", "." ]
e05535fd08e4b0e47e37a77ef521d05eff1d6bc5
https://github.com/mmcauliffe/Conch-sounds/blob/e05535fd08e4b0e47e37a77ef521d05eff1d6bc5/conch/analysis/mfcc/rastamat.py#L35-L66
10,607
frmdstryr/enamlx
enamlx/core/looper.py
ItemViewLooper.windowed_iterable
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: continue elif i>=(effective_offset+self.item_view.iterable_fetch_size): return yield item
python
def windowed_iterable(self): # Seek to offset effective_offset = max(0,self.item_view.iterable_index) for i,item in enumerate(self.iterable): if i<effective_offset: continue elif i>=(effective_offset+self.item_view.iterable_fetch_size): return yield item
[ "def", "windowed_iterable", "(", "self", ")", ":", "# Seek to offset", "effective_offset", "=", "max", "(", "0", ",", "self", ".", "item_view", ".", "iterable_index", ")", "for", "i", ",", "item", "in", "enumerate", "(", "self", ".", "iterable", ")", ":", ...
That returns only the window
[ "That", "returns", "only", "the", "window" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/core/looper.py#L190-L199
10,608
frmdstryr/enamlx
enamlx/core/looper.py
ItemViewLooper.refresh_items
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): iteration.extend(child) else: iteration.append(child) # Add to old items list #self.old_items.extend(old_items) #if self._dirty: for iteration in old_items: for old in iteration: if not old.is_destroyed: old.destroy() if len(new_items) > 0: expanded = [] recursive_expand(sum(new_items, []), expanded) self.parent.insert_children(self, expanded) self.items = new_items# if self._dirty else new_items+old_items self._iter_data = new_iter_data
python
def refresh_items(self): 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): iteration.extend(child) else: iteration.append(child) # Add to old items list #self.old_items.extend(old_items) #if self._dirty: for iteration in old_items: for old in iteration: if not old.is_destroyed: old.destroy() if len(new_items) > 0: expanded = [] recursive_expand(sum(new_items, []), expanded) self.parent.insert_children(self, expanded) self.items = new_items# if self._dirty else new_items+old_items self._iter_data = new_iter_data
[ "def", "refresh_items", "(", "self", ")", ":", "old_items", "=", "self", ".", "items", "[", ":", "]", "# if self._dirty else []", "old_iter_data", "=", "self", ".", "_iter_data", "# if self._dirty else {}", "iterable", "=", "self", ".", "windowed_iterable", "patte...
Refresh the items of the pattern. This method destroys the old items and creates and initializes the new items.
[ "Refresh", "the", "items", "of", "the", "pattern", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/core/looper.py#L201-L252
10,609
frmdstryr/enamlx
enamlx/qt/qt_double_spin_box.py
QtDoubleSpinBox.create_widget
def create_widget(self): """ Create the underlying QDoubleSpinBox widget. """ widget = QDoubleSpinBox(self.parent_widget()) widget.setKeyboardTracking(False) self.widget = widget
python
def create_widget(self): widget = QDoubleSpinBox(self.parent_widget()) widget.setKeyboardTracking(False) self.widget = widget
[ "def", "create_widget", "(", "self", ")", ":", "widget", "=", "QDoubleSpinBox", "(", "self", ".", "parent_widget", "(", ")", ")", "widget", ".", "setKeyboardTracking", "(", "False", ")", "self", ".", "widget", "=", "widget" ]
Create the underlying QDoubleSpinBox widget.
[ "Create", "the", "underlying", "QDoubleSpinBox", "widget", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_double_spin_box.py#L24-L30
10,610
frmdstryr/enamlx
enamlx/qt/qt_table_view.py
QtTableViewItem._update_index
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: self._refresh_count += 1 timed_call(self._loading_interval, self._update_delegate)
python
def _update_index(self): d = self.declaration self.index = self.view.model.index(d.row, d.column) if self.delegate: self._refresh_count += 1 timed_call(self._loading_interval, self._update_delegate)
[ "def", "_update_index", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "index", "=", "self", ".", "view", ".", "model", ".", "index", "(", "d", ".", "row", ",", "d", ".", "column", ")", "if", "self", ".", "delegate", ":...
Update the reference to the index within the table
[ "Update", "the", "reference", "to", "the", "index", "within", "the", "table" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_table_view.py#L161-L167
10,611
frmdstryr/enamlx
enamlx/qt/qt_table_view.py
QtTableViewItem._update_delegate
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 to make a new one delegate.create_widget() delegate.init_widget() # Set the index widget self.view.widget.setIndexWidget(self.index, delegate.widget) except RuntimeError: pass
python
def _update_delegate(self): 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 to make a new one delegate.create_widget() delegate.init_widget() # Set the index widget self.view.widget.setIndexWidget(self.index, delegate.widget) except RuntimeError: pass
[ "def", "_update_delegate", "(", "self", ")", ":", "self", ".", "_refresh_count", "-=", "1", "if", "self", ".", "_refresh_count", "!=", "0", ":", "return", "try", ":", "delegate", "=", "self", ".", "delegate", "if", "not", "self", ".", "is_visible", "(", ...
Update the delegate cell widget. This is deferred so it does not get called until the user is done scrolling.
[ "Update", "the", "delegate", "cell", "widget", ".", "This", "is", "deferred", "so", "it", "does", "not", "get", "called", "until", "the", "user", "is", "done", "scrolling", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_table_view.py#L169-L188
10,612
frmdstryr/enamlx
enamlx/qt/qt_table_view.py
QtTableViewItem.data_changed
def data_changed(self, change): """ Notify the model that data has changed in this cell! """ index = self.index if index: self.view.model.dataChanged.emit(index, index)
python
def data_changed(self, change): index = self.index if index: self.view.model.dataChanged.emit(index, index)
[ "def", "data_changed", "(", "self", ",", "change", ")", ":", "index", "=", "self", ".", "index", "if", "index", ":", "self", ".", "view", ".", "model", ".", "dataChanged", ".", "emit", "(", "index", ",", "index", ")" ]
Notify the model that data has changed in this cell!
[ "Notify", "the", "model", "that", "data", "has", "changed", "in", "this", "cell!" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_table_view.py#L194-L198
10,613
frmdstryr/enamlx
enamlx/qt/qt_occ_viewer.py
QtBaseViewer.GetHandle
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 ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [ ctypes.py_object] win_id = ctypes.pythonapi.PyCObject_AsVoidPtr(win_id) elif type(win_id) is not int: #PyQt4 or 5 ## below integer cast may be required because self.winId() can ## returns a sip.voitptr according to the PyQt version used ## as well as the python version win_id = int(win_id) return win_id
python
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 ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [ ctypes.py_object] win_id = ctypes.pythonapi.PyCObject_AsVoidPtr(win_id) elif type(win_id) is not int: #PyQt4 or 5 ## below integer cast may be required because self.winId() can ## returns a sip.voitptr according to the PyQt version used ## as well as the python version win_id = int(win_id) return win_id
[ "def", "GetHandle", "(", "self", ")", ":", "win_id", "=", "self", ".", "winId", "(", ")", "# this returns either an int or voitptr\r", "if", "\"%s\"", "%", "type", "(", "win_id", ")", "==", "\"<type 'PyCObject'>\"", ":", "# PySide\r", "### with PySide, self.winId() ...
returns an the identifier of the GUI widget. It must be an integer
[ "returns", "an", "the", "identifier", "of", "the", "GUI", "widget", ".", "It", "must", "be", "an", "integer" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_occ_viewer.py#L160-L182
10,614
frmdstryr/enamlx
examples/occ_viewer/occ/occ_shape.py
Topology._map_shapes_and_ancestors
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 if not topo_entity in topo_set: if self.ignore_orientation: unique = True for i in topo_set: if i.IsSame(topo_entity): unique = False break if unique: yield topo_entity else: yield topo_entity topo_set.add(topo_entity) topology_iterator.Next()
python
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 if not topo_entity in topo_set: if self.ignore_orientation: unique = True for i in topo_set: if i.IsSame(topo_entity): unique = False break if unique: yield topo_entity else: yield topo_entity topo_set.add(topo_entity) topology_iterator.Next()
[ "def", "_map_shapes_and_ancestors", "(", "self", ",", "topoTypeA", ",", "topoTypeB", ",", "topologicalEntity", ")", ":", "topo_set", "=", "set", "(", ")", "_map", "=", "TopTools_IndexedDataMapOfShapeListOfShape", "(", ")", "topexp_MapShapesAndAncestors", "(", "self", ...
using the same method @param topoTypeA: @param topoTypeB: @param topologicalEntity:
[ "using", "the", "same", "method" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/examples/occ_viewer/occ/occ_shape.py#L307-L341
10,615
frmdstryr/enamlx
examples/occ_viewer/occ/occ_shape.py
OccDependentShape.init_layout
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 be fully initialized and layed out when this is called. """ for child in self.children(): self.child_added(child) self.update_shape({})
python
def init_layout(self): for child in self.children(): self.child_added(child) self.update_shape({})
[ "def", "init_layout", "(", "self", ")", ":", "for", "child", "in", "self", ".", "children", "(", ")", ":", "self", ".", "child_added", "(", "child", ")", "self", ".", "update_shape", "(", "{", "}", ")" ]
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 be fully initialized and layed out when this is called.
[ "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",...
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/examples/occ_viewer/occ/occ_shape.py#L580-L590
10,616
frmdstryr/enamlx
enamlx/qt/qt_key_event.py
QtKeyEvent.init_widget
def init_widget(self): """ The KeyEvent uses the parent_widget as it's widget """ super(QtKeyEvent, self).init_widget() d = self.declaration widget = self.widget self._keyPressEvent = widget.keyPressEvent self._keyReleaseEvent = widget.keyReleaseEvent self.set_enabled(d.enabled) self.set_keys(d.keys)
python
def init_widget(self): super(QtKeyEvent, self).init_widget() d = self.declaration widget = self.widget self._keyPressEvent = widget.keyPressEvent self._keyReleaseEvent = widget.keyReleaseEvent self.set_enabled(d.enabled) self.set_keys(d.keys)
[ "def", "init_widget", "(", "self", ")", ":", "super", "(", "QtKeyEvent", ",", "self", ")", ".", "init_widget", "(", ")", "d", "=", "self", ".", "declaration", "widget", "=", "self", ".", "widget", "self", ".", "_keyPressEvent", "=", "widget", ".", "key...
The KeyEvent uses the parent_widget as it's widget
[ "The", "KeyEvent", "uses", "the", "parent_widget", "as", "it", "s", "widget" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_key_event.py#L47-L55
10,617
frmdstryr/enamlx
enamlx/qt/qt_key_event.py
QtKeyEvent.set_keys
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) if mod_code is None: raise KeyError("Invalid key modifier '{}'" .format(mod_code)) modifier |= mod_code if code not in codes: codes[code] = [] codes[code].append(modifier) self.codes = codes
python
def set_keys(self, keys): 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) if mod_code is None: raise KeyError("Invalid key modifier '{}'" .format(mod_code)) modifier |= mod_code if code not in codes: codes[code] = [] codes[code].append(modifier) self.codes = codes
[ "def", "set_keys", "(", "self", ",", "keys", ")", ":", "codes", "=", "{", "}", "for", "key", "in", "keys", ":", "parts", "=", "[", "k", ".", "strip", "(", ")", ".", "lower", "(", ")", "for", "k", "in", "key", ".", "split", "(", "\"+\"", ")", ...
Parse all the key codes and save them
[ "Parse", "all", "the", "key", "codes", "and", "save", "them" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_key_event.py#L70-L89
10,618
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin._setup_features
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: self.hook_drop() features = self._extra_features if features & GraphicFeature.WheelEvent: self.hook_wheel() if features & GraphicFeature.DrawEvent: self.hook_draw()
python
def _setup_features(self): 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: self.hook_drop() features = self._extra_features if features & GraphicFeature.WheelEvent: self.hook_wheel() if features & GraphicFeature.DrawEvent: self.hook_draw()
[ "def", "_setup_features", "(", "self", ")", ":", "features", "=", "self", ".", "_features", "=", "self", ".", "declaration", ".", "features", "if", "not", "features", ":", "return", "if", "features", "&", "Feature", ".", "FocusTraversal", ":", "self", ".",...
Setup the advanced widget feature handlers.
[ "Setup", "the", "advanced", "widget", "feature", "handlers", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L158-L178
10,619
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin._teardown_features
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: self.unhook_focus_events() if features & Feature.DragEnabled: self.unhook_drag() if features & Feature.DropEnabled: self.unhook_drop() features = self._extra_features if features & GraphicFeature.WheelEvent: self.unhook_wheel() if features & GraphicFeature.DrawEvent: self.unhook_draw()
python
def _teardown_features(self): features = self._features if not features: return if features & Feature.FocusTraversal: self.unhook_focus_traversal() if features & Feature.FocusEvents: self.unhook_focus_events() if features & Feature.DragEnabled: self.unhook_drag() if features & Feature.DropEnabled: self.unhook_drop() features = self._extra_features if features & GraphicFeature.WheelEvent: self.unhook_wheel() if features & GraphicFeature.DrawEvent: self.unhook_draw()
[ "def", "_teardown_features", "(", "self", ")", ":", "features", "=", "self", ".", "_features", "if", "not", "features", ":", "return", "if", "features", "&", "Feature", ".", "FocusTraversal", ":", "self", ".", "unhook_focus_traversal", "(", ")", "if", "featu...
Teardowns the advanced widget feature handlers.
[ "Teardowns", "the", "advanced", "widget", "feature", "handlers", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L180-L200
10,620
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.tab_focus_request
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. """ widget = self.focus_target() if not widget.focusPolicy & Qt.TabFocus: return False if not widget.isEnabled(): return False if not widget.isVisibleTo(widget.window()): return False widget.setFocus(reason) return False
python
def tab_focus_request(self, reason): widget = self.focus_target() if not widget.focusPolicy & Qt.TabFocus: return False if not widget.isEnabled(): return False if not widget.isVisibleTo(widget.window()): return False widget.setFocus(reason) return False
[ "def", "tab_focus_request", "(", "self", ",", "reason", ")", ":", "widget", "=", "self", ".", "focus_target", "(", ")", "if", "not", "widget", ".", "focusPolicy", "&", "Qt", ".", "TabFocus", ":", "return", "False", "if", "not", "widget", ".", "isEnabled"...
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.
[ "Handle", "a", "custom", "tab", "focus", "request", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L205-L231
10,621
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.hook_focus_events
def hook_focus_events(self): """ Install the hooks for focus events. This method may be overridden by subclasses as needed. """ widget = self.widget widget.focusInEvent = self.focusInEvent widget.focusOutEvent = self.focusOutEvent
python
def hook_focus_events(self): widget = self.widget widget.focusInEvent = self.focusInEvent widget.focusOutEvent = self.focusOutEvent
[ "def", "hook_focus_events", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "widget", ".", "focusInEvent", "=", "self", ".", "focusInEvent", "widget", ".", "focusOutEvent", "=", "self", ".", "focusOutEvent" ]
Install the hooks for focus events. This method may be overridden by subclasses as needed.
[ "Install", "the", "hooks", "for", "focus", "events", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L258-L266
10,622
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.focusNextPrevChild
def focusNextPrevChild(self, next_child): """ The default 'focusNextPrevChild' implementation. """ fd = focus_registry.focused_declaration() if next_child: child = self.declaration.next_focus_child(fd) reason = Qt.TabFocusReason else: child = self.declaration.previous_focus_child(fd) reason = Qt.BacktabFocusReason if child is not None and child.proxy_is_active: return child.proxy.tab_focus_request(reason) widget = self.widget return type(widget).focusNextPrevChild(widget, next_child)
python
def focusNextPrevChild(self, next_child): fd = focus_registry.focused_declaration() if next_child: child = self.declaration.next_focus_child(fd) reason = Qt.TabFocusReason else: child = self.declaration.previous_focus_child(fd) reason = Qt.BacktabFocusReason if child is not None and child.proxy_is_active: return child.proxy.tab_focus_request(reason) widget = self.widget return type(widget).focusNextPrevChild(widget, next_child)
[ "def", "focusNextPrevChild", "(", "self", ",", "next_child", ")", ":", "fd", "=", "focus_registry", ".", "focused_declaration", "(", ")", "if", "next_child", ":", "child", "=", "self", ".", "declaration", ".", "next_focus_child", "(", "fd", ")", "reason", "=...
The default 'focusNextPrevChild' implementation.
[ "The", "default", "focusNextPrevChild", "implementation", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L278-L292
10,623
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.focusInEvent
def focusInEvent(self, event): """ The default 'focusInEvent' implementation. """ widget = self.widget type(widget).focusInEvent(widget, event) self.declaration.focus_gained()
python
def focusInEvent(self, event): widget = self.widget type(widget).focusInEvent(widget, event) self.declaration.focus_gained()
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "widget", "=", "self", ".", "widget", "type", "(", "widget", ")", ".", "focusInEvent", "(", "widget", ",", "event", ")", "self", ".", "declaration", ".", "focus_gained", "(", ")" ]
The default 'focusInEvent' implementation.
[ "The", "default", "focusInEvent", "implementation", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L294-L300
10,624
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.focusOutEvent
def focusOutEvent(self, event): """ The default 'focusOutEvent' implementation. """ widget = self.widget type(widget).focusOutEvent(widget, event) self.declaration.focus_lost()
python
def focusOutEvent(self, event): widget = self.widget type(widget).focusOutEvent(widget, event) self.declaration.focus_lost()
[ "def", "focusOutEvent", "(", "self", ",", "event", ")", ":", "widget", "=", "self", ".", "widget", "type", "(", "widget", ")", ".", "focusOutEvent", "(", "widget", ",", "event", ")", "self", ".", "declaration", ".", "focus_lost", "(", ")" ]
The default 'focusOutEvent' implementation.
[ "The", "default", "focusOutEvent", "implementation", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L302-L308
10,625
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.hook_drag
def hook_drag(self): """ Install the hooks for drag operations. """ widget = self.widget widget.mousePressEvent = self.mousePressEvent widget.mouseMoveEvent = self.mouseMoveEvent widget.mouseReleaseEvent = self.mouseReleaseEvent
python
def hook_drag(self): widget = self.widget widget.mousePressEvent = self.mousePressEvent widget.mouseMoveEvent = self.mouseMoveEvent widget.mouseReleaseEvent = self.mouseReleaseEvent
[ "def", "hook_drag", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "widget", ".", "mousePressEvent", "=", "self", ".", "mousePressEvent", "widget", ".", "mouseMoveEvent", "=", "self", ".", "mouseMoveEvent", "widget", ".", "mouseReleaseEvent", "="...
Install the hooks for drag operations.
[ "Install", "the", "hooks", "for", "drag", "operations", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L310-L317
10,626
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.unhook_drag
def unhook_drag(self): """ Remove the hooks for drag operations. """ widget = self.widget del widget.mousePressEvent del widget.mouseMoveEvent del widget.mouseReleaseEvent
python
def unhook_drag(self): widget = self.widget del widget.mousePressEvent del widget.mouseMoveEvent del widget.mouseReleaseEvent
[ "def", "unhook_drag", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "del", "widget", ".", "mousePressEvent", "del", "widget", ".", "mouseMoveEvent", "del", "widget", ".", "mouseReleaseEvent" ]
Remove the hooks for drag operations.
[ "Remove", "the", "hooks", "for", "drag", "operations", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L319-L326
10,627
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.hook_drop
def hook_drop(self): """ Install hooks for drop operations. """ widget = self.widget widget.setAcceptDrops(True) widget.dragEnterEvent = self.dragEnterEvent widget.dragMoveEvent = self.dragMoveEvent widget.dragLeaveEvent = self.dragLeaveEvent widget.dropEvent = self.dropEvent
python
def hook_drop(self): widget = self.widget widget.setAcceptDrops(True) widget.dragEnterEvent = self.dragEnterEvent widget.dragMoveEvent = self.dragMoveEvent widget.dragLeaveEvent = self.dragLeaveEvent widget.dropEvent = self.dropEvent
[ "def", "hook_drop", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "widget", ".", "setAcceptDrops", "(", "True", ")", "widget", ".", "dragEnterEvent", "=", "self", ".", "dragEnterEvent", "widget", ".", "dragMoveEvent", "=", "self", ".", "drag...
Install hooks for drop operations.
[ "Install", "hooks", "for", "drop", "operations", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L359-L368
10,628
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.unhook_drop
def unhook_drop(self): """ Remove hooks for drop operations. """ widget = self.widget widget.setAcceptDrops(False) del widget.dragEnterEvent del widget.dragMoveEvent del widget.dragLeaveEvent del widget.dropEvent
python
def unhook_drop(self): widget = self.widget widget.setAcceptDrops(False) del widget.dragEnterEvent del widget.dragMoveEvent del widget.dragLeaveEvent del widget.dropEvent
[ "def", "unhook_drop", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "widget", ".", "setAcceptDrops", "(", "False", ")", "del", "widget", ".", "dragEnterEvent", "del", "widget", ".", "dragMoveEvent", "del", "widget", ".", "dragLeaveEvent", "del...
Remove hooks for drop operations.
[ "Remove", "hooks", "for", "drop", "operations", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L370-L379
10,629
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.draw
def draw(self, painter, options, widget): """ Handle the draw event for the widget. """ self.declaration.draw(painter, options, widget)
python
def draw(self, painter, options, widget): self.declaration.draw(painter, options, widget)
[ "def", "draw", "(", "self", ",", "painter", ",", "options", ",", "widget", ")", ":", "self", ".", "declaration", ".", "draw", "(", "painter", ",", "options", ",", "widget", ")" ]
Handle the draw event for the widget.
[ "Handle", "the", "draw", "event", "for", "the", "widget", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L477-L481
10,630
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
FeatureMixin.get_action
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. """ action = self._widget_action if action is None and create: action = self._widget_action = QWidgetAction(None) action.setDefaultWidget(self.widget) return action
python
def get_action(self, create=False): action = self._widget_action if action is None and create: action = self._widget_action = QWidgetAction(None) action.setDefaultWidget(self.widget) return action
[ "def", "get_action", "(", "self", ",", "create", "=", "False", ")", ":", "action", "=", "self", ".", "_widget_action", "if", "action", "is", "None", "and", "create", ":", "action", "=", "self", ".", "_widget_action", "=", "QWidgetAction", "(", "None", ")...
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.
[ "Get", "the", "shared", "widget", "action", "for", "this", "widget", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L486-L507
10,631
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsView.set_renderer
def set_renderer(self, renderer): """ Set the viewport widget. """ viewport = None if renderer == 'opengl': from enaml.qt.QtWidgets import QOpenGLWidget viewport = QOpenGLWidget() elif renderer == 'default': try: from enaml.qt.QtWidgets import QOpenGLWidget viewport = QOpenGLWidget() except ImportError as e: warnings.warn( "QOpenGLWidget could not be imported: {}".format(e)) self.widget.setViewport(viewport)
python
def set_renderer(self, renderer): viewport = None if renderer == 'opengl': from enaml.qt.QtWidgets import QOpenGLWidget viewport = QOpenGLWidget() elif renderer == 'default': try: from enaml.qt.QtWidgets import QOpenGLWidget viewport = QOpenGLWidget() except ImportError as e: warnings.warn( "QOpenGLWidget could not be imported: {}".format(e)) self.widget.setViewport(viewport)
[ "def", "set_renderer", "(", "self", ",", "renderer", ")", ":", "viewport", "=", "None", "if", "renderer", "==", "'opengl'", ":", "from", "enaml", ".", "qt", ".", "QtWidgets", "import", "QOpenGLWidget", "viewport", "=", "QOpenGLWidget", "(", ")", "elif", "r...
Set the viewport widget.
[ "Set", "the", "viewport", "widget", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L674-L689
10,632
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsView.on_selection_changed
def on_selection_changed(self): """ Callback invoked one the selection has changed. """ d = self.declaration selection = self.scene.selectedItems() self._guards |= 0x01 try: d.selected_items = [item.ref().declaration for item in selection if item.ref()] finally: self._guards &= ~0x01
python
def on_selection_changed(self): d = self.declaration selection = self.scene.selectedItems() self._guards |= 0x01 try: d.selected_items = [item.ref().declaration for item in selection if item.ref()] finally: self._guards &= ~0x01
[ "def", "on_selection_changed", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "selection", "=", "self", ".", "scene", ".", "selectedItems", "(", ")", "self", ".", "_guards", "|=", "0x01", "try", ":", "d", ".", "selected_items", "=", "[", ...
Callback invoked one the selection has changed.
[ "Callback", "invoked", "one", "the", "selection", "has", "changed", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L698-L709
10,633
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsView.set_background
def set_background(self, background): """ Set the background color of the widget. """ scene = self.scene scene.setBackgroundBrush(QColor.fromRgba(background.argb))
python
def set_background(self, background): scene = self.scene scene.setBackgroundBrush(QColor.fromRgba(background.argb))
[ "def", "set_background", "(", "self", ",", "background", ")", ":", "scene", "=", "self", ".", "scene", "scene", ".", "setBackgroundBrush", "(", "QColor", ".", "fromRgba", "(", "background", ".", "argb", ")", ")" ]
Set the background color of the widget.
[ "Set", "the", "background", "color", "of", "the", "widget", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L711-L716
10,634
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsView.scale_view
def scale_view(self, x, y): """ Scale the zoom but keep in in the min and max zoom bounds. """ d = self.declaration factor = self.widget.transform().scale(x, y).mapRect( QRectF(0, 0, 1, 1)).width() if (d.min_zoom > factor > d.max_zoom): return self.widget.scale(x, y) return factor
python
def scale_view(self, x, y): d = self.declaration factor = self.widget.transform().scale(x, y).mapRect( QRectF(0, 0, 1, 1)).width() if (d.min_zoom > factor > d.max_zoom): return self.widget.scale(x, y) return factor
[ "def", "scale_view", "(", "self", ",", "x", ",", "y", ")", ":", "d", "=", "self", ".", "declaration", "factor", "=", "self", ".", "widget", ".", "transform", "(", ")", ".", "scale", "(", "x", ",", "y", ")", ".", "mapRect", "(", "QRectF", "(", "...
Scale the zoom but keep in in the min and max zoom bounds.
[ "Scale", "the", "zoom", "but", "keep", "in", "in", "the", "min", "and", "max", "zoom", "bounds", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L748-L758
10,635
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsItem.destroy
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 the widget will be deleted # when the QWidgetAction is garbage collected. This means the # superclass destroy() method must run before the reference to # the QWidgetAction is dropped. del self._widget_action
python
def destroy(self): 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 the widget will be deleted # when the QWidgetAction is garbage collected. This means the # superclass destroy() method must run before the reference to # the QWidgetAction is dropped. del self._widget_action
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "_teardown_features", "(", ")", "focus_registry", ".", "unregister", "(", "self", ".", "widget", ")", "widget", "=", "self", ".", "widget", "if", "widget", "is", "not", "None", ":", "del", "self", "...
Destroy the underlying QWidget object.
[ "Destroy", "the", "underlying", "QWidget", "object", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L830-L845
10,636
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsItem.parent_widget
def parent_widget(self): """ Reimplemented to only return GraphicsItems """ parent = self.parent() if parent is not None and isinstance(parent, QtGraphicsItem): return parent.widget
python
def parent_widget(self): parent = self.parent() if parent is not None and isinstance(parent, QtGraphicsItem): return parent.widget
[ "def", "parent_widget", "(", "self", ")", ":", "parent", "=", "self", ".", "parent", "(", ")", "if", "parent", "is", "not", "None", "and", "isinstance", "(", "parent", ",", "QtGraphicsItem", ")", ":", "return", "parent", ".", "widget" ]
Reimplemented to only return GraphicsItems
[ "Reimplemented", "to", "only", "return", "GraphicsItems" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L847-L851
10,637
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
QtGraphicsWidget.init_layout
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 = QGraphicsProxyWidget(self.parent_widget()) widget = self.widget for item in self.child_widgets(): widget.setWidget(item) break super(QtGraphicsWidget, self).init_widget() super(QtGraphicsWidget, self).init_layout()
python
def init_layout(self): self.widget = QGraphicsProxyWidget(self.parent_widget()) widget = self.widget for item in self.child_widgets(): widget.setWidget(item) break super(QtGraphicsWidget, self).init_widget() super(QtGraphicsWidget, self).init_layout()
[ "def", "init_layout", "(", "self", ")", ":", "self", ".", "widget", "=", "QGraphicsProxyWidget", "(", "self", ".", "parent_widget", "(", ")", ")", "widget", "=", "self", ".", "widget", "for", "item", "in", "self", ".", "child_widgets", "(", ")", ":", "...
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.
[ "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", "...
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L937-L949
10,638
frmdstryr/enamlx
examples/occ_viewer/occ/occ_algo.py
OccOperation._dequeue_update
def _dequeue_update(self,change): """ Only update when all changes are done """ self._update_count -=1 if self._update_count !=0: return self.update_shape(change)
python
def _dequeue_update(self,change): self._update_count -=1 if self._update_count !=0: return self.update_shape(change)
[ "def", "_dequeue_update", "(", "self", ",", "change", ")", ":", "self", ".", "_update_count", "-=", "1", "if", "self", ".", "_update_count", "!=", "0", ":", "return", "self", ".", "update_shape", "(", "change", ")" ]
Only update when all changes are done
[ "Only", "update", "when", "all", "changes", "are", "done" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/examples/occ_viewer/occ/occ_algo.py#L72-L77
10,639
frmdstryr/enamlx
enamlx/widgets/graphics_view.py
GraphicsItem.show
def show(self): """ Ensure the widget is shown. Calling this method will also set the widget visibility to True. """ self.visible = True if self.proxy_is_active: self.proxy.ensure_visible()
python
def show(self): self.visible = True if self.proxy_is_active: self.proxy.ensure_visible()
[ "def", "show", "(", "self", ")", ":", "self", ".", "visible", "=", "True", "if", "self", ".", "proxy_is_active", ":", "self", ".", "proxy", ".", "ensure_visible", "(", ")" ]
Ensure the widget is shown. Calling this method will also set the widget visibility to True.
[ "Ensure", "the", "widget", "is", "shown", ".", "Calling", "this", "method", "will", "also", "set", "the", "widget", "visibility", "to", "True", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/graphics_view.py#L448-L454
10,640
frmdstryr/enamlx
enamlx/widgets/graphics_view.py
GraphicsItem.hide
def hide(self): """ Ensure the widget is hidden. Calling this method will also set the widget visibility to False. """ self.visible = False if self.proxy_is_active: self.proxy.ensure_hidden()
python
def hide(self): self.visible = False if self.proxy_is_active: self.proxy.ensure_hidden()
[ "def", "hide", "(", "self", ")", ":", "self", ".", "visible", "=", "False", "if", "self", ".", "proxy_is_active", ":", "self", ".", "proxy", ".", "ensure_hidden", "(", ")" ]
Ensure the widget is hidden. Calling this method will also set the widget visibility to False.
[ "Ensure", "the", "widget", "is", "hidden", ".", "Calling", "this", "method", "will", "also", "set", "the", "widget", "visibility", "to", "False", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/graphics_view.py#L456-L462
10,641
frmdstryr/enamlx
enamlx/widgets/graphics_view.py
GraphicsView.get_item_at
def get_item_at(self, *args, **kwargs): """ Return the items at the given position """ return self.proxy.get_item_at(coerce_point(*args, **kwargs))
python
def get_item_at(self, *args, **kwargs): return self.proxy.get_item_at(coerce_point(*args, **kwargs))
[ "def", "get_item_at", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "proxy", ".", "get_item_at", "(", "coerce_point", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
Return the items at the given position
[ "Return", "the", "items", "at", "the", "given", "position" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/graphics_view.py#L795-L797
10,642
frmdstryr/enamlx
enamlx/widgets/graphics_view.py
GraphicsView.center_on
def center_on(self, item): """ Center on the given item or point. """ if not isinstance(item, GraphicsItem): item = coerce_point(item) self.proxy.center_on(item)
python
def center_on(self, item): if not isinstance(item, GraphicsItem): item = coerce_point(item) self.proxy.center_on(item)
[ "def", "center_on", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "GraphicsItem", ")", ":", "item", "=", "coerce_point", "(", "item", ")", "self", ".", "proxy", ".", "center_on", "(", "item", ")" ]
Center on the given item or point.
[ "Center", "on", "the", "given", "item", "or", "point", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/graphics_view.py#L803-L807
10,643
frmdstryr/enamlx
enamlx/core/middleware.py
_custom_token_stream
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`. """ token_stream = default_make_token_stream(self) for processor in _token_stream_processors: token_stream = processor(token_stream) return token_stream
python
def _custom_token_stream(self): token_stream = default_make_token_stream(self) for processor in _token_stream_processors: token_stream = processor(token_stream) return token_stream
[ "def", "_custom_token_stream", "(", "self", ")", ":", "token_stream", "=", "default_make_token_stream", "(", "self", ")", "for", "processor", "in", "_token_stream_processors", ":", "token_stream", "=", "processor", "(", "token_stream", ")", "return", "token_stream" ]
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`.
[ "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...
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/core/middleware.py#L15-L27
10,644
frmdstryr/enamlx
enamlx/qt/qt_console.py
QtConsole.init_signal
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() # Let the interpreter run each 200 ms: timer.timeout.connect(lambda: None) timer.start(200) # hold onto ref, so the timer doesn't get cleaned up self._sigint_timer = timer
python
def init_signal(self): 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() # Let the interpreter run each 200 ms: timer.timeout.connect(lambda: None) timer.start(200) # hold onto ref, so the timer doesn't get cleaned up self._sigint_timer = timer
[ "def", "init_signal", "(", "self", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "lambda", "sig", ",", "frame", ":", "self", ".", "exit", "(", "-", "2", ")", ")", "# need a timer, so that QApplication doesn't block until a real\r", "# Q...
allow clean shutdown on sigint
[ "allow", "clean", "shutdown", "on", "sigint" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_console.py#L84-L95
10,645
frmdstryr/enamlx
examples/occ_viewer/occ/shape.py
Shape._update_position
def _update_position(self, change): """ Keep position in sync with x,y,z """ if change['type']!='update': return pt = gp_Pnt(self.x,self.y,self.z) if not pt.IsEqual(self.position,self.tolerance): self.position = pt
python
def _update_position(self, change): if change['type']!='update': return pt = gp_Pnt(self.x,self.y,self.z) if not pt.IsEqual(self.position,self.tolerance): self.position = pt
[ "def", "_update_position", "(", "self", ",", "change", ")", ":", "if", "change", "[", "'type'", "]", "!=", "'update'", ":", "return", "pt", "=", "gp_Pnt", "(", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "z", ")", "if", "not", "pt"...
Keep position in sync with x,y,z
[ "Keep", "position", "in", "sync", "with", "x", "y", "z" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/examples/occ_viewer/occ/shape.py#L229-L235
10,646
frmdstryr/enamlx
examples/occ_viewer/occ/shape.py
Shape._update_xyz
def _update_xyz(self, change): """ Keep x,y,z in sync with position """ self.x,self.y,self.z = self.position.X(),self.position.Y(),self.position.Z()
python
def _update_xyz(self, change): self.x,self.y,self.z = self.position.X(),self.position.Y(),self.position.Z()
[ "def", "_update_xyz", "(", "self", ",", "change", ")", ":", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "z", "=", "self", ".", "position", ".", "X", "(", ")", ",", "self", ".", "position", ".", "Y", "(", ")", ",", "self", ".", ...
Keep x,y,z in sync with position
[ "Keep", "x", "y", "z", "in", "sync", "with", "position" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/examples/occ_viewer/occ/shape.py#L238-L240
10,647
frmdstryr/enamlx
examples/occ_viewer/occ/shape.py
Shape._update_state
def _update_state(self, change): """ Keep position and direction in sync with axis """ self._block_updates = True try: self.position = self.axis.Location() self.direction = self.axis.Direction() finally: self._block_updates = False
python
def _update_state(self, change): self._block_updates = True try: self.position = self.axis.Location() self.direction = self.axis.Direction() finally: self._block_updates = False
[ "def", "_update_state", "(", "self", ",", "change", ")", ":", "self", ".", "_block_updates", "=", "True", "try", ":", "self", ".", "position", "=", "self", ".", "axis", ".", "Location", "(", ")", "self", ".", "direction", "=", "self", ".", "axis", "....
Keep position and direction in sync with axis
[ "Keep", "position", "and", "direction", "in", "sync", "with", "axis" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/examples/occ_viewer/occ/shape.py#L249-L256
10,648
frmdstryr/enamlx
enamlx/qt/qt_plot_area.py
AbstractQtPlotItem._refresh_multi_axis
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) #: Add new axis to scene self.widget.layout.addItem(self.axis,2,i+2) #: Link x axis to the parent axis self.viewbox.setXLink(self.widget.vb) #: Link y axis to the view self.axis.linkToView(self.viewbox) #: Set axis label self.axis.setLabel(d.label_right) #: Add Viewbox to parent scene self.parent().parent_widget().scene().addItem(self.viewbox)
python
def _refresh_multi_axis(self): 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) #: Add new axis to scene self.widget.layout.addItem(self.axis,2,i+2) #: Link x axis to the parent axis self.viewbox.setXLink(self.widget.vb) #: Link y axis to the view self.axis.linkToView(self.viewbox) #: Set axis label self.axis.setLabel(d.label_right) #: Add Viewbox to parent scene self.parent().parent_widget().scene().addItem(self.viewbox)
[ "def", "_refresh_multi_axis", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "#: Create a separate viewbox", "self", ".", "viewbox", "=", "pg", ".", "ViewBox", "(", ")", "#: If this is the first nested plot, use the parent right axis", "_plots", "=", "["...
If linked axis' are used, setup and link them
[ "If", "linked", "axis", "are", "used", "setup", "and", "link", "them" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_plot_area.py#L174-L204
10,649
frmdstryr/enamlx
enamlx/qt/qt_plot_area.py
AbstractQtPlotItem.on_resized
def on_resized(self): """ Update linked views """ d = self.declaration if not self.is_root and d.parent.multi_axis: if self.viewbox: self.viewbox.setGeometry(self.widget.vb.sceneBoundingRect()) self.viewbox.linkedViewChanged(self.widget.vb,self.viewbox.XAxis)
python
def on_resized(self): d = self.declaration if not self.is_root and d.parent.multi_axis: if self.viewbox: self.viewbox.setGeometry(self.widget.vb.sceneBoundingRect()) self.viewbox.linkedViewChanged(self.widget.vb,self.viewbox.XAxis)
[ "def", "on_resized", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "if", "not", "self", ".", "is_root", "and", "d", ".", "parent", ".", "multi_axis", ":", "if", "self", ".", "viewbox", ":", "self", ".", "viewbox", ".", "setGeometry", "...
Update linked views
[ "Update", "linked", "views" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_plot_area.py#L352-L358
10,650
frmdstryr/enamlx
enamlx/widgets/tree_view.py
TreeViewItem._get_columns
def _get_columns(self): """ List of child TreeViewColumns including this item as the first column """ return [self] + [c for c in self.children if isinstance(c, TreeViewColumn)]
python
def _get_columns(self): return [self] + [c for c in self.children if isinstance(c, TreeViewColumn)]
[ "def", "_get_columns", "(", "self", ")", ":", "return", "[", "self", "]", "+", "[", "c", "for", "c", "in", "self", ".", "children", "if", "isinstance", "(", "c", ",", "TreeViewColumn", ")", "]" ]
List of child TreeViewColumns including this item as the first column
[ "List", "of", "child", "TreeViewColumns", "including", "this", "item", "as", "the", "first", "column" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/tree_view.py#L90-L95
10,651
frmdstryr/enamlx
enamlx/widgets/tree_view.py
TreeViewItem._update_rows
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 for column, item in enumerate(self._columns): item.row = self.row # Row is the Parent item item.column = column
python
def _update_rows(self): for row, item in enumerate(self._items): item.row = row # Row is the Parent item item.column = 0 for column, item in enumerate(self._columns): item.row = self.row # Row is the Parent item item.column = column
[ "def", "_update_rows", "(", "self", ")", ":", "for", "row", ",", "item", "in", "enumerate", "(", "self", ".", "_items", ")", ":", "item", ".", "row", "=", "row", "# Row is the Parent item", "item", ".", "column", "=", "0", "for", "column", ",", "item",...
Update the row and column numbers of child items.
[ "Update", "the", "row", "and", "column", "numbers", "of", "child", "items", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/tree_view.py#L110-L118
10,652
frmdstryr/enamlx
enamlx/qt/qt_abstract_item_view.py
QAbstractAtomItemModel.setDeclaration
def setDeclaration(self, declaration): """ Set the declaration this model will use for rendering the the headers. """ assert isinstance(declaration.proxy, ProxyAbstractItemView), \ "The model declaration must be a QtAbstractItemView subclass. " \ "Got {]".format(declaration) self.declaration = declaration
python
def setDeclaration(self, declaration): assert isinstance(declaration.proxy, ProxyAbstractItemView), \ "The model declaration must be a QtAbstractItemView subclass. " \ "Got {]".format(declaration) self.declaration = declaration
[ "def", "setDeclaration", "(", "self", ",", "declaration", ")", ":", "assert", "isinstance", "(", "declaration", ".", "proxy", ",", "ProxyAbstractItemView", ")", ",", "\"The model declaration must be a QtAbstractItemView subclass. \"", "\"Got {]\"", ".", "format", "(", "...
Set the declaration this model will use for rendering the the headers.
[ "Set", "the", "declaration", "this", "model", "will", "use", "for", "rendering", "the", "the", "headers", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_abstract_item_view.py#L42-L51
10,653
frmdstryr/enamlx
enamlx/qt/qt_abstract_item_view.py
QAbstractAtomItemModel.data
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 elif role == Qt.TextAlignmentRole: h, v = d.text_alignment return TEXT_H_ALIGNMENTS[h] | TEXT_V_ALIGNMENTS[v] elif role == Qt.ForegroundRole and d.foreground: return get_cached_qcolor(d.foreground) elif role == Qt.BackgroundRole and d.background: return get_cached_qcolor(d.background) #elif role == Qt.SizeHintRole and d.minimum_size: # return d.minimum_size return None
python
def data(self, index, role): 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 elif role == Qt.TextAlignmentRole: h, v = d.text_alignment return TEXT_H_ALIGNMENTS[h] | TEXT_V_ALIGNMENTS[v] elif role == Qt.ForegroundRole and d.foreground: return get_cached_qcolor(d.foreground) elif role == Qt.BackgroundRole and d.background: return get_cached_qcolor(d.background) #elif role == Qt.SizeHintRole and d.minimum_size: # return d.minimum_size return None
[ "def", "data", "(", "self", ",", "index", ",", "role", ")", ":", "item", "=", "self", ".", "itemAt", "(", "index", ")", "if", "not", "item", ":", "return", "None", "d", "=", "item", ".", "declaration", "if", "role", "==", "Qt", ".", "DisplayRole", ...
Retrieve the data for the item at the given index
[ "Retrieve", "the", "data", "for", "the", "item", "at", "the", "given", "index" ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_abstract_item_view.py#L53-L82
10,654
frmdstryr/enamlx
enamlx/qt/qt_abstract_item_view.py
QAbstractAtomItemModel.setData
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) return True elif role == Qt.EditRole: if value != d.text: d.text = value return True return super(QAbstractAtomItemModel, self).setData(index, value, role)
python
def setData(self, index, value, role=Qt.EditRole): 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) return True elif role == Qt.EditRole: if value != d.text: d.text = value return True return super(QAbstractAtomItemModel, self).setData(index, value, role)
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", ":", "item", "=", "self", ".", "itemAt", "(", "index", ")", "if", "not", "item", ":", "return", "False", "d", "=", "item", ".", "declaration", ...
Set the data for the item at the given index to the given value.
[ "Set", "the", "data", "for", "the", "item", "at", "the", "given", "index", "to", "the", "given", "value", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_abstract_item_view.py#L109-L127
10,655
frmdstryr/enamlx
enamlx/qt/qt_abstract_item_view.py
QtAbstractItemView.set_items
def set_items(self, items): """ Defer until later so the view is only updated after all items are added. """ self._pending_view_refreshes +=1 timed_call(self._pending_timeout, self._refresh_layout)
python
def set_items(self, items): self._pending_view_refreshes +=1 timed_call(self._pending_timeout, self._refresh_layout)
[ "def", "set_items", "(", "self", ",", "items", ")", ":", "self", ".", "_pending_view_refreshes", "+=", "1", "timed_call", "(", "self", ".", "_pending_timeout", ",", "self", ".", "_refresh_layout", ")" ]
Defer until later so the view is only updated after all items are added.
[ "Defer", "until", "later", "so", "the", "view", "is", "only", "updated", "after", "all", "items", "are", "added", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_abstract_item_view.py#L274-L280
10,656
frmdstryr/enamlx
enamlx/qt/qt_abstract_item_view.py
QtAbstractItemView._refresh_layout
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: self.model.layoutChanged.emit() self.on_layout_refreshed() except RuntimeError: # View can be destroyed before we get here return self._refresh_sizes()
python
def _refresh_layout(self): self._pending_view_refreshes -= 1 if self._pending_view_refreshes == 0: try: self.model.layoutChanged.emit() self.on_layout_refreshed() except RuntimeError: # View can be destroyed before we get here return self._refresh_sizes()
[ "def", "_refresh_layout", "(", "self", ")", ":", "self", ".", "_pending_view_refreshes", "-=", "1", "if", "self", ".", "_pending_view_refreshes", "==", "0", ":", "try", ":", "self", ".", "model", ".", "layoutChanged", ".", "emit", "(", ")", "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.
[ "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", ...
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_abstract_item_view.py#L392-L407
10,657
frmdstryr/enamlx
enamlx/qt/qt_tree_view.py
QAtomTreeModel.index
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): proxy = d._items[row].proxy assert isinstance(proxy, QtTreeViewItem), \ "Invalid item {}".format(proxy) else: proxy = d.proxy return self.createIndex(row, column, proxy)
python
def index(self, row, column, parent): item = parent.internalPointer() #: If the parent is None d = self.declaration if item is None else item.declaration if row < len(d._items): proxy = d._items[row].proxy assert isinstance(proxy, QtTreeViewItem), \ "Invalid item {}".format(proxy) else: proxy = d.proxy return self.createIndex(row, column, proxy)
[ "def", "index", "(", "self", ",", "row", ",", "column", ",", "parent", ")", ":", "item", "=", "parent", ".", "internalPointer", "(", ")", "#: If the parent is None", "d", "=", "self", ".", "declaration", "if", "item", "is", "None", "else", "item", ".", ...
The index should point to the corresponding QtControl in the enaml object hierarchy.
[ "The", "index", "should", "point", "to", "the", "corresponding", "QtControl", "in", "the", "enaml", "object", "hierarchy", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_tree_view.py#L46-L59
10,658
frmdstryr/enamlx
enamlx/qt/qt_tree_view.py
QtTreeViewItem._default_view
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 = self.parent() if isinstance(parent, QtTreeView): return parent return parent.view
python
def _default_view(self): parent = self.parent() if isinstance(parent, QtTreeView): return parent return parent.view
[ "def", "_default_view", "(", "self", ")", ":", "parent", "=", "self", ".", "parent", "(", ")", "if", "isinstance", "(", "parent", ",", "QtTreeView", ")", ":", "return", "parent", "return", "parent", ".", "view" ]
If this is the root item, return the parent which must be a TreeView, otherwise return the parent Item's view.
[ "If", "this", "is", "the", "root", "item", "return", "the", "parent", "which", "must", "be", "a", "TreeView", "otherwise", "return", "the", "parent", "Item", "s", "view", "." ]
9582e29c88dc0c0340f912b49168b7307a47ed4f
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_tree_view.py#L230-L238
10,659
LasLabs/python-five9
five9/models/base_model.py
BaseModel.read
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. Returns: BaseModel: The record, if found. Otherwise ``None`` """ results = cls.search(five9, {cls.__uid_field__: external_id}) if not results: return None return results[0]
python
def read(cls, five9, external_id): results = cls.search(five9, {cls.__uid_field__: external_id}) if not results: return None return results[0]
[ "def", "read", "(", "cls", ",", "five9", ",", "external_id", ")", ":", "results", "=", "cls", ".", "search", "(", "five9", ",", "{", "cls", ".", "__uid_field__", ":", "external_id", "}", ")", "if", "not", "results", ":", "return", "None", "return", "...
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. Returns: BaseModel: The record, if found. Otherwise ``None``
[ "Return", "a", "record", "singleton", "for", "the", "ID", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L55-L69
10,660
LasLabs/python-five9
five9/models/base_model.py
BaseModel.update
def update(self, data): """Update the current memory record with the given data dict. Args: data (dict): Data dictionary to update the record attributes with. """ for key, value in data.items(): setattr(self, key, value)
python
def update(self, data): for key, value in data.items(): setattr(self, key, value)
[ "def", "update", "(", "self", ",", "data", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")" ]
Update the current memory record with the given data dict. Args: data (dict): Data dictionary to update the record attributes with.
[ "Update", "the", "current", "memory", "record", "with", "the", "given", "data", "dict", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L86-L93
10,661
LasLabs/python-five9
five9/models/base_model.py
BaseModel._call_and_serialize
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. If ``refresh`` is ``True``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server. """ method(data) if refresh: return cls.read(method.__self__, data[cls.__uid_field__]) else: return cls.deserialize(cls._get_non_empty_dict(data))
python
def _call_and_serialize(cls, method, data, refresh=False): method(data) if refresh: return cls.read(method.__self__, data[cls.__uid_field__]) else: return cls.deserialize(cls._get_non_empty_dict(data))
[ "def", "_call_and_serialize", "(", "cls", ",", "method", ",", "data", ",", "refresh", "=", "False", ")", ":", "method", "(", "data", ")", "if", "refresh", ":", "return", "cls", ".", "read", "(", "method", ".", "__self__", ",", "data", "[", "cls", "."...
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. If ``refresh`` is ``True``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server.
[ "Call", "the", "remote", "method", "with", "data", "and", "optionally", "refresh", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L104-L124
10,662
LasLabs/python-five9
five9/models/base_model.py
BaseModel._get_name_filters
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 isinstance(filters, string_types): filters = r'(%s)' % ('|'.join(filters)) return filters
python
def _get_name_filters(cls, filters): filters = filters.get(cls.__uid_field__) if not filters: filters = '.*' elif not isinstance(filters, string_types): filters = r'(%s)' % ('|'.join(filters)) return filters
[ "def", "_get_name_filters", "(", "cls", ",", "filters", ")", ":", "filters", "=", "filters", ".", "get", "(", "cls", ".", "__uid_field__", ")", "if", "not", "filters", ":", "filters", "=", "'.*'", "elif", "not", "isinstance", "(", "filters", ",", "string...
Return a regex filter for the UID column only.
[ "Return", "a", "regex", "filter", "for", "the", "UID", "column", "only", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L127-L134
10,663
LasLabs/python-five9
five9/models/base_model.py
BaseModel._get_non_empty_list
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 = cls._get_non_empty_dict(value) or None if value is not None: res.append(value) return res
python
def _get_non_empty_list(cls, iter): res = [] for value in iter: if hasattr(value, 'items'): value = cls._get_non_empty_dict(value) or None if value is not None: res.append(value) return res
[ "def", "_get_non_empty_list", "(", "cls", ",", "iter", ")", ":", "res", "=", "[", "]", "for", "value", "in", "iter", ":", "if", "hasattr", "(", "value", ",", "'items'", ")", ":", "value", "=", "cls", ".", "_get_non_empty_dict", "(", "value", ")", "or...
Return a list of the input, excluding all ``None`` values.
[ "Return", "a", "list", "of", "the", "input", "excluding", "all", "None", "values", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L150-L158
10,664
LasLabs/python-five9
five9/models/base_model.py
BaseModel._name_search
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]: A list of records representing the result. """ filters = cls._get_name_filters(filters) return [ cls.deserialize(cls._zeep_to_dict(row)) for row in method(filters) ]
python
def _name_search(cls, method, filters): filters = cls._get_name_filters(filters) return [ cls.deserialize(cls._zeep_to_dict(row)) for row in method(filters) ]
[ "def", "_name_search", "(", "cls", ",", "method", ",", "filters", ")", ":", "filters", "=", "cls", ".", "_get_name_filters", "(", "filters", ")", "return", "[", "cls", ".", "deserialize", "(", "cls", ".", "_zeep_to_dict", "(", "row", ")", ")", "for", "...
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]: A list of records representing the result.
[ "Helper", "for", "search", "methods", "that", "use", "name", "filters", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L161-L177
10,665
LasLabs/python-five9
five9/models/base_model.py
BaseModel._zeep_to_dict
def _zeep_to_dict(cls, obj): """Convert a zeep object to a dictionary.""" res = serialize_object(obj) res = cls._get_non_empty_dict(res) return res
python
def _zeep_to_dict(cls, obj): res = serialize_object(obj) res = cls._get_non_empty_dict(res) return res
[ "def", "_zeep_to_dict", "(", "cls", ",", "obj", ")", ":", "res", "=", "serialize_object", "(", "obj", ")", "res", "=", "cls", ".", "_get_non_empty_dict", "(", "res", ")", "return", "res" ]
Convert a zeep object to a dictionary.
[ "Convert", "a", "zeep", "object", "to", "a", "dictionary", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L180-L184
10,666
LasLabs/python-five9
five9/models/base_model.py
BaseModel.__check_field
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 on "%s"' % ( key, self.__class__.__name__, ), )
python
def __check_field(self, key): if not self._props.get(key): raise KeyError( 'The field "%s" does not exist on "%s"' % ( key, self.__class__.__name__, ), )
[ "def", "__check_field", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "_props", ".", "get", "(", "key", ")", ":", "raise", "KeyError", "(", "'The field \"%s\" does not exist on \"%s\"'", "%", "(", "key", ",", "self", ".", "__class__", ".", ...
Raises a KeyError if the field doesn't exist.
[ "Raises", "a", "KeyError", "if", "the", "field", "doesn", "t", "exist", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/base_model.py#L206-L213
10,667
LasLabs/python-five9
five9/five9.py
Five9.supervisor
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') if not self._api_supervisor_session: self._api_supervisor_session = self.__create_supervisor_session( supervisor, ) return supervisor
python
def supervisor(self): supervisor = self._cached_client('supervisor') if not self._api_supervisor_session: self._api_supervisor_session = self.__create_supervisor_session( supervisor, ) return supervisor
[ "def", "supervisor", "(", "self", ")", ":", "supervisor", "=", "self", ".", "_cached_client", "(", "'supervisor'", ")", "if", "not", "self", ".", "_api_supervisor_session", ":", "self", ".", "_api_supervisor_session", "=", "self", ".", "__create_supervisor_session...
Return an authenticated connection for use, open new if required. Returns: SupervisorWebService: New or existing session with the Five9 Statistics API.
[ "Return", "an", "authenticated", "connection", "for", "use", "open", "new", "if", "required", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L48-L60
10,668
LasLabs/python-five9
five9/five9.py
Five9.create_mapping
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(): ordered[key] = value field_mappings.append({ 'columnNumber': len(ordered), # Five9 is not zero indexed. 'fieldName': key, 'key': key in keys, }) return { 'field_mappings': field_mappings, 'data': ordered, 'fields': list(ordered.values()), }
python
def create_mapping(record, keys): ordered = OrderedDict() field_mappings = [] for key, value in record.items(): ordered[key] = value field_mappings.append({ 'columnNumber': len(ordered), # Five9 is not zero indexed. 'fieldName': key, 'key': key in keys, }) return { 'field_mappings': field_mappings, 'data': ordered, 'fields': list(ordered.values()), }
[ "def", "create_mapping", "(", "record", ",", "keys", ")", ":", "ordered", "=", "OrderedDict", "(", ")", "field_mappings", "=", "[", "]", "for", "key", ",", "value", "in", "record", ".", "items", "(", ")", ":", "ordered", "[", "key", "]", "=", "value"...
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.
[ "Create", "a", "field", "mapping", "for", "use", "in", "API", "updates", "and", "creates", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L68-L97
10,669
LasLabs/python-five9
five9/five9.py
Five9.parse_response
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', 'Lasley', 'LasLabs Inc', None, 'Las Vegas', 'NV', '89123', ] } } ] Returns: list[dict]: List of parsed records. """ data = [i['values']['data'] for i in records] return [ {fields[idx]: row for idx, row in enumerate(d)} for d in data ]
python
def parse_response(fields, records): data = [i['values']['data'] for i in records] return [ {fields[idx]: row for idx, row in enumerate(d)} for d in data ]
[ "def", "parse_response", "(", "fields", ",", "records", ")", ":", "data", "=", "[", "i", "[", "'values'", "]", "[", "'data'", "]", "for", "i", "in", "records", "]", "return", "[", "{", "fields", "[", "idx", "]", ":", "row", "for", "idx", ",", "ro...
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', 'Lasley', 'LasLabs Inc', None, 'Las Vegas', 'NV', '89123', ] } } ] Returns: list[dict]: List of parsed records.
[ "Parse", "an", "API", "response", "into", "usable", "objects", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L100-L150
10,670
LasLabs/python-five9
five9/five9.py
Five9.create_criteria
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}) else: criteria.append({ 'criteria': { 'field': name, 'value': value, }, }) return criteria or None
python
def create_criteria(cls, query): criteria = [] for name, value in query.items(): if isinstance(value, list): for inner_value in value: criteria += cls.create_criteria({name: inner_value}) else: criteria.append({ 'criteria': { 'field': name, 'value': value, }, }) return criteria or None
[ "def", "create_criteria", "(", "cls", ",", "query", ")", ":", "criteria", "=", "[", "]", "for", "name", ",", "value", "in", "query", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "inner_value", "in", "...
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.
[ "Return", "a", "criteria", "from", "a", "dictionary", "containing", "a", "query", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L153-L171
10,671
LasLabs/python-five9
five9/five9.py
Five9._get_authenticated_client
def _get_authenticated_client(self, wsdl): """Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client. """ return zeep.Client( wsdl % quote(self.username), transport=zeep.Transport( session=self._get_authenticated_session(), ), )
python
def _get_authenticated_client(self, wsdl): return zeep.Client( wsdl % quote(self.username), transport=zeep.Transport( session=self._get_authenticated_session(), ), )
[ "def", "_get_authenticated_client", "(", "self", ",", "wsdl", ")", ":", "return", "zeep", ".", "Client", "(", "wsdl", "%", "quote", "(", "self", ".", "username", ")", ",", "transport", "=", "zeep", ".", "Transport", "(", "session", "=", "self", ".", "_...
Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client.
[ "Return", "an", "authenticated", "SOAP", "client", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L173-L184
10,672
LasLabs/python-five9
five9/five9.py
Five9._get_authenticated_session
def _get_authenticated_session(self): """Return an authenticated requests session. Returns: requests.Session: Authenticated session for use. """ session = requests.Session() session.auth = self.auth return session
python
def _get_authenticated_session(self): session = requests.Session() session.auth = self.auth return session
[ "def", "_get_authenticated_session", "(", "self", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "auth", "=", "self", ".", "auth", "return", "session" ]
Return an authenticated requests session. Returns: requests.Session: Authenticated session for use.
[ "Return", "an", "authenticated", "requests", "session", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L186-L194
10,673
LasLabs/python-five9
five9/five9.py
Five9.__create_supervisor_session
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': self.force_logout_session, 'rollingPeriod': self.rolling_period, 'statisticsRange': self.statistics_range, 'shiftStart': self.__to_milliseconds( self.shift_start_hour, ), 'timeZone': self.__to_milliseconds( self.time_zone_offset, ), } supervisor.setSessionParameters(session_params) return session_params
python
def __create_supervisor_session(self, supervisor): session_params = { 'forceLogoutSession': self.force_logout_session, 'rollingPeriod': self.rolling_period, 'statisticsRange': self.statistics_range, 'shiftStart': self.__to_milliseconds( self.shift_start_hour, ), 'timeZone': self.__to_milliseconds( self.time_zone_offset, ), } supervisor.setSessionParameters(session_params) return session_params
[ "def", "__create_supervisor_session", "(", "self", ",", "supervisor", ")", ":", "session_params", "=", "{", "'forceLogoutSession'", ":", "self", ".", "force_logout_session", ",", "'rollingPeriod'", ":", "self", ".", "rolling_period", ",", "'statisticsRange'", ":", "...
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.
[ "Create", "a", "new", "session", "on", "the", "supervisor", "service", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/five9.py#L204-L222
10,674
LasLabs/python-five9
five9/environment.py
Api.model
def model(method): """Use this to decorate methods that expect a model.""" def wrapper(self, *args, **kwargs): if self.__model__ is None: raise ValidationError( 'You cannot perform CRUD operations without selecting a ' 'model first.', ) return method(self, *args, **kwargs) return wrapper
python
def model(method): def wrapper(self, *args, **kwargs): if self.__model__ is None: raise ValidationError( 'You cannot perform CRUD operations without selecting a ' 'model first.', ) return method(self, *args, **kwargs) return wrapper
[ "def", "model", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "__model__", "is", "None", ":", "raise", "ValidationError", "(", "'You cannot perform CRUD operations without sele...
Use this to decorate methods that expect a model.
[ "Use", "this", "to", "decorate", "methods", "that", "expect", "a", "model", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/environment.py#L12-L21
10,675
LasLabs/python-five9
five9/environment.py
Api.recordset
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( 'There are no records in the set.', ) return method(self, *args, **kwargs) return Api.model(wrapper)
python
def recordset(method): def wrapper(self, *args, **kwargs): if self.__records__ is None: raise ValidationError( 'There are no records in the set.', ) return method(self, *args, **kwargs) return Api.model(wrapper)
[ "def", "recordset", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "__records__", "is", "None", ":", "raise", "ValidationError", "(", "'There are no records in the set.'", ","...
Use this to decorate methods that expect a record set.
[ "Use", "this", "to", "decorate", "methods", "that", "expect", "a", "record", "set", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/environment.py#L24-L32
10,676
LasLabs/python-five9
five9/environment.py
Environment.create
def create(self, data, refresh=False): """Create the data on the remote, optionally refreshing.""" self.__model__.create(self.__five9__, data) if refresh: return self.read(data[self.__model__.__name__]) else: return self.new(data)
python
def create(self, data, refresh=False): self.__model__.create(self.__five9__, data) if refresh: return self.read(data[self.__model__.__name__]) else: return self.new(data)
[ "def", "create", "(", "self", ",", "data", ",", "refresh", "=", "False", ")", ":", "self", ".", "__model__", ".", "create", "(", "self", ".", "__five9__", ",", "data", ")", "if", "refresh", ":", "return", "self", ".", "read", "(", "data", "[", "sel...
Create the data on the remote, optionally refreshing.
[ "Create", "the", "data", "on", "the", "remote", "optionally", "refreshing", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/environment.py#L90-L96
10,677
LasLabs/python-five9
five9/environment.py
Environment.new
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__( self.__five9__, self.__model__, records=[self.__model__.deserialize(data)], )
python
def new(self, data): data = self.__model__._get_non_empty_dict(data) return self.__class__( self.__five9__, self.__model__, records=[self.__model__.deserialize(data)], )
[ "def", "new", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "__model__", ".", "_get_non_empty_dict", "(", "data", ")", "return", "self", ".", "__class__", "(", "self", ".", "__five9__", ",", "self", ".", "__model__", ",", "records", "="...
Create a new memory record, but do not create on the remote.
[ "Create", "a", "new", "memory", "record", "but", "do", "not", "create", "on", "the", "remote", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/environment.py#L99-L106
10,678
LasLabs/python-five9
five9/environment.py
Environment.search
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. """ records = self.__model__.search(self.__five9__, filters) return self.__class__( self.__five9__, self.__model__, records, )
python
def search(self, filters): records = self.__model__.search(self.__five9__, filters) return self.__class__( self.__five9__, self.__model__, records, )
[ "def", "search", "(", "self", ",", "filters", ")", ":", "records", "=", "self", ".", "__model__", ".", "search", "(", "self", ".", "__five9__", ",", "filters", ")", "return", "self", ".", "__class__", "(", "self", ".", "__five9__", ",", "self", ".", ...
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.
[ "Search", "Five9", "given", "a", "filter", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/environment.py#L125-L138
10,679
LasLabs/python-five9
five9/models/disposition.py
Disposition.create
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``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server. """ return cls._call_and_serialize( five9.configuration.createDisposition, data, refresh, )
python
def create(cls, five9, data, refresh=False): return cls._call_and_serialize( five9.configuration.createDisposition, data, refresh, )
[ "def", "create", "(", "cls", ",", "five9", ",", "data", ",", "refresh", "=", "False", ")", ":", "return", "cls", ".", "_call_and_serialize", "(", "five9", ".", "configuration", ".", "createDisposition", ",", "data", ",", "refresh", ",", ")" ]
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``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server.
[ "Create", "a", "record", "on", "Five9", "." ]
ef53160d6658604524a2577391280d2b4501a7ce
https://github.com/LasLabs/python-five9/blob/ef53160d6658604524a2577391280d2b4501a7ce/five9/models/disposition.py#L84-L100
10,680
tonioo/sievelib
sievelib/managesieve.py
authentication_required
def authentication_required(meth): """Simple class method decorator. Checks if the client is currently connected. :param meth: the original called method """ def check(cls, *args, **kwargs): if cls.authenticated: return meth(cls, *args, **kwargs) raise Error("Authentication required") return check
python
def authentication_required(meth): def check(cls, *args, **kwargs): if cls.authenticated: return meth(cls, *args, **kwargs) raise Error("Authentication required") return check
[ "def", "authentication_required", "(", "meth", ")", ":", "def", "check", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "cls", ".", "authenticated", ":", "return", "meth", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs...
Simple class method decorator. Checks if the client is currently connected. :param meth: the original called method
[ "Simple", "class", "method", "decorator", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L58-L71
10,681
tonioo/sievelib
sievelib/managesieve.py
Client.__read_block
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 :rtype: string :returns: the read block (can be empty) """ buf = b"" if len(self.__read_buffer): limit = ( size if size <= len(self.__read_buffer) else len(self.__read_buffer) ) buf = self.__read_buffer[:limit] self.__read_buffer = self.__read_buffer[limit:] size -= limit if not size: return buf try: buf += self.sock.recv(size) except (socket.timeout, ssl.SSLError): raise Error("Failed to read %d bytes from the server" % size) self.__dprint(buf) return buf
python
def __read_block(self, size): buf = b"" if len(self.__read_buffer): limit = ( size if size <= len(self.__read_buffer) else len(self.__read_buffer) ) buf = self.__read_buffer[:limit] self.__read_buffer = self.__read_buffer[limit:] size -= limit if not size: return buf try: buf += self.sock.recv(size) except (socket.timeout, ssl.SSLError): raise Error("Failed to read %d bytes from the server" % size) self.__dprint(buf) return buf
[ "def", "__read_block", "(", "self", ",", "size", ")", ":", "buf", "=", "b\"\"", "if", "len", "(", "self", ".", "__read_buffer", ")", ":", "limit", "=", "(", "size", "if", "size", "<=", "len", "(", "self", ".", "__read_buffer", ")", "else", "len", "...
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 :rtype: string :returns: the read block (can be empty)
[ "Read", "a", "block", "of", "size", "bytes", "from", "the", "server", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L103-L134
10,682
tonioo/sievelib
sievelib/managesieve.py
Client.__read_line
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) if not len(nval): break self.__read_buffer += nval except (socket.timeout, ssl.SSLError): raise Error("Failed to read data from the server") if len(ret): m = self.__size_expr.match(ret) if m: raise Literal(int(m.group(1))) m = self.__respcode_expr.match(ret) if m: if m.group(1) == b"BYE": raise Error("Connection closed by server") if m.group(1) == b"NO": self.__parse_error(m.group(2)) raise Response(m.group(1), m.group(2)) return ret
python
def __read_line(self): 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) if not len(nval): break self.__read_buffer += nval except (socket.timeout, ssl.SSLError): raise Error("Failed to read data from the server") if len(ret): m = self.__size_expr.match(ret) if m: raise Literal(int(m.group(1))) m = self.__respcode_expr.match(ret) if m: if m.group(1) == b"BYE": raise Error("Connection closed by server") if m.group(1) == b"NO": self.__parse_error(m.group(2)) raise Response(m.group(1), m.group(2)) return ret
[ "def", "__read_line", "(", "self", ")", ":", "ret", "=", "b\"\"", "while", "True", ":", "try", ":", "pos", "=", "self", ".", "__read_buffer", ".", "index", "(", "CRLF", ")", "ret", "=", "self", ".", "__read_buffer", "[", ":", "pos", "]", "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
[ "Read", "one", "line", "from", "the", "server", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L136-L181
10,683
tonioo/sievelib
sievelib/managesieve.py
Client.__read_response
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 break except Literal as inst: resp += self.__read_block(inst.value) if not resp.endswith(CRLF): resp += self.__read_line() + CRLF continue if not len(line): continue resp += line + CRLF cpt += 1 if nblines != -1 and cpt == nblines: break return (code, data, resp)
python
def __read_response(self, nblines=-1): 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 break except Literal as inst: resp += self.__read_block(inst.value) if not resp.endswith(CRLF): resp += self.__read_line() + CRLF continue if not len(line): continue resp += line + CRLF cpt += 1 if nblines != -1 and cpt == nblines: break return (code, data, resp)
[ "def", "__read_response", "(", "self", ",", "nblines", "=", "-", "1", ")", ":", "resp", ",", "code", ",", "data", "=", "(", "b\"\"", ",", "None", ",", "None", ")", "cpt", "=", "0", "while", "True", ":", "try", ":", "line", "=", "self", ".", "__...
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.
[ "Read", "a", "response", "from", "the", "server", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L183-L217
10,684
tonioo/sievelib
sievelib/managesieve.py
Client.__prepare_args
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): if self.__size_expr.match(a): ret += [a] else: ret += [b'"' + a + b'"'] continue ret += [bytes(str(a).encode("utf-8"))] return ret
python
def __prepare_args(self, args): ret = [] for a in args: if isinstance(a, six.binary_type): if self.__size_expr.match(a): ret += [a] else: ret += [b'"' + a + b'"'] continue ret += [bytes(str(a).encode("utf-8"))] return ret
[ "def", "__prepare_args", "(", "self", ",", "args", ")", ":", "ret", "=", "[", "]", "for", "a", "in", "args", ":", "if", "isinstance", "(", "a", ",", "six", ".", "binary_type", ")", ":", "if", "self", ".", "__size_expr", ".", "match", "(", "a", ")...
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
[ "Format", "command", "arguments", "before", "sending", "them", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L219-L237
10,685
tonioo/sievelib
sievelib/managesieve.py
Client.__parse_error
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"" self.errmsg = self.__read_block(int(m.group(1)) + 2) return m = self.__error_expr.match(text) if m is None: raise Error("Bad error message") if m.group(1) is not None: self.errcode = m.group(1).strip(b"()") else: self.errcode = b"" self.errmsg = m.group(2).strip(b'"')
python
def __parse_error(self, text): m = self.__size_expr.match(text) if m is not None: self.errcode = b"" self.errmsg = self.__read_block(int(m.group(1)) + 2) return m = self.__error_expr.match(text) if m is None: raise Error("Bad error message") if m.group(1) is not None: self.errcode = m.group(1).strip(b"()") else: self.errcode = b"" self.errmsg = m.group(2).strip(b'"')
[ "def", "__parse_error", "(", "self", ",", "text", ")", ":", "m", "=", "self", ".", "__size_expr", ".", "match", "(", "text", ")", "if", "m", "is", "not", "None", ":", "self", ".", "errcode", "=", "b\"\"", "self", ".", "errmsg", "=", "self", ".", ...
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
[ "Parse", "an", "error", "received", "from", "the", "server", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L296-L322
10,686
tonioo/sievelib
sievelib/managesieve.py
Client._plain_authentication
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): password = password.encode("utf-8") params = base64.b64encode(b'\0'.join([authz_id, login, password])) code, data = self.__send_command("AUTHENTICATE", [b"PLAIN", params]) if code == "OK": return True return False
python
def _plain_authentication(self, login, password, authz_id=b""): if isinstance(login, six.text_type): login = login.encode("utf-8") if isinstance(password, six.text_type): password = password.encode("utf-8") params = base64.b64encode(b'\0'.join([authz_id, login, password])) code, data = self.__send_command("AUTHENTICATE", [b"PLAIN", params]) if code == "OK": return True return False
[ "def", "_plain_authentication", "(", "self", ",", "login", ",", "password", ",", "authz_id", "=", "b\"\"", ")", ":", "if", "isinstance", "(", "login", ",", "six", ".", "text_type", ")", ":", "login", "=", "login", ".", "encode", "(", "\"utf-8\"", ")", ...
SASL PLAIN authentication :param login: username :param password: clear password :return: True on success, False otherwise.
[ "SASL", "PLAIN", "authentication" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L324-L339
10,687
tonioo/sievelib
sievelib/managesieve.py
Client._login_authentication
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"' % base64.b64encode(password.encode("utf-8"))] code, data = self.__send_command("AUTHENTICATE", [b"LOGIN"], extralines=extralines) if code == "OK": return True return False
python
def _login_authentication(self, login, password, authz_id=""): extralines = [b'"%s"' % base64.b64encode(login.encode("utf-8")), b'"%s"' % base64.b64encode(password.encode("utf-8"))] code, data = self.__send_command("AUTHENTICATE", [b"LOGIN"], extralines=extralines) if code == "OK": return True return False
[ "def", "_login_authentication", "(", "self", ",", "login", ",", "password", ",", "authz_id", "=", "\"\"", ")", ":", "extralines", "=", "[", "b'\"%s\"'", "%", "base64", ".", "b64encode", "(", "login", ".", "encode", "(", "\"utf-8\"", ")", ")", ",", "b'\"%...
SASL LOGIN authentication :param login: username :param password: clear password :return: True on success, False otherwise.
[ "SASL", "LOGIN", "authentication" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L341-L354
10,688
tonioo/sievelib
sievelib/managesieve.py
Client._digest_md5_authentication
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 ) if not challenge: return False if not dmd5.check_last_challenge(login, password, challenge): self.errmsg = "Bad challenge received from server" return False code, data = self.__send_command('""') if code == "OK": return True return False
python
def _digest_md5_authentication(self, login, password, authz_id=""): 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 ) if not challenge: return False if not dmd5.check_last_challenge(login, password, challenge): self.errmsg = "Bad challenge received from server" return False code, data = self.__send_command('""') if code == "OK": return True return False
[ "def", "_digest_md5_authentication", "(", "self", ",", "login", ",", "password", ",", "authz_id", "=", "\"\"", ")", ":", "code", ",", "data", ",", "challenge", "=", "self", ".", "__send_command", "(", "\"AUTHENTICATE\"", ",", "[", "b\"DIGEST-MD5\"", "]", ","...
SASL DIGEST-MD5 authentication :param login: username :param password: clear password :return: True on success, False otherwise.
[ "SASL", "DIGEST", "-", "MD5", "authentication" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L356-L380
10,689
tonioo/sievelib
sievelib/managesieve.py
Client.get_sieve_capabilities
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 """ if isinstance(self.__capabilities["SIEVE"], six.string_types): self.__capabilities["SIEVE"] = self.__capabilities["SIEVE"].split() return self.__capabilities["SIEVE"]
python
def get_sieve_capabilities(self): if isinstance(self.__capabilities["SIEVE"], six.string_types): self.__capabilities["SIEVE"] = self.__capabilities["SIEVE"].split() return self.__capabilities["SIEVE"]
[ "def", "get_sieve_capabilities", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__capabilities", "[", "\"SIEVE\"", "]", ",", "six", ".", "string_types", ")", ":", "self", ".", "__capabilities", "[", "\"SIEVE\"", "]", "=", "self", ".", "__cap...
Returns the SIEVE extensions supported by the server. They're read from server capabilities. (see the CAPABILITY command) :rtype: string
[ "Returns", "the", "SIEVE", "extensions", "supported", "by", "the", "server", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L473-L483
10,690
tonioo/sievelib
sievelib/managesieve.py
Client.connect
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 msg: raise Error("Connection to server failed: %s" % str(msg)) if not self.__get_capabilities(): raise Error("Failed to read capabilities from server") if starttls and not self.__starttls(): return False if self.__authenticate(login, password, authz_id, authmech): return True return False
python
def connect( self, login, password, authz_id=b"", starttls=False, authmech=None): try: self.sock = socket.create_connection((self.srvaddr, self.srvport)) self.sock.settimeout(Client.read_timeout) except socket.error as msg: raise Error("Connection to server failed: %s" % str(msg)) if not self.__get_capabilities(): raise Error("Failed to read capabilities from server") if starttls and not self.__starttls(): return False if self.__authenticate(login, password, authz_id, authmech): return True return False
[ "def", "connect", "(", "self", ",", "login", ",", "password", ",", "authz_id", "=", "b\"\"", ",", "starttls", "=", "False", ",", "authmech", "=", "None", ")", ":", "try", ":", "self", ".", "sock", "=", "socket", ".", "create_connection", "(", "(", "s...
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
[ "Establish", "a", "connection", "with", "the", "server", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L485-L511
10,691
tonioo/sievelib
sievelib/managesieve.py
Client.capability
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 = ( self.__send_command("CAPABILITY", withcontent=True)) if code == "OK": return capabilities return None
python
def capability(self): code, data, capabilities = ( self.__send_command("CAPABILITY", withcontent=True)) if code == "OK": return capabilities return None
[ "def", "capability", "(", "self", ")", ":", "code", ",", "data", ",", "capabilities", "=", "(", "self", ".", "__send_command", "(", "\"CAPABILITY\"", ",", "withcontent", "=", "True", ")", ")", "if", "code", "==", "\"OK\"", ":", "return", "capabilities", ...
Ask server capabilities. See MANAGESIEVE specifications, section 2.4 This command does not affect capabilities recorded by this client. :rtype: string
[ "Ask", "server", "capabilities", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L520-L532
10,692
tonioo/sievelib
sievelib/managesieve.py
Client.havespace
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 """ code, data = self.__send_command( "HAVESPACE", [scriptname.encode("utf-8"), scriptsize]) if code == "OK": return True return False
python
def havespace(self, scriptname, scriptsize): code, data = self.__send_command( "HAVESPACE", [scriptname.encode("utf-8"), scriptsize]) if code == "OK": return True return False
[ "def", "havespace", "(", "self", ",", "scriptname", ",", "scriptsize", ")", ":", "code", ",", "data", "=", "self", ".", "__send_command", "(", "\"HAVESPACE\"", ",", "[", "scriptname", ".", "encode", "(", "\"utf-8\"", ")", ",", "scriptsize", "]", ")", "if...
Ask for available space. See MANAGESIEVE specifications, section 2.5 :param scriptname: script's name :param scriptsize: script's size :rtype: boolean
[ "Ask", "for", "available", "space", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L535-L548
10,693
tonioo/sievelib
sievelib/managesieve.py
Client.listscripts
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) if m is None: ret += [l.strip(b'"').decode("utf-8")] continue script = m.group(1).decode("utf-8") if self.__active_expr.match(m.group(2)): active_script = script continue ret += [script] self.__dprint(ret) return (active_script, ret)
python
def listscripts(self): 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) if m is None: ret += [l.strip(b'"').decode("utf-8")] continue script = m.group(1).decode("utf-8") if self.__active_expr.match(m.group(2)): active_script = script continue ret += [script] self.__dprint(ret) return (active_script, ret)
[ "def", "listscripts", "(", "self", ")", ":", "code", ",", "data", ",", "listing", "=", "self", ".", "__send_command", "(", "\"LISTSCRIPTS\"", ",", "withcontent", "=", "True", ")", "if", "code", "==", "\"NO\"", ":", "return", "None", "ret", "=", "[", "]...
List available scripts. See MANAGESIEVE specifications, section 2.7 :returns: a 2-uple (active script, [script1, ...])
[ "List", "available", "scripts", "." ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L551-L577
10,694
tonioo/sievelib
sievelib/managesieve.py
Client.getscript
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) if code == "OK": lines = content.splitlines() if self.__size_expr.match(lines[0]) is not None: lines = lines[1:] return u"\n".join([line.decode("utf-8") for line in lines]) return None
python
def getscript(self, name): code, data, content = self.__send_command( "GETSCRIPT", [name.encode("utf-8")], withcontent=True) if code == "OK": lines = content.splitlines() if self.__size_expr.match(lines[0]) is not None: lines = lines[1:] return u"\n".join([line.decode("utf-8") for line in lines]) return None
[ "def", "getscript", "(", "self", ",", "name", ")", ":", "code", ",", "data", ",", "content", "=", "self", ".", "__send_command", "(", "\"GETSCRIPT\"", ",", "[", "name", ".", "encode", "(", "\"utf-8\"", ")", "]", ",", "withcontent", "=", "True", ")", ...
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
[ "Download", "a", "script", "from", "the", "server" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L580-L596
10,695
tonioo/sievelib
sievelib/managesieve.py
Client.putscript
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+}" % len(content)) + CRLF + content code, data = ( self.__send_command("PUTSCRIPT", [name.encode("utf-8"), content])) if code == "OK": return True return False
python
def putscript(self, name, content): content = tools.to_bytes(content) content = tools.to_bytes("{%d+}" % len(content)) + CRLF + content code, data = ( self.__send_command("PUTSCRIPT", [name.encode("utf-8"), content])) if code == "OK": return True return False
[ "def", "putscript", "(", "self", ",", "name", ",", "content", ")", ":", "content", "=", "tools", ".", "to_bytes", "(", "content", ")", "content", "=", "tools", ".", "to_bytes", "(", "\"{%d+}\"", "%", "len", "(", "content", ")", ")", "+", "CRLF", "+",...
Upload a script to the server See MANAGESIEVE specifications, section 2.6 :param name: script's name :param content: script's content :rtype: boolean
[ "Upload", "a", "script", "to", "the", "server" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L599-L614
10,696
tonioo/sievelib
sievelib/managesieve.py
Client.deletescript
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( "DELETESCRIPT", [name.encode("utf-8")]) if code == "OK": return True return False
python
def deletescript(self, name): code, data = self.__send_command( "DELETESCRIPT", [name.encode("utf-8")]) if code == "OK": return True return False
[ "def", "deletescript", "(", "self", ",", "name", ")", ":", "code", ",", "data", "=", "self", ".", "__send_command", "(", "\"DELETESCRIPT\"", ",", "[", "name", ".", "encode", "(", "\"utf-8\"", ")", "]", ")", "if", "code", "==", "\"OK\"", ":", "return", ...
Delete a script from the server See MANAGESIEVE specifications, section 2.10 :param name: script's name :rtype: boolean
[ "Delete", "a", "script", "from", "the", "server" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L617-L629
10,697
tonioo/sievelib
sievelib/managesieve.py
Client.renamescript
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" return False if newname in scripts: self.errmsg = b"New script already exists" return False oldscript = self.getscript(oldname) if oldscript is None: return False if not self.putscript(newname, oldscript): return False if active_script == oldname: if not self.setactive(newname): return False if not self.deletescript(oldname): return False return True
python
def renamescript(self, oldname, newname): 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" return False if newname in scripts: self.errmsg = b"New script already exists" return False oldscript = self.getscript(oldname) if oldscript is None: return False if not self.putscript(newname, oldscript): return False if active_script == oldname: if not self.setactive(newname): return False if not self.deletescript(oldname): return False return True
[ "def", "renamescript", "(", "self", ",", "oldname", ",", "newname", ")", ":", "if", "\"VERSION\"", "in", "self", ".", "__capabilities", ":", "code", ",", "data", "=", "self", ".", "__send_command", "(", "\"RENAMESCRIPT\"", ",", "[", "oldname", ".", "encode...
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
[ "Rename", "a", "script", "on", "the", "server" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L632-L673
10,698
tonioo/sievelib
sievelib/managesieve.py
Client.setactive
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 """ code, data = self.__send_command( "SETACTIVE", [scriptname.encode("utf-8")]) if code == "OK": return True return False
python
def setactive(self, scriptname): code, data = self.__send_command( "SETACTIVE", [scriptname.encode("utf-8")]) if code == "OK": return True return False
[ "def", "setactive", "(", "self", ",", "scriptname", ")", ":", "code", ",", "data", "=", "self", ".", "__send_command", "(", "\"SETACTIVE\"", ",", "[", "scriptname", ".", "encode", "(", "\"utf-8\"", ")", "]", ")", "if", "code", "==", "\"OK\"", ":", "ret...
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
[ "Define", "the", "active", "script" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L676-L691
10,699
tonioo/sievelib
sievelib/managesieve.py
Client.checkscript
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") content = tools.to_bytes(content) content = tools.to_bytes("{%d+}" % len(content)) + CRLF + content code, data = self.__send_command("CHECKSCRIPT", [content]) if code == "OK": return True return False
python
def checkscript(self, content): if "VERSION" not in self.__capabilities: raise NotImplementedError( "server does not support CHECKSCRIPT command") content = tools.to_bytes(content) content = tools.to_bytes("{%d+}" % len(content)) + CRLF + content code, data = self.__send_command("CHECKSCRIPT", [content]) if code == "OK": return True return False
[ "def", "checkscript", "(", "self", ",", "content", ")", ":", "if", "\"VERSION\"", "not", "in", "self", ".", "__capabilities", ":", "raise", "NotImplementedError", "(", "\"server does not support CHECKSCRIPT command\"", ")", "content", "=", "tools", ".", "to_bytes", ...
Check whether a script is valid See MANAGESIEVE specifications, section 2.12 :param name: script's content :rtype: boolean
[ "Check", "whether", "a", "script", "is", "valid" ]
88822d1f1daf30ef3dd9ac74911301b0773ef3c8
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L694-L710