content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_list_channels(sc): """Get list of channels.""" # https://api.slack.com/methods/channels.list response = sc.api_call( "channels.list", ) return response['channels']
d31271bcc065b4a212e298c6283c4d658e5547da
21,133
def error_handler(error): """エラーメッセージを生成するハンドラ""" response = jsonify({ 'cause': error.description['cause'] }) return response, error.code
282b1a11d8e7326be1fa2d0b1b2457dc5d5d5ca1
21,134
def search_records( name: str, search: TextClassificationSearchRequest = None, common_params: CommonTaskQueryParams = Depends(), include_metrics: bool = Query( False, description="If enabled, return related record metrics" ), pagination: PaginationParams = Depends(), service: TextCla...
7dd932131f5fda1680fd419697df9c0a04d19fa5
21,135
def guess_udic(dic,data): """ Guess parameters of universal dictionary from dic, data pair. Parameters ---------- dic : dict Dictionary of JCAMP-DX, acqu, proc and spectrum parameters. data : ndarray Array of NMR data. Returns ------- udic : dict Univers...
a8d79255b34f407ea54766ec2e4aedaf2ae42df9
21,136
def matchPosAny (msg, pos, rules, subrules): """Indicates whether or not `msg` matches any (i.e. a single) `subrule` in `rules`, starting at position `pos`. Returns the position in `msg` just after a successful match, or -1 if no match was found. """ index = -1 for rule in subrules: ...
6ad053cdb61d7cc917e3acb896ea5d23cc042de9
21,137
def compute_accuracy(model, loader): """ :param model: a model which returns classifier_output and segmentator_output :param loader: data loader """ model.eval() # enter evaluation mode score_accum = 0 count = 0 for x, y, _, _ in loader: classifier_output, _ = model(x) ...
ecc86c3c9c2429843bdd25023b3c6f0393c83db9
21,138
from operator import and_ def create_base_query_grouped_fifo(rse_id, filter_by_rse='destination', session=None): """ Build the sqlalchemy queries to filter relevant requests and to group them in datasets. Group requests either by same destination RSE or source RSE. :param rse_id: The RSE id...
e4399a447e767610c7451f61ad543553168de1d6
21,139
def then(state1, state2): """ Like ``bind``, but instead of a function that returns a statetful action, just bind a new stateful action. Equivalent to bind(state1, lambda _: state2) """ return bind(state1, lambda _: state2)
ef6200f8776b84a5a9893b894b3d7cd406598f7d
21,140
from typing import Optional from typing import Dict from typing import Any def get_skyregions_collection(run_id: Optional[int]=None) -> Dict[str, Any]: """ Produce Sky region geometry shapes JSON object for d3-celestial. Args: run_id (int, optional): Run ID to filter on if not None. Returns:...
8d8fe2e46a9d37e774dbdab506f012a0560796e1
21,141
def construct_sru_query(keyword, keyword_type=None, mat_type=None, cat_source=None): """ Creates readable SRU/CQL query, does not encode white spaces or parenthesis - this is handled by the session obj. """ query_elems = [] if keyword is None: raise TypeError("query argument cannot be N...
fbe28156beca73339fa88d200777e25172796864
21,142
def sitemap_xml(): """Default Sitemap XML""" show_years = retrieve_show_years(reverse_order=False) sitemap = render_template("sitemaps/sitemap.xml", show_years=show_years) return Response(sitemap, mimetype="text/xml")
e6be9c98d1a1cd4bbfb04e9ad9676cc4b8521d79
21,143
def remove_property(product_id, property_id): """ Remove the property """ property = db.db.session.query(TypeProperty).\ filter_by(product_id = product_id, product_property_id = property_id).first() try: db.db.session.delete(property) db.db.session.commit() except Exception as e: db.db.session.rollback()...
cca8822d5b7de3ca8ee9b451fe21d4ddeb20e736
21,144
def format_solution_table_calc(solution, node_ids_to_nodes): """ :type solution: dict[int, list[int]] :type node_ids_to_nodes: dict[int, int] :rtype: dict[int, str] """ new_solution = {} for (color, path) in solution.items(): new_path = [] for p in path: back_p = ...
335bc0e90860a9181d5b819a5bb9e44cd44f750d
21,145
import functools def hashable(func): """Decorator for functions with numpy arrays as input arguments that will benefit from caching Example: from midgard.math import nputil from functools import lru_cache @nputil.hashable @lru_cache() def test_func(a: np.ndarray, b: np.ndarray = None) ...
db23cc12f9a322aaae6a585068a5c30194d7be7b
21,146
def object_hash(fd, fmt, repo=None): """ Function to read the content of a open file, create appropiate object and write the object to vcs directory and return the hash of the file""" data = fd.read() # choosing constructor on the basis of the object type found in header if fmt == b'commit' ...
b55a4da36934843c111e4d66dc552c556c8d0ba4
21,148
import io def read_from_pdf(pdf_file): """ 读取PDF文件内容,并做处理 :param pdf_file: PDF 文件 :return: pdf文件内容 """ # 二进制读取pdf文件内的内容 with open(pdf_file, 'rb') as file: resource_manage = PDFResourceManager() return_str = io.StringIO() lap_params = LAParams() # 内容转换 ...
140d4545f952983017d175303397c494457b4628
21,149
def _descending(dbus_object): """ Verify levels of variant values always descend by one. :param object dbus_object: a dbus object :returns: None if there was a failure of the property, otherwise the level :rtype: int or NoneType None is a better choice than False, for 0, a valid variant level,...
55de473807c22c50d8f65597cde390a56dcb9cd6
21,150
def _is_avconv(): """ Returns `True` if the `ffmpeg` binary is really `avconv`. """ out = _run_command(['ffmpeg', '-version']) return out and isinstance(out, strtype) and 'DEPRECATED' in out
dc9003623b4497b75d37f4e759f31401ad6261e1
21,151
def countries(request): """ Returns all valid countries and their country codes """ return JsonResponse({ "countries": [{ "id": unicode(code), "name": unicode(name) } for code, name in list(django_countries.countries)] })
20296279dea898741950715a41b4188f7f5e6724
21,152
def generate_monomer(species, monomerdict, initlen, initnames, tbobs): """ generate a PySB monomer based on species :param species: a Species object :param monomerdict: a dictionary with all monomers linked to their species id :param initlen: number of the initial species :param initnames: name...
2966473ef084991d0c589c16a8479f6395702b43
21,154
import logging import tqdm def convert_bert_tokens(outputs): """ Converts BERT tokens into a readable format for the parser, i.e. using Penn Treebank tokenization scheme. Does the heavy lifting for this script. """ logging.info("Adjusting BERT indices to align with Penn Treebank.") mapped_outp...
27cef75fc48fb87e20f77af95e265406c6b8c520
21,155
def calculate_iou(ground_truth_path, prediction_path): """ Calculate the intersection over union of two raster images. Args: ground_truth_path (str): Path to the ground truth raster image. prediction_path (str): Path to the prediction raster image. Returns: float: The intersection ov...
70e49e787fe57f5c4d94a043d41b96de1b14fd39
21,157
from bokeh.models import ColumnDataSource import warnings def bokeh_scatter(x, y=None, *, xlabel='x', ylabel='y', title='', figure=None, data=None, saveas='scatter', ...
d2bf64efcd751f3dea0d63c1c02af14952684bd7
21,158
from utils.format import format_output from utils.rule import get_all_rules from utils.type import check_type from utils.rule import get_rules from core.exceptions import RuleArgumentsError from utils.type import update_type, check_type from utils.rule import add_rule from core.exceptions import RuleArgumentsError from...
991873d489486b5e6ffc9676a2d9a6e5af9e944b
21,159
def superposition_training_mnist(model, X_train, y_train, X_test, y_test, num_of_epochs, num_of_tasks, context_matrices, nn_cnn, batch_size=32): """ Train model for 'num_of_tasks' tasks, each task is a different permutation of input images. Check how accuracy for original images is changing through tasks us...
e0e837c3a92e047ce894c166d09e2ce6a58b3035
21,160
import json def json2dict(astr: str) -> dict: """将json字符串转为dict类型的数据对象 Args: astr: json字符串转为dict类型的数据对象 Returns: 返回dict类型数据对象 """ return json.loads(astr)
f13b698dcf7dda253fd872bb464594901280f03b
21,161
from typing import Any def any(wanted_type=None): """Matches against type of argument (`isinstance`). If you want to match *any* type, use either `ANY` or `ANY()`. Examples:: when(mock).foo(any).thenReturn(1) verify(mock).foo(any(int)) """ return Any(wanted_type)
4c92d19a2168f815a88f2fa8aa56f0d656a5a534
21,162
def list_top_level_blob_folders(container_client): """ List all top-level folders in the ContainerClient object *container_client* """ top_level_folders,_ = walk_container(container_client,max_depth=1,store_blobs=False) return top_level_folders
baf41750aae23df6d051986f24814d0f286afb6b
21,163
import string def keyword_encipher(message, keyword, wrap_alphabet=KeywordWrapAlphabet.from_a): """Enciphers a message with a keyword substitution cipher. wrap_alphabet controls how the rest of the alphabet is added after the keyword. 0 : from 'a' 1 : from the last letter in the sanitised keyword ...
155e997e1199f4adb25e20ad2c6e0047ffc7f7fd
21,164
import PIL def plt_to_img(dummy: any = None, **kwargs) -> PIL.Image.Image: """ Render the current figure as a (PIL) image - Take dummy arg to support expression usage `plt_to_img(...)` as well as statement usage `...; plt_to_img()` """ return PIL.Image.open(plot_to_file(**kwargs))
d07be803a2f3c71fa62b920c0a72954578d24f59
21,165
def _escape_char(c, escape_char=ESCAPE_CHAR): """Escape a single character""" buf = [] for byte in c.encode('utf8'): buf.append(escape_char) buf.append('%X' % _ord(byte)) return ''.join(buf)
a4f4c69eb51a338d54b685336c036d991c295666
21,166
def error_log_to_html(error_log): """Convert an error log into an HTML representation""" doc = etree.Element('ul') for l in error_log: if l.message.startswith('<runtrace '): continue el = etree.Element('li') el.attrib['class'] = 'domain_{domain_name} level_{level_name} ty...
d2df223a0be82c5f58cf57be504833061d1afd40
21,167
def get_scheduler(optimizer, opt): """Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.  opt.lr_policy is the name of learning...
b8996d9963533249f1b387a36bac3f209e70daff
21,168
def train_PCA(data, num_components): """ Normalize the face by subtracting the mean image Calculate the eigenValue and eigenVector of the training face, in descending order Keep only num_components eigenvectors (corresponding to the num_components largest eigenvalues) Each training face is represent...
2404fca9fe053c275b187e2435b497166ed7f4d8
21,171
def count_revoked_tickets_for_party(party_id: PartyID) -> int: """Return the number of revoked tickets for that party.""" return db.session \ .query(DbTicket) \ .filter_by(party_id=party_id) \ .filter_by(revoked=True) \ .count()
6ad857a4630d2add7d2d46b9e930178a18f89e29
21,172
def get_data(data_x, data_y): """ split data from loaded data :param data_x: :param data_y: :return: Arrays """ print('Data X Length', len(data_x), 'Data Y Length', len(data_y)) print('Data X Example', data_x[0]) print('Data Y Example', data_y[0]) train_x, test_x, train_y, test_y...
a40406da641b36784719da3c3e375130e013e889
21,175
async def api_download_profile() -> str: """Downloads required files for the current profile.""" global download_status assert core is not None download_status = {} def update_status(url, path, file_key, done, bytes_downloaded, bytes_expected): bytes_percent = 100 if (bytes_expecte...
0dd6aaf17b49f8e48eb72c8adf726f2852937f18
21,176
def cumulative_segment_wrapper(fun): """Wrap a cumulative function such that it can be applied to segments. Args: fun: The cumulative function Returns: Wrapped function. """ def wrapped_segment_op(x, segment_ids, **kwargs): with tf.compat.v1.name_scope( Non...
5471e525ab73855927fe04530b8ec6e14a4436d9
21,177
from typing import Any def read_pet_types( skip: int = 0, limit: int = 100, db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_active_superuser) ) -> Any: """ Read pet types :return: """ if not crud.user.is_superuser(current_use...
60de7c25b305bbb1a628db27559bcdb3abc5fb24
21,178
def get_approves_ag_request(): """Creates the prerequisites for - and then creates and returns an instance of - ApprovesAgRequest.""" # Creates an access group request and an approver (required to create an instance of ApprovesAgRequest). agr = AccessGroupRequest(reader=None, ag=None, justification=MAGIC_STRING) a...
139900d7948b4bd836410be09ba35a21954f2dc4
21,179
import requests def currency_history( base: str = "USD", date: str = "2020-02-03", api_key: str = "" ) -> pd.DataFrame: """ Latest data from currencyscoop.com https://currencyscoop.com/api-documentation :param base: The base currency you would like to use for your rates :type base: str :pa...
ed8c547e433a7f08e67863aca86b991bd746ccbb
21,180
from typing import Type from typing import Dict def _ref_tier_copy(source_eaf: Type[Eaf] = None, target_eaf: Type[Eaf] = None, source_tier_name: str = "", target_tier_name: str = "", target_parent_tier_name: str = "", overr...
f0c2fe27446d4a1f992f33c7610bc177d0e2c896
21,184
def fibonacci(length=10): """Get fibonacci sequence given it length. Parameters ---------- length : int The length of the desired sequence. Returns ------- sequence : list of int The desired Fibonacci sequence """ if length < 1: raise ValueError("Sequence le...
afa3ef63a663b4e89e5c4a694315083debdbab59
21,185
def get_direct_hit_response(request, query, snuba_params, referrer): """ Checks whether a query is a direct hit for an event, and if so returns a response. Otherwise returns None """ event_id = normalize_event_id(query) if event_id: snuba_args = get_snuba_query_args( query=u'...
4ffc0dcd5dbac56fc60e2414c1952e629f1fc951
21,187
from typing import List from typing import Tuple from typing import Set def _canonicalize_clusters(clusters: List[List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: """ The data might include 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are ...
d8435e6859e1f9720d7a6f1ec7dd1e2d51df5502
21,189
def remove_outliers(matches, keypoints): """ Calculate fundamental matrix between 2 images to remove incorrect matches. Return matches with outlier removed. Rejects matches between images if there are < 20 :param matches: List of lists of lists where matches[i][j][k] is the kth cv2.Dmatch object for im...
53b70f98389a33ba6a28c65fab8862bc629d2f0d
21,190
def err_comp(uh, snap, times_offline, times_online): """ Computes the absolute l2 error norm and the rms error norm between the true solution and the nirom solution projected on to the full dimensional space """ err = {} w_rms = {} soln_names = uh.keys() # ky = list(uh.keys())[0] ...
d64b061ec1cb3f8d7e9247cc5a74c4b6b852bc3b
21,191
from datetime import datetime def calc_stock_state(portfolio,code:int,date:datetime,stocks,used_days:int): """ 状態を計算 - 株価・テクニカル指標・出来高の時系列情報 - 総資産、所持株数 Args: stocks: 単元株数と始値、終値、高値、低値、出来高を含む辞書を作成 used_days: 用いる情報の日数 """ stock_df=stocks[code]['prices'] date=datetime(date.year,dat...
7aec335e15d5c169bfbaf7995614c532c31bd353
21,192
def lowercase_words(words): """ Lowercases a list of words Parameters ----------- words: list of words to process Returns ------- Processed list of words where words are now all lowercase """ return [word.lower() for word in words]
b6e8658f35743f6729a9f8df229b382797b770f6
21,193
def convert_images_to_arrays_train(file_path, df): """ Converts each image to an array, and appends each array to a new NumPy array, based on the image column equaling the image file name. INPUT file_path: Specified file path for resized test and train images. df: Pandas DataFrame being...
bab9ccc350c891d8c8dc634a431309490533f8ad
21,194
def get_projection_matrix(X_src, X_trg, orthogonal, direction='forward', out=None): """ X_src: ndarray X_trg: ndarray orthogonal: bool direction: str returns W_src if 'forward', W_trg otherwise """ xp = get_array_module(X_src, X_trg) if orthogonal: if direction == 'forwar...
ef7f722e6beeb652069270afd81315a951d2a925
21,195
def _standardize_df(data_frame): """ Helper function which divides df by std and extracts mean. :param data_frame: (pd.DataFrame): to standardize :return: (pd.DataFrame): standardized data frame """ return data_frame.sub(data_frame.mean(), axis=1).div(data_frame.std(), axis=1)
cbe0e1f5c507181a63193a4e08f4ed8139d9e129
21,196
def has_edit_metadata_permission(user, record): """Return boolean whether user can update record.""" return EditMetadataPermission(user, record).can()
fd2a60d27151181c02d5a0fb6548f28beaa5b2b3
21,197
def truncate_chars_middle(text, limit, sep="..."): """ Truncates a given string **text** in the middle, so that **text** has length **limit** if the number of characters is exceeded, or else **len(text)** if it isn't. Since this is a template filter, no exceptions are raised when they would normally do....
e08e6ec0b3522104d54e6690361d6ecf297f5566
21,198
import re def parse_block(block, site_name, site_num, year): """Parse a main data block from a BBC file""" # Cleanup difficult issues manually # Combination of difficult \n's and OCR mistakes replacements = {'Cemus': 'Census', 'Description of plot': 'Description of Plot', ...
0a367e9163d1136ec725560156d67c05ca1c1d38
21,199
def isempty(s): """ return if input object(string) is empty """ if s in (None, "", "-", []): return True return False
9c3ffd6ab818e803c1c0129588c345361c58807f
21,200
def raw(text): """Returns a raw string representation of text""" new_str = '' for char in text: try: new_str += trans_map[char] except KeyError: new_str += char return new_str
528e88837bba76411b44044b566e2a645db4433e
21,202
def airtovac(wave_air): """ taken from idl astrolib ;+ ; NAME: ; AIRTOVAC ; PURPOSE: ; Convert air wavelengths to vacuum wavelengths ; EXPLANATION: ; Wavelengths are corrected for the index of refraction of air under ; standard conditions. Wavelength values below...
68d71855f0fa8256acc23bfd24d68985cfc1f3a7
21,203
def clamp(val, min_, max_): """clamp val to between min_ and max_ inclusive""" if val < min_: return min_ if val > max_: return max_ return val
31f2441ba03cf765138a7ba9b41acbfe21b7bda7
21,204
def GetUserLink(provider, email): """Retrieves a url to the profile of the specified user on the given provider. Args: provider: The name of the provider email: The email alias of the user. Returns: Str of the url to the profile of the user. """ user_link = '' if email and provider == Provider....
ad5f30e7e04000369d45d242b18afc59922da9bc
21,205
def _as_bytes0(path): """Crashes translation if the path contains NUL characters.""" res = _as_bytes(path) rstring.check_str0(res) return res
76c9c130d1a74f9cacb34e30141db74400f6ea33
21,206
def get_ip(request): """Determines user IP address Args: request: resquest object Return: ip_address: requesting machine's ip address (PUBLIC) """ ip_address = request.remote_addr return ip_address
84e1540bc8b79fd2043a8fb6f107f7bcd8d7cc8c
21,207
def _is_valid_new_style_arxiv_id(identifier): """Determine if the given identifier is a valid new style arXiv ID.""" split_identifier = identifier.split('v') if len(split_identifier) > 2: return False elif len(split_identifier) == 2: identifier, version = split_identifier if not...
71171984ad1497fa45e109b9657352c20bfe7682
21,208
def download_suite(request, domain, app_id): """ See Application.create_suite """ if not request.app.copy_of: request.app.set_form_versions(None) return HttpResponse( request.app.create_suite() )
382817e3a790d59c33c69eb5334841d2d9a1a7af
21,209
def get_graph(mol): """ Converts `rdkit.Chem.Mol` object to `PreprocessingGraph`. """ if mol is not None: if not C.use_aromatic_bonds: rdkit.Chem.Kekulize(mol, clearAromaticFlags=True) molecular_graph = PreprocessingGraph(molecule=mol, constants=C) return molecular_graph
3d105de313ab1aed6ed0fff598e791cd903e94de
21,210
def dict_fetchall(cursor): """ Returns all rows from a cursor as a dict """ desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]
6d5e6621ac2cb6229f7caf6714cbc0124a33c271
21,211
def count_vowels(s): """Used to count the vowels in the sequence""" s = s.lower() counter=0 for x in s: if(x in ['a','e','i','o','u']): counter+=1 return counter
236500c76b22510e6f0d97a4200865e2a18b47c3
21,212
def _is_valid_dtype(matrix, complex_dtype=False, all_dtype=False): """ Check to see if it's a usable float dtype """ if all_dtype: return matrix.dtype in NUMPY_FLOAT_DTYPES + NUMPY_COMPLEX_DTYPES elif complex_dtype: return matrix.dtype in NUMPY_COMPLEX_DTYPES else: return matrix....
1ca4a79082f170f53a905773b42fa8cb833e4016
21,213
def assess_edge(self, edge, fsmStack, request, **kwargs): """ Try to transition to ASSESS, or WAIT_ASSESS if not ready, or jump to ASK if a new question is being asked. """ fsm = edge.fromNode.fsm if not fsmStack.state.linkState: # instructor detached return fsm.get_node('END') elif...
e09d07afbc37c73188bbb5e6fa3436c88fce9bd7
21,214
def viable_source_types_for_generator_real (generator): """ Returns the list of source types, which, when passed to 'run' method of 'generator', has some change of being eventually used (probably after conversion by other generators) """ source_types = generator.source_types () if not s...
e946663241fb77d3632f88b2f879d650e65f6d73
21,215
def negSamplingCostAndGradient(predicted, target, outputVectors, dataset, K=10): """ Negative sampling cost function for word2vec models Implement the cost and gradients for one predicted word vector and one target word vector as a building block for word2vec models, usin...
d4b8a16166406f9e13296b8b5c53c56f95ff9d6b
21,216
def get_start_block(block): """ Gets the deepest block to use as the starting block. """ if not block.get('children'): return block first_child = block['children'][0] return get_start_block(first_child)
e658954bb69f88f10c2f328c605d6da094ba065d
21,217
def transform_rank_list(lam_ref, A, b, rank): """ A is a list here. We sum the first `rank` elements of it to return a matrix with the desired rank. """ _A = sum(A[0:rank]) _b = b _d = _A @ lam_ref + _b assert np.linalg.matrix_rank(_A) == rank, "Unexpected rank mismatch" return _A, _...
2b77db3cb27ce3b66d0038042d649226e5a231d2
21,218
def FindWindowsWithTitle(title_to_search): """Finds windows with given title. Args: title_to_search: Window title substring to search, case-insensitive. Returns: A list of HWND that match the search condition. """ desktop_handle = None return FindWindowsWithText(desktop_handle, title_to_search)
bcc75a4351969cfdbb475032d556e73a4b0ceb92
21,219
import time def main_update(next_image_step): """ This includes some functionality for image / file writing at a specified frequency, Assumes global variables: time, step, files_freq, next_image_step if numerical dt exceeds next specified writing point override dt make sure we hi...
6a402c70948dc90aade783b94b054ef5abf8225c
21,220
def assemble_batches(inputs, crop_mode='center_only'): """ Assemble DataFrame of image crops for feature computation. Input: inputs: list of filenames (center_only, corners, and selective_search mode) OR input DataFrame (list mode) mode: string 'list': take the image windows from the input as...
f22f3ed33b339a4375a1e3319d26cb2946762978
21,222
def __VF2_feasible(graph1, graph2, vertex1, vertex2, map21, map12, terminals1, terminals2, subgraph): """ Returns :data:`True` if two vertices `vertex1` and `vertex2` from graphs `graph1` and `graph2`, respectively, are feasible matches. `mapping21` and `mapping12` are the current state of the mappi...
f3ebfa379d710f5e1c6651713c15e9c6148d576d
21,223
async def place_rectangle( interface, element, x, y, width, height, include_all_sides=True, variant=None ): """Place a rectangle of an element. Parameters ---------- interface The editor interface. x X coordinate of the upper left corner. y Y coordinate of the upper ...
e9b2c16e77627dc3e0cac5f0abfcdce23db5eb29
21,224
def calc_Q_hat_hs_d_t(Q, A_A, V_vent_l_d_t, V_vent_g_i, mu_H, mu_C, J_d_t, q_gen_d_t, n_p_d_t, q_p_H, q_p_CS, q_p_CL, X_ex_d_t, w_gen_d_t, Theta_ex_d_t, L_wtr, region): """(40-1a)(40-1b)(40-2a)(40-2b)(40-2c)(40-3) Args: Q: 当該住戸の熱損失係数(W/(m2・K)) A_A: 床面積の合計(m2) V_vent_l_d_t: 日付dの時刻tにおける局所換気量(m3...
64dd272673507b15a2d2c1782a0c3db88c3f8d76
21,226
def get_all_infoproviders(): """ Endpunkt `/infoproviders`. Response enthält Informationen über alle, in der Datenbank enthaltenen, Infoprovider. """ try: return flask.jsonify(queries.get_infoprovider_list()) except Exception: logger.exception("An error occurred: ") err ...
73966c2a5b171baead9edccec27f6380f61fb2ab
21,227
import math def maidenhead(dec_lat, dec_lon): """Convert latitude and longitude to Maidenhead grid locators.""" try: dec_lat = float(dec_lat) dec_lon = float(dec_lon) except ValueError: return '' if _non_finite(dec_lat) or _non_finite(dec_lon): return '' if 90 < ma...
63e44fffbf113f7c8a195b58556eef80a66690f7
21,228
def parse_worker_string(miner, worker): """ Parses a worker string and returns the coin address and worker ID Returns: String, String """ worker_part_count = worker.count(".") + 1 if worker_part_count > 1: if worker_part_count == 2: coin_address, worker = worker.s...
3492716fc9f5290a161de0b46e7af87afbe6b348
21,229
import json def get_inference_sequence(file_path): """ :param file_path: path of 2D bounding boxes :return: """ with open(file_path + '.json', 'r') as f: detected_bdbs = json.load(f) f.close() boxes = list() for j, bdb2d in enumerate(detected_bdbs): box = bdb2d['bbo...
a77b5f24004acf9839881cd52ce06b6f785f9bfb
21,230
def _DC_GetBoundingBox(self): """ GetBoundingBox() -> (x1,y1, x2,y2) Returns the min and max points used in drawing commands so far. """ return (self.MinX(), self.MinY(), self.MaxX(), self.MaxY())
47dc9e8bbc429dbd079695844c9bbcfc79b26229
21,231
from typing import Union from typing import Iterable from typing import List def map_text( text: Union[str, Text, Iterable[str], Iterable[Text]], mapping: StringMapper ) -> Union[str, List[str]]: """ Replace text if it matches one of the dictionary keys. :param text: Text instance(s) to m...
63c9dc6803d1aad572e76cb2a6554363ae358e9c
21,232
def _load_components(config: ConfigType) -> ConfigType: """Load the different componenets in a config Args: config (ConfigType) Returns: ConfigType """ special_key = "_load" if config is not None and special_key in config: loaded_config = read_config_file(config.pop(spe...
b00e2225df4d493636c509380c3c19c107ad32e6
21,233
import typing def _value_to_variant(value: typing.Union[bytes, int, float, str]) -> GLib.Variant: """ Automatically convert a Python value to a GLib.Variant by guessing the matching variant type. """ if isinstance(value, bool): return GLib.Variant("b", value) elif isinstance(value, by...
8b16bad781954238174a160df5239c0b8cb88e2e
21,234
import math def ha_rise_set(el_limit, lat, dec): """ Hour angle from transit for rising and setting. Returns pi for a source that never sets and 0 for a source always below the horizon. @param el_limit : the elevation limit in radians @type el_limit : float @param lat : the observatory latitude in r...
648de7a69039d73f3947706ecc4ee90e1d05597e
21,235
def create(transactions, user=None): """# Create Transactions Send a list of Transaction objects for creation in the Stark Bank API ## Parameters (required): - transactions [list of Transaction objects]: list of Transaction objects to be created in the API ## Parameters (optional): - user [Proje...
32573a0e569fde73c6eaf228ad6a07849297c7b9
21,236
def get_quote(symbol): """ Returns today's stock price """ contents = get_content(symbol) return contents('.time_rtq_ticker span').text()
546ac10e5f7d5b3cc661dde5dceec8c4a8b0fae0
21,237
def load_pil(data, is_file = False): """ Parses a string or file written in PIL notation! """ # We only assign reactions in a postprocessing step, # because there are no macrostates in nuskell. set_io_objects(D = NuskellDomain, C = NuskellComplex) out = dsd_read_pil(data, is_file) clear_io_objec...
0fe0b507d19595f71d18d24e1f003fbaa59485fc
21,238
def get(obj, key, default=None, pattern_default=(), apply_transforms=True): """ Get a value specified by the dotted key. If dotted is a pattern, return a tuple of all matches >>> d = {'hello': {'there': [1, '2', 3]}} >>> get(d, 'hello.there[1]|int') 2 >>> get(d, 'hello.there[1:]') ['2', ...
b6b84a357e18fa0e78d6520ba50ff5668a97067c
21,239
def str_view(request): """ A simple test view that returns a string. """ return '<Response><Message>Hi!</Message></Response>'
fd9d150afdf0589cdb4036bcb31243b2e22ef1e2
21,240
import atexit def _run_script(script, start_with_ctty, args, kwargs): """ Meant to be called inside a python subprocess, do NOT call directly. """ enter_pty(start_with_ctty) result = script(*args, **kwargs) # Python-spawned subprocesses do not call exit funcs - https://stackoverflow.com/q/3450...
15507307bb85013d9354b7506569b69806bdf06a
21,241
def get_feed_list(feeds): """ Return List of Proto Feed Object """ feeds_pb_list = [feeds_pb2.Feed(**_get_valid_fields_feed(feed)) for feed in feeds] return feeds_pb2.FeedList(data=feeds_pb_list)
6e79c563649aef60396f0c8944d3532fabc17bc0
21,242
def group_interpellet_interval_plot(FEDs, groups, kde, logx, **kwargs): """ FED3 Viz: Plot the interpellet intervals as a histogram, first aggregating the values for devices in a Groups. Parameters ---------- FEDs : list of FED3_File objects FED3 files (loaded by load.FED3_File) gro...
5c0ada4fdf71af7cfed8ffe7ec8b656c8984de9b
21,243
def _beta(x, p): """Helper function for `pdf_a`, beta = pi * d(1 - omega(x), omega(p)).""" omega = _amplitude_to_angle return np.pi * _circ_dist(1 - omega(x), omega(p))
9f0defbff0567ba8c181a9565570d0c7444ddc94
21,244
def set_reporting_max_width(w): """ Set the max width for reported parameters. This is used to that failures don't overflow terminals in the event arguments are dumped. :param w: The new max width to enforce for the module :type w: int :return: True """ _REPR_MAX_WIDTH[0] = int(w) r...
5da03b359fc823919bf2782907a0717c1d303a31
21,245
import re def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
1223b13b23eb4dadafbc5a3e8bf3b6e7f521ab5b
21,246
def get_mnsp_offer_index(data) -> list: """Get MNSP offer index""" interconnectors = (data.get('NEMSPDCaseFile').get('NemSpdInputs') .get('PeriodCollection').get('Period') .get('InterconnectorPeriodCollection') .get('InterconnectorPeriod')) ...
46211e9a29f1fd1fd3148deaaaa064b6d6b05ca7
21,247