code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __repr__(self): <NEW_LINE> <INDENT> return "<Apartment({}: {} {})>".format(self.id, self.url, self.opinion.title if self.opinion else "") | Represent the object as a unique string. | 625941cabde94217f3682e94 |
def enqueue(self, item): <NEW_LINE> <INDENT> if self.list[-1] == None: <NEW_LINE> <INDENT> self.list[-1] = item <NEW_LINE> self.size += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(len(self.list)): <NEW_LINE> <INDENT> if i+1 == len(self.list): <NEW_LINE> <INDENT> self.list[i] = item <NEW_LINE> break <... | insert item at the back of the buffer | 625941cad486a94d0b98e1e8 |
def update_many(self, _ids: List, data: Dict = None) -> None: <NEW_LINE> <INDENT> fe_records = self.fe.update_many(records) <NEW_LINE> if self.mode == CaheMode.writethru: <NEW_LINE> <INDENT> be_records = self.be.update_many(_ids, records) <NEW_LINE> <DEDENT> elif self.mode == CacheMode.writeback: <NEW_LINE> <INDENT> se... | Update multiple records. If a single data dict is passed in, then try to
apply the same update to all records; otherwise, if a list of data dicts
is passed in, try to zip the _ids with the data dicts and apply each
unique update or each group of identical updates individually. | 625941caad47b63b2c50a022 |
def current_location(self): <NEW_LINE> <INDENT> if self.input: <NEW_LINE> <INDENT> return self.input.current_location() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '<builtin>' | Return an identifier of the current location | 625941cab830903b967e99af |
@app.route('/predict_file', methods=['POST']) <NEW_LINE> def predict_file(): <NEW_LINE> <INDENT> input_data = pd.read_csv(request.files.get('input_file'), header=None) <NEW_LINE> prediction = model.predict(input_data) <NEW_LINE> return str(list(prediction)) | Example file endpoint returning a prediction of load_iris
---
parameters:
- name: input_file
in: formData
type: file
required: true | 625941cab7558d58953c4fb9 |
def instrument_class(self): <NEW_LINE> <INDENT> raise Exception("Not implemented") | class: Robinhood instrument class this handler is used for. | 625941ca8da39b475bd65016 |
def action_find_active(): <NEW_LINE> <INDENT> with get_connection() as conn: <NEW_LINE> <INDENT> tasks = storage.show_active(conn) <NEW_LINE> <DEDENT> for task in tasks: <NEW_LINE> <INDENT> template = '{task[0]} - {task[1]} - {task[2]} - {task[3]}' <NEW_LINE> print(template.format(task=task)) | Вывести все активные задачи | 625941ca44b2445a33932139 |
def load_volumes(self, vols): <NEW_LINE> <INDENT> devices = ['/dev/xvdb%s' % s for s in string.ascii_lowercase] <NEW_LINE> devmap = {} <NEW_LINE> for volname in vols: <NEW_LINE> <INDENT> vol = vols.get(volname) <NEW_LINE> dev = vol.get('device') <NEW_LINE> if dev in devices: <NEW_LINE> <INDENT> devices.remove(dev) <NEW... | Iterate through vols and set device/partition settings automatically if
not specified.
This method assigns the first volume to /dev/sdz, second to /dev/sdy,
etc. for all volumes that do not include a device/partition setting | 625941ca96565a6dacc8f76f |
def cmd_position(self, north, east, down, heading): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.cmd_position(north, east, down, heading) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("cmd_position not defined") | Command the local position and drone heading
north: local north in meters
east: local east in meters
down: local down in meters (positive down)
heading: drone yaw in degrees | 625941ca4e4d5625662d447c |
def basis(self, n): <NEW_LINE> <INDENT> free_basis = self._basis_for_free_alg(n) <NEW_LINE> basis = [] <NEW_LINE> for v in free_basis: <NEW_LINE> <INDENT> el = prod([self.gen(i)**v[i] for i in range(len(v))]) <NEW_LINE> di = el.dict() <NEW_LINE> if len(di) == 1: <NEW_LINE> <INDENT> k, = di.keys() <NEW_LINE> if tuple(k)... | Return a basis of the ``n``-th homogeneous component of ``self``.
EXAMPLES::
sage: A.<x,y,z,t> = GradedCommutativeAlgebra(QQ, degrees=(1, 2, 2, 3))
sage: A.basis(2)
[z, y]
sage: A.basis(3)
[t, x*z, x*y]
sage: A.basis(4)
[x*t, z^2, y*z, y^2]
sage: A.basis(5)
[z*t, y*t, x*z^2, x*y*z,... | 625941ca01c39578d7e74edf |
def __getitem__(self, k: str) -> Any: <NEW_LINE> <INDENT> return self.__dictionary.__getitem__(k) | x.__getitem__(y) <==> x[y] | 625941ca8da39b475bd65017 |
def cancel_run(self, run_id): <NEW_LINE> <INDENT> api_call='/api/2.0/jobs/runs/cancel' <NEW_LINE> payload = {} <NEW_LINE> payload["run_id"]=run_id <NEW_LINE> req = self.__post_request(api_call, payload) <NEW_LINE> return req | Desc:Cancels a run. The run is canceled asynchronously, so when this request completes,
the run may still be running. The run will be terminated shortly. If the run is already
in a terminal life_cycle_state, this method is a no-op.
URL: /2.0/jobs/runs/cancel
:param run_id:
:return: | 625941ca1f037a2d8b9462a1 |
def source(url): <NEW_LINE> <INDENT> html = requests.get(url=url) <NEW_LINE> html.encoding = 'utf-8' <NEW_LINE> htmlcode = BeautifulSoup(html.text, "html.parser") <NEW_LINE> return htmlcode | 回傳HTML | 625941ca63d6d428bbe44593 |
def get_response(self): <NEW_LINE> <INDENT> from LogPointSearcher import LogPointSearcher <NEW_LINE> searcher = LogPointSearcher() <NEW_LINE> self._response_string = searcher.get_response(self.get_id()) <NEW_LINE> if not isinstance(self._response_string,Error): <NEW_LINE> <INDENT> return Response(self._response_string)... | get_response() => returns response object
This method returns the response object for the live search | 625941cacb5e8a47e48b7b4f |
def get_daily_var(self, notional): <NEW_LINE> <INDENT> DailyVar_series = (np.log(notional.pct_change(1)+1))**2 <NEW_LINE> DailyVar_series = DailyVar_series.fillna(0) <NEW_LINE> return DailyVar_series | (ln(notional return + 1))^2
:param notional: pd.Series
:return: pd.Series | 625941ca44b2445a3393213a |
def test_for_user_login(self): <NEW_LINE> <INDENT> result = self.authenticate() <NEW_LINE> self.assertIn("You logged in successfully.", str(result.data)) | Tests for correct user login. | 625941cad99f1b3c44c67633 |
def __init__(self, amount): <NEW_LINE> <INDENT> super(StorageLicense, self).__init__() <NEW_LINE> self._amount = amount <NEW_LINE> self.refresh() | A license with a volume to be spent over multiple timesteps
This class should not be instantiated directly. Instead, use one of the
subclasses such as AnnualLicense.
Parameters
----------
amount : float
The volume of water available in each period | 625941cad164cc6175782df1 |
def run_cppi(risky_r,safe_r=None,m=3,start=1000,floor=0.8,riskfree_rate=0.03,drawdown=None): <NEW_LINE> <INDENT> dates=risky_r.index <NEW_LINE> n_steps=len(dates) <NEW_LINE> account_value=start <NEW_LINE> floor_value=start*floor <NEW_LINE> peak=start <NEW_LINE> if isinstance(risky_r, pd.Series): <NEW_LINE> <INDENT> ris... | run a backtest of CPPI strategy, given a set of returns of risky assets | 625941ca5fc7496912cc3a21 |
def prazna_stranica(self, i, j): <NEW_LINE> <INDENT> if not self.igra.vodoravne[i][j]: <NEW_LINE> <INDENT> return "vodoravno", i, j <NEW_LINE> <DEDENT> elif not self.igra.vodoravne[i+1][j]: <NEW_LINE> <INDENT> return "vodoravno", i+1, j <NEW_LINE> <DEDENT> elif not self.igra.navpicne[i][j]: <NEW_LINE> <INDENT> return "... | najde eno prazno stranico v kvadratu (i, j) | 625941cacdde0d52a9e530d6 |
def _get_db_tracker(self, url): <NEW_LINE> <INDENT> db_tracker = self.store.find(DBTracker, DBTracker.url == unicode(url)).one() <NEW_LINE> if not db_tracker: <NEW_LINE> <INDENT> raise NotFoundError('Tracker %s not found' % url) <NEW_LINE> <DEDENT> return db_tracker | Get the tracker based on the given URL.
@param url: URL of the tracker
@type url: C{str}
@return: The selected tracker.
@rtype: L{DBTracker}
@raise NotFoundError: When the tracker is not found. | 625941cad53ae8145f87a314 |
def do_connect(self, args): <NEW_LINE> <INDENT> l = args.split() <NEW_LINE> if len(l) > 2: <NEW_LINE> <INDENT> print(fail('invalid number of arguments')) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ip = l[0] <NEW_LINE> if len(l) == 2: <NEW_LINE> <INDENT> self._node.connect_node(ip, l[1]) <NEW_LINE> <... | Parses the arguments to get nodes ip and connects to node
| 625941ca097d151d1a222efe |
@fill.method((Table, Mapping)) <NEW_LINE> def _sd_fill_table(table, cells): <NEW_LINE> <INDENT> table._update_cache() <NEW_LINE> logger.debug(' Clicking Table cell') <NEW_LINE> table.click_cells(cells) <NEW_LINE> return bool(cells) | How to fill a table with a value (by selecting the value as cells in the table)
See Table.click_cells | 625941ca8a349b6b435e8217 |
def add_entry(self,path,title,username,password,url="",notes="",imageid=1): <NEW_LINE> <INDENT> top = self.hierarchy() <NEW_LINE> node = hier.mkdir(top, path, self.gen_groupid(), self.groups, self.header) <NEW_LINE> new_entry = EntryInfo().make_entry(node,title,username,password,url,notes,imageid) <NEW_LINE> self.entri... | Add an entry to the current database at with given values. If
append is False a pre-existing entry that matches path, title
and username will be overwritten with the new one. | 625941ca4e696a04525c94ef |
def __init__(self, solver, progressBar, progresslabel, Mesh = True, Fem = True, Time = True, Extr = True ): <NEW_LINE> <INDENT> QtCore.QThread.__init__(self) <NEW_LINE> self.progressBar = progressBar <NEW_LINE> self.progresslabel = progresslabel <NEW_LINE> self.solver = solver <NEW_LINE> self.Mesh = Mesh <NEW_LINE> sel... | Klasskonstruktor | 625941ca009cb60464c63456 |
def WriteRecommendedPolicy(self, policy): <NEW_LINE> <INDENT> pass | Appends the template text corresponding to a recommended policy into the
internal buffer.
Args:
policy: The recommended policy as it is found in the JSON file. | 625941ca94891a1f4081bb4d |
def cli(): <NEW_LINE> <INDENT> import argparse <NEW_LINE> logging.basicConfig(level=logging.INFO) <NEW_LINE> parser = argparse.ArgumentParser(description='Manage running clusters') <NEW_LINE> parser.add_argument('-r', '--region', default=DEFAULT_REGION, help='The aws region to be used (default: %(default)s)') <NEW_LINE... | cli entrypoint for local execution | 625941cad58c6744b4257d04 |
def get_transform(fp1, fp2): <NEW_LINE> <INDENT> return np.logical_xor(fp1, fp2) | Positions of flipped bits from fp1 to fp2 | 625941ca1b99ca400220ab55 |
def __init__(self, x, y): <NEW_LINE> <INDENT> super().__init__(x, y) | Initialize treasure with given x and y.
:param x: x
:param y: y | 625941cafb3f5b602dac3736 |
def set_shutdown(self, state): <NEW_LINE> <INDENT> if not isinstance(state, int): <NEW_LINE> <INDENT> raise TypeError("state must be an integer") <NEW_LINE> <DEDENT> _lib.SSL_set_shutdown(self._ssl, state) | Set shutdown state
:param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
:return: None | 625941ca8e05c05ec3eea418 |
def p_factor_6(p): <NEW_LINE> <INDENT> p[0]=p[1]+str(p[2]) | factor : '-' factor | 625941ca85dfad0860c3aefe |
def test_get_result_path(self): <NEW_LINE> <INDENT> h = hlxplot(InputHandler='_input_as_lines') <NEW_LINE> res = h(self.input) <NEW_LINE> self.assertEqualItems(res.keys(),['StdOut','StdErr','ExitStatus']) <NEW_LINE> self.assertEqual(res['ExitStatus'],0) <NEW_LINE> assert res['StdOut'] is not None <NEW_LINE> res.cleanUp... | Tests hlxplot result path | 625941ca099cdd3c635f0cff |
def LotkaVolterra(N,R,params): <NEW_LINE> <INDENT> if type(params['c']) is pd.DataFrame: <NEW_LINE> <INDENT> c = params['c'].values <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c = params['c'] <NEW_LINE> <DEDENT> if type(params['D']) is pd.DataFrame: <NEW_LINE> <INDENT> D = params['D'].values <NEW_LINE> <DEDENT> else:... | Compute effective Lotka-Volterra coefficients and carrying capacity for
dynamics near the fixed point. | 625941caa8370b7717052944 |
def __get_addr1(self, item): <NEW_LINE> <INDENT> addr1 = [] <NEW_LINE> namelist = self.config['Special']['addr1'].split('\n') <NEW_LINE> for name in namelist: <NEW_LINE> <INDENT> value = item[self.colname_list[name]] <NEW_LINE> if value: <NEW_LINE> <INDENT> addr1.append(value) <NEW_LINE> <DEDENT> <DEDENT> return " ".jo... | Merge and generate the full street name
:param item:
:return: the full street name | 625941ca167d2b6e31218c3a |
def do_axfr(zone_name, servers, timeout=None, source=None): <NEW_LINE> <INDENT> random.shuffle(servers) <NEW_LINE> timeout = timeout or cfg.CONF["service:mdns"].xfr_timeout <NEW_LINE> xfr = None <NEW_LINE> for srv in servers: <NEW_LINE> <INDENT> to = eventlet.Timeout(timeout) <NEW_LINE> log_info = {'name': zone_name, '... | Performs an AXFR for a given zone name | 625941caf548e778e58cd621 |
def get_fist_bin_size_for_embedding(embedding): <NEW_LINE> <INDENT> past_range_T, number_of_bins_d, scaling_k = embedding <NEW_LINE> return newton(lambda first_bin_size: get_past_range(number_of_bins_d, first_bin_size, scaling_k) - past_range_T, 0.005, tol = 1e-03, maxiter = 100) | Get size of first bin for the embedding, based on the parameters
T, d and k. | 625941cabaa26c4b54cb11c4 |
def build_learningrate(config): <NEW_LINE> <INDENT> LR = mrnn_utility.getlist_str(config['MODEL']['LearningRate']) <NEW_LINE> if (len(LR) == 1): <NEW_LINE> <INDENT> LearningRate = float(LR[0]) <NEW_LINE> <DEDENT> elif (len(LR) > 1): <NEW_LINE> <INDENT> LR_type = LR[0] <NEW_LINE> if (LR_type == 'mono'): <NEW_LINE> <INDE... | Build different learning rates based on the input | 625941ca8c0ade5d55d3ea5e |
def __init__(self, ok_cb, cancel_cb, message=None, title=_("Please select a file"), style=[]): <NEW_LINE> <INDENT> self.ok_cb = ok_cb <NEW_LINE> self._type = 'dir' if 'dir' in style else 'normal' <NEW_LINE> self.__home_path = os.path.expanduser('~') <NEW_LINE> widgets = [] <NEW_LINE> if message: <NEW_LINE> <INDENT> wid... | Create file dialog
@param title: title of the window/popup
@param message: message to display, or None to only show title and file dialog
message will be passed to a Text widget, so markup can be used
@param style: list of string:
- 'dir' if a dir path must be selected | 625941ca187af65679ca51c2 |
def sum_kv_ij(i, j): <NEW_LINE> <INDENT> return i * i + j * j | Сумма квадратов | 625941ca3617ad0b5ed67f9b |
def aes_cipher(timestamp): <NEW_LINE> <INDENT> aes_secret = "" <NEW_LINE> return AesCipherHolder(aes_secret) | for a given timestamp, this should return the appropriate AES object | 625941ca45492302aab5e366 |
def load_file(self): <NEW_LINE> <INDENT> uv = UVData() <NEW_LINE> uv.read_miriad(self.files[self.pol]) <NEW_LINE> if self.caldata == tuple(): <NEW_LINE> <INDENT> self.calculate_caldata(uv) <NEW_LINE> <DEDENT> info = {} <NEW_LINE> info['freqs'] = uv.freq_array[0, :] / 1e9 <NEW_LINE> info['times'] = np.unique(uv.time_arr... | Loads data with given polarization, self.pol, from files, self.files | 625941ca30dc7b7665901a0b |
def test_find_match_two(large_tree_match): <NEW_LINE> <INDENT> tree = FM(large_tree_match, 2) <NEW_LINE> assert len(tree) == 2 <NEW_LINE> for node in tree: <NEW_LINE> <INDENT> assert node.val == 2 | Test find match function. | 625941ca1f5feb6acb0c4bf5 |
def _generate_inner_loop(self, b, node): <NEW_LINE> <INDENT> loop = node <NEW_LINE> if len(self.indices) > 1: <NEW_LINE> <INDENT> for index in self.indices[:-2]: <NEW_LINE> <INDENT> loop = node.body <NEW_LINE> <DEDENT> self.inner_loop = loop.body <NEW_LINE> loop.body = b.pragma_for(self.inner_loop) <NEW_LINE> node = se... | Generate innermost loop, injecting the pointer assignments in the
right place | 625941ca507cdc57c6306d7e |
def __init__(self, id=None): <NEW_LINE> <INDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Base.__nb_objects += 1 <NEW_LINE> self.id = Base.__nb_objects | Instantiation of class which checks for id | 625941ca63b5f9789fde718a |
def visualize(p, text): <NEW_LINE> <INDENT> p = 1 - p <NEW_LINE> y_bar = [''] <NEW_LINE> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> cax = ax.matshow(generate_visualize_array(p), cmap=cm.gray) <NEW_LINE> fig.colorbar(cax, orientation="horizontal") <NEW_LINE> ax.set_xticklabels([''] + text) <NEW_L... | p = [0.1, 0.3, 0, 0.6, 0]
text = ['a', 'b', 'c', 'd', 'e']
:param p:
:param text:
:return: | 625941ca9c8ee82313fbb819 |
def set_logrotate_path(self): <NEW_LINE> <INDENT> logrotate_path = "" <NEW_LINE> logrotate_paths = ["/etc/logrotate.d/syslog", "/etc/logrotate.d/syslog.conf", "/etc/logrotate.d/rsyslog", "/etc/logrotate.d/rsyslog.conf"] <NEW_LINE> for path in logrotate_paths: <NEW_LINE> <INDENT> if os.path.isfile(path): <NEW_LINE> <IND... | determines the correct log rotate config file path
:return: logrotate_path
:rtype: string | 625941ca07d97122c417892e |
def six_cubed(): <NEW_LINE> <INDENT> print(math.pow(6, 3)) | function that gives the solution to 6 in power 3 | 625941ca435de62698dfdcf1 |
def validate_license(self): <NEW_LINE> <INDENT> lic = self['software_license'] <NEW_LINE> if lic is None: <NEW_LINE> <INDENT> if 'software_license' in self.mandatory: <NEW_LINE> <INDENT> raise EasyBuildError("Software license is mandatory, but 'software_license' is undefined") <NEW_LINE> <DEDENT> <DEDENT> elif lic in E... | Validate the license | 625941ca6aa9bd52df036e48 |
@dispatch <NEW_LINE> @abstract() <NEW_LINE> def svd(a: Numeric, compute_uv: bool = True): <NEW_LINE> <INDENT> pass | Compute the singular value decomposition.
Args:
a (tensor): Matrix to decompose.
compute_uv (bool, optional): Also compute `U` and `V`. Defaults to
`True`.
Returns:
tuple: `(U, S, V)` if `compute_uv` is `True` and just `S` otherwise. | 625941ca0c0af96317bb828c |
def canJump(self, nums): <NEW_LINE> <INDENT> target_index = len(nums) - 1 <NEW_LINE> if target_index == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> while target_index > 0: <NEW_LINE> <INDENT> is_proceed = False <NEW_LINE> for i in range(1, target_index + 1): <NEW_LINE> <INDENT> if nums[target_index - i] >= i... | :type nums: List[int]
:rtype: bool | 625941ca4d74a7450ccd4268 |
def bump(self, bump_type): <NEW_LINE> <INDENT> if bump_type == 'micro' and self._resolution < 3 or bump_type == 'patch' and self._resolution < 4: <NEW_LINE> <INDENT> raise ValueError('Invalid bump_type {!r} for version {!r}'.format( bump_type, self.components) ) <NEW_LINE> <DEDENT> if bump_type == 'major... | Bump a version string.
Args:
bump_type (str): Component to bump
Raises:
ValueError: Invalid ``bump_type`` argument | 625941ca5fdd1c0f98dc02d7 |
def test_login_authorized(self): <NEW_LINE> <INDENT> response = self.client1.post('/accounts/login/', {'username': self.user['user1'].username, 'password': 'secret'}) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> is_logged_in = self.client1.login(username=self.user['user1'].username, password='secre... | Test that an authorized user can get in. | 625941ca283ffb24f3c559a6 |
def __init__(self, p_file_yaml: str = None, p_crea_se_inesistente: bool = False): <NEW_LINE> <INDENT> self._preferenze = dict() <NEW_LINE> if p_file_yaml is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.importa(p_file_yaml) <NEW_LINE> <DEDENT> except (FileNotFoundError, FilePreferenzeCorrotto) as e: <NEW_... | Costruttore della classe
Args:
p_file_yaml: Il file in formato YAML
con la configurazione da aprire | 625941cafbf16365ca6f6268 |
def get_hyperbole_dots_coords(): <NEW_LINE> <INDENT> hyperbole = [[], []] <NEW_LINE> right_lim = 1 <NEW_LINE> left_lim = 30 <NEW_LINE> dot = 0.5 <NEW_LINE> k = 30 <NEW_LINE> while right_lim < left_lim: <NEW_LINE> <INDENT> hyperbole[0].append(right_lim) <NEW_LINE> hyperbole[1].append(k / right_lim) <NEW_LINE> right_lim ... | Return format: [[x_coords][y_coords]] | 625941ca8c0ade5d55d3ea5f |
def metadata_updated(self, session): <NEW_LINE> <INDENT> logger.debug('Callback called: Metadata updated') | Callback used by pyspotify | 625941cad164cc6175782df2 |
def __generate_nontextual_output(self, sampleid, collection_name, source, tipe, meta_map, meta_dict): <NEW_LINE> <INDENT> key = 'table_document_' + sampleid + '#' + tipe <NEW_LINE> meta_dict = add_to_dictionary(key, meta_dict, self.__gen_nontext_document_metadata(tipe, sampleid, source)) <NEW_LINE> shutil.copy2(source,... | If we are dealing with non-textual data then copy the required data over generating the meta information | 625941cac4546d3d9de72ad8 |
def __init__(self, low: int, high: int): <NEW_LINE> <INDENT> self._low = low <NEW_LINE> self._high = high <NEW_LINE> tk.IntVar.__init__(self, value=low) | :param low: Lower limit
:param high: Higher limit | 625941ca3d592f4c4ed1d114 |
def get_attributes(self, uid=None, attribute_names=None): <NEW_LINE> <INDENT> if uid is not None: <NEW_LINE> <INDENT> if not isinstance(uid, six.string_types): <NEW_LINE> <INDENT> raise TypeError("uid must be a string") <NEW_LINE> <DEDENT> <DEDENT> if attribute_names is not None: <NEW_LINE> <INDENT> if not isinstance(a... | Get the attributes associated with a managed object.
If the uid is not specified, the appliance will use the ID placeholder
by default.
If the attribute_names list is not specified, the appliance will
return all viable attributes for the managed object.
Args:
uid (string): The unique ID of the managed object wit... | 625941ca7047854f462a14af |
def list_keypairs(self, filters=None): <NEW_LINE> <INDENT> if not filters: <NEW_LINE> <INDENT> filters = {} <NEW_LINE> <DEDENT> return list(self.compute.keypairs(allow_unknown_params=True, **filters)) | List all available keypairs.
:returns: A list of ``munch.Munch`` containing keypair info. | 625941ca4e696a04525c94f0 |
def get_aleatoric_sigma2(pred_logvar): <NEW_LINE> <INDENT> n_Mc, n_val, Y_dim = pred_logvar.shape <NEW_LINE> al_sigma2 = np.mean(np.exp(pred_logvar), axis=0) <NEW_LINE> return al_sigma2 | Parameters
----------
pred_logvar : np.ndarray of shape [n_MC, n_val, Y_dim]
Network predictions of the log(parameter sigmas) | 625941caa79ad161976cc1ea |
def testSparseColumnHashBucketDeepCopy(self): <NEW_LINE> <INDENT> column = fc.sparse_column_with_hash_bucket("a", 10) <NEW_LINE> self.assertEqual("a", column.name) <NEW_LINE> column_copy = copy.deepcopy(column) <NEW_LINE> self.assertEqual("a", column_copy.name) <NEW_LINE> self.assertEqual(10, column_copy.bucket_size) <... | Tests deepcopy of sparse_column_with_hash_bucket. | 625941caf7d966606f6aa0a8 |
def __init__(self, expression): <NEW_LINE> <INDENT> self.original = expression <NEW_LINE> self.head = Node("=") <NEW_LINE> self.treeify(expression) <NEW_LINE> self.simplify() | Initialize the tree with a string that is the equation | 625941ca7b25080760e394fe |
def cbk_descongela(self): <NEW_LINE> <INDENT> lf_hora_now = time.time() <NEW_LINE> lf_hora_dif = lf_hora_now - self.__f_hora_frz <NEW_LINE> self.__f_zero_sys += lf_hora_dif <NEW_LINE> self.__v_congela = False | descongela o relógio da simulação. | 625941ca5e10d32532c5efcb |
def test_stdout_monkeypatch(self, monkeypatch, capsys): <NEW_LINE> <INDENT> p = PrintLogger() <NEW_LINE> new_stdout = StringIO() <NEW_LINE> monkeypatch.setattr(sys, "stdout", new_stdout) <NEW_LINE> p.msg("hello") <NEW_LINE> out, err = capsys.readouterr() <NEW_LINE> assert "hello\n" == new_stdout.getvalue() <NEW_LINE> a... | If stdout gets monkeypatched, the new instance receives the output. | 625941ca71ff763f4b54972f |
def timenow(): <NEW_LINE> <INDENT> return time.strftime("%m-%d-%Y %H:%M:%S", time.localtime()) + " " + time.strftime("%z") | just a timenow function to minimize code repeats | 625941caf8510a7c17cf97a1 |
def prep_request(items, local_id="id"): <NEW_LINE> <INDENT> map_items = ET.Element("map") <NEW_LINE> for idx, pub in enumerate(items): <NEW_LINE> <INDENT> if pub is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> local_id_value = pub.get(local_id) or pub.get(local_id.upper()) <NEW_LINE> if local_id_value is None... | Process the incoming items into an AMR request.
<map name="cite_1">
<val name="{id_type}">{value}</val>
</map> | 625941caeab8aa0e5d26dbfc |
def query(expression,hostname,logfile,unique=True,sort=None,output=None,pattern=None,path=None): <NEW_LINE> <INDENT> if not path: <NEW_LINE> <INDENT> path = r'.' <NEW_LINE> <DEDENT> cmd_str = generate_cmd(expression,logfile,unique,sort,output,pattern) <NEW_LINE> execute(executor,hostname,cmd_str,path,host=hostname) <NE... | expression: regex rule
hostname: hostname as specified hosts()
logfile: log file name, wildcard supported, eg:*.log
unique: whether result is unique
sort: 1(ASC) or -1(DESC) ,default None
output:None or file name, default None imply print stream
pattern: group pattern , default None imply '1'
path: cd to path before ex... | 625941cad6c5a102081440ef |
def get_config(): <NEW_LINE> <INDENT> torch.set_default_tensor_type(torch.cuda.FloatTensor) <NEW_LINE> BASE_DIR = "resources" <NEW_LINE> SYSTEM_NAME = "hoags_object" <NEW_LINE> PARAMS = YAML().load(open(os.path.join(BASE_DIR, "params.yaml")))[SYSTEM_NAME] <NEW_LINE> config = load_config(os.path.join(BASE_DIR, "config-s... | Get the config without polluting the global namespace. | 625941ca91af0d3eaac9babd |
def clk_chksum(icmp_packet): <NEW_LINE> <INDENT> packet_len = len(icmp_packet) <NEW_LINE> summ = 0 <NEW_LINE> for i in range(0, packet_len, 2): <NEW_LINE> <INDENT> if i + 1 < packet_len: <NEW_LINE> <INDENT> summ += icmp_packet[i] + (icmp_packet[i + 1] << 8) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> summ += icmp_pac... | Calculate ICMP packet checksum | 625941caa17c0f6771cbe0f6 |
def resample_particles(particles): <NEW_LINE> <INDENT> num_particles = len(particles) <NEW_LINE> particle_weight_sum = 0 <NEW_LINE> for particle in particles: <NEW_LINE> <INDENT> particle_weight_sum += np.exp(particle.weight) <NEW_LINE> <DEDENT> norm_particle_weights = [] <NEW_LINE> for i in range (0, num_particles): <... | resample particles according to weight
Sample (with replacement) from the list of particles
according to their weight, which was assigned in the
update_map() section. Be sure to copy each particle
args: A transformation for extracting new descriptors of shape H Blum, Models for the perception of speech and visual f... | 625941ca656771135c3eb913 |
def check_latest_version(): <NEW_LINE> <INDENT> check = True <NEW_LINE> with timestamp_file() as f: <NEW_LINE> <INDENT> timestamp = float(f.read() or 0) <NEW_LINE> <DEDENT> delta = time.time() - timestamp <NEW_LINE> check = delta > 3600 <NEW_LINE> if check: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> latest_version = ... | checks for the latest version of cumulusci from pypi, max once per hour | 625941cade87d2750b85fe37 |
def read_data(window, window_std, n_batch) : <NEW_LINE> <INDENT> try : <NEW_LINE> <INDENT> assert csv_path is not None, "Must pass file path as argument" <NEW_LINE> window_std = int(window_std) <NEW_LINE> n_batch = int(n_batch) <NEW_LINE> f = pd.read_csv(csv_path) <NEW_LINE> idx_tmp = f['date'].astype(str) + " " + f['h... | Convert csv data into numpy array with the desired dimensions
(n_batch, window * number of explanatory variables)
Explanatory variables : average price per minute
average volume per minute
moving std of average price for given size of window_std
:param window: win... | 625941ca796e427e537b066a |
def diffpow(self, x, rot=0): <NEW_LINE> <INDENT> N = len(x) <NEW_LINE> if rot: <NEW_LINE> <INDENT> x = rotate(x) <NEW_LINE> <DEDENT> return sum(np.abs(x)**(2. + 4.*np.arange(N) / (N - 1.)))**0.5 | Diffpow test objective function | 625941ca66656f66f7cbc24f |
def is_echelon(A): <NEW_LINE> <INDENT> i = -1 <NEW_LINE> ncols = len(A[0]) <NEW_LINE> for row in A: <NEW_LINE> <INDENT> j = 0 <NEW_LINE> while j < ncols and row[j] == 0: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> if j <= i and j < ncols-1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i = j <NEW_LINE> <DEDEN... | Input:
- A: a list of row lists
Output:
- True if A is in echelon form
- False otherwise
Examples:
>>> is_echelon([[1,1,1],[0,1,1],[0,0,1]])
True
>>> is_echelon([[0,1,1],[0,1,0],[0,0,1]])
False | 625941ca6e29344779a626b7 |
def trans(self, newState, reason=None): <NEW_LINE> <INDENT> oldState = self.state <NEW_LINE> for hook in self.exitHooks.get(oldState, []): <NEW_LINE> <INDENT> hook(newState, reason) <NEW_LINE> <DEDENT> self.state = newState <NEW_LINE> for hook in self.entryHooks.get(newState, []): <NEW_LINE> <INDENT> hook(oldState, rea... | Transitions to the given state, calling hooks as
appropriate. | 625941cabe8e80087fb20ce8 |
def ui_loop(client, station='favs'): <NEW_LINE> <INDENT> c = client <NEW_LINE> if station is None: <NEW_LINE> <INDENT> station = c.stations()[0] <NEW_LINE> <DEDENT> deets = c.station(station) <NEW_LINE> streams = stream_list(c.streams(station)) <NEW_LINE> stations = c.stations() <NEW_LINE> (term_w, term_h) = term_wh() ... | list possible stations, read user input, and call player | 625941ca004d5f362079a3d8 |
def test_login_to_console_with_invalid_credentials(self): <NEW_LINE> <INDENT> step("Login using uaa endpoint") <NEW_LINE> configuration = ConsoleConfigurationProvider.get( username=generate_test_object_name(separator=""), password=generate_test_object_name(separator="")) <NEW_LINE> with pytest.raises(UnexpectedResponse... | <b>Description:</b>
Log in to console with invalid credentials
<b>Input data:</b>
Invalid credentials
<b>Expected results:</b>
It's impossible to log in to platform with invalid credentials
<b>Steps:</b>
Log in to console with invalid credentials | 625941ca3317a56b86939cff |
def test_05(self): <NEW_LINE> <INDENT> obj = ApplicationConf.get_instance() <NEW_LINE> self.assertTrue(hasattr(obj, 'DEFAULT_CHARSET')) <NEW_LINE> self.assertTrue(hasattr(obj, 'CHARSET')) <NEW_LINE> self.assertEqual(obj.DEFAULT_CHARSET, obj.CHARSET) | Test Case 05:
Test if the :py:class:`~magrathea.conf.ApplicationConf` class interface provides also a non-default.
Test is passed if both, default an non-default keys exist and have the same value. | 625941cabde94217f3682e96 |
def configure_logging(app): <NEW_LINE> <INDENT> if app.debug or app.testing: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> import logging <NEW_LINE> from logging.handlers import SMTPHandler <NEW_LINE> app.logger.setLevel(logging.INFO) <NEW_LINE> info_log = os.path.join(app.root_path, "..", "logs", "app-info.log") <NEW... | Configure file(info) and email(error) logging. | 625941cabde94217f3682e97 |
def information(self, formatter, contact, message): <NEW_LINE> <INDENT> self._append_message(contact, message, cedict={}, cedir='', is_incoming=True) | add an information message to the widget | 625941ca377c676e9127224e |
@pytest.mark.slow <NEW_LINE> def test_radial_pvd_vs_r_correctness4(): <NEW_LINE> <INDENT> npts = 100 <NEW_LINE> xc1, yc1, zc1 = 0.5, 0.5, 0.1 <NEW_LINE> xc2, yc2, zc2 = 0.5, 0.5, 0.95 <NEW_LINE> sample1 = generate_locus_of_3d_points(npts, xc=xc1, yc=yc1, zc=zc1, seed=fixed_seed) <NEW_LINE> sample2 = generate_locus_of_3... | This function tests that the
`~halotools.mock_observables.radial_pvd_vs_r` function returns correct
results for a controlled distribution of points whose radial velocity
can be simply calculated.
For this test, the configuration is two tight localizations of points,
the first at (0.5, 0.5, 0.1), the second at (0.5, 0.... | 625941ca96565a6dacc8f771 |
@attr("functional") <NEW_LINE> def test_simple_single_file(): <NEW_LINE> <INDENT> out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_input = "1\ny\n") <NEW_LINE> expected_files = ['Scrubs - [01x01] - My First Day.avi'] <NEW_LINE> verify_out_data(out_data, expected_files) | Test simple interactive usage with single file
| 625941ca01c39578d7e74ee1 |
def finish(self): <NEW_LINE> <INDENT> for ssh_node in self.__connections.values(): <NEW_LINE> <INDENT> ssh_node.finish() | Close all open connections. | 625941cad8ef3951e32435e3 |
def begin_create_or_update( self, resource_group_name, circuit_name, authorization_name, authorization_parameters, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LI... | Creates or updates an authorization in the specified express route circuit.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param circuit_name: The name of the express route circuit.
:type circuit_name: str
:param authorization_name: The name of the authorization.
:type auth... | 625941ca3539df3088e2e3f0 |
def GetStartCityFromArray(cities,index=0): <NEW_LINE> <INDENT> start_city = cities[index,:] <NEW_LINE> return(start_city) | gets details for start city based on array index, default=0, i.e. first city in array | 625941ca60cbc95b062c65e9 |
def address(self): <NEW_LINE> <INDENT> return self._pb2_object.address | Get the unique address of the PdmObject
Returns:
A 64-bit unsigned integer address | 625941ca1d351010ab855bc1 |
def get(self): <NEW_LINE> <INDENT> message, time = self._queue.get() <NEW_LINE> if self._history_size > 0 and len(self.history) >= self._history_size: <NEW_LINE> <INDENT> self.history.pop(0) <NEW_LINE> <DEDENT> self.history.append((message, time)) <NEW_LINE> return message | Return the next message in the queue. | 625941ca097d151d1a222eff |
def spawn_pytest(self, string, expect_timeout=10.0): <NEW_LINE> <INDENT> basetemp = self.tmpdir.mkdir("pexpect") <NEW_LINE> invoke = " ".join(map(str, self._getpytestargs())) <NEW_LINE> cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string) <NEW_LINE> return self.spawn(cmd, expect_timeout=expect_timeout) | Run pytest using pexpect.
This makes sure to use the right pytest and sets up the
temporary directory locations.
The pexpect child is returned. | 625941ca097d151d1a222f00 |
def continue_evolving(self): <NEW_LINE> <INDENT> return (time.time() - self.started_at_ < self.max_evolution_duration and self.cycle_ < self.max_evolution_cycles and not self.solution_candidate_.is_goal and (self.min_genetic_similarity == 0 or self.min_genetic_similarity <= self.genetic_similarity())) | Checks if evolution process should continue.
Returns
-------
True, if evolution should continue, False otherwise. | 625941caa219f33f34628a10 |
def test_story_destroy(self): <NEW_LINE> <INDENT> self.client.force_authenticate(user=self.user) <NEW_LINE> s = self.client.get(f'/api/stories/{self.story.id}') <NEW_LINE> response = self.client.delete(f'/api/stories/{self.story.id}') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) <NEW_LI... | 스토리 삭제 | 625941ca23e79379d52ee60a |
def test_drop_valid_index_policy(self): <NEW_LINE> <INDENT> policy = {'timeout': 1000} <NEW_LINE> self.as_connection.index_integer_create('test', 'demo', 'age', 'age_index', policy) <NEW_LINE> retobj = self.as_connection.index_remove('test', 'age_index', policy) <NEW_LINE> ensure_dropped_index(self.as_connection, 'test... | Invoke drop valid index() policy | 625941cacc0a2c11143dcf36 |
def __str__(self): <NEW_LINE> <INDENT> string = self.observed_variable.name <NEW_LINE> if self.observed_value: <NEW_LINE> <INDENT> string += ' = ' + self.observed_value <NEW_LINE> <DEDENT> return string | Devuelve la representacion como cadena de una variable de evidencia.
@rtype: str
@return: Cadena con el formato variable_observada = valor_observado. | 625941ca099cdd3c635f0d00 |
def properties(): <NEW_LINE> <INDENT> pass | Retrieve the property store for this notification.
@return: an L{IPropertyStore}. | 625941caa934411ee3751739 |
def get_item(): <NEW_LINE> <INDENT> return registries.load( registries._h5py_to_h5preserve( h5py_obj[name], load_on_demand=True ) ) | func for OnDemandWrapper | 625941cafb3f5b602dac3738 |
def _CreateConstantS32Computation(self): <NEW_LINE> <INDENT> c = self._NewComputation("constant_s32_one") <NEW_LINE> c.ParameterFromNumpy(NumpyArrayF32(0)) <NEW_LINE> c.ConstantS32Scalar(1) <NEW_LINE> return c.Build() | Computation (f32) -> s32 that returns a constant 1 for any input. | 625941ca85dfad0860c3af00 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vouchermanager.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are y... | Run administrative tasks. | 625941ca507cdc57c6306d7f |
def load_notung_nhx(filename): <NEW_LINE> <INDENT> with open(filename, 'r') as f: <NEW_LINE> <INDENT> tree = read(f, format='newick') <NEW_LINE> <DEDENT> tree.rooted = True <NEW_LINE> tree = to_networkx(tree) <NEW_LINE> node_translator = {} <NEW_LINE> for node in tree.nodes(): <NEW_LINE> <INDENT> node_translator[node] ... | load reconciled gene tree from NHX formatted file
returns networkx graph object
strips information from the comment field and converts into node properties | 625941ca3cc13d1c6d3c7420 |
def recherche_pivot(A,i): <NEW_LINE> <INDENT> n=len(A) <NEW_LINE> indice_piv=i <NEW_LINE> for k in range(i+1,n): <NEW_LINE> <INDENT> if abs(A[k][i])>abs(A[indice_piv][i]): <NEW_LINE> <INDENT> indice_piv=k <NEW_LINE> <DEDENT> <DEDENT> return(indice_piv) | retourne le plus grand pivot en valeur absolue
sous A[i][i] | 625941ca10dbd63aa1bd2c49 |
def query(self): <NEW_LINE> <INDENT> starttimeq = self.start_time.isoformat() <NEW_LINE> endtimeq = self.end_time.isoformat() <NEW_LINE> probelist = self.config[self.report_type.lower()]['OSG_flocking_probe_list'] <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> self.logger.info(self.indexpattern) <NEW_LINE> self.logger... | Method to query Elasticsearch cluster for EfficiencyReport information
:return elasticsearch_dsl.Search: Search object containing ES query | 625941ca85dfad0860c3af01 |
def warn(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.warn_err(CoconutWarning(*args, **kwargs)) | Creates and displays a warning. | 625941ca435de62698dfdcf2 |
def decompress(content, encoding, filename='N/A'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> encoding = (encoding or '').lower() <NEW_LINE> if encoding == '': <NEW_LINE> <INDENT> return content <NEW_LINE> <DEDENT> elif len(content) == 0: <NEW_LINE> <INDENT> raise DecompressionError('File contains zero bytes: ' + str... | Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip' or 'br'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported codec is specified.
compression.EncodeError if the encoder has... | 625941cacad5886f8bd2707f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.