code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@requires_sklearn <NEW_LINE> @testing.requires_testing_data <NEW_LINE> def test_continuous_regression_with_overlap(): <NEW_LINE> <INDENT> signal = np.zeros(100000) <NEW_LINE> times = [1000, 2500, 3000, 5000, 5250, 7000, 7250, 8000] <NEW_LINE> events = np.zeros((len(times), 3), int) <NEW_LINE> events[:, 2] = 1 <NEW_LINE... | Test regression with overlap correction. | 625941c71f5feb6acb0c4b9c |
def _pack_rpc( self, name, data=None, *, MsgClass=None, exchange=None, dest=None, uuid=None, codec=None, **kwargs ): <NEW_LINE> <INDENT> if dest is not None: <NEW_LINE> <INDENT> if uuid is not None: <NEW_LINE> <INDENT> raise RuntimeError("You cannot specify both uuid and dest") <NEW_LINE> <DEDENT> dest = 'qbroker.app.'... | Package data and metadata into one message object.
Arguments:
name:
the dispatch key to use for processing the message at the
recipient
data:
the actual payload to transmit
dest:
The name of the server to deliver the message to.
Mutually exclusive with ``uuid``.
... | 625941c7fbf16365ca6f620c |
def get_next_iteration(self, iteration, iteration_kwargs={}): <NEW_LINE> <INDENT> if self.SH_only: <NEW_LINE> <INDENT> s = self.max_SH_iter - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = self.max_SH_iter - 1 - (iteration % self.max_SH_iter) <NEW_LINE> <DEDENT> n0 = int(np.floor((self.max_SH_iter) / (s + 1)) * se... | BO-HB uses (just like Hyperband) SuccessiveHalving for each
iteration. See Li et al. (2016) for reference.
Parameters:
-----------
iteration: int
the index of the iteration to be instantiated
Returns:
--------
SuccessiveHalving: the SuccessiveHalving iteration with the
corresponding number of c... | 625941c7dd821e528d63b1f4 |
def mnasneta1_5x5mbconv3(pretrained=False, progress=False, **kwargs): <NEW_LINE> <INDENT> return _mnasnet('mnasneta1', MBConv, layers=[2, 3, 4, 2, 3, 1], expansions=[3, 3, 3, 3, 3, 3], kernel_sizes=[5, 5, 5, 5, 5, 5], SE=[False, False, False, False, False, False], dropout=0, pretrained=pretrained, progress=progress, **... | mnasneta1 w.t. 5x5-MBconv-3 block only | 625941c7f8510a7c17cf9746 |
def segmentation_similarity(*args, **kwargs): <NEW_LINE> <INDENT> return __fnc_metric__(__segmentation_similarity__, args, kwargs, SIMILARITY_METRIC_DEFAULTS) | Segmentation Similarity (S). | 625941c75f7d997b87174ae1 |
def get_supported_versions(self, include_alpha_versions: bool = False): <NEW_LINE> <INDENT> api_version_list = self.get_supported_versions_list( include_alpha_versions=include_alpha_versions) <NEW_LINE> if api_version_list: <NEW_LINE> <INDENT> return [VCDApiVersion(api_version) for api_version in api_version_list] | Return non-deprecated server API version Objects as a list.
:param bool include_alpha_versions: boolean indicating if alpha
versions need to be considered.
:rtype: List[VCDApiVersion]
:return: versions as strings, sorted in numerical order. | 625941c73eb6a72ae02ec524 |
def _get_package_progress(self, package_name): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if self._is_package_in_progress(package_name): <NEW_LINE> <INDENT> return self._package_progress[package_name] <NEW_LINE> <DEDENT> return None | :param package_name: The name of the package for which to query progress
:return: the state of the package | 625941c724f1403a92600bb1 |
def remove_full_lines(self): <NEW_LINE> <INDENT> lines_to_remove = set() <NEW_LINE> for index in xrange(len(self.remnants[0])): <NEW_LINE> <INDENT> if self.line_full(index): <NEW_LINE> <INDENT> lines_to_remove.add(index) <NEW_LINE> <DEDENT> <DEDENT> yellow_blocks = 0 <NEW_LINE> col_index = len(self.remnants[0]) - 1 <NE... | Remove each full line from the heap. | 625941c796565a6dacc8f715 |
def test_crud_set_ownership_and_edit_tags(myservice): <NEW_LINE> <INDENT> myservice.set_ownership("Administrator", "EvmGroup-administrator") <NEW_LINE> myservice.edit_tags("Cost Center *", "Cost Center 001") <NEW_LINE> myservice.update("edited", "edited_desc") <NEW_LINE> edited_name = myservice.service_name + "_" + "ed... | Tests my service crud , edit tags and ownership
Metadata:
test_flag: provision | 625941c7bde94217f3682e3c |
def stop(self, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self._running_managers[self._manager_key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.running = False <NEW_LINE> self._local_addr = None <NEW_LINE> self._local_addr_event.clear() | Stops the TendrilManager. Requires cooperation from the
listener implementation, which must watch the ``running``
attribute and ensure that it stops accepting connections
should that attribute become False. Note that some tendril
managers will not exit from the listening thread until all
connections have been closed. | 625941c7a05bb46b383ec86c |
def _getIncorrectNodeRec(self, current, minVal, maxVal): <NEW_LINE> <INDENT> if current == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if current.getValue() < minVal or current.getValue() > maxVal: <NEW_LINE> <INDENT> return current <NEW_LINE> <DEDENT> if self._getIncorrectNodeRec(current.getLeft(), minVa... | recursive helper for getIncorrectNode
TODO: fix this | 625941c7627d3e7fe0d68e99 |
def transform_layout(learning_map): <NEW_LINE> <INDENT> rows = max([l['element'] for l in learning_map])+1 <NEW_LINE> cols = max([l['row'] for l in learning_map])+1 <NEW_LINE> layout = [[None]*rows for a in [None]*cols] <NEW_LINE> for item in learning_map: <NEW_LINE> <INDENT> layout[item['row']][item['element']] = item... | Convert a learning_map into a hex grid of items
| 625941c732920d7e50b28219 |
def with_totals(m): <NEW_LINE> <INDENT> if is_weight(m): <NEW_LINE> <INDENT> return weight(size(m)) <NEW_LINE> <DEDENT> return tree(total_weight(m), [side(length(s), with_totals(end(s))) for s in sides(m)]) | Return a mobile with total weights stored as the root of each mobile.
>>> t, _, v = examples()
>>> root(with_totals(t))
3
>>> print(root(t)) # t should not change
None
>>> root(with_totals(v))
9
>>> [root(end(s)) for s in sides(with_totals(v))]
[3, 6]
>>> [root(end(s)) for s in sides(v)] ... | 625941c723849d37ff7b30da |
def UpdateOAuthGrant(self, userId, id, client=None, type=None, accessType=None, redirectUri=None, scope=None, networkIds=None): <NEW_LINE> <INDENT> jsonToSend={"userId": userId, "id": id} <NEW_LINE> if client: <NEW_LINE> <INDENT> jsonToSend["client"] = client.ToDictionary() <NEW_LINE> <DEDENT> if type: <NEW_LINE> <INDE... | Updates an existing OAuth grant.
:param userId: User identifier. Use the 'current' keyword to update OAuth grant of the current user.
:param id: OAuth grant identifier.
:param client: A OAuthClient object which includes oauthId property to match.
:param type: OAuth grant type.
Code: Authorization Code grant
Token: Impl... | 625941c78e05c05ec3eea3be |
def initial_donation(): <NEW_LINE> <INDENT> print('Would you like to enter an initial donation for this donor?') <NEW_LINE> choice = CLIMain.get_choice() <NEW_LINE> if choice.upper() == 'Y': <NEW_LINE> <INDENT> return CLIMain.get_donation() | Asks for and returns initial donation | 625941c7377c676e912721f3 |
@app.route('/upload_error') <NEW_LINE> def upload_error(): <NEW_LINE> <INDENT> flash('Your upload is too large, please resize it and try again.') <NEW_LINE> return redirect_back('error') | :URL: /upload_error
On the main site any over-size uploads will be redirected here.
Flash a message to the user and attempt to redirect_back() | 625941c792d797404e3041d4 |
def keyPressEvent(self, event): <NEW_LINE> <INDENT> if self.tile: <NEW_LINE> <INDENT> assert self == self.tile.board.focusTile.graphics, 'id(self):%s, self:%s, focusTile:%s/%s' % (id(self), self, id(self.tile.board.focusTile), self.tile.board.focusTile) <NEW_LINE> return self.tile.board.keyPressEvent(event) | redirect to the board | 625941c75510c4643540f431 |
def get_message(request, global_id): <NEW_LINE> <INDENT> access_id = utils.get_access_id(global_id) <NEW_LINE> if access_id == None: <NEW_LINE> <INDENT> return HttpResponseForbidden() <NEW_LINE> <DEDENT> if not hmac.check_hmac_authentication(request, access_id.access_secret): <NEW_LINE> <INDENT> return HttpResponseForb... | Respond to an HTTP GET "<global_id>/message" API call.
| 625941c729b78933be1e56f8 |
def noise(batch_size, data_size): <NEW_LINE> <INDENT> shape = (batch_size,) + data_size if isinstance(data_size, tuple) else ( batch_size, data_size) <NEW_LINE> return to_pytorch_variable(torch.randn(shape)) | Returns a variable with the dimensions (batch_size, data_size containing gaussian noise | 625941c70fa83653e4657006 |
def callLeaderboard(self, id): <NEW_LINE> <INDENT> data = None <NEW_LINE> if self.accessToken is None: <NEW_LINE> <INDENT> raise NameError("accessToken is none") <NEW_LINE> <DEDENT> path = self.leaderboardUrl % id <NEW_LINE> url = "%s%s%s" % ( self.baseUrl,self.apiUrl, path) <NEW_LINE> self.log.info("callLeaderboard:ur... | Make call to strava LeaderBoard for segment id=id | 625941c7ec188e330fd5a7eb |
def test_removed_mlsconstrains(self): <NEW_LINE> <INDENT> l = sorted(self.diff.removed_mlsconstrains) <NEW_LINE> self.assertEqual(2, len(l)) <NEW_LINE> mlsconstrain = l[0] <NEW_LINE> self.assertEqual(CRT.mlsconstrain, mlsconstrain.ruletype) <NEW_LINE> self.assertEqual("infoflow4", mlsconstrain.tclass) <NEW_LINE> self.a... | Diff: removed mlsconstrains. | 625941c74f6381625f114a86 |
def new_factory(body=None): <NEW_LINE> <INDENT> if connexion.request.is_json: <NEW_LINE> <INDENT> body = FactoryCreateBody.from_dict(connexion.request.get_json()) <NEW_LINE> try: <NEW_LINE> <INDENT> return StringDataResponse( deploy_factory(gas_payer=body.gas_payer, gas_payer_priv=body.gas_payer_private)), 200 <NEW_LIN... | Creates a new factory and returns the address
Creates a new factory and returns the address # noqa: E501
:param body:
:type body: dict | bytes
:rtype: StringDataResponse | 625941c70383005118ecf62d |
def toplist(self, top_n): <NEW_LINE> <INDENT> inverted = invert_dict(self._repo) <NEW_LINE> toplist = [] <NEW_LINE> ordered_keylist = inverted.keys() <NEW_LINE> ordered_keylist.sort(reverse=True) <NEW_LINE> for count in ordered_keylist: <NEW_LINE> <INDENT> for item in inverted[count]: <NEW_LINE> <INDENT> toplist.append... | Return a list of the top_n items | 625941c7cc40096d6159599b |
def _init_anim(self): <NEW_LINE> <INDENT> raise NotImplementedError | Init function (plot the background of each frame) that is passed to FuncAnimation. This has to be
implemented in the child class. | 625941c791af0d3eaac9ba62 |
def fox_says(start, middle, end, num): <NEW_LINE> <INDENT> def repeat(k): <NEW_LINE> <INDENT> if k == 1: <NEW_LINE> <INDENT> return middle <NEW_LINE> <DEDENT> return middle + "-" + repeat(k - 1) <NEW_LINE> <DEDENT> return start + '-' + repeat(num) + '-' + end | >>> fox_says('wa', 'pa', 'pow', 3)
'wa-pa-pa-pa-pow'
>>> fox_says('fraka', 'kaka', 'kow', 4)
'fraka-kaka-kaka-kaka-kaka-kow' | 625941c7d268445f265b4eb8 |
def GetShowLabels(self): <NEW_LINE> <INDENT> return self._showLabels | Returns ``True`` if button labels are currently shown. | 625941c755399d3f055886fe |
def handle_message(self, data, user, msg): <NEW_LINE> <INDENT> msg = tools.strip_name(msg) <NEW_LINE> args = msg.split() <NEW_LINE> if args[0] == "!about" or args[0] == "!bot": <NEW_LINE> <INDENT> self.log.info("Printing \"about\"") <NEW_LINE> self.bot.send_message("MustikkaBot (2013-2020) is a Twitch bot written in py... | :param data: Full IRC command
:type data: str
:param user: name of the user that sent the message
:type user: str
:param msg: the message itself
:type msg: str
Handle incoming chat-messages. Check if it contains either !about or !bot commmands | 625941c7cb5e8a47e48b7af6 |
def p_attraccess(self, p): <NEW_LINE> <INDENT> p[0] = ast.Attr(obj=p[1], attr=p[3]) | attraccess : atom PERIOD NAME | 625941c757b8e32f524834e4 |
def merge_sort(alist): <NEW_LINE> <INDENT> if len(alist)==1: <NEW_LINE> <INDENT> return alist <NEW_LINE> <DEDENT> num=len(alist)//2 <NEW_LINE> left=merge_sort(alist[:num]) <NEW_LINE> right=merge_sort(alist[num:]) <NEW_LINE> return merge(left,right) | 归并排序 | 625941c7adb09d7d5db6c7da |
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: <NEW_LINE> <INDENT> rows, cols, count = len(matrix), len(matrix[0]), 0 <NEW_LINE> for i in range(rows): <NEW_LINE> <INDENT> for j in range(1, cols): <NEW_LINE> <INDENT> matrix[i][j] += matrix[i][j-1] <NEW_LINE> <DEDENT> <DEDENT> for start_col... | One of the most trikiest questions solved till date. Thanks to this video. https://www.youtube.com/watch?v=i5UoDZbQ94Q&feature=emb_title
This question is, in extension to https://leetcode.com/problems/subarray-sum-equals-k/
First of all if our matrix is
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
We calculate the pre_sum column w... | 625941c7d58c6744b4257cab |
def controls_all_section(self, control): <NEW_LINE> <INDENT> temp = np.zeros(0) <NEW_LINE> for i in range(self.number_of_section): <NEW_LINE> <INDENT> temp = np.concatenate([temp, self.controls(control, i)]) <NEW_LINE> <DEDENT> return temp | get controls array
Args:
control (int) : control number
Returns:
controls_all_section ((N, ) ndarray) :
1-D array of all section control | 625941c70c0af96317bb8232 |
def clear_tags(tag, clear_elem): <NEW_LINE> <INDENT> if tag: <NEW_LINE> <INDENT> c_tag = list(set(get_unnecessary_elements(tag, clear_elem))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c_tag = get_unnecessary_elements(tag, clear_elem) <NEW_LINE> <DEDENT> return c_tag | Clearing the tag list from replays. | 625941c7a8ecb033257d3118 |
def aiMove(self, ox): <NEW_LINE> <INDENT> if ox == 'X': <NEW_LINE> <INDENT> opponent = 'O' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> opponent = 'X' <NEW_LINE> <DEDENT> if self.colsToWin(ox): <NEW_LINE> <INDENT> return random.choice(self.colsToWin(ox)) <NEW_LINE> <DEDENT> elif self.colsToWin(opponent): <NEW_LINE> <I... | argument ox is string 'X' or 'O'
returns a single integer, which must be a legal
column in which to make a move
If there is a way for ox to win, then aiMove MUST
return that move (that column number). It must win
when it can. There may be more than one way to win:
in this case, any one of those winning column move... | 625941c7ac7a0e7691ed4119 |
def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.smb_cache_clear() <NEW_LINE> self.final_location = self.get_from_smb() <NEW_LINE> if self.clean_pdf_tag: <NEW_LINE> <INDENT> self.clean_pdf() <NEW_LINE> <DEDENT> return self.final_location | main call function | 625941c7091ae35668666faa |
def skip_comment(self): <NEW_LINE> <INDENT> while self.current_char() != "\n" and self.remaining_code(): <NEW_LINE> <INDENT> self.char_pos += 1 | Move char_pos to first non-whitespace char. | 625941c7090684286d50ed2f |
def set_image_file(filename): <NEW_LINE> <INDENT> self._image_file = filename | Sets the image file for the view.
set_image_file(str) -> None | 625941c78c3a873295158404 |
def view_stock(self): <NEW_LINE> <INDENT> print("\n\n--------------------------------") <NEW_LINE> print("--------------------------------") <NEW_LINE> print("{}").format(self.name) <NEW_LINE> print("{}").format(self.ticker) <NEW_LINE> print("${:.2f}").format(self.current_price) <NEW_LINE> print("${:.2f}").format(self.... | Displays the details of a stock
| 625941c7aad79263cf390a8a |
def setAPIs(self, QsciAbstractAPIs): <NEW_LINE> <INDENT> pass | QsciLexer.setAPIs(QsciAbstractAPIs) | 625941c756b00c62f0f146a3 |
def map_type_from_supertype( typ, sub_info, super_info): <NEW_LINE> <INDENT> inst_type = self_type(sub_info) <NEW_LINE> inst_type = map_instance_to_supertype(inst_type, super_info) <NEW_LINE> return expand_type_by_instance(typ, inst_type) | Map type variables in a type defined in a supertype context to be valid
in the subtype context. Assume that the result is unique; if more than
one type is possible, return one of the alternatives.
For example, assume
class D<S> ...
class C<T> is D<E<T>> ...
Now S in the context of D would be mapped to E<T> in th... | 625941c7236d856c2ad44823 |
def _assign_variable_of_size(self, size): <NEW_LINE> <INDENT> test_var = bytearray(size) <NEW_LINE> time.sleep(0.05) | Assigns a string of the given size
size {int} --variable size in bytes | 625941c7442bda511e8be464 |
def __init__(self, command_line): <NEW_LINE> <INDENT> from subprocess import Popen, PIPE <NEW_LINE> self.cmd = shlsplit(command_line) <NEW_LINE> self.process = Popen(self.cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0) <NEW_LINE> self.timeout = None | Create a new CommandProxy instance. The instance created by this
class can be passed as an argument to the `.Transport` class.
:param str command_line:
the command that should be executed and used as the proxy. | 625941c773bcbd0ca4b2c0c1 |
def max_size(self, strokes): <NEW_LINE> <INDENT> sizes = [len(seq) for seq in strokes] <NEW_LINE> return max(sizes) | larger sequence length in the data set | 625941c75fcc89381b1e1709 |
def removeFile(path): <NEW_LINE> <INDENT> pass | Remove a file.
@param path: The path, as a list of segments, to remove
@type path: C{list} of C{unicode}
@return: A Deferred which fires when the file has been
removed, or which fails if the file cannot be removed. | 625941c7d7e4931a7ee9df68 |
def bank_fjcf_page_url(page: int = 5, item: str = "分局本级", begin: int = 1) -> pd.DataFrame: <NEW_LINE> <INDENT> cbirc_headers = cbirc_headers_without_cookie_2020.copy() <NEW_LINE> main_url = "http://www.cbirc.gov.cn/cbircweb/DocInfo/SelectDocByItemIdAndChild" <NEW_LINE> temp_df = pd.DataFrame() <NEW_LINE> for i_page in ... | 获取 首页-政务信息-行政处罚-银保监分局本级-每一页的 json 数据
:param page: 需要获取前 page 页的内容, 总页数请通过 bank_fjcf_total_page() 获取
:type page: int
:return: 需要的字段
:rtype: pandas.DataFrame | 625941c715fb5d323cde0b59 |
def fix_python_dylib_for_pkg(self): <NEW_LINE> <INDENT> self.cmd.chdir(self.prefix) <NEW_LINE> self.cmd.chmod(self.product.dylib) <NEW_LINE> self.install_name_tool_id( f"@loader_path/../../../../support/{self.product.name_ver}/{self.product.dylib}", self.product.dylib, ) <NEW_LINE> self.cmd.chdir(self.project.root) | change dylib ref to point to loader in package build format | 625941c74e696a04525c9496 |
def get_public_key(self): <NEW_LINE> <INDENT> req = Request(urljoin(self.base_url, 'token_keys')) <NEW_LINE> with urlopen(req) as f: <NEW_LINE> <INDENT> return json.loads(b2s(f.read()))['keys'][0]['value'] | Retrieve public key from UAA base url. | 625941c77d43ff24873a2ceb |
def t_LOGIC_ANY(t): <NEW_LINE> <INDENT> return t | ANY\ OF | 625941c7d486a94d0b98e190 |
def make_folder(self,settings): <NEW_LINE> <INDENT> if not os.path.exists(os.path.join(settings["--output"],"trim")): <NEW_LINE> <INDENT> os.makedirs(os.path.join(settings["--output"],"trim")) <NEW_LINE> <DEDENT> if not os.path.exists(os.path.join(settings["--output"],"trim","trim_info")): <NEW_LINE> <INDENT> os.makedi... | make output folder for task if needed | 625941c79c8ee82313fbb7bf |
def test_entities_domain(): <NEW_LINE> <INDENT> schema = vol.Schema(cv.entities_domain('sensor')) <NEW_LINE> options = ( None, '', 'invalid_entity', ['sensor.light', 'cover.demo'], ['sensor.light', 'sensor_invalid'], ) <NEW_LINE> for value in options: <NEW_LINE> <INDENT> with pytest.raises(vol.MultipleInvalid): <NEW_LI... | Test entities domain validation. | 625941c73cc13d1c6d3c73c5 |
def repN(n, original, sample, khash, verbose=False): <NEW_LINE> <INDENT> if "N" not in n: <NEW_LINE> <INDENT> return khash <NEW_LINE> <DEDENT> for base in ["A", "C", "G", "T"]: <NEW_LINE> <INDENT> a = n.replace('N', base, 1) <NEW_LINE> if "N" in a: <NEW_LINE> <INDENT> repN(a, original, sample, khash, verbose) <NEW_LINE... | Permute the string, replacing each individual occurrence of N with {A, G, C, T}
:param n: The test string
:param original: The original string
:param sample: The specific sample
:param khash: our dict of dicts
:param verbose: more output, but it is written to stderr
:return: | 625941c77c178a314d6ef4a9 |
def save_as(self, event=None): <NEW_LINE> <INDENT> if self.parent.data_object.is_empty(): <NEW_LINE> <INDENT> print("Nothing to save") <NEW_LINE> return <NEW_LINE> <DEDENT> file_name = filedialog.asksaveasfilename(defaultextension=".json", filetypes=[("Configuration Files", "*.json")]) <NEW_LINE> if file_name: <NEW_LIN... | Save as callback in menubar
:event: Callback event
:returns: None | 625941c7e8904600ed9f1f76 |
def parse_server_str(self, server_string): <NEW_LINE> <INDENT> self.servstr= server_string.strip()[:-1] <NEW_LINE> sslisted= self.servstr.strip().lstrip('(').rstrip(')').split(')(') <NEW_LINE> for i in sslisted: <NEW_LINE> <INDENT> w= i.split(' ') <NEW_LINE> self.d[w[0]]= destringify(w[1:]) | Parse the server string. | 625941c7d164cc6175782d98 |
def setFilters(self, filters): <NEW_LINE> <INDENT> self.filters = filters | :param filters: (Optional) productName-产品名称,精确匹配,支持单个
productKey-产品key,精确匹配,支持单个
productType-产品类型,精确匹配,支持单个
| 625941c715baa723493c3fc0 |
def item_split(oi_req, oi, del_id): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for o in oi: <NEW_LINE> <INDENT> if o.id not in del_id and o.quantity > int(oi_req[str(o.id)]): <NEW_LINE> <INDENT> data[str(o.id)] = o.quantity - int(oi_req[str(o.id)]) <NEW_LINE> <DEDENT> <DEDENT> return data | return a dict containing orderitem id, and the different between
request and database(the amount to be moved.) | 625941c7bd1bec0571d9067a |
@login_manager.request_loader <NEW_LINE> def load_user_from_request(request): <NEW_LINE> <INDENT> auth = request.authorization <NEW_LINE> if auth: <NEW_LINE> <INDENT> user = User.query.filter_by(username=auth.username).first() <NEW_LINE> if not user or not user.check_password(auth.password): <NEW_LINE> <INDENT> return ... | Load user for flask login.
| 625941c7f548e778e58cd5c8 |
def node_mem_param(params): <NEW_LINE> <INDENT> logger = params['logger'] <NEW_LINE> shm_pages_to_scan = params.get('shm_pages_to_scan') <NEW_LINE> shm_sleep_millisecs = params.get('shm_sleep_millisecs') <NEW_LINE> shm_merge_across_nodes = params.get('shm_merge_across_nodes') <NEW_LINE> if not shm_pages_to_scan ... | test set host node memory parameters
| 625941c7d4950a0f3b08c39b |
def ordinal_suffix(number): <NEW_LINE> <INDENT> number %= 100 <NEW_LINE> if number >= 20: <NEW_LINE> <INDENT> number %= 10 <NEW_LINE> <DEDENT> if number >= 4: <NEW_LINE> <INDENT> number = 0 <NEW_LINE> <DEDENT> return SUFFIX[number] | Return the ordinal suffix of a given number.
Parameters:
number (int): Specified number
Return:
suffix needed to turn the specified number into an ordinal number. | 625941c77cff6e4e811179d1 |
def falsy(thing): <NEW_LINE> <INDENT> return not truthy(thing) | checks if a value is False or None
>>> falsy(0)
False
>>> falsy({})
False
>>> falsy([])
False
>>> falsy(None)
True
>>> falsy(False)
True | 625941c7e64d504609d7488b |
def score_correction(self, candidate, context): <NEW_LINE> <INDENT> correction, edit = candidate <NEW_LINE> return self.lang_model.prob(correction, context) * self.error_model.prob(edit) | Score a candidate correction.
Params:
candidate: [(string, string)] A tuple containing the correction and
the edit string.
context: [deque] The n - 1 words before candidate where n is the
order of the lang model.
Returns:
[float] The score for the correction. Larger scores are
bet... | 625941c7ab23a570cc2501cd |
def _arith_method(self, other, op): <NEW_LINE> <INDENT> if isinstance(other, ABCTimedeltaIndex): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> elif isinstance(other, (timedelta, np.timedelta64)): <NEW_LINE> <INDENT> return super()._arith_method(other, op) <NEW_LINE> <DEDENT> elif is_timedelta64_dtype(ot... | Parameters
----------
other : Any
op : callable that accepts 2 params
perform the binary op | 625941c776d4e153a657eb7c |
def size(self): <NEW_LINE> <INDENT> return self.num_items | returns the number of items in the queue
Returns:
int : it returns the number of items in the queue | 625941c766656f66f7cbc1f6 |
def _write_log(self, d, path, action): <NEW_LINE> <INDENT> pass | Helper to log RM info for experiments.
:param d: container
:param path: log path
:param action: allocate or free
:return: | 625941c7099cdd3c635f0ca7 |
def kuku(func): <NEW_LINE> <INDENT> for i in range(1, 10): <NEW_LINE> <INDENT> for j in range(1, 10): <NEW_LINE> <INDENT> print('{:3d}'.format(func(i, j)), end='') <NEW_LINE> <DEDENT> print() | 打印输出九九乘法表 | 625941c707f4c71912b114cd |
def _right_sized(contour, image, container_filter=True, size_filter=True): <NEW_LINE> <INDENT> import cv2 <NEW_LINE> image_size = image.shape <NEW_LINE> x, y, w, h = cv2.boundingRect(contour) <NEW_LINE> area = image_size[0] * image_size[1] <NEW_LINE> if w > h: <NEW_LINE> <INDENT> ratio = float(w) / h <NEW_LINE> <DEDENT... | Checks if contour size and shape is that of an object of interest.
Parameters
----------
contour : cv2.Contour
Contour to be analysed.
image_size : tuple
Dimensions of operating image.
container_filter : boolean
Filters with simple heuristic for container contours. These are
contours containing other s... | 625941c7507cdc57c6306d24 |
def value_iteration(get_action_cost, gamma: float = 0.99, delta: float = 0.001, filename = None): <NEW_LINE> <INDENT> history_delta = [] <NEW_LINE> global v_table, p_table, q_table <NEW_LINE> random_initialize() <NEW_LINE> converged = False <NEW_LINE> for iteration in range(1, 1000): <NEW_LINE> <INDENT> for h, a, s in ... | Computes the Optimal Policy and the State Values
:return history_delta: (list<float>) The change in function over the history | 625941c726068e7796caed28 |
def get_network_used_count(ip_range: str): <NEW_LINE> <INDENT> path = f"/api/v1/networks/{urllib.parse.quote(ip_range)}/used_count" <NEW_LINE> history.record_get(path) <NEW_LINE> return get(path).json() | Return a count of the addresses in use on a given network | 625941c7be7bc26dc91cd64d |
def test_cli_vd(capsys): <NEW_LINE> <INDENT> main(["-vd", "2016-01-01", "2016-01-02"]) <NEW_LINE> main(["-vd", "2016-01-03", "2016-01-01"]) <NEW_LINE> out, err = capsys.readouterr() <NEW_LINE> assert out == '\n'.join(( '2016-01-01 00:00:00', '2016-01-02 00:00:00', '1 day 00:00:00', '2016-01-03 00:00:00', '2016-01-01 00... | Test CLI (-vd). | 625941c78c3a873295158405 |
def ingest_local_pose_in_map(self, pose): <NEW_LINE> <INDENT> ts = pose.timestamp <NEW_LINE> if self.init_app_ts.data_ns == 0: <NEW_LINE> <INDENT> self.init_app_ts = ts <NEW_LINE> <DEDENT> for key in list(self.cam_local_pose_map_ms.keys()): <NEW_LINE> <INDENT> if (key < (ts.get_milliseconds() - self.batch_data_retentio... | ingest_local_pose_in_map
Parameters:
pose (sl.Pose): pose of the camera | 625941c7ff9c53063f47c23f |
def get_linear_profiles(u_int, z, dz, zmax): <NEW_LINE> <INDENT> u_max = 2 * u_int / zmax**2 <NEW_LINE> u_z = u_max[:,np.newaxis] * (zmax - z)[np.newaxis,:] <NEW_LINE> scale = u_int / (u_z * dz[np.newaxis]).sum(axis=1) <NEW_LINE> return u_z * scale[:,np.newaxis] | Return transport profile U_z that decreases linearly from z=0 to
z=zmax and is constrained by u_int.
u(z) = umax when z=0
u(z) = 0 when z=zmax
\int_{z=zmax}^{z=0} u(z) dz = u_int | 625941c72c8b7c6e89b3580d |
def test_two_args_the_same(defaults): <NEW_LINE> <INDENT> defaults.update({"discordian": True}) <NEW_LINE> assert parse_args(["dateandtime", "-d", "--discordian"]) == defaults | Shouldn't make a difference. | 625941c7d164cc6175782d99 |
def prepare_history_entry(entry): <NEW_LINE> <INDENT> entry.date = str(entry.date) <NEW_LINE> return entry | Stringifies date of RepExercisesHistory entry | 625941c7a79ad161976cc191 |
def __init__(self, android=None): <NEW_LINE> <INDENT> self._android = None <NEW_LINE> self.discriminator = None <NEW_LINE> if android is not None: <NEW_LINE> <INDENT> self.android = android | OrgsorgidprojectsprojectidbuildtargetsSettingsAdvancedUnityPlayerSettings - a model defined in Swagger | 625941c782261d6c526ab4e9 |
def retrieve_and_save_last_csv_file_from_s3(self): <NEW_LINE> <INDENT> files = self.bucket.objects.all() <NEW_LINE> files = filter(lambda obj: obj.key.endswith(".csv"), files) <NEW_LINE> files_sorted = self.sort_files_by_modfied_date(files) <NEW_LINE> try: <NEW_LINE> <INDENT> last_file_added = files_sorted[0] <NEW_LINE... | Retrieve all the files in the default bucket and
filters the last one added | 625941c7cad5886f8bd27025 |
def classer(Movies): <NEW_LINE> <INDENT> classes = [[] for r in range(3)] <NEW_LINE> for r in Movies: <NEW_LINE> <INDENT> x = int((r.getRating()-4)/2) <NEW_LINE> classes[x].append(r) <NEW_LINE> <DEDENT> return classes | :param Movies:
:return: list of three classified lists with movies sorted into respective ratings class | 625941c74428ac0f6e5ba83d |
def make_video_from_images(image_path, video_path): <NEW_LINE> <INDENT> video_dir = os.path.dirname(video_path) <NEW_LINE> ffmpeg_command = [ 'ffmpeg', '-y', '-framerate', '12', '-i', os.path.join(image_path, '%06d.jpg'), '-c:v', 'libx264', '-s', '1920x1080', '-pix_fmt', 'yuv420p', '-preset', 'slower', '-crf', '23', '... | Makes a video from sequence of jpg images.
The input image names must be formatted like: '%06d.jpg', e.g. 000123.jpg.
The numbering of the image filenames must be a sequence.
Next to the output video, also the stdout and stderr of the ffmpeg
call is saved.
The video quality is set to be a good compromise for the la_pal... | 625941c73317a56b86939ca6 |
def twoSum(self, nums, target): <NEW_LINE> <INDENT> map = {} <NEW_LINE> for i, num in enumerate(nums): <NEW_LINE> <INDENT> if num not in map: <NEW_LINE> <INDENT> map[target - num] = i <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return map[num], i <NEW_LINE> <DEDENT> <DEDENT> return -i, -i | My initial solution had a loop inside a loop -I believe that
made its running time O(n^2)- to compare every number in the
list with each one of the remaining ones (with higher index).
I checked the top solution submitted by Google and I found their
brilliant solution which is to use a hash map to store each of the
num... | 625941c7167d2b6e31218be2 |
def _setlogin(self, username, password): <NEW_LINE> <INDENT> self._login_data = {'user[username]': username, 'user[password]': password, 'authenticity_token': self._fetchtoken()} | This function is used to set data for login.
.. note::
It should be called before _login() function. | 625941c7187af65679ca516a |
def __init__(self, args, jobname, filename, log_filename=None, account=None, jobid=None, **kwargs): <NEW_LINE> <INDENT> self.sbatch_args = kwargs <NEW_LINE> self.args = args <NEW_LINE> self.jobname = jobname <NEW_LINE> self.jobid = jobid <NEW_LINE> self.account = account <NEW_LINE> self.filename = filename <NEW_LINE> s... | Instantiate a marvel_job.
Parameters
---------
args : list of list of str
A list of lists, each representing a line
in the generated script.
jobname : str
Name of the job as used by SLURM.
filename : str
Absolute path where the script should be
saved.
log_filename : str, optional
Absolute path ... | 625941c7b545ff76a8913e62 |
def index(request): <NEW_LINE> <INDENT> new_state_value(request) <NEW_LINE> new_nonce_value(request) <NEW_LINE> FlowHandler.get_flow().params['state'] = request.session['state'] <NEW_LINE> return render(request, 'users/index.html', { 'user': request.user, 'auth_url': FlowHandler.get_flow().step1_get_authorize_url(), 'n... | Initial page with a link that lets us sign in through Google | 625941c715fb5d323cde0b5a |
def has_permission(self, request: HttpRequest, view): <NEW_LINE> <INDENT> return ( request.method in SAFE_METHODS and request.user.is_authenticated or request.user.is_superuser ) | Return bool. | 625941c72ae34c7f2600d17d |
def clean_email(self): <NEW_LINE> <INDENT> email_domain = self.cleaned_data['email'].split('@')[1] <NEW_LINE> if email_domain in settings.BLACKLIST_EMAIL_DOMAINS: <NEW_LINE> <INDENT> raise forms.ValidationError(_("Registration using that email address is prohibited. Please supply a different email address.")) <NEW_LINE... | Check the supplied email address against a list of known free
webmail domains. | 625941c78e05c05ec3eea3bf |
def input_select_callback(self, fnames): <NEW_LINE> <INDENT> self.cfg['meta']['is3d'] = True <NEW_LINE> if self.cfg['meta']['is3d'] : <NEW_LINE> <INDENT> baseName = (fnames[0])[0:-4] <NEW_LINE> radius = (fnames[0])[-7:-4] <NEW_LINE> self.cfg['meta']['rad'] = float(radius) <NEW_LINE> shutil.copy(self.input_dir +baseName... | Implement the callback for the input select to
process the non-standard input | 625941c76e29344779a6265e |
def get(self, pk): <NEW_LINE> <INDENT> data = get_contact_row_by_id(pk) <NEW_LINE> if not data: <NEW_LINE> <INDENT> abort(NotFound.code, message='没有记录', status=False) <NEW_LINE> <DEDENT> if data.status_delete == STATUS_DEL_OK: <NEW_LINE> <INDENT> abort(NotFound.code, message='已经删除', status=False) <NEW_LINE> <DEDENT> re... | Example:
curl http://0.0.0.0:8000/contact/1
:param pk:
:return: | 625941c71f5feb6acb0c4b9e |
def testConstruction(self): <NEW_LINE> <INDENT> vector_a = [2.3, 0.0, 0.0] <NEW_LINE> vector_b = [2.4, 3.0, 0.0] <NEW_LINE> vector_c = [0.0, 0.0, 11.8] <NEW_LINE> basis_points = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]] <NEW_LINE> cell_vectors = [vector_a, vector_b, vector_c] <NEW_LINE> cell = KMCUnitCell(cell_vectors=cell_ve... | Test the construction of the unitcell | 625941c726238365f5f0eeb9 |
def test_str_repr(self, api_objects, monkeypatch): <NEW_LINE> <INDENT> cls = api_objects.UserList <NEW_LINE> monkeypatch.setitem(cls.API_SIMPLE, "name", string_types) <NEW_LINE> child_cls = api_objects.User <NEW_LINE> obj = cls() <NEW_LINE> assert "UserList" in format(obj) <NEW_LINE> assert "UserList" in repr(obj) <NEW... | Test obj with setattr has proper str/repr. | 625941c7f8510a7c17cf9748 |
def resnet50(**kwargs): <NEW_LINE> <INDENT> model = ResNet3D(Bottleneck, [3, 4, 6, 3], **kwargs) <NEW_LINE> return model | Constructs a ResNet-50 model.
| 625941c75f7d997b87174ae2 |
def vmd_draw_arrow(molid, start, end, cylinder_radius=0.4, cone_radius=1.0, cone_length=0.15, resolution=50, double_arrow=False, vmd_material="Basic1Pantone", drawcolor="blue", lstyle="solid"): <NEW_LINE> <INDENT> graphics.material(molid, vmd_material) <NEW_LINE> graphics.color(molid, drawcolor) <NEW_LINE> p_vector = e... | Draws an arrow from start to end using the arrow color and a certain radius
for the cylinder and the cone (top).
Draw cylinder of 90 % of the max length and the tip from 75 % of the total
arrow length.
Input:
> molid int; id of the molecule to draw the arrow to
> start np-array; (1,3)-t... | 625941c78a349b6b435e81bf |
def packet(self, packet, pre_encoded=False): <NEW_LINE> <INDENT> if self.engine_socket.ready_state == EngineSocket.STATE_OPEN: <NEW_LINE> <INDENT> self.debug('writing packet %s' % str(packet)) <NEW_LINE> if not pre_encoded: <NEW_LINE> <INDENT> encoded_packets = self.encoder.encode(packet) <NEW_LINE> <DEDENT> else: <NEW... | Send out a packet
:param packet: The packet
:param pre_encoded: Whether the packet is pre encoded.
:return: | 625941c75f7d997b87174ae3 |
def mark_ship(ship, marker, board): <NEW_LINE> <INDENT> if ship.orientation != 'v': <NEW_LINE> <INDENT> index = ship.col_idx <NEW_LINE> max_idx = ship.col_idx + ship.size <NEW_LINE> while index < max_idx: <NEW_LINE> <INDENT> board.put_value_at_place( col_idx=index, row_idx=ship.row_idx, value=marker) <NEW_LINE> index +... | The ship is marked with a provided marker on the specified board. | 625941c76e29344779a6265f |
def initUI(self) -> None: <NEW_LINE> <INDENT> self.editorWidget = self.__class__.EditorWidgetClass() <NEW_LINE> self.setCentralWidget(self.editorWidget) <NEW_LINE> self.editorWidget.scene.addHasBeenModifiedListener(self.updateTitle) <NEW_LINE> self.createActions() <NEW_LINE> self.createMenus() <NEW_LINE> self.createSta... | Set up this ``QMainWindow``.
Create :class:`~nodedge.editor_widget.EditorWidget`, Actions and Menus | 625941c723849d37ff7b30dc |
def test_TFoutput(self): <NEW_LINE> <INDENT> with open(self.TFout, "w") as output_handle: <NEW_LINE> <INDENT> output_handle.write(self.m.format("transfac")) | Ensure that we can write proper TransFac output files. | 625941c7f9cc0f698b140648 |
def computeRMSE(errors): <NEW_LINE> <INDENT> errors_flat = errors.ravel() <NEW_LINE> return math.sqrt( errors_flat.dot( errors_flat ) / len( errors ) ) | @brief compute root mean square error for a collection of 2D error (distance) tuples.
@return square root of the sum of squared errors
\sqrt{rac{\sum_{i}^{n}e\left(\mathbf{x}_{i},\hat{\mathbf{x}}_{i}
ight)^{2}}{n}}
where error is defined as the euclidean distance
e\left(\mathbf{x},\hat{\mathbf{x}}
ight)=\sqr... | 625941c729b78933be1e56f9 |
def import_image_handler( uow: unit_of_work.ImageUnitOfWork, cmd: commands.ImportImage ) -> None: <NEW_LINE> <INDENT> with uow: <NEW_LINE> <INDENT> uow.import_image(cmd.in_path) | Import a container image. | 625941c791f36d47f21ac53d |
def getRankIdOfTaxonId(self, taxonId): <NEW_LINE> <INDENT> rankId = self._taxonIdToRankId.get(taxonId, None) <NEW_LINE> if rankId is None: <NEW_LINE> <INDENT> rank = self._taxonomy.getRank(taxonId) <NEW_LINE> rankId = self._rankToRankId.get(rank, None) <NEW_LINE> self._taxonIdToRankId[taxonId] = rankId <NEW_LINE> <DEDE... | @return: rankId of the taxonId (ids correspond to method getRankId)
@rtype: int | 625941c792d797404e3041d6 |
def analyze_aux(self,v_type='value',parameter = 'WetZ',sampling=1800,force=False,begin=None,end=None,gps_only=False): <NEW_LINE> <INDENT> begin_date, end_date = check_date_margins(begin=begin, end=end, years_list=self.years_list) <NEW_LINE> eterna_gathers_dir = _os.path.join(self.tmp_dir,'gd2e','eterna_gathers') <NEW_... | If gather file doesn't exist - run with force as exec dirs are shared between v_types
parameters = ['GradEast','GradNorth','WetZ','Clk']
analyze_wetz(self,wetz_gather=None,begin=None,end=None,sampling=1800,force=False,return_sets=False,otl_env=False,v_type='value') | 625941c794891a1f4081baf5 |
def get_digital_latch_data(self, pin): <NEW_LINE> <INDENT> return self._command_handler.get_digital_latch_data(pin) | A list is returned containing the latch state for the pin, the latched value, and the time stamp
[pin_num, latch_state, latched_value, time_stamp]
If the the latch state is LATCH_LATCHED, the table is reset (data and timestamp set to zero)
@param pin: Pin number.
@return: [pin, latch_state, latch_data_value, time_stamp... | 625941c763f4b57ef0001168 |
def fista(X, D, lmbd, max_iter, z0=None, verbose=0): <NEW_LINE> <INDENT> f_cost = LossL2(X, D) <NEW_LINE> if z0 is None: <NEW_LINE> <INDENT> zk = f_cost.get_z0() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> zk = np.copy(z0) <NEW_LINE> <DEDENT> momentum = 1 <NEW_LINE> y = zk <NEW_LINE> _cost_model = cost_network((X.sha... | Fast ISTA for X and D
Parameters
----------
X (array-like - (N, p)): data to compute the sparse code.
There is N samples in a p dimensional space.
D (array-like - (K, p)): dictionary to compute the sparse code.
There is K atoms constituted by p-dimensional points.
lmbd (float): regularization parameter for the... | 625941c78e71fb1e9831d7f6 |
def _qj_extractFullyBifurcatingTree(self, aTree): <NEW_LINE> <INDENT> theTree = aTree.dupe() <NEW_LINE> PP = [] <NEW_LINE> for n in theTree.iterNodes(): <NEW_LINE> <INDENT> if n.isLeaf: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif n == theTree.root: <NEW_LINE> <INDENT> nCh = n.getNChildren() <NEW_LINE> if nCh > 3:... | Dupe the tree, and remove leaves until it is fully bifurcating.
Tries to make the biggest possible fully bifurcating tree. | 625941c750812a4eaa59c36f |
@deprecated_args(number="total", repeat=None) <NEW_LINE> def UnCategorizedCategoryGenerator(total=100, site=None): <NEW_LINE> <INDENT> if site is None: <NEW_LINE> <INDENT> site = pywikibot.Site() <NEW_LINE> <DEDENT> for page in site.uncategorizedcategories(total=total): <NEW_LINE> <INDENT> yield page | Uncategorized category generator.
@param total: Maxmum number of pages to retrieve in total
@type total: int
@param site: Site for generator results.
@type site: L{pywikibot.site.BaseSite} | 625941c7a17c0f6771cbe09d |
@mod.route("/mlb/", methods=["GET"]) <NEW_LINE> @mod.route("/mlb/<int:year>/<int:month>/<int:day>/", methods=["GET"]) <NEW_LINE> def mlb(year=None, month=None, day=None): <NEW_LINE> <INDENT> return jsonify(scores_helper(year, month, day, "mlb")) | Fetches scoring information for the Major League Baseball | 625941c791f36d47f21ac53e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.