code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_phi(self): <NEW_LINE> <INDENT> return self.section_props.phi
:return: Principal bending axis angle :rtype: float :: section = CrossSection(geometry, mesh) section.calculate_geometric_properties() phi = section.get_phi()
625941c301c39578d7e74e0a
def update_user_bug(db: Session, user: PydanticUserUpdate): <NEW_LINE> <INDENT> db_user = db.query(User).filter(User.id == user.id).one_or_none() <NEW_LINE> if db_user is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for var, value in vars(db_user).items(): <NEW_LINE> <INDENT> setattr(db_user, var, value) i...
BUG!! Using a new update method seen in FastAPI https://github.com/tiangolo/fastapi/pull/2665 Simple, does not need each attribute to be updated individually Uses python in built functionality... preferred to the pydintic related method above
625941c315fb5d323cde0adc
def addButtonEvent(self, Widget): <NEW_LINE> <INDENT> form = QDialog() <NEW_LINE> w = Widget <NEW_LINE> w.setupUi(form) <NEW_LINE> form.show() <NEW_LINE> a = form.exec_() <NEW_LINE> if a == 0: <NEW_LINE> <INDENT> self.queryModel.refreshPage() <NEW_LINE> self.queryModel.update() <NEW_LINE> self.updateUI()
hsj 新建产品批次 :param Widget: 要显示的窗体 :return:
625941c332920d7e50b2819d
def uciSetChannel(console, radio, channel): <NEW_LINE> <INDENT> console.sendline( 'uci set wireless.wifi%s.channel=%s; uci commit wireless' % (radio, channel)) <NEW_LINE> console.expect_prompt()
This method sets the channel as per the radio over CM :param console: CM console object :type console: object :param radio: radio to set hwmode :type radio: string :param channel: channel to be set over the CM :type channel: string
625941c30a50d4780f666e60
def test_getAll(self): <NEW_LINE> <INDENT> self.assertIsNone(self.__file1.get_all()) <NEW_LINE> self.assertIsNotNone(self.__file2.get_all())
White box Tests out if the objects may be load from the given file. :return: None
625941c36aa9bd52df036d72
def await_use(self): <NEW_LINE> <INDENT> corourine = self.do_something(1) <NEW_LINE> print(type(corourine), corourine)
使用async可以定义协程对象, 使用await可以针对耗时的操作进行挂起. 就像生成器里的yield一样, 函数让出控制权. 协程遇到await, 事件循环将会挂起该协程, 执行别的协程(如asyncio.sleep), 直到其他的协程也挂起或者执行完毕, 再进行下一个协程的执行 耗时的操作一般是一些IO操作, 例如网络请求, 文件读取等. 在do_something中使用asyncio.sleep函数来模拟IO操作, 协程的目的也是让这些IO操作异步化
625941c399cbb53fe6792bb6
def test_save(self): <NEW_LINE> <INDENT> idf = IDF(self.startfile) <NEW_LINE> setversion(idf, '7.4') <NEW_LINE> idf.save() <NEW_LINE> idf2 = IDF(self.startfile) <NEW_LINE> assert idf is not idf2 <NEW_LINE> result = getversion(idf2) <NEW_LINE> expected = '7.4' <NEW_LINE> assert result == expected
Test save with a changed version number. Fails if the version number has not been changed.
625941c3009cb60464c63382
def test_vector(self): <NEW_LINE> <INDENT> self.assertEqual(list(vector([1, 1, 1], [0, 1, 0])), [-1, 0, -1]) <NEW_LINE> self.assertEqual(list(vector([0, 0, 10], [0, 0, 4])), [0, 0, -6]) <NEW_LINE> self.assertIsInstance(vector([1, 1, 1], [0, 1, 0]), numpy.ndarray) <NEW_LINE> self.assertEqual(vector([1, 1, 1], [0, 1, 0, ...
Tests for mathematics.vector
625941c394891a1f4081ba77
def test(self): <NEW_LINE> <INDENT> gateway = configget("PERSO","gateway_url") <NEW_LINE> cmd_text = "gateway_get" <NEW_LINE> res = CommandResult.parse(self.dut.execute_command(cmd_text,5000)[1]) <NEW_LINE> if res.rc == 0 and gateway == res.data['gateway']: <NEW_LINE> <INDENT> self.logger.info( "CSVFILE Get_Gateway ok...
This function is to set the gat eway the bike
625941c3cb5e8a47e48b7a7b
def popup_menu(self, tv, event): <NEW_LINE> <INDENT> if event.button != 3: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> (path, column) = tv.get_cursor() <NEW_LINE> if path is not None and len(path) == 1: <NEW_LINE> <INDENT> plugin = self.get_plugin_inst(path) <NEW_LINE> pname = self.liststore[path][1] <NEW_LINE> gm =...
Shows a menu when you right click on a plugin. :param tv: the treeview. :param event: The GTK event
625941c32ae34c7f2600d101
def validate(self, data): <NEW_LINE> <INDENT> password1 = data.get('new_password1') <NEW_LINE> password2 = data.get('new_password2') <NEW_LINE> if password1 and password2: <NEW_LINE> <INDENT> if password1 != password2: <NEW_LINE> <INDENT> raise serializers.ValidationError( {'password_mismatch_errors': _("The two passwo...
Check that the two password are the same.
625941c38c3a873295158388
def _ftext_field(self, cr, uid, ids, **kwargs): <NEW_LINE> <INDENT> return kwargs['data'][1]
parameters : {'data':[<type_field>,<python_expression>], 'line':<browse_line_record>} return : Text value of data given in parameters
625941c3b57a9660fec33852
def clean(self): <NEW_LINE> <INDENT> super(Credential, self).clean() <NEW_LINE> cred_type = self.issue_tracker.credential_type <NEW_LINE> if cred_type == CredentialTypes.NoNeed.name: <NEW_LINE> <INDENT> raise ValidationError({ 'issue_tracker': 'Is credential really required? ' 'Credential type "{}" is selected.'.format...
General validation for a concrete credential model Each concrete credential model derived from :class:`Credential` should call parent's ``clean`` before other validation steps.
625941c3de87d2750b85fd60
def set_meta(self, **kwds): <NEW_LINE> <INDENT> self.meta.update(kwds)
Update the metadata dictionary with the keywords and data provided here. Examples -------- set_meta(name="Exponential", equation="y = a exp(b x) + c")
625941c38a43f66fc4b54036
def get_gcs_bucket(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bucket = settings.DJANGAE_BACKUP_GCS_BUCKET <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> bucket = environment.default_gcs_bucket_name() <NEW_LINE> if bucket: <NEW_LINE> <INDENT> bucket = '{}/djangae-backups'.format(bucket) <NEW_LINE> <...
Get a bucket from DJANGAE_BACKUP_GCS_BUCKET setting. Defaults to the default application bucket with 'djangae-backups' appended. Raises an exception if DJANGAE_BACKUP_GCS_BUCKET is missing and there is no default bucket.
625941c326238365f5f0ee3b
def complete_msg(self, msg): <NEW_LINE> <INDENT> bytes_body_length = str(len(msg)).encode() <NEW_LINE> bytes_body_length = b'0' * (MSG_PREFIX_LENGTH - len(bytes_body_length)) + bytes_body_length <NEW_LINE> msg = bytes_body_length + msg <NEW_LINE> return msg
给消息加上 5 位的消息长度前缀
625941c35e10d32532c5eef6
def trim(img, dim): <NEW_LINE> <INDENT> if dim[1] >= img.shape[0] and dim[0] >= img.shape[1]: return img <NEW_LINE> x = int((img.shape[0] - dim[1])/2) + 1 <NEW_LINE> y = int((img.shape[1] - dim[0])/2) + 1 <NEW_LINE> trimmed_img = img[x: x + dim[1], y: y + dim[0]] <NEW_LINE> return trimmed_img
Trim the four sides(black paddings) of the image matrix and crop out the middle with a new dimension Parameters ---------- img: string the image rgb matrix dim: tuple (int, int) The new dimen the image is trimmed to Returns ------- trimmed_img : numpy array The trimmed image after removing black paddings...
625941c33346ee7daa2b2d3a
def optional_data_connections(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for conn in self._data_port_connectors: <NEW_LINE> <INDENT> source_comp = self.find_comp_by_target(conn.source_data_port) <NEW_LINE> target_comp = self.find_comp_by_target(conn.target_data_port) <NEW_LINE> if not source_comp.is_required or ...
Finds all data connections in which one or more components are not required. If all the components involved in a connection are required, that connection is also required. If one or more are not required, that connection is optional. Example: >>> s = RtsProfile(xml_spec=open('test/rtsystem.xml').read()) >>> len(s.opt...
625941c34428ac0f6e5ba7c0
def __init__(self, iterator): <NEW_LINE> <INDENT> self._iterator = iterator <NEW_LINE> self._hasNext = iterator.hasNext() <NEW_LINE> self._next = iterator.next()
Initialize your data structure here. :type iterator: Iterator
625941c3bf627c535bc1319e
def __init__(self, cols=None, sort=False, categorical_cols=None, threshold=0.8, method='pearson', save_corr=False): <NEW_LINE> <INDENT> self.cols = cols <NEW_LINE> self.sort = sort <NEW_LINE> self.categorical_cols = categorical_cols <NEW_LINE> self.threshold = threshold <NEW_LINE> self.method = method <NEW_LINE> self.s...
:param cols: A list of feature names, sorted by importance from high to low :param sort: Either a boolean, or the method name for sorting, available methods are ['tree', 'chi2'] :param categorical_cols: A list of categorical column names which will all be kept at the moment :param threshold: The correlation upper bound...
625941c3377c676e91272178
def test_check_if_aa_seq_no_value_error_raised_with_accepted_stops(self): <NEW_LINE> <INDENT> seq_record = SeqRecord(Seq('CTRPNNNTRKRIRIQRGPGRAFVTIGKIGNMRQAHC*', IUPAC.protein), id='AA_seq_with_stop') <NEW_LINE> seq_utils.check_if_aa_seq(seq_record, stops_ok=True) <NEW_LINE> self.assertTrue(True)
Test check_if_aa_seq(), if the tested sequence record contains stops and the option stops_ok=True, no ValueError is raised.
625941c34c3428357757c2f9
def connection(self): <NEW_LINE> <INDENT> connection = db.connect( host=self.host, port=self.port, user=self.user, password=self.password, database=self.database, cursorclass=db.cursors.DictCursor ) <NEW_LINE> return connection
Méthode retournant l'objet MySQLConnection afin de pouvoir manipuler la base de données MariaDB/MySQL
625941c3cc0a2c11143dce60
def itervalues(self): <NEW_LINE> <INDENT> return iter(self.__vals())
s.itervalues() -> an iterator over the property values in s.
625941c3bd1bec0571d905fe
def sync_state(self): <NEW_LINE> <INDENT> full_status = self.get_status() <NEW_LINE> if full_status: <NEW_LINE> <INDENT> self.state = self.state_lookup.get("active") <NEW_LINE> self.current_state_definition = full_status <NEW_LINE> self.current_state_definition["vaultName"] = full_status.get("VaultName") <NEW_LINE> if ...
Uses get_status() to determine whether the vault exists or not and sets the current state definition
625941c3377c676e91272179
def unselect_sentences(self, weights, state, to_remove): <NEW_LINE> <INDENT> state.subset -= to_remove <NEW_LINE> for sentence_index in to_remove: <NEW_LINE> <INDENT> state.concepts.subtract(self.concept_sets[sentence_index]) <NEW_LINE> state.length -= self.sentences[sentence_index].length <NEW_LINE> for concept in set...
Sentence ``un-selector'' (reverse operation of the select_sentences method). Args: weights (dictionary): the sentence weights dictionary. This dictionnary is updated during this method call (in-place). state (State): the state of the tabu search from which to start un-selecting sentences. to_...
625941c30c0af96317bb81b8
def filename(): <NEW_LINE> <INDENT> fname = u'' <NEW_LINE> for __ in xrange(random.randint(10, 30)): <NEW_LINE> <INDENT> fname += random.choice(NAME_CHARS_W_UNICODE) <NEW_LINE> <DEDENT> fname += random.choice(('.jpg', '.pdf', '.png', '.txt')) <NEW_LINE> return fname
Fake a filename.
625941c3167d2b6e31218b66
def set_vif_bandwidth_config(conf, inst_type): <NEW_LINE> <INDENT> bandwidth_items = ['vif_inbound_average', 'vif_inbound_peak', 'vif_inbound_burst', 'vif_outbound_average', 'vif_outbound_peak', 'vif_outbound_burst'] <NEW_LINE> for key, value in inst_type.get('extra_specs', {}).items(): <NEW_LINE> <INDENT> scope = key....
Config vif inbound/outbound bandwidth limit. parameters are set in instance_type_extra_specs table, key is in the format quota:vif_inbound_average.
625941c391af0d3eaac9b9e7
def hangman_with_hints(secret_word): <NEW_LINE> <INDENT> print("\tWelcome to the game Hangman!") <NEW_LINE> guesses = 6 <NEW_LINE> warnings = 3 <NEW_LINE> letters_guessed = [] <NEW_LINE> vowel_list = ["a","e","i","o","u"] <NEW_LINE> while guesses > 0 and get_guessed_word(secret_word, letters_guessed) != secret_word: <N...
secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how ...
625941c35f7d997b87174a66
def _dct(x, type, n=None, axis=-1, overwrite_x=False, normalize=None): <NEW_LINE> <INDENT> tmp = np.asarray(x) <NEW_LINE> if not np.isrealobj(tmp): <NEW_LINE> <INDENT> raise TypeError("1st argument must be real sequence") <NEW_LINE> <DEDENT> if n is None: <NEW_LINE> <INDENT> n = tmp.shape[axis] <NEW_LINE> <DEDENT> else...
Return Discrete Cosine Transform of arbitrary type sequence x. Parameters ---------- x : array_like input array. n : int, optional Length of the transform. axis : int, optional Axis along which the dct is computed. (default=-1) overwrite_x : bool, optional If True the contents of x can be destroyed. (d...
625941c3956e5f7376d70e3e
def __ls_remote__(name, branch): <NEW_LINE> <INDENT> cmd = "git ls-remote -h " + name + " " + branch + " | cut -f 1" <NEW_LINE> return __salt__['cmd.run_stdout'](cmd)
Returns the upstream hash for any given URL and branch.
625941c326238365f5f0ee3c
def _is_continuous(items, check_count=100): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> i = 0 <NEW_LINE> for i, item in enumerate(items): <NEW_LINE> <INDENT> if _is_float(item): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> if i >= check_count: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return count >= i ...
Are the strings in items continuous numbers.
625941c35510c4643540f3b8
def test_timespan_tot_length(self): <NEW_LINE> <INDENT> a_i1 = self.mat_data1['a_i1'].ravel() <NEW_LINE> b_i1 = self.mat_data1['b_i1'].ravel() <NEW_LINE> time_span = self.int1.time_span() <NEW_LINE> self.assertIsInstance(time_span, nts.IntervalSet) <NEW_LINE> self.assertEqual(time_span['start'][0], a_i1[0]) <NEW_LINE> ...
return the total length and the timespan of the interval set
625941c310dbd63aa1bd2b74
def read(notebook): <NEW_LINE> <INDENT> for i in notebook: print(i)
Prints each note, one per line.
625941c3d6c5a10208144019
def format_task(task, detailed_output=False): <NEW_LINE> <INDENT> result = {"uuid": task.taskuuid, "exit_code": task.exitcode} <NEW_LINE> if detailed_output: <NEW_LINE> <INDENT> result.update( { "file_uuid": task.fileuuid, "file_name": task.filename, "time_created": format_datetime(task.createdtime), "time_started": fo...
Format task attributes for endpoint response
625941c329b78933be1e567e
def make_audio_signals(self): <NEW_LINE> <INDENT> if self.result_masks is None or self.audio_signal.stft_data.size <= 0: <NEW_LINE> <INDENT> raise ValueError('Cannot make audio signals prior to running algorithm!') <NEW_LINE> <DEDENT> self.estimated_sources = [] <NEW_LINE> for cur_mask in self.result_masks: <NEW_LINE> ...
Returns a list of signals (as :class:`audio_signal.AudioSignal` objects) created by applying the ideal masks. This creates the signals by element-wise multiply the masks with the mixture stft. Prior to running this, it is expected that :func:`run()` has been called or else this will throw an error. These of signals is ...
625941c3baa26c4b54cb10f1
def l1normDistance(rankA, rankB): <NEW_LINE> <INDENT> distance = 0 <NEW_LINE> for i in range(0,len(rankA)): <NEW_LINE> <INDENT> distance += abs(rankA[i] - rankB[i]) <NEW_LINE> <DEDENT> return distance
calculates distance between rankA and rankB (treat them as vectors in R^M) using l1 norm :param rankA: first rank :param rankB: second rank :return: distance between rankA and rankB with l1 norm
625941c34f6381625f114a0c
def configure_ihost(self, context, host, do_worker_apply=False): <NEW_LINE> <INDENT> LOG.debug("configure_ihost %s" % host.hostname) <NEW_LINE> self._puppet.update_system_config() <NEW_LINE> self._puppet.update_secure_system_config() <NEW_LINE> if host.personality == constants.CONTROLLER: <NEW_LINE> <INDENT> self._conf...
Configure a host. :param context: an admin context. :param host: a host object. :param do_worker_apply: configure the worker subfunctions of the host.
625941c3d486a94d0b98e115
def check_can_conver(self, user_info, user_created=None): <NEW_LINE> <INDENT> check_time = self.check_coupon_time(user_info, user_created) <NEW_LINE> enable = True <NEW_LINE> tip = '立即兑换' <NEW_LINE> need_coin_num = self.coupon_data.get('credit_coin') <NEW_LINE> level_min = self.coupon_data.get('level_min') <NEW_LINE> i...
兑换检查:1、生效 2、失效 3、用户信用币 4、信用等级 :param user: :param use_status: :param user_created: :return:
625941c3f7d966606f6a9fd2
def decr(self, key, val): <NEW_LINE> <INDENT> raise NotImplementedError
performs DECR <key> returns: None or int If decrement fails, return None If decrement succeeds, return the new value after decrement
625941c373bcbd0ca4b2c046
def put_hPalette(self, hPalette): <NEW_LINE> <INDENT> return super(IScreenDisplay, self).put_hPalette(hPalette)
Method IDisplay.put_hPalette (from IDisplay) INPUT hPalette : OLE_HANDLE
625941c3ac7a0e7691ed40a0
def add_to_frontier(self,path): <NEW_LINE> <INDENT> if self.method=="astar": <NEW_LINE> <INDENT> value = path.cost+self.problem.heuristic(path.end()) <NEW_LINE> <DEDENT> if self.method=="best": <NEW_LINE> <INDENT> value = self.problem.heuristic(path.end()) <NEW_LINE> <DEDENT> if self.method=="least-cost": <NEW_LINE> <I...
add path to the frontier with the appropriate cost
625941c38a349b6b435e8143
def integrate(function, initial_state, end_time=1.0, n_steps=10, step="euler"): <NEW_LINE> <INDENT> check_parameter_accepted_values(step, "step", STEP_FUNCTIONS) <NEW_LINE> dt = end_time / n_steps <NEW_LINE> states = [initial_state] <NEW_LINE> current_state = initial_state <NEW_LINE> step_function = globals()[STEP_FUNC...
Compute the flow under the vector field using symplectic euler. Integration function to compute flows of vector fields on a regular grid between 0 and a finite time from an initial state. Parameters ---------- function : callable Vector field to integrate. initial_state : tuple of arrays Initial position and ...
625941c3236d856c2ad447a8
def verify_args(self,options,args): <NEW_LINE> <INDENT> if hasattr(self,args[0]): <NEW_LINE> <INDENT> func = getattr(self.args[0]) <NEW_LINE> func() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.parse.print_help()
校验并调用相应的功能 :param options: :param args: :return:
625941c385dfad0860c3ae2a
def plot_ACS( self, glm, **keywords ): <NEW_LINE> <INDENT> defaults = dict( scaler=0.1, degree=180, change=lambda x: 2.5 * x, figsize=(10, 5), colormap=mpl.cm.jet, colors=True ) <NEW_LINE> for k in defaults: <NEW_LINE> <INDENT> if k not in keywords: <NEW_LINE> <INDENT> keywords[k] = defaults[k] <NEW_LINE> <DEDENT> <DED...
Plot a tree in which the node size correlates with the size of the ancestral node.
625941c3293b9510aa2c3268
def on_parent_button_press_event(self, widget, event): <NEW_LINE> <INDENT> if event.button == 1: <NEW_LINE> <INDENT> if self.move_finish(): <NEW_LINE> <INDENT> if providers.get_provider('playback-markers', 'repeat-end') is None: <NEW_LINE> <INDENT> position = event.x / widget.allocation.width <NEW_LINE> self.end_marker...
Finishes or cancels insertion of markers
625941c31b99ca400220aa81
def evaluate_density(self, x: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> density = 0 <NEW_LINE> for w, (mu, var) in zip(self.mixture_wts, self.params): <NEW_LINE> <INDENT> density += w * self._gauss_pdf(x, mu, var) <NEW_LINE> <DEDENT> return density
Evaluate the probability of a set of points under the mixture distribution. Args: x (np.ndarray): the points to evaluate Returns: np.ndarray: the density for each point
625941c3d10714528d5ffcb2
def get_path_code(self): <NEW_LINE> <INDENT> return self.__path_code
get url's encoded path segment. :return: str -> encoded path segment
625941c3cdde0d52a9e53002
def interp_large(x0, y0, xnew, axis, nchunks=1, **kwargs): <NEW_LINE> <INDENT> success = False <NEW_LINE> specs_interp = interp1d(x=x0, y=y0, axis=axis, **kwargs) <NEW_LINE> while not success: <NEW_LINE> <INDENT> xchunks = np.array_split(xnew, nchunks) <NEW_LINE> try: <NEW_LINE> <INDENT> ynew = np.concatenate( [specs_i...
large-array-tolerant interpolation
625941c329b78933be1e567f
def get_urls(n): <NEW_LINE> <INDENT> lst = [] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> urli = 'https://book.douban.com/tag/%%E5%%B0%%8F%%E8%%AF%%B4?start=%i&type=T'%(i*20) <NEW_LINE> lst.append(urli) <NEW_LINE> <DEDENT> return lst
【分页网页url采集】函数 n: 页数菜蔬 结果: 得到一个分页网页list
625941c323e79379d52ee536
def register_transaction(self, front_end_id, trust_trans): <NEW_LINE> <INDENT> assert( not self.has_transaction(front_end_id) ) <NEW_LINE> self.trans_registry[front_end_id] = trust_trans
Registers a transaction with this front end plugin, using the unique identifier provided by the bokeep shell
625941c30fa83653e4656f8c
def some_elements(self): <NEW_LINE> <INDENT> d = self.monomial <NEW_LINE> v = self._v <NEW_LINE> return [d( ('E',v(1,1)) ), d( ('E',v(-2,-2)) ), d( ('E',v(0,1)) ), d( ('t',v(1,1)) ), d( ('t',v(4,-1)) ), d( ('t',v(2,3)) ), d( ('K',2) ), d( ('K',4) ), self.an_element()]
Return some elements of ``self``. EXAMPLES:: sage: L = lie_algebras.RankTwoHeisenbergVirasoro(QQ) sage: L.some_elements() [E(1, 1), E(-2, -2), E(0, 1), t(1, 1), t(4, -1), t(2, 3), K2, K4, K3 - 1/2*t(-1, 3) + E(1, -3) + E(2, 2)]
625941c3a934411ee3751664
def testStepDown(self): <NEW_LINE> <INDENT> x0 = numpy.arange(1000) <NEW_LINE> center = 444 <NEW_LINE> height = 1234 <NEW_LINE> fwhm = 210 <NEW_LINE> y0 = functions.sum_stepdown(x0, height, center, fwhm) <NEW_LINE> self.assertLess(max(y0), height) <NEW_LINE> self.assertAlmostEqual(max(y0), height, places=1) <NEW_LINE> ...
sanity check for step down: - absolute value of derivative must be largest around the step center - max value must be close to height parameter
625941c37d847024c06be28a
def run(self, result): <NEW_LINE> <INDENT> if not self.setup_done: <NEW_LINE> <INDENT> self.setup() <NEW_LINE> <DEDENT> ipaddr = self.context_cfg["target"].get("ipaddr", '127.0.0.1') <NEW_LINE> options = self.scenario_cfg['options'] <NEW_LINE> packetsize = options.get("packetsize", 60) <NEW_LINE> self.number_of_ports =...
execute the benchmark
625941c3627d3e7fe0d68e1f
def test_migration_nothing_to_migrate(self): <NEW_LINE> <INDENT> self._create_instances(pre_newton=0, total=5) <NEW_LINE> match, done = virtual_interface.fill_virtual_interface_list( self.context, 5) <NEW_LINE> self.assertEqual(5, match) <NEW_LINE> self.assertEqual(0, done)
This test when there already populated VirtualInterfaceList objects for created instances.
625941c315baa723493c3f45
def exact_filter(model, filter_, cumulative_filter_dict): <NEW_LINE> <INDENT> key = filter_['name'] <NEW_LINE> if isinstance(getattr(model, key).property.columns[0].type, sql.types.Boolean): <NEW_LINE> <INDENT> cumulative_filter_dict[key] = ( utils.attr_as_boolean(filter_['value'])) <NEW_LINE> <DEDENT> else: <NEW_LINE>...
Applies an exact filter to a query. :param model: the table model in question :param dict filter_: describes this filter :param dict cumulative_filter_dict: describes the set of exact filters built up so far
625941c31f5feb6acb0c4b23
def process_video(content): <NEW_LINE> <INDENT> content.seek(0) <NEW_LINE> meta = video_meta(content) <NEW_LINE> content.seek(0) <NEW_LINE> return meta
Retrieves the video/audio metadata :param BytesIO content: content stream :return: dict video/audio metadata
625941c3566aa707497f453c
def parse_all_cached_files(scrape_jobs, session, scraper_search): <NEW_LINE> <INDENT> files = _get_all_cache_files() <NEW_LINE> num_cached = num_total = 0 <NEW_LINE> mapping = {} <NEW_LINE> for job in scrape_jobs: <NEW_LINE> <INDENT> cache_name = cached_file_name( job['query'], job['search_engine'], job['scrape_method'...
Walk recursively through the cachedir (as given by the Config) and parse all cached files. Args: session: An sql alchemy session to add the entities scraper_search: Abstract object representing the current search. Returns: The scrape jobs that couldn't be parsed from the cache directory.
625941c3236d856c2ad447a9
def xr_area_weighted_stat(xr_data, stat='mean', lon_bounds=None, lat_bounds=None, lon_name='lon', lat_name='lat'): <NEW_LINE> <INDENT> area = xr_area(xr_data, lon_name=lon_name, lat_name=lat_name) <NEW_LINE> if (lon_bounds is not None) or (lat_bounds is not None): <NEW_LINE> <INDENT> area = xr_mask_bounds(area, lon_bou...
Calculate area-weighted mean or sum across globe (default) or a specified region. Args: xr_data: an xarray Dataset or DataArray, with longitude and latitude dimensions stat: statistic to calculate, either 'mean' (default) or 'sum' lon_bounds: tuple/list containing longitude bounds (default None) lat_bo...
625941c30fa83653e4656f8d
def get_user_details(self, response): <NEW_LINE> <INDENT> user_data = response['user'] <NEW_LINE> user_data.update({ 'username': user_data.get('user_name'), 'email': user_data.get('settings', {}).get('email_address', ''), 'first_name': user_data.get('first_name'), 'last_name': user_data.get('last_name'), 'fullname': us...
Return user details from an Untappd account
625941c3656771135c3eb83d
def ex_exponetiation(): <NEW_LINE> <INDENT> exp_value = 2**10 <NEW_LINE> print("exp(2**10):{0}".format(exp_value))
指数演算子 Exponetiation '**'
625941c316aa5153ce362449
@hook.command <NEW_LINE> def choose(inp): <NEW_LINE> <INDENT> c = re.findall(r'([^,]+)', inp) <NEW_LINE> if len(c) == 1: <NEW_LINE> <INDENT> c = re.findall(r'(\S+)', inp) <NEW_LINE> if len(c) == 1: <NEW_LINE> <INDENT> return 'the decision is up to you' <NEW_LINE> <DEDENT> <DEDENT> return random.choice(c).strip()
.choose <choice1>, <choice2>, ... <choicen> -- makes a decision
625941c345492302aab5e292
def get_redundant_pairs (df): <NEW_LINE> <INDENT> result = set() <NEW_LINE> cols = df.columns <NEW_LINE> for i in range(0, df.shape[1]): <NEW_LINE> <INDENT> for j in range(0, i + 1): <NEW_LINE> <INDENT> result.add((cols[i], cols[j])) <NEW_LINE> <DEDENT> <DEDENT> return result
Get diagonal and lower triangular pairs of correlation matrix.
625941c39b70327d1c4e0da5
@pytest.mark.parametrize('outer_widths,title,expected', [ ([3, 3, 3], 123, '<123+---+--->'), ([3, 3, 3], 0.9, '<0.9+---+--->'), ([3, 3, 3], True, '<True---+--->'), ([3, 3, 3], False, '<False--+--->'), ]) <NEW_LINE> def test_non_string(outer_widths, title, expected): <NEW_LINE> <INDENT> actual = build_border(outer_width...
Test with non-string values. :param iter outer_widths: List of integers representing column widths with padding. :param title: Title in border. :param str expected: Expected output.
625941c363d6d428bbe444c0
def combine_new_ds_dim( dss: Union[Mapping[str, "T_DSorDA"], Sequence["T_DSorDA"]], new_dim: str, new_coords: Optional[Sequence[float]] = None, ) -> "T_DSorDA": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> new_ds = xr.concat(dss.values(), new_dim) <NEW_LINE> new_ds[new_dim] = list(dss.keys()) <NEW_LINE> <DEDENT> except...
Combines a dictionary of datasets along a new dimension using dictionary keys as the new coordinates. Parameters ---------- dss : dict or list Dictionary or list of xarray Datasets or dataArrays new_dim : str The name of the newly created dimension new_coords Only used if `dss` is a list Returns ------- xa...
625941c399cbb53fe6792bb8
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(MoveBaseActionResult, self).__init__(*args, **kwds) <NEW_LINE> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.status is None: <NEW_LINE> <INDENT> self.status = a...
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,status,result :param args:...
625941c3fff4ab517eb2f40c
def cycle(self, direction: argtypes.HistoryDirection, text: str) -> str: <NEW_LINE> <INDENT> return self._cycle_tmpdeque(direction, text, CycleMode.Regular, match=text[0])
Cycle through command history. Called from the command line by the history command. Args: direction: HistoryDirection element. text: Current text in the command line. Returns: The received command to set in the command line.
625941c316aa5153ce36244a
def test_traffic_lights(self): <NEW_LINE> <INDENT> rospy.init_node('test_node', anonymous=True) <NEW_LINE> msg = rospy.wait_for_message( "/carla/traffic_lights", CarlaTrafficLightStatusList, timeout=TIMEOUT) <NEW_LINE> self.assertNotEqual(len(msg.traffic_lights), 0)
Tests traffic_lights
625941c3cad5886f8bd26fab
def __init__(self, energyConsumer0=None, *args, **kw_args): <NEW_LINE> <INDENT> self._energyConsumer0 = [] <NEW_LINE> self.energyConsumer0 = [] if energyConsumer0 is None else energyConsumer0 <NEW_LINE> super(AggregateLoad, self).__init__(*args, **kw_args)
Initialises a new 'AggregateLoad' instance. @param energyConsumer0:
625941c38e71fb1e9831d77b
def read_trained_model(subject, settings, verbose=False): <NEW_LINE> <INDENT> model_name = "{0}_model_for_{1}_using_{2}_feats.model".format( settings['RUN_NAME'], subject, settings['VERSION']) <NEW_LINE> print_verbose("##Loading Model: {0}##".format(model_name), flag...
Read trained model from repo input: model_name (string for model file name) settings (parsed SETTINGS.json object) output: model
625941c3f8510a7c17cf96cc
def upgrowth(self, tree, alpha): <NEW_LINE> <INDENT> for item in reversed(tree.headerList): <NEW_LINE> <INDENT> localTree = self.createLocalTree(tree, item) <NEW_LINE> node = tree.mapItemNodes[item] <NEW_LINE> ItemTotalUtility = 0 <NEW_LINE> while node != -1: <NEW_LINE> <INDENT> ItemTotalUtility += node.nodeUtility <NE...
A Method to Mine UP Tree recursively :param tree: UPTree to mine :type tree: UPTree :param alpha: prefix itemset :type alpha: list
625941c394891a1f4081ba79
def upload_media(request, form_cls, up_file_callback, instance=None, **kwargs): <NEW_LINE> <INDENT> form = form_cls(request.POST, request.FILES) <NEW_LINE> if request.method == 'POST' and form.is_valid(): <NEW_LINE> <INDENT> return up_file_callback(request.FILES, request.user, **kwargs) <NEW_LINE> <DEDENT> elif not for...
Uploads media files and returns a list with information about each media: name, url, thumbnail_url, width, height. Args: * request object * form class, used to instantiate and validate form for upload * callback to save the file given its content and creator * extra kwargs will all be passed to the callback
625941c3d4950a0f3b08c321
def on_train_begin(self, pbar:PBar, metrics_names:Collection[str], **kwargs:Any)->None: <NEW_LINE> <INDENT> self.pbar = pbar <NEW_LINE> self.names = ['epoch', 'train_loss'] if self.no_val else ['epoch', 'train_loss', 'valid_loss'] <NEW_LINE> self.names += metrics_names <NEW_LINE> if hasattr(self, '_added_met_names'): s...
Initialize recording status at beginning of training.
625941c3004d5f362079a305
def testHeight(self): <NEW_LINE> <INDENT> self.assertEqual(self.tree.root.height(), 4)
Verify the height of the tree is 4.
625941c36e29344779a625e5
def get_sum_zero_pairs(numbers): <NEW_LINE> <INDENT> pairs = [] <NEW_LINE> numbers.sort() <NEW_LINE> numbers_set = set(numbers) <NEW_LINE> for num in numbers_set: <NEW_LINE> <INDENT> if (num < 0) and (-num in numbers_set): <NEW_LINE> <INDENT> pairs.append([num, -num]) <NEW_LINE> <DEDENT> elif num == 0: <NEW_LINE> <INDE...
Given list of numbers, return list of pairs summing to 0. Given a list of numbers, add up each individual pair of numbers. Return a list of each pair of numbers that adds up to 0. For example: >>> sort_pairs( get_sum_zero_pairs([1, 2, 3, -2, -1]) ) [[-2, 2], [-1, 1]] >>> sort_pairs( get_sum_zero_pairs([...
625941c3c4546d3d9de72a03
def __init__(self, description: K, crn: "Crn"): <NEW_LINE> <INDENT> self.crn: Crn = crn <NEW_LINE> self.description: K = description <NEW_LINE> self.activated: bool = False
Create the object from its 'description', to be linked to the parent 'crn'. @param description: object description @type description: K (generic Hashable) @param crn: parent chemical reaction network @type crn: Crn
625941c3d164cc6175782d1f
def _lema_violated_balanced(len_s, s, counter_open_brackets): <NEW_LINE> <INDENT> current_pos = len_s - len(s) <NEW_LINE> OPEN_BRACKET = '(' <NEW_LINE> CLOSE_BRACKET = ')' <NEW_LINE> if len(s) == 0: <NEW_LINE> <INDENT> return ("end", counter_open_brackets) <NEW_LINE> <DEDENT> first_char = s[0] <NEW_LINE> if first_char ...
The function checks if a string is balanced or not :param len_s: int, the length of the original string :param s: string, the current string :param counter_open_brackets: int, number of '(' without ')' currently on test :return: ("end", counter_open_brackets) if the recursion tested the w...
625941c3dd821e528d63b17b
def animate(self, i): <NEW_LINE> <INDENT> global planet, dt <NEW_LINE> planet.step(dt) <NEW_LINE> instrument.measure() <NEW_LINE> self._bob_pos.set_data([self.planet.state[2]], [self.planet.state[1]]) <NEW_LINE> self._bob_traj.set_data(self.theta_arr, self.radial_arr) <NEW_LINE> self._bob_time_text.set_text('time = %.1...
perform animation step
625941c33c8af77a43ae3770
def list( self, resource_group_name, load_balancer_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2017-1...
Gets associated load balancer network interfaces. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :...
625941c3498bea3a759b9a81
def _get_entrez_db_rettype (entrez_db): <NEW_LINE> <INDENT> if (entrez_db in ENTREZ_DB_DICT): <NEW_LINE> <INDENT> return (ENTREZ_DB_DICT[entrez_db]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = '"{}" isn\'t a supported NCBI\'s Entrez DB'.format(entrez_db) <NEW_LINE> raise ValueError(message)
Check if the given entrez database is supported by the BioSeqs class. Supported entrez databases are stored in 'ENTREZ_DB_DICT'. Arguments: entrez_db (string) Entrez database name. Returns: string Corresponding retrieval type for the given entrez database. Raises: ValueError If t...
625941c394891a1f4081ba7a
def est_dame(self): <NEW_LINE> <INDENT> return self.type_de_piece == "dame"
Détermine si la pièce est une dame. Returns: (bool) : True si la pièce est une dame, False autrement.
625941c35fdd1c0f98dc0204
def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.id == request.user.id
Check user is updating their own profile
625941c310dbd63aa1bd2b75
def send_text(email, pas, smtp, port, sms_gateway, msg_subject, msg_content): <NEW_LINE> <INDENT> server = smtplib.SMTP(smtp,port) <NEW_LINE> server.starttls() <NEW_LINE> server.login(email,pas) <NEW_LINE> msg = MIMEMultipart() <NEW_LINE> msg['From'] = email <NEW_LINE> msg['To'] = sms_gateway <NEW_LINE> msg['Subject'] ...
Use this to send the text. Args: ----- email: your email address that you're sending from (str) pas: the password for your email (str) smtp: the smtp server address you're sending from port: the port the smtp server you're sending from runs on sms_gateway: the phone number @ provider gateway you're...
625941c326238365f5f0ee3d
def __call__(self, environ, start_response): <NEW_LINE> <INDENT> req = Request(environ) <NEW_LINE> preferred_languages = list(req.accept_language) <NEW_LINE> if self.default_language not in preferred_languages: <NEW_LINE> <INDENT> preferred_languages.append(self.default_language) <NEW_LINE> <DEDENT> translation = gette...
Called by WSGI when a request comes in. Args: environ: A dict holding environment variables. start_response: A WSGI callable (PEP333). Returns: Application response data as an iterable. It just returns the return value of the inner WSGI app.
625941c3ff9c53063f47c1c5
def _ping_from_remote_client( self, target_ip, count=PING_COUNT, ip_version=4): <NEW_LINE> <INDENT> connection = self.connect_to_proxy() <NEW_LINE> return self._ping_from_here( target_ip=target_ip, count=count, connection=connection, ip_version=ip_version)
Ping target from a remote host. Connects to the proxy, and then pings through proxy connection. @param target_ip: The IP address of the target host @param count: Number of pings to attempt @param ip_version: Version of the IP address to ping. @return String of ping cmd output.
625941c397e22403b379cf6a
def __init__( self, *, value: Optional[List["Location"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(LocationListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value
:keyword value: An array of locations. :paramtype value: list[~azure.mgmt.resource.subscriptions.v2021_01_01.models.Location]
625941c33346ee7daa2b2d3c
def rand10(self): <NEW_LINE> <INDENT> index = acceptance = 40 <NEW_LINE> while index >= acceptance: <NEW_LINE> <INDENT> row = rand7() <NEW_LINE> col = rand7() <NEW_LINE> index = (row - 1) * 7 + col - 1 <NEW_LINE> <DEDENT> return (index % 10) + 1
Note ---- - Rejection Sampling
625941c38a43f66fc4b54038
def reset(self): <NEW_LINE> <INDENT> self._sent = False <NEW_LINE> self._socket = None <NEW_LINE> self._data = None
Reset attributes needed to reuse this beam.
625941c3566aa707497f453d
def _item(self, request, id, do_authz=False, field_list=None, parent_id=None): <NEW_LINE> <INDENT> kwargs = {'fields': field_list} <NEW_LINE> action = self._plugin_handlers[self.SHOW] <NEW_LINE> if parent_id: <NEW_LINE> <INDENT> kwargs[self._parent_id_name] = parent_id <NEW_LINE> <DEDENT> obj_getter = getattr(self._plu...
Retrieves and formats a single element of the requested entity.
625941c33cc13d1c6d3c734c
def load_data_and_labels(pos_fn, neg_fn): <NEW_LINE> <INDENT> pos_file = urlopen(pos_fn) <NEW_LINE> neg_file = urlopen(neg_fn) <NEW_LINE> positive_examples = list(pos_file.readlines()) <NEW_LINE> positive_examples = [s.strip() for s in positive_examples] <NEW_LINE> negative_examples = list(neg_file.readlines()) <NEW_LI...
Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels.
625941c3711fe17d82542340
def ext_to_queue(self): <NEW_LINE> <INDENT> path1 = configs.SECL_DIR <NEW_LINE> for filename in os.listdir(path1): <NEW_LINE> <INDENT> type1 = filename.split('_')[0] <NEW_LINE> type2 = filename.split('_')[1] <NEW_LINE> type3 = filename.split('_')[2].split('.')[0] <NEW_LINE> words_data = ExtSougouScel().deal(path1 + fil...
遍历目录下的所有词库文件 解析文件存入Queue
625941c391af0d3eaac9b9e8
def test_01_SourceConditonEntityType_SourceConditonEntityUsers(self): <NEW_LINE> <INDENT> value = pykerio.enums.SourceConditonEntityType(name='SourceConditonEntityUsers') <NEW_LINE> self.assertEquals(value.dump(), 'SourceConditonEntityUsers') <NEW_LINE> self.assertEquals(value.get_name(), 'SourceConditonEntityUsers') <...
Test SourceConditonEntityType with SourceConditonEntityUsers
625941c3a05bb46b383ec7f4
def get_munin_stats(server, destination_directory='.'): <NEW_LINE> <INDENT> pass
Retrieve the munin statistics
625941c3b5575c28eb68dfd0
def zero_coupon_bond(par, y, t): <NEW_LINE> <INDENT> return par/(1+y)**t
Price a zero coupon bond. Par - face value of the bond. y - annual yield or rate of the bond. t - time to maturity in years.
625941c34c3428357757c2fb
def main(): <NEW_LINE> <INDENT> argument_spec = openstack_full_argument_spec( name=dict(type='str', required=True), port_id=dict(type='str'), state=dict(default='present', choices=['absent', 'present'])) <NEW_LINE> module_kwargs = openstack_module_kwargs() <NEW_LINE> module = AnsibleModule(argument_spec, **module_kwarg...
Main module function
625941c37d43ff24873a2c71
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'orphan.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 you sure ...
Run administrative tasks.
625941c3f548e778e58cd54e
def Q_symbol(self, Q_chain): <NEW_LINE> <INDENT> return WeakTableau(SkewTableau(chain=Q_chain[::2]), self.k-1)
Return the labels along the horizontal boundary of a rectangular growth diagram as a skew :class:`~sage.combinat.k_tableau.WeakTableau`. EXAMPLES:: sage: LLMS4 = GrowthDiagram.rules.LLMS(4) sage: G = LLMS4([3,4,1,2]) sage: G.Q_symbol().pp() 1 2 3 4
625941c3a17c0f6771cbe023
def register(self, serializer): <NEW_LINE> <INDENT> model_name = self.get_model_alias(serializer.Meta.model) <NEW_LINE> if model_name in self.serializers: <NEW_LINE> <INDENT> raise ValueError("Serializer {} already registered for model {}".format(serializer, model_name)) <NEW_LINE> <DEDENT> self.serializers[model_name]...
Add form to register
625941c3cb5e8a47e48b7a7e
def light_years_to_angstroms(light_years): <NEW_LINE> <INDENT> return convert(light_years, 'light_years', 'angstroms')
Convert light years to angstroms.
625941c31f037a2d8b9461d0
def get_subscription(self, tenantId, serverId, subscriptionId): <NEW_LINE> <INDENT> r_query = Subscription.objects.get(subscription_Id__exact=subscriptionId, serverId__exact=serverId) <NEW_LINE> subscription = SubscriptionModel() <NEW_LINE> subscription.ruleId = r_query.__getattribute__("ruleId") <NEW_LINE> subscriptio...
Returns information about a subscription. :param str tenantId: The id of the tenant :param str serverId: The id of the server :param str subscriptionId: The id of the subscription
625941c3a8370b7717052872
def read_format(fmt: str) -> Generator[tuple, tuple, tuple]: <NEW_LINE> <INDENT> return (yield (Traps._read_struct, Struct(fmt)))
read specific formatted data
625941c3046cf37aa974cd1b