code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def create(gitpath, cache=None): if gitpath.startswith(config.LIBRARY_PREFIX): path = gitpath[len(config.LIBRARY_PREFIX):] return Library(*path.split('/'), cache=cache)
Create a Library from a git path.
def publishing_prepare_published_copy(self, draft_obj): mysuper = super(PublishingModel, self) if hasattr(mysuper, 'publishing_prepare_published_copy'): mysuper.publishing_prepare_published_copy(draft_obj)
Prepare published copy of draft prior to saving it
def _init_client(): if client is not None: return global _mysql_kwargs, _table_name _mysql_kwargs = { 'host': __opts__.get('mysql.host', '127.0.0.1'), 'user': __opts__.get('mysql.user', None), 'passwd': __opts__.get('mysql.password', None), 'db': __opts__.get('mysql.d...
Initialize connection and create table if needed
def success(self, request, message, extra_tags='', fail_silently=False): add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently)
Add a message with the ``SUCCESS`` level.
def asrgb(self, *args, **kwargs): if self._keyframe is None: raise RuntimeError('keyframe not set') kwargs['validate'] = False return TiffPage.asrgb(self, *args, **kwargs)
Read image data from file and return RGB image as numpy array.
def clear_components(self): ComponentRegistry._component_overlays = {} for key in self.list_components(): self.remove_component(key)
Clear all of the registered components
def draw_canvas(): for x in range(len(world)): for y in range(len(world[x])): if world[x][y].value: color = world[x][y].color_alive.get_as_hex() else: color = world[x][y].color_dead.get_as_hex() canvas.itemconfig(canvas_grid[x][y], fill=col...
Render the tkinter canvas based on the state of ``world``
def decode_network_packet(buf): off = 0 blen = len(buf) while off < blen: ptype, plen = header.unpack_from(buf, off) if plen > blen - off: raise ValueError("Packet longer than amount of data in buffer") if ptype not in _decoders: raise ValueError("Message type...
Decodes a network packet in collectd format.
def __start(self): assert not self.dispatcher_thread self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher, name='clearly-dispatcher') self.dispatcher_thread.daemon = True self.running = True self.dispatcher_threa...
Starts the real-time engine that captures tasks.
def delete(self): 'Delete this file and return the new, deleted JFSFile' r = self.jfs.post(url=self.path, params={'dl':'true'}) return r
Delete this file and return the new, deleted JFSFile
def parse_file(infile, exit_on_error=True): try: a, b, mag = np.atleast_2d( np.genfromtxt( infile, usecols=[0, 1, 2], delimiter=',' ...
Parse a comma-separated file with columns "ra,dec,magnitude".
def windowed_iterable(self): effective_offset = max(0,self.item_view.iterable_index) for i,item in enumerate(self.iterable): if i<effective_offset: continue elif i>=(effective_offset+self.item_view.iterable_fetch_size): return yield ite...
That returns only the window
def focused_data_item(self) -> typing.Optional[DataItem.DataItem]: return self.__focused_display_item.data_item if self.__focused_display_item else None
Return the data item with keyboard focus.
def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None): ensure_directories(mount_point, lower_dir, upper_dir) if not mount_table: mount_table = MountTable.load() if mount_table.is_mounted(mount_point): raise AlreadyMounted() options = "rw,lowerdir=%s,...
Execute the mount. This requires root
def _get_on_demand_syllabus(self, class_name): url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format( class_name=class_name) page = get_page(self._session, url) logging.debug('Downloaded %s (%d bytes)', url, len(page)) return page
Get the on-demand course listing webpage.
def write_capability_list(self, capabilities=None, outfile=None, links=None): capl = CapabilityList(ln=links) capl.pretty_xml = self.pretty_xml if (capabilities is not None): for name in capabilities.keys(): capl.add_capability(name=name,...
Write a Capability List to outfile or STDOUT.
def cli(config_path, verbose): global config, store if not config_path: config_path = '/etc/record_recommender.yml' config = get_config(config_path) setup_logging(config) store = FileStore(config)
Record-Recommender command line version.
def open(self, auto_commit=None, schema=None): if schema is None: schema = self.schema ac = auto_commit if auto_commit is not None else schema.auto_commit exe = ExecutionContext(self.path, schema=schema, auto_commit=ac) if not os.path.isfile(self.path) or os.path.getsize(self...
Create a context to execute queries
def create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs): cls.validate(data) inst = cls(api_key=api_key) endpoint = '' return inst.request('POST', endpoint=endpoint, data=data, ...
Create an event on your PagerDuty account.
def template_to_text(tmpl, debug=0): tarr = [] for item in tmpl.itertext(): tarr.append(item) text = "{{%s}}" % "|".join(tarr).strip() if debug > 1: print("+ template_to_text:") print(" %s" % text) return text
convert parse tree template to text
def delete_policy(self, pol_id): if pol_id not in self.policies: LOG.error("Invalid policy %s", pol_id) return del self.policies[pol_id] self.policy_cnt -= 1
Deletes the policy from the local dictionary.
def sbo_list(): sbo_packages = [] for pkg in os.listdir(_meta_.pkg_path): if pkg.endswith("_SBo"): sbo_packages.append(pkg) return sbo_packages
Return all SBo packages
def bech32_polymod(values): generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] chk = 1 for value in values: top = chk >> 25 chk = (chk & 0x1ffffff) << 5 ^ value for i in range(5): chk ^= generator[i] if ((top >> i) & 1) else 0 return chk
Internal function that computes the Bech32 checksum.
def process_format(self, kind, context): result = None while True: chunk = yield result if chunk is None: return split = -1 line = chunk.line try: ast.parse(line) except SyntaxError as e: split = line.rfind(' ', 0, e.offset) result = chunk.clone(line='_bless(' + line[:split].rstrip(...
Handle transforming format string + arguments into Python code.
def _parse_service_env_vars(self, env_vars): env = {} for var in env_vars: k, v = var.split('=') env.update({k: v}) return env
Return a dict based on `key=value` pair strings.
def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False): self.searchString = searchString self.category = category self.math = math self.game = game self.searchFiles = searchFiles self.extension = extension
Call this function with all the settings to use for future operations on a repository, must be called FIRST
def locale_escape(string, errors='replace'): encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
Mangle non-supported characters, for savages with ascii terminals.
def compute(self): self._compute_window_size() smooth = [] residual = [] x, y = self.x, self.y self._update_values_in_window() self._update_mean_in_window() self._update_variance_in_window() for i, (xi, yi) in enumerate(zip(x, y)): if ((i - sel...
Perform the smoothing operations.
def resource_urls(request): url_parsed = urlparse(settings.SEARCH_URL) defaults = dict( APP_NAME=__description__, APP_VERSION=__version__, SITE_URL=settings.SITE_URL.rstrip('/'), SEARCH_TYPE=settings.SEARCH_TYPE, SEARCH_URL=settings.SEARCH_URL, SEARCH_IP='%s://%s:...
Global values to pass to templates
def find(self, path, all=False): try: start, _, extn = path.rsplit('.', 2) except ValueError: return [] path = '.'.join((start, extn)) return find(path, all=all) or []
Work out the uncached name of the file and look that up instead
def _is_valid_id(self, inpt): from dlkit.abstract_osid.id.primitives import Id as abc_id if isinstance(inpt, abc_id): return True else: return False
Checks if input is a valid Id
def workbook_data(self): document = XML( fn=os.path.splitext(self.fn)[0]+'.xml', root=Element.workbook()) shared_strings = [ str(t.text) for t in self.xml('xl/sharedStrings.xml') .root.xpath(".//xl:t", namespaces=self.NS)] for key...
return a readable XML form of the data.
def _get_manifest_list(self, image): if image in self.manifest_list_cache: return self.manifest_list_cache[image] manifest_list = get_manifest_list(image, image.registry, insecure=self.parent_registry_insecure, ...
try to figure out manifest list
def created_slices(self, user_id=None): if not user_id: user_id = g.user.id Slice = models.Slice qry = ( db.session.query(Slice) .filter( sqla.or_( Slice.created_by_fk == user_id, Slice.changed_by_fk == u...
List of slices created by this user
def regions(self): url = "%s/regions" % self.root params = {"f": "json"} return self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
gets the regions value
def consume_queue(queue, cascade_stop): while True: try: item = queue.get(timeout=0.1) except Empty: yield None continue except thread.error: raise ShutdownException() if item.exc: raise item.exc if item.is_stop: ...
Consume the queue by reading lines off of it and yielding them.
def natsorted(seq, cmp=natcmp): "Returns a copy of seq, sorted by natural string sort." import copy temp = copy.copy(seq) natsort(temp, cmp) return temp
Returns a copy of seq, sorted by natural string sort.
def shape(self): try: return self.__shape except AttributeError: shape = tuple(len(vec) for vec in self.coord_vectors) self.__shape = shape return shape
Number of grid points per axis.
def tcp_server(tcp_addr, settings): family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) sock.bind(tcp_addr) sock.listen(1) logging.info("Waiting for connection on %s", tcp_addr) conn, addr = sock.accept() logging.info("Acc...
Start up the tcp server, send the settings.
def dry(self, *args, **kwargs): return 'Would have executed:\n%s%s' % ( self.name, Args(self.spec).explain(*args, **kwargs))
Perform a dry-run of the task
def stop_video_recording(self): self.runner.info_log("Stopping video recording...") self.execute_command("./stop_recording.sh") sleep(5) self.scp_file_remote_to_local( self.remote_video_recording_file_path, self.local_video_recording_file_path )
Stop the video recording
def asyncStarMap(asyncCallable, iterable): deferreds = starmap(asyncCallable, iterable) return gatherResults(deferreds, consumeErrors=True)
itertools.starmap for deferred callables
def save(self, *args, **kwargs): if self.created is None: self.created = tz_now() if self.modified is None: self.modified = self.created super(Thread, self).save(*args, **kwargs)
Fill 'created' and 'modified' attributes on first create
def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str]: if fields == ALL: fields = allowed_fields.keys() else: fields = tuple(fields) unknown_fields = set(fields) - allowed_fields.keys() if unknown_fields: raise ValueError('Unknown fields: {}'.f...
Clean lookup fields and check for errors.
def validateFilepath( self ): if ( not self.isValidated() ): return valid = self.isValid() if ( not valid ): fg = self.invalidForeground() bg = self.invalidBackground() else: fg = self.validForeground() bg = self.validBackground...
Alters the color scheme based on the validation settings.
def topic_path(cls, project, topic): return google.api_core.path_template.expand( "projects/{project}/topics/{topic}", project=project, topic=topic )
Return a fully-qualified topic string.
def np2model_tensor(a): "Tranform numpy array `a` to a tensor of the same type." dtype = model_type(a.dtype) res = as_tensor(a) if not dtype: return res return res.type(dtype)
Tranform numpy array `a` to a tensor of the same type.
def And(*args: Union[Bool, bool]) -> Bool: union = [] args_list = [arg if isinstance(arg, Bool) else Bool(arg) for arg in args] for arg in args_list: union.append(arg.annotations) return Bool(z3.And([a.raw for a in args_list]), union)
Create an And expression.
def queue_resize(self): self._children_resize_queued = True parent = getattr(self, "parent", None) if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"): parent.queue_resize()
request the element to re-check it's child sprite sizes
def client_list_entries_multi_project( client, to_delete ): PROJECT_IDS = ["one-project", "another-project"] for entry in client.list_entries(project_ids=PROJECT_IDS): do_something_with(entry)
List entries via client across multiple projects.
def strict_logical(self, value): if value is not None: if not isinstance(value, bool): raise TypeError( 'f90nml: error: strict_logical must be a logical value.') else: self._strict_logical = value
Validate and set the strict logical flag.
def _distance_stats_sqr_fast_generic(x, y, dcov_function): covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denominator_sqr = np.absolute(denominator_sqr_signed) denominator ...
Compute the distance stats using the fast algorithm.
def save(self, resq=None): if not resq: resq = ResQ() data = { 'failed_at' : datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), 'payload' : self._payload, 'exception' : self._exception.__class__.__name__, 'error' : self._parse_message...
Saves the failed Job into a "failed" Redis queue preserving all its original enqueud info.
def google_get_data(self, config, response): params = { 'access_token': response['access_token'], } payload = urlencode(params) url = self.google_api_url + 'userinfo?' + payload req = Request(url) json_str = urlopen(req).read() return json.loads(json_s...
Make request to Google API to get profile data for the user.
def contains_circle(self, pt, radius): return (self.l < pt.x - radius and self.r > pt.x + radius and self.t < pt.y - radius and self.b > pt.y + radius)
Is the circle completely inside this rect?
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None): if not isinstance(string, str): string = str(string) if rgb is None and ansi is None: raise TerminalColorMapException( 'colorize: must specify one named parameter: rgb or ansi') if rgb...
Returns the colored string
def to_json(self, *args, **kwargs): return json.dumps(self.serialize(), *args, **kwargs)
Convert Entity to JSON.
def contains_one_of(*fields): message = 'Must contain any one of the following fields: {0}'.format(', '.join(fields)) def check_contains(endpoint_fields): for field in fields: if field in endpoint_fields: return errors = {} for field in fields: err...
Enables ensuring that one of multiple optional fields is set
def publish(self, distribution, storage=""): try: return self._publishes[distribution] except KeyError: self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.storage)) return self._publishes[distribution]
Get or create publish
def _explain(self, tree): self._explaining = True self._call_list = [] old_call = self.connection.call def fake_call(command, **kwargs): if command == "describe_table": return old_call(command, **kwargs) self._call_list.append((command, kwargs)) ...
Set up the engine to do a dry run of a query
def create(pid_type, pid_value, status, object_type, object_uuid): from .models import PersistentIdentifier if bool(object_type) ^ bool(object_uuid): raise click.BadParameter('Speficy both or any of --type and --uuid.') new_pid = PersistentIdentifier.create( pid_type, pid_value, ...
Create new persistent identifier.
def disable_hidden_api_blacklist(self): version_codename = self._ad.adb.getprop('ro.build.version.codename') sdk_version = int(self._ad.adb.getprop('ro.build.version.sdk')) if self._ad.is_rootable and (sdk_version >= 28 or version_codename == 'P'): ...
If necessary and possible, disables hidden api blacklist.
def reload(self): pid = self._read_pidfile() if pid is None or pid != os.getpid(): raise DaemonError( 'Daemon.reload() should only be called by the daemon process ' 'itself') new_environ = os.environ.copy() new_environ['DAEMONOCLE_RELOAD'] = 't...
Make the daemon reload itself.
def _save_settings(self): if self._autosettings_path == None: return gui_settings_dir = _os.path.join(_cwd, 'egg_settings') if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir) path = _os.path.join(gui_settings_dir, self._autosettings_path) settings = _g.QtCore.Q...
Saves all the parameters to a text file.
def append(self, child): if not (isinstance(child, CP2KSection) or isinstance(child, CP2KKeyword)): raise TypeError("The child must be a CP2KSection or a CP2KKeyword, got: %s." % child) l = self.__index.setdefault(child.name, []) l.append(child) self.__order.append(child)
Add a child section or keyword
def mean_se(series, mult=1): m = np.mean(series) se = mult * np.sqrt(np.var(series) / len(series)) return pd.DataFrame({'y': [m], 'ymin': m-se, 'ymax': m+se})
Calculate mean and standard errors on either side
def uninitialize(cls) -> None: if not cls._initialized: return signal.signal(signal.SIGCHLD, cls._old_sigchld) cls._initialized = False
Removes the ``SIGCHLD`` handler.
async def upcoming(self, details: bool = False) -> list: endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get', endpoint) return data[key]
Return watering statistics for the next 6 days.
def _parse_date_input(date_input, default_offset=0): if date_input: try: return parse_date_input(date_input) except ValueError as err: raise CommandError(force_text(err)) else: return get_midnight() - timedelta(days=default_offset)
Parses a date input.
def pandoc_process(app, what, name, obj, options, lines): if not lines: return None input_format = app.config.mkdsupport_use_parser output_format = 'rst' text = SEP.join(lines) text = pypandoc.convert_text(text, output_format, format=input_format) del lines[:] lines.extend(text.split...
Convert docstrings in Markdown into reStructureText using pandoc
def _get(self, q, params=''): if (q[-1] == '/'): q = q[:-1] headers = {'Content-Type': 'application/json'} r = requests.get('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params), headers=headers) ret = DotDict(r.json()) ...
Generic GET wrapper including the api_key
def close(self): "Stop the output stream, but further download will still perform" if self.stream: self.stream.close(self.scheduler) self.stream = None
Stop the output stream, but further download will still perform
def numpy_to_texture(image): if not isinstance(image, np.ndarray): raise TypeError('Unknown input type ({})'.format(type(image))) if image.ndim != 3 or image.shape[2] != 3: raise AssertionError('Input image must be nn by nm by RGB') grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1)...
Convert a NumPy image array to a vtk.vtkTexture
def load(cls, keys): conversations = [] for key in keys: conversation = unitdata.kv().get(key) if conversation: conversations.append(cls.deserialize(conversation)) return conversations
Load a set of conversations by their keys.
def s3_get(url: str, temp_file: IO) -> None: s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
Pull a file directly from S3.
def pull_from_origin(repo_path): LOG.info("Pulling from origin at %s." % repo_path) command = GIT_PULL_CMD.format(repo_path) resp = envoy.run(command) if resp.status_code != 0: LOG.exception("Pull failed.") raise GitException(resp.std_err) else: LOG.info("Pull successful.")
Execute 'git pull' at the provided repo_path.
def _change_volume(self, increase): sign = "+" if increase else "-" delta = "%d%%%s" % (self.volume_tick, sign) self._run(["amixer", "-q", "sset", "Master", delta])
Change volume using amixer
def saveProfile( self ): manager = self.parent() prof = manager.currentProfile() save_prof = manager.viewWidget().saveProfile() prof.setXmlElement(save_prof.xmlElement())
Saves the current profile to the current settings from the view widget.
async def async_discovery(session): bridges = [] response = await async_request(session.get, URL_DISCOVER) if not response: _LOGGER.info("No discoverable bridges available.") return bridges for bridge in response: bridges.append({'bridgeid': bridge['id'], ...
Find bridges allowing gateway discovery.
def _getTypename(self, defn): return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'
Returns the SQL typename required to store the given FieldDefinition
def raise_msg_to_str(msg): if not is_string_like(msg): msg = '\n'.join(map(str, msg)) return msg
msg is a return arg from a raise. Join with new lines
def main(): options = handle_options() elecs, d_obs = readin_volt(options.d_obs) elecs, d_est = readin_volt(options.d_est) elecs, d_estTC = readin_volt(options.d_estTC) volt_corr = calc_correction(d_obs, d_est, d_estTC, ...
Function to remove temperature effect from field data
def read_epilogue(self): with open(self.filename, "rb") as fp_: fp_.seek(self.mda['total_header_length']) data = np.fromfile(fp_, dtype=hrit_epilogue, count=1) self.epilogue.update(recarray2dict(data))
Read the epilogue metadata.
def _merge_cluster(old, new): logger.debug("_merge_cluster: %s to %s" % (old.id, new.id)) logger.debug("_merge_cluster: add idls %s" % old.loci2seq.keys()) for idl in old.loci2seq: new.add_id_member(old.loci2seq[idl], idl) return new
merge one cluster to another
def create(self): data = self._node_data() data["node_id"] = self._id if self._node_type == "docker": timeout = None else: timeout = 1200 trial = 0 while trial != 6: try: response = yield from self._compute.post("/projec...
Create the node on the compute server
def resume(self, data): 'Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object' if not hasattr(data, 'read'): data = six.BytesIO(data) if self.size == -1: log.debug('%r is an incomplete file, but .size is unknown. Refreshing...
Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object
def GetUnreachableHosts(hostnames, ssh_key): ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_hostnames = [host for (host, ssh_ok) in zip(hostnames, ssh_status) if not ssh_ok] return nonresponsive_hostnames
Returns list of hosts unreachable via ssh.
def server_list_min(self): nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: ...
List minimal information about servers
def poll_for_server_running(job_id): sys.stdout.write('Waiting for server in {0} to initialize ...'.format(job_id)) sys.stdout.flush() desc = dxpy.describe(job_id) while(SERVER_READY_TAG not in desc['tags'] and desc['state'] != 'failed'): time.sleep(SLEEP_PERIOD) sys.stdout.write('.') ...
Poll for the job to start running and post the SERVER_READY_TAG.
def application_unauthenticated(request, token, state=None, label=None): application = base.get_application(secret_token=token) if application.expires < datetime.datetime.now(): return render( template_name='kgapplications/common_expired.html', context={'application': application...
An somebody is trying to access an application.
def _encode_mapping(name, value, check_keys, opts): data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
Encode a mapping type.
def clean_docstring(docstring): docstring = docstring.strip() if '\n' in docstring: if docstring[0].isspace(): return textwrap.dedent(docstring) else: first, _, rest = docstring.partition('\n') return first + '\n' + textwrap.dedent(rest) return docstring
Dedent docstring, special casing the first line.
def _skip(options): values = [options.missing_direct_deps, options.unnecessary_deps] return all(v == 'off' for v in values)
Return true if the task should be entirely skipped, and thus have no product requirements.
def close(self): if self.read_option('save_pointer'): self._update_last_pointer() super(S3Writer, self).close()
Called to clean all possible tmp files created during the process.
def shutdown(self) -> None: self._is_handshake_completed = False try: self._flush_ssl_engine() except IOError: pass try: self._ssl.shutdown() except OpenSSLError as e: if 'SSL_shutdown:uninitialized' not in str(e) and 'shutdown whil...
Close the TLS connection and the underlying network socket.
def verifymessage(self, address, signature, message): return self.req("verifymessage", [address, signature, message])
Verify a signed message.
def tar_and_copy_usr_dir(usr_dir, train_dir): tf.logging.info("Tarring and pushing t2t_usr_dir.") usr_dir = os.path.abspath(os.path.expanduser(usr_dir)) top_dir = os.path.join(tempfile.gettempdir(), "t2t_usr_container") tmp_usr_dir = os.path.join(top_dir, usr_dir_lib.INTERNAL_USR_DIR_PACKAGE) shutil.rmtree(to...
Package, tar, and copy usr_dir to GCS train_dir.
def file_length(in_file): fid = open(in_file) data = fid.readlines() fid.close() return len(data)
Function to return the length of a file.
def scoped_connection(func): def _with(series, *args, **kwargs): connection = None try: connection = series._connection() return func(series, connection, *args, **kwargs) finally: series._return( connection ) return _with
Decorator that gives out connections.
def rar3_type(btype): if btype < rf.RAR_BLOCK_MARK or btype > rf.RAR_BLOCK_ENDARC: return "*UNKNOWN*" return block_strs[btype - rf.RAR_BLOCK_MARK]
RAR3 type code as string.