content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def have_same_SNP_order(dict_A, dict_B): """ Checks if two dictionaries have the same SNP order. """ have_same_order = [k for k in dict_A.keys() if k != "ext"] == [k for k in dict_B.keys() if k != "ext"] return have_same_order
b885dee561e9a61bb50e814401ee088593c2517b
3,627,200
def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features): """random_forest(评估算法性能,返回模型得分) Args: train 训练数据集 test 测试数据集 max_depth 决策树深度不能太深,不然容易导致过拟合 min_size 叶子节点的大小 sample_size 训练数据集的样本比例 n_trees...
92c8fd7337286bf59d501f6e6fd393700791eb7e
3,627,201
def define_plot_id(plot_name, plot_center): """Define plot id, keeping track of coordinates.""" plot_id = f"{plot_name}_X{int(plot_center[0])}_Y{int(plot_center[1])}" return plot_id
8f239a121598157c620ee8eef902e1d89218d01e
3,627,202
def build_mask_trace(ytrace, subarray='SUBSTRIP256', halfwidth=30, extend_below=False, extend_above=False): """Mask out the trace in a given subarray based on the y-positions provided. A band of pixels around the trace position of width = 2*halfwidth will be masked. Optionally extend_ab...
ac6e5ab113384f03b009cdce71dee197244562ab
3,627,203
import json def load_data(): """記録データを返します""" try: # json モジュールでデータベースファイルを開きます database = json.load(open(DATA_FILE, mode="r", encoding="utf-8")) except FileNotFoundError: database = [] return database
6fa14606b90708c528d0f9c6993c024fa37bd804
3,627,204
from typing import Optional def get_pattern(prefix: str) -> Optional[str]: """Get the pattern for the given prefix, if it's available. :param prefix: The prefix to look up, which is normalized with :func:`normalize_prefix` before lookup in the Bioregistry :returns: The pattern for the prefix, if ...
90387677f46dfda678a22d66d6fb21cecd3267c1
3,627,205
def decompressStreamToBytes(inputStream: IOBase) -> int: """Compresses `inputStream` into `outputStream`. Processes the whole data.""" with BytesIO() as outputStream: decompressStreamToStream(inputStream, outputStream) return outputStream.getvalue()
60b03d617c9ee61198a694a4417edc835e5aff1a
3,627,206
import requests def request(url): """ Sends a request to a url :param url: """ if not connected_to_internet(): raise ConnectionError( "You need to have an internet connection to send requests." ) response = requests.get(url) if response.ok: return res...
61805332c73b619bc387b450a904434d1a3dc56e
3,627,207
from typing import List def pil_grid(images: List[Image.Image], max_horiz: int) -> Image.Image: """ Automatically creates a mosaic from a list of PIL images. :param images: List of images in PIL form. :param max_horiz: Maximum number of images in the column. :return: Mosaic-like image. """ ...
e452dd2a69540a400395e898fb2731932d451f80
3,627,208
def rd_current(phi, T): """ Thermionic emission current density based on Richardson-Dushman Args: phi: Work function (eV) T: Temperature (K) Returns: Current density in J/cm**2 """ A = 4 * np.pi * m_e * k ** 2 * e / h ** 3 return A * T ** 2 * np.exp(-phi / (k_ev * ...
9e73560f0386b979b78872600b050f38fc842617
3,627,209
def _auto_levels_locator( *args, N=None, norm=None, norm_kw=None, locator=None, locator_kw=None, vmin=None, vmax=None, extend='both', symmetric=False, positive=False, negative=False, nozero=False, ): """ Automatically generate level locations based on the input data, the input locator, and the i...
5b5ed40eaea5fd6c5c22212b331149a253fab562
3,627,210
import requests def get_default_session() -> requests.Session: """ get the default session used in online-judge-tools :note: cookie is not saved to disk by default. check :py:func:`with_cookiejar` """ global _default_session if _default_session is None: _default_session = _new_sessio...
e00d2cafa9d22e842e891f771e041b5876ba4d65
3,627,211
def find_nearest(array, value): """ Find the nearest element in array to value. Parameters ---------- array : np.ndarray-like The array to search in. value : float The value to search. Returns ------- value : float The closest value in array. idx : int ...
14b75a0ec20503de5711fffc5b9b7821ceb5d2b9
3,627,212
from typing import Type import sys def create_create_one_input(model: Type[IEntityModel]) -> type: """ Create input type for creating one entity. :param model: class to be created :return: input type """ fields = {f: model.get_attribute_type(f) for f in model.get_attributes(GraphQLOperation.C...
32319db15661f582535418391bbe59aac24acf13
3,627,213
import logging def service_remove(service_id: str): """ Stops and removes a service. This can also be done with Service.remove(). @param service_id: the ID of the service you want to remove. @return: boolean value of success status """ try: client.service.get(service_id).remove() ...
0999add7b20d81723e2813ad01217a3ed8d1484b
3,627,214
from sys import audit def qedit_raw_save(topic_id, qt_id): """ Accept the question editor form and save the results. """ valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" user_id = session['user_id'] course_id = Topics.get_course_id(topic_id) if not (check_perm(user_id, cour...
4a0f2b857565791eb2c90866b91b784d46deb5e5
3,627,215
def _topDownConsistencySrcRec(tree1, tree2, matchList, bestMatchList): """ Recurrent version """ refML = [] ph2list = [ ph2 for (ph1,ph2) in matchList if ph1 is tree1 and \ ( ph2 is tree2 or ph2.isDescendent(tree2))] if PRINT_DEBUG: print "Current pos: ", tree1.tag(), tr...
f5375e0ee17590f15fc52885493e920164336d88
3,627,216
def mock_badvector_problem(): """Mocks noisy DataFrames for testing vectorization""" feat_df, _, combined_df = mock_problem() # Feature columns are numeric, but we want to assign bad non-numeric values to test our pre-processing. # To be able to do this, we need to set the datatype to np.object. fo...
ed47ae7fb177b83c28dfa1fea84fab44bf19ba82
3,627,217
def name_parts(author): """ Given the name of an author, break it in to first, middle, last and assign a case number to the type of name information we have Case 0 last name only Case 1 last name, first initial Case 2 last name, first name Case 3 last name, first initial, middle initial ...
5ea03725bf124c226e42ef546f070f0423000e28
3,627,218
def _parse_header(header) -> dict: """ Parses the route duration, links (fare and map data), and misc. data :param header: Element tree containing the header """ header, misc = header.find('td/table') duration, links = header.findall('td') return { 'duration': _parse_duration(dur...
f93e9b68c53bb0b9710ae62f0a7f9abc78811158
3,627,219
def get_version(): """ Return package version as listed in `__version__` in `init.py`. """ return moni.VERSION
036ba335168de6fcbff5f5f1e5dea205017f2a2f
3,627,220
def calculate_mean(i, peaklocationstart, peaklocationend): """ This function is for calculating the mean over the specified area and returns this mean. """ length = peaklocationend - peaklocationstart mean = 0 if i: for interval in i: if interval[0] < peaklocationstart and in...
fe57d6ab202c9c7da9894fd0d5aaab2a18ff113e
3,627,221
def swag(print_swag=True): """Swag!""" output = (""" ( ( ( )⧹ ))⧹ ) . ) ( )⧹ ) ( ( (()/(()/` ) /( )⧹ (()/(( )⧹))( . /(_)/(_)( )(_)) (((_) /(_))⧹ ((_)()⧹ ) (_))(_))(_(_()) )⧹___(_))((_)_(())⧹_)() | _ |_ _|_ _| (/ __| _ | __⧹ ⧹((_)/ / | _/| ...
c75d804e331f61ca4b779a7a05bd0d42298b0dec
3,627,222
import random def create_conn_matrix(name, width, n_neighbors=3, n_states=2, is_sparse=True): """ Creates a random square matrix with Gaussian distribution according to parameters for evodynamic.connection.WeightedConnection. Parameters ---------- name : str Name of the Tensor. width : int ...
ba73809fbc7bd9dc1aa4c118b5d36134e66c6bfc
3,627,223
def noticeOnFinish(filepath=success_audio): """ decorator function, when the fun finishes, noticeOnfinish() will play an audio in wav format(default is success_audio) :param filepath: wav audio path :return: """ def decorator(fun): def wrapper(*args, **kwargs): check_file_ty...
a23d4975983b8fe9851a423a37fc9d5b41cd3a27
3,627,224
import socket import sys def redirectOut(port=port, host=host): """ connect caller's standard output stream to a socket for GUI to listen start caller after listener started, else connect fails before accept """ sock = socket(AF_INET, SOCK_STREAM) sock.connect((host, port)) ...
611f3ef8785c4208fc7f3ffd6e72541543889c5c
3,627,225
import os def buildBwaIndex(reference, dest, output=None, log=None): """Create BWA index for fasta file :param reference: path to fasta reference file :param dest: directory to place bwt file :param output: file handle to write stdout and stderr. If None output is not captured :param log: notatio...
d005624f58f3ddc3c8d0cad82b5720c72d14045b
3,627,226
import uitypes def scriptTable(*args, **kwargs): """ Maya Bug Fix: - fixed getCellCmd to work with python functions, previously only worked with mel callbacks IMPORTANT: you cannot use the print statement within the getCellCmd callback function or your values will not be returned to the table """ ...
4d19a7706cce29c9c710e13adf26f98c9ce0e085
3,627,227
def trim_string(s, maxlen=1024, ellps='...'): """ Trim a string to a maximum length, adding an "ellipsis" indicator if the string was trimmed """ # todo: allow cutting in the middle of the string, # instead of just on the right end..? if len(s) > maxlen: return s[:maxlen - le...
e04474af37699b057d40afa43f5ea2187f0219d2
3,627,228
import os def train_SVM_model(trainX, trainY, testX, testY, class_names): """ 1. Train and evaluate SVM model - use data augmentation to increase data sample. 2. Save classification report. """ # define model base_model = SVC() # define parameters parameters = {'kernel':('linear', 'r...
5fa98bff46fad4167717669fc1da1c99d6c3e237
3,627,229
import argparse def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Caculate GC content', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'FASTA', help='fasta file', metavar='FASTA', n...
f4cb755cf55f43ad8dba8adafac40d680223be5e
3,627,230
def lista_clientes(request): """ Página com a lista de clientes """ # Pega informações da URL codigo = request.GET.get('search_cod_client', '') nome = request.GET.get('search_name_client', '') deletado = request.GET.get('deleted', False) page = int(request.GET.get('page', 1)) # Filtra list...
3e2c9c4e74ff00de78e13fb47641e1881c1e0abe
3,627,231
import subprocess import re def ping(dut, addresses, family='ipv4', **kwargs): """ To Perform ping to ipv4 or ipv6 address. Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param :dut: :param :addresses: :param :family: ipv4|ipv6 :param :count: 3(default) :param :timeout: :pa...
16eb148b26b225e3f3e091b823d24b8d43e852e4
3,627,232
def getRestrictedChemicalStates(labelArray, products, contexts, doubleAction): """ goes through a list of reaction center and their associated context and creates a dictionary of molecules of possible chemical states """ # sortedChemicalStates = defaultdict(lambda: defaultdict(lambda: defaultdict(s...
0e93ccd2384b0517fd39e4b370e628b4c0191951
3,627,233
def collection_getter (getter, *args, **kwargs): """Adds variables to relevant collections.""" var = getter(*args, **kwargs) name = kwargs['name'] trainable = kwargs['trainable'] if trainable: if 'kernel' in name: tf.add_to_collection(tf.GraphKeys.WEIGHTS, var) if 'bia...
6876a19a24b609f3128e2fac9dfcb1cf7601bb9f
3,627,234
def E_edgePair(mesh, edgePair, width, height, edge_len): """ Compute the energy coefficient matrix over a single edge pair. Inputs: mesh - the model in OBJ format edgePair - the edgePair of the model in (fi, (fv0, fv1)) format width, height - texture's dimensions edge_len - ...
24ec14ecb9d2c66465f79f484f6f8707c4863f0f
3,627,235
def getComponentReadingClassByType(componentType): """Given the path mapping of a point, get the class that it belongs to""" componentClass = None if componentType == "AHU": componentClass = AHUReading elif componentType == "VFD": componentClass = VFDReading elif componentType == "Filter": componentClass =...
fab2a51067a28fa2672afda01b8eedb07a589764
3,627,236
def from_rotation_matrix(mtr): """ See http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ """ mtr = tf.convert_to_tensor(mtr) def m(j, i): shape = mtr.shape.as_list() begin = [0 for _ in range(len(shape))] begin[-2] = j begin[-1...
e1b7f4391ec2b401b80eeb43c3cdfdc4e050a2e2
3,627,237
import json def findSimilarVectors(single_id): """ Return a list of _id's that are most similar to the original id """ topic_result, distances = nearestNeighbors.similar_from_id(single_id, 5) topic_result = json.dumps(topic_result, default = json_util.default) print(topic_result) return to...
3b350333fac9bd8f64755af4782b35d5f925cf7a
3,627,238
def set_sleep(sleep=False): """When the option 'sleep' is True, after plotting the computation is paused for 0.01 secs. Optionally, the sleeping time (in secs) can be fixed if a the number is passed (eg: sleep=0.001). The default value is False.""" if sleep==False and type(sleep)==bool: h.sleep=None ...
0ce62689b8f181663067adb06497fc9f346f2f4d
3,627,239
def format_msg(fmt, use_color=False): """Replace $RESET and $BOLD with corresponding ANSI entries""" if use_color: return fmt.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) else: return fmt.replace("$RESET", "").replace("$BOLD", "")
eb07a2871d8b14c19452aa29853c5f4ee72fd8f2
3,627,240
def add_week_course_activity(course_id: int, weektime_id: int, cur_week: int ,course_stage2: bool): """ 添加每周的课程活动 """ course = Course.objects.get(id=course_id) examine_teacher = NaturalPerson.objects.get_teacher( get_setting("course/audit_teacher")) # 当前课程在学期已举办的活动 conducted_num = Ac...
1ed5ac73a3efebd826a57d5aa757335313eaa0a3
3,627,241
def afwd(data): """ AFWD - Request 4WD status """ return data
47823c8e8d306c8fc84eea20ad703bc997498049
3,627,242
import hashlib def create_timestamp_anti_leech_url(host, file_name, query_string_dict, encrypt_key, deadline): """ 创建时间戳防盗链 Args: host: 带访问协议的域名 file_name: 原始文件名,不需要urlencode query_string_dict: 查询参数,不需要urlencode encrypt_key: 时间戳防盗链密钥 dead...
3d7a57ff84e81366089ea0084498322338944bfa
3,627,243
def centroid_points_xy(points): """Compute the centroid of a set of points lying in the XY-plane. Warning ------- Duplicate points are **NOT** removed. If there are duplicates in the sequence, they should be there intentionally. Parameters ---------- points : list of list A seq...
8da6c4154ff0632942108f9b63240c86438f3eb4
3,627,244
def driver(tag): """ Determine driver module :Parameters: `tag` : ``str`` Connection tag :Return: Driver module :Rtype: ``module`` :Exceptions: - `DBConfigurationError` : DB not configured - `KeyError` : DB name not found - `ImportError` : Driver not found ...
74e2a1164c73f6ce35afc040b9ef984bef3741c6
3,627,245
def should_force_reinit(config): """Configs older than 2.0.0 should be replaced""" ver = config.get("cli_version", "0.0.0") return int(ver.split(".")[0]) < 2
12b704fe2f3d2ef7cedf497a4a2e3a92321f52b2
3,627,246
def _import_package(*args, **kwargs): """ Import modules and things from a package """ package_name = kwargs['package_name'] if PACKAGES[package_name] is None: if len(args) < 2: return None return (None for _ in args) module = kwargs.get('module') modules = [] for ...
10b99a766159135237b2adcf480fdb2c13b3667d
3,627,247
def check_tag_list(tag_list): """ Makes a list of any tags entered on the command line. """ tags = [] if len(tag_list) != 0: tags = tag_list[0].split(",") return tags
24fb7d5c1f408ef9825a8efb461dc88483dcba9e
3,627,248
def tipo_cambio_agregar(): """ Agregar nuevo registro a 'tipos_cambio' """ form = SQLFORM(db.tipos_cambio, submit_button='Aceptar') if form.accepts(request.vars, session): response.flash = 'Registro ingresado' return dict(form=form)
f43bc0d5fafd1323c19c87d59af0f7d0ab4c9648
3,627,249
def start_uploading(main_pid): """ Start the process of uploading stdout/stderr """ process = Process(target=upload_stdout_stderr, args=(main_pid,)) process.start() return process
ff35189181a1604bb5b2ebfe98257f3dc64e75c1
3,627,250
import json from datetime import datetime def accounts_post(**kwargs): """ add new account and set first transaction with rests of money """ obj = json.loads(request.data.decode('utf-8', 'strict')) new_account = Account( title=obj['title'], currency_id=int(obj['currency.id'])) ...
caf2ed6aa6abddc9455f24d57a9d82b8da6bc257
3,627,251
def labels_to_image_model(labels_shape, n_channels, generation_labels, output_labels, n_neutral_labels, atlas_res, target_res, output_shap...
3d6b93cc011351a6d063fe851c2b2a9b94eb28eb
3,627,252
from typing import Optional async def unpack_from_prior_in_place( message: dict, resolvers_config: ResolversConfig ) -> Optional[DID_URL]: """ Unpacks from_prior field within a given message from JWT (compactly serialized JWS with claim set) if the message contains from_prior. In result, the messa...
38ea89e2c0867ae636de2d09aca6e48090331c42
3,627,253
import os import string def ensure_file_abs_path_valid(file_abs_path: Text) -> Text: """ ensure file path valid for pytest, handle cases when directory name includes dot/hyphen/space Args: file_abs_path: absolute file path Returns: ensured valid absolute file path """ project_me...
75b366b21ff067f7883a9a834e2093a57a17a10d
3,627,254
def remove_leading_character(string, character): """ If "string" starts with "character", strip that leading character away. Only removes the first instance :param string: :param character: :return: String without the specified, leading character """ if string.startswith(character): ...
4af4d6f86b9a6ed8975c4564904d2e1ca9e6d15a
3,627,255
def _rfind(lst, item): """ Returns the index of the last occurance of <item> in <lst>. Returns -1 if <item> is not in <l>. ex: _rfind([1,2,1,2], 1) == 2 """ try: return (len(lst) - 1) - lst[::-1].index(item) except ValueError: return -1
ab165a6795b0a495d24288d8e757c16ba9c968a4
3,627,256
def plot_all_continuous_efficiency_with_diefk(diefkDF: np.ndarray, colors: list) -> list: """ Generate radar plots that compare dief@k at different answer completeness in a specific test as in <doi:10.1007/978-3-319-68204-4_1>. This function plots the results reported in "Experiment 2". "Experiment...
f856a3fa498efefc886b40ddce5b7cb24a60c1be
3,627,257
from typing import Optional def measure_int_interval(interval: Interval[int]) -> Optional[int]: """Return the size of the integer interval.""" if interval.lower_bound is None or interval.upper_bound is None: return None if interval.is_empty(): return 0 return interval.upper_bound - int...
33b83b1737d1e2037fc4bca1c8467cdcdcd2fab2
3,627,258
def get_case_statuses(read_only): """ Get a list of the case statuses that are read-only. """ if read_only: return CaseStatusEnum.read_only_statuses() else: return [status for status, value in CaseStatusEnum.choices if not CaseStatusEnum.is_read_only(status)]
024c6f42f5049e32d7d14f9abc895e561ff444b2
3,627,259
def laggauss(deg): """ Gauss-Laguerre quadrature. Computes the sample points and weights for Gauss-Laguerre quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[0, \\inf]` with the weight function :math:`f...
8261ee7883158f7f01eba4951341d1d6e25aadac
3,627,260
def list_uiactions(content, request=None, registry=None, category=''): """ List ui actions for specific content """ if request is not None: registry = request.registry url = request.resource_url(content) else: url = '' actions = [] for name, action in registry.adapters.looku...
cb88d0fb86ea0487674f76896f604532796173d9
3,627,261
def create_singularity_cmd(args): """Function that creates and returns the BIDS App singularity run command. Parameters ---------- args : dict Dictionary of parsed input argument in the form:: { 'bids_dir': "/path/to/bids/dataset/directory", 'output_...
1330d7bcdb70fd7194b14395bbaacfbc92a37650
3,627,262
def define_index(min_date: int, max_date: int, interval: str) -> int: """ Return the index of a specific date """ interval_minutes = constants.TICKER_INTERVAL_MINUTES[interval] return int((max_date - min_date) / (interval_minutes * 60))
06dd1a70da23349d04a4a199410118c7e51722c6
3,627,263
def map_box(sbox, dbox, v): """ sbox is (lat1, lat2, long1, long2), dbox is (x1, x2, y1, y2), v is (lat, long). result is (x, y) """ xscale = abs(dbox[1]-dbox[0])/abs(sbox[3]-sbox[2]) yscale = abs(dbox[3]-dbox[2])/abs(sbox[1]-sbox[0]) x = (v[1]-sbox[2]+dbox[0])*xscale y = (v[0]-...
de1cb095d03eacc4930f37a05c5b01ebd983baca
3,627,264
def clash_iter(atoms, min_clash=0.4, radii_attr='radius'): """ Returns an iterator over pairs: -clash value -the pair of clashing atoms min_clash. """ max_radii = max([getattr(a, radii_attr) for a in atoms]) gridhash = GridHash([(a.coordinates, a) for a in atoms], max_radii*2 - m...
b07cd7e5368c3c0102fe5db04553c8ae63b4b6f2
3,627,265
def recognize_po_file(filename: str) -> bool: """ Recognize .po file """ if filename.endswith(".po"): return True return False
9993e1d0f1a45f1ce60709650a7381df00ebdce0
3,627,266
def circle_xy(x0, y0, r0): """ To obtain cartesian coordinates of a circle @param x0: float x coordinate of the center of the circle @param y0: float y coordinate of the center of the circle @param r0: float radius of the circle @return: np.array([float]),np.array([float]...
561db75a9e6aaf7c912921137d49689a19e47610
3,627,267
from typing import List def _build_dev_requirements() -> List[Requirement]: """Load requirements from file.""" with open(REQUIREMENT_PATH, "rt") as req_file: return list(parse_requirements(req_file.read()))
f4e253819459c8f249b3d779f2a01b54d26ea0ca
3,627,268
from bs4 import BeautifulSoup def scrape_video_menu(url): """ Scrape videos from url Args: url (str): url to scrape from (e.g. https://www.exploratorium.edu/video/subjects) Returns TopicNode containing all videos """ LOGGER.info("SCRAPING VIDEOS...") video_topic = nodes.Top...
394bf809c828b2c0816bf056ea91d459cb2dd881
3,627,269
def multiply_nums(n1, n2): """Function to multiplies two numbers. n1 : Must be a numeric type n2 : Must be a numeric type """ result = n1 * n2 return result
05549b4780fec2e2ba14719ebbb93e45491710e7
3,627,270
from typing import Optional import textwrap def _get_setup( benchmark: GroupedBenchmark, runtime: RuntimeMode, language: Language, stmt: str, model_path: Optional[str] ) -> str: """Specialize a GroupedBenchmark for a particular configuration. Setup requires two extra pieces of information...
1b1461a35d4be46bda42d401fad2580fdcbac261
3,627,271
import os def update_from_sheets(request): """Create Student model instances from excel sheet.""" if request.method == 'POST': sheet = request.FILES['sheet'] # Temporarily save the file fs = FileSystemStorage(location=settings.TEMP_ROOT) filename = fs.save(sheet.name, sheet) ...
a1a2da16d0c992a79aa94b13cfb425c7c4846cbf
3,627,272
from sense_hat import SenseHat async def read_temperature(request: web.BaseRequest): """ Request handler for retrieving local sensor data. Args: request: aiohttp request object """ context = request.app["request_context"] sense = SenseHat() temperature = sense.get_temperature() ...
0d40d6d577d8d5ff247e9311062ab65510c2ec08
3,627,273
def expressions(): """Return a sequence of test expressions.""" A = Lambda('a') X = Lambda('x') Y = Lambda('y') Z = Lambda('z') XA = Lambda(X, A) XY = Lambda(X, Y) XZ = Lambda(X, Z) YZ = Lambda(Y, Z) XYZ = Lambda(XY, Z) xX = Lambda('x', X) xyX = Lambda('x', Lambda('y', X)...
98f8fd1bae29bf20cc27ad2022d1c0a4d7118f2b
3,627,274
def misc_tasks_to_goals(real_goals, misc_goals, extra_time=0): """ Converts misc-goal tasks into goals for themselves. That is, each task is a goal for itself consisting of only one task (itself). Args: real_goals: [Goal] representing real goals misc_goals: [{node}] representing mis...
6cd2653b047e23c6b5bbdbf47516d4d0700af12b
3,627,275
def normalize_timedelta(val): """ produces a normalized string value of the timedelta This module returns a normalized time span value consisting of the number of hours in fractional form. For example '1h 15min' is formatted as 01.25. """ if type(val) == str: val = parse_timedelta(v...
c004f5bf8d11c0f71b058e080100fea2d0529061
3,627,276
def up_to(s, i, c): """Il faudrait commenter, je ne sais plus ce que ça fait.""" t = [] k = i while s[k] != c: t.append(s[k]) k += 1 return "".join(t)
ec4ffc90949b3b66c74c52a0019981564ace8aef
3,627,277
def main(): """CollatzPy CLI""" return 0
51f497ce25f4e90da4f0178510ba25d568edfc0b
3,627,278
def bf_get_users(selected_bfaccount): """ Function to get list of users belonging to the organization of the given Blackfynn account Args: selected_bfaccount: name of selected Blackfynn acccount (string) Retun: list_users : list of users (first name -- last name) associated with the o...
8fd449f6692d2dbe3b54c6bafa26473f65fbd2a8
3,627,279
def load_service(service: str, version: str = None, model_type="service-2") -> ServiceModel: """ For example: load_service("sqs", "2012-11-05") """ service_description = loader.load_service_model(service, model_type, version) return ServiceModel(service_description, service)
8a42cba607a07a6ee81f0ac43438166aa024dc40
3,627,280
import os def get_file_size_gb(file_path): """Get File Size by GB""" if os.path.exists(file_path): size = round((os.path.getsize(file_path) / 1024 / 1024 / 1024), 1) LOG.debug("Target File Size : {} ({} GB)".format(file_path, size)) return size else: return 0
5dfac737bb2ebbdd8a5e9e82f1233b123be0304a
3,627,281
def _kv_to_dict(meta): """Transform a list with key/value strings into a dictionary. """ try: return dict(m.split("=", 1) for m in meta) except ValueError: raise _errors.MachineError("Invalid parameter (%s)." % (meta, ))
93ab5ff6d1bd092f6ad0ae4d5a9e071db4caf3a3
3,627,282
def _flip_row_coordinates(move): """Flips a coordinate of a move horizontally. Args: move: row, col index or None if pass move Returns: Horizontally flipped move if move was not None """ if move is None: return move row, col = move row = go.BOARD_SIZE - 1 - row ...
cc89be66ba6de140ffb8d13ad669690b53429d61
3,627,283
def faultReturnHandler(func): """ Handles functions with return. Decorated function returns erro message if something went wrong. """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs); except Exception as error_message: ...
75a18e45bc6d734571ee118dd8fa9cd8d64a9feb
3,627,284
def tag_t_offset_compare_key(): """ Convert a tag_t_offset_compare function into a key=function This method is modeled after functools.cmp_to_key(_func_). It can be used by functions that accept a key function, such as sorted(), min(), max(), etc. to compare tags by their offsets, e.g., sorted(t...
e6d6f82421face3f709045a41315490e5a0302dd
3,627,285
from pyscf.nao.m_ao_matelem import ao_matelem_c def comp_coulomb_den(sv, ao_log=None, funct=coulomb_am, dtype=np.float64, **kvargs): """ Computes the matrix elements given by funct, for instance coulomb interaction Args: sv : (System Variables), this must have arrays of coordinates and species, etc ...
a8cf0bc871271a03d9b5c09ef5b30ed8c7195ede
3,627,286
def dmp_gcd(f, g, u, K): """ Computes polynomial GCD of `f` and `g` in `K[X]`. Examples ======== >>> R, x, y = ring("x y", ZZ) >>> f = x**2 + 2*x*y + y**2 >>> g = x**2 + x*y >>> R.dmp_gcd(f, g) x + y """ return dmp_inner_gcd(f, g, u, K)[0]
20591ac511f83da5bfa145145807d2001d8b8cd7
3,627,287
import gettext def preferences(): """Render preferences page && save user preferences""" # save preferences if request.method == 'POST': resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index')))) try: request.preferences.parse_form(request.form) ...
a4afe0d5728709ab5550d3cf58a8e56420003646
3,627,288
def freq2lin(freq_hz): """Compatibility hack to allow for linearly spaced cosine filters with `make_erb_cos_filters_nx`; intended to generalize the functionality of `make_lin_cos_filters`. """ return _identity(freq_hz)
7f65e09f2223b29355afa26cef282e98e536d41b
3,627,289
import zipfile import json def _GetVersionFromCrx(crx_path): """Retrieves extension version from CRX archive. Args: crx_path: path to CRX archive to extract version from. """ with zipfile.ZipFile(crx_path, 'r') as crx_zip: manifest_contents = crx_zip.read('manifest.json') version = json.loads(man...
e6b612f94b0fa4e62f5ecb8df297a6255294ec5f
3,627,290
def get_fuzzy_continuous_sets(divisions, point_set_method='point_set'): """Generate a list with the triangular fuzzy sets of a variable of a DataFrame given the peaks of the triangles Parameters ---------- divisions : list List of tuples with the names of the sets and the peak of the tr...
16d776625679319ad44da4b96af5ac888294ea59
3,627,291
import os def gen_iclr_data(dir, sent_data, score_fn, limit_to=None, merge=True): """ Create PeerReview ICLR dataset from sentiment lexicon """ iclr_data = [fname for fname in os.listdir(os.path.join(dir, 'reviews'))][:limit_to] n = limit_to or len(iclr_data) y = np.zeros(n) x = np.zero...
c3fb09c48d75dc0d48aaf732473621606cb78e0b
3,627,292
def angle_distance_degree(deg1: float, deg2: float) -> float: """ Return the distance between angles. :param deg1: the starting angle, in degrees. :param deg2: the ending angle, in degrees. :return: the distance in range [-180, 180] """ return _s_dist(deg1, deg2, 360)
40c7767ff7d64ea77c1a546d4087fcb4cda5328e
3,627,293
def _get_transf_matrix(n: int, transform_type: str, dec_levels: int = 0, flip_hardcoded: bool = False) -> (np.ndarray, np.ndarray): """ Create forward and inverse transform matrices, which allow for perfect reconstruction. The forward transform matrix is normalized so that the l2-...
e4d3740f7ae1cc9e57190dc423f3de60822c2233
3,627,294
from typing import OrderedDict def get_hierarchical_data_for_apps(apps): """ Return a hierarchical data structure consisting of nested OrderedDicts for all data collected for apps listed in `apps`. The format of the returned data structure is: ``` { <session_1_code>: { 'code':...
79ea7e411843cf7541d35aad6f8f654fe14d1e0f
3,627,295
from typing import Optional from typing import List def get_available_source_annotations(doc: Optional[str] = None, docs: Optional[List[str]] = None) -> List[str]: """Get a list of available annotations generated from the source, either for a single document or multiple.""" assert doc or docs, "Either 'doc' o...
f8f07a5cb2a1bb5ce7793d18931343e34f72f79c
3,627,296
def get_GEOS_data_folder4dt(dt=None, product='GEOS_CF', host=None, mode='fcast', collection='inst3_3d_aer_Np', inc_collection=True): """ Get the data folder location for a given GEOS product and datetime """ # Where is the data for the product? ...
ae8e9d8484937b999fc96f3968ae0b9efe32c83a
3,627,297
import sys import re def getOptions(): """ Created the option parser according to spec above. Also allows standard svn hook arguments """ optargs = sys.argv[1:] if len(optargs) == 2 and re.search(r'^\d+$', optargs[1]): optargs = ['-p', optargs[0], '-r', optargs[1]] # options as global variables (...
663b4e087860480a268be4d0da88b1d800394c81
3,627,298
import hashlib def safe_md5(open_file, block_size=2**20): """Computes an md5 sum without loading the file into memory This method is based on the answers given in: http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python """ md5 = hashlib.md5() data = True ...
3711eba8479fabc69f30063cfc6fb585345bab66
3,627,299