content
stringlengths
22
815k
id
int64
0
4.91M
def thread_get_messages(service, thread): """Get the list of messages in a given thread. Args: service: gmail api service object. thread: thread from which to get the messages. Returns: list of messages objects (minimal format: only id and label). """ _Context.set('Thread {}: retrieving l...
69,000
def cc_cyclic(amp: Tuple[int, int] = (10, 15), freq: Tuple[int, int] = (10, 15)) -> DeltaGenerator: """ Creates a cyclic shape control chart sequence Parameters ---------- amp: Tuple. Defaults to (10,15) Chooses randomly a number between the tuple values as amplitude of the oscillation....
69,001
def activate(): """ Return the path to the `activate` shell script within a virtual environment. """ path_to_venv = os.environ.get("PATH_TO_VENV", "venv") if os.name != "nt": # Posix return os.path.join(path_to_venv, "bin", "activate") else: # Windows return os.pa...
69,002
def predict(X, y, parameters): """ This function is used to predict the results of a L-layer neural network. Arguments: X -- data set of examples you would like to label parameters -- parameters of the trained model Returns: p -- predictions for the given dataset X """ ...
69,003
def build_log_src_prior(prior_type, xs, ys): """ Construct a log-probability distribution from a prior type specifier. Units are probability per area. """ shape = (len(xs), len(ys)) dx = np.mean(np.diff(xs)) dy = np.mean(np.diff(ys)) if prior_type == 'uniform': log_p_unnormaliz...
69,004
def test_vec_identities(py_c_vec: PyCVec) -> None: """Check that vectors in the same axis as the rotation don't get spun.""" Vec, Angle, Matrix, parse_vec_str = py_c_vec for ang in range(0, 360, 13): # Check the two constructors match. assert_rot(Matrix.from_pitch(ang), Matrix.from_angle(An...
69,005
def decorate_plot(x, y, xlabel, ylabel): """Decorate the plot with labels.""" pl.axis([0, np.max(x)*1.1, 0, np.max(y)*1.1]) pl.legend(numpoints=1, prop=dict(size=20), fancybox=True, loc='lower right') pl.xticks(fontsize=20) pl.xlabel(xlabel, fontsize=24) pl.yticks(fontsize=20) pl.ylabel(ylab...
69,006
def run(): """ Run the workbench server """ # Load the configuration file relative to this script location config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini') workbench_conf = ConfigParser.ConfigParser() config_ini = workbench_conf.read(config_path) if not conf...
69,007
def query_lat_long_with_fallback(address): """ Make a query for latlong from address with fallback mechanism. The method will first attempt to query latlong from Google geocoding service for it's higher precision. If the server cannot connect to the Google service or a timeout happens, the server tries to ...
69,008
def GEV_mean(mu, sigma, xi): """Calculate the mean of a GEV distribution. The arguments mu, sigma, and xi are the location, scale, and shape parameter of the GEV distribution, respectively. """ if xi >= 1: return np.inf elif xi == 0: return mu + sigma * np.euler_gamma else: ...
69,009
def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, aa_features, do_hydro, do_charge, do_pks, do_solubility, ...
69,010
def delete_dup_greater_than(text): """Processes html text deleting duplicated '>' generated after previous processing steps. Args: text (string): html text that is going to be processed. Returns: string: text once it's processed. """ p1 = re.compile(r'(<br>)(>)(</)', re.UNICODE) processed_text = p1.sub(r'...
69,011
def update_config(config, update): """ Update a configuration dictionary with an update configuration dictionary. These two dictionaries are JSON objects. This simply merges the two dictionaries (dictionaries are merged recursively, lists are concatenated) """ for k, v in update.items(): ...
69,012
def svc_model_adjustment_optimization_score(X_train,X_test,y_train,y_test): """ ๆ”ฏๆŒๅ‘้‡ๆœบ Support Vector Machine """ svc_params = {'C': [0.5, 0.7, 0.9, 1], 'kernel': ['rbf', 'poly', 'sigmoid', 'linear']} return model_adjustment_optimization(SVC(),'Support Vector Machine',svc_params,X_train,X_test,y_trai...
69,013
def msg_handle_KOR(string)->list: """Sort for data, double check with isit_covid""" isit_covid = False day = 0 #(0: default, 1: ์˜ค๋Š˜, 2:์–ด์ œ, 3:๊ทธ์ €๊ป˜) my_list = split_string(string) print(string) #0 ๊ธฐ๋ณธ ์–ธ์–ด : ์ฝ”๋กœ๋‚˜, ํ™•์ง„์ž, ๋ช‡, ๋ช… if check_item(my_list, '์ฝ”๋กœ๋‚˜'): if check_item(my_list, '๋ช…') or check_...
69,014
def activity_diff(context: Context, data_dict: DataDict) -> dict[str, Any]: """Returns a diff of the activity, compared to the previous version of the object :param id: the id of the activity :type id: string :param object_type: 'package', 'user', 'group' or 'organization' :type object_type: st...
69,015
def property_graph(graph='g1'): """ Define the properties of the graph to generate :graph : type of desired graph. Options : ['g1','g2', 'g3', 'g4', 'g5'] """ if graph == 'g1': method = 'partition' sizes = [75, 75] probs = [[0.10, 0.005], [0.005, 0.10]] number_class =...
69,016
def readxtalkcoeff(xtalkfile): """read crosstalk coefficent file""" xdict = {} try: xfile = open(xtalkfile,'r') for line in xfile: if (len(line.strip()) > 0 and line[0] != '#'): line = line.rstrip('\r\n') line = line.rstrip() line =...
69,017
def radec2altaz(radec, location, obstime=None, epoch_RA=2000.0, time_type=None): """ ---------------------------------------------------------------------------- Convert RA-Dec to Alt-Az with accurate ephemeris Inputs: radec [numpy array] Altitude and Azimuth as a Nx2 numpy array. All units ...
69,018
def initial_setup(args: config.Params, cl_args: argparse.Namespace) -> (config.Params, int): """Perform setup steps: 1. create project, exp, and run dirs if they don't already exist 2. create log formatter 3. configure GCP remote logging 4. set up email notifier 5. log git info 6. write the...
69,019
def test_create_update_items_start_time_equals_worktime(workplan_model): """Checking when the update date is equals the first worktime_utc.""" worktime = pendulum.datetime(2020, 1, 1, tz="Europe/Moscow") interval_timedelta = dt.timedelta(1) workplan_model.create( **{ workplan_model.n...
69,020
def filter_properties(person, PERSON_PROPERTIES): """ Extract specific properties of the given person into a new dictionary. Parameters: person (dict): the dictionary containing properties of a person. PERSON_PROPERTIES (tupl): a tuple containing the characteristics of a person Returns...
69,021
def OriginFromArg(arg): """Constructs the origin for the token from a command line argument. Returns None if this is not possible (neither a valid hostname nor a valid origin URL was provided.) """ # Does it look like a hostname? hostname = HostnameFromArg(arg) if hostname: return "https://" + hostna...
69,022
def test_attributes(): """ Test for expected package attributes. """ # Package information assert geometry.Geometry assert geometry.CartesianGeometry
69,023
def import_module(module, app): """Handle the import of a module by mocking them with autodoc config. Query the value of ``autodoc_mock_imports`` inside the ``conf.py`` module. Arguments: module (str): The name of the module to import. app (Sphinx): The current sphinx application. Ret...
69,024
def landsat8_spectral_indices(img): """ Function that computes several spectral indices for Landsat 8 sensor. The indices specifically focus in detecting vegetation phenology, and water and salt content in the soil. The indices are added to the input image as bands. The function can be used either w...
69,025
def rphiz_to_xyz(values): """Converts axis values from cylindrical coordinates into cartesian coordinates Parameters ---------- values: array Values of the axis to convert (Nx3) Returns ------- ndarray of the axis (Nx3) """ r = values[:, 0] phi = values[:, 1] if len...
69,026
def get_opt_solution(model=None): """Returns the solution found for the optimization parameters as data frame The resulting data frame will have the columns: * `name`: the name of the parameter * `lower`: the parameters lower bound * `upper`: the parameters upper bound * `sol`: the solution fo...
69,027
def load_conv(save_path, name): """Load convolution layer parameters""" fname = os.path.join(save_path, '%s.msg' % name) with open(fname) as f: weight = mp.unpack(f) bias = mp.unpack(f) weight = np.asarray(weight).astype(np.float32) bias = np.asarray(bias).astype(np.floa...
69,028
def invert(image): """Invert the given image. :param image: image :returns: inverted image """ assert np.amin(image) >= -1e-6 assert np.amax(image) <= 1+1e-6 return 1.0 - np.clip(image, 0, 1.0)
69,029
def PublicObject_IsRegistrationEnabled(): """PublicObject_IsRegistrationEnabled() -> bool""" return _DataModel.PublicObject_IsRegistrationEnabled()
69,030
def element_triple_cross(A, B, C): """Return element-wise triple cross product of three 3D arr in Cartesian""" return ( B * (element_dot(A, C))[:, :, np.newaxis] - C * (element_dot(A, B))[:, :, np.newaxis] )
69,031
def get_anatomical(): """ Get nltools default anatomical image. """ return nib.load(os.path.join(get_resource_path(),'MNI152_T1_2mm.nii.gz'))
69,032
def dict_sample(d, cutoff=-1): """ Sample a key from a dictionary using the values as probabilities (unnormalized) """ if cutoff==-1: cutoff = random() normalizer = float(sum(d.values())) current = 0 for i in d: assert(d[i] > 0) current += float(d[i]) / normalizer ...
69,033
def mems(state, data): """tracks memory writes Provides the 'mems' field that represents all updates made by the current instruction to the memory in a form of a mapping from addresses to bytes. Both are represented with the Python int type """ if state['event'] == 'pc-changed': sta...
69,034
def new_options(lights: list[int], exclude: list[int]) -> dict: """Create a standard options object.""" return {CONF_LIGHTS: lights, CONF_EXCLUDE: exclude}
69,035
def upload_upf_family(folder, group_name, group_description, stop_if_existing=True): """ Upload a set of UPF files in a given group. :param folder: a path containing all UPF files to be added. Only files ending in .UPF (case-insensitive) are considered. :param group_name: ...
69,036
def from_list(leaves: List[hash.Hash]) -> Optional[MerkleTree]: """Create Merkle tree from one or more nodes.""" if not leaves: return None head, tail = leaves[0], leaves[1:] t = from_singleton(head) for leaf in tail: t.insert(leaf) return t
69,037
def get_instance_availability_zone(context, instance): """Return availability zone of specified instance.""" host = instance.host if 'host' in instance else None if not host: # Likely hasn't reached a viable compute node yet so give back the # desired availability_zone in the instance record...
69,038
def add_generic_handlers(socketio): """ Attach handlers to the socketio instance """ socketio.on_event("connect", handle_connection) socketio.on_event("disconnect", handle_disconnection) socketio.on_event("my_event", handle_custom_event)
69,039
async def test_registering_view_while_running(opp, aiohttp_client, aiohttp_unused_port): """Test that we can register a view while the server is running.""" await async_setup_component( opp, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: aiohttp_unused_port()}} ) await opp.async_start() ...
69,040
def makedir(p): """Create directory at path and its parents. Args: p: Path-like object """ path = Path(p) path.mkdir(exist_ok=True, parents=True)
69,041
def guidedFilter(guide, src, radius, eps, dst=None, dDepth=None): """ guidedFilter(guide, src, radius, eps[, dst[, dDepth]]) -> dst """ pass
69,042
def iter_wave_dots( wr: wave.Wave_read, chunk: int = 0 ) -> Generator: """Return a generator of wave dots. :param wr: a ``Wave_read`` object :param chunk: The number of handled wave dots in every iteration. 0 means returning all the wave dots. (default: 0) :return: a generator obj...
69,043
def start_collector(): """Endpoint for starting the collector. Route command to CollectorHandler object.""" run_id = None try: data = request.get_json() start_delta = data['start'] stop_delta = data['stop'] interval = data['interval'] if ("id" in data) is True: ...
69,044
def _distribute_conversion_values( data_consent: pd.DataFrame, conversion_column: str, non_consent_conversion_values: Sequence[float], weighted_conversion_values: Sequence[np.ndarray], neighbors_index: Sequence[np.ndarray], neighbors_distance: Sequence[np.ndarray], weighted_distance: Sequenc...
69,045
def border(x, y, width, pt=20, slant=0.5): """Draws a handrwritten rectangle at (x,y) with given width. This command is usually called from within the pixie text paragraph() command as a callback that draws borders around words. """ _ctx.transform(CENTER) #Somewhere in ...
69,046
def _get_default_frame(instance, shared_tags): """Extracts a metadata from volumetric enhanced instance, drops heavy tags.""" delete_tags(instance, EXCLUDE_TAGS.keys()) for tag in shared_tags: instance.add(tag) return instance
69,047
def download_sst(path, url): """" Download from `url` the zip file corresponding to the Stanford Sentiment Treebank and expand the resulting files into the directory `path` (Note: if the files are already present, the download is not actually run). Arguments --------- path : str, di...
69,048
def load_csv_to_numpy(dir: str): """ Module to load csv files. Args: dir: """ csv = np.genfromtxt(dir, delimiter=',') csv = csv[1:len(csv), 2:5].astype('uint16') return csv
69,049
def comp_cc(x1, x2, maxTimeLag, binSize, numBin): """Compute cross- or auto-correlation from binned data (without normalization). Uses matrix computations to speed up, preferred when multiple processors are available. Parameters ----------- x1, x2 : nd array time-series from binned data (nu...
69,050
def _unlabeled_balls_in_labeled_boxes(balls, box_sizes): """ This recursive generator function was designed to be returned by `unlabeled_balls_in_labeled_boxes`. """ # If there are no balls, all boxes must be empty: if not balls: yield len(box_sizes) * (0,) elif len(box_sizes) == 1: ...
69,051
def test_get_credentials_none_found(monkeypatch): """Tests if it raises the CredentialError if credentials are not found.""" monkeypatch.setattr(sys, "platform", "darwin") monkeypatch.setattr(KeychainCredentialProvider, "_get_keyring_credentials", lambda c: None) with pytest.raises(CredentialError): ...
69,052
def show_memory_info(hint=""): """show_memory_info""" pid = os.getpid() p = psutil.Process(pid) info = p.memory_full_info() memory = info.uss / 1024. / 1024 print(f"{hint} memory used: {memory} MB ")
69,053
def export_to_obj_file3D(polys, fname=None, scale=1, single_mesh=True, uv_map=False, name="poly"): """ exports 3D mesh result to obj file format """ try: dist = polys["dist"] points = polys["points"] rays_vertices = polys["rays_vertices"] rays_faces = polys["rays_faces"] exc...
69,054
def get_objects_from_canvas_by_type(canvas, typename): """ Read objects in canvas and filter by typename :param canvas: canvas :type canvas: TCanvas :param typename: type of object to be filtered :type typename: str :return: objects of type typename in canvas :rtype: list[typename] "...
69,055
def get_chain_hash(contract, s, u_i, s_i, a, b, bytes_30, dyn_bytes, bar_uint, arr) -> bytes: """Uses the contract to create and hash a Foo struct with the given parameters.""" result = contract.functions.hashFooStructFromParams(s, u_i, s_i, a, b, bytes_30, dyn_bytes, bar_uint, arr).call() return result
69,056
def update_plot_hover(ser, year, month, hoverdict): """ Update the history plot, as function of: * selected year in year-slider * selected month in month-slider * selected day in hist-slider In case of None use Current year as default year In case of None month use January as default ...
69,057
def config(key, value, local=True): """Set that config key to that value Unless local is set to False: only change local config """ option = local and '--local' or '' run(f'config {option} "{key}" "{value}"')
69,058
def cluster_script(amoptd, python_path="ccp4-python"): """Create the script for ensembling on a cluster Parameters ---------- amoptd : dict An AMPLE option dictionary python_path : str, optional The path to the CCP4 python executable Returns ------- str The path to...
69,059
def build_hooks(model_configs, distributed_mode=False, is_chief=True): """ Builds training hooks. Args: model_configs: A dictionary of all configurations. distributed_mode: Whether is running under a distributed setting. is_chief: Whether this is the chief process. Returns: A list ...
69,060
def test_zero_one_to_cartesain_incorrect_mode(): """ Test to ensure that an incorrect mode raises an error """ x = np.random.rand(1000) with pytest.raises(RuntimeError) as excinfo: legacy.zero_one_to_cartesian(x, mode='roar') assert 'Unknown mode' in str(excinfo.value)
69,061
def attribute_vertex_perimeter(graph, edge_length=None): """ Vertex perimeter of the given graph. The perimeter of a vertex is defined as the sum of the length of out-edges of the vertex. If the input graph has an attribute value `no_border_vertex_out_degree`, then each vertex perimeter is assumed to b...
69,062
def get_status(dev, recipient, index = 0): """ Get status of the recipient Args: dev - pyusb device recipient - CTRL_RECIPIENT_DEVICE/CTRL_RECIPIENT_INTERFACE/CTRL_RECIPIENT_ENDPOINT index - 0 if recipient is device, interface index if recipient is interface, endpoint index if recipient...
69,063
def map_ttf_to_shx(ttf: str) -> Optional[str]: """Map TTF file names to SHX font names. e.g. "txt_____.ttf" -> "TXT" """ return TTF_TO_SHX.get(ttf.lower())
69,064
def right(ctx): """Work with rights \b Note All sub-commands execute in the context of organization specified via --org option; it defaults to current organization-in-use if --org option is not specified. \b Examples vcd right list -o myOrg Gets list of rights asso...
69,065
def load_kinetics_database(libraries: Optional[list] = None): """ A helper function to load thermo database given libraries used Args: libraries (Optional[list]): A list of libraries to be imported. All libraies will be imported if not assigned. """ kinet...
69,066
def main(): """A simple main""" parser = argparse.ArgumentParser() parser.add_argument( "--ip", type=str, default=robot_IP, help="Robot IP address. On robot or Local Naoqi: use '192.168.11.3'.") parser.add_argument( "--port", type=int, default=9559, help="Naoqi po...
69,067
def edit_beatmap_comment(request, collection_id, beatmap_entry_id): """View for edit beatmap comment in BeatmapEntry""" collection = get_object_or_404(Collection, id=collection_id) beatmap_entry = get_object_or_404(BeatmapEntry, id=beatmap_entry_id, collection=collection) if request.user != collection.a...
69,068
def call_languages(MODE: str, PROCESS_MODE: str, TIMES: int) -> dict[str: float]: """Function that calls the languages and captures the output(version and execution time) and gets the compile time with the GNU Time command. Args: MODE (str): The mode of the program (fast || slow). PROCESS_MODE ...
69,069
def add_const(key, val, skip_exists=True): """import order matters, i.e. 4A's flows file will overrule lc-py""" v = S.constants.get(key) if v is not None: app.warn('Overwriting constant %s' % key, have=v, new=val) S.constants[key] = val
69,070
def oct2text(oct_text): """ Takes in a string oct_text, returns the decoded plain text.""" #Raise exception if there are no spaces in the text if not " " in oct_text and len(oct_text)>3: raise ValueError(noSpaceError.format("oct_text")) oct_text = oct_text.strip() #Converts the oct to text plain_...
69,071
def tanh(z): """Hyperbolic tangent function... Args: z (np.array) Returns: f(z) = 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0 (np.array) """ return 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0
69,072
def test_read_selavy_fwf(mocker): """ Tests read_selavy for a file with standard fixed-width formatting. Args: mocker: Pytest mock mocker object. Returns: None. """ mock_table_read = mocker.patch( 'vasttools.utils.pd.read_fwf') test_filename = 'test.txt' vtu.read...
69,073
def from_qmi_response(problem, response, embedding_context=None, warnings=None, params=None, sampleset=None): """Construct problem data for visualization based on the low-level sampling problem definition and the low-level response. Args: problem ((list/dict, dict[(int, int), ...
69,074
def read(files, v2i, r2i, m, U): """ Read data from files Arguments files: list of files (train, test, valid, aux splits) v2i: vertex-to-index map r2i: relation-to-index map m: maximum size of hyperedge U: set of unseen entities Returns inc: the incidence struct...
69,075
def test_refresh_hkp(openpgp_env_with_refresh, hkp_server, manifest_var, key_var, server_key_fpr, server_key_var, expected): """Test refreshing against a HKP keyserver""" try: if key_var is not None: with io.BytesIO(globals()[key_var]) as f: openpgp_env_w...
69,076
def graph_search_for_vis(problem): """Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. If two paths reach a state, only use the first one.""" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] ...
69,077
def api_runs(resource_id, run_id=None, content_type='json'): """ Get Runs (History of results) for Resource. """ if run_id: runs = [views.get_run_by_id(run_id)] else: runs = views.get_run_by_resource_id(resource_id) run_arr = [] for run in runs: run_dict = { ...
69,078
def _update_playlist_index_state(checked: bool, playlist_items: str, window: Sg.Window) -> None: """ Update the current playlist index form state Keyword arguments: checked -- The value (True to activate form, False to deactivate it) playlist_items -- The playlist items value window...
69,079
def test_build(mocker): """ GIVEN arguments from the parser WHEN they are passed to the build() function THEN the function execute """ m_validate = mocker.patch("open_alchemy.cli.validate_specfile") m_build_json = mocker.patch("open_alchemy.cli.build_json") args = mock.MagicMock() ar...
69,080
def export_document_to_mstr(connection, document_id, instance_id, body, error_msg=None): """Export a specific document in a specific project to an .mstr file. Args: connection: MicroStrategy REST API connection object document_id (string): Document ID instanc...
69,081
def plot_flowcorr(self,scale=None): """ Plots the flowcorr map """ warnings.warn( 'plot_flowcorr is depreciated. Use plot_spatial instead', DepreciationWarning ) try: extent = [0, self.flowcorr.shape[1], 0, self.flowcorr.shape[0]] data = plotting.downsample(self.flowcorr,scale=scale...
69,082
def base_parser(): """Shared arguments for training and evaluation.""" parser = argparse.ArgumentParser() parser.add_argument( '--input-filenames', required=True, nargs='+', type=gcs_file ) parser.add_argument( '--sentence-length', type=int, de...
69,083
def generate(row): """Get china: country, province, city. :param str row: The result of row parsed from qqwry :return: A tuple. """ candicates = Province.china for (cn, province) in candicates: if province in row: _, city = row.split(province) return cn, provi...
69,084
def freqz_cas(sos,w): """ Cascade frequency response Mark Wickert October 2016 """ Ns,Mcol = sos.shape w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w) for k in range(1,Ns): w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w) Hcas *= Htemp return w, Hcas
69,085
def import_dotted_path(path): """ Takes a dotted path to a member name in a module, and returns the member after importing it. """ # stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path) try: module_path, member_name = path.rsplit(".", 1) module = import_module(mod...
69,086
def getBandNoFilter(folderPath): """ getBand is used for getting image exported from gee. Parameters ---------- [folderPath]: variable read by rasterio Returns ------- [b1,b2]: the target layer """ # read images in the folder searchCriteria = "*.tif" globInput = os.p...
69,087
def send_bulk_email(build,send_list,window): """Build and send bulk messages""" try: for c in send_list: if c.status == 'prospect': subject = settings.PROSPECT_SUBJECTS[randint(0,len(settings.PROSPECT_SUBJECTS)-1)] body = settings.PROSPECT_TEMPLATES[randint(0,...
69,088
def sdm_info(): """ SUN decrypting/validating endpoint. """ enc_picc_data = request.args.get(ENC_PICC_DATA_PARAM) enc_file_data = request.args.get(ENC_FILE_DATA_PARAM) sdmmac = request.args.get(SDMMAC_PARAM) if not enc_picc_data or not sdmmac: raise BadRequest("Parameter {} is requi...
69,089
def delete_metadata_store(metadata_store_name: str): """Delete a metadata store.""" service = Repository().get_service() cli_utils.declare(f"Deleting metadata store: {metadata_store_name}") service.delete_metadata_store(metadata_store_name) cli_utils.declare("Deleted!")
69,090
def get_module_functions(module): """ Helper function to get the functions of an imported module as a dictionary. Args: module: python module Returns: dict: module functions mapping { "func1_name": func1, "func2_name": func2,... } """ mo...
69,091
def evaluate_posterior_predictive(samples: xr.Dataset, test: xr.Dataset) -> np.ndarray: """ Computes the predictive likelihood of all the test items w.r.t. each sample. See the class documentation for the `samples` and `test` parameters. :returns: a numpy array of the same size as the sample dimension. ...
69,092
def get_logger() -> Any: """ An entry point of the plug-in and return the usage logger. """ return KoalasUsageLogger()
69,093
def circle_image(shape, center, radii, intensities): """ Creates an image with circle or thickness 2 """ im = np.zeros(shape=shape, dtype=np.float) xx, yy = np.ogrid[0 : shape[0], 0 : shape[1]] xx, yy = xx - center[0], yy - center[1] for radius, intensity in zip(radii, intensities): rr = np....
69,094
def write_number(n): """ Make n dots at the current position. The position should be adjusted before by pen_gfield(). """ { 1: one, 2: two, 3: three, 4: four, 5: five, 6: six, 7: seven, 8: eight, 9: nine }[n]()
69,095
def upsample(prob_maps_multiple_images, output_shape): """ Function for performing upsamping of probability maps :param prob_maps: Probability maps for each class for each resized image :param output_shape: Desired shape to upsample to (should be dimensions of original image) :return: """ up...
69,096
def create_planning_page(skicall): """Fills in the planning page""" call_data = skicall.call_data page_data = skicall.page_data # set date input field to be a datepicker page_data['add_jscript'] = """ $( "#dateradec" ).datepicker({dateFormat: "yy-mm-dd"}); $( "#datename" ).datepicker({dateFormat: ...
69,097
def closest_dataframe_from_origins_destinations(origins, origin_id_fld, destinations, dest_id_fld, gis=None, network_dataset=None, destination_count=4): """ Create a closest destination dataframe using origin and destination Spatially Enabled Dataframes. :para...
69,098
def naive(string: str): """ Recognize POS in a string using Regex. Parameters ---------- string: str Returns ------- string : tokenized string with POS related """ string = string.lower() results = [] for i in string.split(): results.append(_naive_POS_word(i)) ...
69,099