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 get_last_live_chat(self): """ Check if there is a live chat that ended in the last 3 days, and return it. We will display a link to it on the articles page. ...
now = datetime.now() lcqs = self.get_query_set() lcqs = lcqs.filter( chat_ends_at__lte=now, ).order_by('-chat_ends_at') for itm in lcqs: if itm.chat_ends_at + timedelta(days=3) > now: return itm return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment_set(self): """ Get the comments that have been submitted for the chat """
ct = ContentType.objects.get_for_model(self.__class__) qs = Comment.objects.filter( content_type=ct, object_pk=self.pk) qs = qs.exclude(is_removed=True) qs = qs.order_by('-submit_date') return qs
<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_dispatches(filter_kwargs): """Simplified version. Not distributed friendly."""
dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).order_by('-message__time_created') return list(dispatches)
<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_dispatches_for_update(filter_kwargs): """Distributed friendly version using ``select for update``."""
dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).select_for_update( **GET_DISPATCHES_ARGS[1] ).order_by('-message__time_created') try: dispatches = list(dispatches) except NotSupportedError: return None except DatabaseErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def author_list(self): ''' The list of authors als text, for admin submission list overview.''' author_list = [self.submitter] + \ [author for author in self.authors.all().exclude(pk=self.submitter.pk)] return ",\n".join([author.get_full_name() for author in author_list])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def grading_status_text(self): ''' A rendering of the grading that is an answer on the question "Is grading finished?". Used in duplicate view and submission list on the teacher backend. ''' if self.assignment.is_graded(): if self.is_grading_finished(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def grading_value_text(self): ''' A rendering of the grading that is an answer to the question "What is the grade?". ''' if self.assignment.is_graded(): if self.is_grading_finished(): return str(self.grading) else: return st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def grading_means_passed(self): ''' Information if the given grading means passed. Non-graded assignments are always passed. ''' if self.assignment.is_graded(): if self.grading and self.grading.means_passed: return True 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 can_modify(self, user=None): """Determines whether the submission can be modified. Returns a boolean value. The 'user' parameter is optional and additionally...
# The user must be authorized to commit these actions. if user and not self.user_can_modify(user): #self.log('DEBUG', "Submission cannot be modified, user is not an authorized user ({!r} not in {!r})", user, self.authorized_users) return False # Modification of submiss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_reupload(self, user=None): """Determines whether a submission can be re-uploaded. Returns a boolean value. Requires: can_modify. Re-uploads are allowed o...
# Re-uploads are allowed only when test executions have failed. if self.state not in (self.TEST_VALIDITY_FAILED, self.TEST_FULL_FAILED): return False # It must be allowed to modify the submission. if not self.can_modify(user=user): return False return ...
<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_initial_state(self): ''' Return first state for this submission after upload, which depends on the kind of assignment. ''' if not self.assignment.attachment_is_tested(): return Submission.SUBMITTED else: if self.assignment.attachmen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def info_file(self, delete=True): ''' Prepares an open temporary file with information about the submission. Closing it will delete it, which must be considered by the caller. This file is not readable, since the tempfile library wants either readable or writable files. ...
<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_file_upload(self, targetdir): ''' Copies the currently valid file upload into the given directory. If possible, the content is un-archived in the target directory. ''' assert(self.file_upload) # unpack student data to temporary directory # os.chro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_command(self, method_name, data=None): """Sends a command to API. :param str method_name: :param dict data: :return: """
try: response = self.lib.post(self._tpl_url % {'token': self.auth_token, 'method': method_name}, data=data) json = response.json() if not json['ok']: raise TelegramMessengerException(json['description']) return json['result'] except sel...
<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_queryset(self, request): ''' Restrict the listed submission files for the current user.''' qs = super(SubmissionFileAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(submissions__assignment__course__tutors_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_builtin_message_types(): """Registers the built-in message types."""
from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def view_links(obj): ''' Link to performance data and duplicate overview.''' result=format_html('') result+=format_html('<a href="%s" style="white-space: nowrap">Show duplicates</a><br/>'%reverse('duplicates', args=(obj.pk,))) result+=format_html('<a href="%s" style="white-space: nowrap">Show submission...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clean(self): ''' Check if such an assignment configuration makes sense, and reject it otherwise. This mainly relates to interdependencies between the different fields, since single field constraints are already clatified by the Django model configuration. ''' ...
<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_queryset(self, request): ''' Restrict the listed assignments for the current user.''' qs = super(AssignmentAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(course__active=True).filter(Q(course__tutors__pk=request.user.pk) | Q(course__owner=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 get_user_details(self, response): """ Complete with additional information from environment, as available. """
result = { 'username': response[self.ENV_USERNAME], 'email': response.get(self.ENV_EMAIL, None), 'first_name': response.get(self.ENV_FIRST_NAME, None), 'last_name': response.get(self.ENV_LAST_NAME, None) } if result['first_name'] and result['last_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def file_link(self, instance): ''' Renders the link to the student upload file. ''' sfile = instance.file_upload if not sfile: return mark_safe('No file submitted by student.') else: return mark_safe('<a href="%s">%s</a><br/>(<a href="%s" targe...
<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_queryset(self, request): ''' Restrict the listed submission for the current user.''' qs = super(SubmissionAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(assignment__course__tutors__pk=request.user.pk) | ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def formfield_for_dbfield(self, db_field, **kwargs): ''' Offer grading choices from the assignment definition as potential form field values for 'grading'. When no object is given in the form, the this is a new manual submission ''' if db_field.name == "grading": ...
<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_model(self, request, obj, form, change): ''' Our custom addition to the view adds an easy radio button choice for the new state. This is meant to be for tutors. We need to peel this choice from the form data and set the state accordingly. The radio buttons have no 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 setGradingNotFinishedStateAction(self, request, queryset): ''' Set all marked submissions to "grading not finished". This is intended to support grading corrections on a larger scale. ''' for subm in queryset: subm.state = Submission.GRADING_IN_PROGRESS ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setGradingFinishedStateAction(self, request, queryset): ''' Set all marked submissions to "grading finished". This is intended to support grading corrections on a larger scale. ''' for subm in queryset: subm.state = Submission.GRADED subm.save(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def closeAndNotifyAction(self, request, queryset): ''' Close all submissions were the tutor sayed that the grading is finished, and inform the student. CLosing only graded submissions is a safeguard, since backend users tend to checkbox-mark all submissions without thinking. ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def downloadArchiveAction(self, request, queryset): ''' Download selected submissions as archive, for targeted correction. ''' output = io.BytesIO() z = zipfile.ZipFile(output, 'w') for sub in queryset: sub.add_to_zipfile(z) z.close() # go ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def directory_name_with_course(self): ''' The assignment name in a format that is suitable for a directory name. ''' coursename = self.course.directory_name() assignmentname = self.title.replace(" ", "_").replace("\\", "_").replace(",","").lower() return coursename + os.sep + assignment...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def grading_url(self): ''' Determines the teacher backend link to the filtered list of gradable submissions for this assignment. ''' grading_url="%s?coursefilter=%u&assignmentfilter=%u&statefilter=tobegraded"%( reverse('teacher:opensubmit_submission_change...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def has_perf_results(self): ''' Figure out if any submission for this assignment has performance data being available. ''' num_results = SubmissionTestResult.objects.filter(perf_data__isnull=False).filter(submission_file__submissions__assignment=self).count() return num_resul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def url(self, request): ''' Return absolute URL for assignment description. ''' if self.pk: if self.has_description(): return request.build_absolute_uri(reverse('assignment_description_file', args=[self.pk])) else: return self.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 can_create_submission(self, user=None): ''' Central access control for submitting things related to assignments. ''' if user: # Super users, course owners and tutors should be able to test their validations # before the submission is officially possible. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def duplicate_files(self): ''' Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this 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 download_and_run(config): ''' Main operation of the executor. Returns True when a job was downloaded and executed. Returns False when no job could be downloaded. ''' job = fetch_job(config) if job: job._run_validate() return True else: return 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 copy_and_run(config, src_dir): ''' Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def console_script(): ''' The main entry point for the production administration script 'opensubmit-exec', installed by setuptools. ''' if len(sys.argv) == 1: print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]") 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 hashdict(d): """Hash a dictionary """
k = 0 for key,val in d.items(): k ^= hash(key) ^ hash(val) return k
<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_df(cls, df_long, df_short): """ Builds TripleOrbitPopulation from DataFrame ``DataFrame`` objects must be of appropriate form to pass to :func:`OrbitPop...
pop = cls(1,1,1,1,1) #dummy population pop.orbpop_long = OrbitPopulation.from_df(df_long) pop.orbpop_short = OrbitPopulation.from_df(df_short) return 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 load_hdf(cls, filename, path=''): """ Load TripleOrbitPopulation from saved .h5 file. :param filename: HDF file name. :param path: Path within HDF file where...
df_long = pd.read_hdf(filename,'{}/long/df'.format(path)) df_short = pd.read_hdf(filename,'{}/short/df'.format(path)) return cls.from_df(df_long, df_short)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RV_timeseries(self,ts,recalc=False): """ Radial Velocity time series for star 1 at given times ts. :param ts: Times. If not ``Quantity``, assumed to be in da...
if type(ts) != Quantity: ts *= u.day if not recalc and hasattr(self,'RV_measurements'): if (ts == self.ts).all(): return self._RV_measurements else: pass RVs = Quantity(np.zeros((len(ts),self.N)),unit='km/s') for i,t ...
<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_df(cls, df): """Creates an OrbitPopulation from a DataFrame. :param df: :class:`pandas.DataFrame` object. Must contain the following columns: ``['M1','M...
return cls(df['M1'], df['M2'], df['P'], ecc=df['ecc'], mean_anomaly=df['mean_anomaly'], obsx=df['obsx'], obsy=df['obsy'], obsz=df['obsz'])
<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 OrbitPopulation from HDF file. :param filename: HDF file :param path: Path within HDF file store where :class:`Orb...
df = pd.read_hdf(filename,'{}/df'.format(path)) return cls.from_df(df)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_pers_eccs(n,**kwargs): """ Draw random periods and eccentricities according to empirical survey data. """
pers = draw_raghavan_periods(n) eccs = draw_eccs(n,pers,**kwargs) return pers,eccs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_eccs(n,per=10,binsize=0.1,fuzz=0.05,maxecc=0.97): """draws eccentricities appropriate to given periods, generated according to empirical data from Multi...
if np.size(per) == 1 or np.std(np.atleast_1d(per))==0: if np.size(per)>1: per = per[0] if per==0: es = np.zeros(n) else: ne=0 while ne<10: mask = np.absolute(np.log10(MSC_TRIPLEPERS)-np.log10(per))<binsize/2. es...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def withinroche(semimajors,M1,R1,M2,R2): """ Returns boolean array that is True where two stars are within Roche lobe """
q = M1/M2 return ((R1+R2)*RSUN) > (rochelobe(q)*semimajors*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 semimajor(P,mstar=1): """Returns semimajor axis in AU given P in days, mstar in solar masses. """
return ((P*DAY/2/np.pi)**2*G*mstar*MSUN)**(1./3)/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 fluxfrac(*mags): """Returns fraction of total flux in first argument, assuming all are magnitudes. """
Ftot = 0 for mag in mags: Ftot += 10**(-0.4*mag) F1 = 10**(-0.4*mags[0]) return F1/Ftot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfromdm(dm): """Returns distance given distance modulus. """
if np.size(dm)>1: dm = np.atleast_1d(dm) return 10**(1+dm/5)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distancemodulus(d): """Returns distance modulus given d in parsec. """
if type(d)==Quantity: x = d.to('pc').value else: x = d #assumed to be pc if np.size(x)>1: d = np.atleast_1d(x) return 5*np.log10(x/10)
<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_files(path): """ Returns a recursive list of all non-hidden files in and below the current directory. """
return_files = [] for root, dirs, files in os.walk(path): # Skip hidden files files = [f for f in files if not f[0] == '.'] dirs[:] = [d for d in dirs if not d[0] == '.'] for filename in files: return_files.append(os.path.join(root, filename)) return return_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 save_pkl(self, filename): """ Pickles TransitSignal. """
with open(filename, 'wb') as fout: pickle.dump(self, fout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, fig=None, plot_trap=False, name=False, trap_color='g', trap_kwargs=None, **kwargs): """ Makes a simple plot of signal :param fig: (optional) Argum...
setfig(fig) plt.plot(self.ts,self.fs,'.',**kwargs) if plot_trap and hasattr(self,'trapfit'): if trap_kwargs is None: trap_kwargs = {} plt.plot(self.ts, traptransit(self.ts,self.trapfit), color=trap_color, **trap_kwargs) 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 kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500, shortest=True,conftol=0.001,return_max=False): """ Returns desired confidence interval for provided KDE ...
if xmin is None: xmin = kde.dataset.min() if xmax is None: xmax = kde.dataset.max() x = np.linspace(xmin,xmax,npts) return conf_interval(x,kde(x),shortest=shortest,conf=conf, conftol=conftol,return_max=return_max)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qstd(x,quant=0.05,top=False,bottom=False): """returns std, ignoring outer 'quant' pctiles """
s = np.sort(x) n = np.size(x) lo = s[int(n*quant)] hi = s[int(n*(1-quant))] if top: w = np.where(x>=lo) elif bottom: w = np.where(x<=hi) else: w = np.where((x>=lo)&(x<=hi)) return np.std(x[w])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot2dhist(xdata,ydata,cmap='binary',interpolation='nearest', fig=None,logscale=True,xbins=None,ybins=None, nbins=50,pts_only=False,**kwargs): """Plots a 2d ...
setfig(fig) if pts_only: plt.plot(xdata,ydata,**kwargs) return ok = (~np.isnan(xdata) & ~np.isnan(ydata) & ~np.isinf(xdata) & ~np.isinf(ydata)) if ~ok.sum() > 0: logging.warning('{} x values and {} y values are nan'.format(np.isnan(xdata).sum(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ldcoeffs(teff,logg=4.5,feh=0): """ Returns limb-darkening coefficients in Kepler band. """
teffs = np.atleast_1d(teff) loggs = np.atleast_1d(logg) Tmin,Tmax = (LDPOINTS[:,0].min(),LDPOINTS[:,0].max()) gmin,gmax = (LDPOINTS[:,1].min(),LDPOINTS[:,1].max()) teffs[(teffs < Tmin)] = Tmin + 1 teffs[(teffs > Tmax)] = Tmax - 1 loggs[(loggs < gmin)] = gmin + 0.01 loggs[(loggs > gmax...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def impact_parameter(a, R, inc, ecc=0, w=0, return_occ=False): """a in AU, R in Rsun, inc & w in radians """
b_tra = a*AU*np.cos(inc)/(R*RSUN) * (1-ecc**2)/(1 + ecc*np.sin(w)) if return_occ: b_tra = a*AU*np.cos(inc)/(R*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w)) return b_tra, b_occ else: return b_tra
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum_inclination(P,M1,M2,R1,R2): """ Returns the minimum inclination at which two bodies from two given sets eclipse Only counts systems not within each o...
P,M1,M2,R1,R2 = (np.atleast_1d(P), np.atleast_1d(M1), np.atleast_1d(M2), np.atleast_1d(R1), np.atleast_1d(R2)) semimajors = semimajor(P,M1+M2) rads = ((R1+R2)*RSUN/(semimajors*AU)) ok = (~np.isnan(rads) & ~withinroche(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eclipse_pars(P,M1,M2,R1,R2,ecc=0,inc=90,w=0,sec=False): """retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w"""
a = semimajor(P,M1+M2) if sec: b = a*AU*np.cos(inc*np.pi/180)/(R1*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w*np.pi/180)) #aR = a*AU/(R2*RSUN) #I feel like this was to correct a bug, but this should not be. #p0 = R1/R2 #why this also? else: b = a*AU*np.cos(inc*np.pi/180)/(R1*RSUN) ...
<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_traptransit(ts,fs,p0): """ Fits trapezoid model to provided ts,fs """
pfit,success = leastsq(traptransit_resid,p0,args=(ts,fs)) if success not in [1,2,3,4]: raise NoFitError #logging.debug('success = {}'.format(success)) return pfit
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backup(path, password_file=None): """ Replaces the contents of a file with its decrypted counterpart, storing the original encrypted version and a hash of th...
vault = VaultLib(get_vault_password(password_file)) with open(path, 'r') as f: encrypted_data = f.read() # Normally we'd just try and catch the exception, but the # exception raised here is not very specific (just # `AnsibleError`), so this feels safer to avoid suppressing ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(path, password_file=None): """ Retrieves a file from the atk vault and restores it to its original location, re-encrypting it if it has changed. :par...
vault = VaultLib(get_vault_password(password_file)) atk_path = os.path.join(ATK_VAULT, path) # Load stored data with open(os.path.join(atk_path, 'encrypted'), 'rb') as f: old_data = f.read() with open(os.path.join(atk_path, 'hash'), 'rb') as f: old_hash = f.read() # Load new 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 append(self, other): """Appends stars from another StarPopulations, in place. :param other: Another :class:`StarPopulation`; must have same columns as ``self...
if not isinstance(other,StarPopulation): raise TypeError('Only StarPopulation objects can be appended to a StarPopulation.') if not np.all(self.stars.columns == other.stars.columns): raise ValueError('Two populations must have same columns to combine them.') if len(self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bands(self): """ Bandpasses for which StarPopulation has magnitude data """
bands = [] for c in self.stars.columns: if re.search('_mag',c): bands.append(c) return bands
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(self,value): """New distance value must be a ``Quantity`` object """
self.stars['distance'] = value.to('pc').value old_distmod = self.stars['distmod'].copy() new_distmod = distancemodulus(self.stars['distance']) for m in self.bands: self.stars[m] += new_distmod - old_distmod self.stars['distmod'] = new_distmod logging.warn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distok(self): """ Boolean array showing which stars pass all distribution constraints. A "distribution constraint" is a constraint that affects the distribut...
ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name] if c.name not in self.distribution_skip: ok &= c.ok return ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def countok(self): """ Boolean array showing which stars pass all count constraints. A "count constraint" is a constraint that affects the number of stars. """
ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name] if c.name not in self.selectfrac_skip: ok &= c.ok return ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prophist2d(self,propx,propy, mask=None, logx=False,logy=False, fig=None,selected=False,**kwargs): """Makes a 2d density histogram of two given properties :pa...
if mask is not None: inds = np.where(mask)[0] else: if selected: inds = self.selected.index else: inds = self.stars.index if selected: xvals = self.selected[propx].iloc[inds].values yvals = self.select...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prophist(self,prop,fig=None,log=False, mask=None, selected=False,**kwargs): """Plots a 1-d histogram of desired property. :param prop: Name of property to pl...
setfig(fig) inds = None if mask is not None: inds = np.where(mask)[0] elif inds is None: if selected: #inds = np.arange(len(self.selected)) inds = self.selected.index else: #inds = np.arange(len(self.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraint_stats(self,primarylist=None): """Returns information about effect of constraints on population. :param primarylist: List of constraint names that ...
if primarylist is None: primarylist = [] n = len(self.stars) primaryOK = np.ones(n).astype(bool) tot_reject = np.zeros(n) for name in self.constraints: if name in self.selectfrac_skip: continue c = self.constraints[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 constraint_piechart(self,primarylist=None, fig=None,title='',colordict=None, legend=True,nolabels=False): """Makes piechart illustrating constraints on popul...
setfig(fig,figsize=(6,6)) stats = self.constraint_stats(primarylist=primarylist) if primarylist is None: primarylist = [] if len(primarylist)==1: primaryname = primarylist[0] else: primaryname = '' for name in primarylist: ...
<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): """ Constraints applied to the population. """
try: return self._constraints except AttributeError: self._constraints = ConstraintDict() return 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 hidden_constraints(self): """ Constraints applied to the population, but temporarily removed. """
try: return self._hidden_constraints except AttributeError: self._hidden_constraints = ConstraintDict() return self._hidden_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_constraint(self,constraint,selectfrac_skip=False, distribution_skip=False,overwrite=False): """Apply a constraint to the population :param constraint: ...
#grab properties constraints = self.constraints my_selectfrac_skip = self.selectfrac_skip my_distribution_skip = self.distribution_skip if constraint.name in constraints and not overwrite: logging.warning('constraint already applied: {}'.format(constraint.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 replace_constraint(self,name,selectfrac_skip=False,distribution_skip=False): """ Re-apply constraint that had been removed :param name: Name of constraint to...
hidden_constraints = self.hidden_constraints if name in hidden_constraints: c = hidden_constraints[name] self.apply_constraint(c,selectfrac_skip=selectfrac_skip, distribution_skip=distribution_skip) del hidden_constraints[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 constrain_property(self,prop,lo=-np.inf,hi=np.inf, measurement=None,thresh=3, selectfrac_skip=False,distribution_skip=False): """Apply constraint that constr...
if prop in self.constraints: logging.info('re-doing {} constraint'.format(prop)) self.remove_constraint(prop) if measurement is not None: val,dval = measurement self.apply_constraint(MeasurementConstraint(getattr(self.stars,prop), ...
<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, distribution_skip=False, **kwargs): """ Constrains change in RV to be less than limit over time dt. Only works if ``d...
if type(limit) != Quantity: limit = limit * u.m/u.s if type(dt) != Quantity: dt = dt * u.day dRVs = np.absolute(self.dRV(dt)) c1 = UpperLimit(dRVs, limit) c2 = LowerLimit(self.Plong, dt*4) self.apply_constraint(JointConstraintOr(c1,c2,name='RV 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 apply_cc(self, cc, distribution_skip=False, **kwargs): """ Apply contrast-curve constraint to population. Only works if object has ``Rsky``, ``dmag`` attribu...
rs = self.Rsky.to('arcsec').value dmags = self.dmag(cc.band) self.apply_constraint(ContrastCurveConstraint(rs,dmags,cc,name=cc.name), distribution_skip=distribution_skip, **kwargs)
<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, distribution_skip=False, **kwargs): """ Applies "velocity contrast curve" to population. That is, the constraint that comes from not see...
rvs = self.RV.value dmags = self.dmag(vcc.band) self.apply_constraint(VelocityContrastCurveConstraint(rvs,dmags,vcc, name='secondary spectrum'), distribution_skip=distribution_skip, **kwargs)
<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,maxrad, distribution_skip=True): """ Adds a constraint that rejects everything with Rsky > maxrad Requires ``Rsky`` attribute, which should a...
self.maxrad = maxrad self.apply_constraint(UpperLimit(self.Rsky,maxrad, name='Max Rsky'), overwrite=True, distribution_skip=distribution_skip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraint_df(self): """ A DataFrame representing all constraints, hidden or not """
df = pd.DataFrame() for name,c in self.constraints.items(): df[name] = c.ok for name,c in self.hidden_constraints.items(): df[name] = c.ok return df
<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='',properties=None, overwrite=False, append=False): """Saves to HDF5 file. Subclasses should be sure to define ``_properties`` at...
if os.path.exists(filename): with pd.HDFStore(filename) as store: if path in store: if overwrite: os.remove(filename) elif not append: raise IOError('{} in {} exists. '.format(path,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 load_hdf(cls, filename, path=''): """Loads StarPopulation from .h5 file Correct properties should be restored to object, and object will be original type tha...
stars = pd.read_hdf(filename,path+'/stars') constraint_df = pd.read_hdf(filename,path+'/constraints') with pd.HDFStore(filename) as store: has_orbpop = '{}/orbpop/df'.format(path) in store has_triple_orbpop = '{}/orbpop/long/df'.format(path) in store attrs =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary_fraction(self,query='mass_A >= 0'): """ Binary fraction of stars passing given query :param query: Query to pass to stars ``DataFrame``. """
subdf = self.stars.query(query) nbinaries = (subdf['mass_B'] > 0).sum() frac = nbinaries/len(subdf) return frac, frac/np.sqrt(nbinaries)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmag(self,band): """ Difference in magnitude between primary and secondary stars :param band: Photometric bandpass. """
mag2 = self.stars['{}_mag_B'.format(band)] mag1 = self.stars['{}_mag_A'.format(band)] return mag2-mag1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rsky_distribution(self,rmax=None,smooth=0.1,nbins=100): """ Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :p...
if rmax is None: if hasattr(self,'maxrad'): rmax = self.maxrad else: rmax = np.percentile(self.Rsky,99) dist = dists.Hist_Distribution(self.Rsky.value,bins=nbins,maxval=rmax,smooth=smooth) return dist
<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(self, M, age=9.6, feh=0.0, ichrone='mist', n=1e4, bands=None, **kwargs): """ Function that generates population. Called by ``__init__`` if ``M`` is ...
ichrone = get_ichrone(ichrone, bands=bands) if np.size(M) > 1: n = np.size(M) else: n = int(n) M2 = M * self.q_fn(n, qmin=np.maximum(self.qmin,self.minmass/M)) P = self.P_fn(n) ecc = self.ecc_fn(n,P) mass = np.ascontiguousarray(np.ones(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 dmag(self, band): """ Difference in magnitudes between fainter and brighter components in band. :param band: Photometric bandpass. """
m1 = self.stars['{}_mag_A'.format(band)] m2 = addmags(self.stars['{}_mag_B'.format(band)], self.stars['{}_mag_C'.format(band)]) return np.abs(m2-m1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dRV(self, dt, band='g'): """Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter """
return (self.orbpop.dRV_1(dt)*self.A_brighter(band) + self.orbpop.dRV_2(dt)*self.BC_brighter(band))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triple_fraction(self,query='mass_A > 0', unc=False): """ Triple fraction of stars following given query """
subdf = self.stars.query(query) ntriples = ((subdf['mass_B'] > 0) & (subdf['mass_C'] > 0)).sum() frac = ntriples/len(subdf) if unc: return frac, frac/np.sqrt(ntriples) else: return frac
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def starmodel_props(self): """Default mag_err is 0.05, arbitrarily """
props = {} mags = self.mags mag_errs = self.mag_errs for b in mags.keys(): if np.size(mags[b])==2: props[b] = mags[b] elif np.size(mags[b])==1: mag = mags[b] try: e_mag = mag_errs[b] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmag(self,band): """ Magnitude difference between primary star and BG stars """
if self.mags is None: raise ValueError('dmag is not defined because primary mags are not defined for this population.') return self.stars['{}_mag'.format(band)] - self.mags[band]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive(self): """I receive data+hash, check for a match, confirm or not confirm to the sender, and return the data payload. """
def _receive(input_message): self.data = input_message[:-64] _hash = input_message[-64:] if h.sha256(self.data).hexdigest() == _hash: self._w.send_message('Confirmed!') else: self._w.send_message('Not Confirmed!') yield se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validator(ch): """ Update screen if necessary and release the lock so receiveThread can run """
global screen_needs_update try: if screen_needs_update: curses.doupdate() screen_needs_update = False return ch finally: winlock.release() sleep(0.01) # let receiveThread in if necessary winlock.acquire()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(self, inds): """Returns copy of constraint, with mask rearranged according to indices """
new = copy.deepcopy(self) for arr in self.arrays: x = getattr(new, arr) setattr(new, arr, x[inds]) return new
<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(self, overwrite=True): """ Saves PopulationSet and TransitSignal. Shouldn't need to use this if you're using :func:`FPPCalculation.from_ini`. Saves :cla...
self.save_popset(overwrite=overwrite) self.save_signal()
<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(cls, folder): """ Loads PopulationSet from folder ``popset.h5`` and ``trsig.pkl`` must exist in folder. :param folder: Folder from which to load. """
popset = PopulationSet.load_hdf(os.path.join(folder,'popset.h5')) sigfile = os.path.join(folder,'trsig.pkl') with open(sigfile, 'rb') as f: trsig = pickle.load(f) return cls(trsig, popset, folder=folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FPPplots(self, folder=None, format='png', tag=None, **kwargs): """ Make FPP diagnostic plots Makes likelihood "fuzz plot" for each model, a FPP summary figur...
if folder is None: folder = self.folder self.write_results(folder=folder) self.lhoodplots(folder=folder,figformat=format,tag=tag,**kwargs) self.FPPsummary(folder=folder,saveplot=True,figformat=format,tag=tag) self.plotsignal(folder=folder,saveplot=True,figformat=for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_results(self,folder=None, filename='results.txt', to_file=True): """ Writes text file of calculation summary. :param folder: (optional) Folder to which...
if folder is None: folder = self.folder if to_file: fout = open(os.path.join(folder,filename), 'w') header = '' for m in self.popset.shortmodelnames: header += 'lhood_{0} L_{0} pr_{0} '.format(m) header += 'fpV fp FPP' if to_file: ...