_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q46500 | apply_markup | train | def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
"""
if arg is not None:
return formatter(value, filter_name=arg)
return formatter(value) | python | {
"resource": ""
} |
q46501 | ListCallMixin.list | train | def list(cls, params=None):
"""
Retrieves a list of the model
:param params: params as dictionary
:type params: dict
:return: the list of the parsed xml objects
:rtype: list
"""
return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode(
... | python | {
"resource": ""
} |
q46502 | setup_config | train | def setup_config(command, filename, section, vars):
"""Place any commands to setup chatapp here"""
confuri = "config:" + filename
if ":" in section:
confuri += "#" + section.rsplit(":", 1)[-1]
conf = appconfig(confuri)
load_environment(conf.global_conf, conf.local_conf) | python | {
"resource": ""
} |
q46503 | ChatController.push | train | def push(self):
"""This action puts a message in the global queue that all the clients
will get via the 'pull' action."""
print `request.body`
yield request.environ['cogen.call'](pubsub.publish)(
"%s: %s" % (session['client'].name, request.body)
)
# the... | python | {
"resource": ""
} |
q46504 | get_or_create_home_repo | train | def get_or_create_home_repo(reset=False):
"""
Check to make sure we never operate with a non-existing local repo
"""
dosetup = True
if os.path.exists(ONTOSPY_LOCAL):
dosetup = False
if reset:
import shutil
var = input("Delete the local library and all of its contents? (y/n) ")
if var == "y":
shut... | python | {
"resource": ""
} |
q46505 | del_pickled_ontology | train | def del_pickled_ontology(filename):
""" try to remove a cached ontology """
pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle"
if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE:
os.remove(pickledfile)
return True
else:
return None | python | {
"resource": ""
} |
q46506 | rename_pickled_ontology | train | def rename_pickled_ontology(filename, newname):
""" try to rename a cached ontology """
pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle"
newpickledfile = ONTOSPY_LOCAL_CACHE + "/" + newname + ".pickle"
if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE:
os.rename(pickledfile, newpickledfile... | python | {
"resource": ""
} |
q46507 | UpdateCallMixin.update | train | def update(self):
"""
Updates the object
:return:
:rtype: response
"""
return self._put_request(
data=self.element_to_string(
self.encode()
),
endpoint=self.ENDPOINT + '/' + str(self.id)
) | python | {
"resource": ""
} |
q46508 | mixing_phases | train | def mixing_phases(U):
"""Return the angles and CP phases of the CKM or PMNS matrix
in standard parametrization, starting from a matrix with arbitrary phase
convention."""
f = {}
# angles
f['t13'] = asin(abs(U[0,2]))
if U[0,0] == 0:
f['t12'] = pi/2
else:
f['t12'] = atan(ab... | python | {
"resource": ""
} |
q46509 | rephase_standard | train | def rephase_standard(UuL, UdL, UuR, UdR):
"""Function to rephase the quark rotation matrices in order to
obtain the CKM matrix in standard parametrization.
The input matrices are assumed to diagonalize the up-type and down-type
quark matrices like
```
UuL.conj().T @ Mu @ UuR = Mu_diag
UdL.... | python | {
"resource": ""
} |
q46510 | rephase_pmns_standard | train | def rephase_pmns_standard(Unu, UeL, UeR):
"""Function to rephase the lepton rotation matrices in order to
obtain the PMNS matrix in standard parametrization.
The input matrices are assumed to diagonalize the charged lepton and
neutrino mass matrices like
```
UeL.conj().T @ Me @ UeR = Me_diag
... | python | {
"resource": ""
} |
q46511 | warn_if_outdated | train | def warn_if_outdated(package,
version,
raise_exceptions=False,
background=True,
):
"""
Higher level convenience function using check_outdated.
The package and version arguments are the same.
If the package is outdated,... | python | {
"resource": ""
} |
q46512 | _generate_sympify_namespace | train | def _generate_sympify_namespace(
independent_variables, dependent_variables, helper_functions
):
"""Generate the link between the symbols of the derivatives and the
sympy Derivative operation.
Parameters
----------
independent_variable : str
name of the independant variable ("... | python | {
"resource": ""
} |
q46513 | BaseDumpHandler._prepare_output_multi | train | def _prepare_output_multi(self, model):
"""If printing to a different file per model, change the file for the current model"""
model_name = model.__name__
current_path = os.path.join(self._output_path, '{model}.{extension}'.format(
model=model_name,
extension=self.EXTENSI... | python | {
"resource": ""
} |
q46514 | LoadData.prepare_buckets | train | def prepare_buckets(self):
"""
loads buckets to bucket cache.
"""
for mdl in self.registry.get_base_models():
bucket = mdl(super_context).objects.adapter.bucket
self.buckets[bucket.name] = bucket | python | {
"resource": ""
} |
q46515 | GenerateDiagrams._print_split_model | train | def _print_split_model(self, path, apps_models):
"""
Print each model in apps_models into its own file.
"""
for app, models in apps_models:
for model in models:
model_name = model().title
if self._has_extension(path):
model_... | python | {
"resource": ""
} |
q46516 | GenerateDiagrams._print_split_app | train | def _print_split_app(self, path, apps_models):
"""
Print each app in apps_models associative list into its own file.
"""
for app, models in apps_models:
# Convert dir/file.puml to dir/file.app.puml to print to an app specific file
if self._has_extension(path):
... | python | {
"resource": ""
} |
q46517 | GenerateDiagrams._print_single_file | train | def _print_single_file(self, path, apps_models):
"""
Print apps_models which contains a list of 2-tuples containing apps and their models
into a single file.
"""
if path:
outfile = codecs.open(path, 'w', encoding='utf-8')
self._print = lambda s: outfile.wr... | python | {
"resource": ""
} |
q46518 | GenerateDiagrams._print_app | train | def _print_app(self, app, models):
"""
Print the models of app, showing them in a package.
"""
self._print(self._app_start % app)
self._print_models(models)
self._print(self._app_end) | python | {
"resource": ""
} |
q46519 | GenerateDiagrams._print_fields | train | def _print_fields(self, fields):
"""Print the fields, padding the names as necessary to align them."""
# Prepare a formatting string that aligns the names and types based on the longest ones
longest_name = max(fields, key=lambda f: len(f[1]))[1]
longest_type = max(fields, key=lambda f: l... | python | {
"resource": ""
} |
q46520 | GenerateDiagrams._get_model_fields | train | def _get_model_fields(self, model, prefix=_field_prefix):
"""
Find all fields of given model that are not default models.
"""
fields = list()
for field_name, field in model()._ordered_fields:
# Filter the default fields
if field_name not in getattr(model, ... | python | {
"resource": ""
} |
q46521 | GenerateDiagrams._get_model_nodes | train | def _get_model_nodes(self, model):
"""
Find all the non-auto created nodes of the model.
"""
nodes = [(name, node) for name, node in model._nodes.items()
if node._is_auto_created is False]
nodes.sort(key=lambda n: n[0])
return nodes | python | {
"resource": ""
} |
q46522 | GenerateDiagrams._print_links | train | def _print_links(self, model, links):
"""
Print links that start from model.
"""
for link in links:
if link['o2o'] is True:
link_type = self._one_to_one
elif link['m2m'] is True:
link_type = self._many_to_many
else:
... | python | {
"resource": ""
} |
q46523 | printBasicInfo | train | def printBasicInfo(onto):
"""
Terminal printing of basic ontology information
"""
rdfGraph = onto.rdfGraph
print("_" * 50, "\n")
print("TRIPLES = %s" % len(rdfGraph))
print("_" * 50)
print("\nNAMESPACES:\n")
for x in onto.ontologyNamespaces:
print("%s : %s" % (x[0], x[1]))
... | python | {
"resource": ""
} |
q46524 | entityTriples | train | def entityTriples(rdfGraph, anEntity, excludeProps=False, excludeBNodes=False,
orderProps=[RDF, RDFS, OWL.OWLNS, DC.DCNS]):
"""
Returns the pred-obj for any given resource, excluding selected ones..
Sorting: by default results are sorted alphabetically and according to namespaces: [RDF, R... | python | {
"resource": ""
} |
q46525 | Type2CondenseHelper._add_interval | train | def _add_interval(all_intervals, new_interval):
"""
Adds a new interval to a set of none overlapping intervals.
:param set[(int,int)] all_intervals: The set of distinct intervals.
:param (int,int) new_interval: The new interval.
"""
intervals = None
old_interval ... | python | {
"resource": ""
} |
q46526 | Type2CondenseHelper._derive_distinct_intervals | train | def _derive_distinct_intervals(self, rows):
"""
Returns the set of distinct intervals in a row set.
:param list[dict[str,T]] rows: The rows set.
:rtype: set[(int,int)]
"""
ret = set()
for row in rows:
self._add_interval(ret, (row[self._key_start_date... | python | {
"resource": ""
} |
q46527 | Type2CondenseHelper.condense | train | def condense(self):
"""
Condense the data set to the distinct intervals based on the pseudo key.
"""
for pseudo_key, rows in self._rows.items():
tmp1 = []
intervals = sorted(self._derive_distinct_intervals(rows))
for interval in intervals:
... | python | {
"resource": ""
} |
q46528 | _terminate_procs | train | def _terminate_procs(procs):
"""
Terminate all processes in the process dictionary
"""
logging.warn("Stopping all remaining processes")
for proc, g in procs.values():
logging.debug("[%s] SIGTERM", proc.pid)
try:
proc.terminate()
except OSError as e:
# ... | python | {
"resource": ""
} |
q46529 | write_summary | train | def write_summary(all_procs, summary_file):
"""
Write a summary of all run processes to summary_file in tab-delimited
format.
"""
if not summary_file:
return
with summary_file:
writer = csv.writer(summary_file, delimiter='\t', lineterminator='\n')
writer.writerow(('direc... | python | {
"resource": ""
} |
q46530 | template_subs_file | train | def template_subs_file(in_file, out_fobj, d):
"""
Substitute template arguments in in_file from variables in d, write the
result to out_fobj.
"""
with open(in_file, 'r') as in_fobj:
for line in in_fobj:
out_fobj.write(line.format(**d)) | python | {
"resource": ""
} |
q46531 | worker | train | def worker(data, json_file):
"""
Handle parameter substitution and execute command as child process.
"""
# PERHAPS TODO: Support either full or relative paths.
with open(json_file) as fp:
d = json.load(fp)
json_directory = os.path.dirname(json_file)
def p(*parts):
return os.p... | python | {
"resource": ""
} |
q46532 | NestlyProcess.complete | train | def complete(self, return_code):
"""
Mark the process as complete with provided return_code
"""
self.return_code = return_code
self.status = 'COMPLETE' if not return_code else 'FAILED'
self.end_time = datetime.datetime.now() | python | {
"resource": ""
} |
q46533 | NestlyProcess.log_tail | train | def log_tail(self, nlines=10):
"""
Return the last ``nlines`` lines of the log file
"""
log_path = os.path.join(self.working_dir, self.log_name)
with open(log_path) as fp:
d = collections.deque(maxlen=nlines)
d.extend(fp)
return ''.join(d) | python | {
"resource": ""
} |
q46534 | Client.list | train | def list(self,table, **kparams):
"""
get a collection of records by table name.
returns a collection of SnowRecord obj.
"""
records = self.api.list(table, **kparams)
return records | python | {
"resource": ""
} |
q46535 | Client.get | train | def get(self,table, sys_id):
"""
get a single record by table name and sys_id
returns a SnowRecord obj.
"""
record = self.api.get(table, sys_id)
return record | python | {
"resource": ""
} |
q46536 | Client.update | train | def update(self,table, sys_id, **kparams):
"""
update a record via table api, kparams being the dict of PUT params to update.
returns a SnowRecord obj.
"""
record = self.api.update(table, sys_id, **kparams)
return record | python | {
"resource": ""
} |
q46537 | select_product | train | def select_product():
"""
binds the frozen context the selected features
should be called only once - calls after the first call have
no effect
"""
global _product_selected
if _product_selected:
# tss already bound ... ignore
return
_product_selected = True
from dja... | python | {
"resource": ""
} |
q46538 | RDF_Entity.serialize | train | def serialize(self, format="turtle"):
""" xml, n3, turtle, nt, pretty-xml, trix are built in"""
if self.triples:
if not self.rdfgraph:
self._buildGraph()
return self.rdfgraph.serialize(format=format)
else:
return None | python | {
"resource": ""
} |
q46539 | RDF_Entity.bestLabel | train | def bestLabel(self, prefLanguage="en", qname_allowed=True, quotes=True):
"""
facility for extrating the best available label for an entity
..This checks RFDS.label, SKOS.prefLabel and finally the qname local component
"""
test = self.getValuesForProperty(rdflib.RDFS.label)
... | python | {
"resource": ""
} |
q46540 | RDF_Entity.bestDescription | train | def bestDescription(self, prefLanguage="en"):
"""
facility for extrating the best available description for an entity
..This checks RFDS.label, SKOS.prefLabel and finally the qname local component
"""
test_preds = [rdflib.RDFS.comment, rdflib.namespace.DCTERMS.description, rdfl... | python | {
"resource": ""
} |
q46541 | mkp | train | def mkp(*args, **kwargs):
"""
Generate a directory path, and create it if requested.
.. code-block:: Python
filepath = mkp('base', 'folder', 'file')
dirpath = mkp('root', 'path', 'folder', mk=True)
Args:
\*args: File or directory path segments to be concatenated
mk (bo... | python | {
"resource": ""
} |
q46542 | get_internal_modules | train | def get_internal_modules(key='exa'):
"""
Get a list of modules belonging to the given package.
Args:
key (str): Package or library name (e.g. "exa")
"""
key += '.'
return [v for k, v in sys.modules.items() if k.startswith(key)] | python | {
"resource": ""
} |
q46543 | get_user_ip | train | def get_user_ip(request):
"""Return user ip
:param request: Django request object
:return: user ip
"""
ip = get_real_ip(request)
if ip is None:
ip = get_ip(request)
if ip is None:
ip = '127.0.0.1'
return ip | python | {
"resource": ""
} |
q46544 | msvd | train | def msvd(m):
"""Modified singular value decomposition.
Returns U, S, V where Udagger M V = diag(S) and the singular values
are sorted in ascending order (small to large).
"""
u, s, vdgr = np.linalg.svd(m)
order = s.argsort()
# reverse the n first columns of u
s = s[order]
u= u[:,order]
vdgr = vdgr[... | python | {
"resource": ""
} |
q46545 | APIConnection._parse_parameters | train | def _parse_parameters(self, resource, params):
'''Creates a dictionary from query_string and `params`
Transforms the `?key=value&...` to a {'key': 'value'} and adds
(or overwrites if already present) the value with the dictionary in
`params`.
'''
# remove params from res... | python | {
"resource": ""
} |
q46546 | get_vep_info | train | def get_vep_info(vep_string, vep_header):
"""Make the vep annotations into a dictionaries
A vep dictionary will have the vep column names as keys and
the vep annotations as values.
The dictionaries are stored in a list
Args:
vep_string (string): A string with the C... | python | {
"resource": ""
} |
q46547 | get_snpeff_info | train | def get_snpeff_info(snpeff_string, snpeff_header):
"""Make the vep annotations into a dictionaries
A snpeff dictionary will have the snpeff column names as keys and
the vep annotations as values.
The dictionaries are stored in a list.
One dictionary for each transcript.
... | python | {
"resource": ""
} |
q46548 | RegularExpressionCondition.match | train | def match(self, row):
"""
Returns True if the field matches the regular expression of this simple condition. Returns False otherwise.
:param dict row: The row.
:rtype: bool
"""
if re.search(self._expression, row[self._field]):
return True
return Fal... | python | {
"resource": ""
} |
q46549 | Horoscope._get_horoscope | train | def _get_horoscope(self, day='today'):
"""gets a horoscope from site html
:param day: day for which to get horoscope. Default is 'today'
:returns: dictionary of horoscope details
"""
if not is_valid_day(day):
raise HoroscopeException("Invalid day. Allowed days: [tod... | python | {
"resource": ""
} |
q46550 | Horoscope._get_horoscope_meta | train | def _get_horoscope_meta(self, day='today'):
"""gets a horoscope meta from site html
:param day: day for which to get horoscope meta. Default is 'today'
:returns: dictionary of horoscope mood details
"""
if not is_valid_day(day):
raise HoroscopeException("Invalid day... | python | {
"resource": ""
} |
q46551 | Operation.process | train | def process(self, sched, coro):
"""This is called when the operation is to be processed by the
scheduler. Code here works modifies the scheduler and it's usualy
very crafty. Subclasses usualy overwrite this method and call it from
the superclass."""
if self.prio == priorit... | python | {
"resource": ""
} |
q46552 | TimedOperation.process | train | def process(self, sched, coro):
"""Add the timeout in the scheduler, check for defaults."""
super(TimedOperation, self).process(sched, coro)
if sched.default_timeout and not self.timeout:
self.set_timeout(sched.default_timeout)
if self.timeout and self.timeout != -1:
... | python | {
"resource": ""
} |
q46553 | WaitForSignal.process | train | def process(self, sched, coro):
"""Add the calling coro in a waiting for signal queue."""
super(WaitForSignal, self).process(sched, coro)
waitlist = sched.sigwait[self.name]
waitlist.append((self, coro))
if self.name in sched.signals:
sig = sched.signals[self.na... | python | {
"resource": ""
} |
q46554 | WaitForSignal.cleanup | train | def cleanup(self, sched, coro):
"""Remove this coro from the waiting for signal queue."""
try:
sched.sigwait[self.name].remove((self, coro))
except ValueError:
pass
return True | python | {
"resource": ""
} |
q46555 | Signal.process | train | def process(self, sched, coro):
"""If there aren't enough coroutines waiting for the signal as the
recipicient param add the calling coro in another queue to be activated
later, otherwise activate the waiting coroutines."""
super(Signal, self).process(sched, coro)
self.resul... | python | {
"resource": ""
} |
q46556 | AddCoro.finalize | train | def finalize(self, sched):
"""Return a reference to the instance of the newly added coroutine."""
super(AddCoro, self).finalize(sched)
return self.result | python | {
"resource": ""
} |
q46557 | AddCoro.process | train | def process(self, sched, coro):
"""Add the given coroutine in the scheduler."""
super(AddCoro, self).process(sched, coro)
self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP)
if self.prio & priority.CORO:
return self, coro
else:
... | python | {
"resource": ""
} |
q46558 | addToStore | train | def addToStore(store, identifier, name):
"""Adds a persisted factory with given identifier and object name to
the given store.
This is intended to have the identifier and name partially
applied, so that a particular module with an exercise in it can
just have an ``addToStore`` function that remembe... | python | {
"resource": ""
} |
q46559 | IOCPProactor.run | train | def run(self, timeout = 0):
"""
Calls GetQueuedCompletionStatus and handles completion via
IOCPProactor.process_op.
"""
# same resolution as epoll
ptimeout = int(
timeout.days * 86400000 +
timeout.microseconds / 1000 +
timeout.... | python | {
"resource": ""
} |
q46560 | html_from_markdown | train | def html_from_markdown(markdown):
""" Takes raw markdown, returns html result from GitHub api """
if login:
r = requests.get(gh_url+"/rate_limit", auth=login.auth())
if r.status_code >= 400:
if r.status_code != 401:
err = RequestError('Bad HTTP Status Code: %s' % r.s... | python | {
"resource": ""
} |
q46561 | standalone | train | def standalone(body):
""" Returns complete html document given markdown html """
with open(_ROOT + '/html.dat', 'r') as html_template:
head = html_title()
html = "".join(html_template.readlines()) \
.replace("{{HEAD}}", head) \
.replace("{{BODY}}", body)
... | python | {
"resource": ""
} |
q46562 | run_server | train | def run_server(port=8000):
""" Runs server on port with html response """
from http.server import BaseHTTPRequestHandler, HTTPServer
class VerboseHTMLHandler(BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
... | python | {
"resource": ""
} |
q46563 | stringClade | train | def stringClade(taxrefs, name, at):
'''Return a Newick string from a list of TaxRefs'''
string = []
for ref in taxrefs:
# distance is the difference between the taxonomic level of the ref
# and the current level of the tree growth
d = float(at-ref.level)
# ensure no spaces i... | python | {
"resource": ""
} |
q46564 | taxTree | train | def taxTree(taxdict):
"""Return taxonomic Newick tree"""
# the taxonomic dictionary holds the lineage of each ident in
# the same order as the taxonomy
# use hierarchy to construct a taxonomic tree
for rank in taxdict.taxonomy:
current_level = float(taxdict.taxonomy.index(rank))
# g... | python | {
"resource": ""
} |
q46565 | TaxDict._group | train | def _group(self, taxslice):
'''Return list of lists of idents grouped by shared rank'''
res = []
while taxslice:
taxref, lident = taxslice.pop()
if lident == '':
res.append(([taxref], lident))
else:
# identify idents in the same... | python | {
"resource": ""
} |
q46566 | TaxDict._hierarchy | train | def _hierarchy(self):
'''Generate dictionary of referenced idents grouped by shared rank'''
self.hierarchy = {}
for rank in self.taxonomy:
# extract lineage idents for this rank
taxslice = self._slice(level=self.taxonomy.index(rank))
# group idents by shared g... | python | {
"resource": ""
} |
q46567 | Library.register | train | def register(self, bucket, name_or_func, func=None):
"""
Add a function to the registry by name
"""
assert bucket in self, 'Bucket %s is unknown' % bucket
if func is None and hasattr(name_or_func, '__name__'):
name = name_or_func.__name__
func = name_or_fu... | python | {
"resource": ""
} |
q46568 | Library.unregister | train | def unregister(self, bucket, name):
"""
Remove the function from the registry by name
"""
assert bucket in self, 'Bucket %s is unknown' % bucket
if not name in self[bucket]:
raise NotRegistered('The function %s is not registered' % name)
del self[bucket][name] | python | {
"resource": ""
} |
q46569 | Library.get_doc | train | def get_doc(self, tag_name):
"Get documentation for the first tag matching the given name"
for tag,func in self.tags:
if tag.startswith(tag_name) and func.__doc__:
return func.__doc__ | python | {
"resource": ""
} |
q46570 | Library.get_bucket | train | def get_bucket(self, name):
"Find out which bucket a given tag name is in"
for bucket in self:
for k,v in self[bucket].items():
if k == name:
return bucket | python | {
"resource": ""
} |
q46571 | Library.get | train | def get(self, name):
"Get the first tag function matching the given name"
for bucket in self:
for k,v in self[bucket].items():
if k == name:
return v | python | {
"resource": ""
} |
q46572 | open_listing_page | train | def open_listing_page(trailing_part_of_url):
"""
Opens a BBC radio tracklisting page based on trailing part of url.
Returns a lxml ElementTree derived from that page.
trailing_part_of_url: a string, like the pid or e.g. pid/segments.inc
"""
base_url = 'http://www.bbc.co.uk/programmes/'
prin... | python | {
"resource": ""
} |
q46573 | get_programme_title | train | def get_programme_title(pid):
"""Take BBC programme ID as string; returns programme title as string."""
print("Extracting title and station...")
main_page_etree = open_listing_page(pid)
try:
title, = main_page_etree.xpath('//title/text()')
except ValueError:
title = ''
return tit... | python | {
"resource": ""
} |
q46574 | generate_output | train | def generate_output(listing, title, date):
"""
Returns a string containing a full tracklisting.
listing: list of (artist(s), track, record label) tuples
title: programme title
date: programme date
"""
listing_string = '{0}\n{1}\n\n'.format(title, date)
for entry in listing:
list... | python | {
"resource": ""
} |
q46575 | get_output_filename | train | def get_output_filename(args):
"""Returns a filename as string without an extension."""
# If filename and path provided, use these for output text file.
if args.directory is not None and args.fileprefix is not None:
path = args.directory
filename = args.fileprefix
output = os.path.jo... | python | {
"resource": ""
} |
q46576 | write_listing_to_textfile | train | def write_listing_to_textfile(textfile, tracklisting):
"""Write tracklisting to a text file."""
with codecs.open(textfile, 'wb', 'utf-8') as text:
text.write(tracklisting) | python | {
"resource": ""
} |
q46577 | save_tag_to_audio_file | train | def save_tag_to_audio_file(audio_file, tracklisting):
"""
Saves tag to audio file.
"""
print("Trying to tag {}".format(audio_file))
f = mediafile.MediaFile(audio_file)
if not f.lyrics:
print("No tracklisting present. Creating lyrics tag.")
f.lyrics = 'Tracklisting' + '\n' + trac... | python | {
"resource": ""
} |
q46578 | tag_audio_file | train | def tag_audio_file(audio_file, tracklisting):
"""
Adds tracklisting as list to lyrics tag of audio file if not present.
Returns True if successful or not needed, False if tagging fails.
"""
try:
save_tag_to_audio_file(audio_file, tracklisting)
# TODO: is IOError required now or would the... | python | {
"resource": ""
} |
q46579 | output_to_file | train | def output_to_file(filename, tracklisting, action):
"""
Produce requested output; either output text file, tag audio file or do
both.
filename: a string of path + filename without file extension
tracklisting: a string containing a tracklisting
action: 'tag', 'text' or 'both', from command line ... | python | {
"resource": ""
} |
q46580 | write_text | train | def write_text(filename, tracklisting):
"""Handle writing tracklisting to text."""
print("Saving text file.")
try:
write_listing_to_textfile(filename + '.txt', tracklisting)
except IOError:
# if all else fails, just print listing
print("Cannot write text file to path: {}".format(... | python | {
"resource": ""
} |
q46581 | tag_audio | train | def tag_audio(filename, tracklisting):
"""Return True if audio tagged successfully; handle tagging audio."""
# TODO: maybe actually glob for files, then try tagging if present?
if not(tag_audio_file(filename + '.m4a', tracklisting) or
tag_audio_file(filename + '.mp3', tracklisting)):
prin... | python | {
"resource": ""
} |
q46582 | main | train | def main():
"""Get a tracklisting, write to audio file or text."""
args = parse_arguments()
pid = args.pid
title = get_programme_title(pid)
broadcast_date = get_broadcast_date(pid)
listing = extract_listing(pid)
filename = get_output_filename(args)
tracklisting = generate_output(listing,... | python | {
"resource": ""
} |
q46583 | createsuperusers | train | def createsuperusers():
"""
Creates all superusers defined in settings.INITIAL_SUPERUSERS.
These superusers do not have any circles. They are plain superusers.
However you may want to signup yourself and make this new user a super user then.
"""
from django.contrib.auth import models as auth_mod... | python | {
"resource": ""
} |
q46584 | Transformer._log | train | def _log(message):
"""
Logs a message.
:param str message: The log message.
:rtype: None
"""
# @todo Replace with log package.
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ' ' + str(message), flush=True) | python | {
"resource": ""
} |
q46585 | Transformer._handle_exception | train | def _handle_exception(self, row, exception):
"""
Logs an exception occurred during transformation of a row.
:param list|dict|() row: The source row.
:param Exception exception: The exception.
"""
self._log('Error during processing of line {0:d}.'.format(self._source_read... | python | {
"resource": ""
} |
q46586 | Transformer._transform_rows | train | def _transform_rows(self):
"""
Transforms all source rows.
"""
self._find_all_step_methods()
for row in self._source_reader.next():
self._transform_row_wrapper(row) | python | {
"resource": ""
} |
q46587 | Transformer._transform_row_wrapper | train | def _transform_row_wrapper(self, row):
"""
Transforms a single source row.
:param dict[str|str] row: The source row.
"""
self._count_total += 1
try:
# Transform the naturals keys in line to technical keys.
in_row = copy.copy(row)
out_... | python | {
"resource": ""
} |
q46588 | Transformer._step00 | train | def _step00(self, in_row, tmp_row, out_row):
"""
Prunes whitespace for all fields in the input row.
:param dict in_row: The input row.
:param dict tmp_row: Not used.
:param dict out_row: Not used.
"""
for key, value in in_row.items():
in_row[key] = Wh... | python | {
"resource": ""
} |
q46589 | Transformer._step99 | train | def _step99(self, in_row, tmp_row, out_row):
"""
Validates all mandatory fields are in the output row and are filled.
:param dict in_row: The input row.
:param dict tmp_row: Not used.
:param dict out_row: The output row.
"""
park_info = ''
for field in se... | python | {
"resource": ""
} |
q46590 | Transformer._log_statistics | train | def _log_statistics(self):
"""
Log statistics about the number of rows and number of rows per second.
"""
rows_per_second_trans = self._count_total / (self._time1 - self._time0)
rows_per_second_load = self._count_transform / (self._time2 - self._time1)
rows_per_second_ove... | python | {
"resource": ""
} |
q46591 | ListTagCallMixin.list_tags | train | def list_tags(self):
"""
Get the tags of current object
:return: the tags
:rtype: list
"""
from highton.models.tag import Tag
return fields.ListField(
name=self.ENDPOINT,
init_class=Tag
).decode(
self.element_from_strin... | python | {
"resource": ""
} |
q46592 | _clean_dict | train | def _clean_dict(target_dict, whitelist=None):
""" Convenience function that removes a dicts keys that have falsy values
"""
assert isinstance(target_dict, dict)
return {
ustr(k).strip(): ustr(v).strip()
for k, v in target_dict.items()
if v not in (None, Ellipsis, [], (), "")
... | python | {
"resource": ""
} |
q46593 | _request_json | train | def _request_json(
url,
parameters=None,
body=None,
headers=None,
cache=True,
agent=None,
reattempt=5,
):
""" Queries a url for json data
Note: Requests are cached using requests_cached for a week, this is done
transparently by using the package's monkey patching
"""
ass... | python | {
"resource": ""
} |
q46594 | tmdb_find | train | def tmdb_find(
api_key, external_source, external_id, language="en-US", cache=True
):
""" Search for The Movie Database objects using another DB's foreign key
Note: language codes aren't checked on this end or by TMDb, so if you
enter an invalid language code your search itself will succeed, but
... | python | {
"resource": ""
} |
q46595 | tmdb_movies | train | def tmdb_movies(api_key, id_tmdb, language="en-US", cache=True):
""" Lookup a movie item using The Movie Database
Online docs: developers.themoviedb.org/3/movies
"""
try:
url = "https://api.themoviedb.org/3/movie/%d" % int(id_tmdb)
except ValueError:
raise MapiProviderException("id_... | python | {
"resource": ""
} |
q46596 | tmdb_search_movies | train | def tmdb_search_movies(
api_key, title, year=None, adult=False, region=None, page=1, cache=True
):
""" Search for movies using The Movie Database
Online docs: developers.themoviedb.org/3/search/search-movies
"""
url = "https://api.themoviedb.org/3/search/movie"
try:
if year:
... | python | {
"resource": ""
} |
q46597 | tvdb_login | train | def tvdb_login(api_key):
""" Logs into TVDb using the provided api key
Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister
Online docs: api.thetvdb.com/swagger#!/Authentication/post_login=
"""
url = "https://api.thetvdb.com/login"
body = {"apikey": api_key}
status, co... | python | {
"resource": ""
} |
q46598 | tvdb_refresh_token | train | def tvdb_refresh_token(token):
""" Refreshes JWT token
Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token=
"""
url = "https://api.thetvdb.com/refresh_token"
headers = {"Authorization": "Bearer %s" % token}
status, content = _request_json(url, headers=headers, cache=False)
... | python | {
"resource": ""
} |
q46599 | tvdb_series_id | train | def tvdb_series_id(token, id_tvdb, lang="en", cache=True):
""" Returns a series records that contains all information known about a
particular series id
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id=
"""
if lang not in TVDB_LANGUAGE_CODES:
raise MapiProviderException(
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.