INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Usage: sugartex [ OPTIONS ] [ TO ] | def cli():
"""
Usage: sugartex [OPTIONS] [TO]
Reads from stdin and writes to stdout. Can have single argument/option only.
When no args or the arg is not from options then run Pandoc SugarTeX filter
that iterates over math blocks.
Options:
--kiwi Same as above but with kiwi flavo... |
define ribosomal proteins and location of curated databases | def find_databases(databases):
"""
define ribosomal proteins and location of curated databases
"""
# 16 ribosomal proteins in their expected order
proteins = ['L15', 'L18', 'L6', 'S8', 'L5', 'L24', 'L14',
'S17', 'L16', 'S3', 'L22', 'S19', 'L2', 'L4', 'L3', 'S10']
# curated databases
... |
get hits from each search against each RP scaffolds [ scaffold ] = # ORfs s2rp [ scaffold ] = { rp: [ hits ] } | def scaffold_hits(searches, fasta, max_hits):
"""
get hits from each search against each RP
scaffolds[scaffold] = # ORfs
s2rp[scaffold] = {rp:[hits]}
"""
# initialize
## scaffolds[scaffold] = # ORFs
scaffolds = {}
for seq in parse_fasta(fasta):
scaffold = seq[0].split()[0].sp... |
which protein has the best hit the one to the right or to the left? | def find_next(start, stop, i2hits):
"""
which protein has the best hit, the one to the 'right' or to the 'left?'
"""
if start not in i2hits and stop in i2hits:
index = stop
elif stop not in i2hits and start in i2hits:
index = start
elif start not in i2hits and stop not in i2hits:... |
determine which hits represent real ribosomal proteins identify each in syntenic block max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold | def find_ribosomal(rps, scaffolds, s2rp, min_hits, max_hits_rp, max_errors):
"""
determine which hits represent real ribosomal proteins, identify each in syntenic block
max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold
"""
for scaffold, proteins in list(s2rp.items()... |
find ribosomal proteins max_hits = maximum number of blast hits to consider for an orf if 1 only consider best blast hit for each ORF max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold if 1 only consider best RP match to contig max_errors = maximum number of errors when looking for bloc... | def ribosomal(scaffolds, DBdir, min_hits, evalue_thresh, bit_thresh, \
method = 'usearch', threads = 6, \
max_hits = 1, max_hits_rp = 1, max_errors = 35):
"""
find ribosomal proteins
max_hits = maximum number of blast hits to consider for an orf
if 1, only c... |
Parse the rep set file and remove all sequences not associated with unique OTUs. | def filter_rep_set(inF, otuSet):
"""
Parse the rep set file and remove all sequences not associated with unique
OTUs.
:@type inF: file
:@param inF: The representative sequence set
:@rtype: list
:@return: The set of sequences associated with unique OTUs
"""
seqs = []
for record ... |
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions | def _init_data_map(self):
""" OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions """
if self._data_map is not None:
return # Initiation happens once
# Parse and validate the ArcGIS metadata root
if self._xml_tree is None:
agis_... |
Concatenates a list of Digital Form data structures parsed from the metadata | def _parse_digital_forms(self, prop=DIGITAL_FORMS):
""" Concatenates a list of Digital Form data structures parsed from the metadata """
xpath_map = self._data_structures[prop]
# Parse base digital form fields: 'name', 'content', 'decompression', 'version', 'specification'
xpath_root =... |
: return: the text for each element at the configured path if type attribute matches | def _parse_report_item(self, prop):
""" :return: the text for each element at the configured path if type attribute matches"""
item_type = None
if prop == 'attribute_accuracy':
item_type = 'DQQuanAttAcc'
elif prop == 'dataset_completeness':
item_type = 'DQCompOm... |
Update operation for ArcGIS Dates metadata: see: gis_metadata. utils. _complex_definitions [ DATES ] | def _update_dates(self, **update_props):
"""
Update operation for ArcGIS Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES]
"""
tree_to_update = update_props['tree_to_update']
xpath_root = self._data_map['_dates_root']
if self.dates:
... |
Update the text for each element at the configured path if attribute matches | def _update_report_item(self, **update_props):
""" Update the text for each element at the configured path if attribute matches """
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = wrap_value(update_props['values'])
xroot = self._get_xroot_for... |
Wait for a response to be ready ( the provided ready bits are set ). If the specified timeout ( in seconds ) is exceeded and error will be thrown. | def _wait_response(self, ready, timeout_sec):
"""Wait for a response to be ready (the provided ready bits are set).
If the specified timeout (in seconds) is exceeded and error will be
thrown.
"""
# Wait for the measurement to be ready (or a timeout elapses).
start = time.... |
Read the sensor proximity and return it as an unsigned 16 - bit value. The larger the value the closer an object is to the sensor. | def read_proximity(self, timeout_sec=1):
"""Read the sensor proximity and return it as an unsigned 16-bit value.
The larger the value the closer an object is to the sensor.
"""
# Ask for a proximity measurement and wait for the response.
self._device.write8(VCNL40xx_COMMAND, VCNL... |
Read the ambient light sensor and return it as an unsigned 16 - bit value. | def read_ambient(self, timeout_sec=1):
"""Read the ambient light sensor and return it as an unsigned 16-bit value.
"""
# Ask for an ambient measurement and wait for the response.
self._device.write8(VCNL40xx_COMMAND, VCNL40xx_MEASUREAMBIENT)
self._wait_response(VCNL40xx_AMBIENTRE... |
Clear the specified interrupt bit in the interrupt status register. | def _clear_interrupt(self, intbit):
"""Clear the specified interrupt bit in the interrupt status register.
"""
int_status = self._device.readU8(VCNL4010_INTSTAT);
int_status &= ~intbit;
self._device.write8(VCNL4010_INTSTAT, int_status); |
Read the sensor proximity and return it as an unsigned 16 - bit value. The larger the value the closer an object is to the sensor. | def read_proximity(self, timeout_sec=1):
"""Read the sensor proximity and return it as an unsigned 16-bit value.
The larger the value the closer an object is to the sensor.
"""
# Clear any interrupts.
self._clear_interrupt(VCNL4010_INT_PROX_READY)
# Call base class read_p... |
Read the ambient light sensor and return it as an unsigned 16 - bit value. | def read_ambient(self, timeout_sec=1):
"""Read the ambient light sensor and return it as an unsigned 16-bit value.
"""
# Clear any interrupts.
self._clear_interrupt(VCNL4010_INT_ALS_READY)
# Call base class read_ambient and return result.
return super(VCNL4010, self).read... |
Swaps two nodes | def move(self):
"""Swaps two nodes"""
a = random.randint(0, len(self.state) - 1)
b = random.randint(0, len(self.state) - 1)
self.state[[a,b]] = self.state[[b,a]] |
Detect a single core - periphery pair. Parameters ---------- G: NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx. karate_club_graph () # load the karate club network. >>> rb = cp. Rombach ( algorithm = ls ) # label switching algorithm >>> rb. detect ( G ) >>> rb... | def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> rb = cp.Rombach(algorithm='ls') # label swi... |
Detect a single core - periphery pair using the Borgatti - Everett algorithm. Parameters ---------- G: NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx. karate_club_graph () # load the karate club network. >>> be = cpa. BE () >>> be. detect ( G ) | def detect(self, G):
"""Detect a single core-periphery pair using the Borgatti-Everett algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> be = c... |
A bool - if the certificate should be self - signed. | def self_signed(self, value):
"""
A bool - if the certificate should be self-signed.
"""
self._self_signed = bool(value)
if self._self_signed:
self._issuer = None |
An int representable in 160 bits or less - must uniquely identify this certificate when combined with the issuer name. | def serial_number(self, value):
"""
An int representable in 160 bits or less - must uniquely identify
this certificate when combined with the issuer name.
"""
if not isinstance(value, int_types):
raise TypeError(_pretty_message(
'''
se... |
An asn1crypto. x509. Certificate object of the issuer. Used to populate both the issuer field but also the authority key identifier extension. | def issuer(self, value):
"""
An asn1crypto.x509.Certificate object of the issuer. Used to populate
both the issuer field, but also the authority key identifier extension.
"""
is_oscrypto = isinstance(value, asymmetric.Certificate)
if not isinstance(value, x509.Certificat... |
A datetime. datetime object of when the certificate becomes valid. | def begin_date(self, value):
"""
A datetime.datetime object of when the certificate becomes valid.
"""
if not isinstance(value, datetime):
raise TypeError(_pretty_message(
'''
begin_date must be an instance of datetime.datetime, not %s
... |
A datetime. datetime object of when the certificate is last to be considered valid. | def end_date(self, value):
"""
A datetime.datetime object of when the certificate is last to be
considered valid.
"""
if not isinstance(value, datetime):
raise TypeError(_pretty_message(
'''
end_date must be an instance of datetime.dat... |
Grabs the first URL out of a asn1crypto. x509. CRLDistributionPoints object | def _get_crl_url(self, distribution_points):
"""
Grabs the first URL out of a asn1crypto.x509.CRLDistributionPoints
object
:param distribution_points:
The x509.CRLDistributionPoints object to pull the URL out of
:return:
A unicode string or None
... |
Constructs an asn1crypto. x509. CRLDistributionPoints object | def _make_crl_distribution_points(self, name, value):
"""
Constructs an asn1crypto.x509.CRLDistributionPoints object
:param name:
A unicode string of the attribute name to use in exceptions
:param value:
Either a unicode string of a URL, or a 2-element tuple of ... |
Location of the OCSP responder for this certificate. Will be one of the following types: | def ocsp_url(self):
"""
Location of the OCSP responder for this certificate. Will be one of the
following types:
- None for no OCSP responder
- A unicode string of the URL to the OCSP responder
"""
if self._authority_information_access is None:
ret... |
A bool - if the certificate should have the OCSP no check extension. Only applicable to certificates created for signing OCSP responses. Such certificates should normally be issued for a very short period of time since they are effectively whitelisted by clients. | def ocsp_no_check(self, value):
"""
A bool - if the certificate should have the OCSP no check extension.
Only applicable to certificates created for signing OCSP responses.
Such certificates should normally be issued for a very short period of
time since they are effectively whit... |
Validates the certificate information constructs the ASN. 1 structure and then signs it | def build(self, signing_private_key):
"""
Validates the certificate information, constructs the ASN.1 structure
and then signs it
:param signing_private_key:
An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey
object for the private key to sign th... |
Detect a single core - periphery pair using the Borgatti - Everett algorithm. Parameters ---------- G: NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx. karate_club_graph () # load the karate club network. >>> spr = cpa. Surprise () >>> spr. detect ( G ) | def detect(self, G):
"""Detect a single core-periphery pair using the Borgatti-Everett algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> spr = ... |
Passes a connection from the connection pool so that we can call. run () on a query without an explicit connection | def remodel_run(self, c=None, **global_optargs):
"""
Passes a connection from the connection pool so that we can call .run()
on a query without an explicit connection
"""
if not c:
with remodel.connection.get_conn() as conn:
return run(self, conn, **global_optargs)
else:
... |
Removes empty line. | def emptylineless(parser, token):
"""
Removes empty line.
Example usage::
{% emptylineless %}
test1
test2
test3
{% endemptylineless %}
This example would return this HTML::
test1
test2
test3
"""
nodeli... |
Detect a single core - periphery pair. Parameters ---------- G: NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx. karate_club_graph () # load the karate club network. >>> lrc = cp. LowRankCore () >>> lrc. detect ( G ) | def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G)
... |
Do an HTTP PURGE of the given asset. The URL is run through urlparse and must point to the varnish instance not the varnishadm | def http_purge_url(url):
"""
Do an HTTP PURGE of the given asset.
The URL is run through urlparse and must point to the varnish instance not the varnishadm
"""
url = urlparse(url)
connection = HTTPConnection(url.hostname, url.port or 80)
path = url.path or '/'
connection.request('PURGE',... |
Non - threaded batch command runner returning output results | def run(addr, *commands, **kwargs):
"""
Non-threaded batch command runner returning output results
"""
results = []
handler = VarnishHandler(addr, **kwargs)
for cmd in commands:
if isinstance(cmd, tuple) and len(cmd)>1:
results.extend([getattr(handler, c[0].replace('.','_'))(... |
Run a command on the Varnish backend and return the result return value is a tuple of (( status length ) content ) | def fetch(self, command):
"""
Run a command on the Varnish backend and return the result
return value is a tuple of ((status, length), content)
"""
logging.debug('SENT: %s: %s' % (self.host, command))
self.write('%s\n' % command)
while 1:
buffer = self... |
ping [ timestamp ] Ping the Varnish cache process keeping the connection alive. | def ping(self, timestamp=None):
"""
ping [timestamp]
Ping the Varnish cache process, keeping the connection alive.
"""
cmd = 'ping'
if timestamp: cmd += ' %s' % timestamp
return tuple(map(float, self.fetch(cmd)[1].split()[1:])) |
help [ command ] Display a list of available commands. If the command is specified display help for this command. | def help(self, command=None):
"""
help [command]
Display a list of available commands.
If the command is specified, display help for this command.
"""
cmd = 'help'
if command: cmd += ' %s' % command
return self.fetch(cmd)[1] |
vcl. list List available configurations and their respective reference counts. The active configuration is indicated with an asterisk ( * ). | def vcl_list(self):
"""
vcl.list
List available configurations and their respective reference counts. The active configuration
is indicated with an asterisk ("*").
"""
vcls = {}
for line in self.fetch('vcl.list')[1].splitlines():
a = line.sp... |
param. show [ - l ] [ param ] Display a list if run - time parameters and their values. If the - l option is specified the list includes a brief explanation of each parameter. If a param is specified display only the value and explanation for this parameter. | def param_show(self, param, l=False):
"""
param.show [-l] [param]
Display a list if run-time parameters and their values.
If the -l option is specified, the list includes a brief explanation of each parameter.
If a param is specified, display only the value and ... |
function to | def main():
"""function to """
# parse arg to find file(s)
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file",
help="convert the markdown file to HTML")
parser.add_argument("-d", "--directory",
help="convert the markdown files in the... |
add the content of the file ( s ) ( or the text in string ) in HTML body | def add_content(self, text=None, *markdown_files):
"""add the content of the file(s) (or the text in string) in HTML body"""
for markdown_file in markdown_files:
self.markdown_text += self._text_file(markdown_file)
if text:
self.markdown_text += text |
add stylesheet files in HTML head | def add_stylesheets(self, *css_files):
"""add stylesheet files in HTML head"""
for css_file in css_files:
self.main_soup.style.append(self._text_file(css_file)) |
add javascripts files in HTML body | def add_javascripts(self, *js_files):
"""add javascripts files in HTML body"""
# create the script tag if don't exists
if self.main_soup.script is None:
script_tag = self.main_soup.new_tag('script')
self.main_soup.body.append(script_tag)
for js_file in js_files:
... |
return the object in a file | def export(self):
"""return the object in a file"""
with open(self.export_url, 'w', encoding='utf-8') as file:
file.write(self.build())
if self.open_browser:
webbrowser.open_new_tab(self.export_url) |
convert Markdown text as html. return the html file as string | def build(self):
"""convert Markdown text as html. return the html file as string"""
markdown_html = markdown.markdown(self.markdown_text, extensions=[
TocExtension(), 'fenced_code', 'markdown_checklist.extension',
'markdown.extensions.tables'])
markdown_soup = Be... |
return the content of a file | def _text_file(self, url):
"""return the content of a file"""
try:
with open(url, 'r', encoding='utf-8') as file:
return file.read()
except FileNotFoundError:
print('File `{}` not found'.format(url))
sys.exit(0) |
create a graphviz graph from text | def _text_to_graphiz(self, text):
"""create a graphviz graph from text"""
dot = Source(text, format='svg')
return dot.pipe().decode('utf-8') |
add js libraries and css files of mermaid js_file | def _add_mermaid_js(self):
"""add js libraries and css files of mermaid js_file"""
self.add_javascripts('{}/js/jquery-1.11.3.min.js'.format(self.resources_path))
self.add_javascripts('{}/js/mermaid.min.js'.format(self.resources_path))
self.add_stylesheets('{}/css/mermaid.css'.format(self... |
Get score of core - periphery pairs. Parameters ---------- G: Graph object. c: Dict object the keys and values of which are the name of node and its ID of belonging core - periphery pair. Returns ------- q: List. q [ i ] is the quality of core - periphery pair i. | def score(*args):
"""Get score of core-periphery pairs.
Parameters
----------
G : Graph object.
c : Dict object, the keys and values of which are the name of node and its ID of belonging core-periphery pair.
Returns
-------
q : List. q[i] is the quality of core-periphery pair i.
"""... |
Transform NetworkX object to an edge list. Parameters ---------- G: Graph object. Returns ------- node_pairs: ( M 2 ) numpy array where M is the number of edges. node_pairs [ i 0 ] and node_pairs [ i 1 ] are the endpoints of the ith edge. w: Mx1 numpy array. w [ i ] is the weight of the ith edge. node2id: Dict. A funct... | def _to_edge_list(self, G):
"""Transform NetworkX object to an edge list.
Parameters
----------
G : Graph object.
Returns
-------
node_pairs : (M, 2) numpy array, where M is the number of edges. node_pairs[i,0] and node_pairs[i,1] are the endpoints of the ith edge.
w : Mx1 numpy array. w[i]... |
Extract the identifier out of this construct: $ { mylist }: mylist | def getSource(self):
"""Extract the identifier out of this construct: ${mylist}: mylist
"""
bracket = self.next()
# we should only be here because that was a bracket
if not bracket == u'{':
raise Exception(u"parse error getting source")
c = u''
identif... |
Get a character set with individual members or ranges. | def getCharacterSet(self):
'''Get a character set with individual members or ranges.
Current index is on '[', the start of the character set.
'''
chars = u''
c = None
cnt = 1
start = 0
while True:
escaped_slash = False
c... |
Get a sequence of non - special characters. | def getLiteral(self):
'''Get a sequence of non-special characters.'''
# we are on the first non-special character
chars = u''
c = self.current()
while True:
if c and c == u"\\":
c = self.next()
if c:
chars += c
... |
Get a sequence of nodes. | def getSequence(self, level=0):
'''Get a sequence of nodes.'''
seq = []
op = ''
left_operand = None
right_operand = None
sequence_closed = False
while True:
c = self.next()
if not c:
break
if c and c not in self... |
Print the parse tree and then call render for an example. | def dump(self, **kwargs):
import sys
'''Print the parse tree and then call render for an example.'''
if not self.seq:
self.seq = self.getSequence()
print("StringGenerator version: %s" % (__version__))
print("Python version: %s" % sys.version)
# this doesn't wo... |
Return a list of generated strings. | def render_list(self, cnt, unique=False, progress_callback=None, **kwargs):
'''Return a list of generated strings.
Args:
cnt (int): length of list
unique (bool): whether to make entries unique
Returns:
list.
We keep track of total attempts because a... |
Establish the connection. This is done automatically for you. | def connect(self):
"""
Establish the connection. This is done automatically for you.
If you lose the connection, you can manually run this to be re-connected.
"""
self.conn = boto.connect_s3(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, debug=self.S3UTILS_DEBUG_LEVEL)
... |
Connect to Cloud Front. This is done automatically for you when needed. | def connect_cloudfront(self):
"Connect to Cloud Front. This is done automatically for you when needed."
self.conn_cloudfront = connect_cloudfront(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, debug=self.S3UTILS_DEBUG_LEVEL) |
Create a folder on S3. | def mkdir(self, target_folder):
"""
Create a folder on S3.
Examples
--------
>>> s3utils.mkdir("path/to/my_folder")
Making directory: path/to/my_folder
"""
self.printv("Making directory: %s" % target_folder)
self.k.key = re.sub(r"^/|/$", "... |
Delete the path and anything under the path. | def rm(self, path):
"""
Delete the path and anything under the path.
Example
-------
>>> s3utils.rm("path/to/file_or_folder")
"""
list_of_files = list(self.ls(path))
if list_of_files:
if len(list_of_files) == 1:
self.buck... |
Copy a file to s3. | def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source="filename"):
"""Copy a file to s3."""
action_word = "moving" if del_after_upload else "copying"
try:
self.k.key = target_file # setting the path (key) of file in the conta... |
Copy a file or folder from local to s3. | def cp(self, local_path, target_path, acl='public-read',
del_after_upload=False, overwrite=True, invalidate=False):
"""
Copy a file or folder from local to s3.
Parameters
----------
local_path : string
Path to file or folder. Or if you want to copy only t... |
Similar to Linux mv command. | def mv(self, local_file, target_file, acl='public-read', overwrite=True, invalidate=False):
"""
Similar to Linux mv command.
Move the file to the S3 and deletes the local copy
It is basically s3utils.cp that has del_after_upload=True
Examples
--------
>>> s... |
Deal with saving cropduster images to S3. Cropduster is a Django library for resizing editorial images. S3utils was originally written to put cropduster images on S3 bucket. | def cp_cropduster_image(self, the_image_path, del_after_upload=False, overwrite=False, invalidate=False):
"""
Deal with saving cropduster images to S3. Cropduster is a Django library for resizing editorial images.
S3utils was originally written to put cropduster images on S3 bucket.
Ext... |
Return grant permission grant owner grant owner email and grant id as a list. It needs you to set k. key to a key on amazon ( file path ) before running this. note that Amazon returns a list of grants for each file. | def __get_grants(self, target_file, all_grant_data):
"""
Return grant permission, grant owner, grant owner email and grant id as a list.
It needs you to set k.key to a key on amazon (file path) before running this.
note that Amazon returns a list of grants for each file.
option... |
sets permissions for a file on S3 | def chmod(self, target_file, acl='public-read'):
"""
sets permissions for a file on S3
Parameters
----------
target_file : string
Path to file on S3
acl : string, optional
File permissions on S3. Default is public-read
options:
... |
gets the list of file names ( keys ) in a s3 folder | def ls(self, folder="", begin_from_file="", num=-1, get_grants=False, all_grant_data=False):
"""
gets the list of file names (keys) in a s3 folder
Parameters
----------
folder : string
Path to file on S3
num: integer, optional
number of results ... |
Get the list of files and permissions from S3. | def ll(self, folder="", begin_from_file="", num=-1, all_grant_data=False):
"""
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
... |
Invalidate the CDN ( distribution ) cache for a certain file of files. This might take up to 15 minutes to be effective. | def invalidate(self, files_to_be_invalidated):
"""
Invalidate the CDN (distribution) cache for a certain file of files. This might take up to 15 minutes to be effective.
You can check for the invalidation status using check_invalidation_request.
Examples
--------
>... |
Parses a tag that s supposed to be in this format: { % anchor field title % } | def anchor(parser, token):
"""
Parses a tag that's supposed to be in this format: {% anchor field title %}
"""
bits = [b.strip('"\'') for b in token.split_contents()]
if len(bits) < 2:
raise TemplateSyntaxError, "anchor tag takes at least 1 argument"
try:
title = bits[2]
... |
Get the path from a given url including the querystring. | def get_path(url):
"""
Get the path from a given url, including the querystring.
Args:
url (str)
Returns:
str
"""
url = urlsplit(url)
path = url.path
if url.query:
path += "?{}".format(url.query)
return path |
Reads data from disk and generates CSV files. | def run(self):
"""Reads data from disk and generates CSV files."""
# Try to create the directory
if not os.path.exists(self.output):
try:
os.mkdir(self.output)
except:
print 'failed to create output directory %s' % self.output
# Be... |
Process a list of simple string field definitions and assign their order based on prefix. | def process_fields(self, fields):
"""Process a list of simple string field definitions and assign their order based on prefix."""
result = []
strip = ''.join(self.PREFIX_MAP)
for field in fields:
direction = self.PREFIX_MAP['']
if field[0] in self.PREFIX_MAP:
direction = self.PREFIX_MAP[fiel... |
Create this index in the specified collection ; keyword arguments are passed to PyMongo. http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. create_index | def create(self, collection, **kw):
"""Create this index in the specified collection; keyword arguments are passed to PyMongo.
http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_index
"""
options = dict(
name = self.__name__,
unique = self.unique... |
Rubrics search | def rubricator(self, **kwargs):
"""Rubrics search
http://api.2gis.ru/doc/firms/list/rubricator/
"""
# `show_children' parameter must be an integer
kwargs['show_children'] = int(kwargs.pop('show_children', False))
return self._rubricator(**kwargs) |
Firms search | def search(self, **kwargs):
"""Firms search
http://api.2gis.ru/doc/firms/searches/search/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % (point[0], point[1])
bound = kwargs.pop('bound', False)
if bound:
kwar... |
Firms search in rubric | def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
... |
Geo search | def geo_search(self, **kwargs):
"""Geo search
http://api.2gis.ru/doc/geo/search/
"""
if 'types' in kwargs:
kwargs['types'] = ','.join(kwargs['types'])
bound = kwargs.pop('bound', False)
if bound:
kwargs['bound[point1]'] = bound[0]
kw... |
Refresh the list and the screen | def refresh(self):
'''
Refresh the list and the screen
'''
self._screen.force_update()
self._screen.refresh()
self._update(1) |
Mark an action as started | def start(self, activity, action):
'''
Mark an action as started
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action`
'''
try:
self._start_actio... |
Mark a task as completed | def stop(self, activity, action):
'''
Mark a task as completed
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action`
'''
try:
self._remove_runnin... |
Move laggard tasks over | def finish(self, status):
'''
Move laggard tasks over
:param activity: The virtualenv status
:type activity: ``str``
'''
retox_log.info("Completing %s with status %s" % (self.name, status))
result = Screen.COLOUR_GREEN if not status else Screen.COLOUR_RED
... |
Reset the frame between jobs | def reset(self):
'''
Reset the frame between jobs
'''
self.palette['title'] = (Screen.COLOUR_WHITE, Screen.A_BOLD, Screen.COLOUR_BLUE)
self._completed_view.options = []
self._task_view.options = []
self.refresh() |
Returns the available kwargs of the called class | def default_arguments(cls):
"""Returns the available kwargs of the called class"""
func = cls.__init__
args = func.__code__.co_varnames
defaults = func.__defaults__
index = -len(defaults)
return {k: v for k, v in zip(args[index:], defaults)} |
Recreate the class based in your args multiple uses | def recreate(cls, *args, **kwargs):
"""Recreate the class based in your args, multiple uses"""
cls.check_arguments(kwargs)
first_is_callable = True if any(args) and callable(args[0]) else False
signature = cls.default_arguments()
allowed_arguments = {k: v for k, v in kwargs.items... |
Put warnings of arguments whose can t be handle by the class | def check_arguments(cls, passed):
"""Put warnings of arguments whose can't be handle by the class"""
defaults = list(cls.default_arguments().keys())
template = ("Pass arg {argument:!r} in {cname:!r}, can be a typo? "
"Supported key arguments: {defaults}")
fails = []
... |
process the specified type then process its children | def process(self, data, type, history):
""" process the specified type then process its children """
if type in history:
return
if type.enum():
return
history.append(type)
resolved = type.resolve()
value = None
if type.multi_occurrence():
... |
get whether or not to skip the specified child | def skip_child(self, child, ancestry):
""" get whether or not to skip the specified child """
if child.any(): return True
for x in ancestry:
if x.choice():
return True
return False |
Signal endpoint that actually sends knocks whenever an instance is created/ saved | def notify_items(**kwargs):
"""
Signal endpoint that actually sends knocks whenever an instance is created / saved
"""
instance = kwargs.get('instance')
created = kwargs.get('created', False)
if hasattr(instance, 'send_knock') and active_knocks(instance):
try:
# This is a stu... |
Checks whether knocks are enabled for the model given as argument | def active_knocks(obj):
"""
Checks whether knocks are enabled for the model given as argument
:param obj: model instance
:return True if knocks are active
"""
if not hasattr(_thread_locals, 'knock_enabled'):
return True
return _thread_locals.knock_enabled.get(obj.__class__, True) |
Context manager to suspend sending knocks for the given model | def pause_knocks(obj):
"""
Context manager to suspend sending knocks for the given model
:param obj: model instance
"""
if not hasattr(_thread_locals, 'knock_enabled'):
_thread_locals.knock_enabled = {}
obj.__class__._disconnect()
_thread_locals.knock_enabled[obj.__class__] = False
... |
Loop over the report progress | def _loopreport(self):
'''
Loop over the report progress
'''
while 1:
eventlet.sleep(0.2)
ac2popenlist = {}
for action in self.session._actions:
for popen in action._popenlist:
if popen.poll() is None:
... |
Send markdown email | def send(email, subject=None,
from_email=None, to_email=None,
cc=None, bcc=None, reply_to=None,
smtp=None):
"""Send markdown email
Args:
email (str/obj): A markdown string or EmailContent object
subject (str): subject line
from_email (str): sender email addre... |
Process timezone casting and conversion. | def _process_tz(self, dt, naive, tz):
"""Process timezone casting and conversion."""
def _tz(t):
if t in (None, 'naive'):
return t
if t == 'local':
if __debug__ and not localtz:
raise ValueError("Requested conversion to local timezone, but `localtz` not installed.")
t = localtz
... |
Trigger assignment of default values. | def _prepare_defaults(self):
"""Trigger assignment of default values."""
for name, field in self.__fields__.items():
if field.assign:
getattr(self, name) |
Convert data coming in from the MongoDB wire driver into a Document instance. | def from_mongo(cls, doc):
"""Convert data coming in from the MongoDB wire driver into a Document instance."""
if doc is None: # To support simplified iterative use, None should return None.
return None
if isinstance(doc, Document): # No need to perform processing on existing Document instances.
retu... |
Retrieve and remove a value from the backing store optionally with a default. | def pop(self, name, default=SENTINEL):
"""Retrieve and remove a value from the backing store, optionally with a default."""
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.