content
stringlengths
22
815k
id
int64
0
4.91M
def _normalize_unknown_symbols(token): """Símbolos (letras) no reconocidos los decodifica a ASCII.""" return ''.join([ s if ALPHABET.match(s) else _to_unicode(unidecode(s)) for s in _to_unicode(token)])
57,700
def _customized_dumper(container, dumper=Dumper): """ Coutnerpart of :func:`_customized_loader` for dumpers. """ def container_representer(dumper, data, mapping_tag=_MAPPING_TAG): """Container representer. """ return dumper.represent_mapping(mapping_tag, data.items()) def us...
57,701
def write_data(data: Dict[str, pd.DataFrame], start_date: str, end_date: str) -> None: """Writes data as csv to local storge folder 'data' naming based on ticker and dates Args: data (Dict[str, pd.DataFrame]): Dictionary of raw data as dataframe objects with the ticker filename as the key ...
57,702
def inverse_qft(qc, reg, n): """Inverse qft.""" for i in range(0, n): qc.cu1(reg[i], reg[n], -1*math.pi/float(2**(n-i))) qc.h(reg[n])
57,703
def raw_encode(data): """Special case serializer.""" content_type = 'application/data' payload = data if isinstance(payload, unicode): content_encoding = 'utf-8' payload = payload.encode(content_encoding) else: content_encoding = 'binary' return content_type, content_enco...
57,704
def iou(box1, box2): """Computes pairwise intersection-over-union between box collections. Args: box1: a float Tensor with [N, 4]. box2: a float Tensor with [M, 4]. Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = intersection(box1, box2) areas1 = area(...
57,705
def bytes_realize(space, py_obj): """ Creates the string in the interpreter. The PyBytesObject buffer must not be modified after this call. """ py_str = rffi.cast(PyBytesObject, py_obj) s = rffi.charpsize2str(py_str.c_buffer, py_str.c_size) w_obj = space.wrapbytes(s) track_reference(spac...
57,706
def get_interface_by_name(interfaces, name): """ Return an interface by it's devname :param name: interface devname :param interfaces: interfaces dictionary provided by interface_inspector :return: interface dictionary """ for interface in interfaces: if interface['devname'] == name:...
57,707
def plot_cornsyrup(df: pd.DataFrame, out: str = "plot.png"): """Creates a catplot of the data. Args: df (pd.DataFrame): The dataframe to use when plotting. out (str): The path to save the plotting graphic to. Returns: None: The graphic is saved to `out` as a side effect. """ ...
57,708
def trata_texto(texto): """ Trata textos convertendo para maiusulo,\n sem acentos e espaços indesejaveis. """ texto = texto.strip().upper() texto = unicodedata.normalize("NFKD", texto) texto = texto.encode("ascii", "ignore") texto = texto.decode("utf-8").upper() # print(f"trata texto...
57,709
def _apply_new_uuid_mapping(table, mapping): """Take a mapping of pks to UUIDs and apply it to the given table. :param table: database table with uuid column, e.g. 'db_dbnode' :param mapping: dictionary of UUIDs mapped onto a pk """ from aiida.manage.manager import get_manager backend = get_man...
57,710
def get_checkpoint(model, checkpoint='-1'): """Set the checkpoint in the model directory and return the name of the checkpoint Note: This function will modify `checkpoint` in the model directory. Args: model: The model directory. checkpoint: The checkpoint id. If None, set to the BEST one. ...
57,711
def normalize_trans_probs(p): """ Normalize a set of transition probabilities. Parameters ---------- p : pandas.DataFrame, dtype float Unnormalized transition probabilities. Indexed by source_level_idx, destination_level_idx. Returns ------- pandas.DataFrame, dtype floa...
57,712
def vel(track, t_vel, r): """Randomly change the velocity of a note in a track""" time = 0 for msg in track: if msg.type == 'note_on' or msg.type=='note_off': time += msg.time if msg.type == 'note_on': if msg.velocity != 0: # To avoid messing with certain mid ...
57,713
def resize_with_fixed_AR(img, bboxes, h_dst, w_dst): """resize with fixed aspect ratio""" w_src = tf.cast(tf.shape(img)[1], tf.float32) h_src = tf.cast(tf.shape(img)[0], tf.float32) # resize image if h_dst > h_src * (w_dst / w_src): scale = (w_dst / w_src) else: scale = (h_d...
57,714
def choose(): """ Get the user to choose which quiz. :returns: A HTML page with a form, then redirects them to the correct quiz's page once the form is submitted. """ # Ask user which quiz. if 'quiz' not in request.args: return render_template('new.html', quizzes=quizzes) ...
57,715
def get_number_of_ones(n): """ Deterine the number of 1s ins the binary representation of and integer n. """ return bin(n).count("1")
57,716
def hierarchical_link_community(g_original: object) -> EdgeClustering: """ HLC (hierarchical link clustering) is a method to classify links into topologically related groups. The algorithm uses a similarity between links to build a dendrogram where each leaf is a link from the original network and branches ...
57,717
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4): """Gets a bunch of sinusoids of different frequencies. Args: length: scalar, length of timing signal sequence. channels: scalar, size of timing emebddings to create. The number of different timescales...
57,718
def license_update(args): """license handler for xlwings PRO""" key = args.key if not key: sys.exit( "Please provide a license key via the -k/--key option. " "For example: xlwings license update -k MY_KEY" ) license_kv = '"LICENSE_KEY","{0}"\n'.format(key) # U...
57,719
def get(keys): """Wrapper around db.get that counts entities we attempted to get.""" DB_GET.inc(increment=_count(keys)) return db.get(keys)
57,720
def test_kval(q, c): """ Calculate and print the kernel function value between a query string and a candidate. :param q: Query string to calculate the k value in reference to :param c: Candidate to calculate the k value for :return: None """ k = kval(q, c) print k
57,721
def get_graph(request): """Function for getting graph This function allows to get the current graph from server. """ id_of_graph = request.GET.dict()["id"] graph = Graph.objects.get(id=int(id_of_graph)) with open(graph.path_to_graph) as file: data = json.load(file) return JsonR...
57,722
def startswith(df_series, match:str): """ Filter pd.series with string and get index Parameters ---------- df_series : pd.Series match : str, to search the series Returns ------- idx: bool """ return np.array(df_series.str.startswith(match), dtype = bool)
57,723
def get_params_path(reconstructor_key_name_or_type, dataset_name): """ Return path of the parameters for a configuration. It can be passed to :class:`Reconstructor.load_params` as a single argument to load all parameters (hyper params and learned params). Parameters ---------- reconstructor...
57,724
def Pixel_Calibration(motorName,start,stop,step,camNUM,AcqTime): """ """ scanIOC=BL_ioc() scanDIM=1 branch=CheckBranch() if branch == "c": m_RBV,m_VAL=ARPES_PVmotor(motorName) elif branch == "d": m_RBV,m_VAL=Kappa_PVmotor(motorName) pvCam="29id_ps"+str(camNUM)+":"...
57,725
def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulus * vec2_modul...
57,726
def _func_flagvalue(args, is_differentscenario, line, pos): """フラグの値を読む。""" _chk_argscount(args, 1, "FLAGVALUE", line, pos) _chk_string(args[0], "FLAGVALUE", 0) path = args[0].value event = cw.cwpy.event.get_nowrunningevent() if event and path in event.flags: flag = event.flags[...
57,727
def _find_depot_tools(): """Attempts to configure and return a wrapper for invoking depot tools. Returns: A helper object for invoking depot tools. Raises: _DepotToolsNotFoundException: An error occurred trying to find depot tools. """ class DepotToolsWrapper(object): def __init__(self, path):...
57,728
def help(): """ Форма генерации счета для дебага. Принимает POST-запрос с пейлоадом, отдает PDF """ if request.method == "GET": payload_str = json.dumps(sample_payload_obj, indent=4, ensure_ascii=False) return render_template("sample_payload.html", sample_payload_obj=payload_str) pa...
57,729
def cast(variable, dtype): """ Cast sparse variable to the desired dtype. Parameters ---------- variable Sparse matrix. dtype The dtype wanted. Returns ------- Same as `x` but having `dtype` as dtype. Notes ----- The grad implemented is regular, i.e. no...
57,730
def get_authorized_certificate_output(app_id: Optional[pulumi.Input[str]] = None, authorized_certificate_id: Optional[pulumi.Input[str]] = None, view: Optional[pulumi.Input[Optional[str]]] = None, opts: Opt...
57,731
def shape_calculator_transfer_transformer(operator): """ Shape calculator for :epkg:`TransferTransformer`. """ if len(operator.inputs) != 1: raise RuntimeError( # pragma: no cover "Only one input (not %d) is allowed for model %r." "" % (len(operator.inputs), operator)) ...
57,732
def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """ # TODO it keeps the graph alive import tensorflow as tf GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_NAME) r...
57,733
def __notify__(user, type, *message): """ This function send a notifications for the user :param user: the user whom this function notify :type user: globals.User :param type: the type of the message :type type: str :param message: the contact for the message :type message: list[str] """ message ...
57,734
def get_smiles(inp_str, species): """ Get the inchi name of the species """ # Set the geom pattern smi_pattern = ('smiles' + zero_or_more(SPACE) + '=' + zero_or_more(SPACE) + capturing(one_or_more(NONNEWLINE))) # Obtain the appropriate species string species_str = get_spec...
57,735
def find_recipes(recipes, cur_recipes, puzzle, condition, result): """Find recipes as long as condition function is True. Returns result of result function, based on recipes and puzzle. """ while condition(recipes, puzzle): next_recipe = sum(recipes[recipe] for recipe in cur_recipes) di...
57,736
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre): """detector and beam are dxtbx objects, mosflm_beam_centre is a tuple of mm coordinates in order (slow, fast). supports 2-theta offset detectors, assumes correct centre provided for 2-theta=0 """ slow_fast_beam_centre = mosflm_beam_...
57,737
async def votable(ctx): """Configure what parts of the game are subject to democratic decision""" if ctx.invoked_subcommand is None: raise CommandNotFound()
57,738
def prob1(N=10000): """Return an estimate of the volume of the unit sphere using Monte Carlo Integration. Input: N (int, optional) - The number of points to sample. Defaults to 10000. """ points = np.random.rand(3, N) points = points*2 - 1 radiusMask = la.norm(points,ax...
57,739
def delete_meal(): """[summary]""" meal = flask.request.json.get("delete_meal") delete_meal_db(current_user.email, meal)
57,740
def verify_checksums(sources: Iterable[str], hashes: Dict[str, Sequence[str]]) -> bool: """Verify checksums for local files. Prints a message whenever there is a mismatch. Args: sources: An iterable of source strings. hashes: A dictionary of hash name -> hashes. For each entry,...
57,741
def fix_pipe_arg(*args): """Use this function so that if a pipe is passed to it it will automatically use its open function wprk in progress""" print(args) new_args = [] for arg in args: if(type(arg) is Pipe): new_args.append(arg.open) else: new_args...
57,742
def _list_setitem_with_number(data, number_index, value): """ Assigns value to list. Inputs: data (list): Data of type lis. number_index (Number): Index of data. value (Number): Value given. Outputs: list, type is the same as the element type of data. """ return...
57,743
def mergeMaps(map1, weight1, map2, weight2, combfn): """Combine values in two maps according to the passed combfn function, and passed weights for each map.""" # Odds are good that there are built-in function for this # operation. objects1 = map1.keys() objects2 = map2.keys() allObjects = set(objects1).union(set...
57,744
def write_read_list(readset, bipartition, sample_components, numeric_sample_ids, output_file): """ Write a list of reads that has been used for phasing to given file object. readset -- core.ReadSet object with reads to be written bipartition -- bipartition of reads, i.e. iterable with one entry from {0,...
57,745
def update_device_status_on_db( ipaddress: str, connection_status: str, timestamp: str, ) -> None: """ This function update a device environment file to the DB parm: ipaddress: str connection_status: str timestamp: str return: None """ try: # G...
57,746
def _inject_net_into_fs(net, fs, execute=None): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = os.path.join(os.path.join(fs, 'etc'), 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute(...
57,747
def example_control_dependency(src: Channel, example_name: Text, dependency: Channel, namespace: Text = DEFAULT_NAMESPACE ) -> None: """ Add example control dependency. It means src channe...
57,748
def convert_numpy_data_to_polydata(data, header, TNB=None, PT=None): """Converting a range of data to a vtk array. Args: data (numpy.ndarray): Data array. header (list): A list of names for each array. TNB (numpy.ndarray): Data array. PT (numpy.ndarray): Data array. Returns...
57,749
def _get(url): """ Convert a URL into it's response (a *str*). """ if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib...
57,750
def fun_compose(g, f): """Function composition using the geach combinator for the appropriate type, defined above.""" if (not (g.type.functional() and f.type.functional() and g.type.left == f.type.right)): raise types.TypeMismatch(g, f, "Function composition type constraints not met") ...
57,751
async def async_api_set_percentage(hass, config, directive, context): """Process a set percentage request.""" entity = directive.entity percentage = int(directive.payload['percentage']) service = None data = {ATTR_ENTITY_ID: entity.entity_id} if entity.domain == fan.DOMAIN: service = fa...
57,752
def _normalize_in_app(stacktrace, platform=None, sdk_info=None): """ Ensures consistent values of in_app across a stacktrace. """ has_system_frames = _has_system_frames(stacktrace) for frame in stacktrace: # If all frames are in_app, flip all of them. This is expected by the UI if no...
57,753
def login_user(username, password): """ Logs in a user Arguments: username <str>: The username of the user password <str>: The password of the user """ query = f""" SELECT * FROM users WHERE username = '{username}' AND password_hash = '{password}'; """ return ...
57,754
def compare_file(filename, dir1, dir2): """Compare identically named files in two different directories""" assert filecmp.cmp( os.path.join(dir1, filename), os.path.join(dir2, filename))
57,755
def rapids(expr): """ Fire off a Rapids expression. :param expr: The rapids expression (ascii string). :return: The JSON response of the Rapids execution """ result = H2OConnection.post_json("Rapids", ast=urllib.quote(expr)) if result['error'] is not None: raise EnvironmentError("rapids expression no...
57,756
def get_aqi_pm10_24h(pm10_24h: float) -> (int, str, str): """ Calculates PM10 (24h) India AQI :param pm10_24h: PM10 average (24h), μg/m3 :return: PM10 India AQI, Effect message, Caution message """ cp = __round_down(pm10_24h) return __get_aqi_general_formula_texts(cp, IN_PM10_24H, IN_AQI_EF...
57,757
def net_umap( data: MultimodalData, rep: str = "pca", n_jobs: int = -1, n_components: int = 2, n_neighbors: int = 15, min_dist: float = 0.5, spread: float = 1.0, random_state: int = 0, select_frac: float = 0.1, select_K: int = 25, select_alpha: float = 1.0, full_speed: bo...
57,758
def main(): """Run the script.""" capabilities = CAPABILITIES.copy() capabilities.sort() for c in capabilities: print("{} = '{}'".format(re.sub(r"([A-Z])", r"_\1", c).lower(), c))
57,759
def add_user_to_role(user_id, role_id): """ Add a role to a user. Requires server role management. """ auth_headers = { "Authorization": f"Bot {DISCORD_BOT_TOKEN}", } url = f"{DISCORD_API_BASE_URL}/guilds/{DISCORD_GUILD_ID}/members/{user_id}/roles/{role_id}" response = requests.put(url, head...
57,760
def arcmatch(curve,sci,arc,yforw,widemodel,finemodel,goodmodel,linemodel,disp,mswave,extra,logfile): """ arcmatch(curve,sci,arc,yforw,widemodel,finemodel,goodmodel,linemodel ,disp,mswave,extra,logfile) Creates the full 2d distortion solution for a slit. Inputs: curve - first pixel (ie bottom) of...
57,761
def format_rehydrate_payload(micro_form_data, application_id, page_name): """ Returns information in a JSON format that provides the POST body for the utilisation of the save and return functionality in the XGovFormBuilder Parameters: micro_form_data (dict): application data to refo...
57,762
def autolist(ini_file, raw_dir, lst_dir, sel_obj=None, sel_band=None, extra_config=None, # withbands=True, spchar="_" ): """ create list for files in datadir, by their names 21a: use [re] but not [parse], [parse] does not work good at 85 filenames :par...
57,763
def get_p_train_step(): """Wraps train_step with jax.pmap.""" p_train_step = jax.pmap(train_step, axis_name='batch', static_broadcasted_argnums=(3, 4)) return p_train_step
57,764
def cleanup(workflow_uuid, workflow_workspace, publisher): """Do cleanup tasks before exiting.""" logging.info( 'Workflow {workflow_uuid} finished. Files available ' 'at {workflow_workspace}.'.format( workflow_uuid=workflow_uuid, workflow_workspace...
57,765
def run_local(name, model_uri, flavor=None, config=None): """ Run the RedisAI docker container locally and deploy the model to it. It requires docker to be installed in the host machine. Parameters ---------- name : str Name/key for setting the model in RedisAI model_uri : str ...
57,766
def save_image(image, filename): """ Saves unscaled Tensor Images. Args: image: 3D image tensor. [height, width, channels] filename: Name of the file to save to. """ if not isinstance(image, Image.Image): image = tf.clip_by_value(image, 0, 255) image = Image.froma...
57,767
def monkey_patch(): """Hook to monkey-patch the interpreter for this IO module. This calls the standard eventlet monkey-patching routines. Don't worry, it's not called by default unless you're running from the command line. """ eventlet.monkey_patch()
57,768
def test_different_n_values(): """ test_different_n_values() makes sure that various values of n can be loaded into the file without it breaking Checks if the file exists, then loads it in n is set to 1 permenantly such that only one file at a time gets loaded If offset is 7 or above, an error shoul...
57,769
def proper_case(package_name): """Properly case project name from pypi.org.""" # Hit the simple API. r = _get_requests_session().get( f"https://pypi.org/pypi/{package_name}/json", timeout=0.3, stream=True ) if not r.ok: raise OSError(f"Unable to find package {package_name} in PyPI re...
57,770
def predict(url): """ Returns predicted label. params: link or image bytes """ # generating filename datetimeObj = datetime.now() # if url if as https://miro.medi... if "https" in url: response = requests.get(url) pred = prediction(response.content) retu...
57,771
def read_inputs(nomefile, key_strings, n_lines = None, itype = None, defaults = None, verbose=False): """ Standard reading for input files. Searches for the keys in the input file and assigns the value to variable. :param keys: List of strings to be searched in the input file. :param defaults: Dict with...
57,772
def get_test_data_folder(version='1.2', which=''): """ """ import pyswagger.tests.data version = 'v' + version.replace('.', '_') folder = os.path.dirname(os.path.abspath(pyswagger.tests.data.__file__)) folder = os.path.join(os.path.join(folder, version), which) return folder
57,773
def maybe_download_and_extract(url, download_dir): """ Download and extract the data if it doesn't already exist. Assumes the url is a tar-ball file. :param url: Internet URL for the tar-file to download. Example: "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" :param downl...
57,774
def _fn_tan_ ( self , b = 1 ) : """ Tangent function: f = tan(ab) >>> f = >>> a = f.tan ( ) >>> a = f.tan ( b ) >>> a = tan ( f ) """ return _fn_make_fun_ ( self , b , Ostap.MoreRooFit.Tan , ...
57,775
def error_output_bf(number_of_parameters, parameters_file_name): """Write the optimized error values into the params file near the corresponding parameter identicator""" try: file2 = open(parameters_file_name, "a+") #file2.seek(0) #position2 = file2.tell() ...
57,776
def read_fastq_fields(iterable): """ Print out a list of triples (read name, nucleotide seq., quality string), given a list of text lines. >>> list(read_fastq_fields( ... ["@read1","AAAA","+read1","FFFF","@read2","CCC","+","FFF"])) [('read1', 'AAAA', 'FFFF'), ('read2', 'CCC', 'FFF')] >>...
57,777
async def test_locator_do_work_transfer_request_fc_its_over_9000(config, mocker): """Test that _do_work_transfer_request processes each file it gets back from the File Catalog.""" logger_mock = mocker.MagicMock() lta_rc_mock = mocker.MagicMock() lta_rc_mock.request = AsyncMock() lta_rc_mock.request....
57,778
def get_weekday_type(date_to_test): """Gets the weekday of a date Parameters ---------- date_to_test : date Date of a day in ayear Returns ------- daytype : str holiday or working day Note ---- Bank holidays are defined for the year 2002 - 2015. The whole week ...
57,779
def multi_head(heads, loss_weights=None): """Creates a MultiHead stemming from same logits/hidden layer. Args: heads: list of Head objects. loss_weights: optional list of weights to be used to merge losses from each head. All losses are weighted equally if not provided. Returns: A instance o...
57,780
def test_meta__no_notebooks_found(tmpdir: LocalPath, caplog: LogCaptureFixture) -> None: """Log that no notebook was found in the paths passed.""" caplog.set_level(logging.INFO) nb_path = tmpdir.mkdir("notebooks") / "inexistent_nb.ipynb" # type: ignore result = runner.invoke(app, ["meta", str(nb_path)...
57,781
def alarm_content() -> str: """ Determines alarm content and adds it to alarm. Checks whether the news and weather briefing tickboxes have been ticked. If they have been ticked it will poll the corresponding api and provide the corresponding information when the alarm goes off. If neither box has b...
57,782
def map_package_to_dataset(package, portal_url): """Mapea un diccionario con metadatos de cierto 'package' de CKAN a un diccionario con metadatos de un 'dataset' según el estándar data.json.""" dataset = dict() resources = package["resources"] groups = package["groups"] tags = package["tags"] ...
57,783
def op_abs(x): """Returns the absolute value of a mathematical object.""" if isinstance(x, list): return [op_abs(a) for a in x] else: return abs(x)
57,784
def add_column(colname, desc=None): """Adds column in the form of dict.""" return {'name': colname, 'desc': desc}
57,785
def pprint(ast, file=None): """ Pretty print a Pickle AST to a file or stdout """ AstPrinter(file).dump(ast)
57,786
def bulk_update_google_groups(google_bulk_mapping): """ Update Google Groups based on mapping provided from Group -> Users. Args: google_bulk_mapping (dict): {"googlegroup@google.com": ["member1", "member2"]} """ google_project_id = ( config["STORAGE_CREDENTIALS"].get("google", {})....
57,787
def mc_rollout( steps, checkpoint, environment, env_name, callbacks, loggers, output_dir, input_config, step_tolerance=1000000, algorithm="PPO", multi_agent=False, ): """ Monte Carlo rollout. Currently set to return brief summary of rewards and metrics. """ c...
57,788
def test_attempt_to_overwrite_enqueued(measurement_workbench, fake_meas, tmpdir): """Test running the checks when an enqueued measurement with the same name and id already exists. """ fake_meas.name = 'test' fake_meas.id = '001' fake_meas.root_task.default...
57,789
def VerifyDependents(pe_name, dependents, delay_loaded, list_file, verbose): """Compare the actual dependents to the expected ones.""" scope = {} try: execfile(list_file, scope) except: raise Error("Failed to load " + list_file) # The dependency files have dependencies in two section - dependents and...
57,790
def word_by_category_cooccurrence(corpus, labels, tokenizer=None, min_count=0., max_count=None, max_words=None): """ Devuelve la matriz de coocurrencias entre palabras y la categoría a la que pertence el documento. Es decir, las filas de la matriz son las palabras y las columnas son todas las categ...
57,791
def main(): """ Can run this script to test Investment Portfolio service """ Get_Portfolios() #Get_Portfolio_Holdings("P1") Get_Portfolio_Holdings("MyFixedIncomePortfolio")
57,792
def timeit(fn): """ Timing decorator """ def timed(*args, **kwawgs): ts = time.time() result = fn(*args, **kwawgs) te = time.time() print '[time] %r: %2.2f sec' % \ (fn.__name__, te-ts) return result return timed
57,793
def ucnstring_to_python(ucn_string): """Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode (u'\\u4e00'). """ res = re.findall(r"U\+[0-9a-fA-F]*", ucn_string) for r in res: ucn_string = ucn_string.replace(text_type(r), text_type(ucn_to_unicode(r))) ucn_string = ucn_s...
57,794
def LOSToRedshift(xLOS, vLOS, H, split=False): """ Input: line of sight distances (Mpc), velocities (km/s) and Hubble constant. Output: relativistic (Doppler) and cosmological (Hubble) redshifts if split = True, otherwise the sum of these (default). """ c = 3.0e5 zREL = np.sqrt((1+vLOS/...
57,795
def keypoint_change_coordinate_frame(keypoints, window, scope=None): """Changes coordinate frame of the keypoints to be relative to window's frame. Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint coordinates from keypoints of shape [num_instances, num_keypoints, 2] to be relative to t...
57,796
def build_dataloaders(args, random_state=None): """ Build dataloaders according to experiment args Parameters ---------- args : argparse.Namespace Experiment arguments random_state : np.random.RandomState, optional (default: None) Optional random state for reproducibility in tra...
57,797
def save_master_list(conn, chrom, ml): """ :param conn: connection object :param chrom: chromosome number :param ml: master list of variants :return: nothing THIS WIPES ANY PREVIOUS DATA AND WRITES THE LIST AFRESH """ assert type(chrom) == int, 'Chromosome must be a number' assert chrom > 0, 'Chromos...
57,798
def main(): """ The main function """ django.setup() pynet_rtr3 = NetworkDevice( device_name='pynet-rtr3', device_type='cisco_ios', ip_address='192.168.100.1', port=22, ) pynet_rtr3.save() pynet_rtr4 = NetworkDevice.objects.get_or_create( device_...
57,799