content
stringlengths
22
815k
id
int64
0
4.91M
def list_mendeley_accounts_user(auth): """ Returns the list of all of the current user's authorized Mendeley accounts """ provider = MendeleyCitationsProvider() return provider.user_accounts(auth.user)
5,302,700
def test_version(): """ Ensure that -V results in the version being reported """ assert(subprocess.check_output( ['bin/nhlstats', '-V']) == 'Version: %s\n' % nhlstats.__version__)
5,302,701
def find_source_files(input_path, export_packages): """ Get a recursive list of filenames for all Java source files within the given directory. Only include files in packages that are exported """ java_files = [] input_path = os.path.normpath(os.path.abspath(input_path)) exclude_paths = ["ar...
5,302,702
def build_toy_random_forest(path, winner_take_all_inference, add_boolean_features=False, has_catset=False, num_trees=2): """Creates a toy Random Forest model compatible with _build_toy_data_spec.""" logg...
5,302,703
def _verify_address(addr): """Function verifies that address is valid IPv4 address Args: addr : address of machine Return: boolean value defining validity of address """ try: ipaddress.ip_address(unicode(addr)) return True except ValueError: return False
5,302,704
def test_mailto__MailTo__unique_mail_addresses__1(mailto_data): """It is a sorted list of unique email addresses.""" from .mailto import MailTo from gocept.testing.mock import Property view = MailTo() view.request = mock.Mock() persons = ('icemac.addressbook.browser.search.result.handler.mailto....
5,302,705
def make_repo_ref_from_cur_dir(): """Gets the prefix string for a git clone command dependening on the current directories git setup. i.e. if it is https, then use https. """ try: git_output = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']) except subprocess.CalledProcessError...
5,302,706
def output_reduce_list(path_list, force=False): """Generates structure file with protons from a list of structure files.""" output_paths = [] for path in path_list: output_path = output_reduce(path, force=force) if output_path: output_paths.append(output_path) return output_p...
5,302,707
def job_update_notification(ctxt, build_id, state=None, description=None, created_image_id=None, assembly_id=None): """send a status update to the conductor.""" LOG.debug('build id:%s %s (%s) %s %s' % (build_id, state, description, created...
5,302,708
def test_generator_danger_tag_quiet_and_force(cli_runner, pets, rest_mock): """ Test `cray init` for creating the default configuration """ name = 'testuser' runner, cli, opts = cli_runner config = opts['default'] hostname = config['hostname'] orderId = "1" result = runner.invoke(cli, ['pets...
5,302,709
def test_acer_6(): """Test acer parameter header""" text = sandy.njoy._acer_input(-20, -21, -60, 80, 200, header="Hi!") assert text == "acer\n-20 -21 0 -60 80 /\n1 0 1 .00 0 /\n'Hi!'/\n200 293.6 /\n1 1 /\n/\n"
5,302,710
def asStructuredText(I, munge=0): """ Output structured text format. Note, this will whack any existing 'structured' format of the text. """ r = [I.getName()] outp = r.append level = 1 if I.getDoc(): outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level)) bases = [base ...
5,302,711
def current_distribution_by_website(site): """ Reads the checker framework version from the checker framework website and returns the version of the current release """ print 'Looking up checker-framework-version from %s\n' % site ver_re = re.compile(r"<!-- checker-framework-version -->(.*),") ...
5,302,712
def build_card_objects(media_list: list = None) -> list: """ Creates DB objects from S3 objects list """ logger.info("Crafting list of DB objects...") logger.debug( f"Context Parameters: {build_card_objects.__name__} => {build_card_objects.__code__.co_varnames}" ) medias_list = defaultdict(...
5,302,713
def make_hyperspherical_classification_loss(prototypes): """ Args: prototypes: (num_classes, embed_dim) """ def _get_prototypes(labels): return tf.tensordot(labels, prototypes, [[1], [0]]) def loss(preds, labels): """ Args: preds: (Batch, embed_d...
5,302,714
def nz_MgCLN_Gayer( lam: float, T: float, ax: str=None, ): """ Refractive index for MgCLN, based on Gayer et al, APB 2008 Parameters ---------- lam: wavelength (lambda) [um] T: Temperature [Celsius Degrees] ax: polarization Returns ------- nz: Refractive...
5,302,715
def export_corpora( corpus_ids, granularity, corpora_folder, filename, no_download=False ): """ Generates a single JSON file with the chosen granularity for all of the selected corpora :param corpus_ids: IDs of the corpora that will be exported :param granularity: Level of parsing granulari...
5,302,716
def write_csv_header(profiling_data, csv_writer, extra_column_headers): """ Write header row for standard profiler format CSV file with extra column headers followed by tag names found in profiling_data """ csv_writer.writerow(extra_column_headers + list(iterkeys(profiling_data)))
5,302,717
def verify_bss_response(response_object, expected_length=None): """ Verify some basic things about the bss response object: 1) That it is a list 2) That it has the expected length, if specified 3) That all list entries are type dict """ debug("Validating BSS response") if not isinstance(...
5,302,718
def safety(session: Session) -> None: """Scan dependencies for insecure packages.""" install_with_constraints(session, "invoke", "safety") session.run("inv", "safety")
5,302,719
def restart() -> None: """Restart the Docknetwork process inside the running instances""" config = load_config_file() instance_ips = [i.public_ip_address for i in get_running_instances(config)] if not instance_ips: raise Exception('ERROR: No instances with public IPs found. Exiting.') try: ...
5,302,720
def cli_jupyter_strip(ctx): """Strip output cells.""" import nbformat for path in ctx.obj["paths"]: rawnb = nbformat.read(str(path), as_version=nbformat.NO_CONVERT) for cell in rawnb.cells: if cell["cell_type"] == "code": cell["execution_count"] = None ...
5,302,721
def all_pairs_iterator(values: Iterable[T], with_replacement: bool = True, where: Callable[[Tuple[T, T]], bool] = lambda _: True) -> Iterator[Tuple[T, T]]: """ Strongly typed function to get iterator of all pairs from `iterable`. (for using with mypy) This is W...
5,302,722
def syllable_tokenize(text): """ :param str text: input string to be tokenized :return: returns list of strings of syllables """ syllables = [] if text: words = word_tokenize(text) trie = create_custom_dict_trie(custom_dict_source=syllable_dict()) for word in words: ...
5,302,723
def create_sponsor(loggedin_user): """ Creates a new Sponsor manually and bypasses email verification. --- tags: - admin summary: Create Sponsor requestBody: content: application/json: schema: $ref: '#/components/schemas/Sponsor' ...
5,302,724
def generate_groot_image(logger: TextIO) -> None: """ Generates the GRoot image required for generation of queries using equivalence classes. Exits the program if the image generation is not successful. :param logger: The log file pointer """ run_cmd = ['docker', 'build', '-t', "...
5,302,725
def test_lazyadam_target(): """ test_lazyadam_target """ net = NetWithSparseGatherV2() net.set_train() optimizer = LazyAdam(net.trainable_params(), learning_rate=0.1, weight_decay=0.9, loss_scale=2.0) if optimizer.target not in ('CPU', 'Ascend'): raise ValueError("The value must be 'CPU' or...
5,302,726
def get_empty_theme(): """Create object that contains empty theme.""" return { 'theme': {}, 'background': bytearray() }
5,302,727
def random_nat(n: int) -> int: """ Generate a random natural number L{n} bytes long. """ return utils.int_from_bytes(random_bytes(n), 'big', signed=False)
5,302,728
def getNumAtoms(ctab): """ Counts number of atoms of given compounds. CTAB is urlsafe_base64 encoded string containing single molfile or concatenation of multiple molfiles. cURL examples: curl -X GET ${BEAKER_ROOT_URL}getNumAtoms/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_") """ data = base64.urlsa...
5,302,729
def tearDownModule(): """Teardown.""" os.system('rm -rf {}'.format(os.path.join(BASE_DIR, 'test_media_for_photos')))
5,302,730
def send_job(job_payload): """Send a job tuple to the worker pool. Args: job_payload (dict): a dictionary with information to send to the worker process. This description is general so it's easy to change the data without changing the pipeline. Returns: None. "...
5,302,731
def aiuda(update, context): """Send a message when the command /aiuda is issued.""" msg = update.message chat_id = msg['chat']['id'] mssg_id = msg['message_id'] update.message.bot.sendMessage(chat_id, help_message, parse_mode = 'HTML', reply_to_message_id=mssg_id)
5,302,732
def get_requirement_version(package_name, dependency_name): """Get assigned version to a dependency in package requirements.""" package_name = package_name.replace('pollination.', 'pollination_') package_name = name_to_pollination(package_name) dependency_name = dependency_name.replace('_', '-') req...
5,302,733
def cosine(s1, s2): """ Retuns the cosine value between two strings >>> cosine("This is a sentence", "This is a sentence") 1.0 """ vec1 = Counter(s1.split()) vec2 = Counter(s2.split()) intersection = set(vec1.keys()) & set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in i...
5,302,734
def set_download_quality(settings_manager: 'SettingsManager'): """Chose the download quality of the videos from pre-defined qualities""" response = "y" if settings_manager.chosen_quality: response = get_string_input( F"\nThe download quality is {settings_manager.chosen_quality} do you wa...
5,302,735
def generate_multiple_simulations(path_sumo_cfg: Path, flow_configs: typing.Dict[str, typing.Dict], n_simulation: int) -> typing.List[Path]: """Generate "n_simulation" configuration files while updating values following `flow_configs` Returns:...
5,302,736
def get_all_types(inactive=0): """Get all non-deleted instance_types. Pass true as argument if you want deleted instance types returned also. """ return db.instance_type_get_all(context.get_admin_context(), inactive)
5,302,737
def mysqldiff(ctx, source, target, db): """差异 SQL 工具。""" source_cnx = None target_cnx = None try: source_index = source.rindex('@') source_user = source[0:source_index].split(':', 1) source_host = source[source_index + 1:].split(':', 1) databases = db.split(':', 1) ...
5,302,738
def merge_split_assoc_words(assoc_words: List[AssocWord]) -> List[AssocWord]: """ This function merges all groups of AssocWords, apart from when an AssocWord with a `form' appears on the right side in which case a new group is started again. Conversely, if an AssocWord has a form which is a multiwo...
5,302,739
def get_predicates(rules, roles): """Extract predicate information from the rules""" preds = set() pred_names = set() predTypes = {} # maps places to the equivalence class they're in ec = TypedEquivalenceClass() for r in rules: goal_place_types = {} if r.get_head().get_relation() == 'goal': score = r.get...
5,302,740
def test_matrix_set_diag(data_type): """ Feature: ALL TO ALL Description: test geneal matrix cases for matrix_set_diag in pynative or graph mode Expectation: the result match expected_diag_matrix. """ onp.random.seed(0) context.set_context(mode=context.PYNATIVE_MODE) for align in ALIGNME...
5,302,741
def estimate_hqc(): """ Compute and output esitmates for HQC parametersets. """ print("Estimating HQC") estimates = estimate_list(HQC_params, [[2, 8] for i in range(3)], quasi_cyclic=1) HQC_tbls = create_table_array(HQC_params, estimates) print("\nLog memory access") add_mem_restr...
5,302,742
def comment_dicts_to_entities(comment_dicts): """Converts the list of comment dicts to the list of comment entities.""" return [comment_dict_to_entity(comment_dict) for comment_dict in comment_dicts]
5,302,743
def save(filename, data): """Save the current user information to disk A clone is created of the user copy before saving, so that all users can be set to offline before being saved to disk """ with open(filename, 'wb') as db_file: pickle.dump(data, db_file, protocol=pickle.HIGHEST_PROTOCOL)
5,302,744
def get_comment(id, check_author=True): """Get a comment and its post and its author by id. Checks that the id exists and optionally that the current user is the author of its post. :param id: id of comment to get :param check_author: require the current user to be the author :return: the comm...
5,302,745
def letter_extractor(raws): """letter_ Frequencies of 26 English letters in a given text, case insensitive. Known differences with Writeprints Static feature "letter frequency": None. Args: raws: List of documents. Returns: Frequencies of English letters in the document. """ ...
5,302,746
def crop_frames(frames, speaker): """ frames: (b h w c) """ if speaker == "chem" or speaker == "hs": return frames elif speaker == "chess": return frames[:, 270:460, 770:1130] elif speaker == "dl" or speaker == "eh": return frames[:, int(frames.shape[1] * 3 / 4) :, int(fr...
5,302,747
def request_unaffiliated_research_access(request): """ Submit request for unaffiliated research access """ name = "%s %s" % (request.user.first_name, request.user.last_name) form = form_for_request(request, UnaffiliatedResearchRequestForm, initial={'name': name, 'email': request.user.email}) if request...
5,302,748
def builddict(fin): """ Build a dictionary mapping from username to country for all classes. Takes as input an open csv.reader on the edX supplied file that lists classname, country, and username and returns a dictionary that maps from username to country """ retdict = {} for cours...
5,302,749
def plot_clustermap_annot(foldchanges, pvalues, annot, column, threshold=0.05, group_by=None, drop_zeros=False, plot=None, min_occ=3, cluster=True, col_cluster=True, row_cluster=True, dendogram=True, col_dendogram=True, row_dendogram=True, file_path=None): """ Function to plot clustermap of foldchanges and pwms, wi...
5,302,750
def get_timeseries(length, delta=datetime.timedelta(hours=1)): """Generate timeseries data""" start = datetime.datetime.now() timeseries = [start] for i in range(length - 1): timeseries.append(timeseries[i] + delta) return timeseries
5,302,751
def add_static_values(caomlist, statics, data_type, header_type): """ Add entries from the statics dictionary to the caomlist by looking at properties of data_type and header_type. The add_value_caomxml module is used to actually create the CAOMxml objects and add them to the caomlist. """ caomlis...
5,302,752
def dict_to_stix2(stix_dict, allow_custom=False, version=None): """convert dictionary to full python-stix2 object Args: stix_dict (dict): a python dictionary of a STIX object that (presumably) is semantically correct to be parsed into a full python-stix2 obj allow_custom...
5,302,753
def connector(schema: str) -> Callable[[Type[Connector]], Type[Connector]]: """ The @connector class decorator used to register the connector to the global registry. Parameters ---------- schema The schema for the connector, for example 'ssh'. """ def wrapper(cls: Type[Connector...
5,302,754
def resource_show(expression): """returns the metadata of a resource""" url = OPENDATA_URL + "resource_show?{expression}".format(expression=expression) return _request_json(url).get("result", dict())
5,302,755
def n_overlap_1 ( ri, ei, box, r, e ): """Takes in coordinates and orientations of a molecule and counts overlaps. Values of box and partner coordinate array are supplied. Fast or slow algorithm selected. """ import numpy as np # In general, r will be a subset of the complete set of simulatio...
5,302,756
def HJB_ode(y, time, b, I_func): """ Hamilton-Jacobi-Bellman equation """ u, v, w = y dudt = cost_effort(b(T_max - time)) + b(T_max - time) * \ I_func(T_max - time) * (v - u) - vac(T_max - time) * u dvdt = cost_infection(time) + gamma * (w - v) dwdt = rho * (u - w) return dudt, d...
5,302,757
def split_grafs (lines): """ segment the raw text into paragraphs """ graf = [] for line in lines: line = line.strip() if len(line) < 1: if len(graf) > 0: yield "\n".join(graf) graf = [] else: graf.append(line) if...
5,302,758
def get_contexts(pp_threshold: float, d_threshold: float, spans: int, use_qa_table_enrichment: bool, doc_and_tables_dfs: Tuple[pd.DataFrame, pd.DataFrame]) -> Tuple[pd.DataFrame, pd.DataFrame, ...
5,302,759
def _get_suffix(filepath: Union[str, Path, FSMap]) -> str: """Check if file type is supported.""" # TODO: handle multiple files through the same set of checks for combining files if isinstance(filepath, FSMap): suffix = Path(filepath.root).suffix else: suffix = Path(str(filepath)).suffix...
5,302,760
def background(): """Find correlation between background interaction energy and number of hbonds""" import os dirs=os.listdir('data') xs=[] ys=[] count=0 #dirs=['1bli'] for dir in dirs: print 'Processing %s' %dir # # find the PDB file # realdir=os....
5,302,761
def decision_tree_predict(tree, testing_example, max_value_in_target_attribute): """ :param max_value_in_target_attribute: If we are not able to classify due to less data, we return this value when testing :param tree: This is the trained tree which we will use for finding the class of the given instan...
5,302,762
def load_data(census_region: int, filepath: str = "nhts_census_updated.mat"): """Load the data at nhts_census.mat. :param int census_region: the census region to load data from. :param str filepath: the path to the matfile. :raises ValueError: if the census division is not between 1 and 9, inclusive. ...
5,302,763
def handle_quit(mqtt_sender): """ Tell the robot's program to stop its loop (and hence quit). :type mqtt_sender: com.MqttClient """ print('End code for robot') mqtt_sender.send_message('quit') print('Robot code has been terminated')
5,302,764
def nbdoc(fun, *pars, name=None, **kwargs): """Format the output from an IPython notebook cell using the function's docstring and computed variables. If name is specified, use it instead of the function name to distinguish figure file names, say for separate executions with differing parameters. ...
5,302,765
def getFileProperties(fname): """ Read all properties of the given file return them as a dictionary. """ import win32api propNames = ( "Comments", "InternalName", "ProductName", "CompanyName", "LegalCopyright", "ProductVersion", "FileDescripti...
5,302,766
def setup_scanner(hass, config, see, discovery_info=None): """Set up the Volvo tracker.""" if discovery_info is None: return vin, _ = discovery_info vehicle = hass.data[DATA_KEY].vehicles[vin] def see_vehicle(vehicle): """Handle the reporting of the vehicle position.""" hos...
5,302,767
def tvdb_get_id(sername, config): """ TVDB: Get SeriesID from SeriesName """ # Query TVDb for SeriesName xresp = getxml(config.tvdb['mirror'] + "/api/GetSeries.php", {'seriesname': sername}) logthis("Got response from TVDb:", suffix=print_r(xresp), loglevel=LL.DEBUG2) snorm = normalize(sern...
5,302,768
def check_satisfy_program(w, program): """ For each rule in the program, this function checks whether the head exists if all literals(or atoms) in the body exists in each ruler interval of the given Window ``w'' . Args: w (a Window instance): program (a list of rules): Returns: ...
5,302,769
def extend(start,end,vector,holevector) : """ Extend the subgrids one point if possible, to avoid edges """ s=np.max([0,start-1]) e=np.min([len(vector),end+1]) hs=np.max([0,np.where(np.isclose(holevector,vector[s]))[0][0]]) he=np.min([len(holevector),np.where(np.isclose(holevector,vector[e-1]))[...
5,302,770
def array(obj, row_major=0): """Wrapper around numpy.ndarray. It gives you the option of specifying the order of the contents. """ if not isinstance(obj, np.ndarray): obj = np.array(obj) if row_major == 0: if obj.flags.f_contiguous: return obj else: dim = ...
5,302,771
def get_reverse_depends(name, capability_instances): """Gets the reverse dependencies of a given Capability :param name: Name of the Capability which the instances might depend on :type name: str :param capability_instances: list of instances to search for having a dependency on the given Capab...
5,302,772
def normal2(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.randrange(1, 100001) idgirande=random.randran...
5,302,773
def test_revert_point(publish_agent, cancel_schedules): """ Test setting a float value of a point through rpc Expected result = value of the actuation point :param publish_agent: fixture invoked to setup all agents necessary and returns an instance of Agent object used for publishing :param can...
5,302,774
def node_degree_counter(g, node, cache=True): """Returns a Counter object with edge_kind tuples as keys and the number of edges with the specified edge_kind incident to the node as counts. """ node_data = g.node[node] if cache and 'degree_counter' in node_data: return node_data['degree_count...
5,302,775
async def get_account_id(db, name): """Get account id from account name.""" return await db.query_one("SELECT find_account_id( (:name)::VARCHAR, True )", name=name)
5,302,776
def test_un_minified_static_files_injected_in_html(selenium, app, status, warning): """Test if the static files are correctly injected in the html.""" app.build() path = app.outdir / 'index.html' selenium.get(f'file://{path}') page_source = selenium.page_source assert app.config.rtd_sphinx_sea...
5,302,777
def params_to_payload(params, config): """Converts a set of parameters into a payload for a GET or POST request. """ base_payload = {config['param-api-key']: config['api-key']} return dict(base_payload, **params)
5,302,778
def colorize_img(value, vmin=None, vmax=None, cmap='jet'): """ A utility function for TensorFlow that maps a grayscale image to a matplotlib colormap for use with TensorBoard image summaries. By default it will normalize the input value to the range 0..1 before mapping to a grayscale colormap. A...
5,302,779
def evaluate_models( models: Mapping[K, RewardModel], batch: types.Transitions ) -> Mapping[K, np.ndarray]: """Computes prediction of reward models.""" reward_outputs = {k: m.reward for k, m in models.items()} feed_dict = make_feed_dict(models.values(), batch) return tf.get_default_session().run(rew...
5,302,780
def check_clangxx(default="clang++"): """Compile a basic C++11 binary.""" executable = os.getenv("CXX", default) return check_bin(executable, "-x c++ -std=c++11 - -o /dev/null".split(), what="clang++", input="int main() { return 1; }")
5,302,781
def test__graph__no_stereo(): """ test graph conversions """ ref_ichs = ICHS_NO_STEREO if NSAMP is not None: ref_ichs = numpy.random.choice(ref_ichs, NSAMP) for ref_ich in ref_ichs: gra = automol.inchi.graph(ref_ich) gra = automol.graph.without_stereo_parities(gra) #...
5,302,782
def main(inputfile, input_override): """ Run Ocellaris """ if os.environ.get('OCELLARIS_SUPER_DEBUG', False): print('FOUND OCELLARIS_SUPER_DEBUG in environment') from ocellaris.utils.debug import enable_super_debug enable_super_debug() sim = Simulation() # Read input ...
5,302,783
def is_a_string(v: Any) -> bool: """Returns if v is an instance of str. """ return isinstance(v, str)
5,302,784
def wheel_speed_commands(u_ref, w_ref, d, r): """Converts reference speeds to wheel speed commands""" leftSpeed = float((2 * u_ref - d * w_ref) / (2 * r)) rightSpeed = float((2 * u_ref + d * w_ref) / (2 * r)) leftSpeed = np.sign(leftSpeed) * min(np.abs(leftSpeed), MAX_SPEED) rightSpeed = np.sig...
5,302,785
def test_filter_shave(sh_arg, sh_src, sh_dest): """Tests for shave argument. Shave away portion of filename """ args = parser.parse_args(["-sh", sh_arg]) filters = renamer.initfilters(args) dest = renamer.get_renames(sh_src, filters, args.extension, args.raw) assert dest == sh_dest
5,302,786
def _add_default_lambda_args(lambda_parser): """Add the default arguments to the deploy and rollback parsers""" functions = sorted([ 'alert', 'alert_merger', 'apps', 'athena', 'classifier', 'rule', 'rule_promo', 'threat_intel_downloader' ]) # require the name of the function being deplo...
5,302,787
def _get_dataset_from_filename(filename_skip_take, do_skip, do_take): """Returns a tf.data.Dataset instance from given (filename, skip, take).""" filename, skip, take = (filename_skip_take['filename'], filename_skip_take['skip'], filename_skip_take['take'],) dat...
5,302,788
def test_filter_codes_ValueError(): """Setting invalid filter codes on the Genome raises a ValueError.""" with pytest.raises(ValueError): genome = Genome() genome.filter_codes = ("asdf",)
5,302,789
def kde_normalize(arr, mask=None, modality="T1w", norm_value=1): """ Use kernel density estimation to find the peak of the white matter in the histogram of a skull-stripped image. Then normalize intensitites to a normalization value. Parameters ---------- arr: array the input data. ...
5,302,790
def select_bo_type(): """ Prints the buffer overflow types to the screen and stores the users selection """ show_prompt_text('Select type of buffer overflow:') show_prompt_text('[ L ] Local buffer overflow', False) show_prompt_text(' {} = Open a malicious file in an application {}'.format(GRAY, FORMAT_END), F...
5,302,791
def _parse_cmd_args(args_to_parse: list[str]) -> HashableDict: """Parse command line arguments for the sound change applier.""" parser = argparse.ArgumentParser( prog="sound-change-applier-v2.0", description="A program that applies phonological rules to words.", epilog="For more informat...
5,302,792
def nfour_connectivity(I): """ Returns an image of four-connectivity for each pixel, where the pixel value is the number of 4-connected neighbors. """ Ir = np.ravel(I) edgeidcs = edge_coords(I.shape, dtype='flat') allpix = set(np.where(Ir==1)[0]) dopix = allpi...
5,302,793
def sync_params_on_init(sync): """ As default, RaNNC synchronizes model parameters on initialization. This aims to use same initial values of parameters on all ranks, but often takes a long time. You can skip the synchronization by passing ``False`` to this method when you use the same random seed o...
5,302,794
def plot_bargraph(count_plot_df, plot_df): """ Plots the bargraph Arguments: count_plot_df - The dataframe that contains lemma counts plot_df - the dataframe that contains the odds ratio and lemmas """ graph = ( p9.ggplot(count_plot_df.astype({"count": int}), p9.aes(x="lemma...
5,302,795
def flip_labels(Y, p): """Returns binary class labels with proportion p randomly flipped.""" assert set(Y) == {1, 2} Y = np.copy(Y) for i, e in enumerate(Y): if np.random.rand() < p: if e == 1: Y[i] = 2 else: Y[i] = 1 return Y
5,302,796
def find_key(obj, predicate=None): """This method is like :func:`pydash.arrays.find_index` except that it returns the key of the first element that passes the predicate check, instead of the element itself. Args: obj (list|dict): Object to search. predicate (mixed): Predicate applied pe...
5,302,797
def trigger_github_deployment_create(payload): """ Trigger the function that creates the GH deployment with the given payload """ response = lambda_client.invoke( FunctionName="{}-github_deployment_create".format( os.environ['FUNCTION_PREFIX']), InvocationType='RequestRespons...
5,302,798
def save_executable(exe_path, pipeline_id): """ Save a bash script with a command that will run the pipeline against a target directory and generate predictions. """ # TODO(maxlam): FINISH command = "testing" with open(exe_path, "w") as f: f.write(command)
5,302,799