code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def will_remain_enabled_for(self, time=60): <NEW_LINE> <INDENT> warnings.warn('will_remain_enabled_for() is deprecated: ' 'use is_enabled instead.', DeprecationWarning, stacklevel=2) <NEW_LINE> config = self._get_status() <NEW_LINE> status = config.summary_status() <NEW_LINE> if status in (IsEnabledResponse.DEFAULT, Is... | Returns whether a capability will remain enabled.
DEPRECATED: this method was never fully implemented and is considered
deprecated. Use `is_enabled()` instead.
Args:
time: Number of seconds in the future to look when checking for scheduled
downtime.
Returns:
`True` if there is no scheduled downtime for the... | 625941cdd486a94d0b98e247 |
def add_incident(api_url=None, api_token=None, **kwargs): <NEW_LINE> <INDENT> test = _build_args('incidents', 'add', **kwargs) <NEW_LINE> if not test['res']: <NEW_LINE> <INDENT> return test <NEW_LINE> <DEDENT> args= test['data'] <NEW_LINE> status = args['status'] <NEW_LINE> _check_incident_status(status) <NEW_LINE> if ... | Create a new incident.
:param name: MANDATORY
:param message: MANDATORY
:param status: MANDATORY
:param visible: MANDATORY
:param component_id:
:param component_status:
:param notify:
:param api_url: The Cachet URL.
:param api_token: The Cachet Token.
:return: data.
CLI Example:
.. code-block:: bash
salt '*' c... | 625941cd07f4c71912b11584 |
def __setup_calendar(self): <NEW_LINE> <INDENT> obj = model.Calendar( calendar_name='test_calendar', calendar_contact='test@example.com', calendar_description='This is a test calendar', calendar_editor_group='fi-apprentice', calendar_admin_group='infrastructure-main2') <NEW_LINE> obj.save(self.session) <NEW_LINE> self.... | Set up basic calendar information. | 625941cd56b00c62f0f1475b |
def feed(self): <NEW_LINE> <INDENT> if self.pHungry: <NEW_LINE> <INDENT> self.pHungry = False <NEW_LINE> self.pWeight += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Your pet is not hungry!') | Feeds the pet. The pet will stop being hungry and gain weight. | 625941cd956e5f7376d70f70 |
def checkRnf(): <NEW_LINE> <INDENT> global credits, shouldBeReinforced, nReinforcers <NEW_LINE> if shouldBeReinforced: <NEW_LINE> <INDENT> nReinforcers += 1 <NEW_LINE> for frameN in range(30): <NEW_LINE> <INDENT> credits_title_txt.draw() <NEW_LINE> num_credits_txt.draw() <NEW_LINE> coin.setOpacity(1) <NEW_LINE> credits... | Once a response has been recorded,
this function checks whether a response is reinforced
and gives the reward | 625941cd711fe17d8254246e |
def delete(self, key, version=None): <NEW_LINE> <INDENT> packed_val = super(RedisHerdCache, self).get(key, None, version) <NEW_LINE> if packed_val is not None: <NEW_LINE> <INDENT> value, refresh = self._unpack_value(packed_val) <NEW_LINE> self.set(key, value, 0, version) | Remove a key from the cache. | 625941cd0c0af96317bb82ea |
def update(self,cls,dic): <NEW_LINE> <INDENT> if (verbose): print(self.pre,"update :",dic) <NEW_LINE> super().update(cls,dic) <NEW_LINE> _id=dic.pop("_id") <NEW_LINE> dic["classname"]=cls.__name__ <NEW_LINE> result=self.collection.replace_one({"_id":_id},dic) <NEW_LINE> if (result.matched_count<1): <NEW_LINE> <INDENT> ... | Substitute element from list with same "_id"
| 625941cd50485f2cf553ce9c |
def interpolate_slerp( self, in_lat, in_lon ): <NEW_LINE> <INDENT> in_lat = norm_lat(in_lat) <NEW_LINE> in_lon = norm_lon(in_lon) <NEW_LINE> lat_ind = in_lat // self.step_la <NEW_LINE> if in_lat == 90: <NEW_LINE> <INDENT> lat_ind -= 1 <NEW_LINE> <DEDENT> lon_ind = in_lon // self.step_lo <NEW_LINE> if in_lon == 360: <NE... | Slerp interpolation method of wind at specified position.
Uses bilinear aproximation between the vectors.
Proportion is 'slerp' | 625941cdd486a94d0b98e248 |
def levelOrder(root: TreeNode) -> list: <NEW_LINE> <INDENT> def fun(stack, order=0): <NEW_LINE> <INDENT> val_list = [] <NEW_LINE> new_stack = [] <NEW_LINE> while(stack): <NEW_LINE> <INDENT> node = stack.pop() <NEW_LINE> if not node: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> val_list.append(node.val) <NEW_LINE> i... | 广度遍历,与第102相似,但是:
1、需要将list变为stack,因为之字形正好符合后入先出。
2、注意追加左右子树的顺序,先左后右和先右后左是交替进行的。 | 625941cd63f4b57ef000121c |
def find_packages(base): <NEW_LINE> <INDENT> ret = [base] <NEW_LINE> for path in os.listdir(base): <NEW_LINE> <INDENT> if path.startswith('.'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> full_path = os.path.join(base, path) <NEW_LINE> if os.path.isdir(full_path): <NEW_LINE> <INDENT> ret += find_packages(full_path... | Helper function to find subpackages in base.
:param base: Directory holding the main package.
Returns a list of subpackages suitable for setup() packages keyword.
base is already included in the returned list. | 625941cd23e79379d52ee666 |
def find_results(self, filter): <NEW_LINE> <INDENT> selection = self.results <NEW_LINE> for k, v in filter.items(): <NEW_LINE> <INDENT> selection = selection[selection[k] == v] <NEW_LINE> <DEDENT> return list(selection.T.to_dict().values()) | Get a list of all results associated with *filter*. The order is
undefined. | 625941cdff9c53063f47c2f6 |
def expr(self): <NEW_LINE> <INDENT> self.current_token = self.get_next_token() <NEW_LINE> result = self.term() <NEW_LINE> while self.current_token.type in (PLUS, MINUS): <NEW_LINE> <INDENT> if self.current_token.type == PLUS: <NEW_LINE> <INDENT> self.eat(PLUS) <NEW_LINE> result += self.term() <NEW_LINE> <DEDENT> else: ... | expr: term((PLUS|MINUS)term)* | 625941cd21bff66bcd684a56 |
def test_enters_values_if_no_config_exists( config_mock, defaults_options, select_repobee_section ): <NEW_LINE> <INDENT> with patch( "builtins.input", side_effect=list(defaults_options.values()) ), patch("pathlib.Path.exists", autospec=True, return_value=False): <NEW_LINE> <INDENT> configwizard.callback(None, plug.Conf... | If no config mock can be found (ensured by the nothing_exists fixture),
then the config wizard chould proceed without prompting for a continue. | 625941cd3c8af77a43ae38a3 |
def button_accept_candidatures(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> return super(ext_selection_committee, self).button_accept_candidatures(cr, uid, ids, context=context) | ==========================
button_accept_candidatures
==========================
This method calls the candidature workflow for each candidature_id in
order to update their state
:rparam: True
:rtype: boolean
:raise: Error if all candidatures are not in suggested state | 625941cda8ecb033257d31cf |
def convert_csv(fname): <NEW_LINE> <INDENT> if (not is_excel_file(fname)): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> run_soffice() <NEW_LINE> context = connect(Socket(HOST, PORT)) <NEW_LINE> component = get_component(fname, context) <NEW_LINE> r = [] <NEW_LINE> controller = component.getCurrentController() <NEW... | Convert all of the sheets in a given Excel spreadsheet to CSV
files. Also get the name of the currently active sheet.
@param fname (str) The name of the Excel file.
@return (list) A list where the 1st element is the name of the
currently active sheet ("NO_ACTIVE_SHEET" if no sheets are active)
and the rest of the ele... | 625941cd85dfad0860c3af5d |
def test_ChainSet_relative_index(self): <NEW_LINE> <INDENT> result = self.chains.get("#1") <NEW_LINE> self.assertEquals(result, self.molecules[0].chains[0:1]+ self.molecules[1].chains[0:1]+ self.molecules[2].chains[0:1]) <NEW_LINE> self.assertEquals(result.stringRepr,"(hsg1:/+/2plv:/+/1gyc:\\s\\#1)") | test relative index used in chains.get(relative_index) | 625941cda934411ee3751796 |
def t_LITERAL_CHAR(t): <NEW_LINE> <INDENT> t.value = t.value[1].encode() <NEW_LINE> return t | '.?' | 625941cdcad5886f8bd270dc |
def time_stamp(): <NEW_LINE> <INDENT> tmptz = time.timezone <NEW_LINE> sign_str = '+' <NEW_LINE> if tmptz > 0: <NEW_LINE> <INDENT> sign_str = '-' <NEW_LINE> <DEDENT> tmptz_hours = int(tmptz / 3600) <NEW_LINE> return str("%s%s%02d:%02d" % (time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime()), sign_str, abs(tmptz_hours),... | Return ISO-8601 compliant date/time format
:return: time information | 625941cdfff4ab517eb2f53f |
def _is_gles_version(version): <NEW_LINE> <INDENT> assert not isinstance(version, bytes), '{}({})'.format(version, type(version)) <NEW_LINE> if isinstance(version, str): <NEW_LINE> <INDENT> if version.endswith('es'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if version.endswith('compatibility'): <NEW_L... | Return True if version is es, otherwsie false. | 625941cd91af0d3eaac9bb1b |
def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer): <NEW_LINE> <INDENT> label_ids = list(example.label) <NEW_LINE> tokens_a = tokenizer.tokenize(example.text_a) <NEW_LINE> tokens_b = None <NEW_LINE> if example.text_b: <NEW_LINE> <INDENT> tokens_b = tokenizer.tokenize(example.text_b) <N... | 将一个样本进行分析,然后将字转化为id, 标签转化为id,然后结构化到InputFeatures对象中
:param ex_index: index
:param example: 一个样本
:param label_list: 标签列表
:param max_seq_length:
:param tokenizer:
:param output_dir
:param mode:
:return: | 625941cdbd1bec0571d90732 |
def _(): <NEW_LINE> <INDENT> file_path = 'frontend/index.html' <NEW_LINE> return helpers.request(file_path) | Handle '/' endpoint. | 625941cd627d3e7fe0d68f52 |
def get_notify_popup(self): <NEW_LINE> <INDENT> return self.notify_popup | Get notify popup status (enable/disable) | 625941cd8c0ade5d55d3eabd |
def get_fourier_x_axis(): <NEW_LINE> <INDENT> global fourier_x_axis <NEW_LINE> n = data_quantity <NEW_LINE> t = interval <NEW_LINE> fourier_x_axis = np.linspace(0.0, 1.0 / (2.0 * t), n // 2).tolist() | Get fourier x axis based on size and interval.
:param
:return: void | 625941cd60cbc95b062c6646 |
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/KGS/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "KGS") <NEW_LINE> <DEDENT> return os.p... | Return the default location of the kgs data directory | 625941cd32920d7e50b282d2 |
def get_node_instances(nodelist, instances): <NEW_LINE> <INDENT> return _scan_nodes(instances, nodelist) | Find the nodes of a given instance.
:param instances: A class Type, or typle of types to find.
:param nodelist: The Template object, or nodelist to scan.
:returns: A list of Node objects which inherit from the list of given `instances` to find.
:rtype: list | 625941cd4428ac0f6e5ba8f5 |
def cal_Hcost(self,curr): <NEW_LINE> <INDENT> xVal = abs(curr.r_loc - self.end.r_loc) <NEW_LINE> yVal = abs(curr.c_loc - self.end.c_loc) <NEW_LINE> if xVal > yVal: <NEW_LINE> <INDENT> H = 14 * yVal + 10 * (xVal - yVal) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> H = 14 * xVal + 10 * (yVal - xVal) <NEW_LINE> <DEDENT> ... | Computes cost of moving from current node to destination. Uses diagonal distance formula
:param curr: current node
:return: H-cost | 625941cd2eb69b55b151c9b1 |
def check(self, in_d, out_d, force): <NEW_LINE> <INDENT> in_d = in_d.rstrip('/') <NEW_LINE> out_d = out_d.rstrip('/') <NEW_LINE> if not os.path.exists(in_d): <NEW_LINE> <INDENT> print("\033[91m[ERROR]\033[0m Input path not found :(") <NEW_LINE> return <NEW_LINE> <DEDENT> if os.path.exists(out_d): <NEW_LINE> <INDENT> if... | To be called from Main
NOTE: May be unnecessary at this point
NOTE: v1.0.1 '/' is now allowed at the end of directory paths | 625941cd4e696a04525c954e |
def test_initial_magnetic_moments(fixture_code, generate_structure): <NEW_LINE> <INDENT> code = fixture_code('quantumespresso.pw') <NEW_LINE> structure = generate_structure('silicon') <NEW_LINE> initial_magnetic_moments = {'Si': 1.0} <NEW_LINE> builder = PwBaseWorkChain.get_builder_from_protocol( code, structure, initi... | Test ``PwBaseWorkChain.get_builder_from_protocol`` with ``initial_magnetic_moments`` keyword. | 625941cd091ae35668667061 |
def test_reset_long_email(self): <NEW_LINE> <INDENT> long_mail = ('1' * 255) + '@freesound.org' <NEW_LINE> user = User.objects.create_user("testuser", email="testuser@freesound.org") <NEW_LINE> user.set_password('12345') <NEW_LINE> user.save() <NEW_LINE> self.client.force_login(user) <NEW_LINE> resp = self.client.post(... | Check reset email with a long email address | 625941cd435de62698dfdd4f |
def get_multi( namespace: NamespaceType, sub_namespace: str | None, obj_ids: List[str] ) -> Dict[str, Any]: <NEW_LINE> <INDENT> result_dict: Dict[str, Any] = {} <NEW_LINE> if len(obj_ids) == 0: <NEW_LINE> <INDENT> return result_dict <NEW_LINE> <DEDENT> if namespace not in DESERIALIZATION_FUNCTIONS: <NEW_LINE> <INDENT> ... | Get a dictionary of the {id, value} pairs from the memory cache.
Args:
namespace: str. The namespace under which the values associated with
these object ids lie. The namespace determines how the objects are
decoded from their JSON-encoded string. Use CACHE_NAMESPACE_DEFAULT
as the namespace... | 625941cd379a373c97cfac47 |
def initialize_export_vars(self): <NEW_LINE> <INDENT> self.feed = 0 <NEW_LINE> self.speed = 0 <NEW_LINE> self.tool_nr = 1 <NEW_LINE> self.comment = "" <NEW_LINE> self.abs_export = self.vars.General["abs_export"] <NEW_LINE> self.Pe = Point(g.config.vars.Plane_Coordinates['axis1_start_end'], g.config.vars.Plane_Coordinat... | This function is called to initialize all export variables. This will
be done directly before the export starts. | 625941cd8e7ae83300e4b0cf |
def detect(data, encoding = None, language = None): <NEW_LINE> <INDENT> if not isinstance(data, (io.BytesIO, io.BufferedReader)): <NEW_LINE> <INDENT> raise TypeError("Needs to be a buffered file object.") <NEW_LINE> <DEDENT> tried_encodings = set() <NEW_LINE> test_data = data.read(8) <NEW_LINE> data.seek(0) <NEW_LINE> ... | Tries to detect encoding for specified 'data'. Will return a tuple (encoding, confidence).
Confidence may be None, which means the encoding was detected from provided language or
encoding hint, or it stumbled over a unicode BOM. | 625941cdec188e330fd5a8a2 |
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers,weights_matrix=0, drop_prob=0.5, train_on_gpu =False,pretrained=False): <NEW_LINE> <INDENT> super(SentimentRNN, self).__init__() <NEW_LINE> self.train_on_gpu =train_on_gpu <NEW_LINE> self.output_size = output_size <NEW_LINE> self.n_layers ... | Initialize the model by setting up the layers. | 625941cd7047854f462a150d |
def get_high_impact_association_graph_container(self, id, graph_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_high_impact_association_graph_container_with_http_info(id, graph_id, **kwargs) | Get High Impact Topic Associations Graph # noqa: E501
Get the High Impact Topic Associations graph data # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_high_impact_association_graph_container(id, graph_id, as... | 625941cdcc40096d61595a53 |
def save_to_database(self, session, table, initializer=None, mapdict=None, auto_commit=True): <NEW_LINE> <INDENT> save_sheet(self, session=session, table=table, initializer=initializer, mapdict=mapdict, auto_commit=auto_commit) | Save data in sheet to database table
:param session: database session
:param table: a database table
:param initializer: a initialization functions for your table
:param mapdict: custom map dictionary for your data columns
:param auto_commit: by default, data is auto committed. | 625941cde5267d203edcdda0 |
def list( 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.metadata['url'] <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize... | Lists the enrollment accounts the caller has access to.
: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 it... | 625941cd15baa723493c4078 |
def p_positive_empty(t): <NEW_LINE> <INDENT> t[0] = ast.Atom(table=t[1], args=[]) | positive : IDENT OPAR CPAR | 625941cdbe7bc26dc91cd703 |
def load_model(code_length): <NEW_LINE> <INDENT> model = AlexNet(code_length) <NEW_LINE> state_dict = load_state_dict_from_url('https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth') <NEW_LINE> model.load_state_dict(state_dict, strict=False) <NEW_LINE> return model | Load CNN model.
Args
code_length (int): Hashing code length.
Returns
model (torch.nn.Module): CNN model. | 625941cd293b9510aa2c339a |
def _set_driver(self) -> None: <NEW_LINE> <INDENT> chrome_options = Options() <NEW_LINE> chrome_options.add_argument("--headless") <NEW_LINE> self.driver = webdriver.Chrome(options=chrome_options) | Set inst var to a new driver | 625941cd10dbd63aa1bd2ca7 |
def format(self, record): <NEW_LINE> <INDENT> if sys.version_info < (2, 7): <NEW_LINE> <INDENT> s = logging.Formatter.format(self, record) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = super(IndentMultilineLogFormatter, self).format(record) <NEW_LINE> <DEDENT> return s.rstrip("\n").replace("\n", "\n ") | Formats the given `LogRecord` by indenting all newlines.
Args:
record (LogRecord): The `LogRecord` to format.
Returns:
str: The formatted message with all newlines indented. | 625941cd9c8ee82313fbb879 |
def make_immutable(item): <NEW_LINE> <INDENT> if isinstance(item, list) or isinstance(item, tuple): <NEW_LINE> <INDENT> result = LockedTuple(item) <NEW_LINE> <DEDENT> elif isinstance(item, dict): <NEW_LINE> <INDENT> result = ReadOnlyDict(item) <NEW_LINE> result.lock() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resul... | Recursively lock all contents of a ReadOnlyDict.
Any children of supported types will also be locked.
Currently supported:: list, tuple, dict.
and we locked r on a shallow level, we could still r['b'].append() or
r['c']['key2'] = 'value2'. So to avoid that, we need to recursively
lock r via make_immutable.
Args:
... | 625941cd3eb6a72ae02ec5e0 |
def mark_label_leaves(tree): <NEW_LINE> <INDENT> if not isinstance(tree, dict): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for node_label in tree: <NEW_LINE> <INDENT> node = tree[node_label] <NEW_LINE> if node_label == 'label': <NEW_LINE> <INDENT> node = _(node) <NEW_LINE> <DEDENT> if isinstance(node, dict): <NEW_L... | Mutates a given nested dictionary ``tree`` to replace all leaves with
the label "label" with versions wrapped with ``ugettext_lazy``. | 625941cd26238365f5f0ef71 |
def main(): <NEW_LINE> <INDENT> queue = asyncio.Queue() <NEW_LINE> loop = asyncio.get_event_loop() <NEW_LINE> coros = [publish(queue, i) for i in range(1, 4)] <NEW_LINE> try: <NEW_LINE> <INDENT> [loop.create_task(coro) for coro in coros] <NEW_LINE> loop.create_task(consume(queue)) <NEW_LINE> loop.run_forever() <NEW_LIN... | 多个生产者 | 625941cdd8ef3951e3243641 |
def __call__(self): <NEW_LINE> <INDENT> return self.template() | Call our beautiful template
| 625941cd1b99ca400220abb5 |
def check_password(self, request_password): <NEW_LINE> <INDENT> password, salt = self.get('password').split(':') <NEW_LINE> return password == hashlib.sha256(salt.encode() + request_password.encode()).hexdigest() | validates password against the database
----------
arg1 : request_password
password passed in on the request
Returns
-------
boolean
Returns the result of the password check | 625941cd45492302aab5e3c6 |
def step(self): <NEW_LINE> <INDENT> if self.max_grad_norm > 0: <NEW_LINE> <INDENT> params = itertools.chain.from_iterable([group['params'] for group in self.optimizer.param_groups]) <NEW_LINE> _ = nn.utils.clip_grad_norm_(params, self.max_grad_norm) <NEW_LINE> <DEDENT> self.optimizer.step() | Step with the inner optimizer | 625941cdbf627c535bc132d2 |
def parse_raw_data(raw_data): <NEW_LINE> <INDENT> documents = {} <NEW_LINE> raw_documents = re.split(r'</DOC>\s*<DOC>', raw_data) <NEW_LINE> for raw_doc in raw_documents: <NEW_LINE> <INDENT> doc_id = re.search(r'<DOCNO>\s([\w+-]+)\s</DOCNO>', raw_doc).group(1) <NEW_LINE> raw_doc = re.sub(r'<PARENT>\s([\w+-]+)\s</PARENT... | Parse raw data into a collection of documents
Args:
raw_data (basestring): string containing documents
Returns:
documents (dict): a <document_identifier, cleaned_document_text>
dictionary | 625941cdd268445f265b4f72 |
def make_model_tgt0(n_units, merge_mode, drop_rate, drop_rate_emb, att_cosine, att_activation, use_fc_layer, embeddings, docs_train, is_GPU): <NEW_LINE> <INDENT> n_units_dense = n_units * 2 <NEW_LINE> sent_ints = Input(shape=(docs_train.shape[2], )) <NEW_LINE> sent_wv = Embedding(input_dim=embeddings.shape[0], output_d... | Convenient wrapper for generating same model for training and inference
n_units : int, number of units in bidirectional GRU layer
merge_mode : ['sum', 'mul', 'concat', 'ave', None] Mode by which outputs of the forward and backward RNNs will be combined.
drop_rate : float, dropout rate (set to 0 at inference time)
dr... | 625941cd7b180e01f3dc4901 |
def __call__(self, *func_args, **func_kwargs): <NEW_LINE> <INDENT> if hasattr(self, 'proc'): <NEW_LINE> <INDENT> raise AttributeError('The subprocess has already started') <NEW_LINE> <DEDENT> def sub_func(): <NEW_LINE> <INDENT> def notify_sleep_and_return(*args, **kwargs): <NEW_LINE> <INDENT> self.event.set() <NEW_LINE... | Closes the current database connection and starts the
decorated function in a sub-process, then waits on the event
that was passed in. | 625941cd8a43f66fc4b54169 |
def __repr__(self): <NEW_LINE> <INDENT> return '%r' % self.evalRPN() | This method defines the way in which an Expression object represents itself.
An Expression is represented by the list of its RPN tokens.
Returns:
:list of tokens: the RPN of the expression. | 625941cdb57a9660fec33987 |
def create(self): <NEW_LINE> <INDENT> api = client.CoreV1Api() <NEW_LINE> namespace = 'default' <NEW_LINE> if S.getValue('PLUGIN') == 'sriov': <NEW_LINE> <INDENT> configmap = load_manifest(S.getValue('CONFIGMAP_FILEPATH')) <NEW_LINE> self._sriov_config = configmap['metadata']['name'] <NEW_LINE> self._sriov_config_ns = ... | Creation Process | 625941cd956e5f7376d70f71 |
def to_one_hot(x: torch.tensor, n_classes: int): <NEW_LINE> <INDENT> length = len(x) <NEW_LINE> if length < n_classes: <NEW_LINE> <INDENT> _x = torch.arange(length) <NEW_LINE> out = torch.zeros(length, n_classes) <NEW_LINE> out[_x, x] = 1 <NEW_LINE> return out <NEW_LINE> <DEDENT> return torch.eye(length, n_classes)[x, ... | torch.tensor to one hot vector
| 625941cdb57a9660fec33988 |
@pytest.mark.xfail <NEW_LINE> def test_optimizers(): <NEW_LINE> <INDENT> optimizers = ['migrad', 'fmin'] <NEW_LINE> start_values = ['last', 'estimate'] <NEW_LINE> images = make_test_images(shape=(30, 50)) <NEW_LINE> kernel = make_test_kernel(shape=(5, 5)) <NEW_LINE> for optimizer in optimizers: <NEW_LINE> <INDENT> for ... | Compare speed for a few different optimizers | 625941cd56ac1b37e62642d3 |
def __checkProfileIntegrity( self, profile, upperLimit=1.0, lowerLimit=-1.0): <NEW_LINE> <INDENT> mask = N0.greater( profile, upperLimit ) <NEW_LINE> mask += N0.less( profile, lowerLimit ) <NEW_LINE> for i in N0.nonzero(mask): <NEW_LINE> <INDENT> print('WARNING! Profile value %.2f set to O\n'%profile[i]) <NEW_LINE> pr... | In some cases SurfaceRacer generates incorrect curvature
values for some atoms. This function sets values outside
a given range to 0
@param profile: profile name
@type profile: str
@param upperLimit: upper limit for a valid value (default: 1.0)
@type upperLimit: float
@param lowerLimit: lower limit for a valid value... | 625941cd6e29344779a62715 |
def bellman_ford(self, start): <NEW_LINE> <INDENT> previous = {} <NEW_LINE> distance = {node: _GreatestValue for node in self.nodes()} <NEW_LINE> distance[start] = 0 <NEW_LINE> for _ in range(1, len(self._dict)): <NEW_LINE> <INDENT> for node, neighbor, weight in self.edges_with_weights(): <NEW_LINE> <INDENT> if distanc... | Resolve all distances from the given start node to any other pathable node in the graph and return a tuple of
2 dictionaries: a dictionary of all pathable nodes and the total distance of their shortest paths,
and another that shows, for each node in these shortest paths, the previous step in | 625941cd099cdd3c635f0d5f |
def _check_coordinates(coords, size): <NEW_LINE> <INDENT> x, y = coords <NEW_LINE> size_x, size_y = size <NEW_LINE> if x > size_x or y > size_y: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif x < 0 or y < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Check that coordinates are inside the grid given as an argument.
Args:
coords: (x, y) tuple.
size: (size_x, size_y) tuple. | 625941cd45492302aab5e3c7 |
def get_config(self): <NEW_LINE> <INDENT> return self.config | Return configuration file object. | 625941cdf7d966606f6aa108 |
def powersettool(iterable): <NEW_LINE> <INDENT> s = list(iterable) <NEW_LINE> return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) | powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) | 625941cd3c8af77a43ae38a4 |
def test_next_key_ready(self): <NEW_LINE> <INDENT> buffer = PointBuffer(3) <NEW_LINE> buffer.add_point(0, RawPoint(time=1000, value="zebra")) <NEW_LINE> buffer.add_point(1, RawPoint(time=1000, value="leopard")) <NEW_LINE> buffer.add_point(2, RawPoint(time=1000, value="giraffe")) <NEW_LINE> buffer.add_point(0, RawPoint(... | Assert next_key_ready returns correct key | 625941cdaad79263cf390b45 |
def findLongestChainStack(self, pairs): <NEW_LINE> <INDENT> pairs.sort(key=lambda p: p[1]) <NEW_LINE> stack = [] <NEW_LINE> for p in pairs: <NEW_LINE> <INDENT> if not stack or (stack and stack[-1][1] < p[0]): <NEW_LINE> <INDENT> stack.append(p) <NEW_LINE> <DEDENT> <DEDENT> return len(stack) | :type pairs: List[List[int]]
:rtype: int
沒想到本題有 Greedy 的解法
根據尾巴值排序後就從頭開始找就可以 | 625941cd2c8b7c6e89b358c5 |
def resolve_say_attributes(self, predict): <NEW_LINE> <INDENT> attrs = renpy.exports.get_say_attributes() <NEW_LINE> if not attrs: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.image_tag: <NEW_LINE> <INDENT> if not predict: <NEW_LINE> <INDENT> raise Exception("Say has image attributes %r, but there's no im... | Deals with image attributes associated with the current say
statement. | 625941cdbe383301e01b5589 |
def build_distribution(): <NEW_LINE> <INDENT> if IN_TEST: <NEW_LINE> <INDENT> cargo("package", "--allow-dirty") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cargo("package") | Build the crate. | 625941cd851cf427c661a613 |
def data_set(self, data): <NEW_LINE> <INDENT> self.dataSet = ( ('Dots', [(i, l[1]) for i, l in enumerate(data)]), ) <NEW_LINE> self.options = { 'legend': {'hide': True}, 'titleColor': '#000000', 'titleFont': 'Tahoma', 'titleFontSize': 12, 'axis': { 'tickColor': '#000000', 'tickFont': 'Sans', 'tickFontSize': 12, 'labelF... | Set chart data (dataSet) | 625941cd236d856c2ad448df |
def get_filtered_objects(self, filter_classes, objs, filter_properties, index=0): <NEW_LINE> <INDENT> list_objs = list(objs) <NEW_LINE> LOG.debug("Starting with %d host(s)", len(list_objs)) <NEW_LINE> for filter_cls in filter_classes: <NEW_LINE> <INDENT> cls_name = filter_cls.__name__ <NEW_LINE> filter_class = filter_c... | Get objects after filter
:param filter_classes: filters that will be used to filter the
objects
:param objs: objects that will be filtered
:param filter_properties: client filter properties
:param index: This value needs to be increased in the caller
function of get_filtered_object... | 625941cdd99f1b3c44c67692 |
def valid_create_size(size): <NEW_LINE> <INDENT> err = "'{0}' is not valid size.".format(size) <NEW_LINE> if len(size) and size[0] in ['+', '-']: <NEW_LINE> <INDENT> raise argparse.ArgumentTypeError(err) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ret = misc.get_real_size(size) <NEW_LINE> if float(ret) < 0: <NEW_LINE>... | Validate that the 'size' is usable size argument. This is almost the
same as valid_resize_size() except we do not allow '+' and '-' signs
>>> valid_create_size("3.14")
('3.14', 'K')
>>> valid_create_size("+3.14k")
Traceback (most recent call last):
...
ArgumentTypeError: '+3.14k' is not valid size.
>>> valid_create_si... | 625941cd38b623060ff0aef2 |
def rmttest_pos(self): <NEW_LINE> <INDENT> self.run_test(relaxed=True, success=False) | BB Basic with one requirement - parse error | 625941cd99fddb7c1c9de495 |
def count(self, query=None): <NEW_LINE> <INDENT> return len(self._recipes) | Counts the number of Resources entities
:param query: A query parameter (not used in this implementation)
:return: The number of Recipy objects found in the file | 625941cd21bff66bcd684a58 |
def send_reminder(reminders, request_type, worksheet_key): <NEW_LINE> <INDENT> reminder_cfg = dict(config.items('email_defaults')) <NEW_LINE> reminder_cfg.update(dict(config.items('reminder'))) <NEW_LINE> request_details = build_request_details( request_list=reminders, template=reminder_cfg['detail_template']) <NEW_LIN... | Send a reminder email about an application waiting for approval
for more than a given # of hours (specified in config) | 625941cd2ae34c7f2600d235 |
def _notify_change(self): <NEW_LINE> <INDENT> def inner_action(*args): <NEW_LINE> <INDENT> self.editor.file.open(self.editor.file.path) <NEW_LINE> <DEDENT> args = ("File changed", "The file <i>%s</i> has changed externally.\nDo you want to " "reload it?" % os.path.basename(self.editor.file.path)) <NEW_LINE> kwargs = {"... | Notify user from external change if autoReloadChangedFiles is False
then reload the changed file in the editor | 625941cd3c8af77a43ae38a5 |
def scan_vulcan_record(self, log_file_path): <NEW_LINE> <INDENT> status = False <NEW_LINE> try: <NEW_LINE> <INDENT> archive_key = self._myArchiveManager.scan_vulcan_record(log_file_path) <NEW_LINE> scanned_runs_information = self._myArchiveManager.get_experiment_run_info( archive_key=archive_key) <NEW_LINE> self._myPro... | Scan a standard VULCAN record/log file
:param log_file_path:
:return: | 625941cdfff4ab517eb2f541 |
def get_client_type(request): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> pdata = json.loads(request.body.decode('utf-8')) <NEW_LINE> project = pdata.get('project') <NEW_LINE> project = GameProject.objects.get(id=project) <NEW_LINE> client_type = GameServer.objects.filter(project=project)[0].pr... | 获取客户端类型
安卓或者iOS | 625941cdd7e4931a7ee9e022 |
def fire_transition(self , i): <NEW_LINE> <INDENT> inp = self.transition_weights[i][0] <NEW_LINE> out = self.transition_weights[i][1] <NEW_LINE> new_marking = tuple(m-inp[i]+out[i] for i ,m in enumerate(self.marking)) <NEW_LINE> self.marking = new_marking <NEW_LINE> return new_marking | i : index of transition transition should be enabled | 625941cd16aa5153ce36257d |
def run_test_suite(): <NEW_LINE> <INDENT> retval = 0 <NEW_LINE> suite_gdouble = _ut.TestLoader().loadTestsFromTestCase(test_gdual_double) <NEW_LINE> suite_function_calls = _ut.TestLoader().loadTestsFromTestCase(test_function_calls) <NEW_LINE> suite_gvdouble = _ut.TestLoader().loadTestsFromTestCase(test_gdual_vdouble) <... | Run the full test suite.
This function will raise an exception if at least one test fails. | 625941cd462c4b4f79d1d7d5 |
def is_decryptable(lex, message, session): <NEW_LINE> <INDENT> message['share'] = '%s%s' % (settings.SITE_URL, url_for('message', id=str(message['_id']))) <NEW_LINE> if lex.is_accessible(message['message'], session.get('lex_token')): <NEW_LINE> <INDENT> email = str(md5.new(lex.get_email_by_token(message['token'])).hexd... | If message is decryptable, add the extra flags. | 625941cd4e4d5625662d44dc |
def deprecate_module_attr(mod, deprecated): <NEW_LINE> <INDENT> deprecated = set(deprecated) <NEW_LINE> class Wrapper(object): <NEW_LINE> <INDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr in deprecated: <NEW_LINE> <INDENT> warnings.warn("Property {} is deprecated".format(attr), GeogeniusDeprecation) <NE... | Return a wrapped object that warns about deprecated accesses | 625941cd9b70327d1c4e0ed9 |
def __terminate(self, state, error=None): <NEW_LINE> <INDENT> assert state in INACTIVE_STATES <NEW_LINE> self.__terminate_socket() <NEW_LINE> if self.mqtt_state is MqttState.connack: <NEW_LINE> <INDENT> on_disconnect_cb = self.on_connect_fail <NEW_LINE> <DEDENT> elif self.mqtt_state in (MqttState.connected, MqttState.m... | Parameters
----------
state: ReactorState
error: ReactorError | 625941cd596a897236089bc5 |
def testCollect(self): <NEW_LINE> <INDENT> plugin = windows.WindowsAllUsersAppProfileKnowledgeBasePlugin() <NEW_LINE> session = sessions.Session() <NEW_LINE> storage_writer = self._CreateTestStorageWriter() <NEW_LINE> test_knowledge_base = knowledge_base.KnowledgeBase() <NEW_LINE> test_mediator = mediator.PreprocessMed... | Tests the Collect function. | 625941cd046cf37aa974ce4c |
def _select_from_event_list(self, event_list): <NEW_LINE> <INDENT> if len(event_list) == 0: <NEW_LINE> <INDENT> self.presenter.create_new() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dialogs[CONFIRM_NEW_EVENT_DIALOG].activate( self._confirm_new_event_callback, event_list=event_list, date=self.date_range_for_new... | This is (implicitely) called from the
fetch_events_for_new_event_date() in the presenter.
If there is no other event for the given date range,
create a new event. Otherwise open a dialog to
either select one of the existing events or confirm
that a new event needs to be created. | 625941cdfbf16365ca6f62c9 |
def reconstruction_loss(self, model, batch): <NEW_LINE> <INDENT> pred_tf, _, _, _ = model(batch, True) <NEW_LINE> pred, _, _, _ = model(batch, False) <NEW_LINE> loss_tf = torch.nn.functional.binary_cross_entropy_with_logits(pred_tf, batch, reduction='mean') <NEW_LINE> loss = torch.nn.functional.binary_cross_entropy_wit... | Return reconstruction loss with and witout teacher forcing | 625941cd6fece00bbac2d843 |
def _combine_sizing_property(self, sizing: Sizing, canvas_item_sizing: Sizing, property: str, combiner: typing.Callable[[typing.Any, typing.Any], typing.Any], clear_if_missing: bool = False) -> None: <NEW_LINE> <INDENT> property = "_" + property <NEW_LINE> canvas_item_value = getattr(canvas_item_sizing, property) <NEW_... | Utility method for updating the property of the sizing object using the combiner function and the canvas_item_sizing. | 625941cd63b5f9789fde71ea |
def html_unquote(s, encoding=None): <NEW_LINE> <INDENT> if isinstance(s, str): <NEW_LINE> <INDENT> if s == '': <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> s = s.decode(encoding or default_encoding) <NEW_LINE> <DEDENT> return _unquote_re.sub(_entity_subber, s) | Decode the value.
>>> html_unquote('<hey you>')
u'<hey\xa0you>'
>>> html_unquote('')
u''
>>> html_unquote('&blahblah;')
u'&blahblah;'
>>> html_unquote('\xe1\x80\xa9')
u'\u1029' | 625941cd4f6381625f114b3f |
def __plot_spectrum(self, typ): <NEW_LINE> <INDENT> n = len(self.E_min) <NEW_LINE> data = np.zeros(shape=n) <NEW_LINE> if typ == 'rate': <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> data[i] = np.mean(self.rate[:, i]) <NEW_LINE> plt.rcParams["figure.figsize"] = [6, 6] <NEW_LINE> plt... | As a photons come in over the time and with different energies, the spectrum of counts is built up
Spectrum = function of energies for Rate/Counts/Flux | 625941cd0fa83653e46570c0 |
def compute_roc_curve_area(n_classes, X_test, y_test, fittedclf): <NEW_LINE> <INDENT> y_score = fittedclf.decision_function(X_test) <NEW_LINE> fpr = dict() <NEW_LINE> tpr = dict() <NEW_LINE> roc_auc = dict() <NEW_LINE> for i in range(n_classes): <NEW_LINE> <INDENT> fpr[i], tpr[i], _ = metrics.roc_curve(y_test[:, i], y_... | Computes the roc curve and roc area for a multiclass problem
:param n_classes: number of classes
:param X_test: list
:param y_test: list
:param fittedclf: fitted classifier
:return: 3 dictionaries | 625941cd76e4537e8c351777 |
def test_user_can_edit_own_imager_profile(self): <NEW_LINE> <INDENT> pass | Test that user can update fields of their imager profile. | 625941cd293b9510aa2c339b |
def export_mesh(obj, scene, filepath, use_normals, use_colors, use_uv_coords, use_materials, align_model, flipyz, option_truncate, option_scale, export_single_model): <NEW_LINE> <INDENT> mesh = obj.create_mesh(scene, True, 'RENDER') <NEW_LINE> if not mesh: <NEW_LINE> <INDENT> raise Exception("Error, could not get mesh ... | Export single mesh | 625941cd009cb60464c634b6 |
def make_doctest_message(fullfile, num_bad, num_test, elapsed_time_sec): <NEW_LINE> <INDENT> _, file = os.path.split(fullfile) <NEW_LINE> passfail = "pass" if num_bad == 0 else ("*** fail *** : file %r" % (fullfile,)) <NEW_LINE> num_ok = num_test - num_bad <NEW_LINE> elapsed_time_usec_str, elapsed_time_sec_str = time_u... | Create a well-defined error message for summarizing doctests.
See onyx.__init__._test_doctest_functions() for tests which will have to be
updated if the formatting of the doctest msg is changed. | 625941cd63d6d428bbe445f4 |
def add_known_users(self, user_list): <NEW_LINE> <INDENT> self.session.query(self.KnownUsers).delete() <NEW_LINE> for user in user_list: <NEW_LINE> <INDENT> user_entry = self.KnownUsers(user) <NEW_LINE> self.session.add(user_entry) <NEW_LINE> <DEDENT> self.session.commit() | Method for reinitializing a list of known users. | 625941cd3346ee7daa2b2e70 |
def filter_out_st(fac_ret): <NEW_LINE> <INDENT> dts = sorted(fac_ret.index.get_level_values(0).unique()) <NEW_LINE> st_stocks = Parallel(n_jobs=20, backend='threading', verbose=5)(delayed(get_st_stock_today)(dt) for dt in dts) <NEW_LINE> st_stocks = pd.concat(st_stocks, ignore_index=True) <NEW_LINE> st_stocks.loc[:, 'c... | 过滤出ST股票
Args:
fac_ret (DataFrame): 一个multi-index 数据框, level0=date, level1=code.
基本思想是和ST股票聚合, status==null说明不是ST的
Returns:
DataFrame, 不包含停牌股票的fac_ret | 625941cd66673b3332b92196 |
@login_required <NEW_LINE> def employee_delete(request, pk): <NEW_LINE> <INDENT> employee = get_object_or_404(Employee, pk=pk) <NEW_LINE> employee.delete() <NEW_LINE> messages.add_message(request, messages.INFO, 'Funcionário removido com sucesso!') <NEW_LINE> return redirect(r('core:index')) | Deletes an employee | 625941cd8e71fb1e9831d8ae |
def send(self, data): <NEW_LINE> <INDENT> self.sock.sendall(data) | send some data down to child process stdin | 625941cdadb09d7d5db6c894 |
def get(self, name): <NEW_LINE> <INDENT> return self._name_2_ent.get(name) | Raises:
KeyError | 625941cd4a966d76dd551114 |
def fit(self, X_train, y_train): <NEW_LINE> <INDENT> self.X_train = X_train <NEW_LINE> self.y_train = y_train | Fit the model using X as training data and y as target values
Args:
X_train ([array-like]): [description]
y_train ([array-like]): [description]
Passes along to _get_distance function | 625941cdde87d2750b85fe98 |
def word_break_graph_descent( s: str, word_dict: List, memory: Mapping[str, List[str]] ) -> Tuple[List[List[str]], Mapping[str, List[str]]]: <NEW_LINE> <INDENT> if s in memory: <NEW_LINE> <INDENT> return memory[s], memory <NEW_LINE> <DEDENT> accumulator = [] <NEW_LINE> for word in word_dict: <NEW_LINE> <INDENT> if word... | Walk the tree from top to bottom looking for possible ways to segment s.
:param s: `str` to be segmented
:param word_dict: `list` of words we can use
:param memory: `Mapping` from string to sequences we can build using word_dict
:return:
accumulator: `List[List]` with possible ways to segment s and memory for time ... | 625941cd009cb60464c634b7 |
def list_nodes_select(): <NEW_LINE> <INDENT> items = query(method='droplets') <NEW_LINE> ret = {} <NEW_LINE> for node in items['droplets']: <NEW_LINE> <INDENT> ret[node['name']] = {} <NEW_LINE> for item in node.keys(): <NEW_LINE> <INDENT> if str(item) in __opts__['query.selection']: <NEW_LINE> <INDENT> ret[node['name']... | Return a list of the VMs that are on the provider | 625941cd23849d37ff7b3194 |
def isSliceWorking(useCreateCol): <NEW_LINE> <INDENT> return 1 | Return <code>true</code> iff the implementation of slice
and smart copy is correct. | 625941cd15baa723493c407a |
def __on_openall_clicked(self, action, variant): <NEW_LINE> <INDENT> items = [] <NEW_LINE> for i in range(0, self.__closed_section.get_n_items()): <NEW_LINE> <INDENT> uri_attr = self.__closed_section.get_item_attribute_value(i, "uri") <NEW_LINE> title_attr = self.__closed_section.get_item_attribute_value( i, "label") <... | Add all entries
@param Gio.SimpleAction
@param GVariant | 625941cd656771135c3eb974 |
def setup(hass, config): <NEW_LINE> <INDENT> links = config.get(DOMAIN) <NEW_LINE> for link in links.get(CONF_ENTITIES): <NEW_LINE> <INDENT> Link(hass, link.get(CONF_NAME), link.get(CONF_URL), link.get(CONF_URL)) <NEW_LINE> <DEDENT> return True | Setup weblink component. | 625941cd379a373c97cfac4a |
def get_dtype(type_: Any) -> Dtype: <NEW_LINE> <INDENT> args = get_args(type_) <NEW_LINE> origin = get_origin(type_) <NEW_LINE> if origin is Collection: <NEW_LINE> <INDENT> return get_dtype(args[1]) <NEW_LINE> <DEDENT> if origin is Literal: <NEW_LINE> <INDENT> return args[0] <NEW_LINE> <DEDENT> if type_ is Any or type_... | Parse a type and return dtype.
Example:
All of the following expressions will be ``True``::
get_dtype(Any) == None
get_dtype(NoneType) == None
get_dtype(A) == A.__name__
get_dtype(Literal[A]) == A
get_dtype(ArrayLike[..., A]) == get_dtype(A) | 625941cd9c8ee82313fbb87a |
def _init_dnd(self): <NEW_LINE> <INDENT> pass | inheriting objects must set this
| 625941cd9f2886367277a992 |
def plotly_go_figure(xx, yy,the_date_column, target_column): <NEW_LINE> <INDENT> fig = go.Figure() <NEW_LINE> fig.add_trace(go.Scatter( x=xx, y=yy, name="Name of Trace 1" )) <NEW_LINE> fig.update_layout( title="Plot: Target Column vs Time", xaxis_title=the_date_column, yaxis_title=target_column, font=dict( family="Cour... | Interactive plotly plot
:param xx:
:param yy:
:param the_date_column:
:param target_column:
:return: | 625941cd4a966d76dd551115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.