code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def wiggles(data, wiggleInterval=10, overlap=1, posFill='black', negFill=None, lineColor='black', rescale=True, extent=None, ax=None): <NEW_LINE> <INDENT> if rescale: <NEW_LINE> <INDENT> data = data.astype(np.float) <NEW_LINE> data -= data.min() <NEW_LINE> data /= data.ptp() <NEW_LINE> data *= 2 <NEW_LINE> data -= 1 <NEW_LINE> <DEDENT> if extent is None: <NEW_LINE> <INDENT> xmin, ymin = 0, data.shape[0] <NEW_LINE> ymax, xmax = 0, data.shape[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xmin, xmax, ymin, ymax = extent <NEW_LINE> <DEDENT> if ax is None: <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> <DEDENT> ax.invert_yaxis() <NEW_LINE> ax.set(xlim=[xmin, xmax], ylim=[ymin, ymax]) <NEW_LINE> ny, nx = data.shape <NEW_LINE> x_loc = np.linspace(xmin, xmax, nx) <NEW_LINE> for i in range(wiggleInterval//2, nx, wiggleInterval): <NEW_LINE> <INDENT> x = overlap * (wiggleInterval / 2.0) * (x_loc[1] - x_loc[0]) * data[:, i] <NEW_LINE> wiggle(x + x_loc[i], origin=x_loc[i], posFill=posFill, negFill=negFill, lineColor=lineColor, zmin=ymin, zmax=ymax, ax=ax)
2-D Wiggle Trace Variable Amplitude Plot Parameters ---------- x: input data (2D numpy array) wiggleInterval: (default, 10) Plot 'wiggles' every wiggleInterval traces overlap: (default, 0.7) amount to overlap 'wiggles' by (1.0 = scaled to wiggleInterval) posFill: (default, black) color to fill positive wiggles with (string or None) negFill: (default, None) color to fill negative wiggles with (string or None) lineColor: (default, black) color of wiggle trace (string or None) resampleRatio: (default, 10) factor to resample traces by before plotting (1 = raw data) (float) extent: (default, (0, nx, 0, ny)) The extent to use for the plot. A 4-tuple of (xmin, xmax, ymin, ymax) ax: (default, current axis) The matplotlib axis to plot onto. Output: a matplotlib plot on the current axes
625941bed53ae8145f87a193
def run(self): <NEW_LINE> <INDENT> self.load_pcap()
Run the frame producer.
625941be1f5feb6acb0c4a73
def getAddress(self): <NEW_LINE> <INDENT> a = self.server.socket.getsockname() <NEW_LINE> return a
get the addess info the server is listening at (only after setup)
625941be30dc7b7665901888
def drop_obs(self, in_ = None, if_ = None, all_obs = False): <NEW_LINE> <INDENT> if self._nobs == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if all_obs and (in_ is not None or if_ is not None): <NEW_LINE> <INDENT> raise ValueError("all_obs cannot be combined with in_ or if_") <NEW_LINE> <DEDENT> if not all_obs and in_ is None and if_ is None: <NEW_LINE> <INDENT> raise ValueError("must specify one of in_, if_, or all_obs") <NEW_LINE> <DEDENT> if all_obs: <NEW_LINE> <INDENT> self._varvals = [] <NEW_LINE> self._nobs = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> varvals = self._varvals <NEW_LINE> if if_ is None: <NEW_LINE> <INDENT> to_drop = [i for i in in_] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if in_ is None: in_ = range(self._nobs) <NEW_LINE> to_drop = [i for i in in_ if if_(i)] <NEW_LINE> <DEDENT> to_drop.reverse() <NEW_LINE> for i in to_drop: <NEW_LINE> <INDENT> del varvals[i] <NEW_LINE> <DEDENT> self._nobs = len(self._varvals) <NEW_LINE> <DEDENT> self._changed = True
Drop observations from the data set. Parameters ---------- in_ : iterable, optional Used to specify observations to drop. Should be an iterable of int. Default is all observations. if_ : function, optional Used to specify observations to drop. Should be a function taking int and returning Boolean (or coercible to Boolean). Default is True for all obs. all_obs : bool or coercible to Boolean, optional Option to drop all observations. Default value is False. Parameters note --------------- If both `in_` and `if_` are used, the dropped observations are the numbers in `in_` that satisfy `if_`. Returns ------- None Side effects ------------ Deletes specified observations.
625941be6fb2d068a760efba
def schema_type(schema): <NEW_LINE> <INDENT> if type(schema) in (list, tuple, set, frozenset): <NEW_LINE> <INDENT> return ITERABLE <NEW_LINE> <DEDENT> if type(schema) is dict: <NEW_LINE> <INDENT> return DICT <NEW_LINE> <DEDENT> if issubclass(type(schema), type): <NEW_LINE> <INDENT> return TYPE <NEW_LINE> <DEDENT> if hasattr(schema, 'validate'): <NEW_LINE> <INDENT> return VALIDATOR <NEW_LINE> <DEDENT> if callable(schema): <NEW_LINE> <INDENT> return CALLABLE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return COMPARABLE
Return priority for a given object.
625941bed4950a0f3b08c270
def _execute_workload(self) -> tuple: <NEW_LINE> <INDENT> log('Executing workload %s' % self.workload) <NEW_LINE> metrics = Metrics(self.workload) <NEW_LINE> start_time = '' <NEW_LINE> stop_time = '' <NEW_LINE> for i in range(self.repetition): <NEW_LINE> <INDENT> device_short = Mem.re_device.findall(self.device)[0] <NEW_LINE> retry = 0 <NEW_LINE> while retry < Mem.retry: <NEW_LINE> <INDENT> retry += 1 <NEW_LINE> clear_caches(self.device) <NEW_LINE> blktrace = Mem.format_blktrace % (self.device, device_short, self.runtime) <NEW_LINE> adj_command = adjusted_workload(self.command, self.workload) <NEW_LINE> start_time = strftime('%m/%d/%y %I:%M:%S %p', localtime()) <NEW_LINE> out = run_parallel_commands([('blktrace', self.delay, blktrace), (self.workload, 0, adj_command)]) <NEW_LINE> stop_time = strftime('%m/%d/%y %I:%M:%S %p', localtime()) <NEW_LINE> if out is None or 'blktrace' in out and out['blktrace'] is None: <NEW_LINE> <INDENT> log('Error running workload %s' % self.workload) <NEW_LINE> time.sleep(5) <NEW_LINE> continue <NEW_LINE> <DEDENT> blktrace_out, _ = out['blktrace'] <NEW_LINE> workload_out, _ = out[self.workload] <NEW_LINE> log('Workload Output') <NEW_LINE> log(workload_out) <NEW_LINE> if blktrace_out is None or workload_out is None: <NEW_LINE> <INDENT> log('Error running workload %s' % self.workload) <NEW_LINE> time.sleep(5) <NEW_LINE> continue <NEW_LINE> <DEDENT> blkparse = Mem.format_blkparse % (device_short, device_short) <NEW_LINE> _, _ = run_command(blkparse, ignore_output=True) <NEW_LINE> blkrawverify = Mem.format_blkrawverify % device_short <NEW_LINE> blkrawverify_out, _ = run_command(blkrawverify) <NEW_LINE> log('BLKRAWYVERIFY Output') <NEW_LINE> log(blkrawverify_out) <NEW_LINE> btt = Mem.format_btt % device_short <NEW_LINE> btt_out, _ = run_command(btt) <NEW_LINE> if btt_out is None: <NEW_LINE> <INDENT> log('Error running workload %s' % self.workload) <NEW_LINE> time.sleep(5) <NEW_LINE> continue <NEW_LINE> <DEDENT> log('BTT Output') <NEW_LINE> btt_split = btt_out.split("# Total System")[0] <NEW_LINE> btt_split2 = btt_split.split("==================== All Devices ====================")[-1] <NEW_LINE> log("==================== All Devices ====================") <NEW_LINE> log(btt_split2) <NEW_LINE> if Mem.cleanup: <NEW_LINE> <INDENT> log('Cleaning up files') <NEW_LINE> cleanup_files('sda.blktrace.*', 'sda.blkparse.*', 'sys_iops_fp.dat', 'sys_mbps_fp.dat') <NEW_LINE> dmm = get_device_major_minor(self.device) <NEW_LINE> cleanup_files('%s_iops_fp.dat' % dmm, '%s_mbps_fp.dat' % dmm) <NEW_LINE> cleanup_files('%s.verify.out' % device_short) <NEW_LINE> <DEDENT> m = Metrics.gather_metrics(None, btt_out, workload_out, self.workload) <NEW_LINE> metrics.add_metrics(m) <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print_detailed('Unable to run workload %s' % self.workload) <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> return start_time, stop_time, metrics.average_metrics()
Executes a workload. :return: Returns a dictionary of metrics if successful, else None.
625941be60cbc95b062c6462
def handle(self, *app_labels, **options): <NEW_LINE> <INDENT> from lcperformance.Process.LcPerformance import LcPerformance <NEW_LINE> objLcPerformace = LcPerformance() <NEW_LINE> objLcPerformace.SaveLcsInicial() <NEW_LINE> raise CommandError('Only the default is supported')
app_labels - app labels (eg. myapp in "manage.py reset myapp") options - configurable command line options
625941be57b8e32f524833b9
def update(self, likelihood, data): <NEW_LINE> <INDENT> for hypo in self.qs: <NEW_LINE> <INDENT> self[hypo] *= likelihood(data, hypo) <NEW_LINE> <DEDENT> return self.normalize()
Bayesian update. likelihood: function that takes (data, hypo) and returns likelihood of data under hypo data: whatever format like_func understands returns: normalizing constant
625941be30dc7b7665901889
def __init__(self): <NEW_LINE> <INDENT> self.ClusterId = None <NEW_LINE> self.SelectedTables = None <NEW_LINE> self.Remark = None
:param ClusterId: 待创建备份表所属集群ID :type ClusterId: str :param SelectedTables: 待创建备份表信息列表 :type SelectedTables: list of SelectedTableInfoNew :param Remark: 备注信息 :type Remark: str
625941be63b5f9789fde7005
def get_downstream_exon(self) -> Any: <NEW_LINE> <INDENT> if self.transcript_model.chromstrand[-1] == "+": <NEW_LINE> <INDENT> ix = self.exin_no * 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ix = len(self.transcript_model.list_features) - 2 * self.exin_no + 1 <NEW_LINE> <DEDENT> return self.transcript_model.list_features[ix]
To use only for introns. Returns the vcy.Feature corresponding to the neighbour exon downstream Note ---- In a 15 exons transcript model: Downstream to intron10 is exon11 or the interval with index `20` if strand "+". Downtream to intron10 is exon10 or the interval with index `10` if strand "-"
625941beab23a570cc2500a0
def create_email(text_data, recipient, sender): <NEW_LINE> <INDENT> if not text_data: <NEW_LINE> <INDENT> base_msg = ("Sorry, there weren't any results for your flight" + " searches today.\nIf you're in a hurry, you might try increasing" + " or removing the maximum price or maximum flight length in your" + " search.\n") <NEW_LINE> subject = "No flights found today." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base_msg = ("Hey there! Here are your daily flight search results.\n\n") <NEW_LINE> subject = 'Your daily flight search results' <NEW_LINE> <DEDENT> msg = MIMEText(base_msg + text_data) <NEW_LINE> msg['Subject'] = subject <NEW_LINE> msg['From'] = sender <NEW_LINE> msg['To'] = recipient <NEW_LINE> return msg
Generate an email containing the given text. Args: text_data: string, the message to write in the email. recipient: string, the email address to which the message will be sent. Must be a valid email address. sender: string, the email address from which to send the email. Returns: A MIMEText email object with the given data.
625941bef8510a7c17cf961b
def getgeombyindx(fhgeo,xs,xe,ys,ye): <NEW_LINE> <INDENT> D = fhgeo.variables['D'][ys:ye,xs:xe] <NEW_LINE> ah = fhgeo.variables['Ah'][ys:ye,xs:xe] <NEW_LINE> aq = fhgeo.variables['Aq'][ys:ye,xs:xe] <NEW_LINE> dxcu = fhgeo.variables['dxCu'][ys:ye,xs:xe] <NEW_LINE> dycu = fhgeo.variables['dyCu'][ys:ye,xs:xe] <NEW_LINE> dxcv = fhgeo.variables['dxCv'][ys:ye,xs:xe] <NEW_LINE> dycv = fhgeo.variables['dyCv'][ys:ye,xs:xe] <NEW_LINE> dxbu = fhgeo.variables['dxBu'][ys:ye,xs:xe] <NEW_LINE> dybu = fhgeo.variables['dyBu'][ys:ye,xs:xe] <NEW_LINE> dxt = fhgeo.variables['dxT'][ys:ye,xs:xe] <NEW_LINE> dyt = fhgeo.variables['dyT'][ys:ye,xs:xe] <NEW_LINE> f = fhgeo.variables['f'][ys:ye,xs:xe] <NEW_LINE> return D, (ah,aq), (dxcu,dycu,dxcv,dycv,dxbu,dybu,dxt,dyt), f
Usage: | D, (ah,aq), (dxcu,dycu,dxcv,dycv,dxbu,dybu,dxt,dyt), f = getgeom(filename) | This fuction returns the depth of the domain D, | cell areas at T and Bu points ah and aq, resp, | grid spacing at Cu, Cv, Bu and T points, | and f at Bu points.
625941be9b70327d1c4e0cf3
def __init__(self, name: str, ref: str) -> None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.ref = ref
Initialize the C++ field of a composite with the given values. :param name: name of the composite field :param ref: reference path in the mapry schema of this field
625941be460517430c3940ab
def SetElement(self, *args): <NEW_LINE> <INDENT> return _itkFixedArrayPython.itkFixedArrayUL3_SetElement(self, *args)
SetElement(self, unsigned short index, unsigned long value)
625941be76e4537e8c351590
def evaluate(ref_table, s): <NEW_LINE> <INDENT> ref = ref_table.get(s.id_) <NEW_LINE> if ref is None: <NEW_LINE> <INDENT> raise Exception('No reference loaded for ID: {}'.format(s.id_)) <NEW_LINE> <DEDENT> distance, matches = edit_distance(ref.words, s.words) <NEW_LINE> eval_ = Evaluation(len(ref.words), matches, distance) <NEW_LINE> s.eval_ = eval_ <NEW_LINE> return eval_
Given a sentence and a reference table, create and return an Evaluation object. Save a copy in the sentence.
625941bec432627299f04b64
def threshold_binaryW_from_array(array, threshold, p=2, radius=None): <NEW_LINE> <INDENT> if radius is not None: <NEW_LINE> <INDENT> array = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius) <NEW_LINE> <DEDENT> return DistanceBand(array, threshold=threshold, p=p)
Binary weights based on a distance threshold Parameters ---------- array : array (n,m) attribute data, n observations on m attributes threshold : float distance band p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance radius : If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance Weights object with binary weights Examples -------- >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] >>> w=threshold_binaryW_from_array(points,threshold=11.2) WARNING: there is one disconnected observation (no neighbors) Island id: [2] >>> w.weights {0: [1, 1], 1: [1, 1], 2: [], 3: [1, 1], 4: [1], 5: [1]} >>> w.neighbors {0: [1, 3], 1: [0, 3], 2: [], 3: [1, 0], 4: [5], 5: [4]} >>>
625941bebde94217f3682d13
def load_ntt(filename): <NEW_LINE> <INDENT> with open(filename, "rb") as f: <NEW_LINE> <INDENT> header = f.read(16 * 2 ** 10) <NEW_LINE> analog_to_digital = None <NEW_LINE> frequency = None <NEW_LINE> for line in header.split(b"\n"): <NEW_LINE> <INDENT> if line.strip().startswith(b"-ADBitVolts"): <NEW_LINE> <INDENT> analog_to_digital = np.array(float(line.split(b" ")[1].decode())) <NEW_LINE> <DEDENT> if line.strip().startswith(b"-SamplingFrequency"): <NEW_LINE> <INDENT> frequency = float(line.split(b" ")[1].decode()) <NEW_LINE> <DEDENT> <DEDENT> f.seek(2 ** 14) <NEW_LINE> dt = np.dtype( [("time", "<Q"), ("filer", "<i", 10), ("spikes", np.dtype("<h"), (32, 4))] ) <NEW_LINE> data = np.fromfile(f, dt) <NEW_LINE> <DEDENT> if analog_to_digital is None: <NEW_LINE> <INDENT> raise IOError("ADBitVolts not found in .ntt header for " + filename) <NEW_LINE> <DEDENT> if frequency is None: <NEW_LINE> <INDENT> raise IOError("Frequency not found in .ntt header for " + filename) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> return data["time"], data["spikes"] * analog_to_digital, frequency
Loads a neuralynx .ntt tetrode spike file. Parameters ---------- filename: str Returns ------- timestamps: np.array Spikes as (num_spikes, length_waveform, num_channels) spikes: np.array Spike times as uint64 (us) frequency: float Sampling frequency in waveforms (Hz) Usage: timestamps, spikes, frequency = load_ntt('TT13.ntt')
625941be3317a56b86939b7f
def list(self, hide_expired=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> return list(self.stream(hide_expired=hide_expired, limit=limit, page_size=page_size, ))
Lists SyncMapInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param SyncMapInstance.HideExpiredType hide_expired: Hide expired Sync Maps and show only active ones. :param int limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.sync.v1.service.sync_map.SyncMapInstance]
625941be07f4c71912b113a0
def test_relationship_1(dummies): <NEW_LINE> <INDENT> assert dummies.c3.aspinds[0].type == 'advp_for' <NEW_LINE> assert dummies.c3.synargs[0].type == 'subj' <NEW_LINE> assert dummies.c3.synargs[1].type == 'obj'
We should be able to access AspInd and SynArg objects from inside c3.
625941bebe383301e01b53ab
def empty_database(self): <NEW_LINE> <INDENT> for table in TABLES: <NEW_LINE> <INDENT> self.empty_table(table)
Delete all data in database
625941bea8ecb033257d2fee
def __init__(self, bus=None, addr=None, lock=None, unit="°C", **kwargs): <NEW_LINE> <INDENT> JNTComponent.__init__(self, oid = kwargs.pop('oid', '%s.weekly'%OID), bus = bus, addr = addr, name = kwargs.pop('name', "Weekly event"), product_name = kwargs.pop('product_name', "Weekly event"), **kwargs)
Constructor.
625941be4428ac0f6e5ba711
def restore_from_archive(self, rest_dir=None, dout_s_root=None, rundir=None): <NEW_LINE> <INDENT> if dout_s_root is None: <NEW_LINE> <INDENT> dout_s_root = self.get_value("DOUT_S_ROOT") <NEW_LINE> <DEDENT> if rundir is None: <NEW_LINE> <INDENT> rundir = self.get_value("RUNDIR") <NEW_LINE> <DEDENT> if rest_dir is not None: <NEW_LINE> <INDENT> if not os.path.isabs(rest_dir): <NEW_LINE> <INDENT> rest_dir = os.path.join(dout_s_root, "rest", rest_dir) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> rest_dir = os.path.join(dout_s_root, "rest", ls_sorted_by_mtime(os.path.join(dout_s_root, "rest"))[-1]) <NEW_LINE> <DEDENT> logger.info("Restoring restart from {}".format(rest_dir)) <NEW_LINE> for item in glob.glob("{}/*".format(rest_dir)): <NEW_LINE> <INDENT> base = os.path.basename(item) <NEW_LINE> dst = os.path.join(rundir, base) <NEW_LINE> if os.path.exists(dst): <NEW_LINE> <INDENT> os.remove(dst) <NEW_LINE> <DEDENT> logger.info("Restoring {} from {} to {}".format(item, rest_dir, rundir)) <NEW_LINE> safe_copy(item, rundir)
Take archived restart files and load them into current case. Use rest_dir if provided otherwise use most recent restore_from_archive is a member of Class Case
625941be4527f215b584c37a
def get_series(self) -> List[Series]: <NEW_LINE> <INDENT> return self.series
Get Study series Returns ------- List[Series] List of study's Series
625941be460517430c3940ac
def sample(self): <NEW_LINE> <INDENT> experiences = random.sample(self.buffer, k=self.batch_size) <NEW_LINE> states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(self.device) <NEW_LINE> return (states, actions, rewards, next_states, dones)
Randomly sample a batch of experiences from buffer.
625941be5fc7496912cc389e
def test_mark(self): <NEW_LINE> <INDENT> self.vimiv["mark"].mark() <NEW_LINE> expected_marked = [os.path.abspath("arch-logo.png")] <NEW_LINE> self.assertEqual(expected_marked, self.vimiv["mark"].marked) <NEW_LINE> self.vimiv["mark"].mark() <NEW_LINE> self.assertEqual([], self.vimiv["mark"].marked)
Mark images.
625941be187af65679ca503e
def commonChars(self, A): <NEW_LINE> <INDENT> def fun(x,y): <NEW_LINE> <INDENT> res = [] <NEW_LINE> d = {} <NEW_LINE> for i in x: <NEW_LINE> <INDENT> d[i] = d.get(i,0)+1 <NEW_LINE> <DEDENT> for i in y: <NEW_LINE> <INDENT> if d.get(i, 0) > 0: <NEW_LINE> <INDENT> d[i] -= 1 <NEW_LINE> res.append(i) <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> from functools import reduce <NEW_LINE> return list(reduce(fun,A))
:type A: List[str] :rtype: List[str]
625941be23e79379d52ee486
def generate_lpe(self): <NEW_LINE> <INDENT> from generate_LPE_intention import generate_lpe_intention, plot_orientation <NEW_LINE> pixels, thetas = self.get_pixels() <NEW_LINE> for r, pixs in enumerate(pixels): <NEW_LINE> <INDENT> pixs = list(zip(pixs[0], pixs[1])) <NEW_LINE> lpes = generate_lpe_intention(self.global_map, pixs, thetas[r], 30, self.intentions[r], 3000, line_thick=2, steps=300) <NEW_LINE> <DEDENT> plot_orientation(self.global_map, pixs, thetas[-1], lpes)
Use to generate lpe intention for huawei data. We move the function from generate_LPE_intention.py to here for simplicity
625941beb545ff76a8913d36
def test_2_dof(): <NEW_LINE> <INDENT> pi = PolynomialPath([[1, 2, 3], [-2, 3, 4, 5]]) <NEW_LINE> assert pi.dof == 2 <NEW_LINE> npt.assert_allclose( pi.eval([0, 0.5, 1]), [[1, -2], [2.75, 1.125], [6, 10]]) <NEW_LINE> npt.assert_allclose( pi.evald([0, 0.5, 1]), [[2, 3], [5, 10.75], [8, 26]]) <NEW_LINE> npt.assert_allclose(pi.evaldd([0, 0.5, 1]), [[6, 8], [6, 23], [6, 38]])
Polynomial path with 2dof.
625941bebe383301e01b53ac
def get_rec_user(self, count): <NEW_LINE> <INDENT> ratings=self.model.recommendForAllItems(count)
Add additional kindle ratings in the format (user_id, item_id, rating)
625941be377c676e912720c9
def __down_heap(self, pos=1): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> left = self.__get_left_child(pos) if self.__has_left_child(pos) else None <NEW_LINE> right = self.__get_right_child(pos) if self.__has_right_child(pos) else None <NEW_LINE> if right and left and self.__compare__(left, right): <NEW_LINE> <INDENT> self.__swap(pos, pos * 2 + 1) <NEW_LINE> pos = pos * 2 + 1 <NEW_LINE> <DEDENT> elif left: <NEW_LINE> <INDENT> self.__swap(pos, pos * 2) <NEW_LINE> pos *= 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if pos != len(self.__data) - 1: <NEW_LINE> <INDENT> self.__swap(pos, len(self.__data) - 1) <NEW_LINE> self.__up_heap(pos) <NEW_LINE> <DEDENT> self.__data.pop() <NEW_LINE> return
Method for sorting data when element is removed from structure. It goes from position (usually root node), checks for left and right children, if both exists then checks which should go before other one, and that one swaps with position from where started, if right doesn't exist, then just swaps it with left, and if neither child exists, then it stops. When start position is put down as far as it should go (it will always go to the bottom because its value (key) doesn't matter, it implies that start position should be removed), then it is swapped with last filled position, and after that, last filled position is freed, and up_heap is called with position on which initially node was dropped. :param pos: (int) position from which to start (default = root node)
625941befbf16365ca6f60de
def update_when_done( func: Callable[Concatenate[_T, _P], Awaitable[_R]] ) -> Callable[Concatenate[_T, _P], Awaitable[_R]]: <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> async def wrapper(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> _R: <NEW_LINE> <INDENT> result = await func(self, *args, **kwargs) <NEW_LINE> await self.coordinator.async_request_refresh() <NEW_LINE> return result <NEW_LINE> <DEDENT> return wrapper
Decorate function to trigger update when function is done.
625941be8c0ade5d55d3e8df
def apply_moving_k_closest_average(self, input_column, dest_column=None, row_range=(0, None), window=5, kclosest=3): <NEW_LINE> <INDENT> if dest_column == None: <NEW_LINE> <INDENT> dest_column = input_column + '_kca_' + str(window) <NEW_LINE> <DEDENT> full_series = list(self._pd_frame[input_column]) <NEW_LINE> filtered_series = full_series[row_range[0]:row_range[1]] <NEW_LINE> result = Features.moving_k_closest_average(series=filtered_series, window=window, kclosest=kclosest, default=True) <NEW_LINE> full_series[row_range[0]: row_range[1]] = result <NEW_LINE> self.add_column(column_name=dest_column, series=full_series)
Apply moving k closest average as another column :param input_column: Required column to add feature engineering :param dest_column: Destination column name :param row_range: Range of rows that need to modify :param window: Window size of the calculation takes part :param kclosest: k number of closest values to the recent occurrence including itself :return: None
625941be21a7993f00bc7c0c
def pc_output_buffers_full_var(self, *args): <NEW_LINE> <INDENT> return _channels_swig.fading_model_sptr_pc_output_buffers_full_var(self, *args)
pc_output_buffers_full_var(fading_model_sptr self, int which) -> float pc_output_buffers_full_var(fading_model_sptr self) -> pmt_vector_float
625941be925a0f43d2549d95
def test_access_from_banned_ip_when_ban_is_off(self): <NEW_LINE> <INDENT> hass.http.app[KEY_BANS_ENABLED] = False <NEW_LINE> for remote_addr in BANNED_IPS: <NEW_LINE> <INDENT> with patch('homeassistant.components.http.' 'ban.get_real_ip', return_value=ip_address(remote_addr)): <NEW_LINE> <INDENT> req = requests.get( _url(const.URL_API), headers={const.HTTP_HEADER_HA_AUTH: API_PASSWORD}) <NEW_LINE> assert req.status_code == 200
Test accessing to server from banned IP when feature is off
625941be1f5feb6acb0c4a74
@app.task(bind=True, name="bucket.pull_file_task") <NEW_LINE> def pull_file_task(self, path, overwrite): <NEW_LINE> <INDENT> bucket = Bucket() <NEW_LINE> return bucket.pull_file(path, overwrite)
Pull file from bucket. async version of Bucket().pull_file() Args: path (str): file path overwrite (bool): if True, overwrite the existing file in local Returns: None
625941be5166f23b2e1a5079
def test_long(self): <NEW_LINE> <INDENT> stream_handle = open(os.path.join(RESOURCE_PATH, 'SAMI_P0080_180713_orig.txt')) <NEW_LINE> parser = PhsenRecoveredParser(self.config, stream_handle, self.exception_callback) <NEW_LINE> result = parser.get_records(32) <NEW_LINE> self.assertEquals(len(result), 29) <NEW_LINE> self.assertEquals(self.exception_callback_value, []) <NEW_LINE> stream_handle.close()
Test with the full original file
625941bed164cc6175782c6e
def save_cookie(driver, path): <NEW_LINE> <INDENT> with open(path, 'w') as filehandler: <NEW_LINE> <INDENT> json.dump(driver.get_cookies(), filehandler)
Function to save cookies from webdriver to json file.
625941be4c3428357757c24a
def test_unicode_message_regex_searchstring(self): <NEW_LINE> <INDENT> poascii = '# comment\n#: test.c\nmsgid "test"\nmsgstr "rest"\n' <NEW_LINE> pounicode = u'# comment\n#: test.c\nmsgid "test"\nmsgstr "rešṱ"\n' <NEW_LINE> queryascii = 'rest' <NEW_LINE> queryunicode = u'rešṱ' <NEW_LINE> for source, search, expected in [(poascii, queryascii, poascii), (poascii, queryunicode, ''), (pounicode, queryascii, ''), (pounicode, queryunicode, pounicode)]: <NEW_LINE> <INDENT> print("Source:\n%s\nSearch: %s\n" % (source, search)) <NEW_LINE> poresult = self.pogrep(source, search, ["--regexp"]).decode('utf-8') <NEW_LINE> assert poresult.index(expected) >= 0
check that we can grep unicode messages and use unicode regex search strings
625941be94891a1f4081b9c8
def form_valid(self, form): <NEW_LINE> <INDENT> form.instance.user = self.request.user <NEW_LINE> form.instance.save() <NEW_LINE> return super(ProcedureCreate, self).form_valid(form)
Add the user to the form. :return: bool, is the form valid.
625941be4428ac0f6e5ba712
def __stop(self): <NEW_LINE> <INDENT> self.vvpmng.getlock() <NEW_LINE> try: <NEW_LINE> <INDENT> if not self.vvpmng.isset(): <NEW_LINE> <INDENT> APPLOGGER.warn('no process to stop') <NEW_LINE> self.request.sendall(self.clientcmd_stop + '|' + '0') <NEW_LINE> return <NEW_LINE> <DEDENT> if self.vvpmng.isrun(): <NEW_LINE> <INDENT> self.vvpmng.stop() <NEW_LINE> APPLOGGER.warn('terminating..') <NEW_LINE> self.vvpmng.setprocess(None) <NEW_LINE> self.request.sendall(self.clientcmd_stop + '|' + '1') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> APPLOGGER.info('process is terminate') <NEW_LINE> self.vvpmng.setprocess(None) <NEW_LINE> self.request.sendall(self.clientcmd_stop + '|' + '0') <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.vvpmng.process_cmd.record = False <NEW_LINE> self.vvpmng.process_cmd.recordfname = '' <NEW_LINE> self.request.close() <NEW_LINE> self.vvpmng.releaselock()
__stop_process
625941be99fddb7c1c9de2b3
def week(day_time=None): <NEW_LINE> <INDENT> url = f"{BASE_URL}&duration=7d" <NEW_LINE> if day_time is not None: <NEW_LINE> <INDENT> base_url = "https://music.naver.com/listen/history/index.nhn?type=TOTAL" <NEW_LINE> local_dt = utils.localize_time(day_time, TIMEZONE) <NEW_LINE> year = local_dt.strftime("%Y") <NEW_LINE> month = local_dt.strftime("%m") <NEW_LINE> week = utils.get_weeks_in(local_dt) <NEW_LINE> url = f"{base_url}&year={year}&month={month}&week={week}" <NEW_LINE> <DEDENT> return utils.get_ranks(url, SELECTOR, parser)
Return rankings for given week.
625941bed58c6744b4257b81
def test_importing_b1_and_b2(self): <NEW_LINE> <INDENT> initial_instance_count = Instance.objects.count() <NEW_LINE> initial_image_count = images_count() <NEW_LINE> import_instances_from_zip(os.path.join( DB_FIXTURES_PATH, "bulk_submission.zip"), self.user) <NEW_LINE> instance_count = Instance.objects.count() <NEW_LINE> image_count = images_count() <NEW_LINE> self.assertEqual(image_count, initial_image_count + 2) <NEW_LINE> self.assertEqual(instance_count, initial_instance_count + 2)
b1 and b2 are from the *same phone* at different times. (this might not be a realistic test) b1: 1 photo survey (completed) 1 simple survey (not marked complete) b2: 1 photo survey (duplicate, completed) 1 simple survey (marked as complete)
625941be8c3a8732951582d8
def __init__(self, exit_value, msg): <NEW_LINE> <INDENT> self.exit_value = int(exit_value) <NEW_LINE> self.msg = str(msg)
Constructor. @param exit_value: the exit value, which should be given back to OS. @type exit_value: int @param msg: the error message, which should be displayed on exit. @type msg: str
625941be9f2886367277a7b0
def updateSingleComputedValue(dataTable, combinationString, onDatetime): <NEW_LINE> <INDENT> def parser(idx, parseString): <NEW_LINE> <INDENT> if idx == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif idx == 1 or idx == 3: <NEW_LINE> <INDENT> return [int(i) for i in parseString.split(',')] <NEW_LINE> <DEDENT> elif idx == 2: <NEW_LINE> <INDENT> return [float(i) for i in parseString.split(',')] <NEW_LINE> <DEDENT> <DEDENT> null, IDs, CFs, LGs = [parser(i, x) for i,x in enumerate(combinationString.split('/'))] <NEW_LINE> data = pd.Series([0], index=[onDatetime]) <NEW_LINE> for i, ID in enumerate(IDs): <NEW_LINE> <INDENT> shiftedDatetime = onDatetime + pd.DateOffset(LGs[i]) <NEW_LINE> newData = pd.Series(dataTable.loc[(shiftedDatetime, ID), 'Value'], index=[onDatetime]) <NEW_LINE> data = np.sum([data, CFs[i]*pd.Series(newData.values, index=newData.index.get_level_values(0))], axis=0) <NEW_LINE> <DEDENT> return data
Updates a single value in the dataTable
625941be2ae34c7f2600d052
def wnet_sub_tok(sub_tokens, subtok_type, expected_format='tlgs'): <NEW_LINE> <INDENT> if expected_format == 'tlgs': <NEW_LINE> <INDENT> return wnet_tlgs_subtok(sub_tokens, subtok_type) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('unsupported expected_format %s' % expected_format)
Returns the subtoken of the requested type, for the expected format
625941beb57a9660fec337a2
def get_cbm_vbm(self, tol: float = 0.001, abs_tol: bool = False, spin: Spin = None): <NEW_LINE> <INDENT> tdos = self.get_densities(spin) <NEW_LINE> if not abs_tol: <NEW_LINE> <INDENT> tol = tol * tdos.sum() / tdos.shape[0] <NEW_LINE> <DEDENT> i_fermi = 0 <NEW_LINE> while self.energies[i_fermi] <= self.efermi: <NEW_LINE> <INDENT> i_fermi += 1 <NEW_LINE> <DEDENT> i_gap_start = i_fermi <NEW_LINE> while i_gap_start - 1 >= 0 and tdos[i_gap_start - 1] <= tol: <NEW_LINE> <INDENT> i_gap_start -= 1 <NEW_LINE> <DEDENT> i_gap_end = i_gap_start <NEW_LINE> while i_gap_end < tdos.shape[0] and tdos[i_gap_end] <= tol: <NEW_LINE> <INDENT> i_gap_end += 1 <NEW_LINE> <DEDENT> i_gap_end -= 1 <NEW_LINE> return self.energies[i_gap_end], self.energies[i_gap_start]
Expects a DOS object and finds the cbm and vbm. Args: tol: tolerance in occupations for determining the gap abs_tol: An absolute tolerance (True) and a relative one (False) spin: Possible values are None - finds the gap in the summed densities, Up - finds the gap in the up spin channel, Down - finds the gap in the down spin channel. Returns: (cbm, vbm): float in eV corresponding to the gap
625941bebd1bec0571d9054f
def get_tx_fault(self): <NEW_LINE> <INDENT> if not self.dom_supported: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> tx_fault_list = [] <NEW_LINE> if self.sfp_type == OSFP_TYPE: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif self.sfp_type == QSFP_TYPE: <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> dom_channel_monitor_raw = self.__read_eeprom_specific_bytes( (offset + QSFP_CHANNL_TX_FAULT_STATUS_OFFSET), QSFP_CHANNL_TX_FAULT_STATUS_WIDTH) <NEW_LINE> if dom_channel_monitor_raw is not None: <NEW_LINE> <INDENT> tx_fault_data = int(dom_channel_monitor_raw[0], 16) <NEW_LINE> tx_fault_list.append(tx_fault_data & 0x01 != 0) <NEW_LINE> tx_fault_list.append(tx_fault_data & 0x02 != 0) <NEW_LINE> tx_fault_list.append(tx_fault_data & 0x04 != 0) <NEW_LINE> tx_fault_list.append(tx_fault_data & 0x08 != 0) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> offset = 256 <NEW_LINE> dom_channel_monitor_raw = self.__read_eeprom_specific_bytes( (offset + SFP_CHANNL_STATUS_OFFSET), SFP_CHANNL_STATUS_WIDTH) <NEW_LINE> if dom_channel_monitor_raw is not None: <NEW_LINE> <INDENT> tx_fault_data = int(dom_channel_monitor_raw[0], 16) <NEW_LINE> tx_fault_list.append(tx_fault_data & 0x04 != 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return tx_fault_list
Retrieves the TX fault status of SFP Returns: A Boolean, True if SFP has TX fault, False if not Note : TX fault status is lached until a call to get_tx_fault or a reset.
625941bed6c5a10208143f69
def better_float_str(x, tolerance=12, pre_strip=True): <NEW_LINE> <INDENT> if pre_strip: <NEW_LINE> <INDENT> xs = x.replace("(", "").replace(")", "").replace(";", "") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xs = x <NEW_LINE> <DEDENT> ns = str(decimal.Decimal(xs.strip()).quantize(decimal.Decimal(10) ** -tolerance)) <NEW_LINE> estr = "0E-%d" % tolerance <NEW_LINE> ns = ns.replace(estr, "0.") <NEW_LINE> if "E" not in ns: <NEW_LINE> <INDENT> ns = ns.rstrip("0") <NEW_LINE> <DEDENT> return ns
local function to convert a floating point coordinate string representation into a more optimum (quantized with Decimal) string representation
625941be60cbc95b062c6463
def save_summaries(filename, d): <NEW_LINE> <INDENT> with open('output/' + filename + '.txt', 'w') as f: <NEW_LINE> <INDENT> json.dump(d, f)
Saves summaries to new file
625941bea934411ee37515b4
def rm_fstab(name, config='/etc/fstab'): <NEW_LINE> <INDENT> contents = fstab(config) <NEW_LINE> if name not in contents: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> lines = [] <NEW_LINE> try: <NEW_LINE> <INDENT> with open(config, 'r') as fh: <NEW_LINE> <INDENT> for line in fh: <NEW_LINE> <INDENT> if line.startswith('#'): <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not line.strip(): <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> continue <NEW_LINE> <DEDENT> comps = line.split() <NEW_LINE> if not len(comps) == 6: <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> continue <NEW_LINE> <DEDENT> comps = line.split() <NEW_LINE> if comps[1] == name: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> lines.append(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except (IOError, OSError) as exc: <NEW_LINE> <INDENT> msg = "Couldn't read from {0}: {1}" <NEW_LINE> raise CommandExecutionError(msg.format(config, str(exc))) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(config, 'w+') as fh: <NEW_LINE> <INDENT> fh.writelines(lines) <NEW_LINE> <DEDENT> <DEDENT> except (IOError, OSError) as exc: <NEW_LINE> <INDENT> msg = "Couldn't write to {0}: {1}" <NEW_LINE> raise CommandExecutionError(msg.format(config, str(exc))) <NEW_LINE> <DEDENT> return True
Remove the mount point from the fstab CLI Example:: salt '*' mount.rm_fstab /mnt/foo
625941be10dbd63aa1bd2ac7
def __init__(self, name, sources, provides=None, dependencies=None, excludes=None, compiler=_COMPILER_DEFAULT, language=_LANGUAGE_DEFAULT, rpc_style=_RPC_STYLE_DEFAULT, namespace_map=None, exclusives=None): <NEW_LINE> <INDENT> self._provides = provides <NEW_LINE> super(JavaThriftLibrary, self).__init__( name, sources, dependencies, excludes, exclusives=exclusives) <NEW_LINE> self.add_labels('codegen') <NEW_LINE> if dependencies: <NEW_LINE> <INDENT> if not isinstance(dependencies, Iterable): <NEW_LINE> <INDENT> raise TargetDefinitionException(self, 'dependencies must be Iterable but was: %s' % dependencies) <NEW_LINE> <DEDENT> maybe_list(dependencies, expected_type=(JarDependency, JavaThriftLibrary, Pants), raise_type=partial(TargetDefinitionException, self)) <NEW_LINE> <DEDENT> def check_value_for_arg(arg, value, values): <NEW_LINE> <INDENT> if value not in values: <NEW_LINE> <INDENT> raise TargetDefinitionException(self, "%s may only be set to %s ('%s' not valid)" % (arg, ', or '.join(map(repr, values)), value)) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> compiler = compiler or self._COMPILER_DEFAULT <NEW_LINE> self.compiler = check_value_for_arg('compiler', compiler, self._COMPILERS) <NEW_LINE> language = language or self._LANGUAGE_DEFAULT <NEW_LINE> self.language = check_value_for_arg('language', language, self._LANGUAGES) <NEW_LINE> rpc_style = rpc_style or self._RPC_STYLE_DEFAULT <NEW_LINE> self.rpc_style = check_value_for_arg('rpc_style', rpc_style, self._RPC_STYLES) <NEW_LINE> self.namespace_map = namespace_map
:param string name: The name of this target, which combined with this build file defines the target :class:`pants.base.address.Address`. :param sources: A list of filenames representing the source code this library is compiled from. :type sources: list of strings :param Artifact provides: The :class:`pants.targets.artifact.Artifact` to publish that represents this target outside the repo. :param dependencies: List of :class:`pants.base.target.Target` instances this target depends on. :type dependencies: list of targets :param excludes: List of :class:`pants.targets.exclude.Exclude` instances to filter this target's transitive dependencies against. :param compiler: An optional compiler used to compile the thrift files. :param language: The language used to generate the output files. One of 'java' or 'scala' with a default of 'java'. :param rpc_style: An optional rpc style to generate service stubs with. One of 'sync', 'finagle' or 'ostrich' with a default of 'sync'. :param namespace_map: A dictionary of namespaces to remap (old: new) :param exclusives: An optional map of exclusives tags. See CheckExclusives for details.
625941bea4f1c619b28aff60
def objectiveFunction(x, N, N_im, sz, dims, dimOpt, dimLenOpt, lam1, lam2, data, k, strtag, ph, kern, dirWeight=0, dirs=None, dirInfo=[None,None,None,None], nmins=0, wavelet='db4', mode="per", a=10.): <NEW_LINE> <INDENT> tv = 0 <NEW_LINE> xfm = 0 <NEW_LINE> data.shape = N_im <NEW_LINE> x.shape = N <NEW_LINE> if len(N) > 2: <NEW_LINE> <INDENT> x0 = np.zeros(N_im) <NEW_LINE> for i in xrange(N[0]): <NEW_LINE> <INDENT> x0[i,:,:] = tf.iwt(x[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> x0 = tf.iwt(x,wavelet,mode,dims,dimOpt,dimLenOpt) <NEW_LINE> <DEDENT> obj = np.sum(objectiveFunctionDataCons(x0,N_im,ph,data,k,sz,strtag)) <NEW_LINE> if lam1 > 1e-6: <NEW_LINE> <INDENT> tv = np.sum(objectiveFunctionTV(x0,N_im,strtag,kern,dirWeight,dirs,nmins,dirInfo=dirInfo,a=a)) <NEW_LINE> <DEDENT> if lam2 > 1e-6: <NEW_LINE> <INDENT> xfm = np.sum((1/a)*np.log(np.cosh(a*x))) <NEW_LINE> <DEDENT> x.shape = (x.size,) <NEW_LINE> data.shape = (data.size,) <NEW_LINE> return abs(obj + lam1*tv + lam2*xfm)
This is the optimization function that we're trying to optimize. We are optimizing x here, and testing it within the funcitons that we want, as called by the functions that we've created
625941be091ae35668666e84
def deleteFront(self) -> bool: <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.front = (self.front + 1) % self.capcity <NEW_LINE> return True
Deletes an item from the front of Deque. Return true if the operation is successful.
625941be1f037a2d8b94611f
def generate_static_sku_detail_html(spu_id): <NEW_LINE> <INDENT> detail_image = get_sku_image(spu_id) <NEW_LINE> desc_dict = get_detail_image(spu_id) <NEW_LINE> goods_detail, sku_id = get_sku(spu_id, detail_image, desc_dict) <NEW_LINE> context = { "goods_detail": goods_detail } <NEW_LINE> template = loader.get_template('detail.html') <NEW_LINE> html_text = template.render(context) <NEW_LINE> file_path = os.path.join(settings.STATICFILES_DIRS[0], 'detail/'+str(sku_id)+'.html') <NEW_LINE> with open(file_path, 'w') as f: <NEW_LINE> <INDENT> f.write(html_text)
生成静态商品详情页面 :param sku_id: 商品sku id
625941be45492302aab5e1e1
def _get_ffmpeg_commands(args): <NEW_LINE> <INDENT> if args.input_file is not None: <NEW_LINE> <INDENT> for line in args.input_file: <NEW_LINE> <INDENT> yield shlex.split(line) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield args.ffmpeg_arguments
Obtains all the ffmpeg commands that need to be run.
625941be7d847024c06be1da
def del_student(lst): <NEW_LINE> <INDENT> idx = 0 <NEW_LINE> name = input("请输入学生姓名(直接按enter结束):") <NEW_LINE> if name == '': <NEW_LINE> <INDENT> print("输入结束!") <NEW_LINE> return <NEW_LINE> <DEDENT> it = iter(lst) <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> stu = next(it) <NEW_LINE> if name != stu.get_name(): <NEW_LINE> <INDENT> idx += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> print('没有查找到' + name + '的信息。') <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del lst[idx]
删除学生信息 输入参数: lst 类的列表
625941be377c676e912720ca
def __new__(mcs, name, bases, namespace, **kwargs): <NEW_LINE> <INDENT> class_obj = super().__new__(mcs, name, bases, namespace) <NEW_LINE> if name != "NoValidationExperiment": <NEW_LINE> <INDENT> namespace["__class_wide_bases"].append(PredictorOOF) <NEW_LINE> namespace["__class_wide_bases"].append(EvaluatorOOF) <NEW_LINE> <DEDENT> namespace["__class_wide_bases"].append(AggregatorEvaluations) <NEW_LINE> namespace["__class_wide_bases"].append(AggregatorTimes) <NEW_LINE> namespace["__class_wide_bases"].append(LoggerFitStatus) <NEW_LINE> return class_obj
Create a new class object that stores necessary class-wide callbacks to :attr:`__class_wide_bases`
625941beb545ff76a8913d37
def pc_input_buffers_full(self, *args): <NEW_LINE> <INDENT> return _cdma_swig.chopper_sptr_pc_input_buffers_full(self, *args)
pc_input_buffers_full(chopper_sptr self, int which) -> float pc_input_buffers_full(chopper_sptr self) -> pmt_vector_float
625941be38b623060ff0ad0f
def testGetListDataWithStartAndLimit(self): <NEW_LINE> <INDENT> query = TestNDBModel.query() <NEW_LINE> _, start, _ = query.fetch_page(3) <NEW_LINE> list_data = self.list_reader.getListData( NDB_TEST_LIST_ID, query, start=start.urlsafe(), limit=5) <NEW_LINE> expected_list = [{'name': 'name %s' % i, 'value': i} for i in range(3, 8)] <NEW_LINE> _, next_cursor, _ = query.fetch_page(8) <NEW_LINE> self.assertListEqual(list_data.data, expected_list) <NEW_LINE> self.assertEqual(list_data.next_key, next_cursor.urlsafe())
Tests getGetListData method.
625941bed99f1b3c44c674b6
def logo(): <NEW_LINE> <INDENT> print(" |__") <NEW_LINE> print(" |\/") <NEW_LINE> print(" ---") <NEW_LINE> print(" / | [") <NEW_LINE> print(" ! | |||") <NEW_LINE> print(" _/| _/|-++'") <NEW_LINE> print(" + +--| |--|--|_ |-") <NEW_LINE> print(" { /|__| |/\__| |--- |||__/") <NEW_LINE> print( " +---------------___[}-_===_.'____ /\\") <NEW_LINE> print( " ____`-' ||___-{]_| _[}- | |_[___\==-- \/ _") <NEW_LINE> print( " __..._____--==/___]_|__|_____________________________[___\==--____,------' .7") <NEW_LINE> print("| BB-61/") <NEW_LINE> print(" \_________________________________________________________________________|") <NEW_LINE> print() <NEW_LINE> print("██████╗ █████╗ ████████╗████████╗██╗ ███████╗███████╗██╗ ██╗██╗██████╗ ") <NEW_LINE> print("██╔══██╗██╔══██╗╚══██╔══╝╚══██╔══╝██║ ██╔════╝██╔════╝██║ ██║██║██╔══██╗") <NEW_LINE> print("██████╔╝███████║ ██║ ██║ ██║ █████╗ ███████╗███████║██║██████╔╝") <NEW_LINE> print("██╔══██╗██╔══██║ ██║ ██║ ██║ ██╔══╝ ╚════██║██╔══██║██║██╔═══╝ ") <NEW_LINE> print("██████╔╝██║ ██║ ██║ ██║ ███████╗███████╗███████║██║ ██║██║██║ ") <NEW_LINE> print("╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ") <NEW_LINE> print() <NEW_LINE> print(" ################################################################") <NEW_LINE> print(" # ___ __ ___ __ __ #") <NEW_LINE> print(" # | _ _ | _ _ _ _ _ _ |_ |\ | | |_ |__) #") <NEW_LINE> print(" # |(_) |_)|(_|\/ |_)| (-_)_) |__| \| | |__| \ #") <NEW_LINE> print(" # | / | #") <NEW_LINE> print(" ################################################################") <NEW_LINE> input()
(None) -> None Function prints logo of game
625941be63d6d428bbe44410
def SetLong(self, *args, **kwargs): <NEW_LINE> <INDENT> pass
Set for integer fields.
625941becb5e8a47e48b79ce
def get_class_value(geom): <NEW_LINE> <INDENT> x = geom.centroid.x <NEW_LINE> y = geom.centroid.y <NEW_LINE> for val in classras.sample([(x, y)]): <NEW_LINE> <INDENT> return pd.Series(val, index=[predicted_column])
TAKES A VARIABLE OF GEOMETRY TYPE AND RETURNS THE VALUE AT X,Y AS A PANDAS SERIES FOR FOR LOCAL RASTER 'CLASSRAS'
625941be4f88993c3716bf8c
def PrintPdbInfo(self): <NEW_LINE> <INDENT> print ("Number of residues and frame: %s %s"%(self.seqlength ,self.timefrm)) <NEW_LINE> print ("Number of chains: %s "%len(self.chains.keys()))
Print information regarding the number of residues and frame
625941be5510c4643540f30c
def DescribeMessageQueue(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeMessageQueue", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribeMessageQueueResponse() <NEW_LINE> model._deserialize(response["Response"]) <NEW_LINE> return model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code = response["Response"]["Error"]["Code"] <NEW_LINE> message = response["Response"]["Error"]["Message"] <NEW_LINE> reqid = response["Response"]["RequestId"] <NEW_LINE> raise TencentCloudSDKException(code, message, reqid) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if isinstance(e, TencentCloudSDKException): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TencentCloudSDKException(e.message, e.message)
本接口(DescribeMessageQueue)用于查询物联网智能视频产品转发消息配置。 :param request: Request instance for DescribeMessageQueue. :type request: :class:`tencentcloud.iotvideo.v20191126.models.DescribeMessageQueueRequest` :rtype: :class:`tencentcloud.iotvideo.v20191126.models.DescribeMessageQueueResponse`
625941be566aa707497f448e
def scale(self,center,ratio): <NEW_LINE> <INDENT> self.x,self.y = ratio*self.x+(1-ratio)*center.x,ratio*self.y+(1-ratio)*center.y <NEW_LINE> return self
transforms the point whith an homothety center is the center of homothety ratio is a number Example: >>> p = Point(3,0).scale(Point(0,1),2.5) >>> print(p.x,p.y) 7.5 -1.5
625941be596a8972360899e4
def validate(self, db=True): <NEW_LINE> <INDENT> client = self.get_mgmt_system() <NEW_LINE> if not db: <NEW_LINE> <INDENT> sel.force_navigate('{}_provider'.format(self.page_name), context={'provider': self}) <NEW_LINE> <DEDENT> if self._do_stats_match(client, self.STATS_TO_MATCH, db=db): <NEW_LINE> <INDENT> client.disconnect() <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sel.force_navigate('{}_provider'.format(self.page_name), context={'provider': self}) <NEW_LINE> tb.select("Configuration", "Refresh Relationships and Power States", invokes_alert=True) <NEW_LINE> sel.handle_alert() <NEW_LINE> refresh_timer = RefreshTimer(time_for_refresh=300) <NEW_LINE> wait_for(self._do_stats_match, [client, self.STATS_TO_MATCH, refresh_timer], {'db': db}, message="do_stats_match_db", num_sec=1000, delay=60) <NEW_LINE> <DEDENT> client.disconnect()
Validates that the detail page matches the Providers information. This method logs into the provider using the mgmt_system interface and collects a set of statistics to be matched against the UI. The details page is then refreshed continuously until the matching of all items is complete. A error will be raised if the match is not complete within a certain defined time period.
625941be29b78933be1e55d2
def test_invalid_name_does_not_create(self): <NEW_LINE> <INDENT> assert not bootstrap.setup_component(self.hass, 'switch', { 'switch': { 'platform': 'template', 'switches': { 'test INVALID switch': { 'value_template': "{{ rubbish }", 'turn_on': { 'service': 'switch.turn_on', 'entity_id': 'switch.test_state' }, 'turn_off': { 'service': 'switch.turn_off', 'entity_id': 'switch.test_state' }, } } } }) <NEW_LINE> assert self.hass.states.all() == []
Test invalid name.
625941be8c3a8732951582d9
def commit(self): <NEW_LINE> <INDENT> pass
Called when the user clicks the "OK" button in the preferences dialog to actually apply the configuration. This method is only called if no `validate()' method returns a false value. The default implementation does nothing.
625941be4c3428357757c24b
def __eq__(self, other: object) -> bool: <NEW_LINE> <INDENT> return ( isinstance(other, PipetteContext) and self._pipette_id == other._pipette_id )
Compare for object equality. Checks that other object is a `PipetteContext` and has the same identifier.
625941be4a966d76dd550f2e
def merge(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> m, n = m - 1, n - 1 <NEW_LINE> while m >= 0 and n >= 0: <NEW_LINE> <INDENT> if nums1[m] > nums2[n]: <NEW_LINE> <INDENT> nums1[m + n + 1] = nums1[m] <NEW_LINE> m -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums1[m + n + 1] = nums2[n] <NEW_LINE> n -= 1 <NEW_LINE> <DEDENT> <DEDENT> if n != -1: <NEW_LINE> <INDENT> nums1[:n + 1] = nums2[:n + 1] <NEW_LINE> <DEDENT> return nums1
:type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.
625941be1d351010ab855a3e
def sms_campaignsubscriber_detail(self): <NEW_LINE> <INDENT> model_name = SMSCampaignSubscriber._meta.object_name.lower() <NEW_LINE> app_label = self._meta.app_label <NEW_LINE> link = '/admin/%s/%s/' % (app_label, model_name) <NEW_LINE> link += '?sms_campaign__id=%d' % self.id <NEW_LINE> display_link = _("<a href='%(link)s'>%(name)s</a>") % {'link': link, 'name': _('details')} <NEW_LINE> return display_link
This will link to sms_campaign subscribers who are associated with the sms_campaign
625941be63d6d428bbe44411
@cli.command('indico') <NEW_LINE> @click.option('--no-deps', 'deps', is_flag=True, flag_value=False, default=True, help='skip setup_deps') <NEW_LINE> @click.pass_obj <NEW_LINE> def build_indico(obj, deps): <NEW_LINE> <INDENT> target_dir = obj['target_dir'] <NEW_LINE> os.chdir(os.path.join(os.path.dirname(__file__), '..', '..')) <NEW_LINE> clean, output = git_is_clean_indico() <NEW_LINE> if not clean: <NEW_LINE> <INDENT> fail('working tree is not clean', verbose_msg=output) <NEW_LINE> <DEDENT> if deps: <NEW_LINE> <INDENT> setup_deps() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warn('building deps disabled') <NEW_LINE> <DEDENT> clean_build_dirs() <NEW_LINE> build_wheel(target_dir) <NEW_LINE> clean_build_dirs()
Builds the indico wheel.
625941be046cf37aa974cc6b
@app.route("/queues", methods=['GET']) <NEW_LINE> def get_queues(): <NEW_LINE> <INDENT> all = [] <NEW_LINE> conn = get_conn() <NEW_LINE> for q in conn.get_all_queues(): <NEW_LINE> <INDENT> all.append (q.name) <NEW_LINE> <DEDENT> resp = json.dumps(all) <NEW_LINE> return Response(response=resp, mimetype="application/json")
list all queries curl -s -X GET -H 'Accept: application/json' http://localhost:5000/queues | python -mjson.tool
625941be2ae34c7f2600d053
def fit_parameters(self, input_image, background_image, ignore_mask_image, ground_truth_labels, number_of_steps, update_callback, wait_callback): <NEW_LINE> <INDENT> keep_going = True <NEW_LINE> self.param_fit_progress = 0 <NEW_LINE> self.best_snake_score = 10 <NEW_LINE> self.best_rank_score = 1000000000 <NEW_LINE> aft_active = [] <NEW_LINE> adaptations_stopped = False <NEW_LINE> cellstar = self.prepare_cell_star_object(min(11, self.decoded_segmentation_precision_value)) <NEW_LINE> self.best_parameters = cellstar.parameters <NEW_LINE> self.autoadapted_params.value = cellstar.encode_auto_params() <NEW_LINE> try: <NEW_LINE> <INDENT> while (keep_going or not adaptations_stopped) and self.param_fit_progress < number_of_steps: <NEW_LINE> <INDENT> wait_callback(0.5) <NEW_LINE> if any(aft_active) and aft_active[0].exception is not None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> while any(aft_active) and (not aft_active[0].is_alive() and aft_active[0].started): <NEW_LINE> <INDENT> aft_active = aft_active[1:] <NEW_LINE> <DEDENT> if any(aft_active) and not aft_active[0].started: <NEW_LINE> <INDENT> aft_active[0].update_params(self.best_parameters) <NEW_LINE> aft_active[0].start() <NEW_LINE> <DEDENT> adaptations_stopped = aft_active == [] <NEW_LINE> if adaptations_stopped and keep_going and self.param_fit_progress < number_of_steps: <NEW_LINE> <INDENT> aft_active.append( AutoFitterThread(run_pf, self.update_snake_params, input_image, background_image, ignore_mask_image, ground_truth_labels, self.best_parameters, self.decoded_segmentation_precision_value, self.average_cell_diameter.value, self.update_partial_iteration_progress)) <NEW_LINE> aft_active.append( AutoFitterThread(run_rank_pf, self.update_rank_params, input_image, background_image, ignore_mask_image, ground_truth_labels, self.best_parameters, self.update_partial_iteration_progress)) <NEW_LINE> <DEDENT> keep_going_update = update_callback(self.param_fit_progress + self.param_fit_progress_partial) <NEW_LINE> keep_going = keep_going and keep_going_update <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> update_callback(number_of_steps)
:param wait_callback: function that wait and potentially updates UI :param update_callback: function that take number of steps completed and return if fitting should be continued
625941bee76e3b2f99f3a732
def RunModel(self): <NEW_LINE> <INDENT> np.random.shuffle(self.pool) <NEW_LINE> data = self.pool[:self.n], self.pool[self.n:] <NEW_LINE> return data
Run the model of the null hypothesis. returns: simulated data
625941be099cdd3c635f0b7e
def start_server(self): <NEW_LINE> <INDENT> self.logger.info("start_server: start") <NEW_LINE> cmdlist = ['start-server'] <NEW_LINE> try: <NEW_LINE> <INDENT> stdout, stderr = self._command_blocking(cmdlist) <NEW_LINE> <DEDENT> except NoDeviceException: <NEW_LINE> <INDENT> raise AdbNoDevice(u'', u'', u'') <NEW_LINE> <DEDENT> except SubprocessException as err: <NEW_LINE> <INDENT> if err.msg == TIMEOUT: <NEW_LINE> <INDENT> raise AdbTimeout(err.msg, err.stdout, err.stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> if u'daemon started successfully' in stdout: <NEW_LINE> <INDENT> self.logger.info("start-server: success") <NEW_LINE> <DEDENT> elif stdout == u'' and stderr == u'': <NEW_LINE> <INDENT> self.logger.warning("start-server: already start") <NEW_LINE> <DEDENT> elif u'starting it now on port' in stdout: <NEW_LINE> <INDENT> self.logger.info("start-server: success") <NEW_LINE> <DEDENT> elif u'failed to start daemon' in stdout: <NEW_LINE> <INDENT> self.logger.error("start-server: fail. {!r}".format(stdout)) <NEW_LINE> raise AdbFailException('Fail start server', stdout, stderr) <NEW_LINE> <DEDENT> elif u'error: ' in stderr: <NEW_LINE> <INDENT> error = self.adb_error_re.search(stderr).group(1) <NEW_LINE> self.logger.error("start-server: error. %s", error) <NEW_LINE> raise AdbFailException(error, stdout, stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.error("start-server: fail with unknown reason, please check stdout/stderr") <NEW_LINE> self.logger.error("stdout: {!r}".format(stdout)) <NEW_LINE> self.logger.error("stderr: {!r}".format(stderr)) <NEW_LINE> raise AdbFailException('Unknown error', stdout, stderr)
Try start adb demon Output: Result (bool) / Reason / stdout / stderr
625941be85dfad0860c3ad7b
def returnPathIfExists(rawfolder, night, runId): <NEW_LINE> <INDENT> path = tree_path(night, runId, rawfolder, ".fits") <NEW_LINE> if os.path.exists(path+".fz"): <NEW_LINE> <INDENT> return path+".fz" <NEW_LINE> <DEDENT> if os.path.exists(path+".gz"): <NEW_LINE> <INDENT> return path+".gz" <NEW_LINE> <DEDENT> return None
Creates a full path for the specific run and test wheater it is an fz or gz file and if it exists
625941bed53ae8145f87a195
def extract_box(self, imgs, l, size): <NEW_LINE> <INDENT> B, C, P, D = imgs.shape <NEW_LINE> imgs = imgs.view(-1, 3, 10000) <NEW_LINE> zooms = [] <NEW_LINE> for i in range(B): <NEW_LINE> <INDENT> im = imgs[i].float() <NEW_LINE> x = l[i][0] <NEW_LINE> y = l[i][1] <NEW_LINE> z = l[i][2] <NEW_LINE> half_extent = size / 2 <NEW_LINE> x_min = x - half_extent <NEW_LINE> y_min = y - half_extent <NEW_LINE> z_min = z - half_extent <NEW_LINE> x_max = x + half_extent <NEW_LINE> y_max = y + half_extent <NEW_LINE> z_max = z + half_extent <NEW_LINE> bool_mask_x = (im[0, :] >= x_min) & (im[0, :] <= x_max) <NEW_LINE> bool_mask_y = (im[1, :] >= y_min) & (im[1, :] <= y_max) <NEW_LINE> bool_mask_z = (im[2, :] >= z_min) & (im[2, :] <= z_max) <NEW_LINE> bool_mask = bool_mask_x & bool_mask_y & bool_mask_z <NEW_LINE> im = im[:, bool_mask] <NEW_LINE> if (im.numel() < self.num_points * 3): <NEW_LINE> <INDENT> num_missing = int(self.num_points - im.numel() // 3) <NEW_LINE> if (num_missing == self.num_points): <NEW_LINE> <INDENT> fill_box = torch.zeros([3, num_missing]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indices = np.random.choice(im.numel() // 3, (num_missing,), replace=True) <NEW_LINE> fill_box = im[:, indices] <NEW_LINE> <DEDENT> if self.use_gpu: <NEW_LINE> <INDENT> fill_box = fill_box.cuda() <NEW_LINE> <DEDENT> im = torch.cat((im, fill_box), -1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> perm = torch.randperm(im.numel() // 3) <NEW_LINE> idx = perm[:self.num_points] <NEW_LINE> im = im[:, idx] <NEW_LINE> <DEDENT> zooms.append(im.view((1, 3, self.num_points))) <NEW_LINE> <DEDENT> glimpse_imgs = torch.stack(zooms) <NEW_LINE> return glimpse_imgs
Extract a single patch for each image in the minibatch `imgs`. Args ---- - x: a 4D Tensor of shape (B, P, D). The minibatch of images. - l: a 2D Tensor of shape (B, 3). - size: a scalar defining the size of the extracted patch. Returns ------- - patch: a 4D Tensor of shape (B, D, num_points, C)
625941be3346ee7daa2b2c8b
def availability(self, duration=300, nodecount=1, nodetype='type:testing', countries=[], nodes=[], model='', start=0): <NEW_LINE> <INDENT> if len(countries) > 0: <NEW_LINE> <INDENT> l = len(countries) <NEW_LINE> c = 1 <NEW_LINE> ret = "" <NEW_LINE> for item in countries: <NEW_LINE> <INDENT> ret += "country:" + item <NEW_LINE> if c < l: <NEW_LINE> <INDENT> ret += "|" <NEW_LINE> <DEDENT> c += 1 <NEW_LINE> <DEDENT> nodetype = ret +', '+ nodetype <NEW_LINE> <DEDENT> if model: <NEW_LINE> <INDENT> nodetype = nodetype + ',' +model <NEW_LINE> <DEDENT> if len(nodes) > 0: <NEW_LINE> <INDENT> nodes = ','.join([str(i) for i in nodes]) <NEW_LINE> endpoint = "/v1/schedules/find?duration=%s&nodecount=%s&nodes=%s&nodetypes=&start=%s" % ( str(duration), str(nodecount),nodes, start) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> endpoint = "/v1/schedules/find?duration=%s&nodecount=%s&nodetypes=%s&start=%s" % ( str(duration), str(nodecount), nodetype, start) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return AvailabilityReport(self.get(endpoint)[0]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return self.get(endpoint)['message']
Produces and submits HTTP query string for given nodecount, duration and nodetype and returns an AvailabilityReport based on the returned response.
625941bed4950a0f3b08c272
def GetAllMetricsMetadata(self): <NEW_LINE> <INDENT> return self._metrics_metadata
Returns dictionary with metadata for all the registered metrics. Note, that the dictionary may get mutated after it's returned to a caller. Mutations are unlikely, though, as most metrics are registered early in the application's lifetime. Returns: Dictionary of (metric name, stats.MetricMetadata).
625941be851cf427c661a433
def train(self, xtrain, batch=1, epochs=1): <NEW_LINE> <INDENT> self.autoencoder.fit(xtrain, xtrain, batch_size=batch, epochs=epochs, verbose=self.verbose, shuffle=True) <NEW_LINE> self.loss += (self.autoencoder.history.history['loss']) <NEW_LINE> self.accuracy += (self.autoencoder.history.history['accuracy'])
Trains the model on the given data set. Arguments: xtrain - (ndarray) Input training data. Keywords: batch - (int) Batch size. defaults to 1. epochs - (int) Number of epochs. defaults to 1.
625941befb3f5b602dac35b2
def sockMerchant(n: int, ar: list[int]) -> int: <NEW_LINE> <INDENT> socksCounter, numPairs = Counter(ar), 0 <NEW_LINE> for color in socksCounter: <NEW_LINE> <INDENT> numPairs += socksCounter[color] // 2 <NEW_LINE> <DEDENT> return numPairs
:param n: The number of socks :param ar: The colors of the socks :return: The number of matching pairs of socks Sample Input: 9 10 20 20 10 10 30 50 10 20 There are 3 pairs of matching socks. (10,10), (20,20), (10,10) Solution: socksCounter: Lists the number of occurrences of each value. Counter({10: 4, 20: 3, 30: 1 , 50: 1}) Use floor division to determine the number of pairs.
625941bef8510a7c17cf961d
def all(self, limit: Optional[int] = None) -> List[Message]: <NEW_LINE> <INDENT> return self.store[:limit][::-1]
Returns all the events, until a limit if defined Args: limit (int, optional): the max length of the events to return (Default value = None) Returns: list: a list of events
625941be851cf427c661a434
def create_policies_with_http_info(self, policy, **kwargs): <NEW_LINE> <INDENT> all_params = ['policy', 'names'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_policies" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> if ('policy' not in params) or (params['policy'] is None): <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `policy` when calling `create_policies`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> if 'names' in params: <NEW_LINE> <INDENT> query_params.append(('names', params['names'])) <NEW_LINE> collection_formats['names'] = 'csv' <NEW_LINE> <DEDENT> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> if 'policy' in params: <NEW_LINE> <INDENT> body_params = params['policy'] <NEW_LINE> <DEDENT> header_params['Accept'] = self.api_client. select_header_accept(['application/json']) <NEW_LINE> header_params['Content-Type'] = self.api_client. select_header_content_type(['application/json']) <NEW_LINE> auth_settings = ['AuthTokenHeader'] <NEW_LINE> return self.api_client.call_api('/1.12/policies', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PolicyResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
Create a new policy. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_policies_with_http_info(policy, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Policy policy: The attribute map used to create the policy. (required) :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :return: PolicyResponse If the method is called asynchronously, returns the request thread.
625941be7d43ff24873a2bc0
def __init__(self, defaults = {}): <NEW_LINE> <INDENT> self._regex = None <NEW_LINE> self._regexIsDirty = True <NEW_LINE> for k,v in defaults.items(): <NEW_LINE> <INDENT> self[k] = v
Initialize the object, and populate it with the entries in the defaults dictionary.
625941be460517430c3940ad
def get_srp_pool_stats(self, array, array_info): <NEW_LINE> <INDENT> total_capacity_gb = 0 <NEW_LINE> remaining_capacity_gb = 0 <NEW_LINE> subscribed_capacity_gb = 0 <NEW_LINE> array_reserve_percent = 0 <NEW_LINE> srp = array_info['srpName'] <NEW_LINE> LOG.debug( "Retrieving capacity for srp %(srpName)s on array %(array)s.", {'srpName': srp, 'array': array}) <NEW_LINE> srp_details = self.rest.get_srp_by_name(array, srp) <NEW_LINE> if not srp_details: <NEW_LINE> <INDENT> LOG.error("Unable to retrieve srp instance of %(srpName)s on " "array %(array)s.", {'srpName': srp, 'array': array}) <NEW_LINE> return 0, 0, 0, 0, False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> total_capacity_gb = srp_details['total_usable_cap_gb'] <NEW_LINE> try: <NEW_LINE> <INDENT> used_capacity_gb = srp_details['total_used_cap_gb'] <NEW_LINE> remaining_capacity_gb = float( total_capacity_gb - used_capacity_gb) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> remaining_capacity_gb = srp_details['fba_free_capacity'] <NEW_LINE> <DEDENT> subscribed_capacity_gb = srp_details['total_subscribed_cap_gb'] <NEW_LINE> array_reserve_percent = srp_details['reserved_cap_percent'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return (total_capacity_gb, remaining_capacity_gb, subscribed_capacity_gb, array_reserve_percent)
Get the srp capacity stats. :param array: the array serial number :param array_info: the array dict :returns: total_capacity_gb :returns: remaining_capacity_gb :returns: subscribed_capacity_gb :returns: array_reserve_percent
625941be0c0af96317bb810a
def test_u_to_b(self): <NEW_LINE> <INDENT> enc_text = morphys.ensure_bytes(self.__u_text) <NEW_LINE> self.assertEqual(enc_text, self.__b_text)
ensure_bytes uses the changed default encoding.
625941bebde94217f3682d15
@with_nice_docs <NEW_LINE> def CHOICE(arbiter, *predicates, **kwpredicates): <NEW_LINE> <INDENT> workflow = [] <NEW_LINE> mapping = {} <NEW_LINE> for branch in predicates: <NEW_LINE> <INDENT> workflow.append(branch[1:]) <NEW_LINE> mapping[branch[0]] = len(workflow) <NEW_LINE> workflow.append(BREAK()) <NEW_LINE> <DEDENT> for k, v in kwpredicates.items(): <NEW_LINE> <INDENT> workflow.append(v) <NEW_LINE> mapping[k] = len(workflow) <NEW_LINE> workflow.append(BREAK()) <NEW_LINE> <DEDENT> def _exclusive_choice(obj, eng): <NEW_LINE> <INDENT> val = arbiter(obj, eng) <NEW_LINE> i = mapping[val] <NEW_LINE> eng.jump_call(i) <NEW_LINE> <DEDENT> c = _exclusive_choice <NEW_LINE> c.__name__ = arbiter.__name__ <NEW_LINE> workflow.insert(0, c) <NEW_LINE> return workflow
A choice is made to execute either task B, task C or task D after execution of task A. :param arbiter: a function which returns some value (the value must be inside the predicates dictionary) :param predicates: list of callables, the first item must be the value returned by the arbiter, example: ('submit', task_a), ('upload' : task_a, [task_b, task_c]...) :param **kwpredicates: you can supply predicates also as a keywords, example CHOICE(arbiter, one=lambda...., two=[lambda o,e:...., ...]) @postcondition: all tasks are 'jumpable'
625941be50485f2cf553ccba
def get_variable(self): <NEW_LINE> <INDENT> return self._var_names
Returns the variable(s) in use for this placeholder. @ In, None @ Out, var_names, list, variable names
625941be925a0f43d2549d96
def _calc_wire_len(self): <NEW_LINE> <INDENT> hpwl = 0 <NEW_LINE> for net in self.nets: <NEW_LINE> <INDENT> hpwl += net.calc_length() <NEW_LINE> <DEDENT> return hpwl
Calculate cost in terms of area and wire length.
625941bed10714528d5ffc02
def __init__(self, filename, mode="r", format=None): <NEW_LINE> <INDENT> filename = path.normpath(filename) <NEW_LINE> if not (mode == "r" or mode == "w"): <NEW_LINE> <INDENT> raise Exception("Unsupported mode %s" % (mode)) <NEW_LINE> <DEDENT> if mode == "r" and not path.isfile(filename): <NEW_LINE> <INDENT> raise Exception("File '%s' does not exist" % (filename)) <NEW_LINE> <DEDENT> if mode == "w": <NEW_LINE> <INDENT> dir = path.dirname(filename) <NEW_LINE> if dir != "" and not path.isdir(path.dirname(filename)): <NEW_LINE> <INDENT> os.makedirs(dir) <NEW_LINE> <DEDENT> <DEDENT> if format is None: <NEW_LINE> <INDENT> format = detect(filename) <NEW_LINE> <DEDENT> if format == "bzip2": <NEW_LINE> <INDENT> self.handle = bz2.BZ2File(filename, mode) <NEW_LINE> <DEDENT> elif format == "gzip": <NEW_LINE> <INDENT> self.handle = gzip.GzipFile(filename, mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.handle = open(filename, mode + "b") <NEW_LINE> <DEDENT> self.filename = filename <NEW_LINE> self.format = format <NEW_LINE> self.mode = mode <NEW_LINE> self.closed = False
Load an appropriate file compression descriptor for the given filename and read/write access mode.
625941be8e71fb1e9831d6cc
def process(self): <NEW_LINE> <INDENT> temp = [0] * self.dimensions <NEW_LINE> for i, count in enumerate(self.data['pitches.pitchClassHistogram']): <NEW_LINE> <INDENT> temp[i] = count <NEW_LINE> <DEDENT> m = temp.index(max(temp)) <NEW_LINE> for i, val in enumerate(temp): <NEW_LINE> <INDENT> self.feature.vector[(i - m) % self.dimensions] = val
Do processing necessary, storing result in feature.
625941be8da39b475bd64e92
def set(isamAppliance, hvdb_db_type=None, hvdb_address=None, hvdb_port=None, hvdb_user=None, hvdb_password=None, hvdb_db2_alt_address=None, hvdb_db2_alt_port=None, hvdb_db_name=None, hvdb_db_secure=None, hvdb_driver_type=None, hvdb_solid_tc=None, check_mode=False, force=False): <NEW_LINE> <INDENT> warnings = [] <NEW_LINE> service_json = {} <NEW_LINE> if hvdb_db_type is not None: <NEW_LINE> <INDENT> service_json["hvdb_db_type"] = hvdb_db_type <NEW_LINE> <DEDENT> if hvdb_address is not None: <NEW_LINE> <INDENT> service_json["hvdb_address"] = hvdb_address <NEW_LINE> <DEDENT> if hvdb_port is not None: <NEW_LINE> <INDENT> service_json["hvdb_port"] = hvdb_port <NEW_LINE> <DEDENT> if hvdb_user is not None: <NEW_LINE> <INDENT> service_json["hvdb_user"] = hvdb_user <NEW_LINE> <DEDENT> if hvdb_password is not None: <NEW_LINE> <INDENT> warnings.append("Since existing hvdb_password cannot be read - this call will not be idempotent.") <NEW_LINE> service_json["hvdb_password"] = hvdb_password <NEW_LINE> <DEDENT> if hvdb_db2_alt_address is not None: <NEW_LINE> <INDENT> service_json["hvdb_db2_alt_address"] = hvdb_db2_alt_address <NEW_LINE> <DEDENT> if hvdb_db2_alt_port is not None: <NEW_LINE> <INDENT> service_json["hvdb_db2_alt_port"] = hvdb_db2_alt_port <NEW_LINE> <DEDENT> if hvdb_db_name is not None: <NEW_LINE> <INDENT> service_json["hvdb_db_name"] = hvdb_db_name <NEW_LINE> <DEDENT> if hvdb_db_secure is not None: <NEW_LINE> <INDENT> service_json["hvdb_db_secure"] = hvdb_db_secure <NEW_LINE> <DEDENT> if hvdb_driver_type is not None: <NEW_LINE> <INDENT> service_json["hvdb_driver_type"] = hvdb_driver_type <NEW_LINE> <DEDENT> if hvdb_solid_tc is not None: <NEW_LINE> <INDENT> if (isinstance(hvdb_solid_tc, basestring)): <NEW_LINE> <INDENT> import ast <NEW_LINE> hvdb_solid_tc = ast.literal_eval(hvdb_solid_tc) <NEW_LINE> service_json["hvdb_solid_tc"] = hvdb_solid_tc <NEW_LINE> <DEDENT> <DEDENT> if force is True or _check(isamAppliance, service_json) is False: <NEW_LINE> <INDENT> if check_mode is True: <NEW_LINE> <INDENT> return isamAppliance.create_return_object(changed=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return isamAppliance.invoke_post("Set service configuration", uri, service_json, requires_modules=requires_modules, requires_version=requires_version, warnings=warnings) <NEW_LINE> <DEDENT> <DEDENT> return isamAppliance.create_return_object()
Set service configuration
625941be796e427e537b04e5
def getBlockSize(self): <NEW_LINE> <INDENT> return (self.blockwidth,self.blockheight)
Get the size of the current block. Returns a tuple:: (numCols, numRows) for the current block. Mostly the same as the window size, except on the edge of the raster.
625941be76d4e153a657ea52
def text_scraper_cleaner(): <NEW_LINE> <INDENT> pass
cleans text scraped from html for NLP
625941be627d3e7fe0d68d70
def if_it_is_by(row): <NEW_LINE> <INDENT> by_set = {'by'} <NEW_LINE> return 1 if row.tokens.lower() in by_set else 0
Return true if all characters in the string are digits and there is at least one character, false otherwise. str.isdigit():
625941be460517430c3940ae
def get_random_structure(self, bin_range): <NEW_LINE> <INDENT> from random import choice <NEW_LINE> db = connect(self.db_bin_data) <NEW_LINE> candidates = [] <NEW_LINE> scond = [("bin_indx", ">", bin_range[0]), ("bin_indx", "<", bin_range[1])] <NEW_LINE> for row in db.select(scond): <NEW_LINE> <INDENT> candidates.append(row.toatoms()) <NEW_LINE> <DEDENT> if not candidates: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return choice(candidates)
Return a structure from the DB.
625941be462c4b4f79d1d5f2
def getInsertSQL(context,dic): <NEW_LINE> <INDENT> sql = "" <NEW_LINE> for item in context: <NEW_LINE> <INDENT> if not item[0] in dic: <NEW_LINE> <INDENT> sql += '("%s","%s","%s","%s","%s","%s","%s","%s","%s"),' % tuple(item) <NEW_LINE> <DEDENT> <DEDENT> if sql == "": <NEW_LINE> <INDENT> return sql <NEW_LINE> <DEDENT> sql = '''insert into info_list values ''' + sql[:-1] <NEW_LINE> return sql
:param context: type list :param dic: type dict, with approve_id :return: list
625941be187af65679ca5040
def regexp_extract(pattern, method=re.match, group=1): <NEW_LINE> <INDENT> def regexp_extract_lambda(value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> matches = method(pattern, value) <NEW_LINE> if not matches: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return matches.group(group) <NEW_LINE> <DEDENT> return regexp_extract_lambda
Returns the string that matches the specified group in the regex pattern. Args: pattern: A regular expression to match on with at least one group. method: The method to use for matching; normally re.match (the default) or re.search. group: The group to use for extracting a value; the first group by default. Returns: A single-argument function that returns the string that matches the specified group in the pattern, or None if no match was found or the input was empty.
625941bea05bb46b383ec746
def parse_args(self, ctx, args): <NEW_LINE> <INDENT> if args and args[0] in self.commands: <NEW_LINE> <INDENT> args.insert(0, '') <NEW_LINE> <DEDENT> super(OptionalGroup, self).parse_args(ctx, args)
Check if the first argument is an existing command.
625941bed268445f265b4d90