content
stringlengths
22
815k
id
int64
0
4.91M
def raw_compare_ge(stage: ImportStage, left: ir.Value, right: ir.Value) -> ir.Value: """Emits an ApplyCompareOp for 'ge'.""" return d.ApplyCompareOp(d.BoolType.get(), ir.StringAttr.get("ge"), left, right).result
5,297,200
def SearchLunarApsis(startTime): """Finds the time of the first lunar apogee or perigee after the given time. Given a date and time to start the search in `startTime`, this function finds the next date and time that the center of the Moon reaches the closest or farthest point in its orbit with respect ...
5,297,201
def _get_dataset_from_filename( instruction: _Instruction, do_skip: bool, do_take: bool, file_format: file_adapters.FileFormat, add_tfds_id: bool, ) -> tf.data.Dataset: """Returns a tf.data.Dataset instance from given instructions.""" ds = file_adapters.ADAPTER_FOR_FORMAT[file_format].make_tf_da...
5,297,202
def clamp(x, inf=0, sup=1): """Clamps x in the range [inf, sup].""" return inf if x < inf else sup if x > sup else x
5,297,203
def schema_fail_template(messages_list, filename_template, schema): """template for tests that are expected to fail schema validation""" template(messages_list, filename_template, schema, -1)
5,297,204
def open_current_file(): """ Opens the current maya scene file. :return: <bool> True for success. """ cmds.file(cmds.file(q=1, loc=1), o=1, f=1) return True
5,297,205
def flatten(x, name=None, reuse=None): """Flatten Tensor to 2-dimensions. Parameters ---------- x : tf.Tensor Input tensor to flatten. name : None, optional Variable scope for flatten operations Returns ------- flattened : tf.Tensor Flattened tensor. """ ...
5,297,206
def attribute_startswith(search_string, limit=20): """Query attributes starting search_string :param search_string: e.g. al to match allow_from, allow_to etc. :param limit: limit result to n results :return: """ query = Attribute.objects.filter( attribute_id__startswith=search_string)...
5,297,207
def test_iterable_linked_list(): """Test values of initialized linked list.""" from src.linked_list import LinkedList linked_list = LinkedList([1, 2, 3]) assert (len(linked_list), linked_list.head.data) == (3, 3)
5,297,208
def jaccard_stability(explainer, x, neighborhood, k=1): """Jaccard adaptation Stability function. Takes as argument an explanation method, a single observation x of shape (n_features, ), the neighborhood as a matrix of shape (n_neighbors, n_features), and the size of the subset being consider...
5,297,209
def run(cmd): """ Wrapper on `subprocess.run`. Print the command. Execute a command string on the shell (on bash). Exists so that the shell prints out commands as m2g calls them. Parameters ---------- cmd : str Command to be sent to the shell. """ print(f"Running shell c...
5,297,210
def _get_item_kind(item): """Return (kind, isunittest) for the given item.""" try: itemtype = item.kind except AttributeError: itemtype = item.__class__.__name__ if itemtype == 'DoctestItem': return 'doctest', False elif itemtype == 'Function': return 'function', Fal...
5,297,211
def search_by_classifier(): """Use PyPI XML-RPC API to get all Lektor-tagged distributions. https://warehouse.pypa.io/api-reference/xml-rpc.html """ client = ServerProxy("https://pypi.org/pypi") return set(name for name, version in client.browse(["Framework :: Lektor"]))
5,297,212
def xfoil_fortran_binary(name, srcs, archives, includes=[], defines=[], copts=[]): """Compiles a binary from Fortran source. Args: srcs: Source files. archives: Archives that the binary depends on. These must be specified in proper order for the linker. includes: Files included by the source fi...
5,297,213
def do_image_create(gc, args): """Create a new image.""" # Filter out None values fields = dict(filter(lambda x: x[1] is not None, vars(args).items())) fields['is_public'] = fields.get('is_public') if 'is_protected' in fields: fields['protected'] = fields.pop('is_protected') raw_prope...
5,297,214
def _get_page(url: str, headers: dict = {}, cookies: dict = {}) -> BeautifulSoup: """ Return page as BeautifulSoup object Parameters ---------- url : str a useable url headers : dict, optional headers, by default {} cookies : dict, optional cookies, by default {} ...
5,297,215
def champ_win_rate(matches_df, champ, lane='all'): """Calculate the win rate of a single champion. By default, looks in every lane. Lane can also be specified (eg. TOP_SOLO) """ teams_lanes_roles = dc.get_teams_lanes_roles() if lane != 'all': teams_lanes_roles = ['100_' + lane, '200...
5,297,216
def AddPasswordFlagGroup(parser, required=False): """Adds --password and --prompt-for-password flags to the given parser.""" password_group = parser.add_group(required=required, mutex=True) password_group.add_argument( '--password', help="""\ Password for the user that Database Migration Se...
5,297,217
def convert_to_datetime(line): """TODO 1: Extract timestamp from logline and convert it to a datetime object. For example calling the function with: INFO 2014-07-03T23:27:51 supybot Shutdown complete. returns: datetime(2014, 7, 3, 23, 27, 51) """ timestamp = line.split()[1...
5,297,218
def computeDiffSig (train_X, train_Y, mu, classLabel): """ Computes the means of the GDA """ m = train_Y.shape[0] classIndicator = np.array(train_Y == classLabel).flatten() classCount = np.sum(classIndicator == True) Sigma = np.matrix([[0, 0], [0, 0]]) for (indicator, x) in zip(classInd...
5,297,219
def _inc_path(path): """:returns: The path of the next sibling of a given node path.""" newpos = MP_Node._str2int(path[-MP_Node.steplen :]) + 1 key = MP_Node._int2str(newpos) if len(key) > MP_Node.steplen: raise Exception("Path Overflow from") return "{0}{1}{2}".format( path[: -MP_No...
5,297,220
def delete(): """ delete() : Delete a document from Firestore collection """ try: # Check for ID in URL query doc_id = request.args.get('id') db_ref.document(doc_id).delete() return jsonify({"success": True}), 200 except Exception as e: return f"An Error O...
5,297,221
def test_sparse(par): """Sparse matrix representation """ diag = np.arange(par['nx']) +\ par['imag'] * np.arange(par['nx']) D = np.diag(diag) Dop = Diagonal(diag, dtype=par['dtype']) S = Dop.tosparse() assert_array_equal(S.A, D)
5,297,222
def mongo_event(event: str, resource: str, func: Optional[EventFuncType]=None ) -> Event: """A function to return an :class:`Event` with aliases set-up for mongo events. The following aliases can be used for mongo events:: +----------+--------------+ | Alias | Eve Even...
5,297,223
def xml_to_json(survey: database.Survey): """Convert survey from Ankieter xml format to json format :param survey: The Survey that is edited or created :type survey: Survey :return: The survey in json format :rtype: Dict """ def write_element(question, res): res["header"] = qu...
5,297,224
def _refresh_access_token(): """Refreshes the access token.""" url = f"{API_BASE_URL}/oauth/token" data = { "grant_type": "refresh_token", "client_id": get_state("client_id"), "client_secret": get_state("client_key"), "refresh_token": get_state("refresh_token"), } res...
5,297,225
def undeploy_model(endpoint_arn: str): """[Un-deploys a Document Classifier for Text Classification on AWS] Args: endpoint_arn (str): [End point name] Raises: error: [Error] """ try: logging.info(f"Deploy Document Classifier: {endpoint_arn}") response = client.delet...
5,297,226
def payoff_table_method( problem: MOProblem, initial_guess: Optional[np.ndarray] = None, solver_method: Optional[Union[ScalarMethod, str]] = "scipy_de", ) -> Tuple[np.ndarray, np.ndarray]: """Uses the payoff table method to solve for the ideal and nadir points of a MOProblem. Call through to payoff_...
5,297,227
def absmag(mag, z, band1='megacam_r', band2='megacam_r', model='cb07_burst_0.1_z_0.02_salp.model', zf=5): """ Takes a set of magnitudes all at the same redshift z and returns the aboslute magnitudes. This does not need to be done for each object since the conversion from apparent to absol...
5,297,228
def load_yields(location): """Loads up the county corn yields""" pgconn = get_dbconn('coop') df = read_sql(""" select year, num_value as yield from nass_quickstats where county_ansi = %s and state_alpha = 'IA' and year >= 1980 and commodity_desc = 'CORN' and statisticcat_desc...
5,297,229
def report_iferr(plinkcmd, decode_stdout, err_bool, logger=None, type="Error"): """ report error/warning if it exists """ if np.any(err_bool): if logger: logger.debug( f"{type} while running plink cmd:\n {plinkcmd}\n {decode_stdout[np.where(err_bool)[0][0]]}\n" ...
5,297,230
def mapattr(value, arg): """ Maps an attribute from a list into a new list. e.g. value = [{'a': 1}, {'a': 2}, {'a': 3}] arg = 'a' result = [1, 2, 3] """ if len(value) > 0: res = [getattr(o, arg) for o in value] return res else: return []
5,297,231
def _rxcheck(model_type, interval, iss_id, number_of_wind_samples): """Gives an estimate of the fraction of packets received. Ref: Vantage Serial Protocol doc, V2.1.0, released 25-Jan-05; p42""" # The formula for the expected # of packets varies with model number. if model_type == 1: _expec...
5,297,232
def hashable_tensor_or_op(tensor_or_op): """Returns a hashable reference to a Tensor if given a Tensor/CompositeTensor. Use deref_tensor_or_op on the result to get the Tensor (or SparseTensor). Args: tensor_or_op: A `tf.Tensor`, `tf.CompositeTensor`, or other type. Returns: A hashable representation ...
5,297,233
def header_to_xml(header): """ Converts image header metadata into an XML Tree that can be inserted into a JP2 file header. Parameters ---------- header : `MetaDict` A header dictionary to convert to xml. Returns ---------- `lxml.etree._Element` A fits element where...
5,297,234
def string_in_list(str, substr_list): """Returns True if the string appears in the list.""" return any([str.find(x) >= 0 for x in substr_list])
5,297,235
async def _async_watch(job_id, directory, python_datetime=None, first_time=True, **kwargs): """Wait until a list of jobs finishes and get updates.""" watch_one = qwatch.Qwatch(jobs=[job_id], directory=directory, watch=True, users=None, **kwargs) job_dict = watch_one.update_qstat_data(save=True, process=Tr...
5,297,236
def main(): """Select the revelant runs to make Select runs by uncommenting them and also the revelant object instantation. """ lake_drivers = Dynamic_Lake_Drivers() #lake_drivers.prepare_orography_ICE5G_0k_uncorrected() #lake_drivers.prepare_orography_ICE5G_0k_corrected() #lake_drivers.pre...
5,297,237
def vals_missing_plot_list_cmap(binned_array, listed_cmap): """Returns a normalized imshow plot using a 3 value array w vals 2,3,4.""" cmap, norm = listed_cmap bins, arr = binned_array arr[arr == 1] = 2 arr[arr == 5] = 4 f, ax = plt.subplots(figsize=(5, 5)) return ax.imshow(arr, cmap=cmap...
5,297,238
def click_by_js(element): """Clicks on element by triggering .click() using JavaScript Arguments: element -- the Selenium WebDriver Element to click Returns: True or False """ if verbose: print 'Clicking on element by js...' try: Browser.execute_script('arguments[0].click();', element) ...
5,297,239
def get_disk_rse_ids(): """Get rse:rse_id map from pickle file TODO: Get rse:rse_id map via Rucio python library. I could not run Rucio python library unfortunately. Used code in LxPlus (author: David Lange): ```py #!/usr/bin/env python from subprocess import Popen,PIPE import os,sys,pickle def runCo...
5,297,240
def process(tweet, preserve_case=True, preserve_stopwords=False): """ Perform tweet preprocessing :param tweet: :param preserve_case: :param preserve_stopwords: :return: """ tweet = basicProcess(tweet) # perform basic preprocessing if preserve_stopwords is False: # in case we want ...
5,297,241
def loadRaster(source): """ Load a raster dataset from a path to a file on disc Parameters: ----------- source : str or gdal.Dataset * If a string is given, it is assumed as a path to a raster file on disc * If a gdal.Dataset is given, it is assumed to already be an open raster ...
5,297,242
def write_extract(result: Iterable[PiiEntity], index: Dict, out: TextIO): """ Write output for "extract" mode as NDJSON :param result: iterable of result PiiEntity objects :param index: indexing information to be added to each PII_TASKS :param out: destination to write the NDJSON lines to ...
5,297,243
def save_json(info, folder, audio_name): """ TODO DOCUMENTATION :param info: :param folder: :param audio_name: :return: """ check_folder(os.path.join(folder, audio_name), True) out_file = os.path.join(folder, audio_name, 'info.json') with open(out_file, 'w') as fp: json.d...
5,297,244
def show(ctx: click.Context) -> None: """Shows the content of context.""" for key, parser in PARSERS.items(): if key in ctx.obj: click.echo(parser(ctx.obj[key], print_date=False))
5,297,245
def process(fname): """Process verif output file. fname: name of file return: tuple of (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)""" # extract errors ncf = Scientific.IO.NetCDF.NetCDFFile(fname) diff = ncf.variables['thke'][-1,:,:] - ncf.variables['thk'][-1,:,:] centre...
5,297,246
def build_kfold_config(params_dict, train_path, dev_path): """按k-fold拆分好的数据,构造新的json配置,用来启动训练任务 :param params_dict: 原始json配置构造出来的param_dict :param train_path: k-fold拆分之后的训练集路径,list类型 :param dev_path: k-fold拆分之后的评估集路径,list类型 :return: task_param_list: 生成新的json配置,用来启动run_with_json """ assert is...
5,297,247
def handle_right(left_entry_box, right_entry_box, mqtt_sender): """ Tells the robot to move using the speeds in the given entry boxes, but using the negative of the speed in the right entry box. :type left_entry_box: ttk.Entry :type right_entry_box: ttk.Entry :type mqtt_sender: ...
5,297,248
def bft_events_graph(start): """Builds graph of events traversing events in breadth-first order This graph doesnt necessary reflect deployment order, it is used to show dependencies between resources """ dg = nx.DiGraph() stack = [start] visited = set() while stack: item = stac...
5,297,249
def _get_past_names(cur: cx_Oracle.Cursor) -> dict[str, list[str]]: """Returns all the names that each InterPro entry ever had. Names are sorted chronologically. :param cur: Oracle connection cursor. :return: A dictionary (key: entry accession, value: list of names) """ versions, dates = _get_f...
5,297,250
def serve_subtitles(request, great_media_id, language): """Subtitles are stored along with the core.models.GreatMedia instance but they need to be served via their own dedicated URL. """ video = get_object_or_404(GreatMedia, id=great_media_id) # See if there's a subtitle field for the appropriate ...
5,297,251
def makeMostCommonPatternHeuristic(weights): """Return a function that chooses the most common (currently most-used) pattern.""" def weightedPatternHeuristic(wave, total_wave): print(total_wave.shape) # [print(e) for e in wave] wave_sums = numpy.sum(total_wave, (1, 2)) sele...
5,297,252
def ServicesDecorator(func): """ Make sure cfn-hup is running """ def wrapper(*args, **kwargs): kwargs['services'] = { 'sysvinit': InitServices( { 'cfn-hup': InitService( ensureRunning='true', enabled='true',...
5,297,253
def chart_runner(chart, scales, axes, marks): """Iterate through each chart element for check for contents""" for i, scale in enumerate(scales): nt.assert_dict_equal(chart.scales[i].grammar(), scale) for i, axis in enumerate(axes): nt.assert_dict_equal(chart.axes[i].grammar(), axis) f...
5,297,254
async def _fetch( flow_id: uuid.UUID, yaml_only: bool = False ): """ Get Flow information using `flow_id`. Following details are sent: - Flow YAML - Gateway host - Gateway port """ try: with flow_store._session(): host, port_expose, yaml_spec = flow_store._ge...
5,297,255
def get_sample_graph(model_name: Optional[str] = None) -> tf.Graph: """Return a sample model as tf.Graph""" graph_def = get_sample_graph_def(model_name, fmt='proto') graph = tf.Graph() with tf.compat.v1.Session(graph=graph): tf.graph_util.import_graph_def(graph_def, name='') return gra...
5,297,256
def selectMetric(name: str): """Return the metric defined by name. Args: name (str): a string referenced in DeepHyper, one referenced in keras or an attribute name to import. Returns: str or callable: a string suppossing it is referenced in the keras framework or a callable taking (y_true,...
5,297,257
def getTagNames(domain): """ Returns a list of tag names used by the domain. :param domain: a domain object :type domain: `escript.Domain` :return: a list of tag names used by the domain :rtype: ``list`` of ``str`` """ return [n.strip() for n in domain.showTagNames().split(",") ]
5,297,258
def matching(fingerAi, finger_i): """ Matching entre dos huellas """ it = 0 ta = 0 tb = 0 for i in range(len(fingerAi)): if fingerAi["f0"].iloc[i]==finger_i["f0"] and \ fingerAi["f1"].iloc[i]==finger_i["f1"] and \ fingerAi["utime"].iloc[i]==finger_i["...
5,297,259
def test_bodysite_3(base_settings): """No. 3 tests collection for BodySite. Test File: bodysite-example-skin-patch.json """ filename = base_settings["unittest_data_dir"] / "bodysite-example-skin-patch.json" inst = bodysite.BodySite.parse_file( filename, content_type="application/json", encod...
5,297,260
def glob_texture_files(texture_file_pattern): """Collect / glob specified image file path. :arg texture_file_pattern: Image file path need to glob, file name must have glob pattern '*' (asterix). :type texture_file_pattern: str or path.Path :rtype: list of path.Path """ texture_file_glob =...
5,297,261
def make_rotation(theta): """ makes a rotation matrix Note: HWP is a mirror matrix, not a rotation! :param theta: :return: """ a = cos(theta) b = -sin(theta) c = sin(theta) d = cos(theta) retMat = np.array([[a,b], [c, d]]) # need to remove issues from machine precision ...
5,297,262
def verify_routing_route_ip_on_interface(device, interface_dict): """ Verify routes match the configured IP address in running config Args: device (`obj`): Device object interface_dict (`dict`): Interface dict contain ip route info. Get from libs/routing/verify.py::verify_routing_lo...
5,297,263
def calculate_denominator(unvisited_nodes, pheromone_matrix, distance_matrix, current_node, node, load, max_load, demand, alpha, beta, gamma, lam): """ Calculate denominator to compute the probability of a route """ sum = 0.0 for node in unvisited_nodes: tau = calculate_tau(pheromone_matrix...
5,297,264
def get_right_stem_aligned_indices( string, inner_potential_indices, outer_potential_indices ): """Return the indices of the aligned strings :param str string: the original string :param tuple inner_potential_indices: [start, end) of inner part :param tuple outer_potential_indices: [start, e...
5,297,265
def set_deeppavlov_root(config: dict) -> None: """Make a serialization user dir.""" try: deeppavlov_root = Path(config['deeppavlov_root']) except KeyError: deeppavlov_root = Path(__file__, "..", "..", "..", "..", "download").resolve() deeppavlov_root.mkdir(exist_ok=True) paths.deep...
5,297,266
def stack_tensor_dict_list(tensor_dict_list): """ Stack a list of dictionaries of {tensors or dictionary of tensors}. :param tensor_dict_list: a list of dictionaries of {tensors or dictionary of tensors}. :return: a dictionary of {stacked tensors or dictionary of stacked tensors} """ keys = list...
5,297,267
def db_insert(conn, query): """ Execute the insert the query on the db and return the insert id @param conn: Connection @param query: Query string to be executed """ logger = bp_logger('dbutils') try : conn.query(query) except _mysql_exceptions.ProgrammingError as (errno, strerr...
5,297,268
def clean(ctx): """Remove all generated documentation.""" ctx.run('rm -rf {dir}'.format(dir=ctx.build_dir.doc_dir))
5,297,269
def is_gce_instance(): """Check if it's GCE instance via DNS lookup to metadata server""" try: socket.getaddrinfo('metadata.google.internal', 80) except socket.gaierror: return False return True
5,297,270
def get_count_value(context, fieldname): """ {% get_count_value fieldname %} """ return {"value":fieldname}
5,297,271
def gather_notebooks(template_data, cell_pairs_q, problems_per_notebook=10): """Create complete (dict) Jupyter notebooks. limit number of problems in each notebook""" range_val = (len(cell_pairs_q) // problems_per_notebook) + 1 for i in range(range_val): notebook_cells = [] full_data = copy....
5,297,272
def download_feature(feature_name, cache=False, **kwargs): """download a single feature Args: feature_name: (str) name of feature cache: (bool) set to True if you plan on using the instance for more than one job kwargs: Returns: pd.DataFrame """ if valida...
5,297,273
def post_json_example(body: dict) -> dict: """Sample API handler that accepts a json body :param body: the json body variable :return: dictionary containing a single "value" parameter """ from parrot_api.core.requests import get_request_access_token return dict(value=True, token=get_request_acc...
5,297,274
def registerShortcut(categories, keyseq, context=Qt.WidgetShortcut, actionName=None): """Decorate a function to be called when a keyboard shortcut is typed When the keyboard shortcut `keyseq` is pressed in any widget matching `categories`, the decorated function will be called, with the widget passed as first param...
5,297,275
def commands(): """Tracking APIs.""" pass
5,297,276
def test_mongo_clear_being_calculated(): """Testing MongoDB core clear_being_calculated.""" _func_w_bad_mongo.clear_being_calculated()
5,297,277
def fit_normal(x, y): """ Fit Gaussian """ if sum(y) == 0: _logger.debug("Problem with fit: all data points have zero value. Return zeros instead fit parameters!") return [0, 0, 0], None mean = sum(x * y) / sum(y) sigma = np.sqrt(sum(y * (x - mean) ** 2) / sum(y)) area = sum(y[:-...
5,297,278
def as_strided(x, shape, strides, storage_offset=None): """Create a new view of array with the given shape, strides, and offset. Args: x (tuple of :class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): The array pointing a memory buffer. Its view is totall...
5,297,279
def GranularFormLayout(request): """ A simple demonstration of partial rendering of parts of forms. """ schema = schemaish.Structure() schema.add( 'firstName', schemaish.String(title='First Name', \ description='The name before your last one', \ validator=v...
5,297,280
def downgrade(): """ Executa as seguintes tarefas no banco de dados """ op.drop_table('grupos')
5,297,281
def _find_metadata(func): """ Support `xarray.DataArray` for find function. """ @functools.wraps(func) def wrapper(*args, **kwargs): x, y = args x_in, y_in, kwargs = _dataarray_strip(x, y, suffix=('', '_track'), **kwargs) x_out, y_out = func(x_in, y_in, **kwargs) # B...
5,297,282
def create_key_pair(dump: bool = True) -> Dict[str, Union[str, bytes]]: """create key pair :param dump: bool, True: return `bytes.hex`, False: return bytes :return: dict, { 'privateKey': private_key, 'publicKey': public_key, 'address': address } """ # generate priva...
5,297,283
def _forgy_center_initializer( X: np.ndarray, n_clusters: int, random_state: np.random.RandomState ) -> np.ndarray: """Compute the initial centers using forgy method. Parameters ---------- X : np.ndarray (3d array of shape (n_instances,n_dimensions,series_length)) Time series instances to c...
5,297,284
def download_song(title: str, link: str, path: str) -> None: """ Function, that downloads song from the web using wget command. """ system(f'wget -O {path}/{title}.mp3 "{link}"')
5,297,285
def export_table(data, output=None, tablefmt='psql'): """Creates a table as output""" df = pd.DataFrame(data) table = tabulate(df, headers='keys', showindex=False, tablefmt=tablefmt) if output is not None: with open(output, 'w') as outfile: outfile.write(table) else: prin...
5,297,286
def run_migration(migration_id: str, config: dict, app_logger: logger.Logger) -> bool: """ Run migration :param migration_id:. :param migration_id: id of migration to run :param config: pymigrate configuration :param app_logger: instance of configured logger """ migration_dir = os.path.join...
5,297,287
def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]: """Generates a wrapper for richcompare dunder methods.""" # Sort for determinism on Python 3.5 matches = sorted([name for name in RICHCOMPARE_OPS if cl.has_method(name)]) if not matches: return None name = '{}...
5,297,288
async def test_set_operation_bad_attr_and_state(hass): """Test setting operation mode without required attribute. Also check the state. """ state = hass.states.get(ENTITY_WATER_HEATER) assert state.attributes.get("operation_mode") == "eco" assert state.state == "eco" with pytest.raises(vol....
5,297,289
def assign_embedding_colors(points, texPath, flipTexUD=False, flipTexLR=False, rot90=0): """ :param points: :param texPath: :return: """ import imageio import numpy as np # read texture tex = np.array(imageio.imread(texPath)) if flipTexUD: tex = np.flipud(tex) if f...
5,297,290
def parse_table_html(s, first_row_th=True, first_col_th=False, cls=None): """ parser for csv table, creates html :s: the input string to parse, which should be of the format v11, v12, v13, v14 v21, v22, v23, v24 v31, v32, v...
5,297,291
def get_savings_rate(exp_records: list, inc_records: list) -> decimal.Decimal: """ :param List[far_core.db.ExpenseRecord] exp_records: window of expenses :param List[far_core.db.IncomeRecord] inc_records: window of incomes :return: the savings rate over the window, which is defined as: (income -...
5,297,292
def random_row(gdf,x,y): """ sampling the GNSS data randomly by entering the specific number of samples Parameters ---------- gdf: geodataframe geodataframe of all gnss data(population) x : int x is the number of samples y: int y is the random seed, different ran...
5,297,293
def _get_data_for_write( path: pathlib.Path, file_format: str, prefix_keys: typing.Iterable[str], ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.Dict[str, typing.Any]]: """ Retrieve the data from the file if it exists or create a new data object if not. :param path: Location of ...
5,297,294
def _fix(): """ Apply some fixes and patches. """ NS = globals() # Fix glGetActiveAttrib, since if its just the ctypes function if ('glGetActiveAttrib' in NS and hasattr(NS['glGetActiveAttrib'], 'restype')): def new_glGetActiveAttrib(program, index): # Prepare ...
5,297,295
def scipy_powell( criterion_and_derivative, x, lower_bounds, upper_bounds, *, convergence_relative_params_tolerance=CONVERGENCE_RELATIVE_PARAMS_TOLERANCE, convergence_relative_criterion_tolerance=CONVERGENCE_RELATIVE_CRITERION_TOLERANCE, stopping_max_criterion_evaluations=STOPPING_MAX_CR...
5,297,296
def configuration_check_for_servers(servers, option='servers', section='pull'): """Perform a sanity check against the values for servers. Arguments: servers (list): A list of servers. option (str): The name of the option they belong to. section (str): The name of the section the option ...
5,297,297
def prettyPrintDataFrame(df: pd.DataFrame, url_columns=["url"], max_column=50): """Prints pandas dataframes with custom max-width for column and potentially transforms URL into clickable content by using to_html(escape=False) method. WARNING!: Can potentially execute external code if not properly used. ...
5,297,298
def require_retrieval(test_case): """ Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with [`RagRetriever`]. These tests are skipped when respective libraries are not installed. """ if not (is_tf_available() and is_datasets_available() and is_faiss_...
5,297,299