code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def diagonalize_real_symmetric_and_sorted_diagonal_matrices( symmetric_matrix: np.ndarray, diagonal_matrix: np.ndarray, tolerance: Tolerance = Tolerance.DEFAULT ) -> np.ndarray: <NEW_LINE> <INDENT> if (np.any(np.imag(symmetric_matrix) != 0) or not predicates.is_hermitian(symmetric_matrix)): <NEW_LINE> <INDENT> raise Va... | Returns an orthogonal matrix that diagonalizes both given matrices.
The given matrices must commute.
Guarantees that the sorted diagonal matrix is not permuted by the
diagonalization (except for nearly-equal values).
Args:
symmetric_matrix: A real symmetric matrix.
diagonal_matrix: A real diagonal matrix with... | 625941d332920d7e50b283ac |
def num_samples(self, **kwargs): <NEW_LINE> <INDENT> return self.n_samples | Get the number of samples in this data source.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown. | 625941d3a219f33f34628b42 |
def write(self, *args): <NEW_LINE> <INDENT> stream = self.fobj if not callable(self.fobj) else self.fobj() <NEW_LINE> if self.prefix: <NEW_LINE> <INDENT> stream.write(self.prefix) <NEW_LINE> <DEDENT> for s in args: <NEW_LINE> <INDENT> if isinstance(s, str): <NEW_LINE> <INDENT> stream.write(s) <NEW_LINE> <DEDENT> elif s... | Write any number of arguments to the stream. | 625941d33317a56b86939e30 |
def get_schedule_list(factory_id): <NEW_LINE> <INDENT> result = [] <NEW_LINE> schedule_obj = WorkScheduleDB(factory_id=factory_id) <NEW_LINE> schedule_iter = schedule_obj.get_group_and_schedule() <NEW_LINE> workgroup_obj = WorkGroupDB(factory_id=factory_id) <NEW_LINE> for schedule in schedule_iter: <NEW_LINE> <INDENT> ... | 根据该工厂中的work_schedule获取班组的安排信息
:param factory_id: 工厂id
:return: 成功返回班组的安排信息,包含班组,班次,时间段的迭代器 | 625941d3be8e80087fb20e1c |
def _read(self, ti, try_number, metadata=None): <NEW_LINE> <INDENT> log_relative_path = self._render_filename(ti, try_number) <NEW_LINE> remote_loc = os.path.join(self.remote_base, log_relative_path) <NEW_LINE> log_exists = False <NEW_LINE> log = "" <NEW_LINE> try: <NEW_LINE> <INDENT> log_exists = self.s3_log_exists(re... | Read logs of given task instance and try_number from S3 remote storage.
If failed, read the log from task instance host machine.
:param ti: task instance object
:param try_number: task instance try_number to read logs from
:param metadata: log metadata,
can be used for steaming log reading and auto-ta... | 625941d321bff66bcd684b2c |
def _reset_index_cache(self): <NEW_LINE> <INDENT> self._indexed_keys = set() <NEW_LINE> self._deindexed_keys = set() | Reset attributes used to store deindexed/indexed values, used to
rollback the index when something failed. | 625941d32c8b7c6e89b3599b |
def points(self): <NEW_LINE> <INDENT> return _digital_swig.digital_constellation_dqpsk_sptr_points(self) | points(self) -> gr_complex_vector
Returns the set of points in this constellation. | 625941d382261d6c526ab67c |
def function_5(): <NEW_LINE> <INDENT> const_number_01 = const_function(-0.1) <NEW_LINE> const_number_03 = const_function(0.3) <NEW_LINE> const_number_07 = const_function(0.7) <NEW_LINE> const_number_1 = const_function(1) <NEW_LINE> same_number = identity() <NEW_LINE> pow_number = mul_functions(same_number, same_number)... | return f(x) = 0.1*(0.3x^2+0.7x-1)dx | 625941d3f548e778e58cd759 |
def proxy_catch_two(self): <NEW_LINE> <INDENT> url_list = [ 'https://www.kuaidaili.com/free/inha/{}/', 'https://www.kuaidaili.com/free/intr/{}/'] <NEW_LINE> for url in url_list: <NEW_LINE> <INDENT> ip_url = [url.format(str(i)) for i in range(1, 50)] <NEW_LINE> for real_url in ip_url: <NEW_LINE> <INDENT> data = requests... | 快代理 https://www.kuaidaili.com | 625941d3596a897236089c9a |
@contextlib.contextmanager <NEW_LINE> def temp_dir(path=None, quiet=False): <NEW_LINE> <INDENT> dir_created = False <NEW_LINE> if path is None: <NEW_LINE> <INDENT> path = tempfile.mkdtemp() <NEW_LINE> dir_created = True <NEW_LINE> path = os.path.realpath(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LIN... | Return a context manager that creates a temporary directory.
Arguments:
path: the directory to create temporarily. If omitted or None,
defaults to creating a temporary directory using tempfile.mkdtemp.
quiet: if False (the default), the context manager raises an exception
on error. Otherwise, if the pa... | 625941d3dd821e528d63b383 |
def _class_indices_to_onehots(class_indices): <NEW_LINE> <INDENT> num_classes = len(class_indices) <NEW_LINE> class_onehots = {} <NEW_LINE> for class_, index in class_indices.iteritems(): <NEW_LINE> <INDENT> onehot = numpy.zeros(num_classes) <NEW_LINE> onehot[index] = 1.0 <NEW_LINE> class_onehots[class_] = onehot <NEW_... | Return dict mapping class -> onehot_vec. | 625941d3bd1bec0571d9080a |
def initiate_role_from_overlap_TE(nafobj, wSpan, tSpan, timeExList): <NEW_LINE> <INDENT> for te in timeExList: <NEW_LINE> <INDENT> span = te[2] <NEW_LINE> if list_overlap(span, wSpan): <NEW_LINE> <INDENT> tValue = te[1] <NEW_LINE> tClass = 'time_' + te[0] <NEW_LINE> myRole = NafRole(entityType=tClass, timeValue=tValue)... | Function that maps word span of time expression to term span of role
Adapts span if necessary | 625941d3ff9c53063f47c3ce |
def HandleMessage(self, message): <NEW_LINE> <INDENT> self._is_active = True <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> suspended_action_id = message.payload.iterator.suspended_action <NEW_LINE> action = self.suspended_actions[suspended_action_id] <NEW_LINE> <DEDENT> except (AttributeError, KeyError):... | Entry point for processing jobs.
Args:
message: The GrrMessage that was delivered from the server. | 625941d3a05bb46b383ec9fc |
def _updateProjectComboBox(self): <NEW_LINE> <INDENT> projects = nuke.frameioDelegate.frameioSession.projectdict().values() <NEW_LINE> self.projectComboBox.clear() <NEW_LINE> for project in projects: <NEW_LINE> <INDENT> self.projectComboBox.addItem(str(project)) | Updates the project dropdown menu with projects from the Authenticated session | 625941d3b830903b967e9ae5 |
def test_01_website_seo_blog_controller(self): <NEW_LINE> <INDENT> for post in self.post.search([]): <NEW_LINE> <INDENT> if post.seo_url and post.blog_id.seo_url and post.website_published: <NEW_LINE> <INDENT> url = '/%s/%s' % (post.blog_id.seo_url, post.seo_url) <NEW_LINE> r = self.url_open(url) <NEW_LINE> code = self... | Test valid seo url blog post. | 625941d324f1403a92600d40 |
def test_02_cancel_confirm_purchase_order_one_steps(self): <NEW_LINE> <INDENT> self.warehouse.write({'delivery_steps': 'ship_only', 'reception_steps': 'one_step'}) <NEW_LINE> self.picking_out.write({'location_id': self.warehouse.out_type_id.default_location_src_id.id}) <NEW_LINE> self.move.write({'location_id': self.wa... | Check the picking and moves status related purchase order, When canceling purchase order
after confirming.
Ex.
1) Set one steps of receiption and delivery on the warehouse.
2) Create Delivery order with mto move and confirm the order, related RFQ should be generated.
3) Cancel 'confirmed' purchase order, sh... | 625941d3bd1bec0571d9080b |
def BO2mol(mol, BO_matrix, atoms, atomic_valence_electrons, mol_charge, allow_charged_fragments=True, use_atom_maps=False): <NEW_LINE> <INDENT> l = len(BO_matrix) <NEW_LINE> l2 = len(atoms) <NEW_LINE> BO_valences = list(BO_matrix.sum(axis=1)) <NEW_LINE> if (l != l2): <NEW_LINE> <INDENT> raise RuntimeError('sizes of ad... | based on code written by Paolo Toscani
From bond order, atoms, valence structure and total charge, generate an
rdkit molecule.
args:
mol - rdkit molecule
BO_matrix - bond order matrix of molecule
atoms - list of integer atomic symbols
atomic_valence_electrons -
mol_charge - total charge of molecul... | 625941d330bbd722463cbfa2 |
def random(pages=1): <NEW_LINE> <INDENT> query_params = { 'lang': LANG } <NEW_LINE> request = _wiki_request(query_params) <NEW_LINE> titles = [page['title'] for page in request['query']['random']] <NEW_LINE> if len(titles) == 1: <NEW_LINE> <INDENT> return titles[0] <NEW_LINE> <DEDENT> return titles | Get a list of random Wikia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, U
Keyword arguments:
* pages - the number of random pages returned (max of 10) | 625941d356b00c62f0f14835 |
def get_rprop_delta_zero(self): <NEW_LINE> <INDENT> pass | The initial step-size is a positive number determining the initial step
size. | 625941d3d10714528d5ffec0 |
def _onConsumerClosed(self, consumer): <NEW_LINE> <INDENT> self._consumers.remove(consumer) | Called by consumer instance's close() method to remove the consumer from
our outstanding consumers list | 625941d3498bea3a759b9c8a |
def _initializer(shape, dtype=tf.float32): <NEW_LINE> <INDENT> size = shape[0] <NEW_LINE> t = np.zeros(shape) <NEW_LINE> t[:, size:size * 2] = np.identity(size) * scale <NEW_LINE> t[:, :size] = orthogonal([size, size]) <NEW_LINE> t[:, size * 2:size * 3] = orthogonal([size, size]) <NEW_LINE> t[:, size * 3:] = orthogonal... | Ugly cause LSTM params calculated in one matrix multiply | 625941d3ab23a570cc25035e |
def test_xml_empty_tag(self): <NEW_LINE> <INDENT> self.writer._xml_empty_tag('foo') <NEW_LINE> exp = """<foo/>""" <NEW_LINE> got = self.fh.getvalue() <NEW_LINE> self.assertEqual(got, exp) | Test _xml_empty_tag() | 625941d37c178a314d6ef63c |
@login_required <NEW_LINE> @permission_required(perm=(CHANGE_SERVER,), raise_exception=True) <NEW_LINE> def update(request, srv_id): <NEW_LINE> <INDENT> if request.method == "GET": <NEW_LINE> <INDENT> log.info('Into Update server page.') <NEW_LINE> srvs = Server.objects.filter(id=srv_id) <NEW_LINE> if srvs: <NEW_LINE> ... | modify Server by id
:param request:
:param srv_id: server id
:return: | 625941d3fbf16365ca6f63a3 |
def nonbonded_v3_on_specific_pairs(conf, params, box, inds_l, inds_r, beta: float, cutoff: Optional[float] = None): <NEW_LINE> <INDENT> dij = distance_on_pairs(conf[inds_l], conf[inds_r], box) <NEW_LINE> if cutoff is None: <NEW_LINE> <INDENT> cutoff = np.inf <NEW_LINE> <DEDENT> keep_mask = dij <= cutoff <NEW_LINE> def ... | See nonbonded_v3 docstring for more details
Notes
-----
* Responsibility of caller to ensure pair indices (inds_l, inds_r) are complete.
In case of parameter interpolation, more pairs need to be added. | 625941d34a966d76dd5511ec |
def test_CCT_to_uv_ohno2013(self): <NEW_LINE> <INDENT> cmfs = STANDARD_OBSERVERS_CMFS.get( 'CIE 1931 2 Degree Standard Observer') <NEW_LINE> np.testing.assert_almost_equal( CCT_to_uv_ohno2013( 6507.4342201047066, 0.003223690901512735, cmfs), (0.19780034881616862, 0.31220050291046603), decimal=7) <NEW_LINE> np.testing.a... | Tests :func:`colour.temperature.cct.CCT_to_uv_ohno2013` definition. | 625941d36fece00bbac2d91c |
def test_no_questions(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('polls:index')) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, "no polls are available.") <NEW_LINE> self.assertQuerysetEqual(response.context['latest_question_list'], []) | 문제가 없을 경우 출력 테스트 | 625941d3adb09d7d5db6c96a |
def add_fiddle(self, fiddle_function): <NEW_LINE> <INDENT> self._fiddle = fiddle_function <NEW_LINE> Job.depends_on(self, FunctionInvariant(self.output_filename + '_fiddle', fiddle_function)) | Add another function that is called right before the plot is
rendered with a pyggplot.Plot as the only argument in order to be able
to 'fiddle' with the plot.
Please note: if you want to remove an add_fiddle, the plot is only redone if you
call add_fiddle(None) instead of removing the call altogether | 625941d3656771135c3eba4b |
def create_data_loader_with_transform(dataset, root, batch_size, train_transform=None,test_transform=None): <NEW_LINE> <INDENT> if dataset.lower() == "mnist": <NEW_LINE> <INDENT> trainSets = datasets.MNIST(root,train=True,download=False,transform=training_transform) <NEW_LINE> trainDataloader = DataLoader(dataset=train... | create various dataloader object
Args:
str,str,tranform, transform
Return: | 625941d37c178a314d6ef63d |
def rewind(self, n: int): <NEW_LINE> <INDENT> self.p = self.p - n <NEW_LINE> self.c = self.input[self.p] | Rewinds the character stream by 'n' characters.
Sets self.p = self.p - n
Then, sets self.c = self.p | 625941d3a05bb46b383ec9fd |
def _pd_tv2d(x, w, y, max_iters, info, **kwargs): <NEW_LINE> <INDENT> _call(lib.PD2_TV, x, (w, w), (1, 1), (1, 2), y, info, x.shape, 2, 2, kwargs['n_threads'], max_iters) | Proximal dykstra method for 2D TV proximity | 625941d363f4b57ef00012f1 |
def distanceSq(self, v2): <NEW_LINE> <INDENT> dx = v2.x - self.x <NEW_LINE> dy = v2.y - self.y <NEW_LINE> return dx*dx + dy*dy | the squared distance between self and v2 vector | 625941d3236d856c2ad449b7 |
def test_issue3009(en_vocab): <NEW_LINE> <INDENT> patterns = [ [{"LEMMA": "have"}, {"LOWER": "to"}, {"LOWER": "do"}, {"TAG": "IN"}], [ {"LEMMA": "have"}, {"IS_ASCII": True, "IS_PUNCT": False, "OP": "*"}, {"LOWER": "to"}, {"LOWER": "do"}, {"TAG": "IN"}, ], [ {"LEMMA": "have"}, {"IS_ASCII": True, "IS_PUNCT": False, "OP":... | Test problem with matcher quantifiers | 625941d3925a0f43d254a053 |
def getpager(): <NEW_LINE> <INDENT> if not hasattr(sys.stdout, "isatty"): <NEW_LINE> <INDENT> return plainpager <NEW_LINE> <DEDENT> if not sys.stdin.isatty() or not sys.stdout.isatty(): <NEW_LINE> <INDENT> return plainpager <NEW_LINE> <DEDENT> if 'PAGER' in os.environ: <NEW_LINE> <INDENT> if sys.platform == 'win32': <N... | Decide what method to use for paging through text. | 625941d3a17c0f6771cbe22b |
def test__postgres_ready_success(mocker): <NEW_LINE> <INDENT> expected_response = True <NEW_LINE> db = mocker.patch('versions_service.api.v1.health.endpoints.db') <NEW_LINE> db.session.execute().fetchone.return_value = [1] <NEW_LINE> actual_response = _postgres_ready() <NEW_LINE> db.session.execute.assert_has_calls([mo... | test__postgres_ready_success
Tests that the _postgres_ready() function returns True when the database behaves as expected.
:param mocker:
A pytest-mock fixture | 625941d35f7d997b87174c74 |
def __init__(self): <NEW_LINE> <INDENT> self.new_element = None <NEW_LINE> self.linked_list = DoublyLinkedListWithTail() | Initilze Stack object instance | 625941d3287bf620b61d3c3f |
@click.command() <NEW_LINE> @click.option('--seed', default=1) <NEW_LINE> @click.option('--epochs', default=300) <NEW_LINE> @click.option('--rollouts_per_task', default=40) <NEW_LINE> @click.option('--meta_batch_size', default=20) <NEW_LINE> @wrap_experiment(snapshot_mode='all') <NEW_LINE> def maml_trpo_half_cheetah_di... | Set up environment and algorithm and run the task.
Args:
ctxt (garage.experiment.ExperimentContext): The experiment
configuration used by LocalRunner to create the snapshotter.
seed (int): Used to seed the random number generator to produce
determinism.
epochs (int): Number of training epoc... | 625941d34428ac0f6e5ba9ce |
def get_devices(login): <NEW_LINE> <INDENT> with session_scope() as session: <NEW_LINE> <INDENT> reloaded_login = session.query(model.Login).filter(model.Login.id == login.id).one() <NEW_LINE> devices = reloaded_login.devices <NEW_LINE> <DEDENT> return devices | Get devices of a specific login. | 625941d356ac1b37e62643a9 |
def check_queries_using_temporary(database, queries): <NEW_LINE> <INDENT> filtered = filter_explain_extra(database, queries, check='Using temporary') <NEW_LINE> for (query, table_used, context) in filtered: <NEW_LINE> <INDENT> yield LinterEntry(linter_type='queries_using_temporary', table_name=table_used, message='"{}"... | Using temporary
To resolve the query, MySQL needs to create a temporary table to hold the result. This
typically happens if the query contains GROUP BY and ORDER BY clauses that list columns
differently.
:type database indexdigest.database.Database
:type queries list[str]
:rtype: list[LinterEntry] | 625941d321bff66bcd684b2d |
def GetFillModel(self, security): <NEW_LINE> <INDENT> pass | GetFillModel(self: IBrokerageModel, security: Security) -> IFillModel
Gets a new fill model that represents this
brokerage's fill behavior
security: The security to get fill model for
Returns: The new fill model for this brokerage | 625941d3cb5e8a47e48b7c84 |
def over_under(pref, xeid, xhash, args_dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp_dict = {} <NEW_LINE> for period, value in args_dict.items(): <NEW_LINE> <INDENT> mtch_type, max_odds, handy_value, tids = '', 0, 0, [] <NEW_LINE> resp_dict[period] = {} <NEW_LINE> odds_dict = get_page(pref, xeid, xhash, valu... | Коэф. на Over/Under
Arguments:
pref: '1-6' -> baseball
xeid: '67Upolsm'
xhash: 'yj1b4'
args_dict: dict(ftot='5-1', frst='5-3')
Returns: {
'ftot': {
'open': [1.84, 1.97],
'close': [1.75, 2.08],
'mean': [1.79, 2.02],
'value': [10.5, 10.5]},
'frst': {
'ope... | 625941d3a8370b7717052a7a |
def forward(self, x): <NEW_LINE> <INDENT> out = F.relu(self.fc1(x)) <NEW_LINE> out = self.drop(out) <NEW_LINE> out = F.sigmoid(self.fc2(out)) <NEW_LINE> return out | Perform a forward pass of our model on input features, x.
:param x: A batch of input features of size (batch_size, input_features)
:return: A single, sigmoid-activated value as output | 625941d3377c676e91272384 |
def ApplyEdit(self, row, col, grid): <NEW_LINE> <INDENT> grid.GetTable().SetValue(row, col, self.nextval) | Called only in wx >= 2.9
Save the value of the control into the grid if EndEdit() returns as True | 625941d326238365f5f0f04c |
def __init__(self, make, model, year): <NEW_LINE> <INDENT> super().__init__(make, model, year) <NEW_LINE> self.battery = Battery() <NEW_LINE> self.battery_size = 75 | Initialize attributes of the parent class. | 625941d367a9b606de4a8094 |
def test_with_scripts(with_scripts): <NEW_LINE> <INDENT> package_dir, script_dir = with_scripts <NEW_LINE> build() <NEW_LINE> dist_dir = verify_artifacts(package_dir) <NEW_LINE> package_name = os.path.basename(package_dir) <NEW_LINE> expected_in_wheel = [ "/scripts/my_script", "{}/__init__.py".format(package_name), "{}... | Ensure the executable scripts are being included. | 625941d3dc8b845886cb5711 |
def _from_sbj_vrb_obj(self): <NEW_LINE> <INDENT> assert isinstance(self.sbj, Word) <NEW_LINE> assert isinstance(self.vrb, Word) <NEW_LINE> assert isinstance(self.obj, Word) <NEW_LINE> self.lex.populate_word_from_sbj_vrb_obj( self, self.sbj, self.vrb, self.obj ) | Construct a word by looking up its subject-verb-object. | 625941d3aad79263cf390c1f |
def main(): <NEW_LINE> <INDENT> return 0 | To do: Main function. | 625941d396565a6dacc8f8a7 |
def itemData(self, QModelIndex): <NEW_LINE> <INDENT> pass | QAbstractItemModel.itemData(QModelIndex) -> dict-of-int-QVariant | 625941d33317a56b86939e31 |
def is_plugin_enabled(self, plugin_id): <NEW_LINE> <INDENT> return plugin_id in self.enabled_plugins | Returns whether a plugin is currently enabled and loaded | 625941d3460517430c39435e |
def standardize_cipher(word): <NEW_LINE> <INDENT> vow_re = re.compile(r'''(?<!`)({0})[{1}]'''.format( '|'.join(cipher_vow_bases), ''.join(cipher_modifiers)), re.X) <NEW_LINE> no_re = re.compile(r'''(?<!`)([{0}{1}])(?![{2}])'''.format( ''.join(cipher_cons_bases),''.join(cipher_vow_bases), ''.join(cipher_modifiers)), re.... | Turns default Cipher word to IPA. Syllable separation and invalid chars
stay as is. Also works for sentences. | 625941d363f4b57ef00012f2 |
def embed_backgrounds(self): <NEW_LINE> <INDENT> def repl(matchobj): <NEW_LINE> <INDENT> image_url = matchobj.groups()[0] <NEW_LINE> image_url = urlparse(image_url) <NEW_LINE> server_path = join(self.pub_dir, image_url.path.lstrip('/')) <NEW_LINE> if os.path.exists(server_path): <NEW_LINE> <INDENT> filename = os.path.b... | Assumes self.inline_html has been run. | 625941d3fbf16365ca6f63a4 |
def test_to_frame_override(self): <NEW_LINE> <INDENT> ind = pd.date_range(start="2000/1/1", periods=10) <NEW_LINE> events = [TestEvent(ind[i], i, len(ind)-i) for i in range(len(ind))] <NEW_LINE> el = ef.EventList(events, attrs=['id'], repr_col=True) <NEW_LINE> correct = el.to_frame() <NEW_LINE> el2 = ef.EventList(event... | Test to_frame(attrs, repr_col) | 625941d3ac7a0e7691ed42a6 |
def _get_read_receipt(self): <NEW_LINE> <INDENT> def is_read_receipt(event): <NEW_LINE> <INDENT> return event["type"] == "m.receipt" <NEW_LINE> <DEDENT> channel = self.make_request( "GET", self.url % self.next_batch, access_token=self.tok, ) <NEW_LINE> self.assertEqual(channel.code, 200) <NEW_LINE> self.next_batch = ch... | Syncs and returns the read receipt. | 625941d3e76e3b2f99f3a9e5 |
def output_src_nat_rules(self, rules): <NEW_LINE> <INDENT> print(" #===========================") <NEW_LINE> print(" # Nat outbound rules") <NEW_LINE> print(" # ") <NEW_LINE> interfaces = list(self._data.target.interfaces.keys()) <NEW_LINE> interfaces.append('floating') <NEW_LINE> definitions... | Output outbound definitions for pfsense_aggregate | 625941d39f2886367277aa69 |
def image_save(image_object, image_type, image_path): <NEW_LINE> <INDENT> if image_object and image_type and image_path: <NEW_LINE> <INDENT> if image_type == 'png': <NEW_LINE> <INDENT> image_object.save(image_path, format='PNG', optimize=True, dpi=(image_dpi,image_dpi)) <NEW_LINE> <DEDENT> elif image_type == 'gif': <NE... | Saves the given image to the given file with the given type
param: image_object: PIL/Pillow Image Object
param: image_type: one of the standard 3-letter image types
options: png, gif, jpg, pcx, tif, and bmp
param: image_path: full file path where the image will be saved, including filename and extension | 625941d356b00c62f0f14836 |
def compute_Phi(x,p): <NEW_LINE> <INDENT> Phi=[] <NEW_LINE> for j in range(0,len(x)): <NEW_LINE> <INDENT> for k in range(0,len(x[j])): <NEW_LINE> <INDENT> val=x[j,k] <NEW_LINE> n_row=[] <NEW_LINE> for i in range(0,p): <NEW_LINE> <INDENT> if i==0: <NEW_LINE> <INDENT> if val>0: <NEW_LINE> <INDENT> n_row.append(1.) <NEW_L... | Compute the feature matrix Phi of x. We will construct p polynoials, the p features of the data samples.
The features of each sample, is x^0, x^1, x^2 ... x^(p-1)
Input:
x : a vector of samples in one dimensional space, a numpy vector of shape n by 1.
Here n is the number of samples.
p : the number of ... | 625941d394891a1f4081bc86 |
def get_user_id(self): <NEW_LINE> <INDENT> sql = 'SELECT id FROM t_user WHERE loginName = \'Automation\'' <NEW_LINE> return self.s.select(sql)[0][0] | 获取Automation user_id | 625941d316aa5153ce362654 |
def testBasic(self): <NEW_LINE> <INDENT> self.copyfiles() <NEW_LINE> data = mooseutils.VectorPostprocessorReader('vpp_*.csv') <NEW_LINE> self.assertEqual(data.filename, os.path.basename(self._pattern)) <NEW_LINE> self.assertTrue(data._timedata) <NEW_LINE> self.assertTrue(data) <NEW_LINE> self.assertEqual(data.data.shap... | Test that if a file exists it is loaded w/o error. | 625941d350812a4eaa59c4fd |
def skip_gram_cost_gradient(parameters, input, outputs): <NEW_LINE> <INDENT> total_cost = 0.0 <NEW_LINE> total_gradient = np.zeros_like(parameters) <NEW_LINE> for output in outputs: <NEW_LINE> <INDENT> cost, gradient = softmax_cost_gradient(parameters, input, output) <NEW_LINE> total_cost += cost <NEW_LINE> total_gradi... | Skip-gram model in word2vec
:param parameters: word vectors for input and output (shape: (2, vocabulary_size, vector_size))
:param input: index of center word to input word vectors
:param outputs: indices of context words to output word vectors (shape: (context_size))
:return: cost and gradient | 625941d3d99f1b3c44c67769 |
def delete_item_metadata(self, item_uuid): <NEW_LINE> <INDENT> endpoint = "/RESTapi/items/{}/metadata".format(item_uuid) <NEW_LINE> response = self._delete(endpoint, json_expected=False) <NEW_LINE> return response | Clear item metadata. | 625941d357b8e32f52483678 |
def climbStairs(self, n): <NEW_LINE> <INDENT> return self.dynamic(n) | :type n: int
:rtype: int | 625941d3442bda511e8be5f2 |
def get_shared_data(username=''): <NEW_LINE> <INDENT> resp = requests.get(BASE_URL + username).text <NEW_LINE> if resp is not None and '_sharedData' in resp: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shared_data = resp.split("window._sharedData = ")[1].split(";</script>")[0] <NEW_LINE> return json.loads(shared_data)... | Fetches the user's metadata. | 625941d3a4f1c619b28b0213 |
def convolve(self, kernel, method="fft", mode="same"): <NEW_LINE> <INDENT> from gammapy.irf import PSFKernel <NEW_LINE> convolve = scipy.signal.convolve <NEW_LINE> if self.geom.is_image and not isinstance(kernel, PSFKernel): <NEW_LINE> <INDENT> if kernel.ndim > 2: <NEW_LINE> <INDENT> raise ValueError( "Image convolutio... | Convolve map with a kernel.
If the kernel is two dimensional, it is applied to all image planes likewise.
If the kernel is higher dimensional, it should either match the map in the number of
dimensions or the map must be an image (no non-spatial axes). In that case, the
corresponding kernel is selected and applied to ... | 625941d371ff763f4b54986a |
def p_unary_prefix_operators(p): <NEW_LINE> <INDENT> pass | expression : '-' expression %prec UMINUS
| '+' expression %prec UPLUS
| '!' expression %prec UEXCLAMATION | 625941d34d74a7450ccd439f |
def set_color(self, use_color): <NEW_LINE> <INDENT> self._use_color = use_color | Toggle color image usage on/off.
If False is passed, use black-white images for testing,
is True is passed (the default) use color images. | 625941d3435de62698dfde29 |
def get_attachment(self, aname): <NEW_LINE> <INDENT> rsp = self._request('get', self.ctx.url + "/jobs/" + self.jobid + "/attachments/" + aname + "/blob", [200]) <NEW_LINE> return rsp.content | Get a job attachment
Args:
aname: Attachment name
Returns:
Attachment content as a string | 625941d3d486a94d0b98e322 |
def undefined_operation(author: str, arg: str, svc: Any) -> str: <NEW_LINE> <INDENT> raise NotImplementedError('Undefined operation') | This is the default action if nothing is defined in commands.json mapping
author -> (ignored)
arg -> (ignored)
svc -> (ignored) | 625941d373bcbd0ca4b2c252 |
def get_files(file_dir): <NEW_LINE> <INDENT> filenames = [] <NEW_LINE> labels = [] <NEW_LINE> for line in open('test.txt'): <NEW_LINE> <INDENT> line = line.strip('\n') + '.jpg' <NEW_LINE> labels.append(line.split('/')[0]) <NEW_LINE> filenames.append(os.path.join(file_dir, line)) <NEW_LINE> <DEDENT> print('There are tot... | Args:
file_dir: directory include images
Returns:
filenames: list of path of images
labels: list of labels corresponding to images | 625941d38e7ae83300e4b1a9 |
def run_migrations_offline(): <NEW_LINE> <INDENT> url = config.get_main_option("sqlalchemy.url") <NEW_LINE> context.configure( url=url, target_metadata=target_metadata, transaction_per_migration=True, literal_binds=True) <NEW_LINE> with context.begin_transaction(): <NEW_LINE> <INDENT> context.run_migrations() | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | 625941d33617ad0b5ed680d2 |
def set_cert(self, cert, key): <NEW_LINE> <INDENT> rel = self._unit.relation <NEW_LINE> for unit in self._unit.relation.units: <NEW_LINE> <INDENT> pub_key = self.derive_publish_key(unit=unit) <NEW_LINE> data = rel.to_publish.get( pub_key, {}) <NEW_LINE> data['app_data'] = { 'cert': cert, 'key': key, } <NEW_LINE> rel.to... | Send the cert and key to all units of the application
:param cert: TLS Certificate
:type cert: str
:param key: TLS Private Key
:type cert: str | 625941d30c0af96317bb83c5 |
def list(self): <NEW_LINE> <INDENT> return self._get("") | load and return all items from local storage
| 625941d3099cdd3c635f0e37 |
def is_copy(self): <NEW_LINE> <INDENT> return ((not self.X.shape[-1] or self.X.base is None) and (self.Y.base is None) and (self.metas.base is None) and (self.W.base is None)) | Return `True` if the table owns its data | 625941d3fb3f5b602dac3871 |
def _update_data(self, row, start, end, **kwargs): <NEW_LINE> <INDENT> row = self._add_common_usage_info(row, start, end) <NEW_LINE> meter_id = self._meter_id if self._meter_id else self.fake.uuid4() <NEW_LINE> rate = self._resource_rate if self._resource_rate else round(uniform(0.1, 0.50), 5) <NEW_LINE> amount = self.... | Update data with generator specific data. | 625941d350485f2cf553cf77 |
def basename(self, url): <NEW_LINE> <INDENT> url = os.path.basename(url) <NEW_LINE> found = re.search(r"(.*)\?(.*)", url) <NEW_LINE> return found.group(1) | Returns the basename (only filename without query parameters)
TODO: can the regex fail? | 625941d3d164cc6175782f2a |
def can_write(username, server_path): <NEW_LINE> <INDENT> return server_path.split('/')[0] == username | This sharing system is in read-only mode.
Check if an user is the owner of a file (or father directory).
(the server_path begins with his name) | 625941d3e5267d203edcde78 |
def get_lowest_levels(caves: Cave) -> list[Point]: <NEW_LINE> <INDENT> levels = [] <NEW_LINE> for x in range(caves.shape()[0]): <NEW_LINE> <INDENT> for y in range(caves.shape()[1]): <NEW_LINE> <INDENT> p = Point(x, y) <NEW_LINE> if caves.is_lowest(p): <NEW_LINE> <INDENT> levels.append(p) <NEW_LINE> <DEDENT> <DEDENT> <D... | Get risk level of all lowest points in Caves | 625941d3cb5e8a47e48b7c85 |
def get_NumColumns(self): <NEW_LINE> <INDENT> return super(ISelectionPalette, self).get_NumColumns() | Method ISelectionPalette.get_NumColumns
OUTPUT
NumColumns : long* | 625941d33cc13d1c6d3c7556 |
def __getattr__(self, name): <NEW_LINE> <INDENT> if "_options" not in self.__dict__ or name not in self._options: <NEW_LINE> <INDENT> raise AttributeError("Option {0} does not exist.".format(name)) <NEW_LINE> <DEDENT> return self.get(name) | Lookup missing attributes in the options dictionary. | 625941d3090684286d50eec3 |
def sample(self, X = None, metric = 'euclidean'): <NEW_LINE> <INDENT> assert(self.converged == True), 'Train model before running sample() method' <NEW_LINE> n = X.shape[0] <NEW_LINE> y_hat = np.zeros(n) <NEW_LINE> for i in xrange(n): <NEW_LINE> <INDENT> nearest_node = self._nearest_terminal_node(x = X[i, :], metric = ... | Sample labels based distribution of closest terminal nodes
Parameters
----------
X : 2d array-like
Array of test features
metric : str (default = 'euclidean')
Method for calculating distances. See scipy.spatial.distances for valid options
Returns
-------
y_hat : 1d array-like
Array of predicted labels | 625941d3eab8aa0e5d26dd35 |
def _start(self): <NEW_LINE> <INDENT> import asyncio <NEW_LINE> if self.poll_tasks: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> async def poll_neighbour(self): <NEW_LINE> <INDENT> self.logger.debug("polling neighbor table") <NEW_LINE> self.neighbors = EthernetPortManager._get_neigh() <NEW_LINE> await asyncio.sleep(1... | Internal function to register as task and attach/start the event
loop
Returns:
None | 625941d37b25080760e39635 |
def test_import_comma(): <NEW_LINE> <INDENT> import comma <NEW_LINE> return True | Testing the main package can be imported. | 625941d3377c676e91272385 |
def _propose_atomic_position(self, system, atom, bonded_atom, angle_atom, torsion_atom, torsion_parameters, positions): <NEW_LINE> <INDENT> logging.debug("Proposing position %d with bond atom %d, angle atom %d, torsion atom %d" % (atom, bonded_atom, angle_atom, torsion_atom)) <NEW_LINE> r0, k_eq = self._get_bond_parame... | Method to propose the position of a single atom.
Arguments
---------
system : simtk.openmm.System
the system containing the atom of interest
atom : int
the index of the atom whose position should be proposed
bonded_atom : int
the index of the atom bonded to the atom of interest
angle_atom : int
the 1, ... | 625941d3be8e80087fb20e1e |
def getSkipUnknownChrString(): <NEW_LINE> <INDENT> return ('if [ "$coords" == "unmapped:no_mapped_reads" ]; then\n' '\techo "Input is the unmapped bam... exiting" >> $logFile\n' '\techo no_mapped_reads > $outVcf\n' '\texit 0\n' 'else\n' '\techo "Input is not the unmapped bam... continuing" >> $logFile 2>&1\n' 'fi\n\n') | Necessary for various genotyping steps | 625941d3e8904600ed9f210b |
def __init__(self, params): <NEW_LINE> <INDENT> super(BiLstmClassifier, self).__init__() <NEW_LINE> self.embeddings = nn.Embedding(params["vocab_size"], embedding_dim=params["embed_dim"]) <NEW_LINE> self.bilstm = nn.LSTM(input_size=params["embed_dim"], hidden_size=params["lstm_h"], batch_first=True, bidirectional=True)... | Define the neural module layers according to params
:param params: the parameter setting | 625941d3cc0a2c11143dd06d |
def do_notification_type_list(mc, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> notification_types = mc.notificationtypes.list() <NEW_LINE> <DEDENT> except (osc_exc.ClientException, k_exc.HttpError) as he: <NEW_LINE> <INDENT> raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) <NEW_LINE> <DEDENT> else... | List notification types supported by monasca. | 625941d31d351010ab855cf8 |
def libvlc_media_event_manager(p_md): <NEW_LINE> <INDENT> f = _Cfunctions.get('libvlc_media_event_manager', None) or _Cfunction('libvlc_media_event_manager', ((1,),), EventManager, Media) <NEW_LINE> if not __debug__: <NEW_LINE> <INDENT> global libvlc_media_event_manager <NEW_LINE> libvlc_media_event_manager = f ... | Get event manager from media descriptor object.
NOTE: this function doesn't increment reference counting.
@param p_md: a media descriptor object.
@return: event manager object. | 625941d35fcc89381b1e189d |
def forward(self, x, captions, lengths): <NEW_LINE> <INDENT> features = self.fc0(x) <NEW_LINE> embeddings = self.embed(captions) <NEW_LINE> embeddings = torch.cat((features.unsqueeze(1), embeddings), 1) <NEW_LINE> packed = torch.nn.utils.rnn.pack_padded_sequence(embeddings, lengths, batch_first=True) <NEW_LINE> hiddens... | Decode image feature vectors and generates captions. | 625941d3dd821e528d63b385 |
def Norm2d(in_channels): <NEW_LINE> <INDENT> layer = getattr(cfg.MODEL,'BNFUNC') <NEW_LINE> normalizationLayer = layer(in_channels) <NEW_LINE> return normalizationLayer | Custom Norm Function to allow flexible switching | 625941d3566aa707497f4743 |
def write_trailer(trailer): <NEW_LINE> <INDENT> return (trailer or []) | Write the trailer. Not implemented. | 625941d363b5f9789fde72c2 |
def __init__(self, on_message = lambda ws, message: (stdout.write(f'\r{json.loads(message)}'), stdout.flush()), on_error = lambda ws, error: print(error), on_close = lambda ws: print("### closed ###"), testnet: bool = False, symbol: str = 'btcusdt', speed: str = '100ms'): <NEW_LINE> <INDENT> if testnet == True: <NEW_LI... | To use TESTNET Binance Futures API -> testnet = True
To change currency pair -> symbol = 'ethusdt'
To change speed -> speed = '250ms' | 625941d3bd1bec0571d9080c |
@login_required <NEW_LINE> def view_home(request,view_all=False): <NEW_LINE> <INDENT> if view_all: <NEW_LINE> <INDENT> cexec_list = CommandExec.objects.order_by('-last_run', '-id') <NEW_LINE> caption = _(u"List of all command executions") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cexec_list = CommandExec.objects.or... | Welcome page for command management | 625941d3462c4b4f79d1d8ad |
@api.representation('application/json') <NEW_LINE> def output_json(data, code, headers=None): <NEW_LINE> <INDENT> data = to_json(data) <NEW_LINE> resp = make_response(json.dumps(data), code) <NEW_LINE> resp.headers.extend(headers or {}) <NEW_LINE> return resp | overwrite application/json based responses | 625941d373bcbd0ca4b2c253 |
def main(args): <NEW_LINE> <INDENT> mtrack = medleydb.MultiTrack(args.track_id) <NEW_LINE> if os.path.exists(mtrack.activation_conf_fpath): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> activations, index_list = compute_activation_confidence(mtrack) <NEW_LINE> write_activations_to_csv(mtrack, activations, index_l... | Main function. Computes the activation confidence annotation for a given
multitrack id. | 625941d30fa83653e4657197 |
def depthfirst(start: int, finish: int, graph: List[List[int]], accept_func=lambda x: True, pv_func=lambda x: True) -> List[int]: <NEW_LINE> <INDENT> stack: List[List[int, List[int]]] = [[start, graph[start]]] <NEW_LINE> current_room: int = 0 <NEW_LINE> first_portal: int = 0 <NEW_LINE> portals: List[int] = [] <NEW_LINE... | Uses slightly less naïve depth-first search to find a
route out of the Minotaur's maze. | 625941d30a50d4780f667070 |
def _zero_mat(self): <NEW_LINE> <INDENT> return np.zeros((self._pman.dim, self._pman.dim)) | Returns a new square zero valued matrix with dimensions of grid.
| 625941d33d592f4c4ed1d248 |
@app.command() <NEW_LINE> def run( host: str = settings.host, port: int = settings.port, workers: int = settings.workers, ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import multiprocessing <NEW_LINE> import gunicorn.app.base <NEW_LINE> import uvicorn <NEW_LINE> <DEDENT> except ImportError as e: <NEW_LINE> <INDENT> ... | Run the production server. | 625941d330bbd722463cbfa4 |
def nSegments(self): <NEW_LINE> <INDENT> return _algorithms.Cell_nSegments(self) | nSegments(self) -> nta::UInt | 625941d37b25080760e39636 |
def eur_rake_to_tup(row): <NEW_LINE> <INDENT> rkmin = row['rakemin'] <NEW_LINE> rkmax = row['rakemax'] <NEW_LINE> rkav = np.mean((rkmin, rkmax)) <NEW_LINE> return '({},{},{})'.format(int(rkav), rkmin, rkmax) | Converts the `rakemin` and `rakemax` data into a tuple
with the mean rake as the mid range value. | 625941d356b00c62f0f14837 |
def remove(self, ppa=None, repo_url=None): <NEW_LINE> <INDENT> if ppa: <NEW_LINE> <INDENT> SSSShellExec.cmd_exec(self, "add-apt-repository -y " "--remove '{ppa_name}'" .format(ppa_name=ppa)) <NEW_LINE> <DEDENT> elif repo_url: <NEW_LINE> <INDENT> repo_file_path = ("/etc/apt/sources.list.d/" + SSSVariables().sss_repo_fil... | This function used to remove ppa's
If ppa is provided adds repo file to
/etc/apt/sources.list.d/
command. | 625941d3fff4ab517eb2f61a |
@rule(Classpath, [Select(BuildPropertiesConfiguration)]) <NEW_LINE> @printing_func <NEW_LINE> def write_name_file(name): <NEW_LINE> <INDENT> return Classpath(creator='write_name_file') | Write a file containing the name of this target in the CWD. | 625941d34a966d76dd5511ed |
def __init__(self, distribution): <NEW_LINE> <INDENT> Command.__init__(self, distribution) <NEW_LINE> self.__buildConfiguration = BuildConfiguration() | Constructor. | 625941d3627d3e7fe0d6902e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.