code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def create_video_transcript(video_id, language_code, file_format, content, provider=TranscriptProviderType.CUSTOM):
transcript_serializer = TranscriptSerializer(
data=dict(provider=provider, language_code=language_code, file_format=file_format),
context=dict(video_id=video_id),
)
if transcri... | Create a video transcript.
Arguments:
video_id(unicode): An Id identifying the Video data model object.
language_code(unicode): A language code.
file_format(unicode): Transcript file format.
content(InMemoryUploadedFile): Transcript content.
provider(unicode): Transcript pro... |
def submit(self):
u = urlparse(self.url)
if not self.action:
self.action = self.url
elif self.action == u.path:
self.action = self.url
else:
if not u.netloc in self.action:
path = "/".join(u.path.split("/")[1:-1])
if sel... | Posts the form's data and returns the resulting Page
Returns
Page - The resulting page |
def mdownload(args):
from jcvi.apps.grid import Jobs
p = OptionParser(mdownload.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
linksfile, = args
links = [(x.strip(),) for x in open(linksfile)]
j = Jobs(download, links)
j.run() | %prog mdownload links.txt
Multiple download a list of files. Use formats.html.links() to extract the
links file. |
def load_file(self, filename):
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) | Read in file contents and set the current string. |
def delete_params_s(s, params):
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params)
return re.sub(patt, '', '\n' + s.strip() + '\n').strip() | Delete the given parameters from a string
Same as :meth:`delete_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters section
params: list of str
The names of the parameters to delete
... |
def iterkeys(self):
def _iterkeys(bin):
for item in bin:
yield item.key
for bin in self.bins:
yield _iterkeys(bin) | An iterator over the keys of each bin. |
def removeOntology(self, ontology):
q = models.Ontology.delete().where(id == ontology.getId())
q.execute() | Removes the specified ontology term map from this repository. |
def get_job_info(current_job):
trials = TrialRecord.objects.filter(job_id=current_job.job_id)
total_num = len(trials)
running_num = sum(t.trial_status == Trial.RUNNING for t in trials)
success_num = sum(t.trial_status == Trial.TERMINATED for t in trials)
failed_num = sum(t.trial_status == Trial.ERRO... | Get job information for current job. |
def get_decomp_and_e_above_hull(self, entry, allow_negative=False):
if entry in self.stable_entries:
return {entry: 1}, 0
comp = entry.composition
facet, simplex = self._get_facet_and_simplex(comp)
decomp_amts = simplex.bary_coords(self.pd_coords(comp))
decomp = {self... | Provides the decomposition and energy above convex hull for an entry.
Due to caching, can be much faster if entries with the same composition
are processed together.
Args:
entry: A PDEntry like object
allow_negative: Whether to allow negative e_above_hulls. Used to
... |
def upload_object(self, instance, bucket_name, object_name, file_obj,
content_type=None):
url = '/buckets/{}/{}/{}'.format(instance, bucket_name, object_name)
with open(file_obj, 'rb') as f:
if content_type:
files = {object_name: (object_name, f, content... | Upload an object to a bucket.
:param str instance: A Yamcs instance name.
:param str bucket_name: The name of the bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content t... |
def odometry2Pose3D(odom):
pose = Pose3d()
ori = odom.pose.pose.orientation
pose.x = odom.pose.pose.position.x
pose.y = odom.pose.pose.position.y
pose.z = odom.pose.pose.position.z
pose.yaw = quat2Yaw(ori.w, ori.x, ori.y, ori.z)
pose.pitch = quat2Pitch(ori.w, ori.x, ori.y, ori.z)
pose.ro... | Translates from ROS Odometry to JderobotTypes Pose3d.
@param odom: ROS Odometry to translate
@type odom: Odometry
@return a Pose3d translated from odom |
def _parse_nodes_section(f, current_section, nodes):
section = {}
dimensions = None
if current_section == 'NODE_COORD_SECTION':
dimensions = 3
elif current_section == 'DEMAND_SECTION':
dimensions = 2
else:
raise ParseException('Invalid section {}'.format(current_section))
... | Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f
Returns a dict containing the node as key |
def raster_to_projection_coords(self, pixel_x, pixel_y):
h_px_py = np.array([1, pixel_x, pixel_y])
gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]])
arr = np.inner(gt, h_px_py)
return arr[2], arr[1] | Use pixel centers when appropriate.
See documentation for the GDAL function GetGeoTransform for details. |
def _j9SaveCurrent(sDir = '.'):
dname = os.path.normpath(sDir + '/' + datetime.datetime.now().strftime("%Y-%m-%d_J9_AbbreviationDocs"))
if not os.path.isdir(dname):
os.mkdir(dname)
os.chdir(dname)
else:
os.chdir(dname)
for urlID, urlString in j9urlGenerator(nameDict = True).item... | Downloads and saves all the webpages
For Backend |
def get_series_episodes(self, id, page=1):
params = {'page': page}
r = self.session.get(self.base_url + '/series/{}/episodes'.format(id), params=params)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json() | Get series episodes |
def info(self, abspath=True):
logger.debug(str(''))
return self._call_and_parse(['info', '--json'], abspath=abspath) | Return a dictionary with configuration information.
No guarantee is made about which keys exist. Therefore this function
should only be used for testing and debugging. |
def usearch_cluster_error_correction(
fasta_filepath,
output_filepath=None,
output_uc_filepath=None,
percent_id_err=0.97,
sizein=True,
sizeout=True,
w=64,
slots=16769023,
maxrejects=64,
log_name="usearch_cluster_err_corrected.log",
... | Cluster for err. correction at percent_id_err, output consensus fasta
fasta_filepath = input fasta file, generally a dereplicated fasta
output_filepath = output error corrected fasta filepath
percent_id_err = minimum identity percent.
sizein = not defined in usearch helpstring
sizeout = not defined... |
def render_to_response(self, template_name, __data,
content_type="text/html"):
resp = self.render(template_name, __data)
return Response(resp,
content_type=content_type) | Given a template name and template data.
Renders a template and returns `webob.Response` object |
def get_comments_of_confirmation_per_page(self, confirmation_id, per_page=1000, page=1):
return self._get_resource_per_page(
resource=CONFIRMATION_COMMENTS,
per_page=per_page,
page=page,
params={'confirmation_id': confirmation_id},
) | Get comments of confirmation per page
:param confirmation_id: the confirmation id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list |
def on_new_line(self):
self.set_cursor_position('eof')
self.current_prompt_pos = self.get_position('cursor')
self.new_input_line = False | On new input line |
def compute_ecc_hash(ecc_manager, hasher, buf, max_block_size, rate, message_size=None, as_string=False):
result = []
if not message_size:
ecc_params = compute_ecc_params(max_block_size, rate, hasher)
message_size = ecc_params["message_size"]
for i in xrange(0, len(buf), message_size):
... | Split a string in blocks given max_block_size and compute the hash and ecc for each block, and then return a nice list with both for easy processing. |
def context_list_users(zap_helper, context_name):
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for th... | List the users available for a given context. |
def add_job_from_json(self, job_json, destructive=False):
logger.debug('Importing job from JSON document: {0}'.format(job_json))
rec = self.backend.decode_import_json(job_json)
if destructive:
try:
self.delete_job(rec['name'])
except DagobahError:
... | Construct a new Job from an imported JSON spec. |
def get_last_lineno(node):
max_lineno = 0
if hasattr(node, "lineno"):
max_lineno = node.lineno
for _, field in ast.iter_fields(node):
if isinstance(field, list):
for value in field:
if isinstance(value, ast.AST):
max_lineno = max(max_lineno, ge... | Recursively find the last line number of the ast node. |
def drain(iterable):
if getattr(iterable, "popleft", False):
def next_item(coll):
return coll.popleft()
elif getattr(iterable, "popitem", False):
def next_item(coll):
return coll.popitem()
else:
def next_item(coll):
return coll.pop()
while True... | Helper method that empties an iterable as it is iterated over.
Works for:
* ``dict``
* ``collections.deque``
* ``list``
* ``set`` |
def has_changed (filename):
key = os.path.abspath(filename)
mtime = get_mtime(key)
if key not in _mtime_cache:
_mtime_cache[key] = mtime
return True
return mtime > _mtime_cache[key] | Check if filename has changed since the last check. If this
is the first check, assume the file is changed. |
def load_entry_points(self):
if self.entry_point_group:
task_packages = {}
for item in pkg_resources.iter_entry_points(
group=self.entry_point_group):
try:
pkg, related_name = item.module_name.rsplit('.', 1)
except V... | Load tasks from entry points. |
def _get_jvm_opts(out_file, data):
resources = config_utils.get_resources("purple", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx3500m"])
jvm_opts = config_utils.adjust_opts(jvm_opts, {"algorithm": {"memory_adjust":
{... | Retrieve Java options, adjusting memory for available cores. |
def __json(self):
if self.exclude_list is None:
self.exclude_list = []
fields = {}
for key, item in vars(self).items():
if hasattr(self, '_sa_instance_state'):
if len(orm.attributes.instance_state(self).unloaded) > 0:
mapper = in... | Using the exclude lists, convert fields to a string. |
def _TemplateExists(unused_value, context, args):
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | Returns whether the given name is in the current Template's template group. |
def read_comment(self, start: int, line: int, col: int, prev: Token) -> Token:
body = self.source.body
body_length = len(body)
position = start
while True:
position += 1
if position > body_length:
break
char = body[position]
... | Read a comment token from the source file. |
def create(**data):
http_client = HttpClient()
response, _ = http_client.post(routes.url(routes.PAYMENT_RESOURCE), data)
return resources.Payment(**response) | Create a Payment request.
:param data: data required to create the payment
:return: The payment resource
:rtype resources.Payment |
def related_obj_to_dict(obj, **kwargs):
kwargs.pop('formatter', None)
suppress_private_attr = kwargs.get("suppress_private_attr", False)
suppress_empty_values = kwargs.get("suppress_empty_values", False)
attrs = fields(obj.__class__)
return_dict = kwargs.get("dict_factory", OrderedDict)()
for a ... | Covert a known related object to a dictionary. |
def protocol_str(protocol):
if protocol == const.PROTOCOL_MRP:
return 'MRP'
if protocol == const.PROTOCOL_DMAP:
return 'DMAP'
if protocol == const.PROTOCOL_AIRPLAY:
return 'AirPlay'
return 'Unknown' | Convert internal API protocol to string. |
def _cellrepr(value, allow_formulas):
if pd.isnull(value) is True:
return ""
if isinstance(value, float):
value = repr(value)
else:
value = str(value)
if (not allow_formulas) and value.startswith('='):
value = "'%s" % value
return value | Get a string representation of dataframe value.
:param :value: the value to represent
:param :allow_formulas: if True, allow values starting with '='
to be interpreted as formulas; otherwise, escape
them with an apostrophe to avoid formula interpretation. |
def clean_title(title):
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
t... | Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces. |
def _secret_yaml(loader, node):
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fn... | Load secrets and embed it into the configuration YAML. |
def decimal(self, var, default=NOTSET, force=True):
return self._get(var, default=default, cast=Decimal, force=force) | Convenience method for casting to a decimal.Decimal
Note:
Casting |
def error(self, reason=None):
self.set_status(Report.ERROR)
if reason:
self.add('reason', reason) | Set the test status to Report.ERROR, and set the error reason
:param reason: error reason (default: None) |
def authenticate(self, username=None, password=None):
u = self.username
p = self.password
if username and password:
u = username
p = password
client = self.client()
query = client.authenticated_query(username=u, password=p)
res = client.post(query)... | Test the authentication credentials
Raises a ``ValueError`` if there is a problem authenticating
with the human readable reason given by the institution.
:param username: optional username (use self.username by default)
:type username: string or None
:param password: optional p... |
def slices(src_path):
pages = list_slices(src_path)
slices = []
for page in pages:
slices.extend(page.slices)
return slices | Return slices as a flat list |
def _get_all_policy_ids(zap_helper):
policies = zap_helper.zap.ascan.policies()
return [p['id'] for p in policies] | Get all policy IDs. |
def set_defaults(self):
for key, val in self.c_default.items():
self._dict[key] = val | Based on specification set a parameters value to the default value. |
def _format_method_nodes(self, task_method, modulename, classname):
methodname = task_method.__name__
fullname = '.'.join((modulename, classname, methodname))
signature = Signature(task_method, bound_method=True)
desc_sig_node = self._format_signature(
signature, modulename, ... | Create a ``desc`` node summarizing a method docstring. |
def sortByColumn(self, index):
if self.sort_old == [None]:
self.header_class.setSortIndicatorShown(True)
sort_order = self.header_class.sortIndicatorOrder()
self.sig_sort_by_column.emit()
if not self.model().sort(index, sort_order):
if len(self.sort_old) != ... | Implement a column sort. |
def buildASNList(rootnames, asnname, check_for_duplicates=True):
filelist, duplicates = checkForDuplicateInputs(rootnames)
if check_for_duplicates and duplicates:
origasn = changeSuffixinASN(asnname, 'flt')
dupasn = changeSuffixinASN(asnname, 'flc')
errstr = 'ERROR:\nMultiple valid input... | Return the list of filenames for a given set of rootnames |
def spearmanr(self, target, correlation_length, mask=NotSpecified):
from .statistical import RollingSpearman
return RollingSpearman(
base_factor=self,
target=target,
correlation_length=correlation_length,
mask=mask,
) | Construct a new Factor that computes rolling spearman rank correlation
coefficients between `target` and the columns of `self`.
This method can only be called on factors which are deemed safe for use
as inputs to other factors. This includes `Returns` and any factors
created from `Facto... |
def chain(*steps):
if not steps:
return
def on_done(sprite=None):
chain(*steps[2:])
obj, params = steps[:2]
if len(steps) > 2:
params['on_complete'] = on_done
if callable(obj):
obj(**params)
else:
obj.animate(**params) | chains the given list of functions and object animations into a callback string.
Expects an interlaced list of object and params, something like:
object, {params},
callable, {params},
object, {},
object, {params}
Assumes that all callees accept on_complete na... |
def find(self, name, current_location):
assert isinstance(name, basestring)
assert isinstance(current_location, basestring)
project_module = None
if name[0] == '/':
project_module = self.id2module.get(name)
if not project_module:
location = os.path.join(cu... | Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found. |
def vn(x):
if x == []:
return None
if isinstance(x, list):
return '|'.join(x)
if isinstance(x, datetime):
return x.isoformat()
return x | value or none, returns none if x is an empty list |
async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
... | Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process.... |
def insert_row(self, index, row):
row = self._validate_row(row)
row_obj = RowData(self, row)
self._table.insert(index, row_obj) | Insert a row before index in the table.
Parameters
----------
index : int
List index rules apply
row : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `row` is not an iterable.
ValueError:
... |
def no_auth(self):
old_basic_auth, self.auth = self.auth, None
old_token_auth = self.headers.pop('Authorization', None)
yield
self.auth = old_basic_auth
if old_token_auth:
self.headers['Authorization'] = old_token_auth | Unset authentication temporarily as a context manager. |
def evolve(self, years):
world_file = fldr + os.sep + self.name + '.txt'
self.build_base()
self.world.add_mountains()
self.add_life()
self.world.grd.save(world_file)
print('TODO - run ' + str(years) + ' years') | run the evolution of the planet to see how it looks
after 'years' |
def _dump_multipoint(obj, big_endian, meta):
coords = obj['coordinates']
vertex = coords[0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiPoint', num_dims, big_endian, meta
)
point_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Point']
if b... | Dump a GeoJSON-like `dict` to a multipoint WKB string.
Input parameters and output are similar to :funct:`_dump_point`. |
def find_paths_breadth_first(from_target, to_target, log):
log.debug('Looking for all paths from {} to {}'.format(from_target.address.reference(),
to_target.address.reference()))
if from_target == to_target:
yield [from_target]
return
visited_edges ... | Yields the paths between from_target to to_target if they exist.
The paths are returned ordered by length, shortest first.
If there are cycles, it checks visited edges to prevent recrossing them. |
def list_entitlements(owner, repo, page, page_size, show_tokens):
client = get_entitlements_api()
with catch_raise_api_exception():
data, _, headers = client.entitlements_list_with_http_info(
owner=owner,
repo=repo,
page=page,
page_size=page_size,
... | Get a list of entitlements on a repository. |
def basename(path: Optional[str]) -> Optional[str]:
if path is not None:
return os.path.basename(path) | Returns the final component of a pathname and None if the argument is None |
def get_new_session(self):
session = Session()
session.headers = self.headers
session.proxies = self._get_request_proxies()
return session | Returns a new session using the object's proxies and headers |
def get_registration_fields(xmlstream,
timeout=60,
):
iq = aioxmpp.IQ(
to=aioxmpp.JID.fromstr(xmlstream._to),
type_=aioxmpp.IQType.GET,
payload=xso.Query()
)
iq.autoset_id()
reply = yield from aioxmpp.protocol.send_and_wait_... | A query is sent to the server to obtain the fields that need to be
filled to register with the server.
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum ti... |
def _update_frozencell(self, frozen):
toggle_state = frozen is not False
self.ToggleTool(wx.FONTFLAG_MASK, toggle_state) | Updates frozen cell widget
Parameters
----------
frozen: Bool or string
\tUntoggled iif False |
def read_magic_file(self, path, sort_by_this_name):
DATA = {}
try:
with open(path, 'r') as finput:
lines = list(finput.readlines()[1:])
except FileNotFoundError:
return []
line = lines[0]
header = line.strip('\n').split('\t')
error_... | reads a magic formated data file from path and sorts the keys
according to sort_by_this_name
Parameters
----------
path : path to file to read
sort_by_this_name : variable to sort data by |
def remove_template(self, tpl):
try:
del self.templates[tpl.uuid]
except KeyError:
pass
self.unindex_template(tpl) | Removes and un-index a template from the `templates` container.
:param tpl: The template to remove
:type tpl: alignak.objects.item.Item
:return: None |
def open_netcdf_reader(self, flatten=False, isolate=False, timeaxis=1):
self._netcdf_reader = netcdftools.NetCDFInterface(
flatten=bool(flatten),
isolate=bool(isolate),
timeaxis=int(timeaxis)) | Prepare a new |NetCDFInterface| object for reading data. |
def wirevector_subset(self, cls=None, exclude=tuple()):
if cls is None:
initial_set = self.wirevector_set
else:
initial_set = (x for x in self.wirevector_set if isinstance(x, cls))
if exclude == tuple():
return set(initial_set)
else:
return... | Return set of wirevectors, filtered by the type or tuple of types provided as cls.
If no cls is specified, the full set of wirevectors associated with the Block are
returned. If cls is a single type, or a tuple of types, only those wirevectors of
the matching types will be returned. This is h... |
def process(self, checksum, revision=None):
revert = None
if checksum in self:
reverteds = list(self.up_to(checksum))
if len(reverteds) > 0:
revert = Revert(revision, reverteds, self[checksum])
self.insert(checksum, revision)
return revert | Process a new revision and detect a revert if it occurred. Note that
you can pass whatever you like as `revision` and it will be returned in
the case that a revert occurs.
:Parameters:
checksum : str
Any identity-machable string-based hash of revision content
... |
def get_monkeypatched_pathset(self):
from pip_shims.shims import InstallRequirement
uninstall_path = InstallRequirement.__module__.replace(
"req_install", "req_uninstall"
)
req_uninstall = self.safe_import(uninstall_path)
self.recursive_monkey_patch.monkey_patch(
... | Returns a monkeypatched `UninstallPathset` for using to uninstall packages from the virtualenv
:return: A patched `UninstallPathset` which enables uninstallation of venv packages
:rtype: :class:`pip._internal.req.req_uninstall.UninstallPathset` |
def add_current_user_is_applied_representation(func):
@wraps(func)
def _impl(self, instance):
ret = func(self, instance)
user = self.context["request"].user
applied = False
if not user.is_anonymous():
try:
applied = models.Apply.objects.filter(user=user, project=instance).count() > 0
... | Used to decorate Serializer.to_representation method.
It sets the field "current_user_is_applied" if the user is applied to the project |
def __set_log_file_name(self):
dir, _ = os.path.split(self.__logFileBasename)
if len(dir) and not os.path.exists(dir):
os.makedirs(dir)
self.__logFileName = self.__logFileBasename+"."+self.__logFileExtension
number = 0
while os.path.isfile(self.__logFileName):
... | Automatically set logFileName attribute |
def _seconds_to_days(cls, val, **kwargs):
zero_value = kwargs.get('zero_value', 0)
if val is not None:
if val == zero_value:
return 0
return val / 86400
else:
return 'Not Defined' | converts a number of seconds to days |
def bind(self, name, filterset):
if self.name is not None:
name = self.name
self.field.bind(name, self) | attach filter to filterset
gives a name to use to extract arguments from querydict |
def fetch(self):
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return ExportInstance(self._version, payload, resource_type=self._solution['resource_type'], ) | Fetch a ExportInstance
:returns: Fetched ExportInstance
:rtype: twilio.rest.preview.bulk_exports.export.ExportInstance |
def hide(self, _unhide=False):
return self.reddit_session.hide(self.fullname, _unhide=_unhide) | Hide object in the context of the logged in user.
:param _unhide: If True, unhide the item instead. Use
:meth:`~praw.objects.Hideable.unhide` instead of setting this
manually.
:returns: The json response from the server. |
def merge(self, paths):
topojson_binary = 'node_modules/bin/topojson'
if not os.path.exists(topojson_binary):
topojson_binary = 'topojson'
merge_cmd = '%(binary)s -o %(output_path)s --bbox -p -- %(paths)s' % {
'output_path': self.args.output_path,
'paths': ' '... | Merge data layers into a single topojson file. |
def load_projects(self):
server_config = Config.instance().get_section_config("Server")
projects_path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
os.makedirs(projects_path, exist_ok=True)
try:
for project_path in os.listdir(projects_path):
... | Preload the list of projects from disk |
def name(self) -> Optional[str]:
_, params = parse_content_disposition(
self.headers.get(CONTENT_DISPOSITION))
return content_disposition_filename(params, 'name') | Returns name specified in Content-Disposition header or None
if missed or header is malformed. |
def router_id(self, **kwargs):
router_id = kwargs.pop('router_id')
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
rid_args = dict(rbridge_id=rbridge_id, router_id=router_id)
config = self._rbridge.rbridge_id_ip_rtm_config_router_id(**... | Configures device's Router ID.
Args:
router_id (str): Router ID for the device.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
callback (function): A function executed upon completion of the
met... |
def title_line(text):
columns = shutil.get_terminal_size()[0]
start = columns // 2 - len(text) // 2
output = '='*columns + '\n\n' + \
' ' * start + str(text) + "\n\n" + \
'='*columns + '\n'
return output | Returns a string that represents the
text as a title blurb |
def compress(samples, run_parallel):
to_cram = []
finished = []
for data in [x[0] for x in samples]:
if "cram" in dd.get_archive(data) or "cram-lossless" in dd.get_archive(data):
to_cram.append([data])
else:
finished.append([data])
crammed = run_parallel("archive_... | Perform compression of output files for long term storage. |
def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "purpose": purpose})
return self.api_call("groups.setPurpose", json=kwargs) | Sets the purpose for a private channel.
Args:
channel (str): The channel id. e.g. 'G1234567890'
purpose (str): The new purpose for the channel. e.g. 'My Purpose' |
def calc_login_v1(self):
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
log = self.sequences.logs.fastaccess
for idx in range(der.nmb):
for jdx in range(der.ma_order[idx]-2, -1, -1):
log.login[idx, jdx+1] = log.login[idx, jdx]
for idx in range(der... | Refresh the input log sequence for the different MA processes.
Required derived parameters:
|Nmb|
|MA_Order|
Required flux sequence:
|QPIn|
Updated log sequence:
|LogIn|
Example:
Assume there are three response functions, involving one, two and
three MA coeff... |
def aroon_down(data, period):
catch_errors.check_for_period_error(data, period)
period = int(period)
a_down = [((period -
list(reversed(data[idx+1-period:idx+1])).index(np.min(data[idx+1-period:idx+1]))) /
float(period)) * 100 for idx in range(period-1, len(data))]
a_down = fill_... | Aroon Down.
Formula:
AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100 |
def update(self):
if not os.path.isdir(os.path.join(self.path)):
os.makedirs(self.path)
if not os.path.isdir(os.path.join(self.path, 'refs')):
subprocess.check_output([
'git', 'clone', '--bare', self.repo_git, self.path
])
self.run(['gc', '--au... | Get a repository git or update it |
def _format_pair_with_equals(explode, separator, escape, key, value):
if not value:
return key + '='
return _format_pair(explode, separator, escape, key, value) | Format a key, value pair including the equals sign
when there is no value |
def rastrigin(self, x):
if not isscalar(x[0]):
N = len(x[0])
return [10 * N + sum(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x]
N = len(x)
return 10 * N + sum(x**2 - 10 * np.cos(2 * np.pi * x)) | Rastrigin test objective function |
def fix_attr_encoding(ds):
def _maybe_del_attr(da, attr):
if attr in da.attrs:
del da.attrs[attr]
return da
def _maybe_decode_attr(da, attr):
if (attr in da.attrs) and (type(da.attrs[attr] == bool)):
da.attrs[attr] = int(da.attrs[attr])
return da
for v... | This is a temporary hot-fix to handle the way metadata is encoded
when we read data directly from bpch files. It removes the 'scale_factor'
and 'units' attributes we encode with the data we ingest, converts the
'hydrocarbon' and 'chemical' attribute to a binary integer instead of a
boolean, and removes ... |
def prune(self):
target_user_ids = self.get_queryset().values_list('id', flat=True)
exclude_user_ids = SentDrip.objects.filter(date__lt=conditional_now(),
drip=self.drip_model,
user__id__in=target_user_... | Do an exclude for all Users who have a SentDrip already. |
def get_data_by_hex_uuid_or_404(model, hex_uuid, kind=''):
uuid = UUID(hex_uuid)
bin_uuid = uuid.get_bytes()
instance = get_instance_by_bin_uuid(model, bin_uuid)
if not instance:
return abort(404)
return ins2dict(instance, kind) | Get instance data by uuid and kind. Raise 404 Not Found if there is no data.
This requires model has a `bin_uuid` column.
:param model: a string, model name in rio.models
:param hex_uuid: a hex uuid string in 24-bytes human-readable representation.
:return: a dict. |
def _to_numpy(nd4j_array):
buff = nd4j_array.data()
address = buff.pointer().address()
dtype = get_context_dtype()
mapping = {
'double': ctypes.c_double,
'float': ctypes.c_float
}
Pointer = ctypes.POINTER(mapping[dtype])
pointer = ctypes.cast(address, Pointer)
np_array = ... | Convert nd4j array to numpy array |
def delete(self):
params = {"email": self.email_address}
response = self._delete("/admins.json", params=params) | Deletes the administrator from the account. |
def exit_frames(self):
if self._exit_frames is None:
exit_frames = []
for frame in self.frames:
if any(c.group != self for c in frame.children):
exit_frames.append(frame)
self._exit_frames = exit_frames
return self._exit_frames | Returns a list of frames whose children include a frame outside of the group |
def get_new_locations(self, urls):
seen = set(urls)
for i in urls:
for k in self.get_locations(i):
if k not in seen:
seen.add(k)
yield k | Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL addresses
:returns: valid location header values from responses
... |
def service(self):
if not self._service:
self._service = self._client.service(id=self.service_id)
return self._service | Retrieve the `Service` object to which this execution is associated. |
def dataset_format_to_extension(ds_format):
try:
return DATASET_FORMATS[ds_format]
except KeyError:
raise ValueError(
"dataset_format is expected to be one of %s. '%s' is not valid"
% (", ".join(DATASET_FORMATS.keys()), ds_format)
) | Get the preferred Dataset format extension
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
:rtype: str |
def fai_from_bam(ref_file, bam_file, out_file, data):
contigs = set([x.contig for x in idxstats(bam_file, data)])
if not utils.file_uptodate(out_file, bam_file):
with open(ref.fasta_idx(ref_file, data["config"])) as in_handle:
with file_transaction(data, out_file) as tx_out_file:
... | Create a fai index with only contigs in the input BAM file. |
def package_manager_owns(self, dist):
if dist.location.lower() == get_python_lib().lower():
filename = os.path.join(dist.location, dist.egg_name() + ".egg-info")
else:
filename = dist.location
status, output = getstatusoutput("/usr/bin/acmefile -q %s" % filename)
... | Returns True if package manager 'owns' file
Returns False if package manager does not 'own' file
There is currently no way to determine if distutils or
setuptools installed a package. A future feature of setuptools
will make a package manifest which can be checked.
'... |
def generate_routes(config):
routes = []
for name, config in iteritems(config):
pattern = r'^%s(?P<url>.*)$' % re.escape(config['prefix'].lstrip('/'))
proxy = generate_proxy(
prefix=config['prefix'], base_url=config['base_url'],
verify_ssl=config.get('verify_ssl', True),
... | Generate a list of urls that map to generated proxy views.
generate_routes({
'test_proxy': {
'base_url': 'https://google.com/',
'prefix': '/test_prefix/',
'verify_ssl': False,
'csrf_exempt: False',
'middleware': ['djproxy.proxy_middleware.AddXFF']... |
def AssertType(value, expected_type):
if not isinstance(value, expected_type):
message = "Expected type `%r`, but got value `%r` of type `%s`"
message %= (expected_type, value, type(value))
raise TypeError(message) | Ensures that given value has certain type.
Args:
value: A value to assert the type for.
expected_type: An expected type for the given value.
Raises:
TypeError: If given value does not have the expected type. |
def infer_len(node, context=None):
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
raise UseInferenceDefault("TypeError: len() must take no keyword arguments")
if len(call.positional_arguments) != 1:
raise UseInferenceDefault(
"TypeError: len() must take exac... | Infer length calls
:param nodes.Call node: len call to infer
:param context.InferenceContext: node context
:rtype nodes.Const: a Const node with the inferred length, if possible |
def count(self):
return (
self
.mapPartitions(lambda p: [sum(1 for _ in p)])
.reduce(operator.add)
) | Count elements per RDD.
Creates a new RDD stream where each RDD has a single entry that
is the count of the elements.
:rtype: DStream |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.