code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def output_action_with_type(self, data, action_type, **kwargs): <NEW_LINE> <INDENT> state = [] <NEW_LINE> state.extend(data['filter_counts_list']) <NEW_LINE> state.extend(data['binned_data_dist']) <NEW_LINE> self.verbose_logger.info('Data for (Depth Index,DistMSE,Filter Count) %s\n' % str(state)) <NEW_LINE> history_t_p...
Output action acording to one of the below methods Explore: action during the exploration (network growth and netowrk shrinkage) Deterministic: action with highest q value Stochastic: action in a stochastic manner :param data: :return:
625941ebadb09d7d5db6cc84
def analyzeData(ListData): <NEW_LINE> <INDENT> newData = np.array(ListData) <NEW_LINE> npMean, stdev, rangeVal, median = 0,0,0,0 <NEW_LINE> if len(newData) > 0: <NEW_LINE> <INDENT> rangeVal = np.ptp(newData) <NEW_LINE> median = np.median(newData) <NEW_LINE> npMean = np.mean(newData) <NEW_LINE> stdev = np.std(newData) <...
simple function that returns mean, median, mode, stdDev as a tuple
625941eba8370b7717052d95
def set_hh_file(h): <NEW_LINE> <INDENT> if h == '400': <NEW_LINE> <INDENT> household_file = 'hh_ascii400.txt' <NEW_LINE> <DEDENT> elif h == '800': <NEW_LINE> <INDENT> household_file = 'hh_ascii800.txt' <NEW_LINE> <DEDENT> elif h == '100': <NEW_LINE> <INDENT> household_file = 'hh_ascii100.txt' <NEW_LINE> <DEDENT> return...
Sets size of human settlement
625941eb0a50d4780f66738e
def ShapeVar(name): <NEW_LINE> <INDENT> return TypeVar(name, kind=Kind.ShapeVar)
A helper which constructs a type var of which the shape kind. Parameters ---------- name : str Returns ------- type_var : tvm.relay.TypeVar The shape variable.
625941ebd58c6744b4258155
def execute(self, return_only=False): <NEW_LINE> <INDENT> start_time = datetime.datetime.now().strftime("%y-%m-%d") <NEW_LINE> def track_progress(job, update_interval=60): <NEW_LINE> <INDENT> while job._number_left > 0: <NEW_LINE> <INDENT> logging.info("Tasks remaining = {0}".format( job._number_left * job._chunksize )...
This method will start multiprocessing execution of this class. :param return_only: Whether to return the results as a variabel (True) or write to file (False) :type return_only: bool :return: list of lists if :attribute: `return_only` False otherwise None :rtype: list or None
625941eb31939e2706e4d35a
def _read_tweets(self, stream): <NEW_LINE> <INDENT> tweets = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> line = stream.readline() <NEW_LINE> if not line: <NEW_LINE> <INDENT> return tweets <NEW_LINE> <DEDENT> tweet = json.loads(line) <NEW_LINE> tweets.append(tweet) <NEW_LINE> <DEDENT> return tweets
Assumes that each line in ``stream`` is a JSON-serialised object.
625941eb656771135c3ebd6c
def softmax(theta, x): <NEW_LINE> <INDENT> prob_matrix = np.exp(np.dot(theta, x.T)) <NEW_LINE> nomalized = prob_matrix / np.sum(prob_matrix, axis=0) <NEW_LINE> return nomalized
Args: theta: theta.shape == (n_class, n_features) x: x.shape == (n_samples, n_features) Return: normalized probabilty matrix
625941ebcc0a2c11143dd389
def test_train(self, dummy_folder): <NEW_LINE> <INDENT> assert clusterer.DocumentClusterer( encoder.DocumentEncoder().train(dummy_folder) ).train(dummy_folder)
Test training the class :return None:
625941eb046cf37aa974d23a
def get_request_header(request, header): <NEW_LINE> <INDENT> value = request.headers.get(header, "").strip() <NEW_LINE> if value == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return value
Given a header, it returns a cleaned up version of the value from request.headers, or None
625941eb6fb2d068a760f59d
def compute_live_map(cfg, blocks, var_use_map, var_def_map): <NEW_LINE> <INDENT> def fix_point_progress(dct): <NEW_LINE> <INDENT> return tuple(len(v) for v in dct.values()) <NEW_LINE> <DEDENT> def fix_point(fn, dct): <NEW_LINE> <INDENT> old_point = None <NEW_LINE> new_point = fix_point_progress(dct) <NEW_LINE> while ol...
Find variables that must be alive at the ENTRY of each block. We use a simple fix-point algorithm that iterates until the set of live variables is unchanged for each block.
625941ebd58c6744b4258156
def execution_abort(self, execution_id, **kwargs): <NEW_LINE> <INDENT> params = cull_kwargs(('asUser',), kwargs) <NEW_LINE> return self._exec(GET, 'execution/{0}/abort'.format(execution_id), params=params, **kwargs)
Wraps `Rundeck API GET /execution/[ID]/output <http://rundeck.org/docs/api/index.html#execution-output>`_ :Parameters: execution_id : str Rundeck Job Execution ID :Keywords: asUser : str specifies a username identifying the user who aborted the execution :return: A Requests response :rtype: r...
625941ebfbf16365ca6f66c6
def add_to_path(cell): <NEW_LINE> <INDENT> maze.mark_cell(cell, Maze.PATH) <NEW_LINE> maze.mark_space(maze.loop_erased_walk_path[-1], cell, Maze.PATH) <NEW_LINE> maze.loop_erased_walk_path.append(cell)
Add a cell to the path of current random walk.
625941eb7b180e01f3dc4ceb
def init_update_datasets_flow(): <NEW_LINE> <INDENT> with Flow("TriggerUpdateCombinedDatasets") as flow: <NEW_LINE> <INDENT> github_token = PrefectSecret("GITHUB_ACTION_PAT") <NEW_LINE> make_request(github_token=github_token) <NEW_LINE> <DEDENT> flow.register("can-scrape")
Initialize a flow to kick off the covid-data-model Update Combined Datasets Github action
625941ebd99f1b3c44c67a7d
def test_basic(): <NEW_LINE> <INDENT> dm, tau = pygedm.dist_to_dm(204, -6.5, 25*u.kpc, method='ne2001') <NEW_LINE> assert np.isclose(dm.value, 150.80, atol=0.01) <NEW_LINE> for dist in (10.*u.pc, 100.*u.pc, 1000.*u.pc): <NEW_LINE> <INDENT> dm, tau = pygedm.dist_to_dm(0, 0, dist, method='ne2001') <NEW_LINE> dist_out, ta...
Basic tests of YMW16 model Note: tested against online NE2001 interface https://www.nrl.navy.mil/rsd/RORF/ne2001/
625941eb236d856c2ad44cd9
def GetWaveTime(self, staNo, chnNo): <NEW_LINE> <INDENT> wave_time_key = 'WaveTime'; <NEW_LINE> wave_time_field = self.channel_list[staNo][chnNo]['network'] + '.' + self.channel_list[staNo][chnNo][ 'station'] + '.' + self.channel_list[staNo][chnNo]['channel'] + '.' + self.channel_list[staNo][ch...
读取redis中指定台站编号、通道编号的波形开始时间与结束时间,读取失败返回-1
625941eb56ac1b37e62646bd
def prettify_xml(xml_root): <NEW_LINE> <INDENT> xml_string = etree.tostring(xml_root, encoding="utf-8", xml_declaration=True, pretty_print=True) <NEW_LINE> return get_unicode_str(xml_string)
Return pretty-printed string representation of element tree.
625941ebff9c53063f47c6e9
def setGraphicsWidget(self, widget): <NEW_LINE> <INDENT> pass
void Plasma.Dialog.setGraphicsWidget(QGraphicsWidget widget)
625941eb4e696a04525c9945
def autoconf(self): <NEW_LINE> <INDENT> serverInfo = MemcachedInfo(self._host, self._port) <NEW_LINE> return (serverInfo is not None)
Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise.
625941eb67a9b606de4a83af
def parse_input(fname): <NEW_LINE> <INDENT> inputs = np.loadtxt(fname, delimiter=',', dtype=str, encoding=None) <NEW_LINE> return (inputs[1:,0], np.delete(inputs,0,axis=1).astype(float))
Read a CSV file and return a tuple containing the t sats([0]) and std values([1]) Keyword arguments: fname -- the file name to use as input (str)
625941ebdc8b845886cb5a2f
def k2alpha(data): <NEW_LINE> <INDENT> assert 'alpha' not in data.dtype.names <NEW_LINE> assert 'wavelength' in data.dtype.names <NEW_LINE> names = list(data.dtype.names) <NEW_LINE> for name in data.dtype.names: <NEW_LINE> <INDENT> if 'k_' in name: <NEW_LINE> <INDENT> suffix = name.strip('k') <NEW_LINE> print(name, 'al...
appends array with the wavelength data data is required to have the headings: 'energy' and 'alpha'
625941eb442bda511e8be909
def index(request): <NEW_LINE> <INDENT> return render(request, 'leaning_logs/index.html')
Домашняя страница проложения
625941ebfb3f5b602dac3b90
def predict_ovr(estimators, label_binarizer, X): <NEW_LINE> <INDENT> Y = np.array([_predict_binary(e, X) for e in estimators]) <NEW_LINE> e = estimators[0] <NEW_LINE> thresh = 0 if hasattr(e, "decision_function") and is_classifier(e) else .5 <NEW_LINE> return label_binarizer.inverse_transform(Y.T, threshold=thresh)
Make predictions using the one-vs-the-rest strategy.
625941eb91f36d47f21ac9f0
def prepare(self, sess, sample_fn): <NEW_LINE> <INDENT> self.sess = sess <NEW_LINE> self.sample_fn = sample_fn <NEW_LINE> self._op = self.queue.enqueue_many(self.inputs)
Prepare for run Args: sess: Tensorflow session sample_fn: Function to draw one sample from data
625941eb1f5feb6acb0c5041
def _generate_complex_qegt_random_codebook(self, K, Nt, Ns): <NEW_LINE> <INDENT> C = self._rs.rand(K, Nt, Ns) * np.pi <NEW_LINE> C = np.exp(1j * C) <NEW_LINE> return C
Generates a complex Quantized Equal Gain Transmission random codebook. Parameters ---------- K : int Number of precoders in the codebook Nt : int Number of rows (transmit antennas) in each precoder Ns : int Number of columns (number of streams) in each precoder
625941eb23849d37ff7b3583
def test_ip_merge(self): <NEW_LINE> <INDENT> args = BootLoaderArguments() <NEW_LINE> args.update(["start", "blah"]) <NEW_LINE> args.update(["ip=ens0p3:dhcp6", "ip=::::tester::dhcp", "ip=ens0p3:dhcp"]) <NEW_LINE> args.add("end") <NEW_LINE> assert list(args) == ["start", "blah", "ip=ens0p3:dhcp6", "ip=::::test...
BootLoaderArguments.__str__ reorders ip= as expected.
625941eb8e7ae83300e4b4c7
def invalidate( func, *args, **kwargs ) : <NEW_LINE> <INDENT> cachemgr = h.fromconfig( 'cachemgr' ) <NEW_LINE> cachenm = cachemgr.get_cache( func._namespace, **func._kwargs ) <NEW_LINE> clearall = kwargs.pop( 'clearall', False ) <NEW_LINE> if clearall : <NEW_LINE> <INDENT> cachenm.clear() <NEW_LINE> <DEDENT> else : <N...
Invalidate the cache for the namespace for function 'func'. If 'useargs' was True while 'cache'ing the function, then provide the same 'args' (positional parameter) that was used while calling the decorated function.
625941eb01c39578d7e75333
def load(self, data, areaNum, progress=None): <NEW_LINE> <INDENT> super().load(data, areaNum, progress) <NEW_LINE> global Area <NEW_LINE> arc = SarcLib.SARC_Archive() <NEW_LINE> arc.load(data) <NEW_LINE> try: <NEW_LINE> <INDENT> courseFolder = arc['course'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <...
Loads a NSMBU level from bytes data.
625941ebb57a9660fec33d83
def get_user(self, context, username, hostname): <NEW_LINE> <INDENT> results = pgutil.query( pgutil.UserQuery.get(name=username), timeout=30, ) <NEW_LINE> results = tuple(results) <NEW_LINE> if len(results) < 1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return { "_name": results[0][0], "_host": None, "_passwo...
Return a single user matching the criteria. The username and hostname parameter are strings. The return value is a dictionary in the following form: {"_name": "", "_host": None, "_password": None, "_databases": [{"_name": ""}, ...]} Where "_databases" is a list of databases the user has access to.
625941ebe76e3b2f99f3acfb
def test_normalize_page_data_on_prev(self): <NEW_LINE> <INDENT> proxy = ProxyPaginator( self.paginator, normalize_page_data_func=lambda data: list(reversed(data))) <NEW_LINE> self.paginator.prev_url = 'http://example.com/?page=1' <NEW_LINE> data = proxy.prev() <NEW_LINE> self.assertEqual(data, [3, 2, 1])
Testing ProxyPaginator.normalize_page_data on prev
625941ebbd1bec0571d90b27
def runall(self, fvf_params=None): <NEW_LINE> <INDENT> np.random.seed(self.seed) <NEW_LINE> results = {} <NEW_LINE> for search_type in self.task_difficulties: <NEW_LINE> <INDENT> print(f'Running trials for task_difficulty {search_type}') <NEW_LINE> for display_size in self.display_sizes: <NEW_LINE> <INDENT> print(f'\tR...
run trials for all possible permutations of conditions Parameters ---------- fvf_params : dict of parameters for FVFModel, where key is parameter name, and value is the value to pass to FVFModel when creating an instance of the model. Default is None, in which case defaults for model are used. Returns ---...
625941eb0c0af96317bb86e0
def rotate(text, key): <NEW_LINE> <INDENT> cipher_alphabet = DOUBLE_ALPHABET[key:(key + 26)] <NEW_LINE> rotated = '' <NEW_LINE> for char in text: <NEW_LINE> <INDENT> if char.isalpha() is False: <NEW_LINE> <INDENT> rotated += char <NEW_LINE> continue <NEW_LINE> <DEDENT> address = ALPHABET.index(char.lower()) <NEW_LINE> ...
Given a piece of text, return a version of it rotate, like on a ceasar cipher.
625941ebb545ff76a891430e
def test_sort(self): <NEW_LINE> <INDENT> self.python_file.sort() <NEW_LINE> i = 1 <NEW_LINE> while i<len(self.python_file._classes): <NEW_LINE> <INDENT> self.assertTrue(self.python_file._classes[i]._name >= self.python_file._classes[i-1]._name) <NEW_LINE> i+=1
Object method. Params: None Return: None This method tests the behaviour of the sort Method. It calls sort and verifies that the classes list is sorted by alphabetic order.
625941eb7047854f462a18fc
def __verify_manifest_sig(self, repo, pfmri, content): <NEW_LINE> <INDENT> sm = pkg.manifest.Manifest(pfmri=pfmri) <NEW_LINE> sm.set_content(pathname=repo.manifest(pfmri), signatures=True) <NEW_LINE> if isinstance(content, basestring): <NEW_LINE> <INDENT> dm = pkg.manifest.Manifest() <NEW_LINE> dm.set_content(content=c...
Helper method to verify that the given manifest signature data matches that of the corresponding manifest in a repository.
625941ebd10714528d6001e1
def movement(self): <NEW_LINE> <INDENT> for n in reversed(range(1, len(self.x_var))): <NEW_LINE> <INDENT> self.x_var['x{}'.format(n)] = self.x_var['x{}'.format(n - 1)] <NEW_LINE> self.y_var['y{}'.format(n)] = self.y_var['y{}'.format(n - 1)] <NEW_LINE> <DEDENT> if self.MOVE == 'UP': <NEW_LINE> <INDENT> self.y_var['y0'] ...
Move the snake.
625941ebb57a9660fec33d84
def switch_power_socket(sender_path, channel, button, action): <NEW_LINE> <INDENT> sleep_time = 2 <NEW_LINE> loops = 2 <NEW_LINE> cmd = ["/usr/bin/sudo", sender_path, "-c", str(channel), "-b", str(button), action] <NEW_LINE> try: <NEW_LINE> <INDENT> for _ in range(loops): <NEW_LINE> <INDENT> logging.debug("Setting chan...
Does the grunt work of calling strogonanoff_sender.py Builds an array of strings to pass to Popen. Currently needs NOPASSWD sudo access to interact with /dev/mem.
625941ebcdde0d52a9e53530
def call_for_nodes(node, callback, recursive=False): <NEW_LINE> <INDENT> result = callback(node) <NEW_LINE> if recursive and not result: <NEW_LINE> <INDENT> for child in get_child_nodes(node): <NEW_LINE> <INDENT> call_for_nodes(child, callback, recursive)
If callback returns `True` the child nodes are skipped
625941eb498bea3a759b9fa6
def testOrientedGlyphs(self): <NEW_LINE> <INDENT> f = self.gui.loaded_fields()[0] <NEW_LINE> visualiser=self.gui.vector_visualiser(self.gui.master,self.gui,f) <NEW_LINE> visualiser.show_orientedglyphs = 1 <NEW_LINE> self.gui.visualise(f,visualiser,open_widget=1) <NEW_LINE> visualiser.Delete()
Test the Oriented Glyphs vector plot
625941ebe8904600ed9f242e
def DelDataPlaneCPUUtilization(asg_name): <NEW_LINE> <INDENT> logger.info('Deleting dataPlane CPU High CloudWatch alarm for ASG: ' + asg_name) <NEW_LINE> alarmname= asg_name + '-cw-cpu' <NEW_LINE> common_alarm_func_del(alarmname) <NEW_LINE> return
Method to delete the DataPlaneCPUUtilization Alarm. This alarm will trigger when the Data Plane CPU Utilization exceeds the specified threshold. :param asg_name: Name of the ASG :return: None
625941ebd164cc6175783248
def SetCredentials(self, username, password): <NEW_LINE> <INDENT> self.__docs_client.email = username <NEW_LINE> self.__docs_client.password = password <NEW_LINE> self.__spreadsheets_client.email = username <NEW_LINE> self.__spreadsheets_client.password = password <NEW_LINE> if username and password: <NEW_LINE> <INDENT...
Attempts to log in to Google APIs using the provided credentials. If the username or password are None, the client will not request auth tokens. Args: username: str (optional) Example: jo@example.com password: str (optional)
625941eb10dbd63aa1bd309a
def set_count(self, morph, new_count): <NEW_LINE> <INDENT> if self._marginalizer is not None and self.count(morph) > 0: <NEW_LINE> <INDENT> self._marginalizer.add(-self.count(morph), self.condprobs(morph)) <NEW_LINE> <DEDENT> self._contexts[morph] = self._contexts[morph]._replace(count=new_count) <NEW_LINE> assert self...
Set the number of observed occurences of a morph. Also updates the true category distribution.
625941ebc4546d3d9de72f31
def format_date (date_object, month_only=False): <NEW_LINE> <INDENT> if month_only: <NEW_LINE> <INDENT> return date_object.strftime("%Y-%m") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return date_object.strftime("%Y-%m-%d")
Normalise a date to YYYY-MM-DD (ISO 8601)
625941eb63b5f9789fde75df
def __init__(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self._rightRotAssignment = (0, 21, 2, 23, 6, 4, 7, 5, 19, 9, 17, 11, 12, 13, 14, 15, 16, 1, 18, 3, 20, 10, 22, 8) <NEW_LINE> self._frontRotAssignment = (2, 0, 3, 1, 18, 5, 19, 7, 8, 9, 10, 11, 12, 20, 14, 21, 16, 17, 15, 13, 6, 4, 22, 23) <NEW...
The state should be a string of length 24 with 6 unique identifiers. The first four characters represent the front face, then the next four the right, then back, left, up, and down.
625941eba8370b7717052d96
def get_activity(): <NEW_LINE> <INDENT> scheduled_event = events[event.scheduled_event_id - 1] <NEW_LINE> return self._activities[scheduled_event.activity_id]
Return a reference to the corresponding activity. :return: mutable activity :rtype: dict[str, Any]
625941eb2eb69b55b151cdaf
def write(self, cr, uid, ids, values, context=None): <NEW_LINE> <INDENT> for prod_template in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> if ('list_price' in values and prod_template.list_price != values['list_price']) or ('standard_price' in values and prod_template.standard_price != ...
Add old Sale Price or Sale Cost to historial
625941eb596a897236089fb2
def get_string_onset(edge): <NEW_LINE> <INDENT> onset_label = edge.find('labels[@name="SSTART"]') <NEW_LINE> onset_str = onset_label.xpath('@valueString')[0] <NEW_LINE> return int(onset_str)
return the onset (int) of a string
625941eba79ad161976cc63e
def specialize(self, rule): <NEW_LINE> <INDENT> is_unary = lambda p: isinstance(p, UnaryPredicate) <NEW_LINE> def specialize_optimal_subclass(rule): <NEW_LINE> <INDENT> rules = [] <NEW_LINE> eligible_preds = rule.shared_var[rule.latest_var] <NEW_LINE> for pred in filter(is_unary, eligible_preds): <NEW_LINE> <INDENT> fo...
Returns a list of all specializations of 'rule'.
625941eb099cdd3c635f1151
def enable_ovdc_for_k8s(self, ovdc_name, k8s_provider=None, pks_plan=None, pks_cluster_domain=None, org_name=None): <NEW_LINE> <INDENT> method = 'PUT' <NEW_LINE> ovdc = get_vdc(self.client, ovdc_name, org_name=org_name, is_admin_operation=True) <NEW_LINE> ovdc_id = utils.extract_id(ovdc.resource.get('id')) <NEW_LINE> u...
Enable ovdc for k8s for the given container provider. :param str ovdc_name: Name of the ovdc to be enabled :param str k8s_provider: Name of the container provider :param str pks_plan: PKS plan :param str pks_cluster_domain: Suffix of the domain name, which will be used to construct FQDN of the clusters. :param str or...
625941ebac7a0e7691ed45bb
def dwd_airmass(self, backup_orig_data=False): <NEW_LINE> <INDENT> self.check_channels(6.7, 7.3, 9.7, 10.8) <NEW_LINE> if not self._dwd_channel_preparation([6.7, 7.3, 9.7, 10.8], backup_orig_data=backup_orig_data): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ch1 = self[6.7].data - self[7.3].data <NEW_LINE> ch2 ...
Make a DWD specific RGB image composite. +--------------------+--------------------+--------------------+ | Channels | Span | Gamma | +====================+====================+====================+ | WV6.2 - WV7.3 | -25 to 0 K | gamma 1 | +------------------...
625941eb94891a1f4081bfa4
def logposterior(self, params): <NEW_LINE> <INDENT> fep, vcp, vc = self._unpack(params) <NEW_LINE> lp = 0 <NEW_LINE> if self.k_fep > 0: <NEW_LINE> <INDENT> lp += np.dot(self.exog_fe, fep) <NEW_LINE> <DEDENT> if self.k_vc > 0: <NEW_LINE> <INDENT> lp += self.exog_vc.dot(vc) <NEW_LINE> <DEDENT> mu = self.family.link.inver...
The overall log-density: log p(y, fe, vc, vcp). This differs by an additive constant from the log posterior log p(fe, vc, vcp | y).
625941eb21a7993f00bc81f2
def SMA_batch_compute(data_series,n_period_compute,comp_mode='loop'): <NEW_LINE> <INDENT> assert type(data_series).__module__ == np.__name__ <NEW_LINE> if not isinstance(n_period_compute, list): <NEW_LINE> <INDENT> raise ValueError('Batch computation method only permit list as input!') <NEW_LINE> <DEDENT> n_len_return ...
:param data_series: The time series data with length [m*t] :param n_period_compute: The length n one would like to care for the computation. Should be a list, if it is this case return [m * len]. Even if the length of list is 1 :param comp_mode: should be either 'loop' or 'vector', whether to use vectorized com...
625941eb4a966d76dd55150d
def test_bad_start_because_path_not_writable(): <NEW_LINE> <INDENT> unix = '/root/r_unix' <NEW_LINE> receiver = SMSShell.receivers.unix.Receiver(config=dict(path=unix)) <NEW_LINE> assert not receiver.start()
Ensure receiver do not start correctly if path is not writable
625941eb5166f23b2e1a5652
def start(self): <NEW_LINE> <INDENT> self.correlation_map = dict() <NEW_LINE> self.correlation_indices = None
Build an empty correlation map
625941eba05bb46b383ecd16
def shwrite(filename, coeffs, errors=None, header=None, header2=None, lmax=None): <NEW_LINE> <INDENT> if lmax is None: <NEW_LINE> <INDENT> lmax = coeffs.shape[1] - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if lmax > coeffs.shape[1] - 1: <NEW_LINE> <INDENT> raise ValueError('lmax is greater than the input coeffici...
Write shtools-formatted spherical harmonic coefficients to a text file. Usage ----- shwrite(filename, coeffs, [errors, header, header2, lmax]) Parameters ---------- filename : str File name of the shtools-formatted spherical harmonic coefficients. If filename ends with '.gz' the file will be automatically com...
625941eb7047854f462a18fd
def test_tmpdir(self): <NEW_LINE> <INDENT> tmpdir = mkdtemp(dir="/tmp", prefix=".sandbox_test") <NEW_LINE> p = Popen(['sandbox', '-T', tmpdir, '-M', 'id'], stdout=PIPE, stderr=PIPE) <NEW_LINE> out, err = p.communicate() <NEW_LINE> shutil.rmtree(tmpdir) <NEW_LINE> self.assertSuccess(p.returncode, err)
Verify that we set tmpdir a file system
625941eb1f037a2d8b9466f6
def test_compare16(): <NEW_LINE> <INDENT> hand = poker.PokerHand('8H 8D 4C 4D TS') <NEW_LINE> other = poker.PokerHand('8S 8C 4S 4H TD') <NEW_LINE> assert (hand.compare_with(other) == 'Tie')
Testing two pair tie
625941eb6aa9bd52df0372a0
def _get_qty_price(self, qty): <NEW_LINE> <INDENT> qty_discounts = self.price_set.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=qty) <NEW_LINE> if qty_discounts.count() > 0: <NEW_LINE> <INDENT> return qty_discounts.order_by('-quantity')[0].price <NEW_LINE> <DEDENT> else: <NEW_LI...
returns price as a Decimal
625941eb9f2886367277ad82
def test_datefield_auto_now_add(self): <NEW_LINE> <INDENT> b = RumBaba.objects.create() <NEW_LINE> self.assertIsInstance(b.baked_timestamp, datetime.datetime) <NEW_LINE> self.assertIsInstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime)
Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime
625941eb8c3a8732951588ba
def swap(self, first_coor, second_coor): <NEW_LINE> <INDENT> track = False <NEW_LINE> if second_coor in self.tracking: <NEW_LINE> <INDENT> track = True <NEW_LINE> name = self.tracking[second_coor] <NEW_LINE> <DEDENT> content = self.move(first_coor, second_coor) <NEW_LINE> self._set(first_coor, content) <NEW_LINE> if tr...
Moves the contents of the given first coordinate to the given second coordinate and vice versa. Args: first_coor (tuple): content located at this coordinate moves to second_coor second_coor (tuple): content located at this coordinate moves to first_coor Raises: IndexError when either coordinate is outside the m...
625941eb96565a6dacc8fbc3
def FindUser(self, query: Text): <NEW_LINE> <INDENT> pass
This interface doesn't care about plebs.
625941ebcc40096d61595e47
def list_projects(arn=None, nextToken=None): <NEW_LINE> <INDENT> pass
Gets information about projects. See also: AWS API Documentation Exceptions Examples The following example returns information about the specified project in Device Farm. Expected Output: :example: response = client.list_projects( arn='string', nextToken='string' ...
625941ebff9c53063f47c6ea
def get_token_result(self, token): <NEW_LINE> <INDENT> if not self.is_token_in_db(token): <NEW_LINE> <INDENT> raise ValueError("The token given is not in database") <NEW_LINE> <DEDENT> conn = sqlite3.connect(self.database_name) <NEW_LINE> cursor = conn.cursor() <NEW_LINE> token_data = cursor.execute("SELECT * FROM ping...
finds entry for the token given :param token: a unique token given to the client :return: the prime number asked if it has been calculated, None otherwise
625941eb7c178a314d6ef961
def p_fl_named_row_reference(p): <NEW_LINE> <INDENT> _interpretHorribleFLReferenceMess(p, _asNamedRowReference)
fl_named_row_reference : FLNAMEDROWREFERENCE | LONGNAMEDROWREFERENCE | FLCELLREFLIKENAME EXCLAMATION FLNAMEDROWREFERENCE | FLCOLUMNREFLIKENAME EXCLAMATION FLNAMEDROWREFERENCE | FLROWREFLIKENAME EXCLAMATION FLNAMEDROWREFERENCE | NAME EXCLAMATION FLNAMEDROWREFERENCE | fl_naked_worksheet_reference EXCLAMATION FLNAMEDROWRE...
625941eb4f6381625f114f35
def allow_create_card(self, userid): <NEW_LINE> <INDENT> with get_connection('qf_mchnt') as db: <NEW_LINE> <INDENT> where = { 'expire_time': ('>', int(time.time())), 'userid': userid } <NEW_LINE> if db.select_one('card_actv', where=where, fields='count(1) as num')['num']: <NEW_LINE> <INDENT> return None <NEW_LINE> <DED...
是否允许创建集点活动
625941ebdc8b845886cb5a30
def filterOutMFIs(df): <NEW_LINE> <INDENT> noMFIs = df[~df["Cell Type"].str.contains(" hi")] <NEW_LINE> return noMFIs
Takes out any cell types with " hi" in it to separate MFIs from population summary.
625941eb4c3428357757c81e
def rob2( nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> dp = [0 for i in range(len(nums))] <NEW_LINE> dp[0] = nums[0] <NEW_LINE> if len(nums) == 1: <NEW_LINE> <INDENT> return dp[0] <NEW_LINE> <DEDENT> dp[1] = max(nums[0], nums[1]) <NEW_LINE> for i in range(2, len(nums)):...
:type nums: List[int]
625941eb0a366e3fb873ed18
def get_key_owner(self, key): <NEW_LINE> <INDENT> for user in self.subusers.values(): <NEW_LINE> <INDENT> if user.pubkeys.has_key(key): <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> <DEDENT> for key_line in self.custom_key_lines: <NEW_LINE> <INDENT> if key in key_line: <NEW_LINE> <INDENT> raise AuthorizedKeysExce...
Returns the key owner. Raises KeyError if the key is not found and AuthorizedKeysException if key is in use outside of subssh
625941eb91f36d47f21ac9f1
def add_notification(self, notification): <NEW_LINE> <INDENT> return self._query_api_object(Notification, "/rest/notifications", notification.dump(), "POST")
Create a new notification. Args: notification: new notification to be created. It should have no notification_id set Returns: Notification object for the newly created notification
625941ebe76e3b2f99f3acfc
def filtered_logs(self): <NEW_LINE> <INDENT> return self.logs.exclude(type__icontains="error")
Filter logs source
625941ebaad79263cf390f42
def _check_qualifications(ob): <NEW_LINE> <INDENT> for attrName in ('cQualified', 'iQualified'): <NEW_LINE> <INDENT> x = getattr(ob, attrName, None) <NEW_LINE> if not isinstance(x, list): <NEW_LINE> <INDENT> raise errors.InvariantError(ob)
Qualification attributes must be present as lists.
625941ebd268445f265b5368
def compute_batch_error(self, batch_result_dict): <NEW_LINE> <INDENT> TP = batch_result_dict['TP'] <NEW_LINE> FP = batch_result_dict['FP'] <NEW_LINE> FN = batch_result_dict['FN'] <NEW_LINE> TN = batch_result_dict['TN'] <NEW_LINE> return (TP + TN)/float(TP + TN+ FP + FN)
computes the error rate as the number of correctly classified samples Args: batch_result_dict: Returns:
625941eb4e4d5625662d48ca
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description='Test the reset protocol.' ) <NEW_LINE> add_argparser_transport_selector(parser) <NEW_LINE> args = parser.parse_args() <NEW_LINE> transport_loop = parse_argparser_transport_selector(args) <NEW_LINE> batch = Batch(transport_loop) <NEW_LINE> ba...
Test the reset protocol.
625941eb50485f2cf553d295
def staged_predict_proba(self, X): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for score in self.staged_decision_function(X): <NEW_LINE> <INDENT> yield self.loss_._score_to_proba(score) <NEW_LINE> <DEDENT> <DEDENT> except NotFittedError as e: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except AttributeError: <NEW_LI...
Predict class probabilities at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- y : array of shape = [n_samples] The predicted value of the input s...
625941eb21bff66bcd684e47
def time_series(self): <NEW_LINE> <INDENT> self.get_time_series()
Return the time series by querying the data source or use the cached value.
625941eb23e79379d52eea57
def name_pattern_validator(node, value): <NEW_LINE> <INDENT> valid_pattern = re.compile(r"^[a-zA-Z0-9_\-\.]+$") <NEW_LINE> if not valid_pattern.match(value): <NEW_LINE> <INDENT> raise colander.Invalid(node, _("Invalid value"))
>>> name_pattern_validator(None, 'bob') >>> name_pattern_validator(None, 'b ob') Traceback (most recent call last): ... colander.Invalid: <unprintable Invalid object> >>> name_pattern_validator(None, 'b:ob') Traceback (most recent call last): colander.Invalid: <unprintable Invalid object>
625941eb5fcc89381b1e1bbc
def _intercept(self, value, followUp): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> proxies = [clazz for clazz in self._classes if isinstance(value, clazz)] <NEW_LINE> if proxies: <NEW_LINE> <INDENT> if len(proxies) > 1: <NEW_LINE> <INDENT> proxies = [clazz for clazz in proxies if all(not issubclass(cl...
FOR INTERNAL USE! This is the interceptor method used in creating the proxies.
625941eb97e22403b379d495
def numberOfBoomerangs(self, points): <NEW_LINE> <INDENT> res = 0 <NEW_LINE> n = len(points) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> dmap = defaultdict(int) <NEW_LINE> for j in range(n): <NEW_LINE> <INDENT> dmap[pow((points[i][0] - points[j][0]), 2) + pow((points[i][1] - points[j][1]), 2)] += 1 <NEW_LINE> <DE...
:type points: List[List[int]] :rtype: int
625941eb5fcc89381b1e1bbd
def compute_auprc(pred, label): <NEW_LINE> <INDENT> precision, recall, thresholds = precision_recall_curve(label, pred) <NEW_LINE> auprc = auc(recall, precision) <NEW_LINE> return auprc
Calculate AUPRC of predictions in terms of label
625941eb16aa5153ce362972
def get_name(self): <NEW_LINE> <INDENT> return self.name
:return: event name
625941eb379a373c97cfb040
@login_required <NEW_LINE> def user_logout(request): <NEW_LINE> <INDENT> logout(request) <NEW_LINE> return HttpResponseRedirect(reverse('index'))
logout and redirect
625941eb76d4e153a657f02c
def _on_unexpected_error(self, error): <NEW_LINE> <INDENT> LOGGER.debug("An unexpected error occurred. Setting it as the " "exception of the main task.") <NEW_LINE> self._main_task.set_exception(error)
Handle unexpected errors of forwarding tasks Sets the *error* as the exception of the application's main task.
625941ebd268445f265b5369
def check(self, queues=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> queue_urls = self.account.client("sqs").list_queues().get("QueueUrls", []) <NEW_LINE> <DEDENT> except ClientError as err: <NEW_LINE> <INDENT> if err.response['Error']['Code'] in ["AccessDenied", "UnauthorizedOperation"]: <NEW_LINE> <INDENT> logg...
Walk through SQS queues in the account and check them (public or not). Put all gathered queues to `self.queues`. :param queues: list with SQS queue names to check, if it is not supplied - all queue must be checked :return: boolean. True - if check was successful, False - otherwise
625941ebac7a0e7691ed45bc
def __cmd(self, cmd): <NEW_LINE> <INDENT> env = {} <NEW_LINE> for k in ('LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'): <NEW_LINE> <INDENT> if k in os.environ: <NEW_LINE> <INDENT> env[k] = os.environ[k] <NEW_LINE> os.environ.pop(k) <NEW_LINE> <DEDENT> <DEDENT> logging.info("Command is: %s" % " ".join(cmd)) <NEW_LINE> try: <NE...
This is used to execure a command :params list cmd: sencha command which will be executed
625941ebeab8aa0e5d26e054
def create_db_engine_from_config(*, config: Config) -> Engine: <NEW_LINE> <INDENT> engine = create_engine(config.SQLALCHEMY_DATABASE_URI,) <NEW_LINE> _logger.info(f"creating DB conn with URI: {config.SQLALCHEMY_DATABASE_URI}") <NEW_LINE> return engine
The Engine is the starting point for any SQLAlchemy application. It’s “home base” for the actual database and its DBAPI, delivered to the SQLAlchemy application through a connection pool and a Dialect, which describes how to talk to a specific kind of database / DBAPI combination.
625941eb24f1403a9260105b
def result(data, taxon_names, tree, sample_names, **kwargs): <NEW_LINE> <INDENT> envs = make_envs_dict(data, sample_names, taxon_names) <NEW_LINE> unifrac_res = fast_unifrac( tree, envs, weighted=weighted, metric=metric, is_symmetric=is_symmetric, modes=["distance_matrix"], **kwargs) <NEW_LINE> dist_mtx = _reorder_unif...
wraps the fast_unifrac fn to return just a matrix, in correct order sample_names: list of unique strings
625941eb31939e2706e4d35c
def fetch_resources(uri, rel): <NEW_LINE> <INDENT> if uri.startswith(settings.MEDIA_URL): <NEW_LINE> <INDENT> path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) <NEW_LINE> <DEDENT> elif uri.startswith(settings.STATIC_URL): <NEW_LINE> <INDENT> path = os.path.join(settings.STATIC_ROOT, uri.repl...
Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc. `uri` is the href attribute from the html link element. `rel` gives a relative path, but it's not used here.
625941eb711fe17d8254285a
def load_catalog_file(self,catalog_filename): <NEW_LINE> <INDENT> def line_is_star(textline,sep=';'): <NEW_LINE> <INDENT> theline = textline.split(sep) <NEW_LINE> try: <NEW_LINE> <INDENT> int(theline[0].replace(' ','')[0]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return(False) <NEW_LINE> <DEDENT> else: <NEW_LINE...
Returns Catalog lines from the catalog_filename
625941ebd58c6744b4258157
def get_admin_panels(self, req): <NEW_LINE> <INDENT> yield ( 'general', _('General'), 'testquery', _("TestCases") )
returns the Section and the Name for the Navigation
625941eb6e29344779a62b0a
def Lease(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Lease') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Leases a dataflow WorkItem to run. Args: request: (DataflowProjectsJobsWorkItemsLeaseRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (LeaseWorkItemResponse) The response message.
625941eb046cf37aa974d23c
def get_width(self): <NEW_LINE> <INDENT> return self.__width
Returns the number of columns in the grid.
625941ebbe8e80087fb21135
def genRooms(maxsize,amsize,obl): <NEW_LINE> <INDENT> ret = np.zeros((amsize,amsize,4), dtype=np.int32) <NEW_LINE> for x,y in product(range(amsize),repeat=2): <NEW_LINE> <INDENT> if random.random()<0.4 or obl[x,y]: <NEW_LINE> <INDENT> x1 = random.randrange(2,maxsize//2-1) <NEW_LINE> y1 = random.randrange(2,maxsize//2-1...
gives back a 3d array. The first to indices give to position, the last gives the data with resp (x1,y1,x2,y2)
625941eb92d797404e304686
def accountsMerge(self, accounts): <NEW_LINE> <INDENT> owners = {} <NEW_LINE> parents = {} <NEW_LINE> merged = collections.defaultdict(set) <NEW_LINE> results = [] <NEW_LINE> for acc in accounts: <NEW_LINE> <INDENT> for i in range(1, len(acc)): <NEW_LINE> <INDENT> owners[acc[i]] = acc[0] <NEW_LINE> parents[acc[i]] = ac...
:type accounts: List[List[str]] :rtype: List[List[str]] Time: O(N log (N)) <-- all loops except last one is O(N) ( "find" is O(1) due to path compression) The last loop with sorting is worst case O(N log (N)), N being the total number of emails. Worst case being one big user with all the emails. An e...
625941ebd99f1b3c44c67a7f
def get_extensions(self): <NEW_LINE> <INDENT> path = self.end_point + "extensions" <NEW_LINE> data = self._get_data(path) <NEW_LINE> return data
A list of extensions to the management plugin
625941eb82261d6c526ab9a1
def stopProducing(self): <NEW_LINE> <INDENT> self.stop_event.set() <NEW_LINE> self.wakeup_event.set() <NEW_LINE> if not self.deferred.called: <NEW_LINE> <INDENT> with LoggingContext(): <NEW_LINE> <INDENT> self.deferred.errback(Exception("Consumer ask to stop producing"))
See IPushProducer.stopProducing
625941ebb7558d58953c5403
def find_path(self, start, target): <NEW_LINE> <INDENT> open_set = [start] <NEW_LINE> closed_set = [] <NEW_LINE> came_from = {} <NEW_LINE> G_score = {} <NEW_LINE> G_score[start] = 0 <NEW_LINE> H_score = {} <NEW_LINE> H_score[start] = self.calculate_h(start.x, start.z, target.x, target.z) <NEW_LINE> while open is not No...
Find shortest path between 2 points. :param start: starting node :param target: target node :return: a list of nodes which represents the shortest path
625941eb097d151d1a223351
def check_for_blackjack(hand): <NEW_LINE> <INDENT> total = get_hand_total(hand) <NEW_LINE> if total == 21: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Returns True if the hand is a blackjack, False otherwise.
625941ebfb3f5b602dac3b93
def PC(self, SML, LGD): <NEW_LINE> <INDENT> RQL = [] <NEW_LINE> for j in combinations(SML,LGD): <NEW_LINE> <INDENT> list(j).sort() <NEW_LINE> ITF = self.BS(RQL,list(j)) <NEW_LINE> if ITF == False: <NEW_LINE> <INDENT> RQL.append(list(j)) <NEW_LINE> <DEDENT> <DEDENT> return RQL
Generates all different combinations of SMs per input length.
625941eb627d3e7fe0d6934b
@property <NEW_LINE> def _node_rating_count(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.noderatingcount <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> node_rating_count = NodeRatingCount(node=self) <NEW_LINE> node_rating_count.save() <NEW_LINE> return node_rating_count
Return node_rating_count record or create it if it does not exist usage: node = Node.objects.get(pk=1) node.rating_count
625941eb32920d7e50b286cf
def test_txblock(): <NEW_LINE> <INDENT> m, vk_s, sk_s = sigs() <NEW_LINE> _, vk_r, sk_r = sigs() <NEW_LINE> prev_s = generate_genesis_block(vk_s, sk_s).compact.hash <NEW_LINE> prev_r = generate_genesis_block(vk_r, sk_r).compact.hash <NEW_LINE> h_s = 1 <NEW_LINE> h_r = 1 <NEW_LINE> gen_txblock(prev_s, prev_r, vk_s, sk_s...
test creation of a single block :return:
625941eb21a7993f00bc81f3
def get_pick_list_validation(self): <NEW_LINE> <INDENT> return self.__pick_list_validation
This is a getter method to get pick_list_validation. Returns: bool: A bool representing pick_list_validation
625941ebcdde0d52a9e53531
def iconize(self): <NEW_LINE> <INDENT> self.procedure.iconize( self.path, os.path.join(self.icon_location, "main") ) <NEW_LINE> for child in os.listdir(self.path): <NEW_LINE> <INDENT> child_path = os.path.join(self.path, child) <NEW_LINE> if child.startswith(".") or not os.path.isdir(child_path): <NEW_LINE> <INDENT> co...
Iconizes the directory :return: None
625941ebb57a9660fec33d85