code
stringlengths
1
18.2k
def neurons(self): """ Return list of neuron indices. Parameters ---------- None Returns ------- list list of neuron indices See also -------- sqlite3.connect.cursor """ self.cursor.execute('SELECT DISTINCT neuron FROM spikes ORDER BY neuron') sel = self.cursor.fetchall() return np.array(sel).flatten()
def num_spikes(self): """ Return total number of spikes. Parameters ---------- None Returns ------- list """ self.cursor.execute('SELECT Count(*) from spikes') rows = self.cursor.fetchall()[0] # Check against 'wc -l *ex*.gdf' if self.debug: print('DB has %d spikes' % rows) return rows
def plotstuff(self, T=[0, 1000]): """ Create a scatter plot of the contents of the database, with entries on the interval T. Parameters ---------- T : list Time interval. Returns ------- None See also -------- GDF.select_neurons_interval """ fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111) neurons = self.neu...
def represent_as_tuple(string): """ Represent a number-string in the form of a tuple of digits. "868.0F" -> (8, 6, 8, '.', 0, 15) Args: string - Number represented as a string of digits. Returns: Number represented as an iterable container of digits >>> represent_as_tuple('868.0F') (8, 6, 8, '.', 0, 15) """ keep = ("."...
def represent_as_string(iterable): """ Represent a number in the form of a string. (8, 6, 8, '.', 0, 15) -> "868.0F" Args: iterable - Number represented as an iterable container of digits. Returns: Number represented as a string of digits. >>> represent_as_string((8, 6, 8, '.', 0, 15)) '868.0F' """ keep = (".", "[", "]...
def digit(decimal, digit, input_base=10): """ Find the value of an integer at a specific digit when represented in a particular base. Args: decimal(int): A number represented in base 10 (positive integer). digit(int): The digit to find where zero is the first, lowest, digit. base(int): The base to use (default 10). Ret...
(input_base ** digit)) % input_base else: return decimal % input_base
def digits(number, base=10): """ Determines the number of digits of a number in a specific base. Args: number(int): An integer number represented in base 10. base(int): The base to find the number of digits. Returns: Number of digits when represented in a particular base (integer). Examples: >>> digits(255) 3 >>> digit...
def integer_fractional_parts(number): """ Returns a tuple of the integer and fractional parts of a number. Args: number(iterable container): A number in the following form: (..., ".", int, int, int, ...) Returns: (integer_part, fractional_part): tuple. Example: >>> integer_fractional_parts((1,2,3,".",4,5,6)) ((1, 2, 3)...
def from_base_10_int(decimal, output_base=10): """ Converts a decimal integer to a specific base. Args: decimal(int) A base 10 number. output_base(int) base to convert to. Returns: A tuple of digits in the specified base. Examples: >>> from_base_10_int(255) (2, 5, 5) >>> from_base_10_int(255, 16) (15, 15) >>> from_base...
def to_base_10_int(n, input_base): """ Converts an integer in any base into it's decimal representation. Args: n - An integer represented as a tuple of digits in the specified base. input_base - the base of the input number. Returns: integer converted into base 10. Example: >>> to_base_10_int((8,1), 16) 129 """ return ...
def fractional_base(fractional_part, input_base=10, output_base=10, max_depth=100): """ Convert the fractional part of a number from any base to any base. Args: fractional_part(iterable container): The fractional part of a number in the following form: ( ".", int, int, int, ...) input_base(int): The base to convert fro...
numerator *= output_base ** i digit = numerator // denominator numerator -= digit * denominator denominator *= output_base ** i digits.append(digit) i += 1 greatest_common_divisor = gcd(numerator, denominator) numerator //= greatest_common_divisor denominator //= greatest_common_divisor return (".",) + tuple(digits)
def truncate(n): """ Removes trailing zeros. Args: n: The number to truncate. This number should be in the following form: (..., '.', int, int, int, ..., 0) Returns: n with all trailing zeros removed >>> truncate((9, 9, 9, '.', 9, 9, 9, 9, 0, 0, 0, 0)) (9, 9, 9, '.', 9, 9, 9, 9) >>> truncate(('.',)) ('.',) """ count = ...
def str_digit_to_int(chr): """ Converts a string character to a decimal number. Where "A"->10, "B"->11, "C"->12, ...etc Args: chr(str): A single character in the form of a string. Returns: The integer value of the input string digit. """ # 0 - 9 if chr in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): n = int(chr)...
def int_to_str_digit(n): """ Converts a positive integer, to a single string character. Where: 9 -> "9", 10 -> "A", 11 -> "B", 12 -> "C", ...etc Args: n(int): A positve integer number. Returns: The character representation of the input digit of value n (str). """ # 0 - 9 if n < 10: return str(n) # A - Z elif n < 36: re...
def find_recurring(number, min_repeat=5): """ Attempts to find repeating digits in the fractional component of a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) min_repeat(int): the minimum number of times a pattern must occur to be defined as recurring. A min...
number or min_repeat < 1: return number # Seperate the number into integer and fractional parts. integer_part, fractional_part = integer_fractional_parts(number) # Reverse fractional part to get a sequence. sequence = fractional_part[::-1] # Initialize counters # The 'period' is the number of digits in a pattern. perio...
period * repeat if rank > best: best_period = period best_repeat = repeat best = rank # If the pattern does not repeat often enough, return the original number. if best_repeat < min_repeat: return number # Use the best pattern found. pattern = sequence[:best_period] # Remove the pattern from our original number. number...
def expand_recurring(number, repeat=5): """ Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expanded. Example: >>> expan...
def check_valid(number, input_base=10): """ Checks if there is an invalid digit in the input number. Args: number: An number in the following form: (int, int, int, ... , '.' , int, int, int) (iterable container) containing positive integers of the input base input_base(int): The base of the input number. Returns: bool,...
def base(number, input_base=10, output_base=10, max_depth=10, string=False, recurring=True): """ Converts a number from any base to any another. Args: number(tuple|str|int): The number to convert. input_base(int): The base to convert from (defualt 10). output_base(int): The base to convert to (default 10). max_depth(in...
a digit value is too high for the input_base. Example: >>> base((1,9,6,'.',5,1,6), 17, 20) (1, 2, 8, '.', 5, 19, 10, 7, 17, 2, 13, 13, 1, 8) """ # Convert number to tuple representation. if type(number) == int or type(number) == float: number = str(number) if type(number) == str: number = represent_as_tuple(number) # C...
number = truncate(number) # Convert an integer number. else: number = integer_base(number, input_base, output_base) if recurring: number = find_recurring(number, min_repeat=2) # Return the converted number as a srring or tuple. return represent_as_string(number) if string else number
def get_config_directory(appname): """ Get OS-specific configuration directory. :type appname: str :arg appname: capitalized name of the application """ if platform.system().lower() == 'windows': path = os.path.join(os.getenv('APPDATA') or '~', appname, appname) elif platform.system().lower() == 'darwin': path = os.pat...
def save_model(self, request, obj, form, change): """ sends the email and does not save it """ email = message.EmailMessage( subject=obj.subject, body=obj.body, from_email=obj.from_email, to=[t.strip() for t in obj.to_emails.split(',')], bcc=[t.strip() for t in obj.bcc_emails.split(',')], cc=[t.strip() for t in obj.cc_...
def read_gdf(fname): """ Fast line-by-line gdf-file reader. Parameters ---------- fname : str Path to gdf-file. Returns ------- numpy.ndarray ([gid, val0, val1, **]), dtype=object) mixed datatype array """ gdf_file = open(fname, 'r') gdf = [] for l in gdf_file: data = l.split() gdf += [data] gdf = np.array(gdf, dtype=o...
def write_gdf(gdf, fname): """ Fast line-by-line gdf-file write function Parameters ---------- gdf : numpy.ndarray Column 0 is gids, columns 1: are values. fname : str Path to gdf-file. Returns ------- None """ gdf_file = open(fname, 'w') for line in gdf: for i in np.arange(len(line)): gdf_file.write(str(line[i]) + '\t...
def load_h5_data(path='', data_type='LFP', y=None, electrode=None, warmup=0., scaling=1.): """ Function loading results from hdf5 file Parameters ---------- path : str Path to hdf5-file data_type : str Signal types in ['CSD' , 'LFP', 'CSDsum', 'LFPsum']. y : None or str Name of population. electrode : None or int TODO:...
num_cells = int(len(data)*scaling) data = data[:num_cells,:, warmup:] else: f = h5py.File(os.path.join(path, '%ssum.h5' %data_type)) data = f['data'].value[:, warmup:] return data
def dump_dict_of_nested_lists_to_h5(fname, data): """ Take nested list structure and dump it in hdf5 file. Parameters ---------- fname : str Filename data : dict(list(numpy.ndarray)) Dict of nested lists with variable len arrays. Returns ------- None """ # Open file print('writing to file: %s' % fname) f = h5py.File(fn...
def load_dict_of_nested_lists_from_h5(fname, toplevelkeys=None): """ Load nested list structure from hdf5 file Parameters ---------- fname : str Filename toplevelkeys : None or iterable, Load a two(default) or three-layered structure. Returns ------- dict(list(numpy.ndarray)) dictionary of nested lists with variable le...
def setup_file_dest(params, clearDestination=True): """ Function to set up the file catalog structure for simulation output Parameters ---------- params : object e.g., `cellsim16popsParams.multicompartment_params()` clear_dest : bool Savefolder will be cleared if already existing. Returns ------- None """ if RANK == 0:...
'microcircuit.sli']: if os.path.isfile(f): if not os.path.exists(os.path.join(params.sim_scripts_path, f)): shutil.copy(f, os.path.join(params.sim_scripts_path, f)) os.chmod(os.path.join(params.sim_scripts_path, f), stat.S_IREAD) COMM.Barrier()
def calculate_fft(data, tbin): """ Function to calculate the Fourier transform of data. Parameters ---------- data : numpy.ndarray 1D or 2D array containing time series. tbin : float Bin size of time series (in ms). Returns ------- freqs : numpy.ndarray Frequency axis of signal in Fourier space. fft : numpy.ndarray Sig...
def centralize(data, time=False, units=False): """ Function to subtract the mean across time and/or across units from data Parameters ---------- data : numpy.ndarray 1D or 2D array containing time series, 1st index: unit, 2nd index: time time : bool True: subtract mean across time. units : bool True: subtract mean acro...
def normalize(data): """ Function to normalize data to have mean 0 and unity standard deviation (also called z-transform) Parameters ---------- data : numpy.ndarray Returns ------- numpy.ndarray z-transform of input array """ data = data.astype(float) data -= data.mean() return data / data.std()
def movav(y, Dx, dx): """ Moving average rectangular window filter: calculate average of signal y by using sliding rectangular window of size Dx using binsize dx Parameters ---------- y : numpy.ndarray Signal Dx : float Window length of filter. dx : float Bin size of signal sampling. Returns ------- numpy.ndarray Filte...
def decimate(x, q=10, n=4, k=0.8, filterfun=ss.cheby1): """ scipy.signal.decimate like downsampling using filtfilt instead of lfilter, and filter coeffs from butterworth or chebyshev type 1. Parameters ---------- x : numpy.ndarray Array to be downsampled along last axis. q : int Downsampling factor. n : int Filter orde...
# Multidim array can only be processed at once for scipy >= 0.9.0 y = [] for data in x: y.append(ss.filtfilt(b, a, data)) y = np.array(y) try: return y[:, ::q] except: return y[::q]
def mean(data, units=False, time=False): """ Function to compute mean of data Parameters ---------- data : numpy.ndarray 1st axis unit, 2nd axis time units : bool Average over units time : bool Average over time Returns ------- if units=False and time=False: error if units=True: 1 dim numpy.ndarray; time series if time...
time is True: return np.mean(data, axis=1) elif units is True and time is True: return np.mean(data)
def powerspec(data, tbin, Df=None, units=False, pointProcess=False): """ Calculate (smoothed) power spectra of all timeseries in data. If units=True, power spectra are averaged across units. Note that averaging is done on power spectra rather than data. If pointProcess is True, power spectra are normalized by the lengt...
numpy.ndarray; frequency series Examples -------- >>> powerspec(np.array([analog_sig1, analog_sig2]), tbin, Df=Df) Out[1]: (freq,POW) >>> POW.shape Out[2]: (2,len(analog_sig1)) >>> powerspec(np.array([analog_sig1, analog_sig2]), tbin, Df=Df, units=True) Out[1]: (freq,POW) >>> POW.shape Out[2]: (len(analog_sig1),) """ f...
def compound_powerspec(data, tbin, Df=None, pointProcess=False): """ Calculate the power spectrum of the compound/sum signal. data is first summed across units, then the power spectrum is calculated. If pointProcess=True, power spectra are normalized by the length T of the time series. Parameters ---------- data : nump...
def crossspec(data, tbin, Df=None, units=False, pointProcess=False): """ Calculate (smoothed) cross spectra of data. If `units`=True, cross spectra are averaged across units. Note that averaging is done on cross spectra rather than data. Cross spectra are normalized by the length T of the time series -> no scaling with...
1 dim numpy.ndarray; frequency series if `units`=False:3 dim numpy.ndarray; 1st axis first unit, 2nd axis second unit, 3rd axis frequency Examples -------- >>> crossspec(np.array([analog_sig1, analog_sig2]), tbin, Df=Df) Out[1]: (freq,CRO) >>> CRO.shape Out[2]: (2,2,len(analog_sig1)) >>> crossspec(np.array([analog_sig1...
None: cut = int(Df / df) freq = freq[cut:] CRO = np.zeros((N, N, len(freq)), dtype=complex) for i in range(N): for j in range(i + 1): tempij = DATA[i] * DATA[j].conj() if Df is not None: tempij = movav(tempij, Df, df)[cut:] CRO[i, j] = tempij CRO[j, i] = CRO[i, j].conj() assert(len(freq) == len(CRO[0, 0])) if pointProc...
def compound_crossspec(a_data, tbin, Df=None, pointProcess=False): """ Calculate cross spectra of compound signals. a_data is a list of datasets (a_data = [data1,data2,...]). For each dataset in a_data, the compound signal is calculated and the crossspectra between these compound signals is computed. If pointProcess=Tr...
frequency. Examples -------- >>> compound_crossspec([np.array([analog_sig1, analog_sig2]), np.array([analog_sig3,analog_sig4])], tbin, Df=Df) Out[1]: (freq,CRO) >>> CRO.shape Out[2]: (2,2,len(analog_sig1)) """ a_mdata = [] for data in a_data: a_mdata.append(np.sum(data, axis=0)) # calculate compound signals return cros...
def autocorrfunc(freq, power): """ Calculate autocorrelation function(s) for given power spectrum/spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. power : numpy.ndarray 2 dimensional power spectra, 1st axis units, 2nd axis frequencies. Returns ------- time : tuple 1 dim numpy.ndar...
1]]) assert(len(time) == len(autof[0])) else: raw_autof = np.real(np.fft.ifft(power)) mid = int(len(raw_autof) / 2.) autof = np.hstack([raw_autof[mid + 1:], raw_autof[:mid + 1]]) assert(len(time) == len(autof)) # autof *= T*1e-3 # normalization is done in powerspec() return time, autof
def crosscorrfunc(freq, cross): """ Calculate crosscorrelation function(s) for given cross spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. cross : numpy.ndarray 2 dimensional array of cross spectra, 1st axis units, 2nd axis units, 3rd axis frequencies. Returns ------- time : tupl...
for i in range(N): for j in range(N): raw_crossf = np.real(np.fft.ifft(cross[i, j])) mid = int(len(raw_crossf) / 2.) crossf[i, j] = np.hstack( [raw_crossf[mid + 1:], raw_crossf[:mid + 1]]) assert(len(time) == len(crossf[0, 0])) else: raw_crossf = np.real(np.fft.ifft(cross)) mid = int(len(raw_crossf) / 2.) crossf = np.h...
def corrcoef(time, crossf, integration_window=0.): """ Calculate the correlation coefficient for given auto- and crosscorrelation functions. Standard settings yield the zero lag correlation coefficient. Setting integration_window > 0 yields the correlation coefficient of integrated auto- and crosscorrelation functions....
= np.floor(len(time)/2.) for i in range(N): ai = np.sum(crossf[i, i][mid - lim:mid + lim + 1]) offset_autoi = np.mean(crossf[i,i][:mid-1]) for j in range(N): cij = np.sum(crossf[i, j][mid - lim:mid + lim + 1]) offset_cross = np.mean(crossf[i,j][:mid-1]) aj = np.sum(crossf[j, j][mid - lim:mid + lim + 1]) offset_autoj = ...
def coherence(freq, power, cross): """ Calculate frequency resolved coherence for given power- and crossspectra. Parameters ---------- freq : numpy.ndarray Frequencies, 1 dim array. power : numpy.ndarray Power spectra, 1st axis units, 2nd axis frequencies. cross : numpy.ndarray, Cross spectra, 1st axis units, 2nd axis ...
def cv(data, units=False): """ Calculate coefficient of variation (cv) of data. Mean and standard deviation are computed across time. Parameters ---------- data : numpy.ndarray 1st axis unit, 2nd axis time. units : bool Average `cv`. Returns ------- numpy.ndarray If units=False, series of unit `cv`s. float If units=Tru...
def fano(data, units=False): """ Calculate fano factor (FF) of data. Mean and variance are computed across time. Parameters ---------- data : numpy.ndarray 1st axis unit, 2nd axis time. units : bool Average `FF`. Returns ------- numpy.ndarray If units=False, series of unit FFs. float If units=True, mean FF across units...
def collect_gdf(self): """ Collect the gdf-files from network sim in folder `spike_output_path` into sqlite database, using the GDF-class. Parameters ---------- None Returns ------- None """ # Resync COMM.Barrier() # Raise Exception if there are no gdf files to be read if len(glob.glob(os.path.join(self.spike_output_pa...
def get_xy(self, xlim, fraction=1.): """ Get pairs of node units and spike trains on specific time interval. Parameters ---------- xlim : list of floats Spike time interval, e.g., [0., 1000.]. fraction : float in [0, 1.] If less than one, sample a fraction of nodes in random order. Returns ------- x : dict In `x` key-v...
1 return x, y
def plot_raster(self, ax, xlim, x, y, pop_names=False, markersize=20., alpha=1., legend=True, marker='o', rasterized=True): """ Plot network raster plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSubplot` object plot axes xlim : list List of floats. Spike time interval, e.g., [0., 1000.]. x : di...
None """ yoffset = [sum(self.N_X) if X=='TC' else 0 for X in self.X] for i, X in enumerate(self.X): if y[X].size > 0: ax.plot(x[X], y[X]+yoffset[i], marker, markersize=markersize, mfc=self.colors[i], mec='none' if marker in '.ov><v^1234sp*hHDd' else self.colors[i], alpha=alpha, label=X, rasterized=rasterized, clip_on=T...
def plot_f_rate(self, ax, X, i, xlim, x, y, binsize=1, yscale='linear', plottype='fill_between', show_label=False, rasterized=False): """ Plot network firing rate plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSubplot` object. X : str Population name. i : int Population index in class attribute...
/ self.N_X[i], color=self.colors[i], lw=0.5, label=X, rasterized=rasterized, clip_on=False) ax.plot(bins[:-1], hist * 1000. / self.N_X[i], color='k', lw=0.5, label=X, rasterized=rasterized, clip_on=False) elif plottype == 'bar': ax.bar(bins[:-1], hist * 1000. / self.N_X[i], color=self.colors[i], label=X, rasterized=ras...
def raster_plots(self, xlim=[0, 1000], markersize=1, alpha=1., marker='o'): """ Pretty plot of the spiking output of each population as raster and rate. Parameters ---------- xlim : list List of floats. Spike time interval, e.g., `[0., 1000.]`. markersize : float marker size for plot, see `matplotlib.pyplot.plot` alpha...
== 4: ax1.set_ylabel(r'population rates ($s^{-1}$)') if i == 0: ax1.set_title(r'population firing rates ($s^{-1}$)') return fig
def add_sst_to_dot_display(ax, sst, color= '0.',alpha= 1.): ''' suitable for plotting fraction of neurons ''' plt.sca(ax) N = len(sst) current_ymax = 0 counter = 0 while True: if len(ax.get_lines()) !=0: data = ax.get_lines()[-1-counter].get_data()[1] if np.sum(data) != 0: # if not empty array current_ymax = np.max(dat...
def empty_bar_plot(ax): ''' Delete all axis ticks and labels ''' plt.sca(ax) plt.setp(plt.gca(),xticks=[],xticklabels=[]) return ax
def add_to_bar_plot(ax, x, number, name = '', color = '0.'): ''' This function takes an axes and adds one bar to it ''' plt.sca(ax) plt.setp(ax,xticks=np.append(ax.get_xticks(),np.array([x]))\ ,xticklabels=[item.get_text() for item in ax.get_xticklabels()] +[name]) plt.bar([x],number , color = color, width = 1.) return...
def add_to_line_plot(ax, x, y, color = '0.' , label = ''): ''' This function takes an axes and adds one line to it ''' plt.sca(ax) plt.plot(x,y, color = color, label = label) return ax
def colorbar(fig, ax, im, width=0.05, height=1.0, hoffset=0.01, voffset=0.0, orientation='vertical'): ''' draw colorbar without resizing the axes object to make room kwargs: :: fig : matplotlib.figure.Figure ax : matplotlib.axes.AxesSubplot im : matplotlib.image.AxesImage width : float, colorbar width in fraction of ax...
def frontiers_style(): ''' Figure styles for frontiers ''' inchpercm = 2.54 frontierswidth=8.5 textsize = 5 titlesize = 7 plt.rcdefaults() plt.rcParams.update({ 'figure.figsize' : [frontierswidth/inchpercm, frontierswidth/inchpercm], 'figure.dpi' : 160, 'xtick.labelsize' : textsize, 'ytick.labelsize' : textsize, 'font....
def annotate_subplot(ax, ncols=1, nrows=1, letter='a', linear_offset=0.075, fontsize=8): '''add a subplot annotation number''' ax.text(-ncols*linear_offset, 1+nrows*linear_offset, letter, horizontalalignment='center', verticalalignment='center', fontsize=fontsize, fontweight='demibold', transform=ax.transAxes)
def get_colors(num=16, cmap=plt.cm.Set1): '''return a list of color tuples to use in plots''' colors = [] for i in xrange(num): if analysis_params.bw: colors.append('k' if i % 2 == 0 else 'gray') else: i *= 256. if num > 1: i /= num - 1. else: i /= num colors.append(cmap(int(i))) return colors
def compress(self, data, windowLength = None): """Compresses text data using the LZ77 algorithm.""" if windowLength == None: windowLength = self.defaultWindowLength compressed = "" pos = 0 lastPos = len(data) - self.minStringLength while pos < lastPos: searchStart = max(pos - windowLength, 0); matchLength = self.minStr...
(self.referencePrefix + self.__encodeReferenceInt(bestMatchDistance, 2) + self.__encodeReferenceLength(bestMatchLength)) pos += bestMatchLength else: if data[pos] != self.referencePrefix: newCompressed = data[pos] else: newCompressed = self.referencePrefix + self.referencePrefix pos += 1 compressed += newCompressed ret...
def decompress(self, data): """Decompresses LZ77 compressed text data""" decompressed = "" pos = 0 while pos < len(data): currentChar = data[pos] if currentChar != self.referencePrefix: decompressed += currentChar pos += 1 else: nextChar = data[pos + 1] if nextChar != self.referencePrefix: distance = self.__decodeRefer...
def main(): """ Main entry point for running baseconvert as a command. Examples: $ python -m baseconvert -n 0.5 -i 10 -o 20 -s True 0.A $ echo 3.1415926 | python -m baseconvert -i 10 -o 16 -d 3 -s True 3.243 """ # Parse arguments parser = argparse.ArgumentParser(description="Convert rational numbers between bases.") pa...
float(args.input_base) args.output_base = float(args.output_base) if args.input_base == int(args.input_base): args.input_base = int(args.input_base) if args.output_base == int(args.output_base): args.output_base = int(args.output_base) if (args.number): return base(args.number, args.input_base, args.output_base, string...
def message_user(self, username, domain, subject, message): """Currently use send_message_chat and discard subject, because headline messages are not stored by mod_offline.""" jid = '%s@%s' % (username, domain) if self.api_version <= (14, 7): # TODO: it's unclear when send_message was introduced command = 'send_message...
def notify(self, value): """ Increment or decrement the value, according to the given value's sign The value should be an integer, an attempt to cast it to integer will be made """ value = int(value) with self.lock: self.value += value
def get_config(self): """ Load user configuration or return default when not found. :rtype: :class:`Configuration` """ if not self._config: namespace = {} if os.path.exists(self.config_path): execfile(self.config_path, namespace) self._config = namespace.get('config') or Configuration() return self._config
def send(self): """ Sends the object to the watch. Block until completion, or raises :exc:`.PutBytesError` on failure. During transmission, a "progress" event will be periodically emitted with the following signature: :: (sent_this_interval, sent_so_far, total_object_size) """ # Prepare the watch to receive something. ...
def open(self, input_streams=['stdin'], output_streams=['stderr', 'stdout']): """ Opens the remote shell """ shell = dict() shell['rsp:InputStreams'] = " ".join(input_streams) shell['rsp:OutputStreams'] = " ".join(output_streams) shell['rsp:IdleTimeout'] = str(self.idle_timeout) if self.working_directory is not None: s...
def run(self, command, arguments=(), console_mode_stdin=True, skip_cmd_shell=False): """This function does something. :param command: The command to be executed :type name: str. :param arguments: A list of arguments to be passed to the command :type state: str. :returns: int -- the return code. :raises: AttributeError,...
def receive(self, command_id, streams=('stdout', 'stderr'), command_timeout=60): """ Recieves data :param command_id: :param streams: :param command_timeout: :return: """ logging.info('receive command: ' + command_id) response_streams = dict.fromkeys(streams, '') (complete, exit_code) = self._receive_poll(command_id, r...
def _receive_poll(self, command_id, response_streams): """ Recieves data :param command_id: :param streams: :return: """ logging.info('receive command: ' + command_id) resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) stream_attributes = {'#text': " ".join(response...
def close(self): """ Closes pipe :return: """ resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) self.session.delete(resource)
def change_dict_keys(self, data_dict, prefix): """ Prefixes 'L_'/'R_' to the collection keys :param data_dict: dictionary which is to be altered :type data_dict: dict :param prefix: prefix to be attached before every key :type prefix: string :return dict_: dict """ keys = data_dict.keys() dummy_dict = copy.deepcopy(dat...
def generate_join_docs_list(self, left_collection_list, right_collection_list): """ Helper function for merge_join_docs :param left_collection_list: Left Collection to be joined :type left_collection_list: MongoCollection :param right_collection_list: Right Collection to be joined :type right_collection_list: MongoColl...
def merge_join_docs(self, keys): """ Merges the final list of docs :param left_collection_list: :type left_collection_list: MongoCollection :return join: dict """ join = defaultdict(list) for key in keys: join[key] = self.generate_join_docs_list( self.collections_data['left'].get(key, []), self.collections_data['right'...
def inner(self): """ Performs Inner Join :return inner_join: dict """ self.get_collections_data() inner_join = self.merge_join_docs(set(self.collections_data['left'].keys()) & set( self.collections_data['right'].keys())) return inner_join
def left_outer(self): """ Performs Left Outer Join :return left_outer: dict """ self.get_collections_data() left_outer_join = self.merge_join_docs( set(self.collections_data['left'].keys())) return left_outer_join
def right_outer(self): """ Performs Right Outer Join :return right_outer: dict """ self.get_collections_data() right_outer_join = self.merge_join_docs( set(self.collections_data['right'].keys())) return right_outer_join
def full_outer(self): """ Performs Full Outer Join :return full_outer: dict """ self.get_collections_data() full_outer_join = self.merge_join_docs( set(self.collections_data['left'].keys()) | set(self.collections_data['right'].keys())) return full_outer_join
def needs_auth(meth): """Wraps a method of :class:`TwitchSession` and raises an :class:`exceptions.NotAuthorizedError` if before calling the method, the session isn't authorized. :param meth: :type meth: :returns: the wrapped method :rtype: Method :raises: None """ @functools.wraps(meth) def wrapped(*args, **kwargs): i...
def request(self, method, url, **kwargs): """Constructs a :class:`requests.Request`, prepares it and sends it. Raises HTTPErrors by default. :param method: method for the new :class:`Request` object. :type method: :class:`str` :param url: URL for the new :class:`Request` object. :type url: :class:`str` :param kwargs: k...
def start_login_server(self, ): """Start a server that will get a request from a user logging in. This uses the Implicit Grant Flow of OAuth2. The user is asked to login to twitch and grant PyTwitcher authorization. Once the user agrees, he is redirected to an url. This server will respond to that url and get the oauth...