code stringlengths 1 18.2k |
|---|
def calc_signal_sum(self, measure='LFP'): """ Superimpose each cell's contribution to the compound population signal, i.e., the population CSD or LFP Parameters ---------- measure : str {'LFP', 'CSD'}: Either 'LFP' or 'CSD'. Returns ------- numpy.ndarray The populations-specific compound signal. """ #compute the total ... |
def collectSingleContribs(self, measure='LFP'): """ Collect single cell data and save them to HDF5 file. The function will also return signals generated by all cells Parameters ---------- measure : str {'LFP', 'CSD'}: Either 'LFP' or 'CSD'. Returns ------- numpy.ndarray output of all neurons in population, axis 0 corre... |
+= [ids[ids < SAMPLESIZE]] #gather data on this RANK if RANK_CELLINDICES[RANK].size > 0: for i, cellindex in enumerate(RANK_CELLINDICES[RANK]): if i == 0: data_temp = np.zeros([RANK_CELLINDICES[RANK].size] + list(self.output[cellindex ][measure].shape), dtype=np.float32) data_temp[i, ] = self.output[cellindex][measure]... |
tag=13) if RANK == 0: #save all single-cell data to file fname = os.path.join(self.populations_path, '%s_%ss.h5' % (self.y, measure)) f = h5py.File(fname, 'w') f.create_dataset('data', data=data, compression=4) f['srate'] = self.output[0]['srate'] f.close() assert(os.path.isfile(fname)) print('file %s_%ss.h5 ok' % (sel... |
def collect_data(self): """ Collect LFPs, CSDs and soma traces from each simulated population, and save to file. Parameters ---------- None Returns ------- None """ #collect some measurements resolved per file and save to file for measure in ['LFP', 'CSD']: if measure in self.savelist: self.collectSingleContribs(measur... |
csd assert(os.path.isfile(fname)) print('save CSD ok') #save the somatic placements: pop_soma_pos = np.zeros((self.POPULATION_SIZE, 3)) keys = ['xpos', 'ypos', 'zpos'] for i in range(self.POPULATION_SIZE): for j in range(3): pop_soma_pos[i, j] = self.pop_soma_pos[i][keys[j]] fname = os.path.join(self.populations_path, ... |
def get_all_synIdx(self): """ Auxilliary function to set up class attributes containing synapse locations given as LFPy.Cell compartment indices This function takes no inputs. Parameters ---------- None Returns ------- synIdx : dict `output[cellindex][populationindex][layerindex]` numpy.ndarray of compartment indices. ... |
0: print('found synapse locations in %.2f seconds' % (time()-tic)) #print the number of synapses per layer from which presynapse population if self.verbose: for cellindex in self.RANK_CELLINDICES: for i, synidx in enumerate(synIdx[cellindex]): print('to:\t%s\tcell:\t%i\tfrom:\t%s:' % (self.y, cellindex, self.X[i]),) id... |
def get_all_SpCells(self): """ For each postsynaptic cell existing on this RANK, load or compute the presynaptic cell index for each synaptic connection This function takes no kwargs. Parameters ---------- None Returns ------- SpCells : dict `output[cellindex][populationname][layerindex]`, np.array of presynaptic cell ... |
if RANK == 0: print('found presynaptic cells in %.2f seconds' % (time()-tic)) return SpCells |
def get_all_synDelays(self): """ Create and load arrays of connection delays per connection on this rank Get random normally distributed synaptic delays, returns dict of nested list of same shape as SpCells. Delays are rounded to dt. This function takes no kwargs. Parameters ---------- None Returns ------- dict output[... |
delays[cellindex][X] = [] for i in self.k_yXL[:, j]: loc = self.synDelayLoc[j] loc /= self.dt scale = self.synDelayScale[j] if scale is not None: scale /= self.dt delay = np.random.normal(loc, scale, i).astype(int) while np.any(delay < 1): inds = delay < 1 delay[inds] = np.random.normal(loc, scale, inds.sum()).astype(i... |
def get_synidx(self, cellindex): """ Local function, draw and return synapse locations corresponding to a single cell, using a random seed set as `POPULATIONSEED` + `cellindex`. Parameters ---------- cellindex : int Index of cell object. Returns ------- synidx : dict `LFPy.Cell` compartment indices See also -------- Po... |
def fetchSynIdxCell(self, cell, nidx, synParams): """ Find possible synaptic placements for each cell As synapses are placed within layers with bounds determined by self.layerBoundaries, it will check this matrix accordingly, and use the probabilities from `self.connProbLayer to distribute. For each layer, the synapses... |
dtype=int)) else: syn_idx.append(cell.get_rand_idx_area_norm( section=synParams['section'], nidx=nidx[i], z_min=zz.min(), z_max=zz.max()).astype('int16')) return syn_idx |
def cellsim(self, cellindex, return_just_cell = False): """ Do the actual simulations of LFP, using synaptic spike times from network simulation. Parameters ---------- cellindex : int cell index between 0 and population size-1. return_just_cell : bool If True, return only the `LFPy.Cell` object if False, run full simul... |
np.eye(cell.totnsegs) csdcoeff = csd.true_lam_csd(cell, self.populationParams['radius'], electrode.z) csdcoeff *= 1E6 #nA mum^-3 -> muA mm^-3 conversion del cell.tvec, cell.imem cell.simulate(electrode, dotprodcoeffs=[csdcoeff], **self.simulationParams) cell.CSD = helpers.decimate(cell.dotprodresults[0], q=self.decimat... |
def insert_all_synapses(self, cellindex, cell): """ Insert all synaptic events from all presynaptic layers on cell object with index `cellindex`. Parameters ---------- cellindex : int cell index in the population. cell : `LFPy.Cell` instance Postsynaptic target cell. Returns ------- None See also -------- Population.in... |
def insert_synapses(self, cell, cellindex, synParams, idx = np.array([]), X='EX', SpCell = np.array([]), synDelays = None): """ Insert synapse with `parameters`=`synparams` on cell=cell, with segment indexes given by `idx`. `SpCell` and `SpTimes` picked from Brunel network simulation Parameters ---------- cell : `LFPy.... |
i, delay in enumerate(synDelays): if spikes[i].size > 0: spikes[i] += delay #create synapse events: for i in range(idx.size): if len(spikes[i]) == 0: pass #print 'no spike times, skipping network cell #%i' % SpCell[i] else: synParams.update({'idx' : idx[i]}) # Create synapse(s) and setting times using class LFPy.Synaps... |
def fetchSpCells(self, nodes, numSyn): """ For N (nodes count) nestSim-cells draw POPULATION_SIZE x NTIMES random cell indexes in the population in nodes and broadcast these as `SpCell`. The returned argument is a list with len = numSyn.size of np.arrays, assumes `numSyn` is a list Parameters ---------- nodes : numpy.n... |
def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs): """ Provide interface for multiprocessing Args: func: callable functions keys: keys in kwargs that want to use process max_procs: max number of processes show_proc: whether to show process affinity: CPU affinity **kwargs: kwargs for func """... |
def saturate_kwargs(keys, **kwargs): """ Saturate all combinations of kwargs Args: keys: keys in kwargs that want to use process **kwargs: kwargs for func """ # Validate if keys are in kwargs and if they are iterable if isinstance(keys, str): keys = [keys] keys = [k for k in keys if k in kwargs and hasattr(kwargs.get(k... |
def quick_idw(input_geojson_points, variable_name, power, nb_class, nb_pts=10000, resolution=None, disc_func=None, mask=None, user_defined_breaks=None, variable_name2=None, output='GeoJSON', **kwargs): """ Function acting as a one-shot wrapper around SmoothIdw object. Read a file of point values and optionnaly a mask f... |
meters), if not set a default resolution will be used in order to make a grid containing around 10000 pts (default: None). disc_func: str, optionnal The name of the classification function to be used to decide on which break values to use to create the contour layer. (default: None) mask : str, optionnal Path to the fi... |
the first variable (default: None) output : string, optionnal The type of output expected (not case-sensitive) in {"GeoJSON", "GeoDataFrame"} (default: "GeoJSON"). Returns ------- smoothed_result : bytes or GeoDataFrame, The result, dumped as GeoJSON (utf-8 encoded) or as a GeoDataFrame. Examples -------- Basic usage, ... |
def quick_stewart(input_geojson_points, variable_name, span, beta=2, typefct='exponential',nb_class=None, nb_pts=10000, resolution=None, mask=None, user_defined_breaks=None, variable_name2=None, output="GeoJSON", **kwargs): """ Function acting as a one-shot wrapper around SmoothStewart object. Read a file of point valu... |
the underlying grid. (default: 10000) resolution : int, optionnal The resolution to use (in meters), if not set a default resolution will be used in order to make a grid containing around 10000 pts (default: None). mask : str, optionnal Path to the file (Polygons only) to use as clipping mask, can also be a GeoDataFram... |
case-sensitive) in {"GeoJSON", "GeoDataFrame"} (default: "GeoJSON"). Returns ------- smoothed_result : bytes or GeoDataFrame, The result, dumped as GeoJSON (utf-8 encoded) or as a GeoDataFrame. Examples -------- Basic usage, output to raw geojson (bytes): >>> result = quick_stewart("some_file.geojson", "some_variable",... |
def make_regular_points_with_no_res(bounds, nb_points=10000): """ Return a regular grid of points within `bounds` with the specified number of points (or a close approximate value). Parameters ---------- bounds : 4-floats tuple The bbox of the grid, as xmin, ymin, xmax, ymax. nb_points : int, optionnal The desired numb... |
def make_regular_points(bounds, resolution, longlat=True): """ Return a regular grid of points within `bounds` with the specified resolution. Parameters ---------- bounds : 4-floats tuple The bbox of the grid, as xmin, ymin, xmax, ymax. resolution : int The resolution to use, in the same unit as `bounds` Returns ------... |
hav_dist( np.array([minlon, (maxlat + minlat) / 2]), np.array([maxlon, (maxlat + minlat) / 2]) ) else: height = np.linalg.norm( np.array([(maxlon + minlon) / 2, minlat]) - np.array([(maxlon + minlon) / 2, maxlat])) width = np.linalg.norm( np.array([minlon, (maxlat + minlat) / 2]) - np.array([maxlon, (maxlat + minlat) /... |
def make_dist_mat(xy1, xy2, longlat=True): """ Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- xy1 : numpy.array The first set of coordinates as [(x, y), (x, y), (x, y)]. xy2 : numpy.array The second set of coordina... |
def hav_dist(locs1, locs2): """ Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- locs1 : numpy.array The first set of coordinates as [(long, lat), (long, lat)]. locs2 : numpy.array The second set of coordinates as [(... |
def isopoly_to_gdf(collec_poly, levels, field_name="levels"): """ Convert a collection of matplotlib.contour.QuadContourSet to a GeoDataFrame Set an attribute `field_name` on each feature, according to `levels` values (`levels` must have the same number of features as the collection of contours) Parameters ---------- c... |
3: exterior = poly[0] if len(poly) > 1: holes = [h for h in poly[1:] if len(h) > 3] mpoly.append(Polygon(exterior, holes)) if len(mpoly) > 1: mpoly = MultiPolygon(mpoly) polygons.append(mpoly) data.append(levels[i]) elif len(mpoly) == 1: polygons.append(mpoly[0]) data.append(levels[i]) return GeoDataFrame(geometry=poly... |
def render(self, nb_class=8, disc_func=None, user_defined_breaks=None, output="GeoJSON", new_mask=False): """ Parameters ---------- nb_class : int, optionnal The number of class (default: 8). disc_func : str, optionnal The kind of data classification to be used (to be choosed in "equal_interval", "jenks", "percentiles,... |
(utf-8 encoded) or as a GeoDataFrame. """ if disc_func and 'jenks' in disc_func and not jenks_breaks: raise ValueError( "Missing jenkspy package - could not use jenks breaks") zi = self.zi if isinstance(new_mask, (type(False), type(None))): if not self.use_mask: self.use_mask = False self.mask = None else: self.open_ma... |
list(s_levels) levels.sort() try: collec_poly = contourf( self.XI, self.YI, zi.reshape(tuple(reversed(self.shape))).T, levels, vmax=abs(np.nanmax(zi)), vmin=-abs(np.nanmin(zi))) # Retry without setting the levels : except ValueError: collec_poly = contourf( self.XI, self.YI, zi.reshape(tuple(reversed(self.shape))).T, v... |
and the mask layer: ix_max_ft = len(res) - 1 if self.use_mask: res.loc[0:ix_max_ft, "geometry"] = res.geometry.buffer( 0).intersection(unary_union(self.mask.geometry.buffer(0))) # res.loc[0:ix_max_ft, "geometry"] = res.geometry.buffer( # 0).intersection(self.poly_max_extend.buffer(-0.1)) # Repair geometries if necessar... |
def identify(s): """Identify what kind of Chinese characters a string contains. *s* is a string to examine. The string's Chinese characters are tested to see if they are compatible with the Traditional or Simplified characters systems, compatible with both, or contain a mixture of Traditional and Simplified characters.... |
and :func:`has_chinese` are provided. """ chinese = _get_hanzi(s) if not chinese: return UNKNOWN if chinese.issubset(_SHARED_CHARACTERS): return BOTH if chinese.issubset(_TRADITIONAL_CHARACTERS): return TRADITIONAL if chinese.issubset(_SIMPLIFIED_CHARACTERS): return SIMPLIFIED return MIXED |
def is_traditional(s): """Check if a string's Chinese characters are Traditional. This is equivalent to: >>> identify('foo') in (TRADITIONAL, BOTH) """ chinese = _get_hanzi(s) if not chinese: return False elif chinese.issubset(_SHARED_CHARACTERS): return True elif chinese.issubset(_TRADITIONAL_CHARACTERS): return True ... |
def is_simplified(s): """Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH) """ chinese = _get_hanzi(s) if not chinese: return False elif chinese.issubset(_SHARED_CHARACTERS): return True elif chinese.issubset(_SIMPLIFIED_CHARACTERS): return True retu... |
def get(self, resource, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.GetAction, operation_timeout, max_envelope_size, locale) self.servic... |
def put(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ headers = None return self.service.invoke(headers, obj) |
def delete(self, resource, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.DeleteAction, operation_timeout, max_envelope_size, locale) retur... |
def create(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.CreateAction, operation_timeout, max_envelope_size, locale) ... |
def command(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.CommandAction, operation_timeout, max_envelope_size, locale... |
def recieve(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.ReceiveAction, operation_timeout, max_envelope_size, locale... |
def set_default_fig_style(self): '''default figure size''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm, self.frontierswidth/self.inchpercm], }) |
def set_large_fig_style(self): '''twice width figure size''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*2, self.frontierswidth/self.inchpercm], }) |
def set_broad_fig_style(self): '''4 times width, 1.5 times height''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*4, self.frontierswidth/self.inchpercm*1.5], }) |
def set_enormous_fig_style(self): '''2 times width, 2 times height''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*2, self.frontierswidth/self.inchpercm*2], }) |
def set_PLOS_1column_fig_style(self, ratio=1): '''figure size corresponding to Plos 1 column''' plt.rcParams.update({ 'figure.figsize' : [self.PLOSwidth1Col,self.PLOSwidth1Col*ratio], }) |
def set_PLOS_2column_fig_style(self, ratio=1): '''figure size corresponding to Plos 2 columns''' plt.rcParams.update({ 'figure.figsize' : [self.PLOSwidth2Col, self.PLOSwidth2Col*ratio], }) |
def run(self): """ Perform the postprocessing steps, computing compound signals from cell-specific output files. """ if RANK == 0: if 'LFP' in self.savelist: #get the per population LFPs and total LFP from all populations: self.LFPdict, self.LFPsum = self.calc_lfp() self.LFPdictLayer = self.calc_lfp_layer() #save globa... |
data=self.CSDsum, compression=4) f.close() for key, value in list(self.CSDdictLayer.items()): f = h5py.File(os.path.join(self.populations_path, self.output_file.format(key, 'CSD.h5') ), 'w') f['srate'] = 1E3 / self.dt_output f.create_dataset('data', data=value, compression=4) f.close() else: pass |
def _set_up_savefolder(self): """ Create catalogs for different file output to clean up savefolder. """ if not os.path.isdir(self.cells_path): os.mkdir(self.cells_path) if not os.path.isdir(self.figures_path): os.mkdir(self.figures_path) if not os.path.isdir(self.populations_path): os.mkdir(self.populations_path) |
def calc_lfp(self): """ Sum all the LFP contributions from every cell type. """ LFParray = np.array([]) LFPdict = {} i = 0 for y in self.y: fil = os.path.join(self.populations_path, self.output_file.format(y, 'LFP.h5')) f = h5py.File(fil) if i == 0: LFParray = np.zeros((len(self.y), f['data'].shape[0], f['data'].shape[... |
def calc_csd(self): """ Sum all the CSD contributions from every layer. """ CSDarray = np.array([]) CSDdict = {} i = 0 for y in self.y: fil = os.path.join(self.populations_path, self.output_file.format(y, 'CSD.h5')) f = h5py.File(fil) if i == 0: CSDarray = np.zeros((len(self.y), f['data'].shape[0], f['data'].shape[1]))... |
def calc_lfp_layer(self): """ Calculate the LFP from concatenated subpopulations residing in a certain layer, e.g all L4E pops are summed, according to the `mapping_Yy` attribute of the `hybridLFPy.Population` objects. """ LFPdict = {} lastY = None for Y, y in self.mapping_Yy: if lastY != Y: try: LFPdict.update({Y : se... |
def calc_csd_layer(self): """ Calculate the CSD from concatenated subpopulations residing in a certain layer, e.g all L4E pops are summed, according to the `mapping_Yy` attribute of the `hybridLFPy.Population` objects. """ CSDdict = {} lastY = None for Y, y in self.mapping_Yy: if lastY != Y: try: CSDdict.update({Y : se... |
def create_tar_archive(self): """ Create a tar archive of the main simulation outputs. """ #file filter EXCLUDE_FILES = glob.glob(os.path.join(self.savefolder, 'cells')) EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder, 'populations', 'subsamples')) EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder, 'raw_n... |
def sort_queryset(queryset, request, context=None): """ Returns a sorted queryset The context argument is only used in the template tag """ sort_by = request.GET.get('sort_by') if sort_by: if sort_by in [el.name for el in queryset.model._meta.fields]: queryset = queryset.order_by(sort_by) else: if sort_by in request.se... |
def include_before(predicate, num, iterative): """ Return elements in `iterative` including `num`-before elements. >>> list(include_before(lambda x: x == 'd', 2, 'abcded')) ['b', 'c', 'd', 'e', 'd'] """ (it0, it1) = itertools.tee(iterative) ps = _backward_shifted_predicate(predicate, num, it1) return (e for (e, p) in z... |
def include_after(predicate, num, iterative): """ Return elements in `iterative` including `num`-after elements. >>> list(include_after(lambda x: x == 'b', 2, 'abcbcde')) ['b', 'c', 'b', 'c', 'd'] """ (it0, it1) = itertools.tee(iterative) ps = _forward_shifted_predicate(predicate, num, it1) return (e for (e, p) in zip(... |
def include_context(predicate, num, iterative): """ Return elements in `iterative` including `num` before and after elements. >>> ''.join(include_context(lambda x: x == '!', 2, 'bb!aa__bb!aa')) 'bb!aabb!aa' """ (it0, it1, it2) = itertools.tee(iterative, 3) psf = _forward_shifted_predicate(predicate, num, it1) psb = _ba... |
def create_downsampled_data(params): ''' Creates one CSD or LFP file with downsampled data per cell type ''' maxsamples = 1 for data_type in ['LFP','CSD']: if RANK == 0: if not os.path.isdir(os.path.join(params.savefolder, 'populations', 'subsamples')): os.mkdir((os.path.join(params.savefolder,'populations','subsamples... |
## shuffle data #np.random.shuffle(raw_data) # sample size N = int(params.N_y[np.array(params.y) == y]*ana_params.scaling) try: assert(N <= raw_data.shape[0]) except AssertionError as ae: raise ae, 'shape mismatch with sample size' for sample in range(samples): # loop over samples # slice data data = raw_data[sample*N:... |
COUNTER % SIZE == RANK: # initialize full sum signal data_full = np.zeros(datashape[1:]) for j,layer in enumerate(params.y_in_Y): # loop over layers for k,pop in enumerate(layer): # loop over populations # initialize population resolved sum signal data_Y = np.zeros(datashape[1:]) for i,y in enumerate(pop): # loop over ... |
% str(f.filename) f['data'] = data_full f['srate'] = srate f.close() COUNTER += 1 COMM.Barrier() |
def calc_signal_power(params): ''' calculates power spectrum of sum signal for all channels ''' for i, data_type in enumerate(['CSD','LFP','CSD_10_0', 'LFP_10_0']): if i % SIZE == RANK: # Load data if data_type in ['CSD','LFP']: fname=os.path.join(params.savefolder, data_type+'sum.h5') else: fname=os.path.join(params.p... |
Pxx/tvec[tvec >= ana_params.transient].size**2 PSD +=[Pxx.flatten()] PSD=np.array(PSD) # Save data f = h5py.File(os.path.join(params.savefolder, ana_params.analysis_folder, data_type + ana_params.fname_psd),'w') f['freqs']=freqs f['psd']=PSD f['transient']=ana_params.transient f['mlab']=ana_params.mlab f['NFFT']=ana_pa... |
def calc_uncorrelated_signal_power(params): '''This function calculates the depth-resolved power spectrum of signals without taking into account any cross-correlation.''' for i, data_type in enumerate(['LFP','CSD']): if i % SIZE == RANK: # Determine size of PSD matrix f = h5py.File(os.path.join(params.savefolder, data_... |
for ch in range(len(params.electrodeParams['z'])): # loop over channels P_j_ch, freqs = plt.mlab.psd(data_y[j,ch], NFFT=ana_params.NFFT, Fs=srate, noverlap=ana_params.noverlap, window=ana_params.window) P[ch] += P_j_ch else: [freqs, P_j] = hlp.powerspec(data_y[j], tbin= 1./srate*1000., Df=ana_params.Df, pointProcess=Fa... |
def calc_variances(params): ''' This function calculates the variance of the sum signal and all population-resolved signals ''' depth = params.electrodeParams['z'] ############################ ### CSD ### ############################ for i, data_type in enumerate(['CSD','LFP']): if i % SIZE == RANK: f_out = h5py.File(o... |
def on_join(self, connection, event): """Handles the join event and greets everone :param connection: the connection with the event :type connection: :class:`irc.client.ServerConnection` :param event: the event to handle :type event: :class:`irc.client.Event` :returns: None """ target = event.source self.privmsg(target... |
def daemon_run(no_error, restart, record_path, keep_json, check_duplicate, use_polling, log_level): """ Run RASH index daemon. This daemon watches the directory ``~/.config/rash/data/record`` and translate the JSON files dumped by ``record`` command into sqlite3 DB at ``~/.config/rash/data/db.sqlite``. ``rash init`` wi... |
work on NFS.:: # Refresh RASH DB every 10 minutes */10 * * * * rash index """ # Probably it makes sense to use this daemon to provide search # API, so that this daemon is going to be the only process that # is connected to the DB? from .config import ConfigStore from .indexer import Indexer from .log import setup_daemo... |
alive except OSError: flogger.info( 'Process with PID=%d is already dead. ' 'So just go on and use this daemon.', pid) else: if restart: flogger.info('Stopping old daemon with PID=%d.', pid) stop_running_daemon(cfstore, pid) else: message = ('There is already a running daemon (PID={0})!' .format(pid)) if no_error: flog... |
def start_daemon_in_subprocess(options, outpath=os.devnull): """ Run `rash daemon --no-error` in background. :type options: list of str :arg options: options for "rash daemon" command :type outpath: str :arg outpath: path to redirect daemon output """ import subprocess import sys from .utils.py3compat import nested fro... |
def show_run(command_history_id): """ Show detailed command history by its ID. """ from pprint import pprint from .config import ConfigStore from .database import DataBase db = DataBase(ConfigStore().db_path) with db.connection(): for ch_id in command_history_id: crec = db.get_full_command_record(ch_id) pprint(crec.__d... |
def insert(self, database, key, value, callback=None): """ Insert an item into the given database. :param database: The database into which to insert the value. :type database: .BlobDatabaseID :param key: The key to insert. :type key: uuid.UUID :param value: The value to insert. :type value: bytes :param callback: A ca... |
def delete(self, database, key, callback=None): """ Delete an item from the given database. :param database: The database from which to delete the value. :type database: .BlobDatabaseID :param key: The key to delete. :type key: uuid.UUID :param callback: A callback to be called on success or failure. """ token = self._... |
def clear(self, database, callback=None): """ Wipe the given database. This only affects items inserted remotely; items inserted on the watch (e.g. alarm clock timeline pins) are not removed. :param database: The database to wipe. :type database: .BlobDatabaseID :param callback: A callback to be called on success or fa... |
def invoke(self, headers, body): """ Invokes the soap service """ xml = Service._create_request(headers, body) try: response = self.session.post(self.endpoint, verify=False, data=xml) logging.debug(response.content) except Exception as e: traceback.print_exc() raise WSManException(e) if response.status_code == 200: ret... |
def _determine_auth_mechanism(username, password, delegation): """ if the username contains at '@' sign we will use kerberos if the username contains a '/ we will use ntlm either NTLM or Kerberos. In fact its basically always Negotiate. """ if re.match('(.*)@(.+)', username) is not None: if delegation is True: raise Ex... |
is True: return HttpCredSSPAuth(legacy.group(1), legacy.group(2), password) else: return HttpNtlmAuth(legacy.group(1), legacy.group(2), password) #return HttpCredSSPAuth("SERVER2012", "Administrator", password) # attempt NTLM (local account, not domain) - if username is '' then we try anonymous NTLM auth # as if anyone... |
def _create_request(headers, body): """ Create the SOAP 1.2 Envelope An ordered dictionary is required to ensure the same order is reflected in the XML, otherwise the SOAP Body element would appear before the Header element. """ envelope = OrderedDict() for (namespace, alias) in Service.Namespaces.items(): envelope['@x... |
def _parse_response(xml): """ Attempt to parse the SOAP response and return a python object Raise a WSManException if a Fault is found """ try: soap_response = xmltodict.parse(xml, process_namespaces=True, namespaces=Service.Namespaces) except Exception: logging.debug('unable to parse the xml response: %s', xml) raise ... |
def fetch(force=False): """Fetch and extract latest Life-Line version of Fiji is just ImageJ to *~/.bin*. Parameters ---------- force : bool Force overwrite of existing Fiji in *~/.bin*. """ try: # python 2 from urllib2 import urlopen, HTTPError, URLError except ImportError: # python 3 from urllib.request import urlope... |
msg = 'Downloaded %d bytes\r' % fp.tell() sys.stdout.write(msg) except (HTTPError, URLError) as e: print('Error getting fiji: {}'.format(e)) sys.exit(1) try: print('\nExtracting zip') z = ZipFile(fp) z.extractall(BIN_FOLDER) # move to Fiji-VERSION.app to easily check if it exists (upon fijibin upgrade) os.rename(EXTRAC... |
def escapejson_filter(value): """ Escape `value` to prevent </script> and unicode whitespace attacks. If `value` is not a string, JSON-encode it first. """ if isinstance(value, six.string_types): string = value else: string = json.dumps(value, cls=DjangoJSONEncoder) return mark_safe(escapejson(string)) |
def get_mongo_cursor(self, bulk=False): """ Returns Mongo cursor using the class variables :param bulk: bulk writer option :type bulk: boolean :return: mongo collection for which cursor will be created :rtype: mongo colection object """ try: if self.host: if self.port: client = MongoClient(self.host, self.port) else: c... |
def bulk_cursor_execute(self, bulk_cursor): """ Executes the bulk_cursor :param bulk_cursor: Cursor to perform bulk operations :type bulk_cursor: pymongo bulk cursor object :returns: pymongo bulk cursor object (for bulk operations) """ try: result = bulk_cursor.execute() except BulkWriteError as bwe: msg = "bulk_cursor... |
def detect_terminal(_environ=os.environ): """ Detect "terminal" you are using. First, this function checks if you are in tmux, byobu, or screen. If not it uses $COLORTERM [#]_ if defined and fallbacks to $TERM. .. [#] So, if you are in Gnome Terminal you have "gnome-terminal" instead of "xterm-color"". """ if _environ.... |
def get_waittime(self): """Return the appropriate time to wait, if we sent too many messages :returns: the time to wait in seconds :rtype: :class:`float` :raises: None """ now = time.time() self.sentmessages.appendleft(now) if len(self.sentmessages) == self.sentmessages.maxlen: # check if the oldes message is older tha... |
def send_raw(self, string): """Send raw string to the server. The string will be padded with appropriate CR LF. If too many messages are sent, this will call :func:`time.sleep` until it is allowed to send messages again. :param string: the raw string to send :type string: :class:`str` :returns: None :raises: :class:`ir... |
def _process_line(self, line): """Process the given line and handle the events :param line: the raw message :type line: :class:`str` :returns: None :rtype: None :raises: None """ m = self._rfc_1459_command_regexp.match(line) prefix = m.group('prefix') tags = self._process_tags(m.group('tags')) source = self._process_pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.