code
stringlengths
1
18.2k
def update(self, request, id): """ Read the GeoJSON feature from the request body and update the corresponding object in the database. """ if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) session = self.Session() obj = session.query(self.mapped_class).get(id) if obj is None: return HTTPNotF...
def delete(self, request, id): """ Remove the targeted feature from the database """ if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) session = self.Session() obj = session.query(self.mapped_class).get(id) if obj is None: return HTTPNotFound() if self.before_delete is not None: self.before_...
def store(self, text, tier): """ Writes text to the underlying Store mapped at tier. If the store doesn't exists, yet, it creates it :param text: the text to write :param tier: the tier used to identify the store :return: """ store = self._stores.get(tier, None) if not store: store = AutoSplittingFile(self._dir, self._...
def uuid_from_kronos_time(time, _type=UUIDType.RANDOM): """ Generate a UUID with the specified time. If `lowest` is true, return the lexicographically first UUID for the specified time. """ return timeuuid_from_time(int(time) + UUID_TIME_OFFSET, type=_type)
def by(self, technology): """ Get the plugins registered in PedalPi by technology :param PluginTechnology technology: PluginTechnology identifier """ if technology == PluginTechnology.LV2 \ or str(technology).upper() == PluginTechnology.LV2.value.upper(): return self.lv2_builder.all else: return []
def reload_lv2_plugins_data(self): """ Search for LV2 audio plugins in the system and extract the metadata needed by pluginsmanager to generate audio plugins. """ plugins_data = self.lv2_builder.lv2_plugins_data() self._dao.save(plugins_data)
def invert(self): ''' Invert by swapping each value with its key. Returns ------- MultiDict Inverted multi-dict. Examples -------- >>> MultiDict({1: {1}, 2: {1,2,3}}, 4: {}).invert() MultiDict({1: {1,2}, 2: {2}, 3: {2}}) ''' result = defaultdict(set) for k, val in self.items(): result[val].add(k) return MultiDict(dict(...
def _send_with_auth(values, secret_key, url): """Send dictionary of JSON serializable `values` as a POST body to `url` along with `auth_token` that's generated from `secret_key` and `values` scheduler.auth.create_token expects a JSON serializable payload, so we send a dictionary. On the receiving end of the POST reques...
req = urllib2.Request(url, data) response = urllib2.urlopen(req) return json.loads(response.read())
def schedule(code, interval, secret_key=None, url=None): """Schedule a string of `code` to be executed every `interval` Specificying an `interval` of 0 indicates the event should only be run one time and will not be rescheduled. """ if not secret_key: secret_key = default_key() if not url: url = default_url() url = '%s...
def cancel(task_id, secret_key=None, url=None): """Cancel scheduled task with `task_id`""" if not secret_key: secret_key = default_key() if not url: url = default_url() url = '%s/cancel' % url values = { 'id': task_id, } return _send_with_auth(values, secret_key, url)
def read_multireg_file(f, title=None): """ Some REG files have multiple "sections" with different data. This parses each chunk out of such a file (e.g. LCDIAG.REG) """ f.seek(0x26) nparts = struct.unpack('<H', f.read(2))[0] foff = 0x2D if title is None: data = [] for _ in range(nparts): d = read_reg_file(f, foff) data....
def read_reg_file(f, foff=0x2D): """ Given a file handle for an old-style Agilent *.REG file, this will parse that file into a dictonary of key/value pairs (including any tables that are in the *.REG file, which will be parsed into lists of lists). """ # convenience function for reading in data def rd(st): return struc...
= struct.unpack('<HIII21sI', d) names[cd[5]] = cd[4].decode('iso8859').strip('\x00') # except: # pass elif r[1] == 32769 or r[1] == 32771: # b'0180' or b'0380' names[r[4]] = d[:-1].decode('iso8859') elif r[1] == 32774: # b'0680' # this is a string that is referenced elsewhere (in a table) names[r[4]] = d[2:-1].decode('...
= names.get(struct.unpack('<I', d[35:39])[0], '') elif r[1] == 1793: # b'0107' # this is a table of values nrow = struct.unpack('<H', d[4:6])[0] ncol = struct.unpack('<H', d[16:18])[0] if ncol != 0: cols = [struct.unpack('<16sHHHHHI', d[20 + 30 * i:50 + 30 * i]) for i in range(ncol)] colnames = [c[0].split(b'\x00')[0]....
p in enumerate(rawrow): if cols[j][3] == 3: row.append(names.get(p, str(p))) else: row.append(p) tab.append(row) data[names[r[4]]] = [colnames, tab] elif r[1] == 1281 or r[1] == 1283: # b'0105' or b'0305' fm = '<HHBIIhIdII12shIddQQB8sII12shIddQQB8s' m = struct.unpack(fm, d) nrecs = m[4] # number of points in table # x_...
# #print(r[1], len(d), binascii.hexlify(d)) # pass # elif r[1] == 512: # b'0002' # # either points to two null pointers or two other pointers # # (indicates start of linked list?) # print(r[1], len(d), binascii.hexlify(d)) # elif r[1] == 769 or r[1] == 772: # b'0103' or b'0403' # # points to 2nd, 3rd & 4th records (two...
def get(cls, session, team_id): """Return a specific team. Args: session (requests.sessions.Session): Authenticated session. team_id (int): The ID of the team to get. Returns: helpscout.models.Person: A person singleton representing the team, if existing. Otherwise ``None``. """ return cls( '/teams/%d.json' % team_id, ...
def get_members(cls, session, team_or_id): """List the members for the team. Args: team_or_id (helpscout.models.Person or int): Team or the ID of the team to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Users): Users iterator. """ if isinstance(team_or_id, Person): team_or_id = team_or_id...
def t_to_min(x): """ Convert XML 'xs: duration type' to decimal minutes, e.g.: t_to_min('PT1H2M30S') == 62.5 """ g = re.match('PT(?:(.*)H)?(?:(.*)M)?(?:(.*)S)?', x).groups() return sum(0 if g[i] is None else float(g[i]) * 60. ** (1 - i) for i in range(3))
def write_mzxml(filename, df, info=None, precision='f'): """ Precision is either f or d. """ for r in df.values: df.columns pass
def read_binary(self, ba, param_groups=None): """ ba - binaryDataArray XML node """ if ba is None: return [] pgr = ba.find('m:referenceableParamGroupRef', namespaces=self.ns) if pgr is not None and param_groups is not None: q = 'm:referenceableParamGroup[@id="' + pgr.get('ref') + '"]' pg = param_groups.find(q, namespac...
def pretty_memory_info(): ''' Pretty format memory info. Returns ------- str Memory info. Examples -------- >>> pretty_memory_info() '5MB memory usage' ''' process = psutil.Process(os.getpid()) return '{}MB memory usage'.format(int(process.memory_info().rss / 2**20))
def dynamic(name: str, expression: Union[type, Callable[[Type[Any]], type]]) \ -> Callable[[Callable[..., Any]], Callable[..., Any]]: # TODO type annotations for pass-through decorator """ :param name: :param expression: a subclass of ``type`` or a callable in the format ``(owner: Type[Any]) -> type``. :return: """ def...
def invert(series): ''' Swap index with values of series. Parameters ---------- series : ~pandas.Series Series to swap on, must have a name. Returns ------- ~pandas.Series Series after swap. See also -------- pandas.Series.map Joins series ``a -> b`` and ``b -> c`` into ``a -> c``. ''' df = series.reset_index() #TODO a...
def split(series): ''' Split values. The index is dropped, but this may change in the future. Parameters ---------- series : ~pandas.Series[~pytil.numpy.ArrayLike] Series with array-like values. Returns ------- ~pandas.Series Series with values split across rows. Examples -------- >>> series = pd.Series([[1,2],[1,2],[3...
def equals(series1, series2, ignore_order=False, ignore_index=False, all_close=False, _return_reason=False): ''' Get whether 2 series are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- series1 : pandas.Series Series to compare. series2 : pandas.Series Series to compare. ignore_order : b...
`None` if equal or a short explanation of why the series aren't equal, otherwise. Notes ----- All values (including those of indices) must be copyable and ``__eq__`` must be such that a copy must equal its original. A value must equal itself unless it's ``NaN``. Values needn't be orderable or hashable (however pandas r...
def assert_equals(actual, expected, ignore_order=False, ignore_index=False, all_close=False): ''' Assert 2 series are equal. Like ``assert equals(series1, series2, ...)``, but with better hints at where the series differ. See `equals` for detailed parameter doc. Parameters ---------- actual : ~pandas.Series expected : ...
def do_startup(self): """Gtk.Application.run() will call this function()""" Gtk.Application.do_startup(self) gtk_window = Gtk.ApplicationWindow(application=self) gtk_window.set_title('AppKit') webkit_web_view = WebKit.WebView() webkit_web_view.load_uri('http://localhost:' + str(self.port)) screen = Gdk.Screen.get_defau...
def tokenize(self, message, max_length, mentions=None): """ Tokenize a message into a list of messages of no more than max_length, including mentions in each message :param message: Message to be sent :param max_length: Maximum allowed length for each resulting message :param mentions: List of usernames to mention in e...
"... " length = 4 + mention_length + len(tokens[index]) else: # 1 for leading space length += 1 + len(tokens[index]) index += 1 indices.append(index) messages = [" ".join(tokens[0:indices[0]])] for i in range(1, len(indices)): messages[i - 1] += ' ...' parts = [] if mention_text: parts.append(mention_text) parts.append...
def send_message(self, message, mention_id=None, mentions=[]): """ Send the specified message to twitter, with appropriate mentions, tokenized as necessary :param message: Message to be sent :param mention_id: In-reply-to mention_id (to link messages to a previous message) :param mentions: List of usernames to mention ...
def get_reply_to_names(self, mention): """ Get a sorted list of unique usernames mentioned in the message, excluding the bot's own name :param mention: JSON mention object from twitter :return: list of usernames """ mention_list = [user['screen_name'] for user in mention['entities']['user_mentions']] mention_list.appen...
def reply_to_mentions(self): """ For every mention since since_id, create a message with the provider and use it to reply to the mention :return: Number of mentions processed """ since_id = self.since_id.get() kwargs = {'count': 200} if since_id: kwargs['since_id'] = since_id mentions_list = [] try: mentions_list = sel...
a message, but all were duplicates message = 'No unique messages found.' else: message = self.messages.create(mention, self.MESSAGE_LENGTH) error_code = self.send_message(message, mention_id, reply_to_names) tries += 1 mentions_processed += 1 self.since_id.set('{0}'.format(mention_id)) return mentions_processed
def go(self, settings, command): """ Run the specified command using a TwitterBot created with the provided settings :param settings: Settings class :param command: Command to run, either 'post_message' or 'reply_to_mentions' :return: Result of running the command """ bot = TwitterBot(settings) result = 1 if command ==...
def decompress(zdata): """ Unserializes an AstonFrame. Parameters ---------- zdata : bytes Returns ------- Trace or Chromatogram """ data = zlib.decompress(zdata) lc = struct.unpack('<L', data[0:4])[0] li = struct.unpack('<L', data[4:8])[0] c = json.loads(data[8:8 + lc].decode('utf-8')) i = np.fromstring(data[8 + lc:8 ...
def _slice_idxs(df, twin=None): """ Returns a slice of the incoming array filtered between the two times specified. Assumes the array is the same length as self.data. Acts in the time() and trace() functions. """ if twin is None: return 0, df.shape[0] tme = df.index if twin[0] is None: st_idx = 0 else: st_idx = (np.abs...
def _apply_data(self, f, ts, reverse=False): """ Convenience function for all of the math stuff. """ # TODO: needs to catch np numeric types? if isinstance(ts, (int, float)): d = ts * np.ones(self.shape[0]) elif ts is None: d = None elif np.array_equal(ts.index, self.index): d = ts.values else: d = ts._retime(self.inde...
def traces(self): """ Decomposes the Chromatogram into a collection of Traces. Returns ------- list """ traces = [] for v, c in zip(self.values.T, self.columns): traces.append(Trace(v, self.index, name=c)) return traces
def plot(self, style='heatmap', legend=False, cmap=None, ax=None): """ Presents the AstonFrame using matplotlib. Parameters ---------- style : {'heatmap', 'colors', ''} legend : bool, optional cmap: matplotlib.colors.Colormap, optional ax : matplotlib.axes.Axes, optional """ # styles: 2d, colors, otherwise interpret as...
= 1.065 * gaussian(wvs, x=595.8, w=33.33) + \ 0.366 * gaussian(wvs, x=446.8, w=19.44) vis_filt[1] = 1.014 * gaussian(np.log(wvs), x=np.log(556.3), w=0.075) vis_filt[2] = 1.839 * gaussian(np.log(wvs), x=np.log(449.8), w=0.051) if isinstance(self.values, scipy.sparse.spmatrix): xyz = np.dot(self.values.toarray(), vis_fil...
def as_sound(self, filename, speed=60, cutoff=50): """ Convert AstonFrame into a WAV file. Parameters ---------- filename : str Name of wavfile to create. speed : float, optional How much to speed up for sound recording, e.g. a value of 60 will turn an hour-long AstonFrame into a minute-long sound clip. cutoff : float,...
wavelength/mz to a tone. """ try: mz = float(mz) except: return 100 wv = (mz * (max_hz - min_hz) - max_hz * min_mz + min_hz * max_mz) / (max_mz - min_mz) return int(44100 / wv) # go through each trace and map it into the sound array for i, mz in enumerate(self.columns): if float(mz) < cutoff: # clip out mz/wv below a c...
def scan(self, t, dt=None, aggfunc=None): """ Returns the spectrum from a specific time. Parameters ---------- t : float dt : float """ idx = (np.abs(self.index - t)).argmin() if dt is None: # only take the spectra at the nearest time mz_abn = self.values[idx, :].copy() else: # sum up all the spectra over a range en_id...
def setup_cassandra(self, namespaces): """ Set up a connection to the specified Cassandra cluster and create the specified keyspaces if they dont exist. """ connections_to_shutdown = [] self.cluster = Cluster(self.hosts) for namespace_name in namespaces: keyspace = '%s_%s' % (self.keyspace_prefix, namespace_name) names...
def _delete(self, namespace, stream, start_id, end_time, configuration): """ Delete events for `stream` between `start_id` and `end_time`. `stream` : The stream to delete events for. `start_id` : Delete events with id > `start_id`. `end_time` : Delete events ending <= `end_time`. `configuration` : A dictionary of setti...
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration): """ Retrieve events for `stream` between `start_id` and `end_time`. `stream` : The stream to return events for. `start_id` : Return events with id > `start_id`. `end_time` : Return events ending <= `end_time`. `order` : Whether to ...
def index(environment, start_response, headers): """ Return the status of this Kronos instance + its backends> Doesn't expect any URL parameters. """ response = {'service': 'kronosd', 'version': kronos.__version__, 'id': settings.node['id'], 'storage': {}, SUCCESS_FIELD: True} # Check if each backend is alive for name,...
def put_events(environment, start_response, headers): """ Store events in backends POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), events: { stream_name1 : [event1, event2, ...], stream_name2 : [event1, event2, ...], ... } } Where each event is a dictionary of keys and values...
configuration) wait(results.values()) # Did any insertion fail? success = True response = defaultdict(dict) for (stream, backend), result in results.iteritems(): try: result.get() response[stream][backend] = { 'num_inserted': len(events_to_insert[stream]) } except Exception, e: log.exception('put_events: insertion to b...
def get_events(environment, start_response, headers): """ Retrieve events POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), stream : stream_name, start_time : starting_time_as_kronos_time, end_time : ending_time_as_kronos_time, start_id : only_return_events_with_id_greater_than...
else: backend, configuration = router.backend_to_retrieve(namespace, stream) events = backend.retrieve( namespace, stream, long(request_json.get('start_time', 0)), long(request_json['end_time']), request_json.get('start_id'), configuration, order=request_json.get('order', ResultOrder.ASCENDING), limit=limit) start_resp...
def delete_events(environment, start_response, headers): """ Delete events POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), stream : stream_name, start_time : starting_time_as_kronos_time, end_time : ending_time_as_kronos_time, start_id : only_delete_events_with_id_gte_me, } E...
backend `%s` failed.', backend) success = False response[backend] = {'num_deleted': -1, ERRORS_FIELD: [repr(e)]} response = {request_json['stream']: response, SUCCESS_FIELD: success} start_response('200 OK', headers) return response
def get_streams(environment, start_response, headers): """ List all streams that can be read from Kronos right now. POST body should contain a JSON encoded version of: { namespace: namespace_name (optional) } """ start_response('200 OK', headers) streams_seen_so_far = set() namespace = environment['json'].get('namespac...
def infer_schema(environment, start_response, headers): """ Return the inferred schema of the requested stream. POST body should contain a JSON encoded version of: { stream: stream_name, namespace: namespace_name (optional) } """ stream = environment['json']['stream'] namespace = environment['json'].get('namespace') or...
def devices(self): """ Return a list of connected devices in the form (*serial*, *status*) where status can be any of the following: 1. device 2. offline 3. unauthorized :returns: A list of tuples representing connected devices """ devices = None with self.socket.Connect(): devices = self._command("host:devices") retur...
def add_leaf(self, leaf_blob): """Adds a leaf to the list of leaves. Does not build the tree so call `build()` to construct the rest of the tree from the added leaves. :param leaf_blob: the leaf payload to add. should be a hashable object """ self.leaves.append(MerkleLeaf(len(self.leaves), leaf_blob))
def build(self): """Builds the tree from the leaves that have been added. This function populates the tree from the leaves down non-recursively """ self.order = MerkleTree.get_order(len(self.leaves)) n = 2 ** self.order self.nodes = [b''] * 2 * n # populate lowest nodes with leaf hashes for j in range(0, n): if (j < le...
def get_branch(self, i): """Gets a branch associated with leaf i. This will trace the tree from the leaves down to the root, constructing a list of tuples that represent the pairs of nodes all the way from leaf i to the root. :param i: the leaf identifying the branch to retrieve """ branch = MerkleBranch(self.order) j ...
def verify_branch(leaf, branch, root): """This will verify that the given branch fits the given leaf and root It calculates the hash of the leaf, and then verifies that one of the bottom level nodes in the branch matches the leaf hash. Then it calculates the hash of the two nodes on the next level and checks that one o...
are correct try: lh = leaf.get_hash() except: return False for i in range(0, branch.get_order()): if (branch.get_left(i) != lh and branch.get_right(i) != lh): return False h = hashlib.sha256() if (len(branch.get_left(i)) > 0): h.update(branch.get_left(i)) if (len(branch.get_right(i)) > 0): h.update(branch.get_right(i))...
def save(self): """Save this entry. If the entry does not have an :attr:`id`, a new id will be assigned, and the :attr:`id` attribute set accordingly. Pre-save processing of the fields saved can be done by overriding the :meth:`prepare_save` method. Additional actions to be done after the save operation has been comple...
def get_many(self, ids): """Get several entries at once.""" return [self.instance(id, **fields) for id, fields in zip(ids, self.api.mget(ids))]
def create(self, **fields): """Create new entry.""" entry = self.instance(**fields) entry.save() return entry
def generous_parse_uri(uri): """Return a urlparse.ParseResult object with the results of parsing the given URI. This has the same properties as the result of parse_uri. When passed a relative path, it determines the absolute path, sets the scheme to file, the netloc to localhost and returns a parse of the result. """ p...
def getuser(): """Return the username.""" is_windows = platform.system() == "Windows" no_username_in_env = os.environ.get("USERNAME") is None return cross_platform_getuser(is_windows, no_username_in_env)
def _get_config_dict_from_file(config_path=None): """Return value if key exists in file. Return empty string ("") if key or file does not exist. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Default (empty) content will be used if config file does not exist. config_content = {} # If the config file ex...
def write_config_value_to_file(key, value, config_path=None): """Write key/value pair to config file. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Get existing config. config = _get_config_dict_from_file(config_path) # Add/update the key/value pair. config[key] = value # Create parent directories if ...
def get_config_value_from_file(key, config_path=None, default=None): """Return value if key exists in file. Return default if key not in config. """ config = _get_config_dict_from_file(config_path) if key not in config: return default return config[key]
def get_config_value(key, config_path=None, default=None): """Get a configuration value. Preference: 1. From environment 2. From JSON configuration file supplied in ``config_path`` argument 3. The default supplied to the function :param key: name of lookup value :param config_path: path to JSON configuration file :para...
def mkdir_parents(path): """Create the given directory path. This includes all necessary parent directories. Does not raise an error if the directory already exists. :param path: path to create """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise
def timestamp(datetime_obj): """Return Unix timestamp as float. The number of seconds that have elapsed since January 1, 1970. """ start_of_time = datetime.datetime(1970, 1, 1) diff = datetime_obj - start_of_time return diff.total_seconds()
def name_is_valid(name): """Return True if the dataset name is valid. The name can only be 80 characters long. Valid characters: Alpha numeric characters [0-9a-zA-Z] Valid special characters: - _ . """ # The name can only be 80 characters long. if len(name) > MAX_NAME_LENGTH: return False return bool(NAME_VALID_CHARS_R...
def get_admin_metadata(self): """Return the admin metadata as a dictionary.""" logger.debug("Getting admin metdata") text = self.get_text(self.get_admin_metadata_key()) return json.loads(text)
def get_manifest(self): """Return the manifest as a dictionary.""" logger.debug("Getting manifest") text = self.get_text(self.get_manifest_key()) return json.loads(text)
def get_overlay(self, overlay_name): """Return overlay as a dictionary.""" logger.debug("Getting overlay: {}".format(overlay_name)) overlay_key = self.get_overlay_key(overlay_name) text = self.get_text(overlay_key) return json.loads(text)
def put_admin_metadata(self, admin_metadata): """Store the admin metadata.""" logger.debug("Putting admin metdata") text = json.dumps(admin_metadata) key = self.get_admin_metadata_key() self.put_text(key, text)
def put_manifest(self, manifest): """Store the manifest.""" logger.debug("Putting manifest") text = json.dumps(manifest, indent=2, sort_keys=True) key = self.get_manifest_key() self.put_text(key, text)
def put_readme(self, content): """Store the readme descriptive metadata.""" logger.debug("Putting readme") key = self.get_readme_key() self.put_text(key, content)
def update_readme(self, content): """Update the readme descriptive metadata.""" logger.debug("Updating readme") key = self.get_readme_key() # Back up old README content. backup_content = self.get_readme_content() backup_key = key + "-{}".format( timestamp(datetime.datetime.now()) ) logger.debug("README.yml backup key: ...
def put_overlay(self, overlay_name, overlay): """Store the overlay.""" logger.debug("Putting overlay: {}".format(overlay_name)) key = self.get_overlay_key(overlay_name) text = json.dumps(overlay, indent=2) self.put_text(key, text)
def item_properties(self, handle): """Return properties of the item with the given handle.""" logger.debug("Getting properties for handle: {}".format(handle)) properties = { 'size_in_bytes': self.get_size_in_bytes(handle), 'utc_timestamp': self.get_utc_timestamp(handle), 'hash': self.get_hash(handle), 'relpath': self.g...
def _document_structure(self): """Document the structure of the dataset.""" logger.debug("Documenting dataset structure") key = self.get_structure_key() text = json.dumps(self._structure_parameters, indent=2, sort_keys=True) self.put_text(key, text) key = self.get_dtool_readme_key() self.put_text(key, self._dtool_readm...
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs in location given by base_uri.""" parsed_uri = generous_parse_uri(base_uri) uri_list = [] path = parsed_uri.path if IS_WINDOWS: path = unix_to_windows_path(parsed_uri.path, parsed_uri.netloc) for d in os.listdir(path): dir_path = os.path....
def put_text(self, key, text): """Put the text into the storage associated with the key.""" with open(key, "w") as fh: fh.write(text)
def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
def get_utc_timestamp(self, handle): """Return the UTC timestamp.""" fpath = self._fpath_from_handle(handle) datetime_obj = datetime.datetime.utcfromtimestamp( os.stat(fpath).st_mtime ) return timestamp(datetime_obj)
def get_hash(self, handle): """Return the hash.""" fpath = self._fpath_from_handle(handle) return DiskStorageBroker.hasher(fpath)
def list_overlay_names(self): """Return list of overlay names.""" overlay_names = [] if not os.path.isdir(self._overlays_abspath): return overlay_names for fname in os.listdir(self._overlays_abspath): name, ext = os.path.splitext(fname) overlay_names.append(name) return overlay_names
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ manifest = self.get_manifest() item = manifest["items"][identifier] item_abspath = os.path.join(self._data_abs...
def _create_structure(self): """Create necessary structure to hold a dataset.""" # Ensure that the specified path does not exist and create it. if os.path.exists(self._abspath): raise(StorageBrokerOSError( "Path already exists: {}".format(self._abspath) )) # Make sure the parent directory exists. parent, _ = os.path.sp...
def put_item(self, fpath, relpath): """Put item with content from fpath at relpath in dataset. Missing directories in relpath are created on the fly. :param fpath: path to the item on disk :param relpath: relative path name given to the item in the dataset as a handle :returns: the handle given to the item """ # Define...
def iter_item_handles(self): """Return iterator over item handles.""" path = self._data_abspath path_length = len(path) + 1 for dirpath, dirnames, filenames in os.walk(path): for fn in filenames: path = os.path.join(dirpath, fn) relative_path = path[path_length:] if IS_WINDOWS: relative_path = windows_to_unix_path(rela...
def add_item_metadata(self, handle, key, value): """Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value """ if not os.path.isdir(self._metadata_fragments_abspath): os.mkdir(self...
def get_item_metadata(self, handle): """Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen :returns: dictionary containing item metadata """ if not os.pat...
def pre_freeze_hook(self): """Pre :meth:`dtoolcore.ProtoDataSet.freeze` actions. This method is called at the beginning of the :meth:`dtoolcore.ProtoDataSet.freeze` method. It may be useful for remote storage backends to generate caches to remove repetitive time consuming calls """ allowed = set([v[0] for v in _STRUCTU...
def post_freeze_hook(self): """Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for storing item metadata fragment files. """ if ...