content
stringlengths
22
815k
id
int64
0
4.91M
def load_embeddings_from_imgs(det_df, dataset_params, seq_info_dict, cnn_model, return_imgs = False, use_cuda=True): """ Computes embeddings for each detection in det_df with a CNN. Args: det_df: pd.DataFrame with detection coordinates seq_info_dict: dict with sequence meta info (we need fra...
5,305,600
def send_notification(subject, recipients, html, mailtype=''): """ Generic email sending method, handly only HTML emails currently """ if not EMAIL_USER or not EMAIL_API_ENDPOINT: logger.warning( 'Cannot send notifications.\n' 'No username and/or API endpoint set as environment v...
5,305,601
def serial_to_usb_widget(serial_into_USBhub_port_displayed): """Function used to create Jupyter widget. It takes the parameter chosen from the widget and returns it such that it can be used as a variable. Args: serial_into_USBhub_port (str) : the port number of the USB Hub that the Serial Adaptor i...
5,305,602
def build_discriminator(input_shape=(256, 256, 3)): """Returns the discriminator network of the GAN. Args: input_shape (tuple, optional): shape of the input image. Defaults to (256, 256, 3). Returns: 'Model' object: GAN discriminator. """ x0 = layers.Input(input_shape) ...
5,305,603
def user_list(_request): """ This will return a list of all users in the database """ # We'd really like to do .distinct, but sqlite+django does not support this; # hence the hack with sorted(set(...)) users = sorted( user_id[0] for user_id in set(XBlockState.objects.values_list(...
5,305,604
def price_dataframe(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='actual_close', cleaner=clean_dataframe, ): """Retrieve the prices of a list of equities as a DataFrame (columns = symbols) Arguments: symbols (list of str):...
5,305,605
def split_nth(string, count): """ Splits string to equally-sized chunks """ return [string[i:i+count] for i in range(0, len(string), count)]
5,305,606
def market_EWindex(market: simuldata.Market, name: str="Market EW Index") -> pd.DataFrame: """ Sums all assets to make an index, corresponds to the Equally-Weighed (EW) index. The formula for the weights here is: w_i = c / N for all i and we choose c = N so that \sum_i w_i = N. Thus we...
5,305,607
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first...
5,305,608
def _SendNotificationEmail(old_test_key, new_test_key): """Send a notification email about the test migration. This function should be called after we have already found out that there are no new rows to move from the old test to the new test, but before we actually delete the old test. Args: old_test_k...
5,305,609
def column_hash_values(column0, *other_columns, initial_hash_values=None): """Hash all values in the given columns. Returns a new NumericalColumn[int32] """ columns = [column0] + list(other_columns) buf = Buffer(rmm.device_array(len(column0), dtype=np.int32)) result = NumericalColumn(data=buf, d...
5,305,610
def get_service_from_request( request, raise_exception: bool = True ) -> Optional[Service]: """Return the service for the request. Unauthenticated calls will identify the service using ServiceAPIKey. Authenticated calls will check the azp claim of the auth token to see if the client id has been map...
5,305,611
def resnet50( sensor: str, bands: str, pretrained: bool = False, progress: bool = True, **kwargs: Any, ) -> ResNet: """ResNet-50 model. If you use this model in your research, please cite the following paper: * https://arxiv.org/pdf/1512.03385.pdf Args: sensor: imagery sou...
5,305,612
def requests(): """SCORM packages will perform requests to this method, which will interact with the permitted laboratories""" db_lt = db.session.query(LearningTool).filter_by(name = g.lt).first() if request.method == 'GET': local_identifiers = [ permission.local_identifier for permission i...
5,305,613
def divide_graph(graph, distance): """ divide graph with connected components by links whose distance is less than the second argument. """ group = [-1] * NUM_NODE current_group_id = 0 division = [] for i in range(NUM_NODE): current_group = set() if(group[i] != -1): ...
5,305,614
def deduplicate(elements): """Remove duplicate entries in a list of dataset annotations. Parameters ---------- elements: list(vizier.datastore.annotation.base.DatasetAnnotation) List of dataset annotations Returns ------- list(vizier.datastore.annotation.base.DatasetAnnotation) ...
5,305,615
def test_descend_dry(): """Test descend for dry adiabatic descent.""" actual_t, actual_q, actual_l = descend( 1000*units.mbar, -20*units.celsius, 1e-3*units.dimensionless, 0*units.dimensionless, 500*units.mbar) truth_t = 308.5933065618629*units.kelvin truth_q = 1e-3*units.dimensionless ...
5,305,616
def get_keywords(): """ The get_keywords function retrieves keywords from the database if they are set to active.""" return select(k for k in Keyword if k.active)
5,305,617
def parse_spectrum_list2dict(spectrum_list): """ Parse the spectrum list [start, stop, num] to a list """ if spectrum_list[0].unit.physical_type != 'length' and \ spectrum_list[1].unit.physical_type != 'length': raise ValueError('start and end of spectrum need to be a length...
5,305,618
def _connection_line(x, fig, sourceax, targetax, y=1., y_source_transform="transAxes"): """Connect source and target plots with a line. Connect source and target plots with a line, such as time series (source) and topolots (target). Primarily used for plot_joint functions. """ ...
5,305,619
def RDKit_Mol_from_ProDy(prody_instance, removeHs=True): """ Creates an RDKit Mol object from a ProDy AtomGroup instance :return: """ residue_io = io.StringIO() prody.writePDBStream(residue_io, prody_instance) return Chem.MolFromPDBBlock(residue_io.getvalue(), removeHs=removeHs)
5,305,620
def get_cut_rect_x(rect, axis): """ cuts one rect about an x axis """ rects = [rect] llx, lly, urx, ury = rect if llx < axis and urx > axis: rects = [(llx, lly, axis, ury), (axis, lly, urx, ury)] return rects
5,305,621
def get_class_name(obj, fully_qualified=True, truncate_builtins=True): """Get class name for object. If object is a type, returns name of the type. If object is a bound method or a class method, returns its ``self`` object's class name. If object is an instance of class, returns instance's class name. ...
5,305,622
def windShear(u, v, z, top, bottom, unit=None): """ calculate the wind shear between discrete layers <div class=jython> shear = sqrt((u(top)-u(bottom))^2 + (v(top)-v(bottom))^2)/zdiff</pre> </div> """ udiff = layerDiff(u, top, bottom, unit) vdiff = layerDiff(v, top, bottom, unit) zdiff = layerDi...
5,305,623
def test_application_patch(mock_env_access_key, client): # pylint: disable=unused-argument """ Test updating an application """ # happy path with patch('service.resources.application.requests.patch') as mock_patch: mock_patch.return_value.text = json.dumps(mocks.PATCH_RESPONSE) ...
5,305,624
def check_all_links(links): """ Check that the provided links are valid. Links are considered valid if a HEAD request to the server returns a 200 status code. """ broken_links = [] for link in links: head = requests.head(link) if head.status_code != 200: broken_links...
5,305,625
def process_currency(curr): """Gets a formatted list of cryptocurrency to show in home.html""" assets = [] for c in curr: assets.append(c['CGname']) data = new_lookup(assets, "usd") final_list = [] i = 1 for name, price in data.items(): final_list.append({"id": i, "name": n...
5,305,626
async def validation_middleware(request: web.Request, handler) -> web.Response: """ Validation middleware for aiohttp web app Usage: .. code-block:: python app.middlewares.append(validation_middleware) """ orig_handler = request.match_info.handler if not hasattr(orig_handler, "_...
5,305,627
def register_ranged_hparams(name=None): """Register a RangedHParams set. name defaults to fn name snake-cased.""" def decorator(rhp_fn, registration_name=None): """Registers & returns hp_fn with registration_name or default name.""" rhp_name = registration_name or default_name(rhp_fn) if rhp_name in _R...
5,305,628
def get_monitoring_data(): """ 1. Get required arguments 2. Call the worker method 3. Render the response """ # 1. Get required arguments args = Eg001Controller.get_args() try: # 2. Call the worker method to get your monitor data results = Eg001Controller.worker(args...
5,305,629
def calculate_histogram(magnitudes, angles, bin_count=9, is_signed=False): """Calculate the localized histogram of each cell. :param magnitudes: The maginitude of each cell :type: np.ndarray :param angles: The angle of each cell :type: ...
5,305,630
def _create_directories(sub_dir_list, path="", with_text=False): """Creates set of directory from the list. :param sub_dir_list: List of the subdirectory. :param path: Path to store the subdirectories. :param with_text: Boolean that makes a text file with the subdirectory name. (Default=False) """ ...
5,305,631
def test_json_decoder_decodes_bytes(json_decoder, json_loads): """JSONDecoder.decode should correctly decode json-encoded bytes.""" bytes_json_data = json.dumps({'petId': 100, 'petName': 'Azor'}).encode('utf-8') decoded = json_decoder.decode(bytes_json_data) assert decoded == {'petId': 100, 'petName': '...
5,305,632
def dot_product_mpnn_attention(q, k, v, adjacency_matrix, num_edge_types, ignore_zero=True, name=None): """Dot product attention with edge vectors. Args: q: [batch, length, key_depth] tensor k: [batch, num_edge_types, length, key_depth] v: [batch, num_edge_types, length, ...
5,305,633
def selective_representer(dumper, data): """Process yml to correctly handle \n.""" return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|' if '\n' in data else None)
5,305,634
def optimize_trajectory(target, start, parameters): """ 牛顿迭代法,梯度下降法 :param target: :param start: :param parameters: :return: """ for i in range(max_iter): end_state = generate_last_state(start, parameters) end_state_error = np.array(calc_diff(target, end_state)).reshape(...
5,305,635
def get_session_monitor(target): """Px means the session is parallel run coordinator.""" return render_page()
5,305,636
def _evaluate_embedding_cpu(r, d, r_neighbor, metric="dihedral", epsilon=1e-4): """ Evaluate the final embedding by calculating the stress and correlation Args: r (ndarray): n-dimensional dataset (rows: frame; columns: angle/intramolecular distance) d (ndarray): the final projected embe...
5,305,637
def encode_type2_user_id(user_id): """Append a type-2 error detection code to the user_id.""" return f"{user_id:04d}-{Type2Code.calculate(user_id):02d}"
5,305,638
def pipeline(computational_stages, pipeline_depth, repeat_count=1, inputs=None, infeed_queue=None, outfeed_queue=None, optimizer_function=None, device_mapping=None, pipeline_schedule=None, forward_propag...
5,305,639
def twitter(request, account_inactive_template='socialregistration/account_inactive.html', extra_context=dict(), client_class=None): """ Actually setup/login an account relating to a twitter user after the oauth process is finished successfully """ client = client_class( request, setting...
5,305,640
def delete_activator_cd(activatorId, dbsession): """ Args: activatorId ([int]): [The Activator id] list_of_cd ([list]): [A list of CD ids] 1. Logically delete all active CD ids for this activator """ # Inactivates the active activator-cd for this activator (activatorId) ...
5,305,641
def makeVariables_npv(image): """ Make variables for NPV regression model """ year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) season = year.multiply(2 * np.pi) return image.select().addBands(ee.Image(1)).addBands( season.sin().rename(['sin'])).addBands( season.cos().rename(['cos...
5,305,642
def logs(proc='uwsgi'): """tails logfile for speficied proc possible procs are: nginx, uwsgi, celery, celerybeat, redis """ if proc in ('celery', 'celerybeat', 'uwsgi'): run('tail -f %s/%s.log' % (env.log_home, proc)) elif proc == 'nginx': sudo('tail -f /var/log/nginx/%(proj...
5,305,643
def mrg_labeled(tr): """return labeled constituency string.""" if isinstance(tr, nltk.Tree): if tr.label() in WORD_TAGS: return tr.leaves()[0] + ' ' else: s = '(%s ' % (re.split(r'[-=]', tr.label())[0]) for subtr in tr: s += mrg_labeled(subtr) s += ') ' return s else:...
5,305,644
def print_errs(msg, validator_result, quiet=False, die=False, report=_report): """ helper for main validation functions """ err = "print_errs requires a tuple of (errors, warnings, messages)" try: (errors, warnings, messages) = validator_result except ValueError: raise ValueError(err + "...
5,305,645
def fast_genotypes(chrom, pos: int, samples): """Efficiently look up genotypes for a variant Parameters ---------- chrom: str or int chromosome of the variant pos : int position of the variant samples iterable or comma-delimited string of samples to look up Retu...
5,305,646
def compute_seen_words(inscription_list): """Computes the set of all words seen in phrases in the game""" return {word for inscription in inscription_list for phrase in inscription['phrases'] for word in phrase.split()}
5,305,647
def replace_previous(user, code, is_alt): """function replace_previous This function changes the previous lesson code Args: user: user model using tutor code: code that user submitted in last lesson is_alt: boolean for if alternate lesson Returns: code: ? string of code ...
5,305,648
def get_args(batch_size=8, image_size=256, max_iter=100000): """ Get command line arguments. Arguments set the default values of command line arguments. """ import argparse import os description = "Example of Lightweight GAN." parser = argparse.ArgumentParser(description) parser.a...
5,305,649
def create_yaml_ash(): """ Guessing this was a utility used while creating ash files :return: """ shift_lens = ['8', '10', '12', '14', '16', '20', '24'] for shift_len in shift_lens: fn_csv = '../exps/mwts02/inputs/ash/ash_' + shift_len + '.fn_csv' fn_yml = '../exps/mwts02/input...
5,305,650
def page_rank_dense_lstsq(datafile, d, datasize, n=None): """ Solve the page rank problem, given the data in 'datafile', the dampening factor 'd', the size 'datasize' of the dataset, and the number 'n' of nodes to include. Have 'n' default to None. Use the method involving least squares.""" data...
5,305,651
def resume(request): """ Resume the container """ if request.method != "POST": messages.error(request, "Invalid request method.") return redirect('containers') if 'id' not in request.POST or not request.POST.get('id').isdigit(): messages.error(request, "Invalid POST request."...
5,305,652
def TextNodeEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
5,305,653
def set_item_checked(service, context): """ Fixture for factory function to set whether an item is checked. """ def _set_item_checked(shopping_list, item, checked): request = shopping_list_pb2.SetItemCheckedRequest( shopping_list_id=shopping_list.id, item_id=item.id, ...
5,305,654
def as_singleton_instance(cls): """ This is where the magic happens. This defines a class decorator that returns an *instance* of a class with the name "_<original_name>__class" that has the same member functions, etc as the cls argument. The type of the returned value is not accessible to the ...
5,305,655
def set_size(width, fraction=1, subplots=(1, 1)): """ Set figure dimensions to avoid scaling in LaTeX. Parameters ---------- width: float or string Document width in points, or string of predined document type fraction: float, optional Fraction of the width which you wish th...
5,305,656
def parse_options(): """Parses command line options and returns an option dictionary.""" options = {} parser = argparse.ArgumentParser( description='Recursively apply Review Board reviews' ' and GitHub pull requests.') parser.add_argument('-d', '--dry-run', ...
5,305,657
def create_keras_model(): """ create model """ model = Sequential() model.add(Conv1D(500, input_shape=(1280, 1), kernel_size=128, strides=128, activation='relu', padding='same')) model.add(De...
5,305,658
def ndgrid(*args,**kwargs): """ Same as calling meshgrid with indexing='ij' (see meshgrid for documentation). """ kwargs['indexing'] = 'ij' return meshgrid(*args,**kwargs)
5,305,659
def _wass_gen_loss_fn(gen_images, discriminator: tf.keras.Model, generator: tf.keras.Model): """Calculate the Wasserstein (generator) loss.""" disc_gen_output = discriminator( gen_images, training=TRAINING_KWARG_FOR_SECOND_MODEL) gen_loss = tf.reduce_mean(-disc_gen_output) # Now add...
5,305,660
def stump(t, n, angle=90): """Makes a vertical line and leave the turtle at the top, facing right""" lt(t) fd(t, n) rt(t, angle)
5,305,661
def _get_create_repo(request) -> List[str]: """ Retrieves the list of all GIT repositories to be created. Args: request: The pytest requests object from which to retrieve the marks. Returns: The list of GIT repositories to be created. """ names = request.config.getoption("--create-repo...
5,305,662
def save_response_content(response, destination): """ :param requests.Response response: :param str destination: :return: """ chunk_size = 1024 * 1024 logger.info("start downloading...") with open(destination, "wb") as f: for chunk in tqdm(response.iter_content(chunk_size), unit=...
5,305,663
def save_bookpages(book_dict): """ book_dict is a dict, contain these keys: id, url, title. """ if Page.is_existed(book_dict['id']): return book = Page.create(book_dict) session.add(book) session.commit()
5,305,664
def read_in_posterior(date): """ read in samples from posterior from inference """ df = pd.read_hdf("results/soc_mob_posterior"+date+".h5", key='samples') return df
5,305,665
def wrap_dtype(func): """ Check the dtype of the `X` array. Convert dtype of X to np.float64 before to pass to cython function and convert to specified dtype at the end. """ @wraps(func) def check_dtype(X, *args, dtype=None, **kwargs): X, dtype = _check_dtype(X, dtype) if dtyp...
5,305,666
def dirdiff(HEADING,Nmin,loffset): """ Function to calculate the maximum difference of a [0, 360) direction during specified time averging intervals :param HEADING: time series of a direction in degrees [0, 360) :param Nmin: integer specifying the number of minutes to average ...
5,305,667
def update_outputs(region, resource_type, name, outputs): """ update outputs with appropriate results """ element = { "op": "remove", "path": "/%s/%s" % (resource_type, name) } outputs[region].append(element) return outputs
5,305,668
def generate_inputs_1d_spherical(): """Return inputs that parser will expect for the 1D case with spherical averaging.""" inputs = { 'parent_folder': orm.FolderData().store(), 'parameters': orm.Dict( dict={ 'INPUTPP': { 'plot_num':...
5,305,669
def _check_electrification_scenarios_for_download(es): """Checks the electrification scenarios input to :py:func:`download_demand_data` and :py:func:`download_flexibility_data`. :param set/list es: The input electrification scenarios that will be checked. Can be any of: *'Reference'*, *'Medium'*, *...
5,305,670
def bubble_sort(nums: Sequence) -> List: """Sort a list in non-descending order using bubble sort. Return a new list, leaving the original `nums` intact. """ # Bubble sort compares each element with the next element, and if the previous one # is greater than the next one, swap them. Repeat unt...
5,305,671
def image_to_byte_array(image: Image): """ Converts an image into a byte array """ imgByteArr = BytesIO() image.save(imgByteArr, format=image.format if image.format else 'JPEG') imgByteArr = imgByteArr.getvalue() return imgByteArr
5,305,672
def crawling_tweet(): """ Twitter APIを利用して対象ユーザーのツイートを収集する 収集したツイートはGoogle Cloud Text to Speech APIへ連携し、 音声読み上げデータとしてmp3に変換し、保存する :return: """ auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) ...
5,305,673
def run_module(): """ Main Ansible module function """ # Module argument info module_args = { 'sys': { 'type': 'str', 'required': True }, 'dist': { 'type': 'str', 'required': True }, ...
5,305,674
def is_subject_condition_dataframe( data: SubjectConditionDataFrame, raise_exception: Optional[bool] = True ) -> Optional[bool]: """Check whether dataframe is a :obj:`~biopsykit.utils.datatype_helper.SubjectConditionDataFrame`. Parameters ---------- data : :class:`~pandas.DataFrame` data to...
5,305,675
def main(): """Point of entry for our tensorflow mnist multilayer convolutional model. This model runs with components from the cnn module and reduces loss through the cross entropy functions from Tensorflow. The model currently achieves approx 98% accuracy in recognizing the 10,000 handwritte...
5,305,676
def _update_earned_request(player_id, achievement_id, current_value, max_value): """ Create the DynamoDB update_item parameter request to update earned attribute """ now = ddb.timestamp() return { 'Key': { 'player_id': player_id, 'achievement_id': achievement_id ...
5,305,677
def compute_bleu(pred_file_path: str, target_file_path: str, print_all_scores: bool): """ Args: pred_file_path: the file path that contains the predictions. target_file_path: the file path that contains the targets (also called references). print_all_scores: if True, will print one scor...
5,305,678
def PyUnicode_AsRawUnicodeEscapeString(space, unicode): """Encode a Unicode object using Raw-Unicode-Escape and return the result as Python string object. Error handling is "strict". Return NULL if an exception was raised by the codec.""" raise NotImplementedError
5,305,679
def mosaic(*rasters): """ Mosaic rasters covering different areas together into one file. Parts of the rasters may overlap each other, in which case we use the value from the last listed raster (the "last" overlap rule). """ # align all rasters, ie resampling to the same dimensions as the first...
5,305,680
def typing_loop(options, add, atom_type_dict): """ types atoms in ambiguous cases, options should be ordered correctly """ ty = None for option in options: try: ty = atom_type_dict[add + option] break except KeyError: continue if ty !=...
5,305,681
def enable_func_trace(*args): """ enable_func_trace(enable=True) -> bool """ return _ida_dbg.enable_func_trace(*args)
5,305,682
def get_exp_or_package_from_repo_name(repo_name): """Helper function to retrieve experiment or InternalPackage DB object based on repository name Useful for tasks that do not have a session or other information""" git_repo = GitRepository.objects.filter(name=repo_name) if git_repo: git_repo = gi...
5,305,683
def text_to_pronounceable_text(text, symbols_for_base_idx=vowels_and_consonants, captured_alphabet=alpha_numerics, case_sensitive=False, max_word_length=30, artifici...
5,305,684
def is_shuffle(s1, s2, s3): """ Runtime: O(n) """ if len(s3) != len(s1) + len(s2): return False i1 = i2 = i3 = 0 while i1 < len(s1) and i2 < len(s2): c = s3[i3] if s1[i1] == c: i1 += 1 elif s2[i2] == c: i2 += 1 else: return False i3 += 1 return True
5,305,685
def header_is_sorted_by_coordinate(header): """Return True if bam header indicates that this file is sorted by coordinate. """ return 'HD' in header and 'SO' in header['HD'] and header['HD']['SO'].lower() == 'coordinate'
5,305,686
def delete( name, endpoint="incidents", id=None, api_url=None, page_id=None, api_key=None, api_version=None, ): """ Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. ...
5,305,687
def set_reminder(message: str = None, hour: str = None): """ hour (optional): Hour input from user. Expected format is: H:M. message: Message for slackbot to send you when time comes. Any string input is ok. """ if hour is not None: try: assert len(hour.split(":")) == 2 ...
5,305,688
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': ...
5,305,689
def square(x, name=None): """Computes square of x element-wise. I.e., \\(y = x * x = x^2\\). Args: x: An `Output` or `SparseTensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns:...
5,305,690
def manually_adjust_data(pnid, sc_entry): """Returns a modified version of sc_entry to fix some issues manually. Args: pnid: string, ProteinNet ID sc_entry: dictionary containing "seq", "ang", "crd" data Returns: If sc_entry must be modified, then it is corrected and returned. ...
5,305,691
def get_network_container_hostnames(name): """Returns a list of every container hostname in the specified network.""" for network in get_networks(): if network["Name"] == name: return [get_container_hostname(container) for container in network["Containers"]]
5,305,692
def spearmanr_no_pval_vec(X, Y): """Returns spearmans correlation, vectorized version Parameters ---------- X : ndarray (n_samples, n_observations) Y : ndarray (n_samples, 1) Returns ------- R : array (n_observations,) spearmans correlation between each column of X and Y ""...
5,305,693
def setup_logging( default_path='pylogging.json', default_level=logging.INFO, env_key='LOG_CFG' ): """Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: ...
5,305,694
async def surprise_communities(request): """ --- description: This end-point allows to compute surprise_communities Community Discovery algorithm to a network dataset. tags: - surprise_communities produces: - application/json responses: "20...
5,305,695
def set_case(words, method="lower", testing=False): """ Perform capitalization on some or all of the strings in `words`. Default method is "lower". Args: words (list): word list generated by `choose_words()` or `find_acrostic()`. method (str): one of {"alter...
5,305,696
def button(channel, red, blue): """Returns the button for a Combo PWM Mode command.""" return (pf_rc.CHANNEL[channel], PWM_STEP[red], PWM_STEP[blue])
5,305,697
def mini_xception(input_shape, num_classes, regularization = l2(0.01)): """ This function architects the mini_xception model network. This is the best performing model in the facial emotion analysis input_shape: input shape of the image num_classes: number of classes in the output return: Ret...
5,305,698
def calc_node_size(self): """ calculate minimum node size. """ title_width = self._text_item.boundingRect().width() port_names_width = 0.0 port_height = 0.0 if self._input_items: input_widths = [] for port, text in self._input_items.items(): input_width = port.bo...
5,305,699