code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def fillblock(self, *args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> return self._sprite.state.fillblock <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(args[0], Block): <NEW_LINE> <INDENT> self._sprite.state = self._sprite.state._replace(fillblock=args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | Return or set the block that the turtle fills shapes with. Several
input formats are allowed:
``fillblock()``
Return the current fill block. May be used as input to another
penblock or fillblock call.
``fillblock(Block('grass'))``
Set the fill block to the specified :class:`~picraft.block.Block`
insta... | 625941f5cad5886f8bd2760e |
def test_project_insertion(self): <NEW_LINE> <INDENT> p = self.insert_project() <NEW_LINE> self.assertEqual(p.id, 1) | Tests that a project can be inserted, and that the
id is retrievable afterwards. (This is something that
the custom psycopg2 driver is needed for.) | 625941f5e64d504609d74e76 |
def wrapper_filter(df,dyad, max_gap, interpolated): <NEW_LINE> <INDENT> b = filter_by_dyad(df, dyad[0], dyad[1], 1995, 2016, 1, 12, 1, 31) <NEW_LINE> b1 = filter_by_gap(b, max_gap, 1995, 2016, interpolated) <NEW_LINE> return (dyad[0], dyad[1], b1) | Wrapper function to parallelize the creation of
timeseries.
Args:
-----
df[dataframe]: dataframe
dyad [tuple]: tuple with shape ('Source', 'Target')
Returns:
--------
tuple of shape ('Source', 'Target', timeseries) | 625941f5442bda511e8bea45 |
def basicHeatmap(z, x=[], y=[], title='', xlbl='', ylbl='', plot=True): <NEW_LINE> <INDENT> traces = [go.Heatmap(z=z, x=x, y=y)] <NEW_LINE> layout = go.Layout(title=title, xaxis={'title': xlbl}, yaxis={'title': ylbl}, ) <NEW_LINE> fig = go.Figure(data=traces, layout=layout) <NEW_LINE> return plotOut(fig, plot) | Plots a basic heatmap | 625941f523e79379d52eeb92 |
def make_default_config() -> dict: <NEW_LINE> <INDENT> return config_schema_to_defaults(SCHEMA) | Create a default solitude configuration.
:return: a configuration dictionary | 625941f566656f66f7cbc7e4 |
def setbackground(self,theory): <NEW_LINE> <INDENT> if theory in self.bkglist: <NEW_LINE> <INDENT> self.fitconfig['fitbkg']=theory <NEW_LINE> self.bkgfun=self.bkgdict[self.fitconfig['fitbkg']][0] <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 | method: setbackground(self,background)
Usage: self.setbackground(background)
Input:
theory: The name of the background to be used.
It has to be one of the keys of self.bkgdict
Output:
returns 0 if everything went fine | 625941f526068e7796caf31f |
def listen(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for event in self.longpoll.listen(): <NEW_LINE> <INDENT> if event.user_id and event.type == VkEventType.MESSAGE_NEW and event.to_me: <NEW_LINE> <INDENT> self.group.api.messages.send(user_id=event.user_id, message='Доступные команды:', keyboard=self.command_... | Listen vk events. | 625941f563b5f9789fde771d |
def try_recover_from_autosave(self): <NEW_LINE> <INDENT> autosave_dir = get_conf_path('autosave') <NEW_LINE> autosave_mapping = CONF.get('editor', 'autosave_mapping', {}) <NEW_LINE> dialog = RecoveryDialog(autosave_dir, autosave_mapping, parent=self.editor) <NEW_LINE> dialog.exec_if_nonempty() <NEW_LINE> self.recover_f... | Offer to recover files from autosave. | 625941f5187af65679ca5757 |
def _from_dict(obj): <NEW_LINE> <INDENT> if 'reactions' not in obj: <NEW_LINE> <INDENT> raise Exception('JSON object has no reactions attribute. Cannot load.') <NEW_LINE> <DEDENT> model = Model() <NEW_LINE> new_metabolites = [] <NEW_LINE> for metabolite in obj['metabolites']: <NEW_LINE> <INDENT> new_metabolite = Metabo... | build a model from a dict | 625941f58e71fb1e9831dddd |
def rgb_to_lab(L, a, b): <NEW_LINE> <INDENT> print("inside rgb to lab") <NEW_LINE> x_l = (0.412453 * L) + (0.357580 * a) + (0.180423 * b) <NEW_LINE> y_a = (0.212671 * L) + (0.715160 * a) + (0.072169 * b) <NEW_LINE> z_b = (0.019334 * L) + (0.119193 * a) + (0.950227 * b) <NEW_LINE> x_ref = 0.950456 <NEW_LINE> y_ref = ... | Convert from RGB color space to Lab color space. | 625941f5851cf427c661ab40 |
def gen_data_slicer_by_time(self, run_number, start_time, end_time, time_step, raw_nexus_name=None): <NEW_LINE> <INDENT> if raw_nexus_name is None: <NEW_LINE> <INDENT> datatypeutility.check_int_variable('Run number', run_number, (1, None)) <NEW_LINE> <DEDENT> if raw_nexus_name is not None: <NEW_LINE> <INDENT> chopper =... | Generate data slicer by time
if base file name is given, then run number will be ignored, even it is specified with an integer,
which may not make any sense.
:param run_number: run number (integer)
:param start_time:
:param end_time:
:param time_step:
:param raw_nexus_name: Base file name (str)
:return: | 625941f50c0af96317bb881d |
def is_subtree(s: TreeNode, t: TreeNode) -> bool: <NEW_LINE> <INDENT> return in_order(t) in in_order(s) | Time: O(m + n)
Space: O(m + n) | 625941f56fb2d068a760f6de |
def _search_error_code(error_code, list_a, list_b, list_c): <NEW_LINE> <INDENT> if error_code in list_a: <NEW_LINE> <INDENT> return list_a[error_code] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if error_code in list_b: <NEW_LINE> <INDENT> return list_b[error_code] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if err... | Search an error code and returns the corresponding error message.
:param int error_code: Error code
:param dict list_a: List to search in
:param dict list_b: Another list to search in
:param dict list_c: Yet another list to search in
:return string: An error message or empty string. | 625941f51f037a2d8b946833 |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> add_devices([ZigBeeSwitch(hass, ZigBeeDigitalOutConfig(config))]) | Set up the ZigBee switch platform. | 625941f563f4b57ef000173d |
def run(self, **kwargs): <NEW_LINE> <INDENT> self.export_to_xml() <NEW_LINE> openmc.run(**kwargs) <NEW_LINE> n = self.settings.batches <NEW_LINE> if self.settings.statepoint is not None: <NEW_LINE> <INDENT> if 'batches' in self.settings.statepoint: <NEW_LINE> <INDENT> n = self.settings.statepoint['batches'][-1] <NEW_LI... | Creates the XML files, runs OpenMC, and returns k-effective
Parameters
----------
**kwargs
All keyword arguments are passed to :func:`openmc.run`
Returns
-------
uncertainties.UFloat
Combined estimator of k-effective from the statepoint | 625941f530c21e258bdfaadc |
def Hide(self): <NEW_LINE> <INDENT> pass | Hide(self: Control)
Conceals the control from the user. | 625941f566673b3332b926c8 |
def set_coords(self, coords): <NEW_LINE> <INDENT> self.x = coords["x"] <NEW_LINE> self.y = coords["y"] <NEW_LINE> self.xx = coords["xx"] <NEW_LINE> self.yy = coords["yy"] <NEW_LINE> self.dim1 = self.yy.shape[0] <NEW_LINE> self.dim2 = self.xx.shape[1] <NEW_LINE> self.vals = np.empty((self.dim1,self.dim2)) <NEW_LINE> sel... | Sets up the coordinates for the field. | 625941f5236d856c2ad44e1b |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for val1 in self.machines: <NEW_LINE> <INDENT> length = len(val1) <NEW_LINE> if python3 or type(val1) == unicode: <NEW_LINE> <INDENT> val1 = val1.encode('utf-8') <NEW_LINE> length = len(val1) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%lengt... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941f507d97122c4178ed2 |
def setUp(self): <NEW_LINE> <INDENT> self.n = 500 <NEW_LINE> self.X = np.arange(self.n).reshape(-1, 1) <NEW_LINE> self.y = np.ones(self.n) <NEW_LINE> mask = (self.X < int(self.n/3)).ravel() <NEW_LINE> self.y[mask] = 0 <NEW_LINE> self.y0_idx = np.where(self.y==0)[0] <NEW_LINE> self.y1_idx = np.... | Generate toy data | 625941f591af0d3eaac9c054 |
@pytest.mark.parametrize( "number, expected_value", [ (24, []), (104, [(10, 2)]), (328, [(18, 2)]), (611, []), (2000, [(44, 8), (40, 20)]), (2311, []), (9945, [(99, 12), (96, 27), (93, 36), (72, 69)]), (41410, [(197, 51), (183, 89), (181, 93), (159, 127)]), ], ) <NEW_LINE> def test_task243b_main_logic(number, expected_... | Testing task 243a class main logic (must return True if there are two numbers (x, y) that x ^2 + y ^2 = n) | 625941f54e696a04525c9a85 |
def __del__(self): <NEW_LINE> <INDENT> for statement in self.statement: <NEW_LINE> <INDENT> del statement <NEW_LINE> <DEDENT> del self.statement[:] | ! @brief Destructor.
Release Statement instances. | 625941f55166f23b2e1a5790 |
def __init__(self, T, n_batch, n_state, n_ctrl, seed): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.T = T <NEW_LINE> self.n_batch = n_batch <NEW_LINE> self.n_state = n_state <NEW_LINE> self.n_ctrl = n_ctrl <NEW_LINE> self.n_sc = self.n_ctrl + self.n_state <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT>... | LQR constructor
:param T:
:param n_batch:
:param n_state:
:param n_ctrl:
:param n_sc:
:param seed: | 625941f57c178a314d6efaa2 |
def prepare(self): <NEW_LINE> <INDENT> questions = self._create_questions_dict(self.questions_path) <NEW_LINE> print('Questions dict created') <NEW_LINE> answers = self._create_answers_dict(self.answers_path) <NEW_LINE> print('Answers dict created') <NEW_LINE> image_ids = self._get_image_ids(self.images_path) <NEW_LINE... | Prepares the dataset to be used.
It will load all the questions and answers in memory and references to the images. It will also create a
tokenizer holding the word dictionary and both answers and questions will be tokenized and encoded using that
tokenizer. | 625941f5d164cc6175783386 |
def CreateUpdateNodeUnit(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateUpdateNodeUnit", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateUpdateNodeUni... | 创建或更新边缘单元NodeUnit
:param request: Request instance for CreateUpdateNodeUnit.
:type request: :class:`tencentcloud.iecp.v20210914.models.CreateUpdateNodeUnitRequest`
:rtype: :class:`tencentcloud.iecp.v20210914.models.CreateUpdateNodeUnitResponse` | 625941f5e76e3b2f99f3ae37 |
def update_doc_by_id(self, index, id, type= "doc", body=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.es.update(index=index, doc_type=type, id=id, body=body) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) | 更新指定index,type,id所对应的数据.
:param index:
:param type:
:param id:
:param body: 待更新的值.eg:{"doc":dict}
:return: | 625941f54428ac0f6e5bae2f |
def open_settings(self): <NEW_LINE> <INDENT> self.common.log('OnionShareGui', 'open_settings') <NEW_LINE> def reload_settings(): <NEW_LINE> <INDENT> self.common.log('OnionShareGui', 'open_settings', 'settings have changed, reloading') <NEW_LINE> self.common.settings.load() <NEW_LINE> if not self.local_only: <NEW_LINE> ... | Open the SettingsDialog. | 625941f54527f215b584ca88 |
def get_centers(self) -> torch.Tensor: <NEW_LINE> <INDENT> return self.tensor[:, :2] | Returns:
The box centers in a Nx2 array of (x, y). | 625941f5eab8aa0e5d26e191 |
def add_exe_to_path(exe_dir): <NEW_LINE> <INDENT> logger.debug("Add directory, %s, to path", exe_dir) <NEW_LINE> os.environ["PATH"] = exe_dir + os.pathsep + os.environ["PATH"] | Add path to executable to $PATH | 625941f5167d2b6e312191cb |
def test_equals(self): <NEW_LINE> <INDENT> self.comp_vec2.equals(self.comp_vec1) <NEW_LINE> err = self.eq2.base.data - self.eq1.base.data <NEW_LINE> self.assertEqual(np.linalg.norm(err), 0) <NEW_LINE> err = self.pv2.base.data - self.pv1.base.data <NEW_LINE> self.assertEqual(np.linalg.norm(err), 0) | CompositeVector vector-value assignment | 625941f5f8510a7c17cf9d39 |
def sendDescribe(self, target='*', headers=None): <NEW_LINE> <INDENT> self.sendMethod('DESCRIBE', target, headers) | Asks server to describe stream in sdp format | 625941f591af0d3eaac9c055 |
def stop(self): <NEW_LINE> <INDENT> assert self._continue_running <NEW_LINE> with self._lock: <NEW_LINE> <INDENT> self._continue_running = False <NEW_LINE> self._queue = [] <NEW_LINE> self._check_queue.set() <NEW_LINE> <DEDENT> self._thread.join() | Shuts down worker thread | 625941f57d847024c06be8f9 |
def read_and_decode(tfrecords_filename): <NEW_LINE> <INDENT> print("reading from file %s ..." % tfrecords_filename) <NEW_LINE> reader = tf.TFRecordReader() <NEW_LINE> filename_queue = tf.train.string_input_producer([tfrecords_filename], num_epochs=1) <NEW_LINE> _, serialized_example = reader.read(filename_queue) <NEW_L... | reads and decodes image an label data from tfrecords file
Parameters
----------
tfrecords_filename : string
path to the tfrecords file to decode
Returns
----------
(image, label) : tuple (tensor, tensor)
image is a tensor of shape {height, width, num_channels] containing the image and label is a tensor of sha... | 625941f510dbd63aa1bd31d9 |
def test_key_cert_no_ca2(self): <NEW_LINE> <INDENT> mysqldb = mysql_class.Server( self.name, self.server_id, self.sql_user, self.sql_pass, os_type=self.machine, ssl_client_key=self.ssl_client_key, ssl_client_cert=self.ssl_client_cert) <NEW_LINE> self.assertEqual( (mysqldb.ssl_client_ca, mysqldb.ssl_client_flag), (None,... | Function: test_key_cert_no_ca2
Description: Test with cert and key present, but no ca.
Arguments: | 625941f54e4d5625662d4a05 |
def getTransition(self, command): <NEW_LINE> <INDENT> return self.transitions[command] | Returns the transition taken from that command | 625941f53d592f4c4ed1d693 |
def user_products(self) -> Tuple[List[PcsUserProduct], int]: <NEW_LINE> <INDENT> info = self._baidupcs.user_products() <NEW_LINE> pds = [] <NEW_LINE> for p in info["product_infos"]: <NEW_LINE> <INDENT> if not p.get("product_name"): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> pds.append( PcsUserProduct( name=p["pro... | User's product information | 625941f53c8af77a43ae3ddf |
def intersection(self,*args): <NEW_LINE> <INDENT> ret = self.__class__(self) <NEW_LINE> ret.intersection_update(*args) <NEW_LINE> return ret | Return the intersection of two or more sets as a new set.
(i.e. elements that are common to all of the sets.) | 625941f5baa26c4b54cb174f |
def remove_stopwords(words): <NEW_LINE> <INDENT> stopwords = get_stopwords(stopwords_path="VSM_model/stopwords.txt") <NEW_LINE> new_words = [] <NEW_LINE> for i in words: <NEW_LINE> <INDENT> if i in stopwords or i.isdigit(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_words.append(i) <... | 去掉一些停用词和数字 | 625941f5046cf37aa974d378 |
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> res = 0 <NEW_LINE> if not nums: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> for i in range(len(nums)): <NEW_LINE> <INDENT> if i == res: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if nums[i] > nums[res]: <NEW_LINE> <INDENT> nums[res + 1] = nums[i] <NEW_LIN... | :type nums: List[int]
:rtype: int | 625941f54e4d5625662d4a06 |
def __init__(self, dest, sources, dim=2): <NEW_LINE> <INDENT> self.dim = dim <NEW_LINE> super(InitialGuessDensity, self).__init__(dest, sources) | Parameters
----------
dim : int
number of space dimensions (Default: 2) | 625941f530bbd722463cc401 |
def p_expr_match(p): <NEW_LINE> <INDENT> p[0] = Where("(messages.rowid IN (SELECT docid FROM messages_fts WHERE messages_fts MATCH ?))", [p[1]]) | expr : match_expr | 625941f5c432627299f05282 |
def get_message_classes() -> Iterable[type]: <NEW_LINE> <INDENT> return inspect.getmembers(sys.modules[__name__], lambda obj: inspect.isclass(obj) and issubclass(obj, Message)) | Find and return all classes inheriting from :py:class:`Message` in this module. | 625941f563d6d428bbe44b29 |
def get_interface_vpn_name(self, vpninfo, vpn_name): <NEW_LINE> <INDENT> l3vpn_if = vpninfo.findall("l3vpnIf") <NEW_LINE> for l3vpn_ifinfo in l3vpn_if: <NEW_LINE> <INDENT> for ele in l3vpn_ifinfo: <NEW_LINE> <INDENT> if ele.tag in ['ifName']: <NEW_LINE> <INDENT> if ele.text.lower() == self.vpn_interface.lower(): <NEW_L... | get vpn instance name | 625941f53539df3088e2e983 |
def get_all_rules_for_dg(device_group, device_group_hierarchy_parent, devicegroup_objects): <NEW_LINE> <INDENT> dg_hierarchy = [device_group] <NEW_LINE> current_dg = device_group_hierarchy_parent.get(device_group) <NEW_LINE> while current_dg: <NEW_LINE> <INDENT> dg_hierarchy.append(current_dg) <NEW_LINE> current_dg = d... | Per https://docs.paloaltonetworks.com/panorama/9-1/panorama-admin/panorama-overview/centralized-firewall-configuration-and-update-management/device-groups/device-group-policies
The order is: pre-rules top-down, local rules, then post-rules bottom up.
:param device_group: Device Group to get rules for
:param device_gro... | 625941f5a05bb46b383ece53 |
def ParseLogs(logs): <NEW_LINE> <INDENT> return [ParseLogEntry(line) for line in logs.split('\n') if line] | Parses a str containing newline separated log entries.
Parses a series of log entries in the form LOG <level> <timestamp> <message>
where the level is in the range [0, 4]. Null characters in the entry are
replaced by newlines.
Args:
logs: A string containing the log entries.
Returns:
A list of (timestamp, level... | 625941f597e22403b379d5d4 |
def value(v): <NEW_LINE> <INDENT> return lambda: v | Creates a function that returns the given value, and takes no args.
Args:
v: The value to return.
Returns:
The function that returns the provided value. | 625941f582261d6c526abae1 |
def get_page(self): <NEW_LINE> <INDENT> params = (self.query, self.__c_page) <NEW_LINE> post = self.__post % (params) <NEW_LINE> parser = etree.HTMLParser(recover=True) <NEW_LINE> return etree.parse(self.__dom + post, parser=parser) | return documents tree | 625941f52ae34c7f2600d768 |
def get_center(threshold_image): <NEW_LINE> <INDENT> height = threshold_image.shape[0] <NEW_LINE> width = threshold_image.shape[1] <NEW_LINE> contours, hierarchy = cv2.findContours(threshold_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) <NEW_LINE> penumbra_contour = None <NEW_LINE> max_area = 0 <NEW_LINE> for cont... | Selects the largest detected blob within an image,
returns the center x and y coordinates as a tuple, and the radius
of the blob.
:param threshold_image: An OpenCV image with thresholding applied
:returns: The coordinates of the center and radius of the largest blob | 625941f55166f23b2e1a5791 |
def __init__(self, input_size, embed_size, horizon, context_size, quantiles): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.embed_size = embed_size <NEW_LINE> self.horizon = horizon <NEW_LINE> self.context_size = context_size <NEW_LINE> self.quantiles = quantiles <NEW_LI... | Init Decoder
:param input_size (int): size of data received from Encoder (h_t)
:param embed_size (int): size of exogenous covariates (x)
:param horizon (int): number of predictions (K)
:param context_size (int): size of contextual output (c_t)
:param quantiles (list[int]): list of requested quantiles for regression ([q... | 625941f532920d7e50b2880d |
def _repr_(self): <NEW_LINE> <INDENT> s = "Intersection of the following objects:\n" <NEW_LINE> s += '\n'.join(map(str, self._objets)) <NEW_LINE> return s | Retourne la représentation de l'objet en chaîne de caractères.
EXAMPLES::
sage: from slabbe import DiscretePlane, Intersection
sage: p = DiscretePlane([1,3,7], 11)
sage: q = DiscretePlane([1,3,5], 9)
sage: Intersection((p,q))
Intersection of the following objects:
Set of points x in ZZ^3 satis... | 625941f5167d2b6e312191cc |
def get_contact_surveys_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals... | Get Contact Surveys
Get a list of all surveys for a given contact.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = ... | 625941f56fb2d068a760f6df |
def fit(self,datax,datay,testx=None,testy=None): <NEW_LINE> <INDENT> datay = datay.reshape(-1,1) <NEW_LINE> N = len(datay) <NEW_LINE> datax = datax.reshape(N,-1) <NEW_LINE> D = datax.shape[1] <NEW_LINE> self.w = np.random.random((1,D)) <NEW_LINE> pass | :datax: donnees de train
:datay: label de train
:testx: donnees de test
:testy: label de test | 625941f5711fe17d82542994 |
def send_news(self, fakeid, msgid): <NEW_LINE> <INDENT> url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response' <NEW_LINE> payload = { 'lang': 'zh_CN', 'f': 'json', 'tofakeid': fakeid, 'type': 10, 'token': self.__token, 'appmsgid': msgid, 'app_id': msgid, 'error': 'false', 'ajax': 1, 'random': random.random... | 向指定用户发送图文消息 (必须从图文库里选取消息ID传入)
:param fakeid: 用户的 UID (即 fakeid)
:param msgid: 图文消息 ID
:raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据
:raises ValueError: 参数出错, 具体内容有 ``fake id not exist`` 及 ``message id not exist`` | 625941f5009cb60464c639e4 |
def checkUnsavedLine(self, line)->bool: <NEW_LINE> <INDENT> if not isinstance(line,Line): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> flag = QtWidgets.QMessageBox.question(self, "提示", f"是否保存对线路[{line.name}]的修改?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel) <NEW_LINE> if flag ... | 询问是否保存,返回是否要返回原来的位置。
i.e. 返回True iff 选择Cancel或直接关闭。 | 625941f560cbc95b062c6b7b |
def _log_stream_request_create(self, encryption_time, sent_message, sending_size, stream_id, message): <NEW_LINE> <INDENT> monitor_tag = MonitorTags.CP_ECU_ENCRYPTED_REQ_MESSAGE <NEW_LINE> ecu_id = self.authento._ecu_id <NEW_LINE> cur_time = self.sim_env.now + encryption_time <NEW_LINE> asc_id = self.authento.sec_id <N... | logs the monitor input at the end of the stream request message creation
Input: encryption_time float time it takes to encrypt the stream request
sent_message object message to be sent clear
sending_size float size of the message that is to be sent
stream_id integ... | 625941f5097d151d1a22348d |
def get_attribute(self, attr: str) -> StateflowFuture: <NEW_LINE> <INDENT> payload = {"attribute": attr} <NEW_LINE> event_id: str = str(uuid.uuid4()) <NEW_LINE> invoke_method_event = Event( event_id, self._fun_addr, EventType.Request.GetState, payload ) <NEW_LINE> return self._client.send(invoke_method_event) | Gets an attribute of this actor/stateful function.
A GetState request event is send to the runtime.
:param attr: the attribute to request. This attribute is part of the class 'state'.
:return: a stateflow future. | 625941f5091ae3566866758b |
def minHP(pokemon1, pokemon2): <NEW_LINE> <INDENT> return pokemon1.HP <= pokemon2.HP | compares HP of the two pokemon objects and returns True if the first pokemon
has less HP than the second pokemon else returns False
:param pokemon1:
:param pokemon2:
:return: | 625941f58e05c05ec3eea9b2 |
def merge_sort(sort_list): <NEW_LINE> <INDENT> if len(sort_list) < 2: <NEW_LINE> <INDENT> return sort_list <NEW_LINE> <DEDENT> left = sort_list[0: len(sort_list) // 2] <NEW_LINE> right = sort_list[len(sort_list) // 2:] <NEW_LINE> return merge(merge_sort(left), merge_sort(right)) | 归并排序
:param sort_list:
:return: | 625941f57047854f462a1a3a |
def create_snapshot(self, context, snapshot, share_server=None): <NEW_LINE> <INDENT> volume_name = self._get_volume_name(context, snapshot['share']) <NEW_LINE> snapshot_name = snapshot['name'] <NEW_LINE> try: <NEW_LINE> <INDENT> self._maprfs_util.create_snapshot(snapshot_name, volume_name) <NEW_LINE> return {'provider_... | Creates a snapshot. | 625941f50a50d4780f6674cf |
def __handle_input(self, key_event: keyboard.KeyboardEvent): <NEW_LINE> <INDENT> if key_event.name in ['w', 'up']: <NEW_LINE> <INDENT> self.__game_running = self.__game.up() <NEW_LINE> <DEDENT> elif key_event.name in ['a', 'left']: <NEW_LINE> <INDENT> self.__game_running = self.__game.left() <NEW_LINE> <DEDENT> elif ke... | Manages the keyboard controls for the game
WASD or arrow keys can be used for control, escape to end the game
:param key_event latest key press by the user | 625941f556ac1b37e62647fa |
def get_motd(): <NEW_LINE> <INDENT> return choice(motds) | Retrieve a random MOTD. | 625941f5090684286d50f328 |
def test_snapshot_revert(self): <NEW_LINE> <INDENT> raise SkipTest | available on base hypervisor | 625941f5435de62698dfe285 |
def data_file_paths_for_folders(folders): <NEW_LINE> <INDENT> filepaths = [] <NEW_LINE> for folder in folders: <NEW_LINE> <INDENT> location = data_path + folder + "/" <NEW_LINE> filepaths.extend([location + filename for filename in os.listdir(location)]) <NEW_LINE> <DEDENT> return filepaths | Takes in a list of strings corresponding to folders containing data files.
Returns a list of filepaths for data files inside said folders. | 625941f5090684286d50f329 |
def __init__(self, family_id, database): <NEW_LINE> <INDENT> self.family_id = family_id <NEW_LINE> self.database = database <NEW_LINE> family_profile.__init__(self, father = None, mother = None, child = None, marriage = None) | Constructor, this contructor assumes the family is already existing in RootsMagic | 625941f5d7e4931a7ee9e558 |
def _optimise(self): <NEW_LINE> <INDENT> if len(self.heuristic_path) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> nodes = set(self.heuristic_path) <NEW_LINE> i = nodes.pop() <NEW_LINE> path = [i] <NEW_LINE> cost = 0 <NEW_LINE> while len(nodes) > 0: <NEW_LINE> <INDENT> best = float('inf') <NEW_LINE> for j in nod... | Cheapest relink.
>>> from tsp_local.test import matrix
>>> TSP.setEdges(matrix)
>>> l = list(range(len(matrix)))
>>> t = Greedy(l)
Force initial solution.
>>> t.heuristic_path = l
>>> t.heuristic_cost = t.pathCost(l)
>>> t._optimise()
>>> t.heuristic_cost < t.pathCost(l)
True
>>> t.heuristic_cost == t.pathCost(t.heur... | 625941f54c3428357757c95b |
def peak_dtype(n_channels=100, n_sum_wv_samples=200, n_widths=11): <NEW_LINE> <INDENT> if n_channels == 1: <NEW_LINE> <INDENT> raise ValueError("Must have more than one channel") <NEW_LINE> <DEDENT> return peak_interval_dtype + [ (('Classification of the peak(let)', 'type'), np.int8), (('Integral across channels [PE]',... | Data type for peaks - ranges across all channels in a detector
Remember to set channel to -1 (todo: make enum) | 625941f55fdd1c0f98dc086e |
def size(self, path): <NEW_LINE> <INDENT> assert self.is_open <NEW_LINE> path = self.check_path(path) <NEW_LINE> return self._session.stat(path).st_size | Get the size of the file.
:param path: The path to operate on.
:return: The size in bytes. | 625941f53317a56b8693a280 |
def minCostClimbingStairs(self, cost): <NEW_LINE> <INDENT> if len(cost) == 1: <NEW_LINE> <INDENT> return cost[0] <NEW_LINE> <DEDENT> t = [None] * len(cost) <NEW_LINE> t[0], t[1] = cost[0], cost[1] <NEW_LINE> for i in range(2, len(cost)): <NEW_LINE> <INDENT> t[i] = min(t[i - 1] + cost[i], t[i - 2] + cost[i]) <NEW_LINE> ... | :type cost: List[int]
:rtype: int | 625941f58a349b6b435e87aa |
def makeReadLocator(cmpH5, refSeq): <NEW_LINE> <INDENT> if not cmpH5.isSorted: raise Exception("CmpH5 is not sorted") <NEW_LINE> refInfo = cmpH5.referenceInfo(refSeq) <NEW_LINE> offStart, offEnd = refInfo.StartRow, refInfo.EndRow <NEW_LINE> if (offEnd - offStart > 0): <NEW_LINE> <INDENT> refAlignIdx = cmpH5.alignmentIn... | Return a function which can be called iteratively to find reads
quickly. | 625941f591f36d47f21acb32 |
def __init__(self, failed_stage, exception, traceback): <NEW_LINE> <INDENT> self.failed_stage = failed_stage <NEW_LINE> self.exception = exception <NEW_LINE> self.traceback = traceback | Construct a RecordedTraceback object.
Args:
failed_stage: The stage that failed during the build.
exception: The raw exception object.
traceback: The full stack trace for the failure, as a string. | 625941f5bf627c535bc13808 |
def _init(): <NEW_LINE> <INDENT> global _done <NEW_LINE> if _done: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> maxima.eval('load("orthopoly");') <NEW_LINE> maxima.eval('orthopoly_returns_intervals:false;') <NEW_LINE> _done = True | Internal function which checks if Maxima has loaded the
"orthopoly" package. All functions using this in this
file should call this function first.
TEST:
The global starts ``False``::
sage: sage.functions.orthogonal_polys._done
False
Then after using one of these functions, it changes::
sage: from sa... | 625941f5cb5e8a47e48b80d7 |
def get_timeInstance(self): <NEW_LINE> <INDENT> t= datetime.time(datetime.now()) <NEW_LINE> t = t.replace(hour = self.time[0],minute = self.time[1], second= self.time[2], microsecond= self.time[3]) <NEW_LINE> return t | @:return an object of type datatime | 625941f521a7993f00bc8334 |
def set_pnt_pos(data,il,lpos): <NEW_LINE> <INDENT> lptn = data.pset[il] <NEW_LINE> data_pos = getattr(lptn,'pos') <NEW_LINE> for jl in range(data.ldim): <NEW_LINE> <INDENT> data_pos[jl] = lpos[jl] | set position of the single point | 625941f5b5575c28eb68e63e |
def load_layer_with_provider(layer_uri, provider, layer_name='tmp'): <NEW_LINE> <INDENT> if provider in RASTER_DRIVERS: <NEW_LINE> <INDENT> return QgsRasterLayer(layer_uri, layer_name, provider) <NEW_LINE> <DEDENT> elif provider in VECTOR_DRIVERS: <NEW_LINE> <INDENT> return QgsVectorLayer(layer_uri, layer_name, provide... | Load a layer with a specific driver.
:param layer_uri: Layer URI that will be used by QGIS to load the layer.
:type layer_uri: basestring
:param provider: Provider name to use.
:type provider: basestring
:param layer_name: Layer name to use. Default to 'tmp'.
:type layer_name: basestring
:return: The layer or None ... | 625941f5d164cc6175783387 |
def process_premise_sets(premises, depth, verbose=False, full_tree=False): <NEW_LINE> <INDENT> if depth > 3: <NEW_LINE> <INDENT> print("Depth "+str(depth)+"\nYou've searched far enough...") <NEW_LINE> return False <NEW_LINE> <DEDENT> all_new_premises = [] <NEW_LINE> for premise in premises: <NEW_LINE> <INDENT> premise,... | Process every premise in premise set
and feed resulting new premises back into system. | 625941f5a8370b7717052ed5 |
def list_zones(permanent=True): <NEW_LINE> <INDENT> cmd = "--list-all-zones" <NEW_LINE> if permanent: <NEW_LINE> <INDENT> cmd += " --permanent" <NEW_LINE> <DEDENT> return __parse_zone(cmd) | List everything added for or enabled in all zones
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_zones | 625941f5711fe17d82542995 |
def save_folder(self, fullpath): <NEW_LINE> <INDENT> list_of_notebooks = self.get_all_notebooks(fullpath) <NEW_LINE> return list_of_notebooks | We will save the notebooks within the paths, and exclude Library links | 625941f58e71fb1e9831ddde |
def p_module_def(p): <NEW_LINE> <INDENT> p[0] = (p[1],p[2],p[4]) | module_def : MODULE ID COLON module_def_list | 625941f5cc0a2c11143dd4ca |
def wrapped_toco_convert(model_flags_str, toco_flags_str, input_data_str, debug_info_str, enable_mlir_converter): <NEW_LINE> <INDENT> return _pywrap_toco_api.TocoConvert( model_flags_str, toco_flags_str, input_data_str, False, debug_info_str, enable_mlir_converter) | Wraps TocoConvert with lazy loader. | 625941f592d797404e3047c5 |
def find_path(graph, visited=None): <NEW_LINE> <INDENT> if len(visited) == graph.size(): <NEW_LINE> <INDENT> return True, visited <NEW_LINE> <DEDENT> for node in graph.adj_list[visited[-1]]: <NEW_LINE> <INDENT> if node not in visited: <NEW_LINE> <INDENT> visited.append(node) <NEW_LINE> if find_path(graph, visited)[0]: ... | The problem comes down to solving the hamiltonian path problem
starting at the starting point.
I'll be using a DFS approach described in here:
https://www.hackerearth.com/practice/algorithms/graphs/hamiltonian-path/
In short, it consists of multiple DFSs starting at the
starting vertex to see if one of the searches get... | 625941f50a50d4780f6674d0 |
def test_setAbsoluteMode_False(self): <NEW_LINE> <INDENT> unit = AxisPosition(1, 2, 3, True, 4) <NEW_LINE> unit.setAbsoluteMode(False) <NEW_LINE> self.assertFalse(unit.absoluteMode, "absoluteMode should be False") | Test the setAbsoluteMode method when passed False. | 625941f5d8ef3951e3243b76 |
def build_tests(self, testdir_name): <NEW_LINE> <INDENT> test_dir = os.path.join(self.teststmpdir, testdir_name) <NEW_LINE> os.chdir(test_dir) <NEW_LINE> testdir_dict = { "": "check", "selftest": "run_tests", "test": "unsafe-check", "samples": "bench" } <NEW_LINE> failed_tests = [] <NEW_LINE> output = build.run_make(te... | build different test builds | 625941f57cff6e4e81117fbe |
def test_region_read(self): <NEW_LINE> <INDENT> client_no_login = APIClient() <NEW_LINE> res = client_no_login.get("/api/region/?limit=1000") <NEW_LINE> self.assertEqual(len(res.data["results"]), models.Region.objects.count()) <NEW_LINE> for region_tuple in models.Region.REGION_TYPE: <NEW_LINE> <INDENT> region_code, re... | Test region read
===================================
Note:
1. No create/delete operation by admin user is tested here | 625941f5ec188e330fd5adca |
def KL_max_disagreement(committee, X, **predict_proba_kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> p_vote = committee.vote_proba(X, **predict_proba_kwargs) <NEW_LINE> <DEDENT> except NotFittedError: <NEW_LINE> <INDENT> return np.zeros(shape=(X.shape[0],)) <NEW_LINE> <DEDENT> p_consensus = np.mean(p_vote, axis=... | Calculates the max disagreement for the Committee. First it computes the class probabilties
of X for each learner in the Committee, then calculates the consensus probability
distribution by averaging the individual class probabilities for each learner. Then each
learner's class probabilities are compared to the consens... | 625941f521a7993f00bc8335 |
def to_ntuple(val: Union[int, Iterable[int]], n: int) -> Tuple[int, ...]: <NEW_LINE> <INDENT> if isinstance(val, Iterable): <NEW_LINE> <INDENT> out = tuple(val) <NEW_LINE> if len(out) == n: <NEW_LINE> <INDENT> return out <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(f"Cannot cast tuple of length {len(o... | Casts to a tuple with length 'n'. Useful for automatically computing the
padding and stride for convolutions, where users may only provide an integer.
Args:
val: (Union[int, Iterable[int]]) Value to cast into a tuple.
n: (int) Desired length of the tuple
Returns:
(Tuple[int, ...]) Tuple of length 'n' | 625941f5d6c5a10208144688 |
@click.command() <NEW_LINE> @click.argument('identifier') <NEW_LINE> @click.option('--no-vs', is_flag=True, help="Hide virtual server listing") <NEW_LINE> @click.option('--no-hardware', is_flag=True, help="Hide hardware listing") <NEW_LINE> @environment.pass_env <NEW_LINE> def cli(env, identifier, no_vs, no_hardware): ... | Get subnet details. | 625941f5b830903b967e9f3c |
def update(self, *inputs): <NEW_LINE> <INDENT> if len(inputs) != 2: <NEW_LINE> <INDENT> raise ValueError('SSIM need 2 inputs (y_pred, y), but got {}'.format(len(inputs))) <NEW_LINE> <DEDENT> y_pred = self._convert_data(inputs[0]) <NEW_LINE> y = self._convert_data(inputs[1]) <NEW_LINE> res = self.compute_sr_metric(y_pre... | Update the metric. | 625941f5bd1bec0571d90c68 |
def __init__(self, number_of_cheeses, number_of_stools): <NEW_LINE> <INDENT> self.model = TOAHModel(number_of_stools) <NEW_LINE> self.model.fill_first_stool(number_of_cheeses) <NEW_LINE> self.model_complete = TOAHModel(number_of_stools) <NEW_LINE> self.model_complete._stools[number_of_stools-1] = self.model._stools[0][... | Initialize a new ConsoleController self.
@param ConsoleController self:
@param int number_of_cheeses:
@param int number_of_stools:
@rtype: None | 625941f530c21e258bdfaadd |
def is_horizontal(state, pos): <NEW_LINE> <INDENT> return state[1] & (1 << pos) | Check whether the posth cell is occupied by a horizontal piece. | 625941f58e7ae83300e4b608 |
def p_structent_3(t): <NEW_LINE> <INDENT> log.debug("p_structent_3: %s", list(t)) <NEW_LINE> t[0] = {"name": t[3], "type": t[1], "note": "pointer"} | structent : ID TIMES ID SEMI
| typeid TIMES ID SEMI | 625941f5a8ecb033257d3703 |
def GetName(self): <NEW_LINE> <INDENT> return self.name | An accessor for the Role name attribute.
@returns: string form of the name | 625941f5d18da76e23532b17 |
def __init__(self, arg1=""): <NEW_LINE> <INDENT> self.arg1 = arg1 | If there are decorator arguments, the function
to be decorated is not passed to the constructor! | 625941f5004d5f362079a967 |
def test_searchengine_location_with_hierarchy(transactional_db): <NEW_LINE> <INDENT> def filter_locations(value=None): <NEW_LINE> <INDENT> filters = { 'django_ct': 'targeting.targetvalue', 'category': dimensions.g_location } <NEW_LINE> if value: <NEW_LINE> <INDENT> filters['value'] = value <NEW_LINE> <DEDENT> return Se... | Test if search results for location are limited to given dimension
if query contains it | 625941f5cdde0d52a9e53672 |
@click.group() <NEW_LINE> def cli(): <NEW_LINE> <INDENT> pass | Tools for working with (assignment) solutions | 625941f5e64d504609d74e78 |
@contextlib.contextmanager <NEW_LINE> def adb_connect(unittest, serial): <NEW_LINE> <INDENT> output = subprocess.check_output(['adb', 'connect', serial]) <NEW_LINE> unittest.assertEqual(output.strip(), 'connected to {}'.format(serial)) <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <I... | Context manager for an ADB connection.
This automatically disconnects when done with the connection. | 625941f523e79379d52eeb94 |
def get_sha512(self): <NEW_LINE> <INDENT> if not self._sha512: self.calc_hashes() <NEW_LINE> return self._sha512 | Get SHA512.
@return: SHA512. | 625941f563b5f9789fde771f |
def test_cancelQueueAfterSynchronousGet(self): <NEW_LINE> <INDENT> def _failOnErrback(_): <NEW_LINE> <INDENT> self.fail("Unexpected errback call!") <NEW_LINE> <DEDENT> queue = DeferredPriorityQueue() <NEW_LINE> d = queue.get() <NEW_LINE> d.addErrback(_failOnErrback) <NEW_LINE> queue.put(obj=None, priority=0) <NEW_LINE>... | When canceling a L{Deferred} from a L{DeferredQueue} that already has
a result, the cancel should have no effect. | 625941f5498bea3a759ba0e6 |
def get_skip_models(file_size, SKIP_PER_SIZE=5_000_000): <NEW_LINE> <INDENT> return int(file_size / SKIP_PER_SIZE) | Return the number of models to be skipped after each model is read
based on the file_size given in bytes. For small files no models are skipped and the
return value is 0.
:param SKIP_PER_SIZE:
Skips file_size/SKIP_PER_SIZE number of models if the file size in bytes
is greater than SKIP_PER_SIZE.
The smalle... | 625941f56fb2d068a760f6e0 |
def remove_names(self, name: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self._names_index[name] <NEW_LINE> return True <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self._names_multi_index[name] <NEW_LINE> return True <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <I... | Removes all :class:`Name` instances associated with name `name`.
:return: True if a matching name was removed. | 625941f529b78933be1e5cdd |
def smooth2D(data, sigma_x=10, len_x=50, sigma_y=10, len_y=50, fkt=gaussWindow): <NEW_LINE> <INDENT> if type(data) != np.ndarray: <NEW_LINE> <INDENT> error_msg = "ERROR: input needs to by a 2D numpy array. " + "Data type is {}".format(type(data)) <NEW_LINE> raise Exception(error_msg) <NEW_LINE> <DEDE... | This function smoothes the noisy data of a 2D array.
Parameters:
-----------
data - numpy.ndaray (2D)
original (noisy) data - needs to be a 2D array
sigma_x - float (optinal)
standard deviation of the window function 'fkt' in x-direction
default: 10 bins
len_x - int... | 625941f5d58c6744b4258295 |
def load(self,filename): <NEW_LINE> <INDENT> save = pickle.load( open( filename, "rb" ) ) <NEW_LINE> self.ys = save["ys"] <NEW_LINE> self.categories = save["categories"] <NEW_LINE> self.headers = save["headers"] | load class from file | 625941f556b00c62f0f14c96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.