code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_target_property(self, target_name, property_name, property_value): <NEW_LINE> <INDENT> self._engine.set_target_property(target_name, property_name, property_value) | Sets property _property_name_ for target _target_name_.
*Arguments:*
_target_name_: Name of the individual target, whose property to set.
_property_name_: Name of the property.
_property_value_: Value of the property.
*Returns:*
Nothing.
*Supported properties:*
| *Name* | *Description* | *Default Value* ... | 625941f1fbf16365ca6f6786 |
def truncate( s, size ): <NEW_LINE> <INDENT> if len( s ) <= size: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> return s[:size-3] + '...' | truncate given string to specified length | 625941f1cb5e8a47e48b8056 |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--test', dest='test', type=str, required=True, help='Dataset to evaluate.') <NEW_LINE> parser.add_argument('--via', dest='via', type=str, required=True, help='Dataset to assistant PCA whitening.') <NEW_LINE> args = parser... | Main function of the program. | 625941f107d97122c4178e50 |
def __init__(self, fields=None, data_start_row=None): <NEW_LINE> <INDENT> self.fields = fields or self.fields <NEW_LINE> self.data_start_row = data_start_row or self.data_start_row | :param fields: is an ordered iterable of Field tuples. If not provided, the class-level
value will be used.
:param data_start_row: is the 0-based index where the first row of data begins. If not
provided, the class-level value will be used. | 625941f1fff4ab517eb2f9f6 |
def close_alert_page(self): <NEW_LINE> <INDENT> self.close_browser() <NEW_LINE> self.switch_to_default_window() | Implementing close alert page functionality
:return: | 625941f13eb6a72ae02ecaa4 |
def _is_zero(x): <NEW_LINE> <INDENT> if not hasattr(x, 'type'): <NEW_LINE> <INDENT> return np.all(x == 0.) <NEW_LINE> <DEDENT> if isinstance(x.type, NullType): <NEW_LINE> <INDENT> return 'no' <NEW_LINE> <DEDENT> if isinstance(x.type, DisconnectedType): <NEW_LINE> <INDENT> return 'yes' <NEW_LINE> <DEDENT> no_constant_va... | Returns 'yes', 'no', or 'maybe' indicating whether x
is always 0.
'maybe' means that x is an expression that is complicated enough
that we can't tell that it simplifies to 0. | 625941f163b5f9789fde769c |
def AdminLYear_clicked_cb(self, data=None): <NEW_LINE> <INDENT> self.AdminSalesPrint('%s' % (datetime.date.today().year - 1)) | Makes the AdminGui show all sales made last year | 625941f1a219f33f34628f17 |
def nitems_written(self, *args, **kwargs): <NEW_LINE> <INDENT> return _atsc_swig.atsc_bit_timing_loop_sptr_nitems_written(self, *args, **kwargs) | nitems_written(atsc_bit_timing_loop_sptr self, unsigned int which_output) -> uint64_t | 625941f1cad5886f8bd2758e |
def load_playlist(self, playlist = None): <NEW_LINE> <INDENT> if playlist: <NEW_LINE> <INDENT> return self.load_from_playlist(playlist=playlist) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.load_from_playlist() | if all values are None it sets values from config.py | 625941f16e29344779a62bc7 |
def createGlobalAlignmentPlot(meanX, meanY, first, pixSize): <NEW_LINE> <INDENT> sumMeanX = [] <NEW_LINE> sumMeanY = [] <NEW_LINE> def px_to_ang(px): <NEW_LINE> <INDENT> y1, y2 = px.get_ylim() <NEW_LINE> x1, x2 = px.get_xlim() <NEW_LINE> ax_ang2.set_ylim(y1 * pixSize, y2 * pixSize) <NEW_LINE> ax_ang.set_xlim(x1 * pixSi... | Create a plotter with the shift per frame. | 625941f13317a56b8693a200 |
def __init__(self, buysafe_bond_available=None, buysafe_bond_cost=None, buysafe_bond_free=None, buysafe_bond_refunded=None, buysafe_bond_wanted=None, buysafe_shopping_cart_id=None): <NEW_LINE> <INDENT> self._buysafe_bond_available = None <NEW_LINE> self._buysafe_bond_cost = None <NEW_LINE> self._buysafe_bond_free = Non... | OrderBuysafe - a model defined in Swagger | 625941f1507cdc57c630729f |
def main(): <NEW_LINE> <INDENT> tuning = load_tuning() <NEW_LINE> tuning = tune_model(tuning) <NEW_LINE> best_trial = {} <NEW_LINE> trials = tuning['trials'] <NEW_LINE> for trial in trials: <NEW_LINE> <INDENT> if not best_trial or float(trial['loss']) < float(best_trial['loss']): <NEW_LINE> <INDENT> best_trial = trial ... | The main entry point | 625941f1aad79263cf391000 |
def __init__(self, configuration): <NEW_LINE> <INDENT> ALoader.__init__(self, configuration) <NEW_LINE> self.setVariables(configuration) <NEW_LINE> self.ordered = False | Set configuration parameters and create user if required | 625941f1d18da76e23532a94 |
def test_get_user_roles(self): <NEW_LINE> <INDENT> user_cls = get_user_model() <NEW_LINE> superuser = user_cls.objects.filter(is_superuser=True).first() <NEW_LINE> roles = get_user_roles(superuser, normalized=True) <NEW_LINE> self.assertEqual(5, len(roles)) <NEW_LINE> roles = get_user_roles(superuser, False) <NEW_LINE>... | :return: | 625941f1b545ff76a89143cc |
def pdf(s, x): <NEW_LINE> <INDENT> x = sympify(x) <NEW_LINE> if not x.is_Number: <NEW_LINE> <INDENT> raise NotImplementedError("SymPy does not yet support" "piecewise functions") <NEW_LINE> <DEDENT> if x < s.a or x > s.b: <NEW_LINE> <INDENT> return Rational(0) <NEW_LINE> <DEDENT> return 1/(s.b-s.a) | Return the probability density function as an expression in x | 625941f1a8370b7717052e53 |
def parse_attribute_tag(self, ele: Element, iter: iterparse) -> Tuple: <NEW_LINE> <INDENT> id = ele.get('id') <NEW_LINE> attr = '' <NEW_LINE> value = '' <NEW_LINE> for i in range(0, 2): <NEW_LINE> <INDENT> eve, child = iter.__next__() <NEW_LINE> if child.tag == 'mentionSlot': <NEW_LINE> <INDENT> attr = child.get('id') ... | @param ele:the current lxml element that start an attribute defintition
@param iter: lxml element iterator
@return: a Tuple of (attribute_id, corresponding entity id, attribute_name, attribute_value) | 625941f19f2886367277ae3f |
@app.route('/weather.json') <NEW_LINE> def weather(): <NEW_LINE> <INDENT> zipcode = request.args.get('zipcodeEntered') <NEW_LINE> weather_info = WEATHER.get(zipcode, DEFAULT_WEATHER) <NEW_LINE> return jsonify(weather_info) | Return a weather-info dictionary for this zipcode. | 625941f18c0ade5d55d3ef76 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PaymentUrlErrorResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941f131939e2706e4d418 |
def get_name(): <NEW_LINE> <INDENT> output = tvservice_command("-n") <NEW_LINE> name = output.strip('\n').split('=', 1)[1].strip(' ') <NEW_LINE> return name | -n, --name Print the device ID from EDID | 625941f144b2445a33932648 |
def generic_visit(self, t): <NEW_LINE> <INDENT> assert False, "Unsupported syntax: %r" % (t,) | Any node type we don't know about is an error. | 625941f14c3428357757c8da |
def pause(self, name): <NEW_LINE> <INDENT> self.channels[name].pause() | Pauses the specified song. | 625941f1a05bb46b383ecdd2 |
def _log_exception(self, resource, func): <NEW_LINE> <INDENT> def wrapper(*args, **kargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> func(*args, **kargs) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> msg = "While executing {} of resource [{}]\n{}".format( func.__name__, resource.cfg.name, traceback.forma... | Decorator for logging an exception at resource and environment level.
:param resource: resource to log the exception with
:type resource: :py:class:`~testplan.common.entity.base.Resource`
:param func: function to catch exception for
:type func: ``Callable`` | 625941f1e76e3b2f99f3adb8 |
def testFindDailyDirs_007(self): <NEW_LINE> <INDENT> self.extractTar("tree19") <NEW_LINE> stagingDir = self.buildPath(["tree19"]) <NEW_LINE> dailyDirs = findDailyDirs(stagingDir, ENCRYPT_INDICATOR) <NEW_LINE> self.assertEqual(3, len(dailyDirs)) <NEW_LINE> self.assertTrue(self.buildPath(["tree19", "2006", "12", "30"]) i... | Test with a valid staging directory, where some daily directories contain
the encrypt indicator and others do not. | 625941f18c3a873295158978 |
def __long__(self): <NEW_LINE> <INDENT> return self._value | @return: value of this EUI object as an unsigned integer | 625941f173bcbd0ca4b2c62c |
def legislator_inactive(request, abbr, legislator): <NEW_LINE> <INDENT> sponsored_bills = legislator.sponsored_bills( limit=5, sort=[('action_dates.first', pymongo.DESCENDING)]) <NEW_LINE> legislator_votes = legislator.votes_5_sorted() <NEW_LINE> has_votes = bool(legislator_votes) <NEW_LINE> return render( request, tem... | Context:
- feed_entry_template
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/feed_entry.html
- billy/... | 625941f1627d3e7fe0d69408 |
def pollard_rho(n,x=2): <NEW_LINE> <INDENT> y=x <NEW_LINE> d = 1 <NEW_LINE> if n%2 == 0: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> while d==1: <NEW_LINE> <INDENT> x = pollard_g(x,n) <NEW_LINE> y = pollard_g(pollard_g(y,n),n) <NEW_LINE> d = gcd(abs(x-y),n) <NEW_LINE> <DEDENT> if d == n: <NEW_LINE> <INDENT> return... | Finds the next factor of n using the Pollard rho method
| 625941f1a79ad161976cc6fc |
def plot_function(self,**d): <NEW_LINE> <INDENT> from sage.plot.all import Graphics <NEW_LINE> from sage.plot.line import line2d <NEW_LINE> G = Graphics() <NEW_LINE> l = self.singularities() <NEW_LINE> t = self._permutation._twin <NEW_LINE> for i in range(len(self._permutation)): <NEW_LINE> <INDENT> j = t[0][i] <NEW_LI... | Return a plot of the interval exchange transformation as a
function.
INPUT:
- Any option that is accepted by line2d
OUTPUT:
2d plot -- a plot of the iet as a function
EXAMPLES::
sage: t = iet.IntervalExchangeTransformation(('a b c d','d a c b'),[1,1,1,1])
sage: t.plot_function(rgbcolor=(0,1,0))
Graphi... | 625941f1eab8aa0e5d26e111 |
def t_fold_end(self, t): <NEW_LINE> <INDENT> column = find_column(t) <NEW_LINE> indent = self.indent_stack[-1] <NEW_LINE> if column < indent: <NEW_LINE> <INDENT> rollback_lexpos(t) <NEW_LINE> <DEDENT> if column <= indent: <NEW_LINE> <INDENT> t.lexer.pop_state() <NEW_LINE> t.type = 'B_FOLD_END' <NEW_LINE> <DEDENT> if co... | \n+\ * | 625941f1d10714528d6002a1 |
def test_invert_plus_thumbnail_sizer_filtered_path(self): <NEW_LINE> <INDENT> self.assertEqual( self.jpg.image.filters.invert.thumbnail['100x100'].url, ( '/media/__sized__/__filtered__/python-logo__invert__-thumbnail-100x100-{}.jpg'.format(JPEG_QUAL) ) ) <NEW_LINE> self.assertEqual( self.webp.image.filters.invert.thumb... | Ensure crop Sizer paths are set correctly. | 625941f1ac7a0e7691ed4677 |
def clear(self): <NEW_LINE> <INDENT> self.loc.delete("1.0", END) | metoda czyszczenia | 625941f1cdde0d52a9e535ef |
def itkAccumulateImageFilterIUL2IUL2_cast(*args): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_cast(*args) | itkAccumulateImageFilterIUL2IUL2_cast(itkLightObject obj) -> itkAccumulateImageFilterIUL2IUL2 | 625941f12eb69b55b151ce6e |
@register.filter <NEW_LINE> def attribute_lookup(obj, attr): <NEW_LINE> <INDENT> if (hasattr(obj, attr)): <NEW_LINE> <INDENT> return getattr(obj, attr) | Get an attribute from an object. | 625941f13d592f4c4ed1d614 |
def crossesjan1(val): <NEW_LINE> <INDENT> return f"{val:.0f}-{(val + 1):.0f}" | Pretty print for a year. | 625941f13346ee7daa2b3328 |
def test_compute_gen_no_session_fail(self): <NEW_LINE> <INDENT> Log.debug('test_compute_gen_no_session_fail start') <NEW_LINE> para_id = 23 <NEW_LINE> data_id = 23008 <NEW_LINE> res = self.comp_gen.base_compute_gen(para_id=para_id, data_id=data_id, cookies=None, calType=self.calType, max_server=0) <NEW_LINE> self.asser... | BB 基因协同计算,未登录,失败 | 625941f121bff66bcd684f04 |
def test_color_class_init(): <NEW_LINE> <INDENT> inp_exps = [ InpExp(color.Color(), color.RGBA(red=0, green=0, blue=0, alpha=0)), InpExp(color.Color("#000000"), color.RGBA(red=0, green=0, blue=0, alpha=1)), InpExp(color.Color("#40FFAA80"), color.RGBA(0.25, 1, 2 / 3, 0.5)), ] <NEW_LINE> for inp_exp in inp_exps: <NEW_LIN... | Test that Color instances are properly initialized. | 625941f1d58c6744b4258214 |
@needs('pavelib.prereqs.install_prereqs') <NEW_LINE> @task <NEW_LINE> @timed <NEW_LINE> def update_bokchoy_db_cache(): <NEW_LINE> <INDENT> print('Removing cached db files for bokchoy tests') <NEW_LINE> remove_files_from_folder(BOKCHOY_DB_FILES, CACHE_FOLDER) <NEW_LINE> reset_test_db(BOKCHOY_DB_FILES, update_cache_files... | Update and cache the MYSQL database for bokchoy testing:
* Remove any previously cached database files
* Apply migrations on a fresh db
* Write the collective sha1 checksum for all of these files to disk
WARNING: This will take several minutes. | 625941f11f037a2d8b9467b3 |
def SnapshotEnumerateWithFilters(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | SnapshotEnumerate returns a list of snapshots for a specific volume
that match the labels provided if any. | 625941f15e10d32532c5f4dc |
def test_splice_collection_right_is_known(self): <NEW_LINE> <INDENT> col = SpliceCollection() <NEW_LINE> col.add_splices(self.test_splices) <NEW_LINE> known1 = col.right_is_known(self.test_splices[0]) <NEW_LINE> self.assertEqual(known1, True) <NEW_LINE> known2 = col.right_is_known(Splice("SEQ_REGION", 2, 10)) <NEW_LINE... | Test splice collection right is known | 625941f14428ac0f6e5badaf |
def __init__(self, clubid="BBCC89Q", username="...", password="..."): <NEW_LINE> <INDENT> uitslagenfile = r"./uitslagen/{0}.pk".format(clubid) <NEW_LINE> programmafile = r"./programma/{0}.pk".format(clubid) <NEW_LINE> self.delete_file(uitslagenfile) <NEW_LINE> self.delete_file(programmafile) <NEW_LINE> if os.path.exist... | Initialize | 625941f176e4537e8c351c2f |
def normalize_phase(phase): <NEW_LINE> <INDENT> out = np.fmod(phase, 2.0 * np.pi) <NEW_LINE> nans = np.isnan(out) <NEW_LINE> np.putmask(out, nans, 0) <NEW_LINE> out[out < -np.pi] += 2.0 * np.pi <NEW_LINE> out[out > np.pi] -= 2.0 * np.pi <NEW_LINE> np.putmask(out, nans, np.nan) <NEW_LINE> return out | Normalize phase to the range [-pi, pi].
Parameters
----------
phase : array of float
Phase to normalize.
Returns
-------
array of float
Normalized phases. | 625941f157b8e32f52483a56 |
def test_group_promotes(self): <NEW_LINE> <INDENT> p = om.Problem() <NEW_LINE> ivc = om.IndepVarComp() <NEW_LINE> ivc.add_output('a', 2.0) <NEW_LINE> ivc.add_output('x', 5.0) <NEW_LINE> p.model.add_subsystem('comp1', ivc, promotes_outputs=['x']) <NEW_LINE> p.model.add_subsystem('comp2', om.ExecComp('y=2*x'), promotes_i... | Promoting a single variable. | 625941f1090684286d50f2a6 |
def update_object(self, event): <NEW_LINE> <INDENT> self._locked = True <NEW_LINE> try: <NEW_LINE> <INDENT> self.value = self.control.GetValue() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._locked = False | Handles the user selecting a new value in the spin box.
| 625941f130c21e258bdfaa5b |
def test_archive_subdir(self): <NEW_LINE> <INDENT> tar_archive = os.path.join(TMP, 'test_archive.tar.gz') <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertTrue( self.run_function( 'git.archive', [os.path.join(self.repo, 'qux'), tar_archive], prefix='foo/' ) ) <NEW_LINE> self.assertTrue(tarfile.is_tarfile(tar_archive)) <N... | Test git.archive on a subdir, giving only a partial copy of the repo in
the resulting archive | 625941f17b25080760e39a0c |
def getDescription(self, template, extraparams=None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> params.update(self.metadata) <NEW_LINE> params.update(extraparams or {}) <NEW_LINE> description = '{{%s\n' % template <NEW_LINE> for key in sorted(params.keys()): <NEW_LINE> <INDENT> value = params[key] <NEW_LINE> if not ke... | Generate a description for a file. | 625941f1e8904600ed9f24ee |
def itkSparseFieldLayerNBNIF2_cast(*args): <NEW_LINE> <INDENT> return _itkSparseFieldFourthOrderLevelSetImageFilterPython.itkSparseFieldLayerNBNIF2_cast(*args) | itkSparseFieldLayerNBNIF2_cast(itkLightObject obj) -> itkSparseFieldLayerNBNIF2 | 625941f1b57a9660fec33e44 |
def __init__(self, msg_id, msg_name, msg_len, msg_type=None, msg_sender=None, msg_receivers=None, msgSendType=None, signals = None): <NEW_LINE> <INDENT> self._msg_id = msg_id <NEW_LINE> self._msg_name = msg_name <NEW_LINE> self._msg_len = msg_len <NEW_LINE> self._msg_type = msg_type <NEW_LINE> self._msg_sender = msg_se... | Constructor | 625941f1925a0f43d254a434 |
def convert_to_datetime(julian_date): <NEW_LINE> <INDENT> return datetime.datetime.strptime(julian_date, '%y%j') | This method will accept either a string
or an integer representation of the date
Eventually this will likely need to check that the
date makes sense in case I start adding days to it
somewhere. | 625941f10fa83653e465756e |
def get_coords_for_text(content_dict_web): <NEW_LINE> <INDENT> doc_complete3, doc_clean3, dictionary3, doc_term_matrix3 = prepare_texts(content_dict_web) <NEW_LINE> props_df = format_all_topics_for_documents(ldamodel=ldamodel, corpus=doc_term_matrix3, texts=doc_clean3) <NEW_LINE> x = scaler.transform(props_df.values) <... | Parameters
==========
content_dict_test: dict
mapping from some uuid to the text to be placed in the coord system | 625941f17cff6e4e81117f3d |
def on_signal(self, signal_event): <NEW_LINE> <INDENT> initial_order = self._create_order_from_signal(signal_event) <NEW_LINE> if signal_event.isclose is False: <NEW_LINE> <INDENT> sized_order = self.position_sizer.size_order( self.portfolio, initial_order ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sized_order = i... | This is called by the backtester or live trading architecture
to form the initial orders from the SignalEvent.
These orders are sized by the PositionSizer object and then
sent to the RiskManager to verify, modify or eliminate.
Once received from the RiskManager they are converted into
full OrderEvent objects and sent... | 625941f1566aa707497f4b17 |
def has_edges(node_label, edges): <NEW_LINE> <INDENT> return len([ k for k in edges.keys() if k[0] == node_label or k[1] == node_label]) > 0 | Checks if given node name has any edges. Nodes with no edges are not added
to the graph. | 625941f1d486a94d0b98e6fe |
def clean_site_species(self): <NEW_LINE> <INDENT> return (self.clean_species('site_species') if self.cleaned_data['site_species_same'] else self.cleaned_data['site_species']) | Cleans site_species field.
If site_species_same field is selected, assigns species data to the
cleaned data. | 625941f17c178a314d6efa21 |
def assert_config_file_contains(self, config_file, expected): <NEW_LINE> <INDENT> file = open(config_file) <NEW_LINE> config = yaml.safe_load(file.read()) <NEW_LINE> file.close() <NEW_LINE> self.assertEqual(config, expected) | Custom assert to check content of config_file. | 625941f1b7558d58953c54bf |
def strip_color(inp: str) -> str: <NEW_LINE> <INDENT> return re.sub('\x1b\\[(K|.*?m)', '', inp) | Remove ANSI color/style sequences from a string. May not catch obscure codes used outside this module.
:param inp: the string to strip
:return: ``inp`` with ansi codes removed | 625941f13cc13d1c6d3c792e |
def load_results_from_json(json_path: str): <NEW_LINE> <INDENT> with open(json_path, "r") as results_file: <NEW_LINE> <INDENT> results_json = json.load(results_file) <NEW_LINE> <DEDENT> return [Result.from_dict(result) for result in results_json] | loads run results from json file
Args:
json_path: the path of the json file to load the results from
Returns:
list: results object that was saved in the json file (list of qiskit Results) | 625941f16fece00bbac2dcfd |
def grad_logQ(sample,alpha,m): <NEW_LINE> <INDENT> gradient = np.zeros((alpha.shape[0],2)) <NEW_LINE> gradient[:,0] = np.log(alpha) - np.log(m) + 1. + np.log(sample) - sample/m <NEW_LINE> gradient[:,0] -= sp.digamma(alpha) <NEW_LINE> gradient[:,1] = -alpha/m + alpha*sample/m**2 <NEW_LINE> return gradient | Evaluates the gradient of the log of variational approximation, vectorized. | 625941f1e76e3b2f99f3adb9 |
def _save_default_text_report_dialog(self): <NEW_LINE> <INDENT> txt = self.make_txt_report(self.text_template) <NEW_LINE> self._save_text_report_dialog(txt, Config.text_report_prefix) | Create text report and open dialog for saving it | 625941f1851cf427c661aac1 |
def read_embarks(self): <NEW_LINE> <INDENT> return tuple([ os.path.basename(o) for o in self.get_text_files(self.embarks_dir)]) | Returns a list of embark profiles. | 625941f1a79ad161976cc6fd |
def test_get_metrics_for_model(self): <NEW_LINE> <INDENT> obj = FakeModel.objects.create(name='fake') <NEW_LINE> metric = FakeModelMetric(obj) <NEW_LINE> metric.compute() <NEW_LINE> response = self.get(url_for('api.metrics', id=obj.id)) <NEW_LINE> self.assert200(response) <NEW_LINE> self.assertEqual(response.json['leve... | It should fetch my user data on GET | 625941f1c4546d3d9de72ff1 |
def test_signup_post_complete_data_gets_201_status_code(testapp): <NEW_LINE> <INDENT> data = { 'first_name': FAKE.first_name(), 'last_name': FAKE.last_name(), 'email': FAKE.email(), 'password': FAKE.password() } <NEW_LINE> res = testapp.post('/signup', data) <NEW_LINE> assert res.status_code == 201 | Test that POST to signup route gets 201 status code. | 625941f13cc13d1c6d3c792f |
def AIC(SX_, S_, L_, ei_thresh=1e-6): <NEW_LINE> <INDENT> F, p, _ = S_.shape <NEW_LINE> R_ = S_ - L_ <NEW_LINE> rank = sum([np.linalg.matrix_rank(L_[f]) for f in xrange(L_.shape[0])]) <NEW_LINE> n_edges = np.sum(np.max(partial_coher(S_), axis=0) > ei_thresh) - S_.shape[1] <NEW_LINE> ewR_ = np.linalg.eigvalsh(R_) <NEW_L... | AIC = trace(SX*R) - sum(log(ewR)) + 2*F*n_edges + rank | 625941f16fb2d068a760f65e |
def test_add_after_last_step_constraint(self): <NEW_LINE> <INDENT> num_steps = 1 <NEW_LINE> qubit_num = 0 <NEW_LINE> state = np.array([1/math.sqrt(2), 1/math.sqrt(2)], dtype=np.complex_) <NEW_LINE> r = register.Register(1, state) <NEW_LINE> c = qc.QuantumCircuit(r, num_steps) <NEW_LINE> gate = paulix.PauliXQuantumGate(... | Adding a gate after last position, fails | 625941f191af0d3eaac9bfd6 |
def volume_add_quota(volume: str, path: str, size: int) -> Result: <NEW_LINE> <INDENT> arg_list = ["volume", "quota", volume, "limit-usage", path, str(size)] <NEW_LINE> return run_command("gluster", arg_list, True, False) | Adds a size quota to the volume and path.
volume: String Volume to add a quota to
path: String. Path of the directory to apply a quota on
size: int. Size in bytes of the quota to apply
:return: 0 on success
:raises: GlusterError if the command fails to run | 625941f166673b3332b92649 |
def 生成反应谱(A,C,episilon,Tg,T_int=0.01,T_end=6,name='',unit='g')->EarthquakeWave: <NEW_LINE> <INDENT> jieta1=0.02+(0.05-episilon)/8 <NEW_LINE> jieta2=1+(0.05-episilon)/(0.06+1.7*episilon) <NEW_LINE> gama=0.9+(0.05-episilon)/(0.5+5*episilon) <NEW_LINE> Smax=2.25*C*A <NEW_LINE> T=np.arange(0,T_end,T_int) <NEW_LINE> S=[] <N... | ccj 城市桥梁反应谱
:param A: 地震峰值加速度
:param C: 调整系数
:param episilon: 阻尼比
:param Tg: 特征周期
:param T_int: 生成的周期间隔
:param T_end: 结束周期
:param name:
:param unit: 单位
:return: | 625941f1462c4b4f79d1dc87 |
@app.command("provider_info", "Returns provider info") <NEW_LINE> def get_provider_info(address): <NEW_LINE> <INDENT> t1.join() <NEW_LINE> log(Ebb.get_provider_info(address)) | Return provider info.
:param str address: Ethereum address of the provider | 625941f1004d5f362079a8e6 |
def resolve_resource_var(self, string_data): <NEW_LINE> <INDENT> data = string.Template(string_data).substitute(self.host_vars) <NEW_LINE> return data | Substitute variables in strings. | 625941f171ff763f4b549c4e |
def p4_counter_retrieve(self, counter_id): <NEW_LINE> <INDENT> pass | Parameters:
- counter_id | 625941f1379a373c97cfb0ff |
def find_unexpected_subdirectories(self, expected_dirs, deductPoints = 0): <NEW_LINE> <INDENT> self.log_addEntry("Expecting no other directories besides: " + str(expected_dirs)) <NEW_LINE> dirs = self.get_immediate_subdirectories() <NEW_LINE> for f in expected_dirs: <NEW_LINE> <INDENT> if f in dirs: <NEW_LINE> <INDENT>... | Identify directories that the student submitted that are not in the expected_files list and deduct points for each one. | 625941f1b5575c28eb68e5bd |
def jnjnp_zeros(nt): <NEW_LINE> <INDENT> if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200): <NEW_LINE> <INDENT> raise ValueError("Number must be integer <= 1200.") <NEW_LINE> <DEDENT> nt = int(nt) <NEW_LINE> n, m, t, zo = specfun.jdzo(nt) <NEW_LINE> return zo[1:nt+1], n[:nt], m[:nt], t[:nt] | Compute zeros of integer-order Bessel functions Jn and Jn'.
Results are arranged in order of the magnitudes of the zeros.
Parameters
----------
nt : int
Number (<=1200) of zeros to compute
Returns
-------
zo[l-1] : ndarray
Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
n[l-1] : ndarray
Order ... | 625941f110dbd63aa1bd315a |
def walk_and_encrypt(branch, key, aad=b'', stash=None, isRoot=True, digest=None): <NEW_LINE> <INDENT> if isRoot: <NEW_LINE> <INDENT> digest = hashlib.sha512() <NEW_LINE> <DEDENT> for k, v in branch.items(): <NEW_LINE> <INDENT> if k == 'sops' and isRoot: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> caad = aad + k.en... | Walk the branch recursively and encrypts its leaves. | 625941f1be7bc26dc91cdbad |
def spaceFromElement(elem, slurBundle=None): <NEW_LINE> <INDENT> theDuration = _qlDurationFromAttr(elem.get('dur')) <NEW_LINE> theDuration = makeDuration(theDuration, int(elem.get('dots', 0))) <NEW_LINE> theSpace = note.SpacerRest(duration=theDuration) <NEW_LINE> if elem.get(_XMLID) is not None: <NEW_LINE> <INDENT> the... | <space> A placeholder used to fill an incomplete measure, layer, etc. most often so that the
combined duration of the events equals the number of beats in the measure.
In MEI 2013: pg.440 (455 in PDF) (MEI.shared module) | 625941f1b5575c28eb68e5be |
def get_gray_word_color(self, bg, text_x, text_y, word_height, word_width): <NEW_LINE> <INDENT> offset = 10 <NEW_LINE> ymin = text_y - offset <NEW_LINE> ymax = text_y + word_height + offset <NEW_LINE> xmin = text_x - offset <NEW_LINE> xmax = text_x + word_width + offset <NEW_LINE> word_roi_bg = bg[ymin: ymax, xmin: xma... | Only use word roi area to get word color | 625941f13d592f4c4ed1d615 |
def execute( via, params=None, pass_thru=None, details=False ): <NEW_LINE> <INDENT> with contextlib.closing( ( via.read_details if details else via.read )( via.parameter_substitution( params or PARAMS, pass_thru=pass_thru ))) as reader: <NEW_LINE> <INDENT> for p,v in zip( params or PARAMS, reader ): <NEW_LINE> <INDENT>... | Perform a single poll via the supplied enip.get_attribute 'proxy' instance, yielding the
parameters and their polled values (or full result details, if True)
By default, we'll look for the parameters in the module's PARAMS list, which must be recognized
by the supplied via's parameter_substitutions method, if pass_thr... | 625941f1099cdd3c635f1210 |
def is_operator(token): <NEW_LINE> <INDENT> return token == '+' or token == '-' or token == '*' or token == '/' or token == '^' | Returns whether the specified token is an operator. | 625941f1e5267d203edce24d |
def run_tests(): <NEW_LINE> <INDENT> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "intranet.settings") <NEW_LINE> django.setup() <NEW_LINE> test_runner = get_runner(settings)() <NEW_LINE> failures = test_runner.run_tests([]) <NEW_LINE> sys.exit(failures) | Wrapper for ./setup.py test. | 625941f1f548e778e58cdb38 |
@api.route('/customers/<int:customer_id>/', methods=['DELETE']) <NEW_LINE> @login_required <NEW_LINE> def delete_customer(customer_id): <NEW_LINE> <INDENT> customer = Customer.query.filter_by(id=customer_id).first() <NEW_LINE> if customer is None: <NEW_LINE> <INDENT> return abort(404) <NEW_LINE> <DEDENT> else: <NEW_LIN... | Delete a specific customer by id | 625941f1fbf16365ca6f6788 |
def getPlacementsList(documentObject, context = None, suppressWarning = False): <NEW_LINE> <INDENT> if not isObjectLattice(documentObject): <NEW_LINE> <INDENT> if not suppressWarning: <NEW_LINE> <INDENT> lattice2Executer.warning(context, documentObject.Name + " is not a placement or an array of placements. Results may ... | getPlacementsList(documentObject, context = None): extract list of placements
from an array object. Context is an object to report as context, when displaying
a warning if the documentObject happens to be a non-lattice. | 625941f15fdd1c0f98dc07ee |
def path(path_str): <NEW_LINE> <INDENT> path_str = expand_placeholders(path_str, SETTINGS) <NEW_LINE> try: <NEW_LINE> <INDENT> project_dir = SETTINGS['project_dir'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> error_message = "Cannot call path(...) until fbs.init(...) has been " "call... | Return the absolute path of the given file in the project directory. For
instance: path('src/main/python'). The `path_str` argument should always use
forward slashes `/`, even on Windows. You can use placeholders to refer to
settings. For example: path('${freeze_dir}/foo'). | 625941f1ff9c53063f47c7a8 |
def dice_coef(logits, labels): <NEW_LINE> <INDENT> n_class = 2; <NEW_LINE> a_p = tf.reduce_sum(tf.multiply(flat_logits, flat_logits), axis=1, keep_dims=True) <NEW_LINE> a_l = tf.reduce_sum(tf.multiply(flat_labels, flat_labels), axis=1, keep_dims=True) <NEW_LINE> a_pl = tf.reduce_sum(flat_logits * flat_labels, axis=1, k... | Dice coeficient | 625941f1e8904600ed9f24ef |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SL256AFR98, self).__init__( max_seq_len=256, alloc_free_ratio=.98, *args, **kwargs) | Generator where the available allocation sizes are just those in
use as the overflow source and target. | 625941f130c21e258bdfaa5c |
def customWindow(option, opt, value, parser): <NEW_LINE> <INDENT> WINWOWS = { '--home': 'home', '--weather': 'weather', '--settings': 'settings', '--videos': 'videos', } <NEW_LINE> if opt in WINWOWS: <NEW_LINE> <INDENT> parser.values.window = WINWOWS[opt] | Open custom window | 625941f1cb5e8a47e48b8058 |
def _serialiseEnv(self) -> None: <NEW_LINE> <INDENT> with self._jobStore.write_shared_file_stream("environment.pickle") as fileHandle: <NEW_LINE> <INDENT> pickle.dump(dict(os.environ), fileHandle, pickle.HIGHEST_PROTOCOL) <NEW_LINE> <DEDENT> logger.debug("Written the environment for the jobs to the environment file") | Put the environment in a globally accessible pickle file. | 625941f16aa9bd52df037360 |
def make_imageresize(file_path, extension='.jpg'): <NEW_LINE> <INDENT> gorizontal = [1080, 565] <NEW_LINE> vertical = [600, 750] <NEW_LINE> quadrate = [gorizontal[0], gorizontal[0]] <NEW_LINE> if get_file_extension(file_path) == extension: <NEW_LINE> <INDENT> fd_img = open(file_path, 'rb') <NEW_LINE> img = Image.open(f... | Resize images for standardized instagram posting and overwrite their.
Args:
file_path(str): image file location
extension(str): image file extension | 625941f19f2886367277ae40 |
def __init__( self ,repo ,owner ,timestamp=0 ,commit=0 ,file=None ,lines_added=-1 ,lines_deleted=-1 ,author=None ,is_defect=False ): <NEW_LINE> <INDENT> self.repo = repo <NEW_LINE> self.owner = owner <NEW_LINE> self.timestamp = timestamp <NEW_LINE> self.commit = commit <NEW_LINE> self.file ... | Initialize the instance, generally, we're creating an almost
empty object whose attributes will be filled in during analysis,
so most of the parameters have defaults that signify, "not yet
assigned." The one exception is "repo" which must have the same
value for every record in the run | 625941f1cdde0d52a9e535f0 |
def do_start(self, arg): <NEW_LINE> <INDENT> if self.Game != None: <NEW_LINE> <INDENT> print('A game is already running') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Game = Chessgame() <NEW_LINE> self.Game.print() | Start a new game.
If you are in IA vs IA mode, the game will run automatically. | 625941f199cbb53fe679319d |
def action_vminstance(self, vm_id, action_dict, created_items={}): <NEW_LINE> <INDENT> raise vimconnNotImplemented( "Should have implemented this" ) | Send and action over a VM instance. Returns created_items if the action was successfully sent to the VIM.
created_items is a dictionary with items that
:param vm_id: VIM identifier of the VM, provided by method new_vminstance
:param action_dict: dictionary with the action to perform
:param created_items: provided by me... | 625941f1a17c0f6771cbe607 |
def max_subarray_sum(array): <NEW_LINE> <INDENT> max_so_far = -sys.maxsize - 1 <NEW_LINE> max_ending_here = 0 <NEW_LINE> for i in range(len(array)): <NEW_LINE> <INDENT> max_ending_here += array[i] <NEW_LINE> if max_so_far < max_ending_here : <NEW_LINE> <INDENT> max_so_far = max_ending_here <NEW_LINE> <DEDENT> if max_en... | Find the sum of contiguous subarray within
a one-dimensional array of numbers that has
the largest sum. | 625941f1796e427e537b0b83 |
def eta_s_char_func(self): <NEW_LINE> <INDENT> p = self.eta_s_char.param <NEW_LINE> expr = self.get_char_expr(p) <NEW_LINE> if not expr: <NEW_LINE> <INDENT> msg = ('Please choose a valid parameter, you want to link the ' 'isentropic efficiency to at component ' + self.label + '.') <NEW_LINE> logging.error(msg) <NEW_LIN... | Equation for given isentropic efficiency characteristic.
Returns
-------
residual : float
Residual value of equation.
.. math::
0 = - \left( h_\mathrm{out} - h_\mathrm{in} \right) +
\eta_\mathrm{s,design} \cdot f\left( expr \right) \cdot
\left(h_\mathrm{out,s}-h_\mathrm{in}\right) | 625941f1d18da76e23532a96 |
def return_values(self): <NEW_LINE> <INDENT> return {'data': self.data, 'maxeval': self.maxeval, 'exp_design': self.exp_des, 'response_surface': self.surrogate, 'sampling_method': self.adapt_samp} | Request the PySOT object.
The method will return a dictionary containing the objects
required to initialize the strategy for the Experiment.
:return: dict | 625941f16e29344779a62bc9 |
def buildArray(self, target, n): <NEW_LINE> <INDENT> t = 0 <NEW_LINE> result = [] <NEW_LINE> for i in range(1, n + 1): <NEW_LINE> <INDENT> result.append("Push") <NEW_LINE> if i != target[t]: <NEW_LINE> <INDENT> result.append("Pop") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if t + 1 < len(target): <NEW_LINE> <INDENT... | :type target: List[int]
:type n: int
:rtype: List[str] | 625941f13317a56b8693a202 |
def list_all( self, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = self.list_all.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId': self._serialize.url("self.conf... | Gets all route tables in a subscription.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like ins... | 625941f1925a0f43d254a435 |
def test_crud_user_domain_role_grants_no_user(self): <NEW_LINE> <INDENT> user_id = uuid.uuid4().hex <NEW_LINE> collection_url = ( '/domains/%(domain_id)s/users/%(user_id)s/roles' % { 'domain_id': self.domain_id, 'user_id': user_id}) <NEW_LINE> member_url = '%(collection_url)s/%(role_id)s' % { 'collection_url': collecti... | Grant role on a domain to a user that doesn't exist, 404 result.
When grant a role on a domain to a user that doesn't exist, the server
returns 404 Not Found for the user. | 625941f1a8370b7717052e55 |
def setUp(self): <NEW_LINE> <INDENT> self.conn = self.dbi.connection() <NEW_LINE> self.dao = DatasetList(self.logger, self.dbi, self.dbowner) | setup all necessary parameters | 625941f10a366e3fb873edd8 |
def estimate_sequence( self, Z: Sequence[np.ndarray], init_immstate: MixtureParameters, Ts: Union[float, Sequence[float]], *, sensor_state: Optional[Iterable[Optional[Dict[str, Any]]]] = None, start_with_prediction: bool = False, ) -> Tuple[List[MixtureParameters], List[MixtureParameters], List[GaussParams]]: <NEW_LINE... | Create estimates for the whole time series of measurements. | 625941f18c0ade5d55d3ef78 |
def on_test_end(self, logs=None): <NEW_LINE> <INDENT> logs = self._process_logs(logs) <NEW_LINE> for callback in self.callbacks: <NEW_LINE> <INDENT> callback.on_test_end(logs) | Calls the `on_test_end` methods of its callbacks.
Args:
logs: Dict. Currently, no data is passed via this argument
for this method, but that may change in the future. | 625941f155399d3f05588c70 |
def test_average_3(): <NEW_LINE> <INDENT> data = torch.arange(6).reshape((3, 2)) <NEW_LINE> weights = torch.Tensor([1./4, 3./4]) <NEW_LINE> with pytest.raises(TypeError) as error: <NEW_LINE> <INDENT> pm.average(data, weights=weights) <NEW_LINE> <DEDENT> assert error.match( "Axis must be specified when shapes of a and w... | test_average_3
| 625941f17047854f462a19bb |
def test_fit(self) -> type(None): <NEW_LINE> <INDENT> mmf = MovingMedianForecaster() <NEW_LINE> mmf.fit(None) <NEW_LINE> self.assertTrue(hasattr(mmf, 'is_fitted_')) <NEW_LINE> mmf = MovingMedianForecaster() <NEW_LINE> mmf.fit(pd.Series([0, 1])) <NEW_LINE> self.assertTrue(hasattr(mmf, 'is_fitted_')) | Test `fit` method.
:return:
None | 625941f144b2445a3393264a |
def onBoost(**bvalues): <NEW_LINE> <INDENT> pass | function (boost, target, source, effect) {
if (effect && effect.isBerry) {
var b = void 0;
for (b in boost) {
boost[b] *= 2;
}
}
} | 625941f14c3428357757c8dc |
def check_passphrase(passphrase): <NEW_LINE> <INDENT> words_array = passphrase[0].split() <NEW_LINE> for word in words_array: <NEW_LINE> <INDENT> if words_array.count(word) > 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> return True | Check if the passphrase is valid.
It does not contain duplicate words | 625941f19b70327d1c4e1390 |
def _get_maximum_pool(self, poolinconf, poolindev, luntype): <NEW_LINE> <INDENT> maxpoolid = None <NEW_LINE> maxpoolsize = 0 <NEW_LINE> if luntype == 'Thin': <NEW_LINE> <INDENT> nameindex = 1 <NEW_LINE> sizeindex = 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nameindex = 5 <NEW_LINE> sizeindex = 3 <NEW_LINE> <DEDENT... | Get the maximum pool from config file.
According to the given pools' name in config file,
we select the pool of maximum free capacity. | 625941f176d4e153a657f0eb |
def emitTransactionEnd(self, cursor: "isqlcursor.ISqlCursor") -> None: <NEW_LINE> <INDENT> if self.notify_end_transaction_: <NEW_LINE> <INDENT> cursor.transactionEnd.emit() | Emit transaction end signal. | 625941f1627d3e7fe0d6940a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.