code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# test orientation angles = np.unwrap(np.arctan2(cy, cx)) grad = np.gradient(angles) if np.average(grad) > 0: return cx[::-1], cy[::-1] else: return cx, cy
def counter_clockwise(cx, cy)
Put contour coordinates into counter-clockwise order Parameters ---------- cx, cy: 1d ndarrays The x- and y-coordinates of the contour Returns ------- cx_cc, cy_cc: The x- and y-coordinates of the contour in counter-clockwise orientation.
4.461109
3.902598
1.143113
tslist = BaseSectorList(header) for start in range(0, len(sector_list), header.ts_pairs): end = min(start + header.ts_pairs, len(sector_list)) if _xd: log.debug("ts: %d-%d" % (start, end)) s = Dos33TSSector(header, sector_list, start, end) s.ts_st...
def add_metadata_sectors(self, vtoc, sector_list, header)
Add track/sector list
5.148744
4.688782
1.098098
subject = None last_tagid = None cursor.execute(SQL['get-subject-list']) for s in cursor.fetchall(): tagid, tagname, portal_type, count = s if tagid != last_tagid: # It's a new subject, create a new dict and initialize count if subject: yield...
def _get_subject_list_generator(cursor)
Return all subjects (tags) in the database except "internal" scheme.
4.22263
4.13177
1.021991
key = request.matchdict.get('key', '').lstrip('/') key_map = { 'languages': _get_available_languages_and_count, 'subjects': _get_subject_list, 'featured': _get_featured_links, 'messages': _get_service_state_messages, 'licenses': _get_licenses } with db_c...
def extras(request)
Return a dict with archive metadata for webview.
3.570215
3.381706
1.055744
return_value = None def target(): nonlocal return_value return_value = call(*args, **kwargs) t = Thread(target=target) t.start() t.join(delay) if t.is_alive(): raise RuntimeError("Operation did not complete within time.") return return_value
def timeout(delay, call, *args, **kwargs)
Run a function call for `delay` seconds, and raise a RuntimeError if the operation didn't complete.
2.469022
2.415653
1.022093
prog = _gen_prog_name(name) parser = argparse.ArgumentParser(prog=prog, description=description) parser.add_argument('config_uri', help="Configuration INI file.") parser.add_argument('--config-name', action='store', default='main', ...
def create_parser(name, description=None)
Create an argument parser with the given ``name`` and ``description``. The name is used to make ``cnx-archive-<name>`` program name. This creates and returns a parser with the ``config_uri`` argument declared.
4.760329
4.266664
1.115703
config_filepath = os.path.abspath(args.config_uri) return get_appsettings(config_filepath, name=args.config_name)
def get_app_settings_from_arguments(args)
Parse ``argparse`` style arguments into app settings. Given an ``argparse`` set of arguments as ``args`` parse the arguments to return the application settings. This assumes the parser was created using ``create_parser``.
6.157394
7.547902
0.815776
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: return sock.connect_ex((host, port)) == 0
def check_socket(host, port)
Checks if port is open on host. This is used to check if the Xenon-GRPC server is running.
1.807426
2.019878
0.89482
creds = grpc.ssl_channel_credentials( root_certificates=open(str(crt_file), 'rb').read(), private_key=open(str(key_file), 'rb').read(), certificate_chain=open(str(crt_file), 'rb').read()) address = "{}:{}".format(socket.gethostname(), port) channel = grpc.secure_channel(addres...
def get_secure_channel(crt_file, key_file, port=50051)
Try to connect over a secure channel.
1.840968
1.84689
0.996793
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.bind(('', 0)) return sock.getsockname()[1]
def find_free_port()
Finds a free port.
1.743527
1.712684
1.018009
logger = logging.getLogger('xenon.{}'.format(name)) for line in file: logger.info('[{}] {}'.format(name, line.strip()))
def print_stream(file, name)
Print stream from file to logger.
4.321036
3.909999
1.105125
logger = logging.getLogger('xenon') logger.setLevel(logging.INFO) logger_handler = logging.StreamHandler() logger_handler.setFormatter(logging.Formatter(style='{')) logger_handler.setLevel(getattr(logging, log_level)) logger.addHandler(logger_handler) if port is None: port = f...
def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING')
Start the Xenon GRPC server on the specified port, or, if a service is already running on that port, connect to that. If no port is given, a random port is selected. This means that, by default, every python instance will start its own instance of a xenon-grpc process. :param port: the port number...
2.804589
2.855967
0.98201
response.headerlist.append(('Access-Control-Allow-Origin', '*')) response.headerlist.append( ('Access-Control-Allow-Methods', 'GET, OPTIONS')) response.headerlist.append( ('Access-Control-Allow-Headers', ','.join(DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS)))
def add_cors_headers(request, response)
Add cors headers needed for web app implementation.
2.392297
2.305816
1.037506
if self._trace is None: self._trace = self.load_trace(self.mname) return self._trace
def trace(self)
Initializes the trace data
5.569978
5.19712
1.071743
tname = TraceColumn.find_trace_file(mname) # Initialize empty trace dictionary trace = {} if tname is None: pass elif tname.suffix == ".tdms": # Again load the measurement tdms file. # This might increase memory usage, but it is clea...
def load_trace(mname)
Loads the traces and returns them as a dictionary Currently, only loading traces from tdms files is supported. This forces us to load the full tdms file into memory which takes some time.
8.821412
8.437599
1.045488
mname = pathlib.Path(mname) tname = None if mname.exists(): cand = mname.with_name(mname.name[:-5] + "_traces.tdms") if cand.exists(): tname = cand return tname
def find_trace_file(mname)
Tries to find the traces tdms file name Returns None if no trace file is found.
4.260248
3.495946
1.218625
# cast name if autocast enabled name_secret = name.lower() if autocast_name else name name_env = name.upper() if autocast_name else name # initiallize value value = None # try to read from secret file try: with open(os.path.join(secrets_dir, name_secret), 'r') as secret_file:...
def get_docker_secret(name, default=None, cast_to=str, autocast_name=True, getenv=True, safe=True, secrets_dir=os.path.join(root, 'var', 'run', 'secrets'))
This function fetches a docker secret :param name: the name of the docker secret :param default: the default value if no secret found :param cast_to: casts the value to the given type :param autocast_name: whether the name should be lowercase for secrets and upper case for environment :param getenv...
3.060643
2.885814
1.060582
if isinstance(arg, np.ndarray): self.ahash.update(arg.view(np.uint8)) elif isinstance(arg, list): [self._update_hash(a) for a in arg] else: self.ahash.update(str(arg).encode('utf-8'))
def _update_hash(self, arg)
Takes an argument and updates the hash. The argument can be an np.array, string, or list of things that are convertable to strings.
2.408027
2.310729
1.042107
del Cache._keys for k in list(Cache._cache.keys()): it = Cache._cache.pop(k) del it del Cache._cache Cache._keys = [] Cache._cache = {} gc.collect()
def clear_cache()
Remove all cached objects
4.617043
4.855474
0.950894
if not self.sector_is_valid(sector): raise ByteNotInFile166("Sector %d out of range" % sector) pos = sector * self.sector_size + self.header_offset size = self.sector_size return pos, size
def get_pos(self, sector)
Get index (into the raw data of the disk image) of start of sector This base class method assumes the sectors are one after another, in order starting from the beginning of the raw data.
5.538435
5.620302
0.985434
pos, size = self.header.get_pos(start) if end is None: end = start while start < end: start += 1 _, more = self.header.get_pos(start) size += more return slice(pos, pos + size)
def get_sector_slice(self, start, end=None)
Get contiguous sectors :param start: first sector number to read (note: numbering starts from 1) :param end: last sector number to read :returns: bytes
4.202043
5.237563
0.80229
s = self.get_sector_slice(start, end) return self.bytes[s], self.style[s]
def get_sectors(self, start, end=None)
Get contiguous sectors :param start: first sector number to read (note: numbering starts from 1) :param end: last sector number to read :returns: bytes
8.78527
11.661553
0.753353
state = self.begin_transaction() try: directory = self.directory_class(self.header) self.get_directory(directory) dirent = directory.add_dirent(filename, filetype) data = to_numpy(data) sector_list = self.build_sectors(data) ...
def write_file(self, filename, filetype, data)
Write data to a file on disk This throws various exceptions on failures, for instance if there is not enough space on disk or a free entry is not available in the catalog.
5.199784
4.931902
1.054316
if scale == "linear": b = a elif scale == "log": with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") b = np.log(a) if len(w): # Tell the user that the log-transformation issue...
def _apply_scale(self, a, scale, feat)
Helper function for transforming an aray to log-scale Parameters ---------- a: np.ndarray Input array scale: If set to "log", take the logarithm of `a`; if set to "linear" return `a` unchanged. Returns ------- b: np.ndarray ...
3.602584
3.196214
1.127141
mycols = [] for col in dfn.feature_names: if col in self: mycols.append(col) mycols.sort() return mycols
def features(self)
All available features
5.926901
5.528533
1.072057
if downsample < 0: raise ValueError("`downsample` must be zero or positive!") downsample = int(downsample) xax = xax.lower() yax = yax.lower() # Get data x = self[xax][self.filter.all] y = self[yax][self.filter.all] # Apply scale (n...
def get_downsampled_scatter(self, xax="area_um", yax="deform", downsample=0, xscale="linear", yscale="linear")
Downsampling by removing points at dense locations Parameters ---------- xax: str Identifier for x axis (e.g. "area_um", "aspect", "deform") yax: str Identifier for y axis downsample: int Number of points to draw in the down-sampled plot. ...
3.647806
4.109167
0.887724
xax = xax.lower() yax = yax.lower() kde_type = kde_type.lower() if kde_type not in kde_methods.methods: raise ValueError("Not a valid kde type: {}!".format(kde_type)) # Get data x = self[xax][self.filter.all] y = self[yax][self.filter.all] ...
def get_kde_contour(self, xax="area_um", yax="deform", xacc=None, yacc=None, kde_type="histogram", kde_kwargs={}, xscale="linear", yscale="linear")
Evaluate the kernel density estimate for contour plots Parameters ---------- xax: str Identifier for X axis (e.g. "area_um", "aspect", "deform") yax: str Identifier for Y axis xacc: float Contour accuracy in x direction yacc: float ...
2.438503
2.564186
0.950985
xax = xax.lower() yax = yax.lower() kde_type = kde_type.lower() if kde_type not in kde_methods.methods: raise ValueError("Not a valid kde type: {}!".format(kde_type)) # Get data x = self[xax][self.filter.all] y = self[yax][self.filter.all] ...
def get_kde_scatter(self, xax="area_um", yax="deform", positions=None, kde_type="histogram", kde_kwargs={}, xscale="linear", yscale="linear")
Evaluate the kernel density estimate for scatter plots Parameters ---------- xax: str Identifier for X axis (e.g. "area_um", "aspect", "deform") yax: str Identifier for Y axis positions: list of two 1d ndarrays or ndarray of shape (2, N) The p...
2.379478
2.41657
0.984651
if not isinstance(filt, (PolygonFilter, int, float)): msg = "`filt` must be a number or instance of PolygonFilter!" raise ValueError(msg) if isinstance(filt, PolygonFilter): uid = filt.unique_id else: uid = int(filt) # append item...
def polygon_filter_add(self, filt)
Associate a Polygon Filter with this instance Parameters ---------- filt: int or instance of `PolygonFilter` The polygon filter to add
5.142072
5.180028
0.992672
if not isinstance(filt, (PolygonFilter, int, float)): msg = "`filt` must be a number or instance of PolygonFilter!" raise ValueError(msg) if isinstance(filt, PolygonFilter): uid = filt.unique_id else: uid = int(filt) # remove item...
def polygon_filter_rm(self, filt)
Remove a polygon filter from this instance Parameters ---------- filt: int or instance of `PolygonFilter` The polygon filter to remove
4.8927
4.934278
0.991574
if isinstance(data, dict): return fmt_dict.RTDC_Dict(data, identifier=identifier) elif isinstance(data, (str_types)) or isinstance(data, pathlib.Path): return load_file(data, identifier=identifier) elif isinstance(data, RTDCBase): return fmt_hierarchy.RTDC_Hierarchy(data, identi...
def new_dataset(data, identifier=None)
Initialize a new RT-DC dataset Parameters ---------- data: can be one of the following: - dict - .tdms file - .rtdc file - subclass of `RTDCBase` (will create a hierarchy child) identifier: str A unique identifier for this dataset. If set to `N...
4.226981
3.234507
1.306839
hits = {} initial_timestamp = None def clean_timestamp(v): return ' '.join(v).strip('[]') for line in log: data = line.split() if not initial_timestamp: initial_timestamp = clean_timestamp(data[3:5]) match = url_pattern.match(data[6]) if match: ...
def parse_log(log, url_pattern)
Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log.
3.187473
2.83258
1.12529
parser = create_parser('hits_counter', description=__doc__) parser.add_argument('--hostname', default='cnx.org', help="hostname of the site (default: cnx.org)") parser.add_argument('--log-format', default=LOG_FORMAT_GZ, choices=LOG_FORMATS, ...
def main(argv=None)
Count the hits from logfile.
3.91433
3.650447
1.072288
if isinstance(value, str_types): value = value.lower() if value == "false": value = False elif value == "true": value = True elif value: value = bool(float(value)) else: raise ValueError("empty string") else: va...
def fbool(value)
boolean
2.465976
2.518621
0.979098
if isinstance(value, str_types): # strings might have been saved wrongly as booleans value = value.lower() if value == "false": value = 0 elif value == "true": value = 1 elif value: value = int(float(value)) else: r...
def fint(value)
integer
3.264024
3.232021
1.009902
outlist = [] if not isinstance(alist, (list, tuple)): # we have a string (comma-separated integers) alist = alist.strip().strip("[] ").split(",") for it in alist: if it: outlist.append(fint(it)) return outlist
def fintlist(alist)
A list of integers
4.123549
4.145103
0.9948
path = pathlib.Path(path) ds = self.rtdc_ds # Make sure that path ends with .avi if path.suffix != ".avi": path = path.with_name(path.name + ".avi") # Check if file already exist if not override and path.exists(): raise OSError("File alrea...
def avi(self, path, filtered=True, override=False)
Exports filtered event images to an avi file Parameters ---------- path: str Path to a .tsv file. The ending .tsv is added automatically. filtered: bool If set to `True`, only the filtered data (index in ds._filter) are used. override: bool ...
3.693008
3.504365
1.053831
features = [c.lower() for c in features] ds = self.rtdc_ds path = pathlib.Path(path) # Make sure that path ends with .fcs if path.suffix != ".fcs": path = path.with_name(path.name + ".fcs") # Check if file already exist if not override and pa...
def fcs(self, path, features, filtered=True, override=False)
Export the data of an RT-DC dataset to an .fcs file Parameters ---------- mm: instance of dclab.RTDCBase The dataset that will be exported. path: str Path to a .tsv file. The ending .tsv is added automatically. features: list of str The featur...
3.64727
3.012133
1.21086
features = [c.lower() for c in features] path = pathlib.Path(path) ds = self.rtdc_ds # Make sure that path ends with .tsv if path.suffix != ".tsv": path = path.with_name(path.name + ".tsv") # Check if file already exist if not override and pat...
def tsv(self, path, features, filtered=True, override=False)
Export the data of the current instance to a .tsv file Parameters ---------- path: str Path to a .tsv file. The ending .tsv is added automatically. features: list of str The features in the resulting .tsv file. These are strings that are defined in `d...
3.048272
2.745845
1.11014
hasher = hashlib.md5() fname = pathlib.Path(fname) with fname.open('rb') as fd: buf = fd.read(blocksize) ii = 0 while len(buf) > 0: hasher.update(buf) buf = fd.read(blocksize) ii += 1 if count and ii == count: break...
def hashfile(fname, blocksize=65536, count=0)
Compute md5 hex-hash of a file Parameters ---------- fname: str path to the file blocksize: int block size in bytes read from the file (set to `0` to hash the entire file) count: int number of blocks read from the file
1.869669
2.097491
0.891384
if isinstance(obj, str_types): return obj.encode("utf-8") elif isinstance(obj, pathlib.Path): return obj2str(str(obj)) elif isinstance(obj, (bool, int, float)): return str(obj).encode("utf-8") elif obj is None: return b"none" elif isinstance(obj, np.ndarray): ...
def obj2str(obj)
String representation of an object for hashing
2.14616
2.171301
0.988421
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc' config_dir.mkdir(parents=True, exist_ok=True) key_prefix = gethostname() crt_file = config_dir / ('%s.crt' % key_prefix) key_file = config_dir / ('%s.key' % key_prefix) if crt_file.exists() and key_file.exists(): retu...
def create_self_signed_cert()
Creates a self-signed certificate key pair.
1.894161
1.876872
1.009211
path = pathlib.Path(path) if path.suffix == ".tdms": dirn = path.parent mx = path.name.split("_")[0] elif path.is_dir(): dirn = path mx = "" else: dirn = path.parent mx = "" project = "" if mx: # check para.ini para = dirn / (...
def get_project_name_from_path(path, append_mx=False)
Get the project name from a path. For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or without the ".tdms" file, this will return always "HLC12398". Parameters ---------- path: str path to tdms file append_mx: ...
3.785557
3.059931
1.237138
path = pathlib.Path(directory).resolve() # get all tdms files tdmslist = [r for r in path.rglob("*.tdms") if r.is_file()] # exclude traces files tdmslist = [r for r in tdmslist if not r.name.endswith("_traces.tdms")] return sorted(tdmslist)
def get_tdms_files(directory)
Recursively find projects based on '.tdms' file endings Searches the `directory` recursively and return a sorted list of all found '.tdms' project files, except fluorescence data trace files which end with `_traces.tdms`.
3.009286
2.601042
1.156954
tdms_file = TdmsFile(str(tdms_filename)) # time is always there table = "Cell Track" # Edit naming.dclab2tdms to add features for arg in naming.tdms2dclab: try: data = tdms_file.object(table, arg).data except KeyError: ...
def _init_data_with_tdms(self, tdms_filename)
Initializes the current RT-DC dataset with a tdms file.
5.702368
5.687759
1.002568
if self._hash is None: # Only hash _camera.ini and _para.ini fsh = [self.path.with_name(self._mid + "_camera.ini"), self.path.with_name(self._mid + "_para.ini")] tohash = [hashfile(f) for f in fsh] tohash.append(self.path.name) ...
def hash(self)
Hash value based on file name and .ini file content
5.876041
5.495102
1.069323
# In case of regular RTDC, the first contour is # missing. In case of fRTDC, it is there, so we # might have an offset. We find out if the first # contour frame is missing by comparing it to # the "frame" column of the rtdc dataset. fref = self._contour_data.get_...
def determine_offset(self)
Determines the offset of the contours w.r.t. other data columns Notes ----- - the "frame" column of `rtdc_dataset` is compared to the first contour in the contour text file to determine an offset by one event - modifies the property `event_offset` and sets `_initial...
6.939415
5.483592
1.265487
cont_id = rtdc_dataset.path.stem cands = [c.name for c in rtdc_dataset._fdir.rglob("*_contours.txt")] cands = sorted(cands) # Search for perfect matches, e.g. # - M1_0.240000ul_s.tdms # - M1_0.240000ul_s_contours.txt for c1 in cands: if c1.sta...
def find_contour_file(rtdc_dataset)
Tries to find a contour file that belongs to an RTDC dataset Returns None if no contour file is found.
3.759444
3.897283
0.964632
with self.filename.open() as fd: data = fd.read() ident = "Contour in frame" self._data = data.split(ident)[1:] self._initialized = True
def _index_file(self)
Open and index the contour file This function populates the internal list of contours as strings which will be available as `self.data`.
12.669246
9.354466
1.354353
cont = self.data[idx] frame = int(cont.strip().split(" ", 1)[0]) return frame
def get_frame(self, idx)
Return the frame number of a contour
7.178923
5.493518
1.306799
if medium.lower() not in ["cellcarrier", "cellcarrier b", "water"]: raise ValueError("Invalid medium: {}".format(medium)) # convert flow_rate from µl/s to m³/s # convert channel_width from µm to m term1 = 1.1856 * 6 * flow_rate * 1e-9 / (channel_width * 1e-6)**3 * 2 / 3 if medium == "...
def get_viscosity(medium="CellCarrier", channel_width=20.0, flow_rate=0.16, temperature=23.0)
Returns the viscosity for RT-DC-specific media Parameters ---------- medium: str The medium to compute the viscosity for. One of ["CellCarrier", "CellCarrier B", "water"]. channel_width: float The channel width in µm flow_rate: float Flow rate in µl/s temperature...
3.598547
3.267443
1.101334
if methods is None: cls = list(Statistics.available_methods.keys()) # sort the features in a usable way avm = Statistics.available_methods me1 = [m for m in cls if not avm[m].req_feature] me2 = [m for m in cls if avm[m].req_feature] methods = me1 + me2 if fe...
def get_statistics(ds, methods=None, features=None)
Compute statistics for an RT-DC dataset Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset for which to compute the statistics. methods: list of str or None The methods wih which to compute the statistics. The list of available methods is given with `dclab...
4.373455
3.908429
1.11898
# size n = data.shape[0] # interquartile range iqr = np.percentile(data, 75)-np.percentile(data, 25) # Freedman–Diaconis bin_size = 2 * iqr / n**(1/3) if bin_size == 0: return np.nan # Add bin_size/2, because we want the center of the bin and # not the left corner of t...
def mode(data)
Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freedman–Diaconis rule. Parameters ---------- data: 1d ndarra...
3.487162
3.31257
1.052706
if "ds" not in kwargs: raise ValueError("Keyword argument 'ds' missing.") ds = kwargs["ds"] if self.req_feature: if "feature" not in kwargs: raise ValueError("Keyword argument 'feature' missing.") return self.get_feature(ds, kwargs["...
def _get_data(self, kwargs)
Convenience wrapper to get statistics data
3.390494
3.398808
0.997554
if ds.config["filtering"]["enable filters"]: x = ds[feat][ds._filter] else: x = ds[feat] bad = np.isnan(x) | np.isinf(x) xout = x[~bad] return xout
def get_feature(self, ds, feat)
Return filtered feature data The features are filtered according to the user-defined filters, using the information in `ds._filter`. In addition, all `nan` and `inf` values are purged. Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset contain...
6.265802
5.076488
1.234279
if self.exc_info: try: six.reraise(*self.exc_info) except Exception as e: return e
def get_exception(self)
Retrieve the exception
3.849179
3.533777
1.089253
serverless_cnt = len(list(filter(lambda x: x._serverless_type, self._data['resources']))) if serverless_cnt > 0: return False return True
def check_global_valid(self)
Makes sure there aren't any SAM resources in a template that will be used in a CloudFormation StackSet :return: bool
7.648899
6.756132
1.132142
cf = self.cf_client try: resp = cf.describe_stacks(StackName=stack_name) if len(resp["Stacks"]) != 1: return False # When you run CreateChangeSet on a a stack that does not exist, # CloudFormation will create a stack and set it's ...
def has_stack(self, stack_name)
Checks if a CloudFormation stack with given name exists :param stack_name: Name or ID of the stack :return: True if stack exists. False otherwise
4.425387
4.468144
0.990431
key = args if len(args) > 1 else args[0] return key in cls._instances
def has_key(cls, *args)
Check whether flyweight object with specified key has already been created. Returns: bool: True if already created, False if not
4.539666
6.585397
0.689353
key = args if len(args) > 1 else args[0] return cls._instances.get(key, None)
def from_key(cls, *args)
Return flyweight object with specified key, if it has already been created. Returns: cls or None: Previously constructed flyweight object with given key or None if key not found
3.544706
4.556157
0.778003
data["name"] = name if not ("timestamp" in data): data["timestamp"] = datetime.utcnow() try: self.client.index( index=self.get_index(), doc_type=self.doc_type, id=None, body=data ) ...
def write(self, name, **data)
Write the metric to elasticsearch Args: name (str): The name of the metric to write data (dict): Additional data to store with the metric
4.25209
3.604948
1.179515
actions = [] index = self.get_index() for metric in metrics: actions.append({'index': {'_index': index, '_type': self.doc_type}}) actions.append(metric) try: self.client.bulk(actions) except TransportError as exc: logger.wa...
def bulk_write(self, metrics)
Write multiple metrics to elasticsearch in one request Args: metrics (list): data with mappings to send to elasticsearch
3.156269
3.383079
0.932958
# This method is based on a pull request by Maik Herbig. ret_avg = "avg" in ret_data ret_std = "sd" in ret_data if ret_avg + ret_std == 0: raise ValueError("No valid metrices selected!") if isinstance(mask, np.ndarray) and len(mask.shape) == 2: # We have a single image ...
def get_bright(mask, image, ret_data="avg,sd")
Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool The mask values, True where the event is located in `i...
3.123187
3.139044
0.994948
settings = get_current_registry().settings memcache_servers = settings['memcache-servers'].split() if not memcache_servers: # memcache is not enabled, do a database search directly return database_search(query, query_type) # sort query params and create a key for the search sea...
def search(query, query_type, nocache=False)
Search archive contents. Look up search results in cache, if not in cache, do a database search and cache the result
3.770258
3.738872
1.008395
cols = {} for inst in AncillaryFeature.features: if inst.is_available(rtdc_ds): cols[inst.feature_name] = inst return cols
def available_features(rtdc_ds)
Determine available features for an RT-DC dataset Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to check availability for Returns ------- features: dict Dictionary with feature names as keys and instances of `Ancilla...
5.983231
5.622052
1.064243
data = self.method(rtdc_ds) dsize = len(rtdc_ds) - len(data) if dsize > 0: msg = "Growing feature {} in {} by {} to match event number!" warnings.warn(msg.format(self.feature_name, rtdc_ds, abs(dsize)), BadFeatureSizeWarning) ...
def compute(self, rtdc_ds)
Compute the feature with self.method Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to compute the feature for Returns ------- feature: array- or list-like The computed data feature (read-only).
2.329678
2.306955
1.00985
feats = [] for ft in AncillaryFeature.features: if ft.feature_name == feature_name: feats.append(ft) return feats
def get_instances(feature_name)
Return all all instances that compute `feature_name`
4.878041
4.557274
1.070386
hasher = hashlib.md5() # data columns for col in self.req_features: hasher.update(obj2str(rtdc_ds[col])) # config keys for sec, keys in self.req_config: for key in keys: val = rtdc_ds.config[sec][key] data = "{}:{}=...
def hash(self, rtdc_ds)
Used for identifying an ancillary computation The data columns and the used configuration keys/values are hashed.
3.613135
3.15523
1.145126
# Check config keys for item in self.req_config: section, keys = item if section not in rtdc_ds.config: if verbose: print("{} not in config".format(section)) return False else: for key in key...
def is_available(self, rtdc_ds, verbose=False)
Check whether the feature is available Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to check availability for Returns ------- available: bool `True`, if feature can be computed with `compute` Notes ----- ...
3.471347
3.338908
1.039665
if self._producer: return self._producer self._producer = KafkaProducer( bootstrap_servers=self.hosts, value_serializer=lambda v: self._serializer_class().dumps(v).encode('utf-8'), **self._kwargs ) return self._producer
def producer(self)
:raises: kafka.errors.NoBrokersAvailable if the connection is broken
3.149499
2.738195
1.15021
data["name"] = name if not ("timestamp" in data): data["timestamp"] = datetime.utcnow() try: self.producer.send(topic=self.topic, value=data) self.producer.flush() except (KafkaTimeoutError, NoBrokersAvailable) as exc: logger.war...
def write(self, name, **data)
Write the metric to kafka Args: name (str): The name of the metric to write data (dict): Additional data to store with the metric
4.639311
4.092985
1.133479
try: for metric in metrics: self.producer.send(self.topic, metric) self.producer.flush() except (KafkaTimeoutError, NoBrokersAvailable) as exc: logger.warning('bulk_write metrics %r failure %r', metrics, exc)
def bulk_write(self, metrics)
Write multiple metrics to kafka in one request Args: metrics (list):
4.113349
4.070994
1.010404
if not opts.noheadings: text = format_heading(1, '%s module' % module) else: text = '' # text += format_heading(2, ':mod:`%s` Module' % module) text += format_directive(module, package) write_file(makename(package, module), text, opts)
def create_module_file(package, module, opts)
Build the text of the file and write the file.
4.67275
4.512414
1.035532
text = format_heading(1, '%s' % makename(master_package, subroot)) if opts.modulefirst: text += format_directive(subroot, master_package) text += '\n' # build a list of directories that are szvpackages (contain an INITPY file) subs = [sub for sub in subs if path.isfile(path.join(r...
def create_package_file(root, master_package, subroot, py_files, opts, subs)
Build the text of the file and write the file.
2.819905
2.777692
1.015197
# skip it if there is nothing (or just \n or \r\n) in the file if path.getsize(module) <= 2: return True # skip if it has a "private" name and this is selected filename = path.basename(module) if filename != '__init__.py' and filename.startswith('_') and \ not opts.includeprivate...
def shall_skip(module, opts)
Check if we want to skip this module.
6.378743
6.28868
1.014321
"Use threads and a subproc to bodge a timeout on top of filesystem access" global safe_stat_process if cmd is None: cmd = ['/usr/bin/stat'] cmd.append(path) def target(): global safe_stat_process logger.debug('Stat thread started') safe_stat_process = subprocess.Po...
def safe_stat(path, timeout=1, cmd=None)
Use threads and a subproc to bodge a timeout on top of filesystem access
3.769918
2.599077
1.450484
names = [] for p in PolygonFilter.instances: names.append(p.name) return names
def get_polygon_filter_names()
Get the names of all polygon filters in the order of creation
4.106366
3.943352
1.041339
if self.axes is None: raise PolygonFilterError("`axes` parm not set.") if self.points is None: raise PolygonFilterError("`points` parm not set.") self.points = np.array(self.points) if self.points.shape[1] != 2: raise PolygonFilterError("data ...
def _check_data(self)
Check if the data given is valid
3.126268
3.053356
1.02388
filename = pathlib.Path(filename) with filename.open() as fd: data = fd.readlines() # Get the strings that correspond to self.fileid bool_head = [l.strip().startswith("[") for l in data] int_head = np.squeeze(np.where(bool_head)) int_head = np.atlea...
def _load(self, filename)
Import all filters from a text file
3.550528
3.491216
1.016989
assert isinstance(unique_id, int), "unique_id must be an integer" if PolygonFilter.instace_exists(unique_id): newid = max(PolygonFilter._instance_counter, unique_id+1) msg = "PolygonFilter with unique_id '{}' exists.".format(unique_id) msg += " Using new uni...
def _set_unique_id(self, unique_id)
Define a unique id
3.713424
3.728727
0.995896
if invert: inverted = not self.inverted else: inverted = self.inverted return PolygonFilter(axes=self.axes, points=self.points, name=self.name, inverted=inverted)
def copy(self, invert=False)
Return a copy of the current instance Parameters ---------- invert: bool The copy will be inverted w.r.t. the original
4.911232
5.434244
0.903756
f = np.ones(datax.shape, dtype=bool) for i, p in enumerate(zip(datax, datay)): f[i] = PolygonFilter.point_in_poly(p, self.points) if self.inverted: np.invert(f, f) return f
def filter(self, datax, datay)
Filter a set of datax and datay according to `self.points`
4.319886
3.9039
1.106557
for instance in PolygonFilter.instances: if instance.unique_id == unique_id: return instance # if this does not work: raise KeyError("PolygonFilter with unique_id {} not found.". format(unique_id))
def get_instance_from_id(unique_id)
Get an instance of the `PolygonFilter` using a unique id
5.429851
3.686646
1.472843
plist = [] fid = 0 while True: try: p = PolygonFilter(filename=path, fileid=fid) plist.append(p) fid += 1 except IndexError: break return plist
def import_all(path)
Import all polygons from a .poly file. Returns a list of the imported polygon filters
5.220327
4.122139
1.266412
poly = np.array(poly) n = poly.shape[0] inside = False x, y = p # Coarse bounding box exclusion: if (x <= poly[:, 0].max() and x > poly[:, 0].min() and y <= poly[:, 1].max() and y > poly[:, 1].min()): # The point is within the coarse ...
def point_in_poly(p, poly)
Determine whether a point is within a polygon area Uses the ray casting algorithm. Parameters ---------- p: float Coordinates of the point poly: array_like of shape (N, 2) Polygon (`PolygonFilter.points`) Returns ------- inside: ...
4.187777
4.204339
0.996061
for p in PolygonFilter.instances: if p.unique_id == unique_id: PolygonFilter.instances.remove(p)
def remove(unique_id)
Remove a polygon filter from `PolygonFilter.instances`
4.563419
2.091697
2.181682
if is_file_obj(polyfile): fobj = polyfile else: fobj = pathlib.Path(polyfile).open("a") # Who the hell would use more then 10 million polygons or # polygon points? -> 08d (easier if other people want to import) data2write = [] data2write....
def save(self, polyfile, ret_fobj=False)
Save all data to a text file (appends data if file exists). Polyfile can be either a path to a file or a file object that was opened with the write "w" parameter. By using the file object, multiple instances of this class can write their data. If `ret_fobj` is `True`, then the file obj...
3.886365
3.973765
0.978006
nump = len(PolygonFilter.instances) if nump == 0: raise PolygonFilterError("There are not polygon filters to save.") for p in PolygonFilter.instances: # we return the ret_obj, so we don't need to open and # close the file multiple times. p...
def save_all(polyfile)
Save all polygon filters
7.745193
7.018682
1.103511
hash = request.matchdict['hash'] # Do the file lookup with db_connect() as db_connection: with db_connection.cursor() as cursor: args = dict(hash=hash) cursor.execute(SQL['get-resource'], args) try: mimetype, file = cursor.fetchone() ...
def get_resource(request)
Retrieve a file's data.
3.698659
3.646647
1.014263
style_bits = 0 if user: style_bits |= (user & user_bit_mask) if diff: style_bits |= diff_bit_mask if match: style_bits |= match_bit_mask if comment: style_bits |= comment_bit_mask if data: style_bits |= (data_style & user_bit_mask) if selected: ...
def get_style_bits(match=False, comment=False, selected=False, data=False, diff=False, user=0)
Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region data: labeled in the disassembler as a data region (i.e. not disassembled)
2.007274
2.377215
0.844381
bits = get_style_bits(**kwargs) if 'user' in kwargs and kwargs['user']: bits |= user_bit_mask else: bits &= (0xff ^ user_bit_mask) return 0xff ^ bits
def get_style_mask(**kwargs)
Get the bit mask that, when anded with data, will turn off the selected bits
4.913677
4.624039
1.062638
if self.data.base is None: if self.is_indexed: basearray = self.data.np_data else: basearray = self.data return 0, len(basearray) return int(self.data_start - self.base_start), int(self.data_end - self.base_start)
def byte_bounds_offset(self)
Return start and end offsets of this segment's data into the base array's data. This ignores the byte order index. Arrays using the byte order index will have the entire base array's raw data.
4.263052
3.542703
1.203333
if self.is_indexed: return int(self.order[i]) if self.data.base is None: return int(i) return int(self.data_start - self.base_start + i)
def get_raw_index(self, i)
Get index into base array's raw data, given the index into this segment
6.438252
5.758432
1.118056
if self.is_indexed: return np.copy(self.order[i]) if self.data.base is None: i = 0 else: i = self.get_raw_index(0) return np.arange(i, i + len(self), dtype=np.uint32)
def get_indexes_from_base(self)
Get array of indexes from the base array, as if this raw data were indexed.
5.003529
4.269783
1.171846
if self._reverse_index_mapping is None: if self.is_indexed: # Initialize array to out of range r = np.zeros(self.base_length, dtype=np.int32) - 1 r[self.order] = np.arange(len(self.order), dtype=np.int32) elif self.data.base is Non...
def reverse_index_mapping(self)
Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array
2.724069
2.707626
1.006073
r = self.reverse_index_mapping[base_index] if r < 0: raise IndexError("index %d not mapped in this segment" % base_index) return r
def get_reverse_index(self, base_index)
Get index into this segment's data given the index into the base data Raises IndexError if the base index doesn't map to anything in this segment's data
4.940976
3.995924
1.236504
if not self.can_resize: raise ValueError("Segment %s can't be resized" % str(self)) # only makes sense for the container (outermost) object if not self.rawdata.is_base: raise ValueError("Only container segments can be resized") origsize = len(self) ...
def resize(self, newsize, zeros=True)
Resize the data arrays. This can only be performed on the container segment. Child segments must adjust their rawdata to point to the correct place. Since segments don't keep references to other segments, it is the user's responsibility to update any child segments that point to this ...
4.958372
4.493061
1.103562
if hasattr(self, 'start_addr'): self.origin = self.start_addr log.debug(f"moving start_addr to origin: {self.start_addr}") delattr(self, 'start_addr')
def restore_renamed_serializable_attributes(self)
Hook for the future if attributes have been renamed. The old attribute names will have been restored in the __dict__.update in __setstate__, so this routine should move attribute values to their new names.
4.510538
4.142281
1.088902
start, end = self._rawdata_bounds r = rawdata[start:end] delattr(self, '_rawdata_bounds') try: if self._order_list: order = to_numpy_list(self._order_list) r = r.get_indexed(order) delattr(self, '_order_list') e...
def reconstruct_raw(self, rawdata)
Reconstruct the pointers to the parent data arrays Each segment is a view into the primary segment's data, so those pointers and the order must be restored in the child segments.
4.639773
4.779675
0.97073
start, end = other.byte_bounds_offset() r = self.rawdata[start:end] if other.rawdata.is_indexed: r = r.get_indexed[other.order] return r
def get_parallel_raw_data(self, other)
Get the raw data that is similar to the specified other segment
9.71117
10.019933
0.969185