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 toList(self): """ Returns date as signed list. """
date = self.date() sign = '+' if date[0] >= 0 else '-' date[0] = abs(date[0]) return list(sign) + date
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toString(self): """ Returns date as string. """
slist = self.toList() sign = '' if slist[0] == '+' else '-' string = '/'.join(['%02d' % v for v in slist[1:]]) return sign + string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUTC(self, utcoffset): """ Returns a new Time object set to UTC given an offset Time object. """
newTime = (self.value - utcoffset.value) % 24 return Time(newTime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toList(self): """ Returns time as signed list. """
slist = angle.toList(self.value) # Keep hours in 0..23 slist[1] = slist[1] % 24 return slist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toString(self): """ Returns time as string. """
slist = self.toList() string = angle.slistStr(slist) return string if slist[0] == '-' else string[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 fromJD(jd, utcoffset): """ Builds a Datetime object given a jd and utc offset. """
if not isinstance(utcoffset, Time): utcoffset = Time(utcoffset) localJD = jd + utcoffset.value / 24.0 date = Date(round(localJD)) time = Time((localJD + 0.5 - date.jdn) * 24) return Datetime(date, time, utcoffset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUTC(self): """ Returns this Datetime localized for UTC. """
timeUTC = self.time.getUTC(self.utcoffset) dateUTC = Date(round(self.jd)) return Datetime(dateUTC, timeUTC)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getObject(ID, jd, lat, lon): """ Returns an object for a specific date and location. """
if ID == const.SOUTH_NODE: obj = swe.sweObject(const.NORTH_NODE, jd) obj.update({ 'id': const.SOUTH_NODE, 'lon': angle.norm(obj['lon'] + 180) }) elif ID == const.PARS_FORTUNA: pflon = tools.pfLon(jd, lat, lon) obj = { 'id': ID, 'lon': pflon, 'lat': 0, 'lonspeed': 0, 'latspeed': 0 } elif ID == const.SYZYGY: szjd = tools.syzygyJD(jd) obj = swe.sweObject(const.MOON, szjd) obj['id'] = const.SYZYGY else: obj = swe.sweObject(ID, jd) _signInfo(obj) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFixedStar(ID, jd): """ Returns a fixed star. """
star = swe.sweFixedStar(ID, jd) _signInfo(star) return star
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextSunrise(jd, lat, lon): """ Returns the JD of the next sunrise. """
return swe.sweNextTransit(const.SUN, jd, lat, lon, 'RISE')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextSunset(jd, lat, lon): """ Returns the JD of the next sunset. """
return swe.sweNextTransit(const.SUN, jd, lat, lon, 'SET')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _signInfo(obj): """ Appends the sign id and longitude to an object. """
lon = obj['lon'] obj.update({ 'sign': const.LIST_SIGNS[int(lon / 30)], 'signlon': lon % 30 })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pfLon(jd, lat, lon): """ Returns the ecliptic longitude of Pars Fortuna. It considers diurnal or nocturnal conditions. """
sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) asc = swe.sweHousesLon(jd, lat, lon, const.HOUSES_DEFAULT)[1][0] if isDiurnal(jd, lat, lon): return angle.norm(asc + moon - sun) else: return angle.norm(asc + sun - moon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isDiurnal(jd, lat, lon): """ Returns true if the sun is above the horizon of a given date and location. """
sun = swe.sweObject(const.SUN, jd) mc = swe.sweHousesLon(jd, lat, lon, const.HOUSES_DEFAULT)[1][1] ra, decl = utils.eqCoords(sun['lon'], sun['lat']) mcRA, _ = utils.eqCoords(mc, 0.0) return utils.isAboveHorizon(ra, decl, mcRA, lat)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def syzygyJD(jd): """ Finds the latest new or full moon and returns the julian date of that event. """
sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) dist = angle.distance(sun, moon) # Offset represents the Syzygy type. # Zero is conjunction and 180 is opposition. offset = 180 if (dist >= 180) else 0 while abs(dist) > MAX_ERROR: jd = jd - dist / 13.1833 # Moon mean daily motion sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) dist = angle.closestdistance(sun - offset, moon) return jd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solarReturnJD(jd, lon, forward=True): """ Finds the julian date before or after 'jd' when the sun is at longitude 'lon'. It searches forward by default. """
sun = swe.sweObjectLon(const.SUN, jd) if forward: dist = angle.distance(sun, lon) else: dist = -angle.distance(lon, sun) while abs(dist) > MAX_ERROR: jd = jd + dist / 0.9833 # Sun mean motion sun = swe.sweObjectLon(const.SUN, jd) dist = angle.closestdistance(sun, lon) return jd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextStationJD(ID, jd): """ Finds the aproximate julian date of the next station of a planet. """
speed = swe.sweObject(ID, jd)['lonspeed'] for i in range(2000): nextjd = jd + i / 2 nextspeed = swe.sweObject(ID, nextjd)['lonspeed'] if speed * nextspeed <= 0: return nextjd 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 clean_caches(path): """ Removes all python cache files recursively on a path. :param path: the path :return: None """
for dirname, subdirlist, filelist in os.walk(path): for f in filelist: if f.endswith('pyc'): try: os.remove(os.path.join(dirname, f)) except FileNotFoundError: pass if dirname.endswith('__pycache__'): shutil.rmtree(dirname)
<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_py_files(path): """ Removes all .py files. :param path: the path :return: None """
for dirname, subdirlist, filelist in os.walk(path): for f in filelist: if f.endswith('py'): os.remove(os.path.join(dirname, 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 _orbList(obj1, obj2, aspList): """ Returns a list with the orb and angular distances from obj1 to obj2, considering a list of possible aspects. """
sep = angle.closestdistance(obj1.lon, obj2.lon) absSep = abs(sep) return [ { 'type': asp, 'orb': abs(absSep - asp), 'separation': sep, } for asp in aspList ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _aspectProperties(obj1, obj2, aspDict): """ Returns the properties of an aspect between obj1 and obj2, given by 'aspDict'. This function assumes obj1 to be the active object, i.e., the one responsible for starting the aspect. """
orb = aspDict['orb'] asp = aspDict['type'] sep = aspDict['separation'] # Properties prop1 = { 'id': obj1.id, 'inOrb': False, 'movement': const.NO_MOVEMENT } prop2 = { 'id': obj2.id, 'inOrb': False, 'movement': const.NO_MOVEMENT } prop = { 'type': asp, 'orb': orb, 'direction': -1, 'condition': -1, 'active': prop1, 'passive': prop2 } if asp == const.NO_ASPECT: return prop # Aspect within orb prop1['inOrb'] = orb <= obj1.orb() prop2['inOrb'] = orb <= obj2.orb() # Direction prop['direction'] = const.DEXTER if sep <= 0 else const.SINISTER # Sign conditions # Note: if obj1 is before obj2, orbDir will be less than zero orbDir = sep-asp if sep >= 0 else sep+asp offset = obj1.signlon + orbDir if 0 <= offset < 30: prop['condition'] = const.ASSOCIATE else: prop['condition'] = const.DISSOCIATE # Movement of the individual objects if abs(orbDir) < MAX_EXACT_ORB: prop1['movement'] = prop2['movement'] = const.EXACT else: # Active object applies to Passive if it is before # and direct, or after the Passive and Rx.. prop1['movement'] = const.SEPARATIVE if (orbDir > 0 and obj1.isDirect()) or \ (orbDir < 0 and obj1.isRetrograde()): prop1['movement'] = const.APPLICATIVE elif obj1.isStationary(): prop1['movement'] = const.STATIONARY # The Passive applies or separates from the Active # if it has a different direction.. # Note: Non-planets have zero speed prop2['movement'] = const.NO_MOVEMENT obj2speed = obj2.lonspeed if obj2.isPlanet() else 0.0 sameDir = obj1.lonspeed * obj2speed >= 0 if not sameDir: prop2['movement'] = prop1['movement'] return 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 _getActivePassive(obj1, obj2): """ Returns which is the active and the passive objects. """
speed1 = abs(obj1.lonspeed) if obj1.isPlanet() else -1.0 speed2 = abs(obj2.lonspeed) if obj2.isPlanet() else -1.0 if speed1 > speed2: return { 'active': obj1, 'passive': obj2 } else: return { 'active': obj2, 'passive': obj1 }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aspectType(obj1, obj2, aspList): """ Returns the aspect type between objects considering a list of possible aspect types. """
ap = _getActivePassive(obj1, obj2) aspDict = _aspectDict(ap['active'], ap['passive'], aspList) return aspDict['type'] if aspDict else const.NO_ASPECT
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasAspect(obj1, obj2, aspList): """ Returns if there is an aspect between objects considering a list of possible aspect types. """
aspType = aspectType(obj1, obj2, aspList) return aspType != const.NO_ASPECT
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isAspecting(obj1, obj2, aspList): """ Returns if obj1 aspects obj2 within its orb, considering a list of possible aspect types. """
aspDict = _aspectDict(obj1, obj2, aspList) if aspDict: return aspDict['orb'] < obj1.orb() 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 getAspect(obj1, obj2, aspList): """ Returns an Aspect object for the aspect between two objects considering a list of possible aspect types. """
ap = _getActivePassive(obj1, obj2) aspDict = _aspectDict(ap['active'], ap['passive'], aspList) if not aspDict: aspDict = { 'type': const.NO_ASPECT, 'orb': 0, 'separation': 0, } aspProp = _aspectProperties(ap['active'], ap['passive'], aspDict) return Aspect(aspProp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def movement(self): """ Returns the movement of this aspect. The movement is the one of the active object, except if the active is separating but within less than 1 degree. """
mov = self.active.movement if self.orb < 1 and mov == const.SEPARATIVE: mov = const.EXACT return mov
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setFaces(variant): """ Sets the default faces variant """
global FACES if variant == CHALDEAN_FACES: FACES = tables.CHALDEAN_FACES else: FACES = tables.TRIPLICITY_FACES
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setTerms(variant): """ Sets the default terms of the Dignities table. """
global TERMS if variant == EGYPTIAN_TERMS: TERMS = tables.EGYPTIAN_TERMS elif variant == TETRABIBLOS_TERMS: TERMS = tables.TETRABIBLOS_TERMS elif variant == LILLY_TERMS: TERMS = tables.LILLY_TERMS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def term(sign, lon): """ Returns the term for a sign and longitude. """
terms = TERMS[sign] for (ID, a, b) in terms: if (a <= lon < b): return ID 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 face(sign, lon): """ Returns the face for a sign and longitude. """
faces = FACES[sign] if lon < 10: return faces[0] elif lon < 20: return faces[1] else: return faces[2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getInfo(sign, lon): """ Returns the complete essential dignities for a sign and longitude. """
return { 'ruler': ruler(sign), 'exalt': exalt(sign), 'dayTrip': dayTrip(sign), 'nightTrip': nightTrip(sign), 'partTrip': partTrip(sign), 'term': term(sign, lon), 'face': face(sign, lon), 'exile': exile(sign), 'fall': fall(sign) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isPeregrine(ID, sign, lon): """ Returns if an object is peregrine on a sign and longitude. """
info = getInfo(sign, lon) for dign, objID in info.items(): if dign not in ['exile', 'fall'] and ID == objID: return False return 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 score(ID, sign, lon): """ Returns the score of an object on a sign and longitude. """
info = getInfo(sign, lon) dignities = [dign for (dign, objID) in info.items() if objID == ID] return sum([SCORES[dign] for dign in dignities])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def almutem(sign, lon): """ Returns the almutem for a given sign and longitude. """
planets = const.LIST_SEVEN_PLANETS res = [None, 0] for ID in planets: sc = score(ID, sign, lon) if sc > res[1]: res = [ID, sc] return res[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 getDignities(self): """ Returns the dignities belonging to this object. """
info = self.getInfo() dignities = [dign for (dign, objID) in info.items() if objID == self.obj.id] return dignities
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isPeregrine(self): """ Returns if this object is peregrine. """
return isPeregrine(self.obj.id, self.obj.sign, self.obj.signlon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _computeChart(chart, date): """ Internal function to return a new chart for a specific date using properties from old chart. """
pos = chart.pos hsys = chart.hsys IDs = [obj.id for obj in chart.objects] return Chart(date, pos, IDs=IDs, hsys=hsys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextSolarReturn(chart, date): """ Returns the solar return of a Chart after a specific date. """
sun = chart.getObject(const.SUN) srDate = ephem.nextSolarReturn(date, sun.lon) return _computeChart(chart, srDate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getHourTable(date, pos): """ Returns an HourTable object. """
table = hourTable(date, pos) return HourTable(table, date)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(self, date): """ Returns the index of a date in the table. """
for (i, (start, end, ruler)) in enumerate(self.table): if start <= date.jd <= end: return i 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 indexInfo(self, index): """ Returns information about a specific planetary time. """
entry = self.table[index] info = { # Default is diurnal 'mode': 'Day', 'ruler': self.dayRuler(), 'dayRuler': self.dayRuler(), 'nightRuler': self.nightRuler(), 'hourRuler': entry[2], 'hourNumber': index + 1, 'tableIndex': index, 'start': Datetime.fromJD(entry[0], self.date.utcoffset), 'end': Datetime.fromJD(entry[1], self.date.utcoffset) } if index >= 12: # Set information as nocturnal info.update({ 'mode': 'Night', 'ruler': info['nightRuler'], 'hourNumber': index + 1 - 12 }) return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute(chart, date, fixedObjects=False): """ Returns a profection chart for a given date. Receives argument 'fixedObjects' to fix chart objects in their natal locations. """
sun = chart.getObject(const.SUN) prevSr = ephem.prevSolarReturn(date, sun.lon) nextSr = ephem.nextSolarReturn(date, sun.lon) # In one year, rotate chart 30º rotation = 30 * (date.jd - prevSr.jd) / (nextSr.jd - prevSr.jd) # Include 30º for each previous year age = math.floor((date.jd - chart.date.jd) / 365.25) rotation = 30 * age + rotation # Create a copy of the chart and rotate content pChart = chart.copy() for obj in pChart.objects: if not fixedObjects: obj.relocate(obj.lon + rotation) for house in pChart.houses: house.relocate(house.lon + rotation) for angle in pChart.angles: angle.relocate(angle.lon + rotation) return pChart
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge(listA, listB): """ Merges two list of objects removing repetitions. """
listA = [x.id for x in listA] listB = [x.id for x in listB] listA.extend(listB) set_ = set(listA) return list(set_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute(chart): """ Computes the behavior. """
factors = [] # Planets in House1 or Conjunct Asc house1 = chart.getHouse(const.HOUSE1) planetsHouse1 = chart.objects.getObjectsInHouse(house1) asc = chart.getAngle(const.ASC) planetsConjAsc = chart.objects.getObjectsAspecting(asc, [0]) _set = _merge(planetsHouse1, planetsConjAsc) factors.append(['Planets in House1 or Conj Asc', _set]) # Planets conjunct Moon or Mercury moon = chart.get(const.MOON) mercury = chart.get(const.MERCURY) planetsConjMoon = chart.objects.getObjectsAspecting(moon, [0]) planetsConjMercury = chart.objects.getObjectsAspecting(mercury, [0]) _set = _merge(planetsConjMoon, planetsConjMercury) factors.append(['Planets Conj Moon or Mercury', _set]) # Asc ruler if aspected by disposer ascRulerID = essential.ruler(asc.sign) ascRuler = chart.getObject(ascRulerID) disposerID = essential.ruler(ascRuler.sign) disposer = chart.getObject(disposerID) _set = [] if aspects.isAspecting(disposer, ascRuler, const.MAJOR_ASPECTS): _set = [ascRuler.id] factors.append(['Asc Ruler if aspected by its disposer', _set]); # Planets aspecting Moon or Mercury aspMoon = chart.objects.getObjectsAspecting(moon, [60,90,120,180]) aspMercury = chart.objects.getObjectsAspecting(mercury, [60,90,120,180]) _set = _merge(aspMoon, aspMercury) factors.append(['Planets Asp Moon or Mercury', _set]) return factors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def termLons(TERMS): """ Returns a list with the absolute longitude of all terms. """
res = [] for i, sign in enumerate(SIGN_LIST): termList = TERMS[sign] res.extend([ ID, sign, start + 30 * i, ] for (ID, start, end) in termList) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute(chart): """ Computes the Almutem table. """
almutems = {} # Hylegic points hylegic = [ chart.getObject(const.SUN), chart.getObject(const.MOON), chart.getAngle(const.ASC), chart.getObject(const.PARS_FORTUNA), chart.getObject(const.SYZYGY) ] for hyleg in hylegic: row = newRow() digInfo = essential.getInfo(hyleg.sign, hyleg.signlon) # Add the scores of each planet where hyleg has dignities for dignity in DIGNITY_LIST: objID = digInfo[dignity] if objID: score = essential.SCORES[dignity] row[objID]['string'] += '+%s' % score row[objID]['score'] += score almutems[hyleg.id] = row # House positions row = newRow() for objID in OBJECT_LIST: obj = chart.getObject(objID) house = chart.houses.getObjectHouse(obj) score = HOUSE_SCORES[house.id] row[objID]['string'] = '+%s' % score row[objID]['score'] = score almutems['Houses'] = row # Planetary time row = newRow() table = planetarytime.getHourTable(chart.date, chart.pos) ruler = table.currRuler() hourRuler = table.hourRuler() row[ruler] = { 'string': '+7', 'score': 7 } row[hourRuler] = { 'string': '+6', 'score': 6 } almutems['Rulers'] = row; # Compute scores scores = newRow() for _property, _list in almutems.items(): for objID, values in _list.items(): scores[objID]['string'] += values['string'] scores[objID]['score'] += values['score'] almutems['Score'] = scores return almutems
<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(self, resource_id=None, resource_action=None, resource_cls=None, single_resource=False): """ Gets the details for one or more resources by ID Args: cls - gophish.models.Model - The resource class resource_id - str - The endpoint (URL path) for the resource resource_action - str - An action to perform on the resource resource_cls - cls - A class to use for parsing, if different than the base resource single_resource - bool - An override to tell Gophish that even though we aren't requesting a single resource, we expect a single response object Returns: One or more instances of cls parsed from the returned JSON """
endpoint = self.endpoint if not resource_cls: resource_cls = self._cls if resource_id: endpoint = self._build_url(endpoint, resource_id) if resource_action: endpoint = self._build_url(endpoint, resource_action) response = self.api.execute("GET", endpoint) if not response.ok: raise Error.parse(response.json()) if resource_id or single_resource: return resource_cls.parse(response.json()) return [resource_cls.parse(resource) for resource in response.json()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, resource): """ Creates a new instance of the resource. Args: resource - gophish.models.Model - The resource instance """
response = self.api.execute( "POST", self.endpoint, json=(resource.as_dict())) if not response.ok: raise Error.parse(response.json()) return self._cls.parse(response.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, resource): """ Edits an existing resource Args: resource - gophish.models.Model - The resource instance """
endpoint = self.endpoint if resource.id: endpoint = self._build_url(endpoint, resource.id) response = self.api.execute("PUT", endpoint, json=resource.as_dict()) if not response.ok: raise Error.parse(response.json()) return self._cls.parse(response.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, resource_id): """ Deletes an existing resource Args: resource_id - int - The resource ID to be deleted """
endpoint = '{}/{}'.format(self.endpoint, resource_id) response = self.api.execute("DELETE", endpoint) if not response.ok: raise Error.parse(response.json()) return self._cls.parse(response.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_dict(self): """ Returns a dict representation of the resource """
result = {} for key in self._valid_properties: val = getattr(self, key) if isinstance(val, datetime): val = val.isoformat() # Parse custom classes elif val and not Model._is_builtin(val): val = val.as_dict() # Parse lists of objects elif isinstance(val, list): # We only want to call as_dict in the case where the item # isn't a builtin type. for i in range(len(val)): if Model._is_builtin(val[i]): continue val[i] = val[i].as_dict() # If it's a boolean, add it regardless of the value elif isinstance(val, bool): result[key] = val # Add it if it's not None if val: result[key] = val return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, method, path, **kwargs): """ Executes a request to a given endpoint, returning the result """
url = "{}{}".format(self.host, path) kwargs.update(self._client_kwargs) response = requests.request( method, url, headers={"Authorization": "Bearer {}".format(self.api_key)}, **kwargs) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary(self, campaign_id=None): """ Returns the campaign summary """
resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( resource_id=campaign_id, resource_action='summary', resource_cls=resource_cls, single_resource=single_resource)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def results(self, campaign_id): """ Returns just the results for a given campaign """
return super(API, self).get( resource_id=campaign_id, resource_action='results', resource_cls=CampaignResults)
<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_path(self, file_path): """ Set the path of the database. Create the file if it does not exist. """
if not file_path: self.read_data = self.memory_read self.write_data = self.memory_write elif not is_valid(file_path): self.write_data(file_path, {}) self.path = file_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, key): """ Removes the specified key from the database. """
obj = self._get_content() obj.pop(key, None) self.write_data(self.path, obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self, **kwargs): """ If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and a value is provided then an entry will be created in the database. """
key = kwargs.pop('key', None) value = kwargs.pop('value', None) dictionary = kwargs.pop('dictionary', None) # Fail if a key and a dictionary or a value and a dictionary are given if (key is not None and dictionary is not None) or \ (value is not None and dictionary is not None): raise ValueError # If only a key was provided return the corresponding value if key is not None and value is None: return self._get_content(key) # if a key and a value are passed in if key is not None and value is not None: self._set_content(key, value) if dictionary is not None: for key in dictionary.keys(): value = dictionary[key] self._set_content(key, value) return self._get_content()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """
results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): for item, content in iteritems(self._get_content()): for key, value in iteritems(filter_arguments): keys = key.split('.') value = filter_arguments[key] if not self._contains_value({item: content}, keys, value): del results[item] # Filter based on an input string that should match database key if isinstance(filter_arguments, str): if filter_arguments in results: return [{filter_arguments: results[filter_arguments]}] else: return [] return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop(self): """ Remove the database by deleting the JSON file. """
import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._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 read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """
if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
<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_data(path, obj): """ Writes to a file and returns the updated file content. """
with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
<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_valid(file_path): """ Check to see if a file exists or is empty. """
from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(file_path) and is_file and stat(file_path).st_size > 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 create_edges(cells_nodes): """Setup edge-node and edge-cell relations. Adapted from voropy. """
# Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where `n` is # the number of cells. Make sure that the k-th edge is opposite of the k-th # point in the triangle. local_idx = numpy.array([[1, 2], [2, 0], [0, 1]]).T # Map idx back to the nodes. This is useful if quantities which are in # idx shape need to be added up into nodes (e.g., equation system rhs). nds = cells_nodes.T idx_hierarchy = nds[local_idx] s = idx_hierarchy.shape a = numpy.sort(idx_hierarchy.reshape(s[0], s[1] * s[2]).T) b = numpy.ascontiguousarray(a).view( numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1])) ) _, idx, inv, cts = numpy.unique( b, return_index=True, return_inverse=True, return_counts=True ) # No edge has more than 2 cells. This assertion fails, for example, if # cells are listed twice. assert all(cts < 3) edge_nodes = a[idx] cells_edges = inv.reshape(3, -1).T return edge_nodes, cells_edges
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot2d(points, cells, mesh_color="k", show_axes=False): """Plot a 2D mesh using matplotlib. """
import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_off() xmin = numpy.amin(points[:, 0]) xmax = numpy.amax(points[:, 0]) ymin = numpy.amin(points[:, 1]) ymax = numpy.amax(points[:, 1]) width = xmax - xmin xmin -= 0.1 * width xmax += 0.1 * width height = ymax - ymin ymin -= 0.1 * height ymax += 0.1 * height ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) edge_nodes, _ = create_edges(cells) # Get edges, cut off z-component. e = points[edge_nodes][:, :, :2] line_segments = LineCollection(e, color=mesh_color) ax.add_collection(line_segments) return fig
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return 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 contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """
for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) return 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 grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 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 shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] for i in range(len(list(args))): r.append(results.get()) return 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 run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.run() self.jobs.task_done() except TerminationNotice: self.jobs.task_done() break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the content is small, this step is not needed as the data can be included in the URL Parameters content - (see make_geojson) domain - string, default http://geojson.io force_gist - bool, default False Create an anonymous gist on Github regardless of the size of the contents """
url = make_url(contents, domain, force_gist) webbrowser.open(url) return url
<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_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters contents * string - assumed to be GeoJSON * an object that implements __geo_interface__ A FeatureCollection will be constructed with one feature, the object. * a sequence of objects that each implement __geo_interface__ A FeatureCollection will be constructed with the objects as the features domain - string, default http://geojson.io force_gist - force gist creation regardless of file size. For more information about __geo_interface__ see: https://gist.github.com/sgillies/2217756 If the contents are large, then a gist will be created. """
contents = make_geojson(contents) if len(contents) <= size_for_gist and not force_gist: url = data_url(contents, domain) else: gist = _make_gist(contents) url = gist_url(gist.id, domain) return url
<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_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """
if isinstance(contents, six.string_types): return contents if hasattr(contents, '__geo_interface__'): features = [_geo_to_feature(contents)] else: try: feature_iter = iter(contents) except TypeError: raise ValueError('Unknown type for input') features = [] for i, f in enumerate(feature_iter): if not hasattr(f, '__geo_interface__'): raise ValueError('Unknown type at index {0}'.format(i)) features.append(_geo_to_feature(f)) data = {'type': 'FeatureCollection', 'features': features} return json.dumps(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 data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters contents - string of GeoJSON domain - string, default http://geojson.io """
url = (domain + '#data=data:application/json,' + urllib.parse.quote(contents)) return url
<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_gist(contents, description='', filename='data.geojson'): """ Create and return an anonymous gist with a single file and specified contents """
ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clenshaw(a, alpha, beta, t): """Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details. """
n = len(alpha) assert len(beta) == n assert len(a) == n + 1 try: b = numpy.empty((n + 1,) + t.shape) except AttributeError: # 'float' object has no attribute 'shape' b = numpy.empty(n + 1) # b[0] is unused, can be any value # TODO shift the array b[0] = 1.0 b[n] = a[n] b[n - 1] = a[n - 1] + (t - alpha[n - 1]) * b[n] for k in range(n - 2, 0, -1): b[k] = a[k] + (t - alpha[k]) * b[k + 1] - beta[k + 1] * b[k + 2] phi0 = 1.0 phi1 = t - alpha[0] return phi0 * a[0] + phi1 * b[1] - beta[1] * phi0 * b[2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """
S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt gamma = sympy.gamma if symbolic else scipy.special.gamma if standardization == "monic": p0 = 1 a = n * [1] b = [2 * k + 1 + alpha for k in range(n)] c = [k * (k + alpha) for k in range(n)] c[0] = gamma(alpha + 1) elif standardization == "classical": p0 = 1 a = [-S(1) / (k + 1) for k in range(n)] b = [-S(2 * k + 1 + alpha) / (k + 1) for k in range(n)] c = [S(k + alpha) / (k + 1) for k in range(n)] c[0] = numpy.nan else: assert ( standardization == "normal" ), "Unknown Laguerre standardization '{}'.".format( standardization ) p0 = 1 / sqrt(gamma(alpha + 1)) a = [-1 / sqrt((k + 1) * (k + 1 + alpha)) for k in range(n)] b = [-(2 * k + 1 + alpha) / sqrt((k + 1) * (k + 1 + alpha)) for k in range(n)] c = [sqrt(k * S(k + alpha) / ((k + 1) * (k + 1 + alpha))) for k in range(n)] c[0] = numpy.nan return p0, numpy.array(a), numpy.array(b), numpy.array(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 plot(f, lcar=1.0e-1): """Plot function over a disk. """
import matplotlib import matplotlib.pyplot as plt import pygmsh geom = pygmsh.built_in.Geometry() geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True) points, cells, _, _, _ = pygmsh.generate_mesh(geom, verbose=True) x = points[:, 0] y = points[:, 1] triang = matplotlib.tri.Triangulation(x, y, cells["triangle"]) plt.tripcolor(triang, f(points.T), shading="flat") plt.colorbar() # Choose a diverging colormap such that the zeros are clearly # distinguishable. plt.set_cmap("coolwarm") # Make sure the color map limits are symmetric around 0. clim = plt.gci().get_clim() mx = max(abs(clim[0]), abs(clim[1])) plt.clim(-mx, mx) # circle outline circle = plt.Circle((0, 0), 1.0, edgecolor="k", fill=False) plt.gca().add_artist(circle) plt.gca().set_aspect("equal") plt.axis("off") 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 tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, Further, each level is organized like a discrete (dim-1)-dimensional simplex. Let's demonstrate this for 3D: L = 1: (0, 0, 0) L = 2: (1, 0, 0) (0, 1, 0) (0, 0, 1) L = 3: (2, 0, 0) (1, 1, 0) (1, 0, 1) (0, 2, 0) (0, 1, 1) (0, 0, 2) The main insight here that makes computation for n dimensions easy is that the next level is composed by: * Taking the whole previous level and adding +1 to the first entry. * Taking the last row of the previous level and adding +1 to the second entry. * Taking the last entry of the last row of the previous and adding +1 to the third entry. In the same manner this can be repeated for `dim` dimensions. """
p0, a, b, c = legendre(n + 1, "normal", symbolic=symbolic) dim = X.shape[0] p0n = p0 ** dim out = [] level = numpy.array([numpy.ones(X.shape[1:], dtype=int) * p0n]) out.append(level) # TODO use a simpler binom implementation for L in range(n): level = [] for i in range(dim - 1): m1 = int(scipy.special.binom(L + dim - i - 1, dim - i - 1)) if L > 0: m2 = int(scipy.special.binom(L + dim - i - 2, dim - i - 1)) r = 0 for k in range(L + 1): m = int(scipy.special.binom(k + dim - i - 2, dim - i - 2)) val = out[L][-m1:][r : r + m] * (a[L - k] * X[i] - b[L - k]) if L - k > 0: val -= out[L - 1][-m2:][r : r + m] * c[L - k] r += m level.append(val) # treat the last one separately val = out[L][-1] * (a[L] * X[-1] - b[L]) if L > 0: val -= out[L - 1][-1] * c[L] level.append([val]) out.append(numpy.concatenate(level)) return out
<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(corners, f, n=100): """Plot function over a triangle. """
import matplotlib.tri import matplotlib.pyplot as plt # discretization points def partition(boxes, balls): # <https://stackoverflow.com/a/36748940/353337> def rec(boxes, balls, parent=tuple()): if boxes > 1: for i in range(balls + 1): for x in rec(boxes - 1, i, parent + (balls - i,)): yield x else: yield parent + (balls,) return list(rec(boxes, balls)) bary = numpy.array(partition(3, n)).T / n X = numpy.sum([numpy.outer(bary[k], corners[:, k]) for k in range(3)], axis=0).T # plot the points # plt.plot(X[0], X[1], 'xk') x = numpy.array(X[0]) y = numpy.array(X[1]) z = numpy.array(f(bary), dtype=float) triang = matplotlib.tri.Triangulation(x, y) plt.tripcolor(triang, z, shading="flat") plt.colorbar() # Choose a diverging colormap such that the zeros are clearly # distinguishable. plt.set_cmap("coolwarm") # Make sure the color map limits are symmetric around 0. clim = plt.gci().get_clim() mx = max(abs(clim[0]), abs(clim[1])) plt.clim(-mx, mx) # triangle outlines X = numpy.column_stack([corners, corners[:, 0]]) plt.plot(X[0], X[1], "-k") plt.gca().set_aspect("equal") plt.axis("off") 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 _iget(key, lookup_dict): """ Case-insensitive search for `key` within keys of `lookup_dict`. """
for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v 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 write(filename, f): """Write a function `f` defined in terms of spherical coordinates to a file. """
import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], points[:, 0]) vals = f(polar, azimuthal) meshio.write(filename, points, {"triangle": cells}, point_data={"f": vals}) 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 tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """
cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#Orthogonality_and_normalization>. config = { "acoustic": ("complex spherical", False), "quantum mechanic": ("complex spherical", True), "geodetic": ("complex spherical 1", False), "schmidt": ("schmidt", False), } standard, cs_phase = config[standardization] return tree_alp( cos(polar), n, phi=azimuthal, standardization=standard, with_condon_shortley_phase=cs_phase, symbolic=symbolic, )
<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_if_this_file_exist(filename): """Check if this file exist and if it's a directory This function will check if the given filename actually exists and if it's not a Directory Arguments: filename {string} -- filename Return: True : if it's not a directory and if this file exist False : If it's not a file and if it's a directory """
#get the absolute path filename = os.path.abspath(filename) #Boolean this_file_exist = os.path.exists(filename) a_directory = os.path.isdir(filename) result = this_file_exist and not a_directory if result == False: raise ValueError('The filename given was either non existent or was a directory') else: return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_line(cmd): """Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output """
try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subprocess.CalledProcessError: return 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 information(filename): """Returns the file exif"""
check_if_this_file_exist(filename) filename = os.path.abspath(filename) result = get_json(filename) result = result[0] return result
<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_json(filename): """ Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object """
check_if_this_file_exist(filename) #Process this function filename = os.path.abspath(filename) s = command_line(['exiftool', '-G', '-j', '-sort', filename]) if s: #convert bytes to string s = s.decode('utf-8').rstrip('\r\n') return json.loads(s) else: return 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 get_csv(filename): """ Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string """
check_if_this_file_exist(filename) #Process this function filename = os.path.abspath(filename) s = command_line(['exiftool', '-G', '-csv', '-sort', filename]) if s: #convert bytes to string s = s.decode('utf-8') return s else: return 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 render(self, context=None, clean=False): """ Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Arguments clean : bool If ``True``, remove any template specific properties from the message object. Default is ``False``. """
# Load template if it is not loaded yet. if not self.template: self.load_template(self.template_name) # The signature of the `render()` method was changed in Django 1.7. # https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/#get-template-and-select-template if hasattr(self.template, 'template'): context = (context or self.context).copy() else: context = Context(context or self.context) # Add tag strings to the context. context.update(self.extra_context) result = self.template.render(context) # Don't overwrite default value with empty one. subject = self._get_block(result, 'subject') if subject: self.subject = self._get_block(result, 'subject') body = self._get_block(result, 'body') is_html_body = False # The html block is optional, and it also may be set manually. html = self._get_block(result, 'html') if html: if not body: # This is an html message without plain text part. body = html is_html_body = True else: # Add alternative content. self.attach_alternative(html, 'text/html') # Don't overwrite default value with empty one. if body: self.body = body if is_html_body: self.content_subtype = 'html' self._is_rendered = True if clean: self.clean()
<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(self, *args, **kwargs): """ Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments clean : bool If ``True``, remove any template specific properties from the message object. Default is ``False``. """
clean = kwargs.pop('clean', False) if not self._is_rendered: self.render() if clean: self.clean() return super(EmailMessage, self).send(*args, **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 send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the same way as the standard :func:`send_mail()<django.core.mail.send_mail>` function. .. |main_difference| replace:: The main difference is that two first arguments ``subject`` and ``body`` are replaced with ``template_name`` and ``context``. However you still can pass subject or body as keyword arguments to provide static content if needed. |main_difference| The ``template_name``, ``context``, ``from_email`` and ``recipient_list`` parameters are required. Note ---- |args_note| Arguments --------- template_name : str |template_name| context : dict |context| from_email : str |from_email| recipient_list : list |recipient_list| Keyword Arguments fail_silently : bool If it's False, send_mail will raise an :exc:`smtplib.SMTPException`. See the :mod:`smtplib` docs for a list of possible exceptions, all of which are subclasses of :exc:`smtplib.SMTPException`. auth_user | str The optional username to use to authenticate to the SMTP server. If this isn't provided, Django will use the value of the :django:setting:`EMAIL_HOST_USER` setting. auth_password | str The optional password to use to authenticate to the SMTP server. If this isn't provided, Django will use the value of the :django:setting:`EMAIL_HOST_PASSWORD` setting. connection : EmailBackend The optional email backend to use to send the mail. If unspecified, an instance of the default backend will be used. See the documentation on :ref:`Email backends<django:topic-email-backends>` for more details. subject : str |subject| body : str |body| render : bool |render| Returns ------- int The number of successfully delivered messages (which can be 0 or 1 since it can only send one message). See Also -------- :func:`django.core.mail.send_mail` Documentation for the standard ``send_mail()`` function. """
connection = connection or mail.get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) clean = kwargs.pop('clean', True) return EmailMessage( template_name, context, from_email, recipient_list, connection=connection, **kwargs).send(clean=clean)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the distance between a sample and the nearest cluster that the sample is not a part of. Note that Silhouette Coefficient is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the mean Silhouette Coefficient over all samples. To obtain the values for each sample, use :func:`silhouette_samples`. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Negative values generally indicate that a sample has been assigned to the wrong cluster, as a different cluster is more similar. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] Predicted labels for each sample. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`metrics.pairwise.pairwise_distances <sklearn.metrics.pairwise.pairwise_distances>`. If X is the distance array itself, use ``metric="precomputed"``. sample_size : int or None The size of the sample to use when computing the Silhouette Coefficient on a random subset of the data. If ``sample_size is None``, no sampling is used. random_state : int, RandomState instance or None, optional (default=None) The generator used to randomly select a subset of samples. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Used when ``sample_size is not None``. **kwds : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : float Mean Silhouette Coefficient for all samples. References .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """
if sample_size is not None: X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr']) random_state = check_random_state(random_state) indices = random_state.permutation(X.shape[0])[:sample_size] if metric == "precomputed": X, labels = X[indices].T[indices].T, labels[indices] else: X, labels = X[indices], labels[indices] return np.mean(silhouette_samples(X, labels, metric=metric, **kwds))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each other, and well separated, where samples in different clusters are not very similar to each other. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. Note that Silhouette Coefficient is only defined if number of labels is 2 <= n_labels <= n_samples - 1. This function returns the Silhouette Coefficient for each sample. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Read more in the :ref:`User Guide <silhouette_coefficient>`. Parameters X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] label values for each sample metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is the distance array itself, use "precomputed" as the metric. **kwds : optional keyword parameters Any further parameters are passed directly to the distance function. If using a ``scipy.spatial.distance`` metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- silhouette : array, shape = [n_samples] Silhouette Coefficient for each samples. References .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <http://www.sciencedirect.com/science/article/pii/0377042787901257>`_ .. [2] `Wikipedia entry on the Silhouette Coefficient <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """
X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr']) le = LabelEncoder() labels = le.fit_transform(labels) check_number_of_labels(len(le.classes_), X.shape[0]) distances = pairwise_distances(X, metric=metric, **kwds) unique_labels = le.classes_ n_samples_per_label = np.bincount(labels, minlength=len(unique_labels)) # For sample i, store the mean distance of the cluster to which # it belongs in intra_clust_dists[i] intra_clust_dists = np.zeros(distances.shape[0], dtype=distances.dtype) # For sample i, store the mean distance of the second closest # cluster in inter_clust_dists[i] inter_clust_dists = np.inf + intra_clust_dists for curr_label in range(len(unique_labels)): # Find inter_clust_dist for all samples belonging to the same # label. mask = labels == curr_label current_distances = distances[mask] # Leave out current sample. n_samples_curr_lab = n_samples_per_label[curr_label] - 1 if n_samples_curr_lab != 0: intra_clust_dists[mask] = np.sum( current_distances[:, mask], axis=1) / n_samples_curr_lab # Now iterate over all other labels, finding the mean # cluster distance that is closest to every sample. for other_label in range(len(unique_labels)): if other_label != curr_label: other_mask = labels == other_label other_distances = np.mean( current_distances[:, other_mask], axis=1) inter_clust_dists[mask] = np.minimum( inter_clust_dists[mask], other_distances) sil_samples = inter_clust_dists - intra_clust_dists sil_samples /= np.maximum(intra_clust_dists, inter_clust_dists) # score 0 for clusters of size 1, according to the paper sil_samples[n_samples_per_label.take(labels) == 1] = 0 return sil_samples
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calinski_harabaz_score(X, labels): """Compute the Calinski and Harabaz score. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the :ref:`User Guide <calinski_harabaz_index>`. Parameters X : array-like, shape (``n_samples``, ``n_features``) List of ``n_features``-dimensional data points. Each row corresponds to a single data point. labels : array-like, shape (``n_samples``,) Predicted labels for each sample. Returns ------- score : float The resulting Calinski-Harabaz score. References .. [1] `T. Calinski and J. Harabasz, 1974. "A dendrite method for cluster analysis". Communications in Statistics <http://www.tandfonline.com/doi/abs/10.1080/03610927408827101>`_ """
X, labels = check_X_y(X, labels) le = LabelEncoder() labels = le.fit_transform(labels) n_samples, _ = X.shape n_labels = len(le.classes_) check_number_of_labels(n_labels, n_samples) extra_disp, intra_disp = 0., 0. mean = np.mean(X, axis=0) for k in range(n_labels): cluster_k = X[labels == k] mean_k = np.mean(cluster_k, axis=0) extra_disp += len(cluster_k) * np.sum((mean_k - mean) ** 2) intra_disp += np.sum((cluster_k - mean_k) ** 2) return (1. if intra_disp == 0. else extra_disp * (n_samples - n_labels) / (intra_disp * (n_labels - 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 handle_zeros_in_scale(scale, copy=True): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): if scale == .0: scale = 1. return scale elif isinstance(scale, np.ndarray): if copy: # New array to avoid side-effects scale = scale.copy() scale[scale == 0.0] = 1.0 return scale
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _joint_probabilities(distances, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances. Parameters distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and duplicate entries and store everything in a one-dimensional array. desired_perplexity : float Desired perplexity of the joint probability distributions. verbose : int Verbosity level. Returns ------- P : array, shape (n_samples * (n_samples-1) / 2,) Condensed joint probability matrix. """
# Compute conditional probabilities such that they approximately match # the desired perplexity distances = distances.astype(np.float32, copy=False) conditional_P = _utils._binary_search_perplexity( distances, None, desired_perplexity, verbose) P = conditional_P + conditional_P.T sum_P = np.maximum(np.sum(P), MACHINE_EPSILON) P = np.maximum(squareform(P) / sum_P, MACHINE_EPSILON) return 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 _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improves this substantially to O(uN). Parameters distances : array, shape (n_samples, k) Distances of samples to its k nearest neighbors. neighbors : array, shape (n_samples, k) Indices of the k nearest-neighbors for each samples. desired_perplexity : float Desired perplexity of the joint probability distributions. verbose : int Verbosity level. Returns ------- P : csr sparse matrix, shape (n_samples, n_samples) Condensed joint probability matrix with only nearest neighbors. """
t0 = time() # Compute conditional probabilities such that they approximately match # the desired perplexity n_samples, k = neighbors.shape distances = distances.astype(np.float32, copy=False) neighbors = neighbors.astype(np.int64, copy=False) conditional_P = _utils._binary_search_perplexity( distances, neighbors, desired_perplexity, verbose) assert np.all(np.isfinite(conditional_P)), \ "All probabilities should be finite" # Symmetrize the joint probability distribution using sparse operations P = csr_matrix((conditional_P.ravel(), neighbors.ravel(), range(0, n_samples * k + 1, k)), shape=(n_samples, n_samples)) P = P + P.T # Normalize the joint probability distribution sum_P = np.maximum(P.sum(), MACHINE_EPSILON) P /= sum_P assert np.all(np.abs(P.data) <= 1.0) if verbose >= 2: duration = time() - t0 print("[t-SNE] Computed conditional probabilities in {:.3f}s" .format(duration)) return 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 _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and individual gains. Parameters objective : function or callable Should return a tuple of cost and gradient for a given parameter vector. When expensive to compute, the cost can optionally be None and can be computed every n_iter_check steps using the objective_error function. p0 : array-like, shape (n_params,) Initial parameter vector. it : int Current number of iterations (this function will be called more than once during the optimization). n_iter : int Maximum number of gradient descent iterations. n_iter_check : int Number of iterations before evaluating the global error. If the error is sufficiently low, we abort the optimization. n_iter_without_progress : int, optional (default: 300) Maximum number of iterations without progress before we abort the optimization. momentum : float, within (0.0, 1.0), optional (default: 0.8) The momentum generates a weight for previous gradients that decays exponentially. learning_rate : float, optional (default: 200.0) The learning rate for t-SNE is usually in the range [10.0, 1000.0]. If the learning rate is too high, the data may look like a 'ball' with any point approximately equidistant from its nearest neighbours. If the learning rate is too low, most points may look compressed in a dense cloud with few outliers. min_gain : float, optional (default: 0.01) Minimum individual gain for each parameter. min_grad_norm : float, optional (default: 1e-7) If the gradient norm is below this threshold, the optimization will be aborted. verbose : int, optional (default: 0) Verbosity level. args : sequence Arguments to pass to objective function. kwargs : dict Keyword arguments to pass to objective function. Returns ------- p : array, shape (n_params,) Optimum parameters. error : float Optimum. i : int Last iteration. """
if args is None: args = [] if kwargs is None: kwargs = {} p = p0.copy().ravel() update = np.zeros_like(p) gains = np.ones_like(p) error = np.finfo(np.float).max best_error = np.finfo(np.float).max best_iter = i = it tic = time() for i in range(it, n_iter): error, grad = objective(p, *args, **kwargs) grad_norm = linalg.norm(grad) inc = update * grad < 0.0 dec = np.invert(inc) gains[inc] += 0.2 gains[dec] *= 0.8 np.clip(gains, min_gain, np.inf, out=gains) grad *= gains update = momentum * update - learning_rate * grad p += update if (i + 1) % n_iter_check == 0: toc = time() duration = toc - tic tic = toc if verbose >= 2: print("[t-SNE] Iteration %d: error = %.7f," " gradient norm = %.7f" " (%s iterations in %0.3fs)" % (i + 1, error, grad_norm, n_iter_check, duration)) if error < best_error: best_error = error best_iter = i elif i - best_iter > n_iter_without_progress: if verbose >= 2: print("[t-SNE] Iteration %d: did not make any progress " "during the last %d episodes. Finished." % (i + 1, n_iter_without_progress)) break if grad_norm <= min_grad_norm: if verbose >= 2: print("[t-SNE] Iteration %d: gradient norm %f. Finished." % (i + 1, grad_norm)) break return p, error, 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 trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) where :math:`r(i, j)` is the rank of the embedded datapoint j according to the pairwise distances between the embedded datapoints, :math:`U^{(k)}_i` is the set of points that are in the k nearest neighbors in the embedded space but not in the original space. * "Neighborhood Preservation in Nonlinear Projection Methods: An Experimental Study" J. Venna, S. Kaski * "Learning a Parametric Embedding by Preserving Local Structure" L.J.P. van der Maaten Parameters X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. X_embedded : array, shape (n_samples, n_components) Embedding of the training data in low-dimensional space. n_neighbors : int, optional (default: 5) Number of neighbors k that will be considered. precomputed : bool, optional (default: False) Set this flag if X is a precomputed square distance matrix. Returns ------- trustworthiness : float Trustworthiness of the low-dimensional embedding. """
if precomputed: dist_X = X else: dist_X = pairwise_distances(X, squared=True) dist_X_embedded = pairwise_distances(X_embedded, squared=True) ind_X = np.argsort(dist_X, axis=1) ind_X_embedded = np.argsort(dist_X_embedded, axis=1)[:, 1:n_neighbors + 1] n_samples = X.shape[0] t = 0.0 ranks = np.zeros(n_neighbors) for i in range(n_samples): for j in range(n_neighbors): ranks[j] = np.where(ind_X[i] == ind_X_embedded[i, j])[0][0] ranks -= n_neighbors t += np.sum(ranks[ranks > 0]) t = 1.0 - t * (2.0 / (n_samples * n_neighbors * (2.0 * n_samples - 3.0 * n_neighbors - 1.0))) return t