_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q241200 | spline_backwards_hankel | train | def spline_backwards_hankel(ht, htarg, opt):
r"""Check opt if deprecated 'spline' is used.
Returns corrected htarg, opt.
r"""
# Ensure ht is all lowercase
ht = ht.lower()
# Only relevant for 'fht' and 'hqwe', not for 'quad'
if ht in ['fht', 'qwe', 'hqwe']:
# Get corresponding htar... | python | {
"resource": ""
} |
q241201 | gpr | train | def gpr(src, rec, depth, res, freqtime, cf, gain=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='quad', htarg=None, ft='fft', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the Ground-Penetrating Radar signal.
THIS FUNCTION IS EXPERI... | python | {
"resource": ""
} |
q241202 | dipole_k | train | def dipole_k(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic dip... | python | {
"resource": ""
} |
q241203 | wavenumber | train | def wavenumber(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
r"""Depreciated. Use `dipole_k` instead."""
# Issue warning
mesg = ("\n The use of `model.wavenumber` is deprecated and will " +
"be removed;\... | python | {
"resource": ""
} |
q241204 | tem | train | def tem(fEM, off, freq, time, signal, ft, ftarg, conv=True):
r"""Return the time-domain response of the frequency-domain response fEM.
This function is called from one of the above modelling routines. No
input-check is carried out here. See the main description of :mod:`model`
for information regarding... | python | {
"resource": ""
} |
q241205 | save_filter | train | def save_filter(name, filt, full=None, path='filters'):
r"""Save DLF-filter and inversion output to plain text files."""
# First we'll save the filter using its internal routine.
# This will create the directory ./filters if it doesn't exist already.
filt.tofile(path)
# If full, we store the inver... | python | {
"resource": ""
} |
q241206 | load_filter | train | def load_filter(name, full=False, path='filters'):
r"""Load saved DLF-filter and inversion output from text files."""
# First we'll get the filter using its internal routine.
filt = DigitalFilter(name.split('.')[0])
filt.fromfile(path)
# If full, we get the inversion output
if full:
# ... | python | {
"resource": ""
} |
q241207 | plot_result | train | def plot_result(filt, full, prntres=True):
r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r"""
# Check matplotlib (soft dependency)
if not plt:
pr... | python | {
"resource": ""
} |
q241208 | print_result | train | def print_result(filt, full=None):
r"""Print best filter information.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
"""
print(' Filter length : %d' % filt.base.size)
print(' Best filter')
if full: # If full provided, we have more infor... | python | {
"resource": ""
} |
q241209 | _call_qc_transform_pairs | train | def _call_qc_transform_pairs(n, ispacing, ishift, fI, fC, r, r_def, reim):
r"""QC the input transform pairs."""
print('* QC: Input transform-pairs:')
print(' fC: x-range defined through ``n``, ``spacing``, ``shift``, and ' +
'``r``-parameters; b-range defined through ``r``-parameter.')
print(... | python | {
"resource": ""
} |
q241210 | _plot_transform_pairs | train | def _plot_transform_pairs(fCI, r, k, axes, tit):
r"""Plot the input transform pairs."""
# Plot lhs
plt.sca(axes[0])
plt.title('|' + tit + ' lhs|')
for f in fCI:
if f.name == 'j2':
lhs = f.lhs(k)
plt.loglog(k, np.abs(lhs[0]), lw=2, label='j0')
plt.loglog(k... | python | {
"resource": ""
} |
q241211 | _plot_inversion | train | def _plot_inversion(f, rhs, r, k, imin, spacing, shift, cvar):
r"""QC the resulting filter."""
# Check matplotlib (soft dependency)
if not plt:
print(plt_msg)
return
plt.figure("Inversion result "+f.name, figsize=(9.5, 4))
plt.subplots_adjust(wspace=.3, bottom=0.2)
plt.clf()
... | python | {
"resource": ""
} |
q241212 | empy_hankel | train | def empy_hankel(ftype, zsrc, zrec, res, freqtime, depth=None, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None,
htarg=None, verblhs=0, verbrhs=0):
r"""Numerical transform pair with empymod.
All parameters except ``ftype``, ``verblhs``, and ``verbrhs`` correspond to... | python | {
"resource": ""
} |
q241213 | _get_min_val | train | def _get_min_val(spaceshift, *params):
r"""Calculate minimum resolved amplitude or maximum r."""
# Get parameters from tuples
spacing, shift = spaceshift
n, fI, fC, r, r_def, error, reim, cvar, verb, plot, log = params
# Get filter for these parameters
dlf = _calculate_filter(n, spacing, shift... | python | {
"resource": ""
} |
q241214 | _calculate_filter | train | def _calculate_filter(n, spacing, shift, fI, r_def, reim, name):
r"""Calculate filter for this spacing, shift, n."""
# Base :: For this n/spacing/shift
base = np.exp(spacing*(np.arange(n)-n//2) + shift)
# r :: Start/end is defined by base AND r_def[0]/r_def[1]
# Overdetermined system if r_def... | python | {
"resource": ""
} |
q241215 | _print_count | train | def _print_count(log):
r"""Print run-count information."""
log['cnt2'] += 1 # Current number
cp = log['cnt2']/log['totnr']*100 # Percentage
if log['cnt2'] == 0: # Not sure about this; brute seems to call the
pass # function with the first arguments twice...
... | python | {
"resource": ""
} |
q241216 | wavenumber | train | def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd,
ab, xdirect, msrc, mrec, use_ne_eval):
r"""Calculate wavenumber domain solution.
Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``,
which have to be transformed with a Hankel transform to the f... | python | {
"resource": ""
} |
q241217 | reflections | train | def reflections(depth, e_zH, Gam, lrec, lsrc, use_ne_eval):
r"""Calculate Rp, Rm.
.. math:: R^\pm_n, \bar{R}^\pm_n
This function corresponds to equations 64/65 and A-11/A-12 in
[HuTS15]_, and loosely to the corresponding files ``Rmin.F90`` and
``Rplus.F90``.
This function is called from the f... | python | {
"resource": ""
} |
q241218 | angle_factor | train | def angle_factor(angle, ab, msrc, mrec):
r"""Return the angle-dependent factor.
The whole calculation in the wavenumber domain is only a function of the
distance between the source and the receiver, it is independent of the
angel. The angle-dependency is this factor, which can be applied to the
cor... | python | {
"resource": ""
} |
q241219 | versions | train | def versions(mode=None, add_pckg=None, ncol=4):
r"""Old func-way of class `Versions`, here for backwards compatibility.
``mode`` is not used any longer, dummy here.
"""
# Issue warning
mesg = ("\n Func `versions` is deprecated and will " +
"be removed; use Class `Versions` instead.")... | python | {
"resource": ""
} |
q241220 | Versions._repr_html_ | train | def _repr_html_(self):
"""HTML-rendered versions information."""
# Check ncol
ncol = int(self.ncol)
# Define html-styles
border = "border: 2px solid #fff;'"
def colspan(html, txt, ncol, nrow):
r"""Print txt in a row spanning whole table."""
html ... | python | {
"resource": ""
} |
q241221 | Versions._get_packages | train | def _get_packages(add_pckg):
r"""Create list of packages."""
# Mandatory packages
pckgs = [numpy, scipy, empymod]
# Optional packages
for module in [IPython, numexpr, matplotlib]:
if module:
pckgs += [module]
# Cast and add add_pckg
... | python | {
"resource": ""
} |
q241222 | DigitalFilter.tofile | train | def tofile(self, path='filters'):
r"""Save filter values to ascii-files.
Store the filter base and the filter coefficients in separate files
in the directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Load a fil... | python | {
"resource": ""
} |
q241223 | DigitalFilter.fromfile | train | def fromfile(self, path='filters'):
r"""Load filter values from ascii-files.
Load filter base and filter coefficients from ascii files in the
directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Create an empty ... | python | {
"resource": ""
} |
q241224 | fht | train | def fht(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, fhtarg, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the Digital Linear Filter method.
The *Digital Linear Filter* method was introduced to geophysics by
[Ghos70]_, and made popular and wide-spread b... | python | {
"resource": ""
} |
q241225 | hquad | train | def hquad(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, quadargs, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the ``QUADPACK`` library.
This routine uses the ``scipy.integrate.quad`` module, which in turn makes
use of the Fortran library ``QUADPACK``... | python | {
"resource": ""
} |
q241226 | ffht | train | def ffht(fEM, time, freq, ftarg):
r"""Fourier Transform using the Digital Linear Filter method.
It follows the Filter methodology [Ande75]_, using Cosine- and
Sine-filters; see ``fht`` for more information.
The function is called from one of the modelling routines in :mod:`model`.
Consult these m... | python | {
"resource": ""
} |
q241227 | fft | train | def fft(fEM, time, freq, ftarg):
r"""Fourier Transform using the Fast Fourier Transform.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling routines for a description of the input and output
parameters.
Returns
-------
tEM : array
Ret... | python | {
"resource": ""
} |
q241228 | quad | train | def quad(sPJ0r, sPJ0i, sPJ1r, sPJ1i, sPJ0br, sPJ0bi, ab, off, factAng, iinp):
r"""Quadrature for Hankel transform.
This is the kernel of the QUAD method, used for the Hankel transforms
``hquad`` and ``hqwe`` (where the integral is not suited for QWE).
"""
# Define the quadrature kernels
def q... | python | {
"resource": ""
} |
q241229 | get_spline_values | train | def get_spline_values(filt, inp, nr_per_dec=None):
r"""Return required calculation points."""
# Standard DLF
if nr_per_dec == 0:
return filt.base/inp[:, None], inp
# Get min and max required out-values (depends on filter and inp-value)
outmax = filt.base[-1]/inp.min()
outmin = filt.bas... | python | {
"resource": ""
} |
q241230 | fhti | train | def fhti(rmin, rmax, n, q, mu):
r"""Return parameters required for FFTLog."""
# Central point log10(r_c) of periodic interval
logrc = (rmin + rmax)/2
# Central index (1/2 integral if n is even)
nc = (n + 1)/2.
# Log spacing of points
dlogr = (rmax - rmin)/n
dlnr = dlogr*np.log(10.)
... | python | {
"resource": ""
} |
q241231 | _actual_get_cpu_info_from_cpuid | train | def _actual_get_cpu_info_from_cpuid(queue):
'''
Warning! This function has the potential to crash the Python runtime.
Do not call it directly. Use the _get_cpu_info_from_cpuid function instead.
It will safely call this function in another process.
'''
# Pipe all output to nothing
sys.stdout = open(os.devnull, '... | python | {
"resource": ""
} |
q241232 | get_cpu_info_json | train | def get_cpu_info_json():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string
'''
import json
output = None
# If running under pyinstaller, run normally
if getattr(sys, 'frozen', False):
info = _get_cpu_info_internal()
output = json.dumps(info... | python | {
"resource": ""
} |
q241233 | get_cpu_info | train | def get_cpu_info():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a dict
'''
import json
output = get_cpu_info_json()
# Convert JSON to Python with non unicode strings
output = json.loads(output, object_hook = _utf_to_str)
return output | python | {
"resource": ""
} |
q241234 | _verbs_with_subjects | train | def _verbs_with_subjects(doc):
"""Given a spacy document return the verbs that have subjects"""
# TODO: UNUSED
verb_subj = []
for possible_subject in doc:
if (possible_subject.dep_ == 'nsubj' and possible_subject.head.pos_ ==
'VERB'):
verb_subj.append([possible_subjec... | python | {
"resource": ""
} |
q241235 | mangle_agreement | train | def mangle_agreement(correct_sentence):
"""Given a correct sentence, return a sentence or sentences with a subject
verb agreement error"""
# # Examples
#
# Back in the 1800s, people were much shorter and much stronger.
# This sentence begins with the introductory phrase, 'back in the 1800s'
... | python | {
"resource": ""
} |
q241236 | _build_trigram_indices | train | def _build_trigram_indices(trigram_index):
"""Build a dictionary of trigrams and their indices from a csv"""
result = {}
trigram_count = 0
for key, val in csv.reader(open(trigram_index)):
result[key] = int(val)
trigram_count += 1
return result, trigram_count | python | {
"resource": ""
} |
q241237 | _begins_with_one_of | train | def _begins_with_one_of(sentence, parts_of_speech):
"""Return True if the sentence or fragment begins with one of the parts of
speech in the list, else False"""
doc = nlp(sentence)
if doc[0].tag_ in parts_of_speech:
return True
return False | python | {
"resource": ""
} |
q241238 | get_language_tool_feedback | train | def get_language_tool_feedback(sentence):
"""Get matches from languagetool"""
payload = {'language':'en-US', 'text':sentence}
try:
r = requests.post(LT_SERVER, data=payload)
except requests.exceptions.ConnectionError as e:
raise requests.exceptions.ConnectionError('''The languagetool ser... | python | {
"resource": ""
} |
q241239 | is_participle_clause_fragment | train | def is_participle_clause_fragment(sentence):
"""Supply a sentence or fragment and recieve a confidence interval"""
# short circuit if sentence or fragment doesn't start with a participle
# past participles can sometimes look like adjectives -- ie, Tired
if not _begins_with_one_of(sentence, ['VBG', 'VBN'... | python | {
"resource": ""
} |
q241240 | check | train | def check(sentence):
"""Supply a sentence or fragment and recieve feedback"""
# How we decide what to put as the human readable feedback
#
# Our order of prefence is,
#
# 1. Spelling errors.
# - A spelling error can change the sentence meaning
# 2. Subject-verb agreement errors
# ... | python | {
"resource": ""
} |
q241241 | list_submissions | train | def list_submissions():
"""List the past submissions with information about them"""
submissions = []
try:
submissions = session.query(Submission).all()
except SQLAlchemyError as e:
session.rollback()
return render_template('list_submissions.html', submissions=submissions) | python | {
"resource": ""
} |
q241242 | get_submissions | train | def get_submissions():
"""API endpoint to get submissions in JSON format"""
print(request.args.to_dict())
print(request.args.get('search[value]'))
print(request.args.get('draw', 1))
# submissions = session.query(Submission).all()
if request.args.get('correct_filter', 'all') == 'all':
co... | python | {
"resource": ""
} |
q241243 | check_sentence | train | def check_sentence():
"""Sole porcupine endpoint"""
text = ''
if request.method == 'POST':
text = request.form['text']
if not text:
error = 'No input'
flash_message = error
else:
fb = check(request.form['text'])
correct = False
... | python | {
"resource": ""
} |
q241244 | raise_double_modal_error | train | def raise_double_modal_error(verb_phrase_doc):
"""A modal auxilary verb should not follow another modal auxilary verb"""
prev_word = None
for word in verb_phrase:
if word.tag_ == 'MD' and prev_word.tag == 'MD':
raise('DoubleModalError')
prev_word = word | python | {
"resource": ""
} |
q241245 | raise_modal_error | train | def raise_modal_error(verb_phrase_doc):
"""Given a verb phrase, raise an error if the modal auxilary has an issue
with it"""
verb_phrase = verb_phrase_doc.text.lower()
bad_strings = ['should had', 'should has', 'could had', 'could has', 'would '
'had', 'would has'] ["should", "could", "would... | python | {
"resource": ""
} |
q241246 | split_infinitive_warning | train | def split_infinitive_warning(sentence_str):
"""Return a warning for a split infinitive, else, None"""
sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
inf_pattern = r'<PART><ADV><VERB>' # To aux/auxpass* csubj
infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
for inf ... | python | {
"resource": ""
} |
q241247 | raise_infinitive_error | train | def raise_infinitive_error(sentence_str):
"""Given a string, check that all infinitives are properly formatted"""
sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
inf_pattern = r'<PART|ADP><VERB>' # To aux/auxpass* csubj
infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
... | python | {
"resource": ""
} |
q241248 | drop_modifiers | train | def drop_modifiers(sentence_str):
"""Given a string, drop the modifiers and return a string
without them"""
tdoc = textacy.Doc(sentence_str, lang='en_core_web_lg')
new_sent = tdoc.text
unusual_char = '形'
for tag in tdoc:
if tag.dep_.endswith('mod'):
# Replace the tag
... | python | {
"resource": ""
} |
q241249 | cluster | train | def cluster(list_of_texts, num_clusters=3):
"""
Cluster a list of texts into a predefined number of clusters.
:param list_of_texts: a list of untokenized texts
:param num_clusters: the predefined number of clusters
:return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1]
"""
... | python | {
"resource": ""
} |
q241250 | find_topics | train | def find_topics(token_lists, num_topics=10):
""" Find the topics in a list of texts with Latent Dirichlet Allocation. """
dictionary = Dictionary(token_lists)
print('Number of unique words in original documents:', len(dictionary))
dictionary.filter_extremes(no_below=2, no_above=0.7)
print('Number o... | python | {
"resource": ""
} |
q241251 | fetch_bookshelf | train | def fetch_bookshelf(start_url, output_dir):
"""Fetch all the books off of a gutenberg project bookshelf page
example bookshelf page,
http://www.gutenberg.org/wiki/Children%27s_Fiction_(Bookshelf)
"""
# make output directory
try:
os.mkdir(OUTPUT_DIR + output_dir)
except OSError as e:... | python | {
"resource": ""
} |
q241252 | lemmatize | train | def lemmatize(text, lowercase=True, remove_stopwords=True):
""" Return the lemmas of the tokens in a text. """
doc = nlp(text)
if lowercase and remove_stopwords:
lemmas = [t.lemma_.lower() for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]
elif lowercase:
lemmas = [t.lemma_... | python | {
"resource": ""
} |
q241253 | inflate | train | def inflate(deflated_vector):
"""Given a defalated vector, inflate it into a np array and return it"""
dv = json.loads(deflated_vector)
#result = np.zeros(dv['reductions']) # some claim vector length 5555, others
#5530. this could have occurred doing remote computations? or something.
# anyhow, we w... | python | {
"resource": ""
} |
q241254 | text_to_vector | train | def text_to_vector(sent_str):
"""Given a string, get it's defalted vector, inflate it, then return the
inflated vector"""
r = requests.get("{}/sva/vector".format(VECTORIZE_API), params={'s':sent_str})
return inflate(r.text) | python | {
"resource": ""
} |
q241255 | detect_missing_verb | train | def detect_missing_verb(sentence):
"""Return True if the sentence appears to be missing a main verb"""
# TODO: should this be relocated?
doc = nlp(sentence)
for w in doc:
if w.tag_.startswith('VB') and w.dep_ == 'ROOT':
return False # looks like there is at least 1 main verb
retu... | python | {
"resource": ""
} |
q241256 | detect_infinitive_phrase | train | def detect_infinitive_phrase(sentence):
"""Given a string, return true if it is an infinitive phrase fragment"""
# eliminate sentences without to
if not 'to' in sentence.lower():
return False
doc = nlp(sentence)
prev_word = None
for w in doc:
# if statement will execute exactly... | python | {
"resource": ""
} |
q241257 | perform_srl | train | def perform_srl(responses, prompt):
""" Perform semantic role labeling on a list of responses, given a prompt."""
predictor = Predictor.from_path("https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz")
sentences = [{"sentence": prompt + " " + response} for response in responses]
... | python | {
"resource": ""
} |
q241258 | detokenize | train | def detokenize(s):
""" Detokenize a string by removing spaces before punctuation."""
print(s)
s = re.sub("\s+([;:,\.\?!])", "\\1", s)
s = re.sub("\s+(n't)", "\\1", s)
return s | python | {
"resource": ""
} |
q241259 | Task.start | train | def start(self):
"""This method starts a task executing and returns immediately.
Subclass should override this method, if it has an asynchronous
way to start the task and return immediately.
"""
if self.threadPool:
self.threadPool.addTask(self)
# Lets oth... | python | {
"resource": ""
} |
q241260 | Task.init_and_start | train | def init_and_start(self, taskParent, override={}):
"""Convenience method to initialize and start a task.
"""
tag = self.initialize(taskParent, override=override)
self.start()
return tag | python | {
"resource": ""
} |
q241261 | Task.wait | train | def wait(self, timeout=None):
"""This method waits for an executing task to finish.
Subclass can override this method if necessary.
"""
self.ev_done.wait(timeout=timeout)
if not self.ev_done.is_set():
raise TaskTimeout("Task %s timed out." % self)
# --> self... | python | {
"resource": ""
} |
q241262 | Task.done | train | def done(self, result, noraise=False):
"""This method is called when a task has finished executing.
Subclass can override this method if desired, but should call
superclass method at the end.
"""
# [??] Should this be in a critical section?
# Has done() already been call... | python | {
"resource": ""
} |
q241263 | Task.runTask | train | def runTask(self, task, timeout=None):
"""Run a child task to completion. Returns the result of
the child task.
"""
# Initialize the task.
task.initialize(self)
# Start the task.
task.start()
# Lets other threads run
time.sleep(0)
# Wai... | python | {
"resource": ""
} |
q241264 | SequentialTaskset.execute | train | def execute(self):
"""Run all child tasks, in order, waiting for completion of each.
Return the result of the final child task's execution.
"""
while self.index < len(self.tasklist):
res = self.step()
self.logger.debug('SeqSet task %i has completed with result %s'... | python | {
"resource": ""
} |
q241265 | oldConcurrentAndTaskset.execute | train | def execute(self):
"""Run all child tasks concurrently in separate threads.
Return 0 after all child tasks have completed execution.
"""
self.count = 0
self.taskset = []
self.results = {}
self.totaltime = time.time()
# Register termination callbacks for a... | python | {
"resource": ""
} |
q241266 | newConcurrentAndTaskset.execute | train | def execute(self):
"""Run all child tasks concurrently in separate threads.
Return last result after all child tasks have completed execution.
"""
with self._lock_c:
self.count = 0
self.numtasks = 0
self.taskset = []
self.results = {}
... | python | {
"resource": ""
} |
q241267 | WorkerThread.execute | train | def execute(self, task):
"""Execute a task.
"""
taskid = str(task)
res = None
try:
# Try to run the task. If we catch an exception, then
# it becomes the result.
self.time_start = time.time()
self.setstatus('executing %s' % taskid... | python | {
"resource": ""
} |
q241268 | ThreadPool.startall | train | def startall(self, wait=False, **kwdargs):
"""Start all of the threads in the thread pool. If _wait_ is True
then don't return until all threads are up and running. Any extra
keyword arguments are passed to the worker thread constructor.
"""
self.logger.debug("startall called")... | python | {
"resource": ""
} |
q241269 | ThreadPool.stopall | train | def stopall(self, wait=False):
"""Stop all threads in the worker pool. If _wait_ is True
then don't return until all threads are down.
"""
self.logger.debug("stopall called")
with self.regcond:
while self.status != 'up':
if self.status in ('stop', 'do... | python | {
"resource": ""
} |
q241270 | wcs_pix_transform | train | def wcs_pix_transform(ct, i, format=0):
"""Computes the WCS corrected pixel value given a coordinate
transformation and the raw pixel value.
Input:
ct coordinate transformation. instance of coord_tran.
i raw pixel intensity.
format format string (optional).
Returns:
WCS cor... | python | {
"resource": ""
} |
q241271 | IIS_DataListener.handle_request | train | def handle_request(self):
"""
Handles incoming connections, one at the time.
"""
try:
(request, client_address) = self.get_request()
except socket.error as e:
# Error handling goes here.
self.logger.error("error opening the connection: %s" % (... | python | {
"resource": ""
} |
q241272 | IIS_DataListener.mainloop | train | def mainloop(self):
"""main control loop."""
try:
while (not self.ev_quit.is_set()):
try:
self.handle_request()
except socketTimeout:
continue
finally:
self.socket.close() | python | {
"resource": ""
} |
q241273 | IIS_RequestHandler.handle_feedback | train | def handle_feedback(self, pkt):
"""This part of the protocol is used by IRAF to erase a frame in
the framebuffers.
"""
self.logger.debug("handle feedback")
self.frame = self.decode_frameno(pkt.z & 0o7777) - 1
# erase the frame buffer
self.server.controller.init_f... | python | {
"resource": ""
} |
q241274 | IIS_RequestHandler.handle_lut | train | def handle_lut(self, pkt):
"""This part of the protocol is used by IRAF to set the frame number.
"""
self.logger.debug("handle lut")
if pkt.subunit & COMMAND:
data_type = str(pkt.nbytes / 2) + 'h'
#size = struct.calcsize(data_type)
line = pkt.datain.re... | python | {
"resource": ""
} |
q241275 | IIS_RequestHandler.handle_imcursor | train | def handle_imcursor(self, pkt):
"""This part of the protocol is used by IRAF to read the cursor
position and keystrokes from the display client.
"""
self.logger.debug("handle imcursor")
if pkt.tid & IIS_READ:
if pkt.tid & IMC_SAMPLE:
self.logger.debug... | python | {
"resource": ""
} |
q241276 | IIS_RequestHandler.handle | train | def handle(self):
"""
This is where the action starts.
"""
self.logger = self.server.logger
# create a packet structure
packet = iis()
packet.datain = self.rfile
packet.dataout = self.wfile
# decode the header
size = struct.calcsize('8h')... | python | {
"resource": ""
} |
q241277 | IIS_RequestHandler.display_image | train | def display_image(self, reset=1):
"""Utility routine used to display an updated frame from a framebuffer.
"""
try:
fb = self.server.controller.get_frame(self.frame)
except KeyError:
# the selected frame does not exist, create it
fb = self.server.contro... | python | {
"resource": ""
} |
q241278 | Contents._highlight_path | train | def _highlight_path(self, hl_path, tf):
"""Highlight or unhighlight a single entry.
Examples
--------
>>> hl_path = self._get_hl_key(chname, image)
>>> self._highlight_path(hl_path, True)
"""
fc = self.settings.get('row_font_color', 'green')
try:
... | python | {
"resource": ""
} |
q241279 | Contents.update_highlights | train | def update_highlights(self, old_highlight_set, new_highlight_set):
"""Unhighlight the entries represented by ``old_highlight_set``
and highlight the ones represented by ``new_highlight_set``.
Both are sets of keys.
"""
if not self.gui_up:
return
un_hilite_s... | python | {
"resource": ""
} |
q241280 | CatalogListing.show_selection | train | def show_selection(self, star):
"""This method is called when the user clicks on a plotted star in the
fitsviewer.
"""
try:
# NOTE: this works around a quirk of Qt widget set where
# selecting programatically in the table triggers the widget
# selectio... | python | {
"resource": ""
} |
q241281 | CatalogListing.select_star_cb | train | def select_star_cb(self, widget, res_dict):
"""This method is called when the user selects a star from the table.
"""
keys = list(res_dict.keys())
if len(keys) == 0:
self.selected = []
self.replot_stars()
else:
idx = int(keys[0])
st... | python | {
"resource": ""
} |
q241282 | BaseImage._calc_order | train | def _calc_order(self, order):
"""Called to set the order of a multi-channel image.
The order should be determined by the loader, but this will
make a best guess if passed `order` is `None`.
"""
if order is not None and order != '':
self.order = order.upper()
e... | python | {
"resource": ""
} |
q241283 | BaseImage.cutout_data | train | def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, astype=None):
"""cut out data area based on coords.
"""
view = np.s_[y1:y2:ystep, x1:x2:xstep]
data = self._slice(view)
if astype:
data = data.astype(astype, copy=False)
return data | python | {
"resource": ""
} |
q241284 | BaseImage.get_shape_mask | train | def get_shape_mask(self, shape_obj):
"""
Return full mask where True marks pixels within the given shape.
"""
wd, ht = self.get_size()
yi = np.mgrid[:ht].reshape(-1, 1)
xi = np.mgrid[:wd].reshape(1, -1)
pts = np.asarray((xi, yi)).T
contains = shape_obj.con... | python | {
"resource": ""
} |
q241285 | BaseImage.get_shape_view | train | def get_shape_view(self, shape_obj, avoid_oob=True):
"""
Calculate a bounding box in the data enclosing `shape_obj` and
return a view that accesses it and a mask that is True only for
pixels enclosed in the region.
If `avoid_oob` is True (default) then the bounding box is clippe... | python | {
"resource": ""
} |
q241286 | BaseImage.cutout_shape | train | def cutout_shape(self, shape_obj):
"""
Cut out and return a portion of the data corresponding to `shape_obj`.
A masked numpy array is returned, where the pixels not enclosed in
the shape are masked out.
"""
view, mask = self.get_shape_view(shape_obj)
# cutout ou... | python | {
"resource": ""
} |
q241287 | Callbacks.remove_callback | train | def remove_callback(self, name, fn, *args, **kwargs):
"""Remove a specific callback that was added.
"""
try:
tup = (fn, args, kwargs)
if tup in self.cb[name]:
self.cb[name].remove(tup)
except KeyError:
raise CallbackError("No callback c... | python | {
"resource": ""
} |
q241288 | cmap2pixmap | train | def cmap2pixmap(cmap, steps=50):
"""Convert a Ginga colormap into a QPixmap
"""
import numpy as np
inds = np.linspace(0, 1, steps)
n = len(cmap.clst) - 1
tups = [cmap.clst[int(x * n)] for x in inds]
rgbas = [QColor(int(r * 255), int(g * 255),
int(b * 255), 255).rgba() fo... | python | {
"resource": ""
} |
q241289 | Timer.start | train | def start(self, duration=None):
"""Start the timer. If `duration` is not None, it should
specify the time to expiration in seconds.
"""
if duration is None:
duration = self.duration
self.set(duration) | python | {
"resource": ""
} |
q241290 | ScreenShot._snap_cb | train | def _snap_cb(self, w):
"""This function is called when the user clicks the 'Snap' button.
"""
# Clear the snap image viewer
self.scrnimage.clear()
self.scrnimage.redraw_now(whence=0)
self.fv.update_pending()
format = self.tosave_type
if self._screen_size... | python | {
"resource": ""
} |
q241291 | ScreenShot._save_cb | train | def _save_cb(self, w):
"""This function is called when the user clicks the 'Save' button.
We save the last taken shot to the folder and name specified.
"""
format = self.saved_type
if format is None:
return self.fv.show_error("Please save an image first.")
# ... | python | {
"resource": ""
} |
q241292 | ScreenShot._lock_aspect_cb | train | def _lock_aspect_cb(self, w, tf):
"""This function is called when the user clicks the 'Lock aspect'
checkbox. `tf` is True if checked, False otherwise.
"""
self._lock_aspect = tf
self.w.aspect.set_enabled(tf)
if self._lock_aspect:
self._set_aspect_cb()
... | python | {
"resource": ""
} |
q241293 | ScreenShot._screen_size_cb | train | def _screen_size_cb(self, w, tf):
"""This function is called when the user clicks the 'Screen size'
checkbox. `tf` is True if checked, False otherwise.
"""
self._screen_size = tf
self.w.width.set_enabled(not tf)
self.w.height.set_enabled(not tf)
self.w.lock_aspec... | python | {
"resource": ""
} |
q241294 | load_asdf | train | def load_asdf(asdf_obj, data_key='sci', wcs_key='wcs', header_key='meta'):
"""
Load from an ASDF object.
Parameters
----------
asdf_obj : obj
ASDF or ASDF-in-FITS object.
data_key, wcs_key, header_key : str
Key values to specify where to find data, WCS, and header
in AS... | python | {
"resource": ""
} |
q241295 | Colorbar._match_cmap | train | def _match_cmap(self, fitsimage, colorbar):
"""
Help method to change the ColorBar to match the cut levels or
colormap used in a ginga ImageView.
"""
rgbmap = fitsimage.get_rgbmap()
loval, hival = fitsimage.get_cut_levels()
colorbar.set_range(loval, hival)
... | python | {
"resource": ""
} |
q241296 | Colorbar.rgbmap_cb | train | def rgbmap_cb(self, rgbmap, channel):
"""
This method is called when the RGBMap is changed. We update
the ColorBar to match.
"""
if not self.gui_up:
return
fitsimage = channel.fitsimage
if fitsimage != self.fv.getfocus_fitsimage():
return ... | python | {
"resource": ""
} |
q241297 | show_mode_indicator | train | def show_mode_indicator(viewer, tf, corner='ur'):
"""Show a keyboard mode indicator in one of the corners.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the mark; else remove it if prese... | python | {
"resource": ""
} |
q241298 | show_color_bar | train | def show_color_bar(viewer, tf, side='bottom'):
"""Show a color bar in the window.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the color bar; else remove it if present.
side : str
... | python | {
"resource": ""
} |
q241299 | show_focus_indicator | train | def show_focus_indicator(viewer, tf, color='white'):
"""Show a focus indicator in the window.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the color bar; else remove it if present.
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.