code
stringlengths
1
18.2k
def set_refresh(self, timeout, callback, *callback_args): """ It is just stub for simplify setting timeout. Args: timeout (int): timeout in milliseconds, after which callback will be called callback (callable): usually, just a function that will be called each time after timeout *callback_args (any type): arguments tha...
def add_menu_item(self, command, title): """ Add mouse right click menu item. Args: command (callable): function that will be called after left mouse click on title title (str): label that will be shown in menu """ m_item = Gtk.MenuItem() m_item.set_label(title) m_item.connect('activate', command) self.menu.append(m_it...
def add_seperator(self): """ Add separator between labels in menu that called on right mouse click. """ m_item = Gtk.SeparatorMenuItem() self.menu.append(m_item) self.menu.show_all()
def right_click_event_statusicon(self, icon, button, time): """ It's just way how popup menu works in GTK. Don't ask me how it works. """ def pos(menu, aicon): """Just return menu""" return Gtk.StatusIcon.position_menu(menu, aicon) self.menu.popup(None, None, pos, icon, button, time)
def check_battery(self): """ Implement how we will check battery condition. Now it just trying to check standard battery in /sys """ self.charging = False if \ subprocess.getoutput("cat /sys/class/power_supply/BAT0/status") == 'Discharging' \ else True percent = subprocess.getoutput("cat /sys/class/power_supply/BAT0/ca...
def tooltip_query(self, widget, x, y, keyboard_mode, tooltip): """ Set tooltip which appears when you hover mouse curson onto icon in system panel. """ tooltip.set_text(subprocess.getoutput("acpi")) return True
def about(): """ About box for aps. Gives version numbers for aps, NumPy, SciPy, Cython, and MatPlotLib. """ print("") print("aps: APS Journals API in Python for Humans") print("Copyright (c) 2017 and later.") print("Xiao Shang") print("") print("aps Version: %s" % aps.__version__) print("Numpy Version: %s" % numpy.__v...
def success(headers = None, data = ''): """ Generate success JSON to send to client """ passed_headers = {} if headers is None else headers if isinstance(data, dict): data = json.dumps(data) ret_headers = {'status' : 'ok'} ret_headers.update(passed_headers) return server_responce(ret_headers, data)
def lock_access(repository_path, callback): """ Synchronise access to the user file between processes, this specifies which user is allowed write access at the current time """ with open(cpjoin(repository_path, 'lock_file'), 'w') as fd: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) returned = callback() fcntl.flo...
def update_user_lock(repository_path, session_token): """ Write or clear the user lock file """ # NOTE ALWAYS use within lock access callback # While the user lock file should ALWAYS be written only within a lock_access # callback, it is sometimes read asynchronously. Because of this updates to # the file must be atomi...
def can_aquire_user_lock(repository_path, session_token): """ Allow a user to acquire the lock if no other user is currently using it, if the original user is returning, presumably after a network error, or if the lock has expired. """ # NOTE ALWAYS use within lock access callback user_file_path = cpjoin(repository_pat...
def varify_user_lock(repository_path, session_token): """ Verify that a returning user has a valid token and their lock has not expired """ with open(cpjoin(repository_path, 'user_file'), 'r') as fd2: content = fd2.read() if len(content) == 0: return False try: res = json.loads(content) except ValueError: return False ...
def auth_db_connect(db_path): """ An SQLite database is used to store authentication transient data, this is tokens, strings of random data which are signed by the client, and session_tokens which identify authenticated users """ def dict_factory(cursor, row): return {col[0] : row[idx] for idx,col in enumerate(cursor.d...
def begin_auth(): """ Request authentication token to sign """ repository = request.headers['repository'] if repository not in config['repositories']: return fail(no_such_repo_msg) # == repository_path = config['repositories'][repository]['path'] conn = auth_db_connect(cpjoin(repository_path, 'auth_transient.db')); gc_...
def authenticate(): """ This does two things, either validate a pre-existing session token or create a new one from a signed authentication token. """ client_ip = request.environ['REMOTE_ADDR'] repository = request.headers['repository'] if repository not in config['repositories']: return fail(no_such_repo_msg) # == rep...
by this system and is still valid res = conn.execute("select * from tokens where token = ? and ip = ? ", (auth_token, client_ip)).fetchall() # Validate token matches one we sent if res == [] or len(res) > 1: return fail(user_auth_fail_msg) # Does the user have permission to use this repository? if repository not in con...
def have_authenticated_user(client_ip, repository, session_token): """ check user submitted session token against the db and that ip has not changed """ if repository not in config['repositories']: return False repository_path = config['repositories'][repository]['path'] conn = auth_db_connect(cpjoin(repository_path, '...
# the current operation. We exclude any tokens owned by the client which currently owns the user # lock for this reason. user_lock = read_user_lock(repository_path) active_commit = user_lock['session_token'] if user_lock != None else None if active_commit != None: conn.execute("delete from session_tokens where expires ...
def find_changed(): """ Find changes since the revision it is currently holding """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail(use...
server_changes.iteritems() if v['path'] not in resolutions['client']} sorted_changes = merge_client_and_server_changes(server_changes, client_changes) return success({}, {'head' : head, 'sorted_changes': sorted_changes})
def pull_file(): """ Get a file from the server """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail(user_auth_fail_msg) #=== data_store...
def begin_commit(): """ Allow a client to begin a commit and acquire the write lock """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail...
lock only needs to survive until # the client owning the lock sends another request and re acquires the flock. if not can_aquire_user_lock(repository_path, session_token): return fail(lock_fail_msg) # Commits can only take place if the committing user has the latest revision, # as committing from an outdated state coul...
first obtaining the lock again by calling begin_commit(). # Any remaining commit data from failed prior commits is garbage collected here. # While it would technically be possible to implement commit resume should the same # client resume, I only see commits failing due to a network error and this is so # rare I don't ...
def push_file(): """ Push a file to the server """ #NOTE beware that reading post data in flask causes hang until file upload is complete session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, se...
# updates the user lock expiry update_user_lock(repository_path, session_token) return success() return lock_access(repository_path, with_exclusive_lock)
def delete_files(): """ Delete one or more files from the server """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail(user_auth_fail_msg...
def commit(): """ Commit changes and release the write lock """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail(user_auth_fail_msg) #==...
def serialize(self): """ Converts :class:`adnpy.models.Model` into a normal dict without references to the api """ data = {} for k, v in self.iteritems(): if k.startswith('_'): continue if isinstance(v, APIModel): data[k] = v.serialize() elif v and is_seq_not_string(v) and isinstance(v[0], APIModel): data[k] = [x.seria...
def get_annotation(self, key, result_format='list'): """ Is a convenience method for accessing annotations on models that have them """ value = self.get('_annotations_by_key', {}).get(key) if not value: return value if result_format == 'one': return value[0] return value
def update_user(self): """ Save the state of the current user """ # First create a copy of the current user user_dict = self.serialize() # Then delete the entities in the description field del user_dict['description']['entities'] # Then upload user_dict user, meta = self._api.update_user('me', data=user_dict)
def is_same_dict(d1, d2): """Test two dictionary is equal on values. (ignore order) """ for k, v in d1.items(): if isinstance(v, dict): is_same_dict(v, d2[k]) else: assert d1[k] == d2[k] for k, v in d2.items(): if isinstance(v, dict): is_same_dict(v, d1[k]) else: assert d1[k] == d2[k]
def Items(cls): """non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ... ... class D(Constant): ... pass >>> MyClass.Items() [("a", 1), ("b", 2)] .. versionadded:: 0.0.5 """ l = list()...
def items(self): """non-class attributes ordered by alphabetical order. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # non-class attributre ... ... class C(Constant): ... pass ... ... class D(Constant): ... pass >>> my_class = MyClass() >>> my_class.items() [("a", 1), ("b", 2)] .. versionc...
def Subclasses(cls, sort_by=None, reverse=False): """Get all nested Constant class and it's name pair. :param sort_by: the attribute name used for sorting. :param reverse: if True, return in descend order. :returns: [(attr, value),...] pairs. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre ... b = 2 # ...
def subclasses(self, sort_by=None, reverse=False): """Get all nested Constant class instance and it's name pair. :param sort_by: the attribute name used for sorting. :param reverse: if True, return in descend order. :returns: [(attr, value),...] pairs. :: >>> class MyClass(Constant): ... a = 1 # non-class attributre .....
def GetFirst(cls, attr, value, e=0.000001, sort_by="__name__"): """Get the first nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attribute. .. versionadded:: 0.0.5 ""...
def get_first(self, attr, value, e=0.000001, sort_by="__name__", reverse=False): """Get the first nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attribute. .. versio...
def GetAll(cls, attr, value, e=0.000001, sort_by="__name__"): """Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attribute. .. versionadded:: 0.0.5 """ matche...
def get_all(self, attr, value, e=0.000001, sort_by="__name__", reverse=False): """Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested class is ordered by <sort_by> attribute. .. versionchanged...
def BackAssign(cls, other_entity_klass, this_entity_backpopulate_field, other_entity_backpopulate_field, is_many_to_one=False): """ Assign defined one side mapping relationship to other side. For example, each employee belongs to one department, then one department includes many employees. If you defined each employee'...
if isinstance(other_field_value, (tuple, list)): for self_klass in other_field_value: self_key = self_klass.__name__ try: data[self_key].append(other_klass) except KeyError: data[self_key] = [other_klass, ] else: if other_field_value is not None: self_klass = other_field_value self_key = self_klass.__name__ try: data[s...
def dump(cls): """Dump data into a dict. .. versionadded:: 0.0.2 """ d = OrderedDict(cls.Items()) d["__classname__"] = cls.__name__ for attr, klass in cls.Subclasses(): d[attr] = klass.dump() return OrderedDict([(cls.__name__, d)])
def load(cls, data): """Construct a Constant class from it's dict data. .. versionadded:: 0.0.2 """ if len(data) == 1: for key, value in data.items(): if "__classname__" not in value: # pragma: no cover raise ValueError name = key bases = (Constant,) attrs = dict() for k, v in value.items(): if isinstance(v, dict): if ...
def hourly(location='Fresno, CA', days=1, start=None, end=None, years=1, use_cache=True, verbosity=1): """ Get detailed (hourly) weather data for the requested days and location The Weather Underground URL for Fresno, CA on 1/1/2011 is: http://www.wunderground.com/history/airport/KFAT/2011/1/1/DailyHistory.html?MR=1&fo...
datetime.datetime.today().date() days = pd.date_range(start=start, end=end, periods=days) # refresh the cache each calendar month or each change in the number of days in the dataset cache_path = 'hourly-{}-{}-{:02d}-{:04d}.csv'.format(airport_code, days[-1].year, days[-1].month, len(days)) cache_path = os.path.join(CAC...
table[1:] tzs = [s[4:] for s in columns if (s[5:] in ['ST', 'DT'] and s[4] in 'PMCE' and s[:4].lower() == 'time')] if tzs: tz = tzs[0] else: tz = 'UTC' for rownum, row in enumerate(table): try: table[rownum] = [util.make_tz_aware(row[0], tz)] + row[1:] except ValueError: pass dates = [row[-1] for row in table] if not a...
msg += "Attempted a GET request using the URI:\n {0}\n".format(url) warnings.warn(msg) try: df.to_csv(cache_path) except: if verbosity > 0 and use_cache: from traceback import print_exc print_exc() warnings.warn('Unable to write weather data to cache file at {}'.format(cache_path)) return df
def api(feature='conditions', city='Portland', state='OR', key=None): """Use the wunderground API to get current conditions instead of scraping Please be kind and use your own key (they're FREE!): http://www.wunderground.com/weather/api/d/login.html References: http://www.wunderground.com/weather/api/d/terms.html Examp...
rawtide satellite tide webcams yesterday').split(' ') feature = util.fuzzy_get(features, feature) # Please be kind and use your own key (they're FREE!): # http://www.wunderground.com/weather/api/d/login.html key = key or env.get('WUNDERGROUND', None, verbosity=-1) or env.get('WUNDERGROUND_KEY', 'c45a86c2fc63f7d0', verb...
def daily(location='Fresno, CA', years=1, use_cache=True, verbosity=1): """Retrieve weather for the indicated airport code or 'City, ST' string. >>> df = daily('Camas, WA', verbosity=-1) >>> 365 <= len(df) <= 365 * 2 + 1 True Sacramento data has gaps (airport KMCC): 8/21/2013 is missing from 2013. Whole months are miss...
yr in years): years = np.array([abs(yr) if (1900 <= abs(yr) <= this_year) else (this_year - abs(int(yr))) for yr in years])[::-1] airport_code = airport(location, default=location) # refresh the cache each time the start or end year changes cache_path = 'daily-{}-{}-{}.csv'.format(airport_code, years[0], years[-1]) cac...
# clean up the last column (if it contains <br> tags) table = [util.strip_br(row) if len(row) > 1 else row for row in table] # numcols = max(len(row) for row in table) # table = [row for row in table if len(row) == numcols] columns = table.pop(0) tzs = [s for s in columns if (s[1:] in ['ST', 'DT'] and s[0] in 'PMCE')] ...
verbosity > 1: print(df) try: df.to_csv(cache_path) except: if verbosity > 0 and use_cache: from traceback import print_exc print_exc() warnings.warn('Unable to write weather data to cache file at {}'.format(cache_path)) return df
def ensure_cache_folder(self): """ Creates a gradle cache folder if it does not exist. """ if os.path.exists(self.cache_folder) is False: os.makedirs(self.cache_folder)
def is_app_folder(self, folder): """ checks if a folder """ with open('%s/%s/build.gradle' % (self.path, folder)) as f: for line in f.readlines(): if config.gradle_plugin in line: return True return False
def get_src_folder(self): """ Gets the app source folder from settings.gradle file. Returns: A string containing the project source folder name (default is "app") """ with open('%s/settings.gradle' % self.path) as f: for line in f.readlines(): if line.startswith('include'): matches = re.findall(r'\'\:?(.+?)\'', line) i...
def get_build_tool_version(self): """ Gets the build tool version to be used by zipalign from build.gradle file. Returns: A string containing the build tool version, default is 23.0.2. """ with open('%s/%s/build.gradle' % (self.path, self.src_folder)) as f: for line in f.readlines(): if 'buildToolsVersion' in line: mat...
def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name='app'): """ Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param k...
def validate(self): """ Validates the app project before the build. This is the first step in the build process. Needs to be implemented by the subclass. """ if os.path.exists('%s/gradlew' % self.path) is False: raise errors.InvalidProjectStructure(message='Missing gradlew project root folder') self.touch_log('validate...
def prepare(self): """ Prepares the android project to the build process. Checks if the project uses either gradle or ant and executes the necessary steps. """ self.src_folder = self.get_src_folder() st = os.stat('%s/gradlew' % self.path) os.chmod('%s/gradlew' % self.path, st.st_mode | stat.S_IEXEC)
def build(self, mode='debug'): """ Builds the app project after the execution of validate and prepare. This is the third and last step in the build process. Needs to be implemented by the subclass. """ self.ensure_cache_folder() ref = { 'debug': 'assembleDebug', 'release': 'assembleRelease' } cmd = [ './gradlew', ref.g...
def smart_insert(df, table, engine, minimal_size=5): """An optimized Insert strategy. **中文文档** 一种优化的将大型DataFrame中的数据, 在有IntegrityError的情况下将所有 好数据存入数据库的方法。 """ from sqlalchemy.exc import IntegrityError try: table_name = table.name except: table_name = table # 首先进行尝试bulk insert try: df.to_sql(table_name, engine, index=Fa...
def excel_to_sql(excel_file_path, engine, read_excel_kwargs=None, to_generic_type_kwargs=None, to_sql_kwargs=None): """Create a database from excel. :param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method. example: ``{"employee": {"skiprows": 10}, "department": {}}`` :param to_sql_kwargs: dict, argum...
)
def database_to_excel(engine, excel_file_path): """Export database to excel. :param engine: :param excel_file_path: """ from sqlalchemy import MetaData, select metadata = MetaData() metadata.reflect(engine) writer = pd.ExcelWriter(excel_file_path) for table in metadata.tables.values(): sql = select([table]) df = pd.rea...
def requirements(requirements_file): """Return packages mentioned in the given file. Args: requirements_file (str): path to the requirements file to be parsed. Returns: (list): 3rd-party package dependencies contained in the file. """ return [ str(pkg.req) for pkg in parse_requirements( requirements_file, session=pip_d...
def createNewOoid(timestamp=None, depth=None): """Create a new Ooid for a given time, to be stored at a given depth timestamp: the year-month-day is encoded in the ooid. If none, use current day depth: the expected storage depth is encoded in the ooid. If non, use the defaultDepth returns a new opaque id string holding...
def uuidToOoid(uuid,timestamp=None, depth= None): """ Create an ooid from a 32-hex-digit string in regular uuid format. uuid: must be uuid in expected format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxx7777777 timestamp: the year-month-day is encoded in the ooid. If none, use current day depth: the expected storage depth is encoded ...
def dateAndDepthFromOoid(ooid): """ Extract the encoded date and expected storage depth from an ooid. ooid: The ooid from which to extract the info returns (datetime(yyyy,mm,dd),depth) if the ooid is in expected format else (None,None) """ year = month = day = None try: day = int(ooid[-2:]) except: return None,None try...
def HeadList(self): """Return a list of all the currently loaded repo HEAD objects.""" return [(rname, repo.currenthead) for rname, repo in self.repos.items() ]
def setorigin(self): """Set the 'origin' remote to the upstream url that we trust.""" try: origin = self.repo.remotes.origin if origin.url != self.origin_url: log.debug('[%s] Changing origin url. Old: %s New: %s', self.name, origin.url, self.origin_url) origin.config_writer.set('url', self.origin_url) except AttributeE...
def fetchall(self): """Fetch all refs from the upstream repo.""" try: self.repo.remotes.origin.fetch() except git.exc.GitCommandError as err: raise GitError(err)
def fetchref(self, ref): """Fetch a particular git ref.""" log.debug('[%s] Fetching ref: %s', self.name, ref) fetch_info = self.repo.remotes.origin.fetch(ref).pop() return fetch_info.ref
def sethead(self, ref): """Set head to a git ref.""" log.debug('[%s] Setting to ref %s', self.name, ref) try: ref = self.repo.rev_parse(ref) except gitdb.exc.BadObject: # Probably means we don't have it cached yet. # So maybe we can fetch it. ref = self.fetchref(ref) log.debug('[%s] Setting head to %s', self.name, ref)...
def get_file(self, filename): """Get a file from the repo. Returns a file-like stream with the data. """ log.debug('[%s]: reading: //%s/%s', self.name, self.name, filename) try: blob = self.repo.head.commit.tree/filename return blob.data_stream except KeyError as err: raise GitError(err)
def show_progress(self, message=None): """If we are in a progress scope, and no log messages have been shown, write out another '.'""" if self.in_progress_hanging: if message is None: sys.stdout.write('.') sys.stdout.flush() else: if self.last_message: padding = ' ' * max(0, len(self.last_message)-len(message)) else: p...
def funclog(logger): """A decorator function that provides debug input/output logging.""" # check if logger is from structlog use_structlog = False if STRUCTLOG: if isinstance(logger, structlog._config.BoundLoggerLazyProxy): real_logger = logger use_structlog = True # If a Logger object is passed in, use that. Otherwis...
inspect.getframeinfo(inspect.stack()[1][0]) filename = os.path.basename(frame_info.filename) lineno = frame_info.lineno func_name = getattr(fn, name_attr) arg_string = get_arg_string(args, kwargs) source_info = '{}:{}:{}({})'.format(filename, lineno, func_name, arg_string) if use_structlog: real_logger.debug(u'calling'...
def create(app_id: int = None, login: str = None, password: str = None, service_token: str = None, proxies: dict = None) -> API: """ Creates an API instance, requires app ID, login and password or service token to create connection :param app_id: int: specifies app ID :param login: str: specifies login, can be phone nu...
def user_homedir(username=None): """Returns a user's home directory. If no username is specified, returns the current user's homedir. """ if username: return os.path.expanduser('~%s/' % username) elif 'HOME' in os.environ: return os.environ['HOME'] elif os.name == 'posix': return os.path.expanduser('~/') else: raise Ru...
def hash_stream(fileobj, hasher=None, blocksize=65536): """Read from fileobj stream, return hash of its contents. Args: fileobj: File-like object with read() hasher: Hash object such as hashlib.sha1(). Defaults to sha1. blocksize: Read from fileobj this many bytes at a time. """ hasher = hasher or hashlib.sha1() buf = ...
def hash_str(data, hasher=None): """Checksum hash a string.""" hasher = hasher or hashlib.sha1() hasher.update(data) return hasher
def glob(*args): """Returns list of paths matching one or more wildcard patterns. Args: include_dirs: Include directories in the output """ if len(args) is 1 and isinstance(args[0], list): args = args[0] matches = [] for pattern in args: for item in glob2.glob(pattern): if not os.path.isdir(item): matches.append(item) ...
def flatten(listish): """Flatten an arbitrarily-nested list of strings and lists. Works for any subclass of basestring and any type of iterable. """ for elem in listish: if (isinstance(elem, collections.Iterable) and not isinstance(elem, basestring)): for subelem in flatten(elem): yield subelem else: yield elem
def linkorcopy(src, dst): """Hardlink src file to dst if possible, otherwise copy.""" if not os.path.isfile(src): raise error.ButcherError('linkorcopy called with non-file source. ' '(src: %s dst: %s)' % src, dst) elif os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) elif os.path.exists(dst): os.unlin...
def getcwd(cls): """ Provide a context dependent current working directory. This method will return the directory currently holding the lock. """ if not hasattr(cls._tl, "cwd"): cls._tl.cwd = os.getcwd() return cls._tl.cwd
def fname(self, version=None, tags=None, ext=None): """Returns the filename appropriate for an instance of this dataset. Parameters ---------- version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated with the instance of this dataset. ext : str, optional The f...
def fpath(self, version=None, tags=None, ext=None): """Returns the filepath appropriate for an instance of this dataset. Parameters ---------- version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated with the given instance of this dataset. ext : str, optional...
def add_local(self, source_fpath, version=None, tags=None): """Copies a given file into local store as an instance of this dataset. Parameters ---------- source_fpath : str The full path for the source file to use. version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags...
def upload(self, version=None, tags=None, ext=None, source_fpath=None, overwrite=False, **kwargs): """Uploads the given instance of this dataset to dataset store. Parameters ---------- version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated with the given ins...
tags=tags) if ext is None: ext = self._find_extension(version=version, tags=tags) if ext is None: attribs = "{}{}".format( "version={} and ".format(version) if version else "", "tags={}".format(tags) if tags else "", ) raise MissingDatasetError( "No dataset with {} in local store!".format(attribs)) fpath = self.fpath(v...
def download(self, version=None, tags=None, ext=None, overwrite=False, verbose=False, **kwargs): """Downloads the given instance of this dataset from dataset store. Parameters ---------- version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated with the given i...
azure.storage.blob.BlockBlobService.get_blob_to_path. """ fpath = self.fpath(version=version, tags=tags, ext=ext) if os.path.isfile(fpath) and not overwrite: if verbose: print( "File exists and overwrite set to False, so not " "downloading {} with version={} and tags={}".format( self.name, version, tags)) return downlo...
def df(self, version=None, tags=None, ext=None, **kwargs): """Loads an instance of this dataset into a dataframe. Parameters ---------- version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated with the desired instance of this dataset. ext : str, optional The ...
in local store!".format(attribs)) fpath = self.fpath(version=version, tags=tags, ext=ext) fmt = SerializationFormat.by_name(ext) return fmt.deserialize(fpath, **kwargs)
def dump_df(self, df, version=None, tags=None, ext=None, **kwargs): """Dumps an instance of this dataset into a file. Parameters ---------- df : pandas.DataFrame The dataframe to dump to file. version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated with the g...
def upload_df(self, df, version=None, tags=None, ext=None, **kwargs): """Dumps an instance of this dataset into a file and then uploads it to dataset store. Parameters ---------- df : pandas.DataFrame The dataframe to dump and upload. version: str, optional The version of the instance of this dataset. tags : list of st...
def from_inline(cls: Type[IdentityType], version: int, currency: str, inline: str) -> IdentityType: """ Return Identity instance from inline Identity string :param version: Document version number :param currency: Name of the currency :param inline: Inline string of the Identity :return: """ selfcert_data = Identity.re...
def from_signed_raw(cls: Type[IdentityType], signed_raw: str) -> IdentityType: """ Return Identity instance from a signed_raw string :param signed_raw: Signed raw document :return: """ n = 0 lines = signed_raw.splitlines(True) version = int(Identity.parse_field("Version", lines[n])) n += 1 Identity.parse_field("Type", ...