text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_popset(self,filename='popset.h5',**kwargs):
"""Saves the PopulationSet Calls :func:`PopulationSet.save_hdf`. """ |
self.popset.save_hdf(os.path.join(self.folder,filename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_signal(self,filename=None):
""" Saves TransitSignal. Calls :func:`TransitSignal.save`; default filename is ``trsig.pkl`` in ``self.folder``. """ |
if filename is None:
filename = os.path.join(self.folder,'trsig.pkl')
self.trsig.save(filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modelshift_weaksec(koi):
""" Max secondary depth based on model-shift secondary test from Jeff Coughlin secondary metric: mod_depth_sec_dv * (1 + 3*mod_fred_... |
num = KOIDATA.ix[ku.koiname(koi), 'koi_tce_plnt_num']
if np.isnan(num):
num = 1
kid = KOIDATA.ix[ku.koiname(koi), 'kepid']
tce = '{:09.0f}-{:02.0f}'.format(kid,num)
#return largest depth between DV detrending and alternate detrending
try:
r = ROBOVETDATA.ix[tce]
except KeyE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_property(kepid, prop):
"""Returns true if provenance of property is SPE or AST """ |
try:
prov = kicu.DATA.ix[kepid, '{}_prov'.format(prop)]
return any([prov.startswith(s) for s in ['SPE', 'AST']])
except KeyError:
raise MissingStellarError('{} not in stellar table?'.format(kepid)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def star_config(koi, bands=['g','r','i','z','J','H','K'], unc=dict(g=0.05, r=0.05, i=0.05, z=0.05, J=0.02, H=0.02, K=0.02), **kwargs):
"""returns star config obj... |
folder = os.path.join(KOI_FPPDIR, ku.koiname(koi))
if not os.path.exists(folder):
os.makedirs(folder)
config = ConfigObj(os.path.join(folder,'star.ini'))
koi = ku.koiname(koi)
maxAV = koi_maxAV(koi)
config['maxAV'] = maxAV
mags = ku.KICmags(koi)
for band in bands:
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fpp_config(koi, **kwargs):
"""returns config object for given KOI """ |
folder = os.path.join(KOI_FPPDIR, ku.koiname(koi))
if not os.path.exists(folder):
os.makedirs(folder)
config = ConfigObj(os.path.join(folder,'fpp.ini'))
koi = ku.koiname(koi)
rowefit = jrowe_fit(koi)
config['name'] = koi
ra,dec = ku.radec(koi)
config['ra'] = ra
config['de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_default_constraints(self):
"""Applies default secthresh & exclusion radius constraints """ |
try:
self.apply_secthresh(pipeline_weaksec(self.koi))
except NoWeakSecondaryError:
logging.warning('No secondary eclipse threshold set for {}'.format(self.koi))
self.set_maxrad(default_r_exclusion(self.koi)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_old_sha(diff_part):
""" Returns the SHA for the original file that was changed in a diff part. """ |
r = re.compile(r'index ([a-fA-F\d]*)')
return r.search(diff_part).groups()[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_old_filename(diff_part):
""" Returns the filename for the original file that was changed in a diff part. """ |
regexps = (
# e.g. "+++ a/foo/bar"
r'^--- a/(.*)',
# e.g. "+++ /dev/null"
r'^\-\-\- (.*)',
)
for regexp in regexps:
r = re.compile(regexp, re.MULTILINE)
match = r.search(diff_part)
if match is not None:
return match.groups()[0]
raise M... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_new_filename(diff_part):
""" Returns the filename for the updated file in a diff part. """ |
regexps = (
# e.g. "+++ b/foo/bar"
r'^\+\+\+ b/(.*)',
# e.g. "+++ /dev/null"
r'^\+\+\+ (.*)',
)
for regexp in regexps:
r = re.compile(regexp, re.MULTILINE)
match = r.search(diff_part)
if match is not None:
return match.groups()[0]
rais... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_contents(diff_part):
""" Returns a tuple of old content and new content. """ |
old_sha = get_old_sha(diff_part)
old_filename = get_old_filename(diff_part)
old_contents = get_old_contents(old_sha, old_filename)
new_filename = get_new_filename(diff_part)
new_contents = get_new_contents(new_filename)
return old_contents, new_contents |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadcache(cachefile):
""" Returns a dictionary resulting from reading a likelihood cachefile """ |
cache = {}
if os.path.exists(cachefile):
with open(cachefile) as f:
for line in f:
line = line.split()
if len(line) == 2:
try:
cache[int(line[0])] = float(line[1])
except:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_trapezoids(self, MAfn=None, msg=None, use_pbar=True, **kwargs):
""" Fit trapezoid shape to each eclipse in population For each instance in the population... |
logging.info('Fitting trapezoid models for {}...'.format(self.model))
if msg is None:
msg = '{}: '.format(self.model)
n = len(self.stars)
deps, durs, slopes = (np.zeros(n), np.zeros(n), np.zeros(n))
secs = np.zeros(n, dtype=bool)
dsec = np.zeros(n)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eclipseprob(self):
""" Array of eclipse probabilities. """ |
#TODO: incorporate eccentricity/omega for exact calculation?
s = self.stars
return ((s['radius_1'] + s['radius_2'])*RSUN /
(semimajor(s['P'],s['mass_1'] + s['mass_2'])*AU)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modelshort(self):
""" Short version of model name Dictionary defined in ``populations.py``:: SHORT_MODELNAMES = {'Planets':'pl', 'EBs':'eb', 'HEBs':'heb', 'B... |
try:
name = SHORT_MODELNAMES[self.model]
#add index if specific model is indexed
if hasattr(self,'index'):
name += '-{}'.format(self.index)
return name
except KeyError:
raise KeyError('No short name for model: %s' % self.mod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def constrain_secdepth(self, thresh):
""" Constrain the observed secondary depth to be less than a given value :param thresh: Maximum allowed fractional depth fo... |
self.apply_constraint(UpperLimit(self.secondary_depth, thresh, name='secondary depth')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prior(self):
""" Model prior for particular model. Product of eclipse probability (``self.prob``), the fraction of scenario that is allowed by the various co... |
prior = self.prob * self.selectfrac
for f in self.priorfactors:
prior *= self.priorfactors[f]
return prior |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_priorfactor(self,**kwargs):
"""Adds given values to priorfactors If given keyword exists already, error will be raised to use :func:`EclipsePopulation.ch... |
for kw in kwargs:
if kw in self.priorfactors:
logging.error('%s already in prior factors for %s. use change_prior function instead.' % (kw,self.model))
continue
else:
self.priorfactors[kw] = kwargs[kw]
logging.info('%s add... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_prior(self, **kwargs):
""" Changes existing priorfactors. If given keyword isn't already in priorfactors, then will be ignored. """ |
for kw in kwargs:
if kw in self.priorfactors:
self.priorfactors[kw] = kwargs[kw]
logging.info('{0} changed to {1} for {2} model'.format(kw,kwargs[kw],
self.model)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _density(self, logd, dur, slope):
""" Evaluate KDE at given points. Prepares data according to whether sklearn or scipy KDE in use. :param log, dur, slope: T... |
if self.sklearn_kde:
#TODO: fix preprocessing
pts = np.array([(logd - self.mean_logdepth)/self.std_logdepth,
(dur - self.mean_dur)/self.std_dur,
(slope - self.mean_slope)/self.std_slope])
return self.kde.score_samples(p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lhood(self, trsig, recalc=False, cachefile=None):
"""Returns likelihood of transit signal Returns sum of ``trsig`` MCMC samples evaluated at ``self.kde``. :p... |
if not hasattr(self,'kde'):
self._make_kde()
if cachefile is None:
cachefile = self.lhoodcachefile
if cachefile is None:
cachefile = 'lhoodcache.dat'
lhoodcache = _loadcache(cachefile)
key = hashcombine(self, trsig)
if key in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_hdf(cls, filename, path=''):
#perhaps this doesn't need to be written? """ Loads EclipsePopulation from HDF file Also runs :func:`EclipsePopulation._mak... |
new = StarPopulation.load_hdf(filename, path=path)
#setup lazy loading of starmodel if present
try:
with pd.HDFStore(filename) as store:
if '{}/starmodel'.format(path) in store:
new._starmodel = None
new._starmodel_file = fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def constraints(self):
""" Unique list of constraints among all populations in set. """ |
cs = []
for pop in self.poplist:
cs += [c for c in pop.constraints]
return list(set(cs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_hdf(self, filename, path='', overwrite=False):
""" Saves PopulationSet to HDF file. """ |
if os.path.exists(filename) and overwrite:
os.remove(filename)
for pop in self.poplist:
name = pop.modelshort
pop.save_hdf(filename, path='{}/{}'.format(path,name), append=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_hdf(cls, filename, path=''):
""" Loads PopulationSet from file """ |
with pd.HDFStore(filename) as store:
models = []
types = []
for k in store.keys():
m = re.search('/(\S+)/stars', k)
if m:
models.append(m.group(1))
types.append(store.get_storer(m.group(0)).attrs.poptype... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_population(self,pop):
"""Adds population to PopulationSet """ |
if pop.model in self.modelnames:
raise ValueError('%s model already in PopulationSet.' % pop.model)
self.modelnames.append(pop.model)
self.shortmodelnames.append(pop.modelshort)
self.poplist.append(pop) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_population(self,pop):
"""Removes population from PopulationSet """ |
iremove=None
for i in range(len(self.poplist)):
if self.modelnames[i]==self.poplist[i].model:
iremove=i
if iremove is not None:
self.modelnames.pop(i)
self.shortmodelnames.pop(i)
self.poplist.pop(i) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def colordict(self):
""" Dictionary holding colors that correspond to constraints. """ |
d = {}
i=0
n = len(self.constraints)
for c in self.constraints:
#self.colordict[c] = colors[i % 6]
d[c] = cm.jet(1.*i/n)
i+=1
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def priorfactors(self):
"""Combinartion of priorfactors from all populations """ |
priorfactors = {}
for pop in self.poplist:
for f in pop.priorfactors:
if f in priorfactors:
if pop.priorfactors[f] != priorfactors[f]:
raise ValueError('prior factor %s is inconsistent!' % f)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_multicolor_transit(self,band,depth):
""" Applies constraint corresponding to measuring transit in different band This is not implemented yet. """ |
if '{} band transit'.format(band) not in self.constraints:
self.constraints.append('{} band transit'.format(band))
for pop in self.poplist:
pop.apply_multicolor_transit(band,depth) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_maxrad(self,newrad):
""" Sets max allowed radius in populations. Doesn't operate via the :class:`stars.Constraint` protocol; rather just rescales the sky... |
if not isinstance(newrad, Quantity):
newrad = newrad * u.arcsec
#if 'Rsky' not in self.constraints:
# self.constraints.append('Rsky')
for pop in self.poplist:
if not pop.is_specific:
try:
pop.maxrad = newrad
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_dmaglim(self,dmaglim=None):
""" Applies a constraint that sets the maximum brightness for non-target star :func:`stars.StarPopulation.set_dmaglim` not ... |
raise NotImplementedError
if 'bright blend limit' not in self.constraints:
self.constraints.append('bright blend limit')
for pop in self.poplist:
if not hasattr(pop,'dmaglim') or pop.is_specific:
continue
if dmaglim is None:
dm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_trend_constraint(self, limit, dt, **kwargs):
""" Applies constraint corresponding to RV trend non-detection to each population See :func:`stars.StarPop... |
if 'RV monitoring' not in self.constraints:
self.constraints.append('RV monitoring')
for pop in self.poplist:
if not hasattr(pop,'dRV'):
continue
pop.apply_trend_constraint(limit, dt, **kwargs)
self.trend_limit = limit
self.trend_dt = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_secthresh(self, secthresh, **kwargs):
"""Applies secondary depth constraint to each population See :func:`EclipsePopulation.apply_secthresh`; all argum... |
if 'secondary depth' not in self.constraints:
self.constraints.append('secondary depth')
for pop in self.poplist:
if not isinstance(pop, EclipsePopulation_Px2):
pop.apply_secthresh(secthresh, **kwargs)
self.secthresh = secthresh |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def constrain_property(self,prop,**kwargs):
""" Constrains property for each population See :func:`vespa.stars.StarPopulation.constrain_property`; all arguments ... |
if prop not in self.constraints:
self.constraints.append(prop)
for pop in self.poplist:
try:
pop.constrain_property(prop,**kwargs)
except AttributeError:
logging.info('%s model does not have property stars.%s (constraint not applied)' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace_constraint(self,name,**kwargs):
""" Replaces removed constraint in each population. See :func:`vespa.stars.StarPopulation.replace_constraint` """ |
for pop in self.poplist:
pop.replace_constraint(name,**kwargs)
if name not in self.constraints:
self.constraints.append(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_constraint(self,*names):
""" Removes constraint from each population See :func:`vespa.stars.StarPopulation.remove_constraint """ |
for name in names:
for pop in self.poplist:
if name in pop.constraints:
pop.remove_constraint(name)
else:
logging.info('%s model does not have %s constraint' % (pop.model,name))
if name in self.constraints:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_cc(self, cc, **kwargs):
""" Applies contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_cc`; all arguments passed ... |
if type(cc)==type(''):
pass
if cc.name not in self.constraints:
self.constraints.append(cc.name)
for pop in self.poplist:
if not pop.is_specific:
try:
pop.apply_cc(cc, **kwargs)
except AttributeError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_vcc(self,vcc):
""" Applies velocity contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_vcc`; all arguments passed... |
if 'secondary spectrum' not in self.constraints:
self.constraints.append('secondary spectrum')
for pop in self.poplist:
if not pop.is_specific:
try:
pop.apply_vcc(vcc)
except:
logging.info('VCC constraint no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_trilegal(filename,ra,dec,folder='.', galactic=False, filterset='kepler_2mass',area=1,maglim=27,binaries=False, trilegal_version='1.6',sigma_AV=0.1,convert... |
if galactic:
l, b = ra, dec
else:
try:
c = SkyCoord(ra,dec)
except UnitsError:
c = SkyCoord(ra,dec,unit='deg')
l,b = (c.galactic.l.value,c.galactic.b.value)
if os.path.isabs(filename):
folder = ''
if not re.search('\.dat$',filename):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_wrapper(self):
""" Wrapper to set logging parameters for output """ |
log = logging.getLogger('client.py')
# Set the log format and log level
try:
debug = self.params["debug"]
log.setLevel(logging.DEBUG)
except KeyError:
log.setLevel(logging.INFO)
# Set the log format.
stream = logging.StreamHandler()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_setid(encoded):
"""Decode setid as uint128""" |
try:
lo, hi = struct.unpack('<QQ', b32decode(encoded.upper() + '======'))
except struct.error:
raise ValueError('Cannot decode {!r}'.format(encoded))
return (hi << 64) + lo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_setid(uint128):
"""Encode uint128 setid as stripped b32encoded string""" |
hi, lo = divmod(uint128, 2**64)
return b32encode(struct.pack('<QQ', lo, hi))[:-6].lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reduce_opacity(self, watermark, opacity):
""" Returns an image with reduced opacity. Converts image to RGBA if needs. Simple watermark.opacity(65535 - int(6... |
if watermark.type() != ImageType.TrueColorMatteType:
watermark.type(ImageType.TrueColorMatteType)
depth = 255 - int(255 * opacity)
watermark.quantumOperator(ChannelType.OpacityChannel, QuOp.MaxQuantumOp, depth) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_relations(self):
"""Cleanup listing relations""" |
collections = self.collections
for relation in [x for col in collections.values()
for x in col.model.relations.values()]:
db.session.query(relation)\
.filter(~relation.listing.any())\
.delete(synchronize_session=False)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_cleanup(ctx, discarded, unused_tags):
"""Cleanup unused tags and discarded datasets.""" |
if not any([discarded, unused_tags]):
click.echo(ctx.get_help())
ctx.exit(1)
site = create_app().site
if discarded:
site.cleanup_discarded()
if unused_tags:
site.cleanup_tags()
site.cleanup_relations() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_develop_server(port, public):
"""Run development webserver. ATTENTION: By default it is only served on localhost. To run it within a container and ac... |
from flask_cors import CORS
app = create_app(push=False)
app.site.load_for_web()
CORS(app)
class IPDBMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
from ipdb import launch_ipdb_on_exception
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_discard(datasets, all_nodes, nodes, tags, comments, confirm):
"""Mark DATASETS to be discarded or discard associated data. Without any options the sp... |
mark_discarded = not any([all_nodes, nodes, tags, comments])
site = create_app().site
setids = parse_setids(datasets)
if tags or comments:
if confirm:
msg = ' and '.join(filter(None, ['tags' if tags else None,
'comments' if comments els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_undiscard(datasets):
"""Undiscard DATASETS previously discarded.""" |
create_app()
setids = parse_setids(datasets, discarded=True)
dataset = Dataset.__table__
stmt = dataset.update()\
.where(dataset.c.setid.in_(setids))\
.values(discarded=False)
db.session.execute(stmt)
db.session.commit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_restore(file):
"""Restore previously dumped database""" |
data = json.load(file)
site = create_app().site
site.restore_database(**data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_query(ctx, list_tags, collections, discarded, outdated, path, tags, null):
"""Query datasets. Use --collection=* to list all datasets across all coll... |
if not any([collections, discarded, list_tags, outdated, path, tags]):
click.echo(ctx.get_help())
ctx.exit(1)
sep = '\x00' if null else '\n'
site = create_app().site
if '*' in collections:
collections = None
else:
for col in collections:
if col not in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_tag(ctx, add, remove, datasets):
"""Add or remove tags to datasets""" |
if not any([add, remove]) or not datasets:
click.echo(ctx.get_help())
ctx.exit(1)
app = create_app()
setids = parse_setids(datasets)
app.site.tag(setids, add, remove) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_comment_add(user, message, datasets):
"""Add comment as user for one or more datasets""" |
app = create_app()
try:
db.session.query(User).filter(User.name==user).one()
except NoResultFound:
click.echo("ERROR: No such user '{}'".format(user), err=True)
sys.exit(1)
ids = parse_setids(datasets, dbids=True)
app.site.comment(user, message, ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_comment_list(datasets):
"""Lists comments for datasets. Output: setid comment_id date time author message """ |
app = create_app()
ids = parse_setids(datasets, dbids=True)
comments = db.session.query(Comment)\
.options(db.joinedload(Comment.dataset))\
.filter(Comment.dataset_id.in_(ids))
for comment in sorted(comments, key=lambda x: (x.dataset._setid, x.id)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_comment_rm(ids):
"""Remove comments. Remove comments by id as given in second column of: marv comment list """ |
app = create_app()
db.session.query(Comment)\
.filter(Comment.id.in_(ids))\
.delete(synchronize_session=False)
db.session.commit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_user_list():
"""List existing users""" |
app = create_app()
for name in db.session.query(User.name).order_by(User.name):
click.echo(name[0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marvcli_user_rm(ctx, username):
"""Remove a user""" |
app = create_app()
try:
app.um.user_rm(username)
except ValueError as e:
ctx.fail(e.args[0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watermark(self, image, options):
""" Wrapper for ``_watermark`` Takes care of all the options handling. """ |
watermark_img = options.get("watermark", settings.THUMBNAIL_WATERMARK)
if not watermark_img:
raise AttributeError("No THUMBNAIL_WATERMARK defined or set on tag.")
watermark_path = find(watermark_img)
if not watermark_path:
raise RuntimeError("Could not find the c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_funcs(dataset, setdir, store):
"""Functions available for listing columns and filters.""" |
return {
'cat': lambda *lists: [x for lst in lists for x in lst],
'comments': lambda: None,
'detail_route': detail_route,
'format': lambda fmt, *args: fmt.format(*args),
'get': partial(getnode, dataset, setdir, store),
'join': lambda sep, *args: sep.join([x for x in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_summary_funcs(rows, ids):
"""Functions available for listing summary fields.""" |
return {
'len': len,
'list': lambda *x: filter(None, list(x)),
'max': max,
'min': min,
'rows': partial(summary_rows, rows, ids),
'sum': sum,
'trace': print_trace
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cached_property(func):
"""Create read-only property that caches its function's value""" |
@functools.wraps(func)
def cached_func(self):
cacheattr = '_{}'.format(func.func_name)
try:
return getattr(self, cacheattr)
except AttributeError:
value = func(self)
setattr(self, cacheattr, value)
return value
return property(cached_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_stream(name, **header):
"""Create a stream for publishing messages. All keyword arguments will be used to form the header. """ |
assert isinstance(name, basestring), name
return CreateStream(parent=None, name=name, group=False, header=header) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull(handle, enumerate=False):
"""Pulls next message for handle. Args: handle: A :class:`.stream.Handle` or GroupHandle. enumerate (bool):
boolean to indica... |
assert isinstance(handle, Handle), handle
return Pull(handle, enumerate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_geometry(geometry, ratio=None):
""" Enhanced parse_geometry parser with percentage support. """ |
if "%" not in geometry:
# fall back to old parser
return xy_geometry_parser(geometry, ratio)
# parse with float so geometry strings like "42.11%" are possible
return float(geometry.strip("%")) / 100.0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image(cam):
"""Extract first image of input stream to jpg file. Args: cam: Input stream of raw rosbag messages. Returns: File instance for first image of inp... |
# Set output stream title and pull first message
yield marv.set_header(title=cam.topic)
msg = yield marv.pull(cam)
if msg is None:
return
# Deserialize raw ros message
pytype = get_message_type(cam)
rosmsg = pytype()
rosmsg.deserialize(msg.data)
# Write image to jpeg and p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image_section(image, title):
"""Create detail section with one image. Args: title (str):
Title to be displayed for detail section. image: marv image file. R... |
# pull first image
img = yield marv.pull(image)
if img is None:
return
# create image widget and section containing it
widget = {'title': image.title, 'image': {'src': img.relpath}}
section = {'title': title, 'widgets': [widget]}
yield marv.push(section) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def images(cam):
"""Extract images from input stream to jpg files. Args: cam: Input stream of raw rosbag messages. Returns: File instances for images of input st... |
# Set output stream title and pull first message
yield marv.set_header(title=cam.topic)
# Fetch and process first 20 image messages
name_template = '%s-{}.jpg' % cam.topic.replace('/', ':')[1:]
while True:
idx, msg = yield marv.pull(cam, enumerate=True)
if msg is None or idx >= 20:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gallery_section(images, title):
"""Create detail section with gallery. Args: title (str):
Title to be displayed for detail section. images: stream of marv i... |
# pull all images
imgs = []
while True:
img = yield marv.pull(images)
if img is None:
break
imgs.append({'src': img.relpath})
if not imgs:
return
# create gallery widget and section containing it
widget = {'title': images.title, 'gallery': {'images':... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filesizes(images):
"""Stat filesize of files. Args: images: stream of marv image files Returns: Stream of filesizes """ |
# Pull each image and push its filesize
while True:
img = yield marv.pull(images)
if img is None:
break
yield marv.push(img.size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(name, validator=None):
""" Set a name on a validator callable. Useful for user-friendly reporting when using lambdas to populate the [`Invalid.expected`... |
# Decorator mode
if validator is None:
def decorator(f):
f.name = name
return f
return decorator
# Direct mode
validator.name = name
return validator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stringmethod(func):
""" Validator factory which call a single method on the string. """ |
method_name = func()
@wraps(func)
def factory():
def validator(v):
if not isinstance(v, six.string_types):
raise Invalid(_(u'Not a string'), get_type_name(six.text_type), get_type_name(type(v)))
return getattr(v, method_name)()
return validator
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_z(cls, offset):
""" Parse %z offset into `timedelta` """ |
assert len(offset) == 5, 'Invalid offset string format, must be "+HHMM"'
return timedelta(hours=int(offset[:3]), minutes=int(offset[0] + offset[3:])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_z(cls, offset):
""" Format `timedelta` into %z """ |
sec = offset.total_seconds()
return '{s}{h:02d}{m:02d}'.format(s='-' if sec<0 else '+', h=abs(int(sec/3600)), m=int((sec%3600)/60)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strptime(cls, value, format):
""" Parse a datetime string using the provided format. This also emulates `%z` support on Python 2. :param value: Datetime stri... |
# Simplest case: direct parsing
if cls.python_supports_z or '%z' not in format:
return datetime.strptime(value, format)
else:
# %z emulation case
assert format[-2:] == '%z', 'For performance, %z is only supported at the end of the string'
# Parse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_random_type(valid):
""" Generate a random type and samples for it. :param valid: Generate valid samples? :type valid: bool :return: type, sample-gen... |
type = choice(['int', 'str'])
r = lambda: randrange(-1000000000, 1000000000)
if type == 'int':
return int, (r() if valid else str(r()) for i in itertools.count())
elif type == 'str':
return str, (str(r()) if valid else r() for i in itertools.count())
else:
raise Assertion... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_random_schema(valid):
""" Generate a random plain schema, and a sample generation function. :param valid: Generate valid samples? :type valid: bool ... |
schema_type = choice(['literal', 'type'])
if schema_type == 'literal':
type, gen = generate_random_type(valid)
value = next(gen)
return value, (value if valid else None for i in itertools.count())
elif schema_type == 'type':
return generate_random_type(valid)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_dict_schema(size, valid):
""" Generate a schema dict of size `size` using library `lib`. In addition, it returns samples generator :param size: Sche... |
schema = {}
generator_items = []
# Generate schema
for i in range(0, size):
while True:
key_schema, key_generator = generate_random_schema(valid)
if key_schema not in schema:
break
value_schema, value_generator = generate_random_schema(valid... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calc_q_statistic(x, h, nt):
"""Calculate Portmanteau statistics up to a lag of h. """ |
t, m, n = x.shape
# covariance matrix of x
c0 = acm(x, 0)
# LU factorization of covariance matrix
c0f = sp.linalg.lu_factor(c0, overwrite_a=False, check_finite=True)
q = np.zeros((3, h + 1))
for l in range(1, h + 1):
cl = acm(x, l)
# calculate tr(cl' * c0^-1 * cl * c0^-1... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calc_q_h0(n, x, h, nt, n_jobs=1, verbose=0, random_state=None):
"""Calculate q under the null hypothesis of whiteness. """ |
rng = check_random_state(random_state)
par, func = parallel_loop(_calc_q_statistic, n_jobs, verbose)
q = par(func(rng.permutation(x.T).T, h, nt) for _ in range(n))
return np.array(q) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Create a copy of the VAR model.""" |
other = self.__class__(self.p)
other.coef = self.coef.copy()
other.residuals = self.residuals.copy()
other.rescov = self.rescov.copy()
return other |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_yw(self, acms):
"""Determine VAR model from autocorrelation matrices by solving the Yule-Walker equations. Parameters acms : array, shape (n_lags, n_cha... |
if len(acms) != self.p + 1:
raise ValueError("Number of autocorrelation matrices ({}) does not"
" match model order ({}) + 1.".format(len(acms),
self.p))
n_channels = acms[0].shape[0]
a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(self, data):
"""Predict samples on actual data. The result of this function is used for calculating the residuals. Parameters data : array, shape (tr... |
data = atleast_3d(data)
t, m, l = data.shape
p = int(np.shape(self.coef)[1] / m)
y = np.zeros(data.shape)
if t > l - p: # which takes less loop iterations
for k in range(1, p + 1):
bp = self.coef[:, (k - 1)::p]
for n in range(p, l):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_stable(self):
"""Test if VAR model is stable. This function tests stability of the VAR model as described in [1]_. Returns ------- out : bool True if the ... |
m, mp = self.coef.shape
p = mp // m
assert(mp == m * p) # TODO: replace with raise?
top_block = []
for i in range(p):
top_block.append(self.coef[:, i::p])
top_block = np.hstack(top_block)
im = np.eye(m)
eye_block = im
for i in range... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(dataset="mi", datadir=datadir):
"""Fetch example dataset. If the requested dataset is not found in the location specified by `datadir`, the function at... |
if dataset not in datasets:
raise ValueError("Example data '{}' not available.".format(dataset))
else:
files = datasets[dataset]["files"]
url = datasets[dataset]["url"]
md5 = datasets[dataset]["md5"]
if not isdir(datadir):
makedirs(datadir)
data = []
for n,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def supports_undefined(self):
""" Test whether this schema supports Undefined. A Schema that supports `Undefined`, when given `Undefined`, should return some val... |
# Test
try:
yes = self(const.UNDEFINED) is not const.UNDEFINED
except (Invalid, SchemaError):
yes = False
# Remember (lame @cached_property)
self.__dict__['supports_undefined'] = yes
return yes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_schema_type(cls, schema):
""" Get schema type for the argument :param schema: Schema to analyze :return: COMPILED_TYPE constant :rtype: str|None """ |
schema_type = type(schema)
# Marker
if issubclass(schema_type, markers.Marker):
return const.COMPILED_TYPE.MARKER
# Marker Type
elif issubclass(schema_type, six.class_types) and issubclass(schema, markers.Marker):
return const.COMPILED_TYPE.MARKER
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def priority(self):
""" Get priority for this Schema. Used to sort mapping keys :rtype: int """ |
# Markers have priority set on the class
if self.compiled_type == const.COMPILED_TYPE.MARKER:
return self.compiled.priority
# Other types have static priority
return const.compiled_type_priorities[self.compiled_type] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_schemas(cls, schemas_list):
""" Sort the provided list of schemas according to their priority. This also supports markers, and markers of a single type ... |
return sorted(schemas_list,
key=lambda x: (
# Top-level priority:
# priority of the schema itself
x.priority,
# Second-level priority (for markers of the common type)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sub_compile(self, schema, path=None, matcher=False):
""" Compile a sub-schema :param schema: Validation schema :type schema: * :param path: Path to this sche... |
return type(self)(
schema,
self.path + (path or []),
None,
None,
matcher
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Invalid(self, message, expected):
""" Helper for Invalid errors. Typical use: err_type = self.Invalid(_(u'Message'), self.name) raise err_type(<provided-valu... |
def InvalidPartial(provided, path=None, **info):
""" Create an Invalid exception
:type provided: unicode
:type path: list|None
:rtype: Invalid
"""
return Invalid(
message,
expected, #six.text_type(expected)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_schema_compiler(self, schema):
""" Get compiler method for the provided schema :param schema: Schema to analyze :return: Callable compiled :rtype: callab... |
# Schema type
schema_type = self.get_schema_type(schema)
if schema_type is None:
return None
# Compiler
compilers = {
const.COMPILED_TYPE.LITERAL: self._compile_literal,
const.COMPILED_TYPE.TYPE: self._compile_type,
const.COMPILED... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_schema(self, schema):
""" Compile the current schema into a callable validator :return: Callable validator :rtype: callable :raises SchemaError: Sche... |
compiler = self.get_schema_compiler(schema)
if compiler is None:
raise SchemaError(_(u'Unsupported schema data type {!r}').format(type(schema).__name__))
return compiler(schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_schema(self, schema):
""" Compile another schema """ |
assert self.matcher == schema.matcher
self.name = schema.name
self.compiled_type = schema.compiled_type
return schema.compiled |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadmat(filename):
"""This function should be called instead of direct spio.loadmat as it cures the problem of not properly recovering python dictionaries fr... |
data = sploadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_keys(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_keys(dictionary):
""" checks if entries in dictionary are mat-objects. If yes todict is called to change them to nested dictionaries """ |
for key in dictionary:
if isinstance(dictionary[key], matlab.mio5_params.mat_struct):
dictionary[key] = _todict(dictionary[key])
return dictionary |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _todict(matobj):
""" a recursive function which constructs from matobjects nested dictionaries """ |
dictionary = {}
#noinspection PyProtectedMember
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, matlab.mio5_params.mat_struct):
dictionary[strg] = _todict(elem)
else:
dictionary[strg] = elem
return dictionary |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plainica(x, reducedim=0.99, backend=None, random_state=None):
""" Source decomposition with ICA. Apply ICA to the data x, with optional PCA dimensionality re... |
x = atleast_3d(x)
t, m, l = np.shape(x)
if backend is None:
backend = scotbackend
# pre-transform the data with PCA
if reducedim == 'no pca':
c = np.eye(m)
d = np.eye(m)
xpca = x
else:
c, d, xpca = backend['pca'](x, reducedim)
# run on residuals I... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _msge_with_gradient_underdetermined(data, delta, xvschema, skipstep, p):
"""Calculate mean squared generalization error and its gradient for underdetermined ... |
t, m, l = data.shape
d = None
j, k = 0, 0
nt = np.ceil(t / skipstep)
for trainset, testset in xvschema(t, skipstep):
a, b = _construct_var_eqns(atleast_3d(data[trainset, :, :]), p)
c, d = _construct_var_eqns(atleast_3d(data[testset, :, :]), p)
e = sp.linalg.inv(np.eye(a.sh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _msge_with_gradient_overdetermined(data, delta, xvschema, skipstep, p):
"""Calculate mean squared generalization error and its gradient for overdetermined eq... |
t, m, l = data.shape
d = None
l, k = 0, 0
nt = np.ceil(t / skipstep)
for trainset, testset in xvschema(t, skipstep):
a, b = _construct_var_eqns(atleast_3d(data[trainset, :, :]), p)
c, d = _construct_var_eqns(atleast_3d(data[testset, :, :]), p)
e = sp.linalg.inv(np.eye(a.sh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_msge_with_gradient(data, delta, xvschema, skipstep, p):
"""Calculate mean squared generalization error and its gradient, automatically selecting the bes... |
t, m, l = data.shape
n = (l - p) * t
underdetermined = n < m * p
if underdetermined:
return _msge_with_gradient_underdetermined(data, delta, xvschema,
skipstep, p)
else:
return _msge_with_gradient_overdetermined(data, delta, xvsch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.