content
stringlengths
22
815k
id
int64
0
4.91M
def _load_from_url(url: str, chinese_only=False) -> Mapping[str, DictionaryEntry]: """Reads the dictionary from a local file """ logging.info('Opening the dictionary remotely') with urllib.request.urlopen(url) as dict_file: data = dict_file.read().decode('utf-8') return _load_dictiona...
5,342,100
def get_images(): """ Canned response for glance images list call """ return images
5,342,101
def firstUniqChar(self, s): """ :type s: str :rtype: int """ letters = 'abcdefghijklmnopqrstuvwxyz' index = [s.index(l) for l in letters if s.count(l) == 1] return min(index) if len(index) > 0 else -1
5,342,102
def get_form_class_for_class(klass): """ A helper function for creating a model form class for a model on the fly. This is used with models (usually part of an inheritance hierarchy) which define a function **get_editable_fields** which returns an iterable of the field names which should be placed in th...
5,342,103
def dict_remove_key(d, key, default=None): """ removes a key from dict __WITH__ side effects Returns the found value if it was there (default=None). It also modifies the original dict. """ return d.pop(key, default)
5,342,104
def write_pickle(obj, path, makedir=True): """Write object in Python pickle format.""" # TODO: use normal pickling by implementing pickling protocol for Network # class http://docs.python.org/library/pickle.html#the-pickle-protocol # TODO: find out origin of maximum recursion depth problem, hack sol...
5,342,105
def momentum(snap: Snap, mask: Optional[ndarray] = None) -> ndarray: """Calculate the total momentum vector on a snapshot. Parameters ---------- snap The Snap object. mask Mask the particle arrays. Default is None. Returns ------- ndarray The total momentum as a...
5,342,106
def limit_epochs(tensor, num_epochs=None, name=None): """Returns tensor num_epochs times and then raises an OutOfRange error. Args: tensor: Any Tensor. num_epochs: An integer (optional). If specified, limits the number of steps the output tensor may be evaluated. name: A name for the operations ...
5,342,107
def init_app(app): """Register database functions with app.""" app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) app.cli.add_command(mock_db_command)
5,342,108
def hex_machine(emit): """ State machine for hex escaped characters in strings Args: emit (callable): callback for parsed value (number) Returns: callable: hex-parsing state machine """ left = 4 num = 0 def _hex(byte_data): nonlocal num, left if 0x30 <...
5,342,109
def write_json_to_file(file: str, data: Union[dict, list]): """ Creates a manifest to the file containing it's sha256sum and the installation result :param file: File to write to :param data: Dict to write :return: """ with open(file, "w", encoding="utf-8") as file_handle: json.dum...
5,342,110
def isbns(self, key, value): """Translates isbns fields.""" _isbns = self.get("identifiers", []) for v in force_list(value): subfield_u = clean_val("u", v, str) isbn = { "value": clean_val("a", v, str) or clean_val("z", v, str), "scheme": "ISBN", } if ...
5,342,111
def create_user(name, age, occupation): """ Function to post a new user. Parameters ---------- name : str Name of the user. age : int Age of the user. occupation : str Occupation of the user. Returns ------- message : str request_status : int ...
5,342,112
def gauss_dataset(dim, size=1e6): """ Creates a dataloader of randomly sampled gaussian noise The returned dataloader produces batsize batches of dim-sized vectors """ def samplef(bsize): return torch.randn(bsize, dim) ret = SampleDataset(samplef, size=size) return ret
5,342,113
def nightwatch_environment(request): # convenience spelling """Run tests against this environment (staging, production, etc.)""" return request.config.getoption('--nightwatch-environment')
5,342,114
def get_hrs(pid_arg): """ Pulls all recorded heart rate data for a patient from the database Args: pid_arg: patient_id to pull heart rate data for Returns: list: containing all recorded heart rates """ u5 = User.objects.raw({"_id": pid_arg}).first() return u5.heart_rate
5,342,115
def resolve(match, *objects): """Given an array of objects and a regex match, this function returns the first matched group if it exists in one of the objects, otherwise returns the orginial fully matches string by the regex. Example: if regex = \\\.([a-z]) and string = test\.abc, then the match = {group0: \...
5,342,116
def Collider_CollisionGroupsWorkflow(): # type: () -> None """ Summary: Runs an automated test to ensure PhysX collision groups dictate whether collisions happen or not. The test has two phases (A and B) for testing collision groups under different circumstances. Phase A is run first and upon su...
5,342,117
def _timestamp(zone="Europe/Istanbul") -> int: """Return timestamp of now.""" return int(time.mktime(datetime.now(timezone(zone)).timetuple()))
5,342,118
def sumReplacements(tex, functionName): """ Search tex file for the keyString "\\apisummary{" and its matching parenthesis. All text between will be processed such that there are no consecutive spaces, no tabs, and unnecessary "\\n". The text will then have all the macros replaced and put back into...
5,342,119
def parse_args(args): """ Parse command line parameters Parameters ---------- args : list command line parameters as list of strings Returns ------- argparse.Namespace : obj command line parameters namespace """ parser = argparse.ArgumentParser( descript...
5,342,120
def rle(seq, keyfunc=None): """ Run-length encode a sequence of values. This implements a generator which yields tuples `(symbol, begin, end)`. `begin` and `end` are indices into the passed sequence, begin inclusive and end exclusive. :param iterable seq: :param function keyfunc: opti...
5,342,121
def path(path: Union[str, List[str]], *, disable_stage_removal: Optional[bool] = False): """Validate the path in the event against the given path(s). The following APIErrorResponse subclasses are used: PathNotFoundError: When the path doesn't match. Args: path: A path literal or list of pa...
5,342,122
def get_last_id(statefile): """Retrieve last status ID from a file""" debug_print('Getting last ID from %s' % (statefile,)) try: f = open(statefile,'r') id = int(f.read()) f.close() except IOError: debug_print('IOError raised, returning zero (0)') return 0 de...
5,342,123
def inference_fn(trained_model, remove, fixed_params, overwrite_fixed_params=False, days_of_purchases=710, days_of_clicks=710, lifespan_of_items=710, **params): """ Function to run inference in...
5,342,124
def main(): """Gitlab."""
5,342,125
def initialize_mean_variance(args): """Initialize the current mean and variance values semi-intelligently. Inspired by the kmeans++ algorithm: iteratively choose new centers from the data by weighted sampling, favoring points that are distant from those already chosen """ X = args.X.reshape(args.X....
5,342,126
def verify_file_checksum(path, expected_checksum): """Verifies the sha256 checksum of a file.""" actual_checksum = calculate_file_checksum(path) return actual_checksum == expected_checksum
5,342,127
def float_to_str(f, p=20): """ 将给定的float转换为字符串,而无需借助科学计数法。 @param f 浮点数参数 @param p 精读 """ if type(f) == str: f = float(f) ctx = decimal.Context(p) d1 = ctx.create_decimal(repr(f)) return format(d1, 'f')
5,342,128
def get_classes(parsed) -> List[ClassDef]: """Returns classes identified in parsed Python code.""" return [ element for element in parsed.body if isinstance(element, ClassDef) ]
5,342,129
def get_steps(r): """Clone OSA.""" nextsteps = [] nextsteps.append( steps.SimpleCommandStep( 'git-clone-osa', ('git clone %s/openstack/openstack-ansible ' '/opt/openstack-ansible' % r.complete['git-mirror-openstack']), **r.kwargs ...
5,342,130
def check_java(interface): """ Checks for the presence of a minimally useful java on the user's system. """ interface.info("""\ I'm compiling a short test program, to see if you have a working JDK on your system. """) SOURCE = """\ class test { public static void main(String args[]) { ...
5,342,131
def test_list_nmtoken_max_length_1_nistxml_sv_iv_list_nmtoken_max_length_2_2(mode, save_output, output_format): """ Type list/NMTOKEN is restricted by facet maxLength with value 6. """ assert_bindings( schema="nistData/list/NMTOKEN/Schema+Instance/NISTSchema-SV-IV-list-NMTOKEN-maxLength-2.xsd", ...
5,342,132
def create_index( corpus_f: str, model_name_or_path: str, output_f: str, mode: str = "sent2vec", batch_size: int = 64, use_cuda: bool = False, ): """Given a corpus file `corpus_f` and a sent2vec model `sent2vec_f`, convert the sentences in the corpus (line-by-line) to vector represent...
5,342,133
def _convert_and_call(function, *args, **kwargs): """ Use annotation to convert args and kwargs to the correct type before calling function If __annotations__ is not present (py2k) or empty, do not perform any conversion. This tries to perform the conversion by calling the type (works for int,str). ...
5,342,134
def import_module(name, path): """ correct way of importing a module dynamically in python 3. :param name: name given to module instance. :param path: path to module. :return: module: returned module instance. """ spec = importlib.util.spec_from_file_location(name, path) module = importl...
5,342,135
def response_ssml_text_and_prompt(output, endsession, reprompt_text): """ create a Ssml response with prompt """ return { 'outputSpeech': { 'type': 'SSML', 'ssml': "<speak>" + output + "</speak>" }, 'reprompt': { 'outputSpeech': { 'ty...
5,342,136
def test_queryset_serialization(): """Verify that querysets may be serialized.""" articles = Article.objects.all() request = factory.get('/') assert Serializer(articles).serialize(request) == [ { 'id': 1, 'title': 'Title', 'content': 'Content', 'i...
5,342,137
def getAreaQuantityQuantUnit(words): """ from training data: count perc cum_sum cum_perc kind_c hectare 7 58.333333 7 58.333333 acre 2 16.666667 9 75.000000 meter 1 8.333333 10 8...
5,342,138
def add_user( username: str, password: Optional[str] = None, shell: str = "/bin/bash", system_user: bool = False, primary_group: str = None, secondary_groups: List[str] = None, uid: int = None, home_dir: str = None, ) -> str: """Add a user to the system. Will log but otherwise s...
5,342,139
def xyz_insert(weeded_list): """Inserts geometries into both orca and gaussian input files""" extension = ".inp" if preferences.comp_software == "orca" else preferences.gauss_ext sub_folder = os.path.join(os.getcwd(),"inserted_input_files") if os.path.exists(sub_folder): print("'inserted_input_files' directory al...
5,342,140
def main(): """Do nothing.""" pass
5,342,141
def tokenize_and_align(tokenizer, words, cased=False): """Splits up words into subword-level tokens.""" words = ["[CLS]"] + list(words) + ["[SEP]"] basic_tokenizer = tokenizer.basic_tokenizer tokenized_words = [] for word in words: word = tokenization.convert_to_unicode(word) word = basic_token...
5,342,142
def _vagrant_format_results(line): """Extract fields from vm status line. :param line: Status line for a running vm :type line: str :return: (<vm directory path>, <vm status>) :rtype: tuple of strings """ line_split = line.split() return (line_split[-1], line_split[-2],)
5,342,143
def rect_to_xys(rect, image_shape): """Convert rect to xys, i.e., eight points The `image_shape` is used to to make sure all points return are valid, i.e., within image area """ h, w = image_shape[0:2] def get_valid_x(x): if x < 0: return 0 if x >= w: return w...
5,342,144
def determine_aws_service_name( request: Request, services: ServiceCatalog = get_service_catalog() ) -> Optional[str]: """ Tries to determine the name of the AWS service an incoming request is targeting. :param request: to determine the target service name of :param services: service catalog (can be...
5,342,145
def comorder(node): """层序遍历, 广度优先搜索bfs 通过队列来实现 """ q = Queue() q.put(node) if node.data != None: # 循环取出node while q.empty() != True: node = q.get(0) print(node.data, end='') if node.node_left: q.put(node.node_left) ...
5,342,146
def file_senzing_info(): """#!/usr/bin/env bash # --- Main -------------------------------------------------------------------- SCRIPT_DIR="$( cd "$( dirname "${{BASH_SOURCE[0]}}" )" >/dev/null 2>&1 && pwd )" PROJECT_DIR="$(dirname ${{SCRIPT_DIR}})" source ${{SCRIPT_DIR}}/docker-environment-vars.sh RED='\033[0;...
5,342,147
def remove_barrier(tape): """Quantum function transform to remove Barrier gates. Args: qfunc (function): A quantum function. Returns: function: the transformed quantum function **Example** Consider the following quantum function: .. code-block:: python def qfunc(x, ...
5,342,148
async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator: DataUpdateCoordinator[Domain] = hass.data[DOMAIN][entry.entry_id] return { "creation_date": coordinator.data.creation_date, ...
5,342,149
def binary_to_single(param_dict: Dict[str, float], star_index: int) -> Dict[str, float]: """ Function for converting a dictionary with atmospheric parameters of a binary system to a dictionary of parameters for one of the two stars. Parameters ---------- param_dict : dict Dictionary...
5,342,150
def welcome(): """List all available api routes.""" return ( """Available Routes: /api/v1.0/precipitation Convert the query results to a dictionary using date as the key and prcp as the value. Return the JSON representation of your dictionary. /api/v1.0/...
5,342,151
def armenian_input_latin(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace latin characters with Armenian equivalents. """ if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'): return text textTrans = '' for c in re.findall('...
5,342,152
def create_audit_directory(): """ Creates directory for analyze_iam_policy audit files and places audit files there. """ audit_directory_path = HOME + CONFIG_DIRECTORY + AUDIT_DIRECTORY_FOLDER create_directory_if_it_doesnt_exist(audit_directory_path) destination = audit_directory_path exist...
5,342,153
def df_style_cell(*styles: Union[ Tuple[Callable[['cell'], bool], 'style'], Tuple['cell', 'style'], Callable[['cell'], Optional['style']], ]) -> Callable[['cell'], 'style']: """ Shorthand for df.style.applymap(...). Example usage: df.style.applymap(df_style_cell( (lambda x: 0 < x...
5,342,154
def _interactive_pick( plotter, model, picking_list: Optional[list] = None, key: str = "groups", label_size: int = 12, checkbox_size: int = 27, checkbox_color: Union[str, tuple, list] = "blue", checkbox_position: tuple = (5.0, 5.0), ): """Add a checkbox button widget to the scene."""...
5,342,155
def bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)): """Forward transform that maps proposal boxes to predicted ground-truth boxes using bounding-box regression deltas. See bbox_transform_inv for a description of the weights argument. """ if boxes.shape[0] == 0: return np.zeros((...
5,342,156
def get_item_tds(item_id): """ Method conntect to ILS to retrieve item information and generates an html table cells with the information. :param item_id: Item id :rtype: HTML string """ item_bot = ItemBot(opac_url=ils_settings.OPAC_URL,item_id=item_id) output_html = "<td>{0}</td><t...
5,342,157
def get_data(): """ Reads the data files. """ pass
5,342,158
def query_ports(session, switch_resource_id, **kwargs): """ Retrieve multiple :class:`Port` objects from database. switch_resource_id is optional # TODO: Implement and document query_ports() correctly """ # TODO: Add csv output option to query_ports() # Check all arguments before queryin...
5,342,159
def run(prefix): """ Exercise TensorMol calculator works together with Q|R. """ tm = TensormolCalculator() energy, gradient = tm.run_qr(tm.atoms.mols[0]) assert approx_equal(energy, -7.01911003671) assert approx_equal(gradient, [[54.72373444954559, 43.50211011650701, 55.0681687461352], ...
5,342,160
def build_data_request(mac, request_type='current', interval=1, units='english'): """ Creates RainWise API request for Recent Data based on station mac, format (optional), and units (optional) """ # Check if interval requested is valid interval if interval not in [1, 5, 10, 15, 30, 60]: rais...
5,342,161
def load_acs_access_to_car() -> pd.DataFrame: """Function to merge the two files for the QOL outputs and do some standard renaming. Because these are QOL indicators they remain in the same csv output with columns indicating year""" df_0812 = pd.read_excel( "./resources/ACS_PUMS/EDDT_ACS2008-2012.xls...
5,342,162
def canonicalize(top_dir): """ Canonicalize filepath. """ return os.path.realpath(top_dir)
5,342,163
def test_cpu_limit(): """Test the cpu n argument.""" if 'cpu' in fresnel.Device.available_modes: fresnel.Device(mode='cpu', n=2)
5,342,164
def elastic_transform(image, alpha, sigma, random_state=None): """Elastic deformation of images as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Confe...
5,342,165
def convert_epoch_to_mysql_timestamp(epoch_timestamp): """ Converts a given epoch timestamp in seconds to the MySQL datetime format. :param epoch_timestamp: The timestamp as seconds since epoch time :return: The MySQL timestamp string in the format 'Y-m-d HH:MM:SS' :rtype: str """ t...
5,342,166
def _ensure_eventlet(func): """Decorator that verifies we have the needed eventlet components.""" @six.wraps(func) def wrapper(*args, **kwargs): if not _utils.EVENTLET_AVAILABLE or greenthreading is None: raise RuntimeError('Eventlet is needed to wait on green futures') return f...
5,342,167
def ReplaceOldWithNewFile(orig_file='', new_temp_file=''): """ Compare original file and the new temp file ( contents and permissions). If they are the same, just remove the temp version. ( maybe not needed, handled in calling function) If they are different, backup original and then replace teh orig_f...
5,342,168
def check_public_key(pk): """ Checks if a given string is a public (or at least if it is formatted as if it is). :param pk: ECDSA public key to be checked. :type pk: hex str :return: True if the key matches the format, raise exception otherwise. :rtype: bool """ prefix = pk[0:2] l = le...
5,342,169
def write_json(data): """ Writing dictionary contents to a json file. Args: data (dict) -- The dictionary that will be placed into the json file. Returns: JsonPath -- The path to the json file. """ with open(_UI_CONFIGURATION, 'w') as json_file: json.dump(...
5,342,170
def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False return True
5,342,171
def main(): """ Calls the TEST functions in this module. """ run_test_problem1()
5,342,172
def validate_config_params(optimo_url, version, access_key): """Validates and normalizes the parameters passed to :class:`optimo.api.OptimoAPI` constructor. :param optimo_url: string url of the optimoroute's service :param version: ``int`` or ``str`` denoting the API version :param access_key: stri...
5,342,173
def deque_and_stack(): """Solution to exercise R-6.14. Repeat the previous problem using the deque D and an initially empty stack S. -------------------------------------------------------------------------- Solution: -------------------------------------------------------------------------- ...
5,342,174
def test_save_fails_without_path(): """User asked for save without specifying path""" with pytest.raises(ValueError): watchdog = PrivacyWatchdog( udl, target_delta=1e-5, target_epsilon=1.0, abort=True, save=True, path=None )
5,342,175
def apply_subst(name, user): """ user.username forced in lowercase (VMware Horizon) """ name = re.sub(r'_SCIPER_DIGIT_', user.sciper_digit, name) name = re.sub(r'_SCIPER_', user.sciper, name) name = re.sub(r'_USERNAME_', user.username.lower(), name) name = re.sub(r'_HOME_DIR_', user.home_...
5,342,176
def train_word2vec(): """ train word2vec model :return: """ class MyCorpus(object): def __init__(self): pass def __iter__(self): for fname in os.listdir(TEXT_DIR): text = read_document_from_text(os.path.join(TEXT_DIR, fname)) ...
5,342,177
def A_real_deph(Q_deph, Kt_real_deph, deltaT_diff_deph): """ Calculates the real heatransfer area. Parameters ---------- Q_deph : float The heat load of dephlegmator, [W] , [J/s] deltaT_diff_deph : float The coefficient difference of temperatures, [degrees celcium] Kt_real_de...
5,342,178
def is_1d_like(oned_like_object: Union[np.ndarray, np.void]) -> bool: """ Checks if the input is either a 1D numpy array or a structured numpy row. Parameters ---------- oned_like_object : Union[numpy.ndarray, numpy.void] The object to be checked. Raises ------ TypeError ...
5,342,179
def PDef (inDict): """ Create TableDesc from the contents of a Python Dictionary Returns new Table Descriptor inDict = Python dictionary with values, must be in the form produced by PGetDict """ ################################################################ # outTD = TableDe...
5,342,180
def minf(ar, min_val=nan): """ Gets the minimum value in the entire N-D array. @param ar The array. """ sa = shape(ar) np = 1 for n in sa: np *= n ar2 = reshape(ar, np) ar2 = delete(ar2, get_nan_inds(ar2), 0) cinds = [] if not isnan(min_val): ...
5,342,181
def read_from_netcdf(netcdf_file_name=None): """Reads boundary from NetCDF file. :param netcdf_file_name: Path to input file. If None, will look for file in repository. :return: latitudes_deg: See doc for `_check_boundary`. :return: longitudes_deg: Same. """ if netcdf_file_name is Non...
5,342,182
def update_pins(session): """ Update the python and docker pins version inplace. """ session.install("-e", ".[dev]") session.run("python", "bin/update_pythons.py", "--force") session.run("python", "bin/update_docker.py")
5,342,183
def generate_sector(size: int, object_weight: list) -> dict: """ Generates an Sector with Weighted Spawns Args: size: Int Representing the Size of the Sector (Size X Size) object_weight: An Nested List with Object / Value Types Examples: generate_sector(6, [["*", 50], ["#", 10]...
5,342,184
def run(port): """Run the daemon.""" reactor.listenTCP(port, NAFactory()) LOG.info('*** Tiedot NA Server starting @ port {}.'.format(port)) reactor.run()
5,342,185
def rbf_kernel(theta, h=-1): """Radial basis function kernel.""" sq_dist = _pdist(theta) pairwise_dists = _squareform(sq_dist) ** 2 if h < 0: # if h < 0, using median trick h = _numpy.median(pairwise_dists) h = _numpy.sqrt(0.5 * h / _numpy.log(theta.shape[0] + 1)) # compute the rbf...
5,342,186
def get_default_out_of_workspace_subcommands(): """Returns a dict of default out-of-workspace subcommands as <name: `CliCommand`>s :return: A dict of <name: `CliCommand`> """ new_cmd = NewCommand() return {new_cmd.name(): new_cmd}
5,342,187
def test_json_view(): """Turns a Python object into a response.""" def func(request): return {'x': 1} response = decorators.json_view(func)(mock.Mock()) assert isinstance(response, http.HttpResponse) eq_(response.content, '{"x": 1}') eq_(response['Content-Type'], 'application/json') ...
5,342,188
def compile(what, mimetype, cwd=None, uri_cwd=None, debug=None): """ Compile a given text based on mimetype. The text to compile must be provided as a Unicode object and this function must return the compiled text as a Unicode object. """ try: compiler = compilers[mimetype.lower()] ...
5,342,189
def run_model(idx): """ Run BART on idx index from dataset. Args: idx (int): The index of the dataset. Returns: tuple: tuple with fname: Filename slice_num: Slice number. prediction: Reconstructed image. """ masked_kspace, reg_wt, fname, slic...
5,342,190
def _saveJob(event): """ When a job is saved, if it is a docker run task, add the Dask Bokeh port to the list of exposed ports. """ job = event.info try: from bson import json_util jobkwargs = json_util.loads(job['kwargs']) if ('docker_run_args' not in jobkwargs['task'] ...
5,342,191
async def test_invoke_default_fail(default_listener, inter): """Test a default listener invocation that fails during param conversion.""" inter.component.custom_id = "default_listener<>abc" with pytest.raises(components.exceptions.ConversionError) as exc_info: await default_listener(inter) ass...
5,342,192
def is_tt_tensor(arg) -> bool: """Determine whether the object is a `TT-Tensor` or `WrappedTT` with underlying `TT-Tensor`. :return: `True` if `TT-Tensor` or `WrappedTT(TT-Tensor)`, `False` otherwise :rtype: bool """ return isinstance(arg, TT) or (isinstance(arg, WrappedTT) and not arg.tt.is_tt_m...
5,342,193
def wait_for_event(event): """wait for the event to be set before doing anything""" print('wait_for_event: starting') event.wait() print('wait_for_event: event.is_set()-> ', event.is_set())
5,342,194
def ensure_node(): """ Ensure nodejs from nodesource is installed """ key = b""" -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 Comment: GPGTools - https://gpgtools.org mQINBFObJLYBEADkFW8HMjsoYRJQ4nCYC/6Eh0yLWHWfCh+/9ZSIj4w/pOe2V6V+ W6DHY3kK3a+2bxrax9EqKe7uxkSKf95gfns+I9+R+RJfRpb1qvljURr54y35I...
5,342,195
def top_predicted_outcomes(proba_pred, index_to_outcome_dict, N_top = 3): """ extract the most likely outcomes based on a 1d-array of predicted probabilities Parameters ---------- proba_pred: numpy 1d-array array containing the predicted probabilities index_to_outcome_dict: dict r...
5,342,196
def parse_kafka_table(beamsqltable, name, logger): # loop through the kafka structure # map all key value pairs to 'key' = 'value', # except properties """ parse kafka parameter """ ddl = "" kafka = beamsqltable.spec.get("kafka") if not kafka: message = f"Beamsqltable {name} ...
5,342,197
def submit(client, job_path, output_job_path, files): """ Submit a new Fuzzing Job via the MSRD REST API. """ with open(job_path) as input_job_file: job = json.load(input_job_file) job = add_file_info_to_job(client, job, files) if output_job_path: with open(output_job_path) as ...
5,342,198
def linear_operator_from_num_variables(num_variables, type_, W): """Generates the linear operator for the TV lasso Nesterov function from number of variables. Parameters: ---------- num_variables : Integer. The total number of variables, including the intercept variable(s). """ ...
5,342,199