content
stringlengths
22
815k
id
int64
0
4.91M
def findchallenge(name: str) -> Optional[HTBChallenge]: """Finds a specific challenge by name. Searches HTB for a specific challenge matching the specified name and returns it if one is found. Otherwise returns None. Args: name: An exact challenge name to lookup. Returns: A HTBChal...
5,286,900
def create_result_dataframe(y_test: DataFrame, y_pred: DataFrame, model_name: str) -> DataFrame: """ :param y_test: DataFrame with target values :param y_pred: DataFrame with predicted values :param model_name: Actual model name :return: DataFrame with models scores """ scores = _prepare_sc...
5,286,901
def create_custom_tiling_node(tile_mode, tile_level=TileLevel.L1, tensor_name=DEFAULT_STRING, tile_pos=DEFAULT_VALUE, tile_band=DEFAULT_VALUE, tile_axis=DEFAULT_VALUE, ...
5,286,902
def get_surface_distance(seg_pred, seg_gt, distance_metric="euclidean"): """ (from MONAI) This function is used to compute the surface distances from `seg_pred` to `seg_gt`. Args: seg_pred: the edge of the predictions. seg_gt: the edge of the ground truth. distance_metric: ...
5,286,903
def makeState(fromacct,toacct,amount): """ make a tranfer state parameter currently due to the compiler problem, must be created as this format :param fromacct: :param toacct: :param amount: :return: """ return state(fromacct, toacct, amount)
5,286,904
def params_used(self): """Check for that params in ``nextflow.config`` are mentioned in ``main.nf``.""" ignore_params_template = [ "params.custom_config_version", "params.custom_config_base", "params.config_profile_name", "params.show_hidden_params", "params.schema_ignor...
5,286,905
def brocher_vp(f): """ V_p derived from V_s via Brocher (2005) eqn 9. """ f *= 0.001 f = 0.9409 + f * (2.0947 - f * (0.8206 - f * (0.2683 - f * 0.0251))) f *= 1000.0 return f
5,286,906
def new_swapped_deployment( old_deployment: Dict, container_to_update: str, run_id: str, expose: PortMapping, add_custom_nameserver: bool, ) -> Dict: """ Create a new Deployment that uses telepresence-k8s image. Makes the following changes: 1. Changes to single replica. 2. Disa...
5,286,907
def final(data): """ Last evolution time point, can be used to obtain parameters at the very end of the run. :param data: numpy ndarray containing the history of the system. :return: selection of the last evolution point. """ return ([data.shape[0]-1],)
5,286,908
def detach_project_from_that_group(request): """ detach that group from the requested project """ id_project = request.matchdict[u'id'] id_group = request.matchdict[u'group_id'] project = request.dbsession.query(Project).options( joinedload(Project.groups)).get(id_project) group = r...
5,286,909
def main(): """ ############################################################################# # 1.Issue get request to private domain https://alb.workshop.com # # 2.You will see the error message of the exception - what happened? # ##################################################...
5,286,910
async def play_after_async( file: str, block: bool = BLOCK_WHILE_PLAYING, loop: bool = False, interval: float = DEFAULT_WAIT, ) -> AsyncContextManager[Path]: """Do a playback after a task is finished using asyncio""" try: yield file finally: await play_file_async(file, block...
5,286,911
def dec_resource(resource_port, expr, stream_port): """Decrease the count of available resource by the specified number, waiting for the processes capturing the resource as needed.""" r = resource_port e = expr s = stream_port expect_resource(r) expect_expr(e) expect_stream(s) expect_sam...
5,286,912
def _compute_v2_quantities(v2_arr, bias_arr, n_blocks): """Compute the squared visibilities quantities: - average ('v2') over the cube, - covariance ('v2_cov'), - avar ('avar') and - 'err_avar'.""" n_ps = v2_arr.shape[0] n_baselines = v2_arr.shape[1] v2 = np.zeros(n_baselines) v2_cov = np.zeros...
5,286,913
def make_default_config(project): """ Return a default configuration for exhale. **Parameters** ``project`` (str) The name of the project that will be searched for in ``testing/projects/{project}``. **Return** ``dict`` The global default testing conf...
5,286,914
def remove_bad_data(net, init='flat', tolerance=1e-6, maximum_iterations=10, calculate_voltage_angles=True, rn_max_threshold=3.0): """ Wrapper function for bad data removal. INPUT: **net** - The net within this line should be created **init** - (string) Initial voltage ...
5,286,915
async def execute_model( inputs, server_url=None, model_name=None, config=None, select_outputs=None, request_id="", model_version="", compression_algorithm="gzip", serialization="triton", decode_bytes=False, decode_json=False, verbose=False, **kwargs, ): """ F...
5,286,916
def find_suspicious_regions(misassemblies, min_cutoff = 2): """ Given a list of miassemblies in gff format """ regions =[] for misassembly in misassemblies: regions.append([misassembly[0], misassembly[3], 'START', misassembly[2]]) regions.append([misassembly[0], misassembly[4], 'EN...
5,286,917
def make_accounts(n) -> List[AccountSchema]: """Make n test accounts.""" return [ AccountSchema( uuid=uuid.uuid4(), bank_name=f"Starling Personal {i}", account_name=f"Account {i}", currency="GBP", created_at=datetime.now(pytz.timezone("Europe/L...
5,286,918
def fabonacci(n): """ Return the n'th number of the fabonacci sequence """ if n == 0: return 0 elif n == 1: return 1 else: return fabonacci(n-1) + fabonacci(n-2)
5,286,919
def read_file(filepath, *args, **kwargs) -> str: """Try different encoding to open a file in readonly mode.""" for mode in ("utf-8", "gbk", "cp1252", "windows-1252", "latin-1", "ascii"): try: with open(filepath, *args, encoding=mode, **kwargs) as f: content = f.read() ...
5,286,920
def s3_set_extension(url, extension=None): """ Add a file extension to the path of a url, replacing all other extensions in the path. @param url: the URL (as string) @param extension: the extension, defaults to the extension of current. request """ ...
5,286,921
def fill_from_root(filename, spectrum_name="", config=None, spectrum=None, bipo=False, **kwargs): """ This function fills in the ndarray (dimensions specified in the config) with weights. It takes the parameter specified in the config from the events in the root file. Args: fil...
5,286,922
def test_familymemberhistory_2(base_settings): """No. 2 tests collection for FamilyMemberHistory. Test File: familymemberhistory-example-mother.json """ filename = ( base_settings["unittest_data_dir"] / "familymemberhistory-example-mother.json" ) inst = familymemberhistory.FamilyMemberHi...
5,286,923
def low_rank_cov_root(covs, rank, implementation='randomized_svd'): """ return X: (n_data, n_dim, rank) matrix so that X[i].dot(X[i].T) ~ covs[i] """ n_data, n_dim = covs.shape[:2] if implementation == 'randomized_svd': X = np.empty((n_data, n_dim, rank)) for i in xrange(n_data): ...
5,286,924
def save_run(config, metric, metric_values, values, exp_type, path, timestamp): """ Save the experiment """ artefact = { 'config': config, metric: metric_values, 'values': values, 'exp_type': exp_type, 'timestamp': timestamp } joblib.dump(artefact, path)
5,286,925
def show_all(effect=True): """ 展示所有的颜色名称和代号 :param effect: 是否显示效果 :return: 终端打印效果或代号 提示:在一些终端可能无法显示,例如 windows """ max_len = 21 try: import os length = os.get_terminal_size().columns except: length = 200 base = "%s%s,%s%s" if plat == "Linux": ...
5,286,926
def _map(term, predicate): """ A 'generic-function' verison of map, which defers to term.map, if one exists, and otherwise calls predicate on term. Actually iterable mapping is handled by term.map """ # validate(predicate, collections.Callable) if _IS_LOGICAL(term): return term.m...
5,286,927
def run_examples(examples, args): """ Takes a list of Example objects, tests each one in succession, and prints data. Used from the command line, as in sample_problems.py """ # handle switches if '-v' in args: messages.set_verbosity(messages.normal) args.remove('-v') else: ...
5,286,928
def main(unused_argv): """Main entry point for SDK Fn Harness.""" if 'LOGGING_API_SERVICE_DESCRIPTOR' in os.environ: logging_service_descriptor = beam_fn_api_pb2.ApiServiceDescriptor() text_format.Merge(os.environ['LOGGING_API_SERVICE_DESCRIPTOR'], logging_service_descriptor) # Se...
5,286,929
def has_byobu() -> bool: """Determines whether byobu can run.""" return _has_command('byobu')
5,286,930
def fail(msg): """ Writes the message to stderr and exits with code 1. """ sys.stderr.write(msg + "\n") sys.exit(1)
5,286,931
def cylinder_divergence(xi, yi, zi, r, v): """ Calculate the divergence of the velocity field returned by the cylinder_flow() function given the path of a streamtube providing its path components xi, yi, zi. The theoretical formula used to calculate the returned variable 'div...
5,286,932
def aggregate(df, signal_names, geo_resolution='county'): """Aggregate signals to appropriate resolution and produce standard errors. Parameters ---------- df: pd.DataFrame County block group-level data with prepared signals (output of construct_signals(). signal_names: List[str] ...
5,286,933
def _equal_mstype(x, y): """ Determine if two mindspore types are equal. Args: x (mstype): first input mindspore type. y (mstype): second input mindspore type. Returns: bool, if x == y return true, x != y return false. """ return const_utils.mstype_eq(x, y)
5,286,934
def LM(f, *gens, **args): """ Return the leading monomial of ``f``. **Examples** >>> from sympy import LM >>> from sympy.abc import x, y >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **arg...
5,286,935
def markers( data: AnnData, head: int = None, de_key: str = "de_res", sort_by: str = "auroc,WAD_score", alpha: float = 0.05, ) -> Dict[str, Dict[str, pd.DataFrame]]: """ Parameters ---------- data: ``anndata.AnnData`` Annotated data matrix with rows for cells and columns for...
5,286,936
def vggcif16_bn(): """VGG 16-layer model (configuration "D") with batch normalization""" return VGGcif(make_layers(cfg['D'], batch_norm=True))
5,286,937
def get_platforms(): """Return the list of all the platforms""" controller = PlatformController return controller.get_list(MySQLFactory.get())
5,286,938
def test_score(piece1, jinja_env, instrument_list1, piano, tmpdir): """Test the score template.""" instruments = instrument_list1.append(piano) lyglobal = lynames.LyName(name='global') template = jinja_env.get_template('score.ly') render = template.render(piece=piece1, filename='score.ly', ...
5,286,939
def metade(x=0, cvsao=False): """ ==> Divide o valor de x pela metade :param x: valor recebido. :param cvsao: (opcional) Se deseja ou não exibir o valor convertido em moeda local :return: valor de x pela metade com ou não conversão para moeda local. """ x /= 2 if cvsao: x = moeda...
5,286,940
def to_conll_iob(annotated_sentence): """ `annotated_sentence` = list of triplets [(w1, t1, iob1), ...] Transform a pseudo-IOB notation: O, PERSON, PERSON, O, O, LOCATION, O to proper IOB notation: O, B-PERSON, I-PERSON, O, O, B-LOCATION, O """ proper_iob_tokens = [] for idx, annotated_token in enumerate(annotat...
5,286,941
def generate_bc(pattern, m, bc): """ 生成坏字符哈希表 :param pattern: :param m: :param bc: :return: """ for i in range(m): bc[ord(pattern[i])] = i
5,286,942
def get_moves(player): """Based on th tuple of player's position, return the list of acceptable moves Parameters ---------- player : tuple Player move data >>> GAME_DIMENSIONS = (2, 2) >>> get_moves((0, 2)) ['RIGHT', 'UP', 'DOWN'] """ x, y = player moves = ['LEFT',...
5,286,943
def get_models(model_names): """Retrieve Odoo models :param model_names: a list of Odoo model names :return: a list of dictionaries describing Odoo models """ query = create_model_query(model_names) app.logger.debug(query) return query_odoo("ir.model", "search_read", query)
5,286,944
def find_auto_threshold(trace_log, variants, decreasingFactor): """ Find automatically variants filtering threshold based on specified decreasing factor Parameters ---------- trace_log Trace log variants Dictionary with variant as the key and the list of traces as the va...
5,286,945
def setup_logger(file_path: str, default=True, error=False, warning=False): """ Allows to setup logging into user defined logging file. :param file_path: Full/relative path to the file to save logged messages :param default: Set in true to use default (all) log filter :param error: Set in true to l...
5,286,946
def test_repr(vec): """ repr(vec) be a Python expression representing vec """ from fractions import Fraction from hypervector import Vector, Vector2, Vector3 assert isclose(vec, eval(repr(vec)))
5,286,947
def insert_references(text, last_ref=0): """ Insert references section to the page according to local manual of style. last_ref parameter is used for transfering last reference position: it will be used for additional checks. If last_ref equals -1, references section will not be added. You...
5,286,948
def KK_RC44(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
5,286,949
def test_read_patch_comments(specfile, lines, files, expectation): """Check reading comment lines that belong to patches""" content = specfile.read_text() content = content.replace("### patches ###\n", lines) specfile.write_text(content) for patch_file in files: Path(specfile.parent, patch_f...
5,286,950
def collate_rank_eval(data): """Collate multiple datapoints for candidate product ranking during evaluation Parameters ---------- data : list of 3-tuples Each tuple is for a single datapoint, consisting of DGLGraphs for reactants and candidate products, scores for candidate products by ...
5,286,951
async def lock_tb(dut): """Randomly generates input code sequences to try to unlock the lock. Args: dut: The object representing the DUT being simulated. Required Environment Vars: NUM_LOCK_STATES: The number of input codes to generate in a sequece. LOCK_COMP_WIDTH: The width (in # of bits) of the i...
5,286,952
def garbage(): """ Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph` based on collected garbage. The collected elements are removed from ``gc.garbage``, but are still kept alive by the references in the graph. Deleting the :class:`~refcycle.object_graph.ObjectGraph` ins...
5,286,953
def fifo(FALL_THROUGH=0, DATA_WIDTH=32, DEPTH=8): """ args: FALL_THROUGH: fifo is in fall-through mode DATA_WIDTH: default data width if the fifo is of type DEPTH: depth can be arbitrary from 0 to 2**32 """ ADDR_DEPTH = int(log(DEPTH, 2)) if DEPTH > 1 else 1 F...
5,286,954
def from_snbt(snbt : str, pos : int = 0): """Create a TAG from SNBT when type is unknown""" #print(f'Starting tests at {pos}') for i in sorted(Base.subtypes, key = lambda i : i.snbtPriority): try: value, pos = i.from_snbt(snbt, pos) except ValueError: ...
5,286,955
def test_sulfoxide_normalization2(): """Normalize sulfoxide.""" assert standardize_smiles('COC1=CC2=C(C=C1)[N]C(=N2)[S](=O)CC3=C(C(=C(C=N3)C)OC)C') == 'COc1ccc2c(c1)N=C([S+]([O-])Cc1ncc(C)c(OC)c1C)[N]2'
5,286,956
def parse_data_txt(zip_file_path): """ Extract the tables in fastqc_data.txt from FastQC results contained in a zip file. Returns a dictionary representing the tables in the file, keyed by section headers in the form: {u'Basic Statistics': {'column_labels': (u'Measure', u'Value'), ...
5,286,957
def _construct_lookup( orders, dists, growth, recurrence_algorithm, rules, tolerance, scaling, n_max, ): """ Create abscissas and weights look-up table so values do not need to be re-calculatated on the fly. """ x_lookup = [] w_look...
5,286,958
def feedback_system(request): """ get: Get the contents of the system feedback. post: Add a new system feedback from a user. delete: Delete a the user's system feedback. """ if request.method == 'GET': feedback = SystemFeedback.objects.all() serializer = S...
5,286,959
def show_game_over() -> None: """ Muestra en la pantalla el mensaje GAME OVER """ draw_text("GAME", WINDOW_WIDTH / 2 - 5, WINDOW_HEIGHT / 2 - 80, size=70, fill="#E3E4E5") draw_text("OVER", WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, size=70, fill="#E3E4E5")
5,286,960
def init_network_socket(host='127.0.0.1', port=3310, timeout=None): """Deprecated API - use ClamdNetworkSocket instead.""" global socketinst socketinst = ClamdNetworkSocket(host=host, port=port, timeout=timeout)
5,286,961
def connected_component(mg, bus, notravbuses=[]): """ Finds all buses in a NetworkX graph that are connected to a certain bus. INPUT: **mg** (NetworkX graph) - NetworkX Graph or MultiGraph that represents a pandapower network. **bus** (integer) - Index of the bus at which the search for co...
5,286,962
def print_stlats(*players): """ Pretty print the stlats for the given list of players """ headers = [ 'base_thirst', 'continuation', 'ground_friction', 'indulgence', 'laserlikeness', 'divinity', 'martyrdom', 'moxie', 'musclitude', ...
5,286,963
def choose_bits(): """Asks the user for the number of bits reserved to the hidden message and changes it.""" while True: n = input("\n\033[1mNumber of bits reserved to the hidden message: \033[0;2m(default is 2; maximum 8; 0 to exit)\033[0m ") if n == '0': exit() elif n.isnu...
5,286,964
def get_vm_by_id(id): """Returns the VM setting information of a VM""" r = requests.get(api_url + '/vms/' + id, headers=headers).json() # populate name for vm in get_vms(): if vm['id'] == id: r['name'] = os.path.split(vm['path'])[1].split('.')[0] return r
5,286,965
def parse_mr_job_stderr(stderr, counters=None): """Parse counters and status messages out of MRJob output. :param stderr: a filehandle, a list of lines (bytes), or bytes :param counters: Counters so far, to update; a map from group (string to counter name (string) to count. Return...
5,286,966
def predict_coefficients(inputs: tf.Tensor, hparams: tf.contrib.training.HParams, reuse: object = tf.AUTO_REUSE) -> tf.Tensor: """Predict finite difference coefficients with a neural networks. Args: inputs: float32 Tensor with dimensions [batch, x]. hparams...
5,286,967
def ckd(xparentkey: Octets, index: Union[Octets, int]) -> bytes: """Child Key Derivation (CDK) Key derivation is normal if the extended parent key is public or child_index is less than 0x80000000. Key derivation is hardened if the extended parent key is private and child_index is not less than 0x8...
5,286,968
def _treeizeAvailabilityZone(zone): """Build a tree view for availability zones.""" AvailabilityZone = availability_zones.AvailabilityZone az = AvailabilityZone(zone.manager, copy.deepcopy(zone._info), zone._loaded) result = [] # Zone tree view item az.zoneName = zone...
5,286,969
def reducer(state, action): """Add HTML loaded action to state""" if isinstance(action, dict): try: action = forest.actions.Action.from_dict(action) except TypeError: # TODO: Remove try/except when Actions are supported return state if isinstance(state, di...
5,286,970
def parseDisambig(html): """Parse disambiguation page and return list of (article, text) tuples.""" sections = OrderedDict() soup = bs4.BeautifulSoup(html, 'lxml') for i in soup.find_all(True, class_=skipclass): i.decompose() sections[''] = _processDisambigSection(soup) for i in soup.fin...
5,286,971
def main(): """ stuff """ # # Search the nr database # database = "../data/nr.db" sequences = [ "MSYLGQTDDRAIRQLACKCSVPREQTVHVAKGGPEDCRGAGGSAVGSSRMGPRWVLRMVTRHFILVQRSRSPVSLLPRRRFGRPTPPHPAPSPTLLASKQHIIISDRQKRPHRCALPKNFSPSKISSLRQAENPKMVP", "MSYLGQTDDRAIRQLACKCSVPREQTVHVAKGGPEDCRGA...
5,286,972
def get_rookie_prediction(input): """This function receives the data from the requests, parses it as a dictionary and gets the prediction Args: input (json) The request body Returns: The prediction for the input value """ try: data = json.loads(input) except ValueEr...
5,286,973
def task_rebuild_lowering_directory(gearman_worker, gearman_job): """ Verify and create if necessary all the lowering sub-directories """ job_results = {'parts':[]} payload_obj = json.loads(gearman_job.data) logging.debug("Payload: %s", json.dumps(payload_obj, indent=2)) gearman_worker.se...
5,286,974
def make_makeblastdb_cmd(filename): """ Construct a makeblastdb command line to make a BLAST nucleotide database from the passed fragmented input sequence FASTA file. - filename is the location of the fragmented input FASTA sequence file, for constructing the database """ db_p...
5,286,975
def config_register(value): """Register a value or values. Parameters: -A Value """ return ConfigurationSettings().register(value)
5,286,976
def add_topics_v1(df): """Add topics to the given dataframe Performs the addition in-place Parameters ---------- df: DataFrame source dataframe to add topics to """ for topic, params in TOPICS.items(): topic_counts = df["text"].str.count(params["regex"]) df[f"topic...
5,286,977
def normalize(text): """ Normalizes text before keyword matching. Converts to lowercase, performs KD unicode normalization and replaces multiple whitespace characters with single spaces. """ return unicodedata.normalize('NFKD', re.sub(r'\s+', ' ', text.lower()))
5,286,978
def main() -> None: """Main entry point.""" arguments = docopt(__doc__, version=__version__) bundle_name = arguments["--bundle"] filenames = generate_filenames(bundle_name) configure_logger(filenames.log_file) logging.info("Initializing Pyxel window") pyxel.init(width=SCREEN_WIDTH, he...
5,286,979
def gdb_path(): """ Get path to the gdb """ return _get_ya_plugin_instance().gdb_path
5,286,980
def pass_to_key(password): """Return a key from the given password for encryption.""" byte_pass = password.encode() kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=b"\r7\xb6bT\xa0\xd5\xdcG.'+\xb7\xdb\r\xcd", iterations=100000, backend=default_backend() ...
5,286,981
def _ProcessCards(data): """Process the set lines and corresponding data""" # Reset all values # ------------------------------------------------------------------------- setLine = [] sd = {"brN": None, "branches": None, "histN": None, "histories": None, "times": None, "units": None} ...
5,286,982
def sigmoid_backward(x): """ derivation of sigmoid Paras ----------------------------------- x: output of the linear layer Returns ----------------------------------- max of nums """ s = sigmoid(x) return s * (1 - s)
5,286,983
def csv_announcement_email(df_matched): """ This function returns the df_matched in the format that can be used for the email messaging: Announcing buddies to the participants. Use of the email template email_responses.py. """ df_email_og = df_matched.copy() df_email_og.drop(["id_user_1", "id_us...
5,286,984
def test_default_startup_program(): """ test default_startup_program :return: """ train_program = fluid.Program() startup_program = fluid.Program() with fluid.unique_name.guard(): with fluid.program_guard(train_program, startup_program): x = fluid.layers.data(name="x", sh...
5,286,985
def list_sources(username, token=None): """List all Tileset Sources for an account. Response is an un-ordered array of sources. tilesets list-sources <username> """ mapbox_api = utils._get_api() mapbox_token = utils._get_token(token) s = utils._get_session() url = "{0}/tilesets/v1/sources/{...
5,286,986
def some_class_from( value: typing.Any, id: str, other_classes_registry: typing.Mapping[ str, some.graph.OtherClass], some_classes_registry: typing.Mapping[ str, some.graph.SomeClass], ref: str, errors: some.graph.parse.Erro...
5,286,987
def min_steps(step_records): """ Random """ tmp=list() for k,v in step_records.items(): tmp.append((v,k)) print( tmp) tmp.sort() print(tmp) print(min(tmp))
5,286,988
def multiple( context: mgp.ProcCtx, start_points: List[mgp.Vertex], end_points: List[mgp.Vertex], metrics: str = "m", ) -> mgp.Record(distances=List[float]): """ This distance calculator procedure for multiple entries returns 1 field. * `distances` is the final result obtained by calcula...
5,286,989
def merge_reads_with_novelty(reads, novelty): """ Given a data frame of reads and a transcript novelty data frame, perform a left merge to annotate the reads with their novelty status. """ merged = pd.merge(reads, novelty, on = "transcript_ID", how = "left") return merged
5,286,990
def run_with_timeout(command, timeoutSecs, inputStream = "", combinedOutput=True): """ Runs the given process until it exits or the given time out is reached. Returns a tuple: (bool:timeout, str:stdout, str:stderr, int:exitcode) """ timePassed = 0.0 increment = 0.01 stderrFD, errFile = tem...
5,286,991
def cash (): """*****for retrieving cash data from stock.csv FILE and use it accordingly.*****""" fp = open("stock.csv","r") #*****FILE pointer which is opening the file stock.csv as in read mode***** first = fp.readline() split_line = first.split(",") cash = float(split_line[0]) stockCash.appen...
5,286,992
def compute_bin_efficiencies(y_score, bin_indices, cut, sample_weight, minlength=None): """Efficiency of bin = total weight of (signal) events that passed the cut in the bin / total weight of signal events in the bin. Returns small negative number for empty bins""" y_score = column_or_1d(y_score) as...
5,286,993
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ from math import floor if type(kernel_size) is not tuple: kernel_size = (kernel_size, kernel_size) ...
5,286,994
def deadvertizeFactory(factory_name, glidein_name, factory_collector=DEFAULT_VAL): """ Deadvertize all entry and global classads for this factory. """ tmpnam = classadSupport.generate_classad_filename(prefix='gfi_de_fact') fd = file(tmpnam, "w") try: try: fd.write('MyType = "...
5,286,995
def random_int(n=5): """ Create a random string of ints :return: """ return str(random.randint(1, 10 ** n))
5,286,996
def main(): """Write id conversion files, from pharm, pubchem, and inchi to chembl.""" c_df = pd.read_csv('../raw_data/chemicals/chemicals.tsv', sep='\t') d_df = pd.read_csv('../raw_data/drugs/drugs.tsv', sep='\t') drugs_df = d_df.append(c_df, ignore_index=True) drugs_df = drugs_df.drop_duplicates(...
5,286,997
def generate_dataset(data_dir, train=True, n_noisy=30000, k=5): """generate mnist noisy dataset""" data = [] img_sampler = get_noisy_sampler(data_dir) num_sampler = get_number_sampler(load_mnist(data_dir, 'train' if train else 'test')) for i in range(10): print('Generate for number %d ...' %...
5,286,998
def always_no_state(function, interval): """ This constraint ensures that a state function is undefined on an interval. This function returns a constraint that ensures that *function* is undefined everywhere on an interval (interval variable *interval* when it is present or fixed interval [*start*, *end*))...
5,286,999