query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return the color temperature of this light.
def color_temp(self): return kelvin_to_mired(self._color_temp)
[ "def current_color_temperature(self) -> int | float | None:\n return self.color_temperature.value", "def temperature(self):\n temp_status = self._driver.query_temp_status(self._handle)\n return temp_status['imaging_ccd_temperature']", "def temperature(self):\n return self._temperatur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns the number of elements in the numbers list that are divisible by divide.
def listDivide(numbers, divide = 2): divisible_count = 0 for i in numbers: if i % divide == 0: divisible_count += 1 return divisible_count
[ "def listDivide(numbers,divide=2):\n div = 0\n for num in numbers:\n if num % divide == 0:\n div += 1\n return div", "def listDivide(numbers=[], divide=2):\n a = [x % divide for x in numbers]\n count = a.count(0)\n return count", "def answer(l)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function tests the listDivide function.
def testListDivide(): assert listDivide([1,2,3,4,5]) == 2 assert listDivide([2,4,6,8,10]) == 5 assert listDivide([30, 54, 63,98, 100], divide = 10) == 2 assert listDivide([]) == 0 assert listDivide([1,2,3,4,5], 1) == 5
[ "def testListDivide():\n listDivide([1, 2, 3, 4, 5])\n listDivide([2, 4, 6, 8, 10])\n listDivide([30, 54, 63, 98, 100], divide=10)\n listDivide([])\n listDivide([1, 2, 3, 4, 5], 1)", "def testListDivide():\n\n result = listDivide([1, 2, 3, 4, 5])\n if result != 2:\n raise ListDivideExc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drops an Operation, identified by it's Operation Id and it's children recursively Drop deletes the Operations from Database
def drop_operation(cls,operation_id): db = cls._core.get_db() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;" cur = db.query(cls._core,stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.drop_operation(row["OPE_ID"]) ...
[ "def cancel_operation(cls,operation_id):\n db = cls._core.get_db()\n\n stmnt = \"SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;\"\n cur = db.query(cls._core,stmnt,(operation_id,))\n for row in cur.fetchallmap():\n cls.cancel_operation(row[\"OPE_ID\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the state of an operation and it's children recursively to 0 (PENDING) The operation is identified by a given operationId
def retry_operation(cls,operation_id): db = cls._core.get_db() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 2 ;" cur = db.query(cls._core,stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.retry_operation(row["OPE_ID"]) stmn...
[ "def cancel_operation(cls,operation_id):\n db = cls._core.get_db()\n\n stmnt = \"SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;\"\n cur = db.query(cls._core,stmnt,(operation_id,))\n for row in cur.fetchallmap():\n cls.cancel_operation(row[\"OPE_ID\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancels an Operation, identified by it's Operation Id and it's children recursively Cancel Deletes the Operation from Database
def cancel_operation(cls,operation_id): db = cls._core.get_db() stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;" cur = db.query(cls._core,stmnt,(operation_id,)) for row in cur.fetchallmap(): cls.cancel_operation(row["OPE_ID"]) st...
[ "def drop_operation(cls,operation_id):\n db = cls._core.get_db()\n\n stmnt = \"SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;\"\n cur = db.query(cls._core,stmnt,(operation_id,))\n for row in cur.fetchallmap():\n cls.drop_operation(row[\"OPE_I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore an Operationobject stored in the database by a Dataset consisting of
def restore_operation(cls, operation_record): classname = operation_record["OPE_TYPE"] module = "" #TODO Implement modulename from database if Operation belongs to Module is_operation_of_module = False exec """ try: type(%(class)s) except NameError,e: is_operation_of_module = Tru...
[ "def restore(self, checkpoint):\n raise NotImplementedError", "def mos_object(self):\n return self._restore_fn(*self._restore_args)", "def _restore_state(self, data, *, copy=True):\n if self._state_metadata['dims'] == self.rhs.dims[1]:\n state = Qobj(unstack_columns(data),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively executes the workloads of Operation's Childoperations It hereby catches exceptions in the workloads, sets the OPE_STATUS to 2 (FAILED) if a catch occurs, then passes the exception on to the higher layer. If an Operation succeeds, it's entry in DB gets deleted
def process_children(cls, operation): db = cls._core.get_db() stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT = ? ORDER BY OPE_INVOKED ;" stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 WHERE OPE_ID = ? ;" cur = db.query(cls._core,stmnt,(operation.get_id(),)) ...
[ "def retry_operation(cls,operation_id):\n db = cls._core.get_db()\n\n stmnt = \"SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 2 ;\"\n cur = db.query(cls._core,stmnt,(operation_id,))\n for row in cur.fetchallmap():\n cls.retry_operation(row[\"OPE_ID\"]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the status of the next toplevel operation to 1 (ACTIVE) Fetches the next topleveloperation from the database, applies a FILESYSTEMLOCK! Which is /tmp/scv_operating.lck !!!
def process_next(cls): db = cls._core.get_db() configuration = cls._core.get_configuration() if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"): return False lockfile = open(configuration.get_entry("core.webpath")+"/scv_operating.lck","w") ...
[ "def setPLOn(self):\n self.querier.setMsgHandler(DefaultMsgHandler(\"Set Programming Lock ON\"))\n return self.querier.queryext(0x20, 0x00, [0x00, 0x00, 0x00]);", "def arm_oplock_future(self):\n self.oplock_future = self.tree.session.client.oplock_break_future(self.file_id)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets this operations values from module metadata
def set_values(self,module): if type(module) == dict: self.set_value("name",module["name"]) self.set_value("hrname",module["hrname"]) self.set_value("version_major",module["version_major"]) self.set_value("version_minor",module["version_minor"]) self.s...
[ "def set_metadata(self, data):\r\n pass", "def configure_operation(self, operation):\n operation.axis = self.axis\n operation.axisMatrix = self.axisMatrix", "def applyMeta(self):\n self.interface.setMeta('kernel', 'opencl r%s' % self.REVISION)\n self.interface.setMeta('device'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an Array of ModuleOperationObjects that are currently listedin the queue
def get_currently_processed_modules(cls): db = cls._core.get_db() stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_TYPE FROM OPERATIONS \ WHERE OPE_TYPE = 'ModuleInstallOperation' \ or OPE_TYPE = 'ModuleUninstallOperation' ;" cur = db.query(cls._core,stmnt); ...
[ "def to_array(self):\n\n return list(self.global_queue.queue)", "def operations(self):\r\n return self._operations_list", "def get_queue_list(self):\n return self.manager.get_queue_list()", "def _recent_commissions(self):\n\n ## we don't set up a queue, as there is a permanent one\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute squarefree decomposition of the monic ``f`` in ``GF(q)[X]``. Notes ===== Uses a modified version of Musser's algorithm for squarefree decomposition of univariate polynomials over finite fields. References ==========
def _gf_sqf_list(self, f): domain = self.domain n, factors, p = 1, [], int(domain.characteristic) m = int(domain.order // p) while not f.is_ground: df = [f.diff(x) for x in self.gens] if any(_ for _ in df): g = f for q in df: ...
[ "def _squarefree_decomposition_univariate_polynomial(self, f):\n from sage.structure.factorization import Factorization\n if f.degree() == 0:\n return Factorization([], unit=f[0])\n if self.characteristic() != 0:\n raise NotImplementedError(\"square-fre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ``True`` if ``f`` is a squarefree polynomial in ``K[X]``. Examples ======== >>> _, x, y = ring('x y', ZZ) >>> ((x + y)2).is_squarefree False >>> (x2 + y2).is_squarefree True
def is_squarefree(self, f): if f.is_ground: return True g = f for x in self.gens: g = self.gcd(g, f.diff(x)) if g.is_ground: return True return False
[ "def is_squarefree_hilbert_number(n):\n return is_hilbert_number(n) and is_hilbert_squarefree_number(n)", "def is_sqf(f):\n return dmp_sqf_p(f.rep, f.lev, f.dom)", "def is_quantifier_free(formula):\n assert type(formula) is Formula\n # Task 11.3.1\n root = formula.root\n if is_quantifier(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Squarefree norm of ``f`` in ``K[X]``, useful over algebraic domains. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(xsa)`` and ``r(x) = Norm(g(x))`` is a squarefree polynomial over K, where ``a`` is the algebraic extension of ``K``. Examples ======== >>> _, x, y = ring('x y', QQ.algebraic_field(I)) >>> (xy + y2).sqf...
def sqf_norm(self, f): domain = self.domain if not domain.is_AlgebraicField: raise DomainError(f'ground domain must be algebraic, got {domain}') new_ring = self.to_ground().inject(*domain.symbols, front=True) g = domain.mod.set_ring(new_ring) s = 0 while Tr...
[ "def sqf_norm(f):\n s, g, r = dmp_sqf_norm(f.rep, f.lev, f.dom)\n return s, f.per(g), f.per(r, dom=f.dom.dom)", "def sqrt(S):\r\n from math import sqrt as _sqrt\r\n if isinstance(S, PowerSeries):\r\n return S.squareroot()\r\n return _sqrt(S)", "def rsqrt_(self):\n return math_fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start twisted event loop and the fun should begin... brokerTimeout how long to wait for a broker a negative number upon failure. Otherwise, it never returns.
def start(config, brokerTimeout = 60.0): manager = multiprocessing.Manager() serverUpEvent = manager.Event() broker = multiprocessing.Process(target=startSTOMPBroker, args=(config,serverUpEvent)) broker.daemon = True broker.name = 'STOMP-Broker' broker.start() serverUpEvent.wait(brokerTimeout) if no...
[ "def testReactor(self):\n lbrynet.dht.protocol.reactor.listenUDP(0, self.protocol)\n lbrynet.dht.protocol.reactor.callLater(0, lbrynet.dht.protocol.reactor.stop)\n lbrynet.dht.protocol.reactor.run()", "def start(self):\n if not self._connected:\n self._client.connect(self._a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the solar noon (the time when the sun is at its highest point.)
def solar_noon(self, date=None, local=True): if self.astral is None: self.astral = Astral() if date is None: date = datetime.date.today() noon = self.astral.solar_noon_utc(date, self.longitude) if local: return noon.astimezone(self.tz) ...
[ "def find_solar_noon(self,dt):\n year = dt.timetuple().tm_year\n #print year\n month = dt.timetuple().tm_mon\n #print month\n \n day = dt.timetuple().tm_mday \n \n sitka = ephem.Observer()\n \n date = str(year)+'/'+str(month)+'/'+str(day)\n #p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the solar azimuth angle for a specific date/time.
def solar_azimuth(self, dateandtime=None): if self.astral is None: self.astral = Astral() if dateandtime is None: dateandtime = datetime.datetime.now(tz=self.tz) return self.astral.solar_azimuth(dateandtime, self.latitude, self.longitude)
[ "def HourAngle(solar_time):\n return solar_time*15 - 180", "def hour_angle(solar_time):\n ha = pi / 12 * (solar_time - 12)\n\n return ha", "def angle_and_azimuth(self, satellite_ecef):\n from numpy import arcsin, arctan2, dot\n from numpy.linalg import norm\n\n r_ss = satellite_ece...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the solar elevation angle for a specific time.
def solar_elevation(self, dateandtime=None): if self.astral is None: self.astral = Astral() if dateandtime is None: dateandtime = datetime.datetime.now(tz=self.tz) return self.astral.solar_elevation(dateandtime, self.latitude, self.longitude)
[ "def HourAngle(solar_time):\n return solar_time*15 - 180", "def hour_angle(solar_time):\n ha = pi / 12 * (solar_time - 12)\n\n return ha", "def solar_azimuth(self, dateandtime=None):\n\n if self.astral is None:\n self.astral = Astral()\n\n if dateandtime is None:\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialise the city database and set the default depression.
def __init__(self): self._citydb = CityDB() self._depression = 6 # Set default depression in degrees
[ "def init_db(self):\n self.create_db()\n col_rows = self.check_default_settings()\n if col_rows == 0:\n self.set_default_settings()", "def initialize():\n sql_db = SQLConnection()\n with SQLCursor(sql_db) as cur:\n cur.execute('SELECT position from govt_info')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the City instance specified by ``key``.
def __getitem__(self, key): city = self._citydb[key] city.astral = self return city
[ "def retrieve_city(city_id):\n city = storage.get('City', city_id)\n if city:\n return city.to_dict()\n abort(404)", "def get_city(city_id):\n city = storage.get(City, city_id)\n\n if not city:\n abort(404)\n\n return jsonify(city.to_dict()), 200", "def city_by_id(city_id):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate dawn time in the UTC timezone.
def dawn_utc(self, date, latitude, longitude): julianday = self._julianday(date.day, date.month, date.year) if latitude > 89.8: latitude = 89.8 if latitude < -89.8: latitude = -89.8 t = self._jday_to_jcentury(julianday) eqti...
[ "def get_unixtime(self):\n if not self.Complete():\n raise DateTimeError(\"get_unixtime requires complete timepoint\")\n zoffset = self.time.GetZoneOffset()\n if zoffset is None:\n raise DateTimeError(\"get_unixtime requires timezone\")\n elif zoffset == 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate sunrise time in the UTC timezone.
def sunrise_utc(self, date, latitude, longitude): julianday = self._julianday(date.day, date.month, date.year) t = self._jday_to_jcentury(julianday) eqtime = self._eq_of_time(t) solarDec = self._sun_declination(t) try: hourangle = self._hour_angle_sunrise(l...
[ "def sunrise_time(datetime=None):\n pass", "def alt_sunrise(cls, date):\n rise = cls.UJJAIN.dawn(date, angle(0, 47, 0))\n return 1/24 * 1/60 * iround(rise * 24 * 60)", "def sunrise(cls, date):\n return (date + Clock.days_from_hours(6) + \n ((cls.UJJAIN.longitude - cls.LOCA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate solar noon time in the UTC timezone.
def solar_noon_utc(self, date, longitude): julianday = self._julianday(date.day, date.month, date.year) newt = self._jday_to_jcentury(julianday + 0.5 + longitude / 360.0) eqtime = self._eq_of_time(newt) timeUTC = 720.0 + (longitude * 4.0) - eqtime timeUTC = timeUTC/60...
[ "def solar_noon(self, date=None, local=True):\n \n if self.astral is None:\n self.astral = Astral()\n\n if date is None:\n date = datetime.date.today()\n\n noon = self.astral.solar_noon_utc(date, self.longitude)\n\n if local:\n return noon.astimezo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate sunset time in the UTC timezone.
def sunset_utc(self, date, latitude, longitude): julianday = self._julianday(date.day, date.month, date.year) t = self._jday_to_jcentury(julianday) eqtime = self._eq_of_time(t) solarDec = self._sun_declination(t) try: hourangle = self._hour_angle_sunset(lat...
[ "def sunset(cls, date):\n return (date + Clock.days_from_hours(18) + \n ((cls.UJJAIN.longitude - cls.LOCATION.longitude) / 360) -\n cls.equation_of_time(date) +\n (((1577917828/1582237828) / 360) *\n (- cls.ascensional_difference(date, cls.LOCATION...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate dusk time in the UTC timezone.
def dusk_utc(self, date, latitude, longitude): julianday = self._julianday(date.day, date.month, date.year) if latitude > 89.8: latitude = 89.8 if latitude < -89.8: latitude = -89.8 t = self._jday_to_jcentury(julianday) eqti...
[ "def timezone():\n \n pass", "def nowUTC():\n return datetime.datetime.now(pytz.utc)", "def dawn_utc(self, date, latitude, longitude):\n \n julianday = self._julianday(date.day, date.month, date.year)\n\n if latitude > 89.8:\n latitude = 89.8\n \n if lat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate ruhakaalam times in the UTC timezone.
def rahukaalam_utc(self, date, latitude, longitude): if date is None: date = datetime.date.today() try: sunrise = self.sunrise_utc(date, latitude, longitude) sunset = self.sunset_utc(date, latitude, longitude) except: raise AstralError('S...
[ "def timezone():\n \n pass", "def set_time_by_timezone(df):\n df = set_city_time_by_timezone(df, 1078, 3)\n df = set_city_time_by_timezone(df, 22390, 4)\n df = set_city_time_by_timezone(df, 22430, 4)\n df = set_city_time_by_timezone(df, 22438, 5)\n return df", "def time_from_utc(utc_offset,t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the phase of the moon on the specified date.
def moon_phase(self, date): jd = self._julianday(date.day, date.month, date.year) DT = pow((jd - 2382148), 2) / (41048480*86400) T = (jd + DT - 2451545.0) / 36525 T2 = pow(T,2) T3 = pow(T,3) D = 297.85 + (445267.1115*T) - (0.0016300*T2) + (T3/545868) D = ...
[ "def test_moon_phase(date_: datetime.date, phase: float):\n assert moon.phase(date_) == pytest.approx(phase, abs=0.001) # type: ignore", "def get_moon_phase(now):\n from math import pi\n\n ref = date_to_jd('1899-12-31', '12:00:00')\n T = (now - ref) / 36525\n nu = -9.26009 + 445267.12165*T + 0.001...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder 'shape' according to the chosen data layout to optimize data distribution.
def _optimizeshape(shape): shape.sort() if ORDER == 'C': shape[:] = shape[::-1]
[ "def sort_shape(self):\r\n DrawingProgram.merge_sort(self.__shape_list)", "def __change_shape(self):\r\n self.shape = self.next_shape", "def restore_backup_shape(self):\n\n self.shape = self.shape_backup", "def backup_shape(self):\n\n self.shape_backup = np.copy(self.shape)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if ghost layer length is not zero.
def has_ghosts(self): return not np.all(self.mesh.discretization.ghosts == 0)
[ "def empty(self):\n return len(self.layers) == 0", "def is_layered(self):\n count = 0\n for l in self.layers:\n if not l.is_empty():\n count += 1\n return count > 1", "def is_empty(self):\n return len(self.layers) == 1 and self.layer.is_empty()", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if target and current object are equal and have the same parent. Equal means same mesh, same shape and same domain.
def is_consistent_with(self, target): same_parent = self.parent() == target.parent() # Note FP. Is it really required to have the # same parent? Inclusion of all proc may be enough? return npw.equal(self.shape, target.shape).all() and same_parent
[ "def same_parent(self, parent):\n is_instance_of_step_parent = (\n inspect.isclass(parent)\n and isinstance(self._parent, parent)\n )\n return is_instance_of_step_parent or parent == self._parent", "def __eq__(self, other):\n parent_same = self.parent1.rid == othe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if current topo is complient with target.
def can_communicate_with(self, target): if self == target: return True msg = 'You try to connect topologies belonging to' msg += ' two different mpi tasks. Set taskids properly or use' msg += ' InterBridge.' assert self.task_id() == target.task_id(), msg # Pa...
[ "def is_dedicated_node(self):\n return self.is_node() and not self.is_master()", "def can_reach_support(self, target):\n if self.territory.is_complex:\n return target in self.named_coast.neighbours\n\n if self.territory.is_coastal and target.is_coastal:\n return target i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collect global indices of local meshes on each process of topo
def gather_global_indices(topo, toslice=True, root=None, comm=None): if comm is None: comm = topo.parent() size = comm.size start = topo.mesh.start() end = topo.mesh.stop() - 1 # communicator that owns the topology rank = comm.Get_rank() dimension = to...
[ "def index_and_return_global_ids(self):\n \n assert( len(self.largest_mappings) == 1 )\n\n mapped_ids = []\n for global_id, frame_one_id in enumerate(self.largest_mappings[0]):\n self.mesh_one.get_element_with_frame_id(frame_one_id).global_id = global_id\n self.mesh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This functions does the same thing as gather_global_indices but may also work when topo is None. The function is usefull if you need to collect global indices on a topo define only on a subset of comm, when for the procs not in this subset, topo will be equal to None. In such a case, comm and dom are required. This may...
def gather_global_indices_overlap(topo=None, comm=None, dom=None, toslice=True, root=None): if topo is None: assert comm is not None and dom is not None size = comm.Get_size() rank = comm.Get_rank() dimension = dom.dimension ...
[ "def gather_global_indices(topo, toslice=True, root=None, comm=None):\n if comm is None:\n comm = topo.parent()\n size = comm.size\n start = topo.mesh.start()\n end = topo.mesh.stop() - 1\n # communicator that owns the topology\n rank = comm.Get_rank()\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if all mpi processes of child belong to parent
def is_parent(child, parent): # Get the list of processes assert child is not None assert parent is not None #child_ranks = [i for i in xrange(child.Get_size())] child_group = child.Get_group() parent_group = parent.Get_group() inter_group = MPI.Group.Intersect(ch...
[ "def mpi_multi():\n comm, procs, rank = mpi_world()\n if procs > 1:\n return True\n else:\n return False", "def has_mpi_peer_processes():\n return mpi4py_available and MPI.COMM_WORLD.Get_size() > 1", "def contains_parent(self, pid):\n return pid in self._parent_ids", "def can_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Number of processess common to comm_1 and comm_2
def intersection_size(comm_1, comm_2): if comm_1 == MPI.COMM_NULL or comm_2 == MPI.COMM_NULL: return None group_1 = comm_1.Get_group() group_2 = comm_2.Get_group() inter_group = MPI.Group.Intersect(group_1, group_2) return inter_group.Get_size()
[ "def getNumberOfCommonLabels(variant1=[], variant2=[]):\n\n return len(commonLabels(variant1,variant2))", "def communities_with_protesters(partition, active_nodes):\n return len(set([partition[node] for node in active_nodes]))", "def _num_of_consolidated(self, observation):\n a = set(observation)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare two mpi communicators. Returns true if the two communicators are handles for the same group of proc and for the same communication context.
def compare_comm(comm_1, comm_2): assert comm_1 != MPI.COMM_NULL assert comm_2 != MPI.COMM_NULL result = MPI.Comm.Compare(comm_1, comm_2) res = [MPI.IDENT, MPI.CONGRUENT, MPI.SIMILAR, MPI.UNEQUAL] return result == res[0]
[ "def compare_groups(comm_1, comm_2):\n assert comm_1 != MPI.COMM_NULL\n assert comm_2 != MPI.COMM_NULL\n result = MPI.Comm.Compare(comm_1, comm_2)\n res = [MPI.IDENT, MPI.CONGRUENT, MPI.SIMILAR, MPI.UNEQUAL]\n return result in res[:-1]", "def mpi_multi():\n comm, procs, rank ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare the groups of two mpi communicators. Returns true if each comm handles the same group of mpi processes.
def compare_groups(comm_1, comm_2): assert comm_1 != MPI.COMM_NULL assert comm_2 != MPI.COMM_NULL result = MPI.Comm.Compare(comm_1, comm_2) res = [MPI.IDENT, MPI.CONGRUENT, MPI.SIMILAR, MPI.UNEQUAL] return result in res[:-1]
[ "def compare_comm(comm_1, comm_2):\n assert comm_1 != MPI.COMM_NULL\n assert comm_2 != MPI.COMM_NULL\n result = MPI.Comm.Compare(comm_1, comm_2)\n res = [MPI.IDENT, MPI.CONGRUENT, MPI.SIMILAR, MPI.UNEQUAL]\n return result == res[0]", "def mpi_multi():\n comm, procs, rank = mp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the values of ranks in target from ranks in source.
def convert_ranks(source, target): assert source != MPI.COMM_NULL and target != MPI.COMM_NULL g_source = source.Get_group() g_target = target.Get_group() size_source = g_source.Get_size() r_source = [i for i in xrange(size_source)] res = MPI.Group.Translate_ranks(g_source...
[ "def findRanks(toBeRanked, values):\n\treturn list(map(lambda e: findRank(e, values), toBeRanked))", "def find_vectors_mapping(source, target):\n return [np.argmax([abs(scalar_projection(s, t)) for t in target]) for s in source]", "def findClosestNodes(self, target: hash.hash.Hash):\n # TODO: make mor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute drift score as the percentage of overlapping probabilities
def compute_drift_score(ref_col_prob, col_prob): return sum(abs(np.asarray(ref_col_prob) - np.array(col_prob)) * 100)
[ "def score(self):\n s = 100*self.coverage-10*self.overlapRatio-0.01*self.traveledDist\n return s", "def drift_score(self):\n if self.measured_val is None:\n return 0.0\n\n if self.rebalance_type == self.REBALANCE_TYPE_ABSOLUTE:\n return (self.measured_val - self.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine training and inference datasets as one data frame
def combine_train_infer(train_file, infer_dir): train_df = pd.read_feather(train_file) time_range = range(len([f for f in os.listdir(infer_dir) if 'feather' in f])) infer_df_list = [pd.read_feather(f'{infer_dir}/{t}.feather') for t in time_range] comb_df_list = [] train_df.index = [-1] * len(trai...
[ "def load_train_and_dev() -> Tuple[pd.DataFrame, pd.DataFrame]:\n return load_split('train'), load_split('dev')", "def triples(self):\n return pd.concat((self._load_train(), self._load_valid(), self._load_test()))", "def _get_input_dataset(self):\n print(\"[INFO] Loading training data as tf.dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the shell script that handles BLAST database formatting.
def format_blast(makeblastdb_path, fname): # The script is written in shell, so this function just calls it and # checks the output # Build the shell command cmd = ['bash', DBFORMAT_SCRIPT, makeblastdb_path, fname] # Execute the script # shell=False to ensure that we aren't executing c...
[ "def dbshell(args=\"\"):\n with cd(env.app):\n run(\"%s | %s %s dbshell\" % (args, get_binary('python'), MANAGE))", "def make_blastDB(name, infile, db_type):\n cline = \"makeblastdb -in \"+ infile +\" -dbtype \"+ db_type +\" -title \"+ \\\n infile +\" -out \"+ name +\" -parse_seqids\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns tag of the first matched ListofValues. For each element in ``series`` returned is the tag of the listofvalues in the dictionary of LoVs ``taglov`` which first matches the element with one of its values OR value from donor with the same index OR ``na``.
def which_tag(series: pd.Series, taglov: Union[TagLoV, Any], na: Any, donor: pd.Series = None, method: Optional[Union[Callable, str]] = None, **kwargs): if series.empty: return series if not isinstance(taglov, TagLoV): taglov ...
[ "def tag_one(self, tokens, index, history):\n tag = None\n for tagger in self._taggers:\n tag = tagger.choose_tag(tokens, index, history)\n if tag is not None:\n break\n return tag", "def find_first_tag(self, tag):\n for lm, _ in self.search(tag=tag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
prepro 200x235x3 uint8 frame into 8300 (83x100) 1D float vector
def prepro(I): # """ prepro 200x235x3 uint8 frame into 10000 (100x100) 1D float vector """ I = I[35:200] # crop - remove 35px from start & 35px from end of image in x, to reduce redundant parts of image (i.e. after ball passes paddle) I = I[::2,::2,0] # downsample by factor of 2 I[I == 43] = 0 # erase...
[ "def preprocess(self, frame: np.ndarray) -> torch.TensorType:\n tensor = cv.resize(frame, (self.IMGSZ, self.IMGSZ)) \n tensor = tensor.transpose(2, 0, 1)\n tensor = torch.from_numpy(tensor)\n tensor = torch.unsqueeze(tensor, 0)\n tensor = tensor.half() if self.half else tensor.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test _arrange_test_result method with only one module.
def test_arrange_test_result_one_module(self): pass_1 = self._create_test_result(status=test_runner_base.PASSED_STATUS) pass_2 = self._create_test_result(status=test_runner_base.PASSED_STATUS) pass_3 = self._create_test_result(status=test_runner_base.PASSED_STATUS) fail_1 = self._create_...
[ "def test_arrange_test_result_multi_module(self):\n group_a_pass_1 = self._create_test_result(group_name='grpup_a',\n status=test_runner_base.PASSED_STATUS)\n group_b_pass_1 = self._create_test_result(group_name='grpup_b',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test _arrange_test_result method with multi module.
def test_arrange_test_result_multi_module(self): group_a_pass_1 = self._create_test_result(group_name='grpup_a', status=test_runner_base.PASSED_STATUS) group_b_pass_1 = self._create_test_result(group_name='grpup_b', ...
[ "def test_arrange_test_result_one_module(self):\n pass_1 = self._create_test_result(status=test_runner_base.PASSED_STATUS)\n pass_2 = self._create_test_result(status=test_runner_base.PASSED_STATUS)\n pass_3 = self._create_test_result(status=test_runner_base.PASSED_STATUS)\n fail_1 = self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test _arrange_test_result method with multi runner.
def test_arrange_test_result_multi_runner(self): runner_a_pass_1 = self._create_test_result(runner_name='runner_a', status=test_runner_base.PASSED_STATUS) runner_a_pass_2 = self._create_test_result(runner_name='runner_a', ...
[ "def test_arrange_test_result_multi_module(self):\n group_a_pass_1 = self._create_test_result(group_name='grpup_a',\n status=test_runner_base.PASSED_STATUS)\n group_b_pass_1 = self._create_test_result(group_name='grpup_b',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A Helper to create TestResult
def _create_test_result(self, **kwargs): test_info = test_runner_base.TestResult(**RESULT_TEST_TEMPLATE._asdict()) return test_info._replace(**kwargs)
[ "def _makeResult(self):\n return TestResultAdaptor(self.test_results, self.stream, self.descriptions, self.verbosity)", "def _makeResult(self):\r\n return _XMLTestResult(self.stream, self.descriptions, \\\r\n self.verbosity, self.elapsed_times)", "def test_make_result( self ):\n sent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a list of viable coordinates for mines, and randomly choose them.
def generate_mines(self, number): mine_locations = [] available_places = [[j, i] for i in xrange(0, self.x) for j in xrange(0, self.y)] while number > 0: # the chosen coordinate for a mine is appended into the list and is # removed from the lis...
[ "def random_coords(coord_list: typing.List[Coordinate]) -> Coordinate:\n return random.choice(coord_list)", "def generate_special_coords(self):\n special_coord = []\n for _ in range(2):\n coord = random.randint(1, 7)\n while coord == 3:\n coord = random.ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open neighbours if the flag number matches the count.
def special_open_neighbours(self, y, x): if self.table_state[y][x] != "-" and self.table_state[y][x] == self.flags_nearby(y, x): l = [[ye, xe] for xe in range( x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0] for ye, xe in l: if xe >= sel...
[ "def count_neighbor_flags(self, i, j):\n return np.count_nonzero(self.flags[(i-1 if i > 0 else 0):i+2, (j-1 if j > 0 else 0):j+2])", "def closedIsland1(self, grid: List[List[int]]) -> int:\n dic = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n m, n = len(grid), len(grid[0])\n count = 0\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open neighbours if the current coordinates are 0 and neighbours are untouched. Recursively opens if the neighbours are also 0.
def open_neighbours(self, y, x): if [y, x] in self.mine_locations: return [y, x] # generate neighbours with positive indexes l = [[ye, xe] for xe in range( x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0] for ye, xe in l: # if the ind...
[ "def special_open_neighbours(self, y, x):\n if self.table_state[y][x] != \"-\" and self.table_state[y][x] == self.flags_nearby(y, x):\n l = [[ye, xe] for xe in range(\n x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0]\n for ye, xe in l:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
come here when the coordinates do not have a bomb. update the table_state with the selected coordinate.
def tease_user(self, y, x): self.table_state[y][x] = self.final_table[y][x] # if there are no neighbouring 0s, open neighbours if self.table_state[y][x] == '0': self.open_neighbours(y, x) self.print_table(self.table_state)
[ "def _update_clicked_cell(self, event):\n if self._app.is_active() or not self._inside_range(event):\n return\n\n row, col = self._get_coord(event)\n if self.coords((row, col)): # coords method inherited from Canvas\n self.display_cell_as_dead(row, col)\n else:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method that check if file at provided url exist.
def file_exist(file_url): try: response = requests.head(file_url) if 200 <= response.status_code < 300: return True return False except ConnectionError: return False
[ "def remote_file_exists(url):\n status = requests.head(url).status_code\n\n if status == 200:\n return True\n else:\n raise RemoteFileDoesntExist", "def url_exists(url):\n request = requests.get(url)\n if request.status_code == 200:\n exist = True\n else:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method that based on file url return appropriate hash.
def get_hash(file_url): file_extension = os.path.splitext(file_url)[1] return str(HASHES.get(file_extension))
[ "def getHash(url):\n #return hashlib.sha256(url).hexdigest()\n\n # NOTE: debugging\n return url", "def read_hash_from_url(url_hash):\n user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\n headers = {'User-Agent':user_agent,}\n\n aux_req = re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Newton's second law of motion for measuring stoppnig distance Newton's second law of motion is d = (1/2)(v02/(mug)) so the stopping distance of an object in motion, like a car, can be measured. The friction coefficient measures how slick a road is with a default of 0.3.
def stopping_length_function(initial_velocity=120, friction_coefficient=0.3): g = 9.81 v0 = initial_velocity/3.6 mu = friction_coefficient return (1/2)*(v0**2/(mu*g))
[ "def friction(self):\n deceleration = 3\n if(self.speed > self.currentFrontSpeed * 1.5): deceleration = 25\n if(self.speed > self.currentFrontSpeed * 1.75): deceleration = 50\n if(self.speed > self.currentFrontSpeed * 2): deceleration = 100\n \n if self.speed > 0: self.spee...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Integration function Using scitools.StringFunction to do integration. >>> integration.py 'sin(x)' 0 pi/2
def integrate_function(): def midpoint_integration(f, a, b, n=100): h = (b - a)/float(n) I = 0 for i in range(n): I += f(a + i*h + 0.5*h) return h*I f_formula = sys.argv[1] a = eval(sys.argv[2]) b = eval(sys.argv[3]) if len (sys.argv) >= 5: n = i...
[ "def sin(x):", "def main():\n try:\n f_formula = sys.argv[1]\n a = eval(sys.argv[2])\n b = eval(sys.argv[3])\n n = int(sys.argv[4])\n except IndexError:\n print 'Usage: %s f-formula a b n' % sys.argv[0]\n sys.exit(1)\n\n from scitools.std import StringFunction\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
user enters an integer and the corresponding link is deleted
def delete_registry(self) -> None: self.view_registry() links = self.load_links()[0] try: url_to_delete = links[abs(int(input("Enter no. of URL to delete: ")))] except IndexError: print('Item not found - Nothing was deleted') return wi...
[ "def delete_link(self, link):", "def unlink(self, link_id):", "def remove_link():", "def delete_secret_link(link_id):\n\n Secret_Link.objects.filter(link_id=link_id).delete()", "def deleteLink(self):\n # get selected index\n index = self.getSelectedIndex(\"delete\")\n # check selecti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculating the psi operator for the transport and production of the enstrophy
def psi_enstrophy( Tau, # SGS; (6,64,64,64) h = False, # spatial step size flag = True): # spectral flag; default is gradient tool #---------------------------------------------------------------------# # Default variables ...
[ "def _phi2psi(self):\n try:\n locq = self.param_q(self.rhotor)\n except:\n self._readeqdsk(self.shot)\n locq = self.param_q(self.rhotor)\n \n locphi = self.rhotor**2\n psi = integrate.cumtrapz(1/locq,locphi)\n psi = np.concatenate([[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the coordinates of this atom. Returns
def get_coords(self): return self.coords
[ "def get_coords(self):\n return tuple(self.coords)", "def get_coords(self):\n assert all(atom.idx is not None for atom in self)\n atoms = self.atoms[:]\n atoms.sort(key=lambda a: a.idx)\n return np.array([atom.coords for atom in atoms])", "def getCoordinates(self):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the x coordinate of this atom. Returns
def get_x(self): return self.coords[0]
[ "def get_x(self):\n return self.__x_position", "def getXPosition(self):\n return self._x", "def get_pos_x(self):\n return self.__pos_x", "def x(self):\n return self.coords[0]", "def get_x(self) -> int:\n return self.__x", "def x(self):\n return _libsbml.Point_x(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the z coordinate of this atom. Returns
def get_z(self): return self.coords[2]
[ "def getZ(self):\n\t\treturn self.coords.z", "def z(self):\n return self.coords[2]", "def get_z(self):\n return self._z", "def get_z(self) -> int:\n return self.__z", "def getZ(self):\n return _libsbml.BoundingBox_getZ(self)", "def z(self):\n return self.position[2]", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the mass of this atom. Returns
def get_mass(self): return self.m
[ "def get_mass(self):\n\n return self.__mass", "def mass(self):\n return self._mass", "def get_mass(self):\n _pal.lib.geometry_get_mass.restype = c.c_float\n return _pal.lib.geometry_get_mass(self._geometry)", "def get_mass(self):\n return sum([cell.mass for cell in self.cell...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the van Der Waals radius of this atom. Returns
def get_van_Der_Waals_radius(self): return self.van_Der_Waals_radius
[ "def get_radius(self):\n return self.radius", "def outer_radius(self):\n return self._outer_radius", "def radius(self):\n return self._radius", "def get_radius(self):\n return self._handler.get_radius()", "def get_radius(self):\n if self.no_dist is False:\n dist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the euler tensor of this atom. Returns
def get_euler(self): return array([ coord * self.coords for coord in self.coords ])
[ "def euler_x(self):\n return self._euler_x", "def euler_z(self):\n return self._euler_z", "def euler_y(self):\n return self._euler_y", "def imu_get_euler(self):\n return self.imu.get_euler()", "def inertia_tensor(self):\n\n mu = self.moments_central\n a = mu[0, 2]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the symbol of this atom. Returns
def get_symbol(self): return self.symbol
[ "def symbol(self):\n return self._symbol", "def getSymbol(self):\n return self.data[1:-1]", "def symbol(self, name):\n return self.symbols[name]", "def get_atomic_symbol(self, atom):\n atomic_number = self.get_atomic_number(atom)\n return get_symbol(atomic_number)", "def s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the chain sequence number of the amminoacid this atom belongs to. Returns
def get_ammino_chain_seq(self): return self.ammino_chain_seq
[ "def get_sequence_num(self):\n return self._sequence_num", "def sequence_number(self):\n return self._sequence_number", "def sequence_num(self):\n return self._sequence_num", "def seq_no(self):\n return self._seq_no", "def get_tx_seq(self, ac):\n cur = self._get_cursor()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the euclid distance from this atom to the given atom. Returns
def get_euclid_distance_to(self, atom): return linalg.norm(self.get_coords() - atom.get_coords())
[ "def distance(cls, atom_1, atom_2):\n\t\t\n\t\treturn np.linalg.norm((atom_1-atom_2).atom_loc)", "def __get_distance(self, game_object):\n obj_x, obj_y = game_object.get_coordinates()\n self_x, self_y = self._coordinates\n\n inner = (obj_x-self_x)**2 + (obj_y-self_y)**2\n return math.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a PLaSM cuboid with a color an put it on this atom coords.
def plasm_cube(self, size=0.1, color=WHITE): return COLOR(color)(T([1,2,3])(self.coords)(CUBOID([size, size, size])))
[ "def make_cube(self, color=Cube.Colors.RED):\n cube = Cube(self.__canvas, (100, 100), color)\n self.__cubes.append(cube)\n\n return cube", "def space_to_draw_cube(city, color) :\n (x,y) = CityLocs[city]\n ColorOffsets = {'red':(0,0),'blue': (15,0),'black':(0,15),'yellow':(15,15)}\n return (x + C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the GsmModem in PDU mode accepts outgoing SMS, when the text is within ASCII chars 22 126.
def testSendSmsPduMode(self): # setup expectation to raise a timeout error with prompt err = errors.GsmReadTimeoutError(">") when(self.mockDevice).read_lines().thenRaise(err).thenReturn(self.oklines) self.gsm.send_sms("1234", "Test Message") # must see command wi...
[ "def _check_voice_message(self, text):\n\t\tif self._gsm0338_length(text) > 160:\n\t\t\traise SMSTradeError(u'too many GSM characters in message')", "def is_gsm_text(text):\n try:\n tx = text.encode(\"gsm0338\")\n print(tx, type(tx), len(tx))\n except UnicodeError:\n return False\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the GsmModem in PDU mode does not send message if error, when the text is within ASCII chars 22 126.
def testSendSmsPduModeError(self): # setup expectation to raise a non-timeout error with prompt when(self.mockDevice).read_lines().thenRaise(Exception("something other than timeout")) self.gsm.send_sms("1234", "Test Message") # must see command with size verify(self.mock...
[ "def _check_voice_message(self, text):\n\t\tif self._gsm0338_length(text) > 160:\n\t\t\traise SMSTradeError(u'too many GSM characters in message')", "def _check_unicode_message(text):\n\t\tfor char in text:\n\t\t\tcode = ord(char)\n\t\t\tif (0xd800 <= code <= 0xdfff) or (code > 0xffff):\n\t\t\t\traise SMSTradeErr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the content type is valid.
def is_valid_content_type(cls, content_type: str) -> bool: return content_type in cls.CONTENT_TYPES.value
[ "def _is_valid_ct(content_type: str) -> bool:\n content_type = content_type.strip()\n return _is_valid_regex(CT_CONTENT_TYPE_REGEX_PATTERN, content_type)", "def _is_valid_content_type_format(content_type: str) -> bool:\n return (\n _is_valid_ct(content_type)\n or _is_valid_pt(content_type)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for facebook sdk
def init_fb(self, **kwargs): try: self.graph = facebook.GraphAPI(access_token=fb_token, version='2.4') except Exception as e: sys.exit(str(e))
[ "def __init__(self):\n try:\n access_token = facebook.is_connected(request.cookies)[\"access_token\"]\n except:\n raise Exception(\"Not authed.\")\n self.graph = facebook.GraphAPI(access_token)\n self.user = self.graph.get_object(\"me\")", "def initialize_facebook...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save event to database
def save_event(self, data): rdb.table(self.rdb_table).insert(data)
[ "def __save_event(cls, e: Event) -> None:\n statement = 'INSERT OR REPLACE INTO events VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'\n values = e.to_db_tuple()\n\n cls.__get_cursor().execute(statement, values)\n # cls.__connection.commit()", "def save(self, event):\n self.sa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate through all events pages
def get_events(self): url = '/v2.4/'+self.page_id+'/events' data = self.graph.request(url) while 'next' in data['paging'].keys(): print data['paging']['next'] data = self.graph.request(url, args={ 'limit' : 100, 'after' : ...
[ "def _events(self):\n try:\n latest_event = Event.objects.latest('start_time')\n last_update = latest_event.start_time\n except Event.DoesNotExist:\n last_update = timezone.make_aware(datetime.min,\n timezone.get_default_tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup the Binary Sensor platform fo EnOcean.
def setup_platform(hass, config, add_devices, discovery_info=None): dev_id = config.get(CONF_ID, None) devname = config.get(CONF_NAME, "EnOcean binary sensor") add_devices([EnOceanBinarySensor(dev_id, devname)])
[ "def setUp(self):\n self.platform = wirelesstagpy.WirelessTags(username=USERNAME, password=PASSWORD)\n self.tag_outdoor = wirelesstagpy.SensorTag(MOCK.OUTDOOR_PROBE, self.platform)\n self.platform._tags[\"fake-1\"] = self.tag_outdoor # pylint: disable=protected-access", "def setUp(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load an ARFF File from a file.
def load(filename): o = open(filename) s = o.read() a = ArffFile.parse(s) o.close() return a
[ "def LoadFromFile(self, filename):\n f = open(filename, 'r')\n contents = f.read()\n self.LoadFromData(contents)\n f.close()", "def load(self, arffile=None):\n inputstream = _get_file_object(arffile)\n if inputstream is None:\n inputstream = self.inputstream\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a new attribute. atype has to be one of 'numeric', 'string', and 'nominal'. For nominal attributes, pass the possible values as data.
def define_attribute(self, name, atype, data=None): self.attributes.append(name) self.attribute_types[name] = atype self.attribute_data[name] = data
[ "def addAttr(*args, attributeType: Union[AnyStr, bool]=\"\", binaryTag: Union[AnyStr, bool]=\"\",\n cachedInternally: bool=True, category: Union[AnyStr, List[AnyStr], bool]=\"\",\n dataType: Union[AnyStr, List[AnyStr], bool]=\"\", defaultValue: Union[float,\n bool]=0.0, disconnectBe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the overall ignorance
def update_overall_ignorance(overall_ignorance, object_ignorance, rate=0.05): return (1-rate)*overall_ignorance + rate*object_ignorance
[ "def update_potential(self):\n pass", "def dummy_update( self ):\r\n pass", "def updateAll(self):\n self.elevatorInterfaceVis.updateElevators(self.elevatorInterface)\n stats = self.elevatorInterface.bridge.getStats()\n self.infoPanel.updateStats(stats)", "def update_inhibiti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return focus image at target positon
def check_target_position(environment, target_xy, fovea): temp_fovea = Fovea(target_xy, fovea.size, [0, 0, 0], fovea.unit) temp_image = temp_fovea.get_focus_image(environment) return temp_image
[ "def click_img(self, target_img):\n pos = imagesearch_loop(target_img, timesample=0.5)\n if pos[0] == -1:\n print(\"No image found\")\n else:\n self.click(pos)", "def extract_target_pixel_location(self):\n #Respective Image location\n pixel_array = self.ima...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if target area is free
def check_free_space(environment, target_xy, fovea): temp_image = check_target_position(environment, target_xy, fovea) if np.array_equal(temp_image, np.zeros(temp_image.shape)): return True else: return False
[ "def is_free(self) -> bool:\n return self.places < self.total", "def is_free(self,x,y):\n self.insist_valid(x,y) \n return self.grid[y][x] == \" \"", "def is_free(self):\n return self.name == 'free' # (No coverage)", "def _isFree(self, pos:ndarray):\n map = self._sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate loss and gradient for the threelayer convolutional network.
def loss(self, X, y=None): W1, b1 = self.params['W1'], self.params['b1'] W2, b2 = self.params['W2'], self.params['b2'] W3, b3 = self.params['W3'], self.params['b3'] # pass conv_param to the forward pass for the convolutional layer filter_size = W1.shape[2] conv_param = {'stride': 1, 'pad': ...
[ "def loss_func_c3():\n ub = global_model(Zb_elem_tensor) # ub constains element boundary value tensor, shape: (n_elem, 2, 1)\n dub_dx = K.gradients(ub, Zb_elem_tensor) # dub_dx contains du/dx tensor on boundary, shape: (n_elem,2,1)\n dub_dx_2 = K.gradients(dub_dx, Zb_elem_tensor) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inplace applies a one mode gate G into the process matrix T in mode i
def _apply_one_mode_gate(G, T, i): T[i] *= G return T
[ "def _apply_two_mode_gate(G, T, i, j):\n (T[i], T[j]) = (G[0, 0] * T[i] + G[0, 1] * T[j], G[1, 0] * T[i] + G[1, 1] * T[j])\n return T", "def _apply_gate(self, mat, modes):\n\n args = [mat, self._state, self._pure, modes, self._num_modes, self._trunc]\n if self._mode == 'blas':\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inplace applies a two mode gate G into the process matrix T in modes i and j
def _apply_two_mode_gate(G, T, i, j): (T[i], T[j]) = (G[0, 0] * T[i] + G[0, 1] * T[j], G[1, 0] * T[i] + G[1, 1] * T[j]) return T
[ "def _apply_one_mode_gate(G, T, i):\n\n T[i] *= G\n return T", "def _apply_gate(self, mat, modes):\n\n args = [mat, self._state, self._pure, modes, self._num_modes, self._trunc]\n if self._mode == 'blas':\n self._state = ops.apply_gate_BLAS(*args)\n elif self._mode == 'einsum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of the columns that are in our features dataframe that should not be used in prediction. These are essentially either metadata columns (team name, for example), or potential target variables that include the outcome. We want to make sure not to use the latter, since we don't want to use information about...
def get_non_feature_columns(): return ['teamid', 'op_teamid', 'matchid', 'competitionid', 'seasonid', 'goals', 'op_goals', 'points', 'timestamp', 'team_name', 'op_team_name']
[ "def only_feature_columns(self) -> list:\n return self._tf_feature_cols", "def no_export_feature_columns(self) -> list:\n return self._tf_no_export_cols", "def get_features(self, df):\n return df.drop(df.columns[self.target_col], axis=1)", "def missing_columns(self):\r\n _missing_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of all columns that should be used in prediction (i.e. all features that are in the dataframe but are not in the features.get_non_feature_column() list).
def get_feature_columns(all_cols): return [col for col in all_cols if col not in get_non_feature_columns()]
[ "def only_feature_columns(self) -> list:\n return self._tf_feature_cols", "def get_cols(df):\n meta = get_metafeatures(df)\n categorical_columns = meta.loc[meta['type'] == 'object', 'column'].tolist()\n cols_to_drop = meta.loc[meta['missing'] > 0.5, 'column'].tolist()\n logging.debug('%s catego...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup cache object for wallet
def setup_cache(self): if self.walletname not in cache: cache[self.walletname] = { "raw_transactions": {}, "transactions": [], "tx_count": None, "tx_changed": True, "last_block": None, "raw_tx_block_upda...
[ "def __init_cache__(self) -> None:\n try:\n self.cache = caches[CACHE_NAME]\n logging.info(\"GeoIP2 - successfully initialised cache\")\n except InvalidCacheBackendError as ex:\n raise MiddlewareNotUsed(f\"GeoIP2 - cache configuration error: {ex}\") from ex", "def se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cache `raw_transactions` (with full data on all the inputs and outputs of each tx)
def cache_raw_txs(self, cli_txs): # Get list of all tx ids txids = list(dict.fromkeys(cli_txs.keys())) tx_count = len(txids) # If there are new transactions (if the transations count changed) if tx_count != self.cache["tx_count"]: for txid in txids: ...
[ "def cache_txs(self, raw_txs):\n # Get the cached `raw_transactions` dict (txid -> tx) as a list of txs\n transactions = list(sorted(raw_txs.values(), key = lambda tx: tx['time'], reverse=True))\n result = []\n\n # If unconfirmed transactions were mined, assign them their block height\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Caches the transactions list. Cache the inputs and outputs which belong to the user's wallet for each `raw_transaction`
def cache_txs(self, raw_txs): # Get the cached `raw_transactions` dict (txid -> tx) as a list of txs transactions = list(sorted(raw_txs.values(), key = lambda tx: tx['time'], reverse=True)) result = [] # If unconfirmed transactions were mined, assign them their block height if l...
[ "def cache_raw_txs(self, cli_txs): \n # Get list of all tx ids\n txids = list(dict.fromkeys(cli_txs.keys()))\n tx_count = len(txids)\n\n # If there are new transactions (if the transations count changed)\n if tx_count != self.cache[\"tx_count\"]:\n for txid in tx...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method hides fields that were added in newer API versions. Certain node fields were introduced at certain API versions. These fields are only made available when the request's API version matches or exceeds the versions when these fields were introduced.
def hide_fields_in_newer_versions(obj): if not api_utils.allow_start_end_audit_time(): obj.start_time = wtypes.Unset obj.end_time = wtypes.Unset if not api_utils.allow_force(): obj.force = wtypes.Unset
[ "def hide_fields_in_newer_versions(obj):\n pass", "def remove_read_only_fields(self):\n self.fields = XML_List(Elements.FIELDS, [field for field in self.fields if\n not field.read_only or not str_to_bool(field.read_only)])", "def remove_access_request_fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve information about the given audit.
def get_one(self, audit): if self.from_audits: raise exception.OperationNotPermitted context = pecan.request.context rpc_audit = api_utils.get_resource('Audit', audit) policy.enforce(context, 'audit:get', rpc_audit, action='audit:get') return Audit.convert_with_link...
[ "def get(self, audit_uuid):\n audit = AuditResource.get_by_id(audit_uuid=audit_uuid, withContacts=True, withScans=True)\n return audit", "def get_audit(self, session, query, auth_context):\n entity_name = query.get('entity')\n if not entity_name:\n raise exceptions.NotFound(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check request is authenticated. If API_AUTH_SECRET_HEADER_NAME is not in request headers then return 401. If API_AUTH_SECRET_HEADER_NAME is in request headers but incorrect then return 403. Else return none.
def is_authenticated_request(req: Request) -> Optional[Response]: if API_AUTH_SECRET_HEADER_NAME not in req.headers: return make_error_response(HTTP_STATUS_CODE.UNAUTHORIZED) if req.headers[API_AUTH_SECRET_HEADER_NAME] != API_AUTH_SECRET: return make_error_response(HTTP_STATUS_CODE.FORBIDDEN) ...
[ "def check_auth_header_secret():\n return True\n # bearer_header = request.headers.get('Authorization')\n # return 'bearer ' + app.config.get('SECRET_KEY') == bearer_header", "def test_authorization_header_not_present(self, _get_key_secret):\n request = Request(self.environ)\n request.body ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the the number of minutes represented by min to the currentDate input and returns that new date timestamp
def addMinutes(self, currentDate:str, dateFormat:str, mins:int) -> str: inputDateTime = datetime.strptime(currentDate, dateFormat) nextTime = inputDateTime + timedelta(minutes=mins) return nextTime.strftime(dateFormat)
[ "def now_plus_minutes(num_minutes):\n now_seconds = time.time()\n now_date = datetime.datetime.fromtimestamp(now_seconds)\n now_plus = now_date + datetime.timedelta(minutes=num_minutes)\n return now_plus.isoformat(' ')", "def dt_min_ago(obj):\n return round(dt_sec_ago(obj=obj) / 60)", "def get_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints out ">>" to make the prompt look nice.
def prompt(): sys.stdout.write('>> ') sys.stdout.flush()
[ "def user_prompt():\n sys.stdout.write('\\nYou > ')\n sys.stdout.flush()", "def showPrompt(self):\r\n self.terminal.nextLine()\r\n self.terminal.write(self.ps[self.pn])", "def do_prompt(self, line):\n self.prompt = line + ': '", "def prompt(self, question):\n self.output(' ')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes video file path and a transcode profile, transcode the file, and returns the transcoded file in bytes, along with ffmpeg's stderr output.
def transcode_segment(self, in_path: str, profile: TranscodeProfile ) -> Tuple[bytes, str, str]: out_filepath = f"/tmp/{uuid4()}.ts" transcode_command = [ "ffmpeg", "-i", in_path, "-vf", f"s...
[ "def reencode(filepath, loglevel='panic'):\n try:\n import ffmpeg\n except ImportError:\n logger.error(\n 'Import Error! Cant import ffmpeg. '\n 'Annotations operations will be limited. import manually and fix errors')\n raise\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get duration from an ffmpeg stderr dump.
def parse_duration_from_stderr(self, stderr: str) -> float: pattern = "Duration: (\\d\\d):(\\d\\d):(\\d\\d\\.\\d\\d)" pattern = re.compile(pattern) result = pattern.search(stderr) if result is None: return None # Parse result hours = float(result.grou...
[ "def get_movie_length(file):\n\n len = 0\n p = subprocess.Popen(\"ffmpeg -i '\" + file + \"'\", shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n for line in p.stderr:\n if \"Duration:\" in line:\n h,m,s = (float(x) for x in re.findall(\"Duration: (\\d+...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save this entry in the SugarCRM server. If the 'id' field is blank, it creates a new entry and sets the 'id' value.
def save(self): # If 'id' wasn't blank, it's added to the list of dirty fields; this # way the entry will be updated in the SugarCRM connection. if self['id'] != '': self._dirty_fields.append('id') # nvl is the name_value_list, which has the list of attributes. ...
[ "def save(self):\n if self.id is None:\n self._insert()\n else:\n self._update()", "def save(self):\n if not self.id:\n self.id = uuid4()\n DataStore.add_instance(self)", "def save(self):\n session = _get_session()\n session.add(self)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the related entries in another module.
def get_related(self, module): connection = self._module._connection result = connection.get_relationships(self._module._name, self['id'], module._name.lower(), '', ['id']) entries = [] for elem in result['entry_list']: entry = Su...
[ "def get_modules_and_revisions(self, ctx):", "def related_items(self):\r\n return self._related_items", "def get_related(page):\n related = []\n entry = Entry.get_for_model(page)\n\n if entry:\n related = entry.related\n\n return related", "def relationships(self):", "def related...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Partition list ``l`` in ``K`` partitions. Examples >>> l = [0, 1, 2] >>> list(clusters(l, K=3)) [[[0], [1], [2]], [[], [0, 1], [2]], [[], [1], [0, 2]], [[0], [], [1, 2]], [[], [0], [1, 2]], [[], [], [0, 1, 2]]] >>> list(clusters(l, K=2)) [[[0, 1], [2]], [[1], [0, 2]], [[0], [1, 2]], [[], [0, 1, 2]]] >>> list(clusters(l...
def clusters(l, K): # noqa if l: prev = None for t in clusters(l[1:], K): tup = sorted(t) if tup != prev: prev = tup for i in range(K): yield tup[:i] + [ [l[0]] + tup[i], ] + tup[...
[ "def partition_to_k(layerlist, k, order=False):\n for each_partition_candidate in partition(layerlist):\n if len(each_partition_candidate) == k:\n if not order:\n yield each_partition_candidate\n else:\n for enum_item in permutations(each_partition_candi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Partition list ``l`` in ``K`` partitions, without empty parts. >>> l = [0, 1, 2] >>> list(neclusters(l, 2)) [[[0, 1], [2]], [[1], [0, 2]], [[0], [1, 2]]] >>> list(neclusters(l, 1)) [[[0, 1, 2]]]
def neclusters(l, K): # noqa for c in clusters(l, K): if all(x for x in c): yield c
[ "def clusters(l, K): # noqa\n if l:\n prev = None\n for t in clusters(l[1:], K):\n tup = sorted(t)\n if tup != prev:\n prev = tup\n for i in range(K):\n yield tup[:i] + [\n [l[0]] + tup[i],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all segmentations of a list ``l``.
def all_segmentations(l): for K in range(1, len(l) + 1): gen = neclusters(l, K) yield from gen
[ "def Chunks(l):\n return_list = [[]]\n counter = 0\n index = 0\n for i in l:\n # Size is split in half due to the max size being a sum of src and dst.\n if counter > (self._ADDRESS_LENGTH_LIMIT/2):\n counter = 0\n index += 1\n return_list.append([])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if ``s1`` and ``s2`` are in the same symbol, given the ``segmentation``.
def q(segmentation, s1, s2): index1 = find_index(segmentation, s1) index2 = find_index(segmentation, s2) return index1 == index2
[ "def __eq__(self, other: Segment) -> bool:\n return any(\n (\n self.start == other.start and self.end == other.end,\n self.start == other.end and self.end == other.start,\n )\n )", "def sequence_in(s1, s2):\n return bool(re.search(\".*\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }