content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import requests def get_local_funds_js(): """ Get funds string from js. 本來打算從 HTML 取得,但發現網站原本的 HTML 裡只有幾個 X ,資料是由 javascript 填入的。 """ taiwan_funds_endpoint = "https://www.moneydj.com/funddj/js/yfundjs.djjs" req = requests.get(taiwan_funds_endpoint) req.encoding = "big5" return req...
68f5d60c21fb7a23a1510f8400a95e6c9745b51d
674,428
import argparse def get_argument(): """Tinybert general distill argument parser.""" parser = argparse.ArgumentParser(description='tinybert general distill') parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU', 'CPU'], help='device where the c...
08e4ab5fdb23415453bfa30bb53cd5b66d296024
674,429
def __transit(partition,rawnodepart): """Map partition of partition to the partition of original nodes """ res = dict() for n,mn in rawnodepart.items(): res[n] = partition[mn] return res
c2759bacf24ebe65db085b61bbb3a7b3b12be769
674,430
from typing import Dict from typing import List def extract_tracks(plist: Dict) -> List[Dict[str, str]]: """Takes a Dict loaded from plistlib and extracts the in-order tracks. :param plist: the xml plist parsed into a Dict. :returns: a list of the extracted track records. """ try: ...
dc596d084909a68c0f7070d05db8a79585898993
674,431
import inspect def _source(obj): """ Returns the source code of the Python object `obj` as a list of lines. This tries to extract the source from the special `__wrapped__` attribute if it exists. Otherwise, it falls back to `inspect.getsourcelines`. If neither works, then the empty list is re...
0faf18c32fa03ef3ac39b8e163b8e2ea028e1191
674,432
def _CheckForUseOfWrongClock(input_api, output_api): """Make sure new lines of media code don't use a clock susceptible to skew.""" def FilterFile(affected_file): """Return true if the file could contain code referencing base::Time.""" return affected_file.LocalPath().endswith( ('.h', '.cc', '.cpp'...
73d85dd534a59f5aa650e9d8586a01c6b958a195
674,433
def is_connection_valid(connection): """ Checks if connection can be established """ try: connection.get_connection() return True except: return False
d612a9ba9968acc81aaea10f5fe4f53ee02bc55c
674,435
import csv def precip_table_etl_cnrccep( ws_precip, rainfall_adjustment=1 ): """ Extract, Transform, and Load data from a Cornell Northeast Regional Climate Center Extreme Precipitation estimates csv into an array Output: 1D array containing 24-hour duration estimate for frequencies 1...
ed1fef33ad36b0a5c1405242ef491b327e5d5911
674,437
def find_9(s): """Return -1 if '9' not found else its location at position >= 0""" return s.split('.')[1].find('9')
63c9fca569f50adcf5b41c03ab4146ce5c0bdd54
674,438
import re def _remove_repeating_whitespaces_and_new_lines(text: str) -> str: """ Removes repeating new lines and tabular char. """ return re.sub(r"(\n|\r|\t| ){1,}", " ", text)
8e89ed7334b7cd912bd4b83ee39b685aac1d0aff
674,439
def normalize_cov_type(cov_type): """ Normalize the cov_type string to a canonical version Parameters ---------- cov_type : str Returns ------- normalized_cov_type : str """ if cov_type == 'nw-panel': cov_type = 'hac-panel' if cov_type == 'nw-groupsum': cov_...
1ba4d7c750964382525c50ef84e4c262f226e70a
674,440
def headless(request): """ Setup headless flag :param request: :return: flag headless value """ return request.config.getoption("--headless")
28d07a08f7667d321ca1d9fecd407cf131c6e453
674,441
def get_scaling_active_nodes(sg): """ Returns the number of active connections associated with a scaling group Note: this() != get_total_connections """ return sg.get_state()["active_capacity"]
1a5d347e885c73a7c7cb243de9a22652ea616a67
674,442
import json def parse_payload(payload): """Returns a dict of command data""" return json.loads(payload.get('data').decode())
6db1d1681635edd9729a4686cfc4db107307dc8d
674,443
from typing import List def uniform_knot_vector(count: int, order: int, normalize=False) -> List[float]: """ Returns an uniform knot vector for a B-spline of `order` and `count` control points. `order` = degree + 1 Args: count: count of control points order: spline order norm...
5b8369e0164d8a75d39ee014064a0266d4e55e93
674,445
def _textDD(t): """t is a tuple (d, f)""" if 0 <= t[0] <= 360: dd = t[0] if 0.0 <= t[1] < 0.5: dd = 0.0 return '%02d0' % int((dd+5)/10.0) else: return ''
b8abd226ad9c07b0327bdb4d9bb4b694e002a28b
674,446
import random def get_cdf1(latencies): """Get CDF of all latencies""" all_values = [] for k, values in latencies.items(): all_values.extend(values) all_values.sort() number_values = len(all_values) p = 1.0 if number_values > 10000: p = 10000.0 / number_values cdf_array...
c0b77f7280415470dc847a95635bc50d3f851571
674,447
def process_mmdet_results(mmdet_results, cat_id=1): """Process mmdet results, and return a list of bboxes. :param mmdet_results: :param cat_id: category id (default: 1 for human) :return: a list of detected bounding boxes """ if isinstance(mmdet_results, tuple): det_results = mmdet_resu...
ec04ee586276dce6ff9d68439107adde8ac2ba5b
674,448
def get_top_header(table, field_idx): """ Return top header by field header index. :param table: Rendered table (dict) :param field_idx: Field header index (int) :return: dict or None """ tc = 0 for th in table['top_header']: tc += th['colspan'] if tc > field_idx: ...
58e8c21b0cabc31f7a8d0a55b413c2c00c96929b
674,449
import torch def choose_feedback_optimizer(args, net, lr_fb): """ Return the wished optimizer (based on inputs from args). Args: args: cli net: neural network Returns: optimizer """ if args.freeze_fb_weights_output: feedback_params = net.get_feedback_parameter_list()[:...
93a16c878d0599c7463102c230916ebd866c34a6
674,450
def calculate_point(c, kmax): """Python version for calculating on point of the set This is slow and for reference purposes only. Use version from mandel_ext instead. """ z = complex(0,0) count = 0 while count < kmax and abs(z) <= 2: z = z*z + c count += 1 return...
9fabb6924cb67c1ff276d08f7825f8f0395cdb23
674,451
def sanitize_markdown(input_string): """ Sanitize Markdown input so it can be handled by Python. The expectation is that the input is already valid Markdown, so no additional escaping is required. """ input_string = input_string.replace('\r', '') input_string = input_string.rstrip() ret...
4e38f675a1f18d60f3651598f846653b2a66db2c
674,452
def _make_title(differential, metric, el1, el2, pref='', postf=''): """Produce the plot title based on plot parmaters, pref and posf are used for plot specific adjustments; return the title string""" metric_title = 'metric: ' if metric == 'euclid': metric_title += 'L1 Euclidean distance' ...
70ac7de6bbc0e0869e8ffe9e4d7acdbe3e9c206c
674,454
def make_db_entry(run_time_ix_seconds, run_time_ecl2ix_seconds, num_processes): """ Linked to indices above. """ return [run_time_ix_seconds, run_time_ecl2ix_seconds, num_processes]
eb13a7fae8db62e66bf432bb2b60acd27be83c2f
674,455
def incident_related_resource_data_to_xsoar_format(resource_data, incident_id): """ Convert the incident relation from the raw to XSOAR format. :param resource_data: (dict) The related resource raw data. :param incident_id: The incident id. """ properties = resource_data.get('properties', {}) ...
4154540b6a4566775d372713dea6b08295df453a
674,456
import torch def is_gpu_available() -> bool: """Check if GPU is available Returns: bool: True if GPU is available, False otherwise """ return torch.cuda.is_available()
a56cdd29dfb5089cc0fc8c3033ba1f464820778a
674,458
import os def get_out_file(patterns, out_dir): """Given a set of patterns corresponding to a single musical piece and the output directory, get the output file path. Parameters ---------- patterns: list of list of strings (files) Set of all the patterns with the occurrences of a given pie...
0a9db763d7dae1b406932e765a6e31bb78dc91bf
674,459
def find_ingredients_graph_leaves(product): """ Recursive function to search the ingredients graph and find its leaves. Args: product (dict): Dict corresponding to a product or a compound ingredient. Returns: list: List containing the ingredients graph leaves. """ if 'ingredie...
40bebe2a8ec73d492f0312a350a324e9b54a849c
674,460
from io import StringIO import csv def parse_pmsrvinfo_stdout(stdout_str): """ Example result: $ /opt/quest/sbin/pmsrvinfo -l -c qpm-rhel6-64d,/etc/opt/quest/qpm4u/policy/sudoers,7.1.99.7-55-g787b0a37e,1634124307 qpm-rhel6-64c,/etc/opt/quest/qpm4u/policy/sudoers,7.1.99.10-6-g8c6b6955d,1634124308 ...
79183561dd1102474ebbada98a92ddf61bf94150
674,461
def getPathName(path): """Get the name of the final entity in C{path}. @param path: A fully-qualified C{unicode} path. @return: The C{unicode} name of the final element in the path. """ unpackedPath = path.rsplit(u'/', 1) return path if len(unpackedPath) == 1 else unpackedPath[1]
6c5559c1f8b6667f7b592798b3c67bec0f7b0874
674,462
def region_within(coords, dist): """ Determine the number of points that are within a summed Manhattan distance of dist from all the points in coords. :param coords: the coordinates of the points under consideration :param dist: the maximum distance allowed :return: the number of points >>>...
318b17be59ee652f3b7acd6641f1d872fbc66636
674,463
def text_to_rank(dataset, _vocab, desired_vocab_size=15000): """Encode words to ids. Args: dataset: the text from load_data _vocab: a _ordered_ dictionary of vocab words and counts from get_vocab desired_vocab_size: the desired vocabulary size. words no longer in vocab become unk Returns: ...
603a72f1156a141afa899aeba866ffae343695a9
674,464
def has_duplicates(array): """Write a function called has_duplicates that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.""" copy_array = array[:] copy_array.sort() val = copy_array[0] for i in range (1, len(array)): ...
6486559361500563b55b82faaa4b37084e9312a3
674,465
import pipes def shell_join(command): """Return a valid shell string from a given command list. >>> shell_join(['echo', 'Hello, World!']) "echo 'Hello, World!'" """ return ' '.join([pipes.quote(x) for x in command])
67252a291c0b03858f41bbbde61ff4cd811895b6
674,466
def iv(): """ The initialization vector to use for encryption or decryption. It is ignored for MODE_ECB and MODE_CTR. """ return chr(0) * 16
f38999b898427f5c6df124acd727744652d5db75
674,467
def gen_fasta2phy_cmd(fasta_file, phylip_file): """ Returns a "fasta2phy" command <list> Input: fasta_file <str> -- path to fasta file phylip_file <str> -- path to output phylip file """ return ['fasta2phy', '-i', fasta_file, '-o', phylip_file]
90136ca5c60a9ca6990f7e66eae2bfe452310c86
674,468
import torch def group_points_torch(feature, index): """built-in operators""" b, c, n1 = feature.size() _, n2, k = index.size() feature_expand = feature.unsqueeze(2).expand(b, c, n2, n1) index_expand = index.unsqueeze(1).expand(b, c, n2, k) return torch.gather(feature_expand, 3, index_expand)
019616ac64f930fa43cb385d71a9b754fedd6ce1
674,469
def on_off(status): """ :param status: :return: """ return 'Off' if status else 'On'
65e3b3eebcb7ddb81513fe2ea9b38e804f14a2ea
674,470
def get_nested_default(d, path, delimiter="/", default=None): """ Address nested dicts via combined path """ def item_by_tag(d, tags): # print(">>>>>>>>>>>>>> running nested", d, tags) t = tags[-1] try: child = d[t] except: return default i...
1d7b605b7311554885b143c0a3aaaf25f2701404
674,472
def _MakePreservedStateIPAddress(messages, ip_address_literal=None, ip_address_url=None): """Construct a preserved state IP message.""" if ip_address_literal is None and ip_address_url is None: raise ValueError( """ For a stateful...
dd6744a27040ae67c63dbe16dcd35d71c499a45f
674,474
import re def strip_multi_value_operators(string): """The Search API will parse a query like `PYTHON OR` as an incomplete multi-value query, and raise an error as it expects a second argument in this query language format. To avoid this we strip the `AND` / `OR` operators tokens from the end of query ...
582c8ba2da345bdb7e9eb5b092fdbb1b5e5f656e
674,475
def append_no_duplicate(config, path, base, nxt): """ a list strategy to append only the elements not yet in the list.""" for e in nxt: if e not in base: base.append(e) return base
b0d455d0104fb129cdda5b46788c8b62e5d3708c
674,477
def map_tile_to_vpr_coord(conn, tile): """ Converts prjxray tile name into VPR tile coordinates. It is assumed that this tile should only have one mapped tile. """ c = conn.cursor() c.execute("SELECT pkey FROM phy_tile WHERE name = ?;", (tile, )) phy_tile_pkey = c.fetchone()[0] c.execute(...
07b186dbfd55671832a6f02bf25665b380c44b8a
674,479
def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports): """return lines with leading/trailing whitespace and any ignored code features removed """ strippedlines = [] docstring = None for line in lines: line = line.strip() if ignore_docstrings: ...
e1bd5378dd2b2fe800d8c0aeb489e8aeac044e49
674,481
def get_nodes(database): """Get all connected nodes as a list of objects with node_id and node_label as elements""" results = list(database["nodes"].find()) nodes = [] for node in results: nodes.append({"id": node["_id"], "description": node["label"]}) return nodes
5033e2500921e4f40d8f0c35d9394b1b06998895
674,483
def count_scores(scores): """ 分段计数 :param scores: scores列表 :return: 分段计数结果列表 """ nums=[0]*10 params =[ (0,10,0), (10,20,1), (20,30,2), (30, 40, 3), (40, 50, 4), (50, 60, 5), (60, 70, 6), (70, 80, 7), (80, 90, 8), ...
d692321dd6a647ff5d238b84dd81e1226310a38a
674,484
import re def extract_code(text): """ Extracts the python code from the message Return value: (success, code) success: True if the code was found, False otherwise code: the code if success is True, None otherwise """ regex = r"(?s)```(python)?(\n)?(.*?)```" match = re.search(rege...
a912c90973f1d5ebbc356f4a9310a45757928d63
674,485
from unittest.mock import Mock def get_discovered_bridge(bridge_id="aabbccddeeff", host="1.2.3.4", supports_v2=False): """Return a mocked Discovered Bridge.""" return Mock(host=host, id=bridge_id, supports_v2=supports_v2)
588393281cef9289928936b9859d7bddfa660e8c
674,486
import argparse def number_of_colors(value): """Function for parsing number of colors argument. Parameters: value: String that contains an integer Raises: argparse.ArgumentTypeError if value is not integer or out of valid range. Returns: Integer value of v...
d22191ac379201e2ac18729cb35bb08b2dffe401
674,487
def host_get_id(host): """ Retrieve the host id """ return host['id']
73096a0ab4336a17b5bfe37b8807e0671a8ad075
674,488
def get_ue_sla(ue_throughput, ue_required_bandwidth): """ Function to calculate UE's SLA """ return int(ue_throughput >= ue_required_bandwidth)
83b6557324bc9f1b7ed7a47b952e80bb72ffdab3
674,489
import sys import os def NP_FindActualWingHome(winghome): """ Find the actual directory to use for winghome. Needed on OS X where the .app directory is the preferred dir to use for WINGHOME and .app/Contents/MacOS is accepted for backward compatibility. """ if sys.platform != 'darwin': return winghome...
7613ce2750f43d39ab4c8558d4a40121eeb4e819
674,491
import struct def int_array_arguments(specifier='I', *integers): """ Convenience function that collapses an array of integers into a libgreat command payload. Args: specifier -- A single letter specifying the way the integer is to be encoded. Should be one of the format l...
edc2223372bdd1dd3ef21506f0198806e3d47d42
674,492
def rename_cols_df(df): """Take a dataframe with various signals (e.g. current_main, current_sub, etc.) and re-lable the columns to standard names """ # Dict of columns names to standard names col_name_change = { "Current_MainSpindle": "current_main", "Current_SubSpindle": "cur...
9e2030835ea1a269841db1f8b1cd77a45bc40090
674,493
from typing import Dict def flatten(dictionary) -> Dict: """ This function makes dictionary flattening by following rule: example_dict = { "test1": "string here", "test2": "another string", "test3": { "test4": 25, ...
30a6067b23442e0987d52abfaa901b99b06f66e5
674,494
def is_nds_service(network_data_source): """Determine if the network data source points to a service. Args: network_data_source (network data source): Network data source to check. Returns: bool: True if the network data source is a service URL. False otherwise. """ return bool(net...
eb078fa482fc02ce504b0718a5721294a67cdbcd
674,495
def _calculate_MOM6_cell_grid_area(mom6_grid): """Compute the area for the MOM6 cells (not the sub-cells of the supergrid).""" # Combine areas of smaller supergrid cells into areas of cell-grid cells a00 = mom6_grid['supergrid']['area'][0::2,0::2] a01 = mom6_grid['supergrid']['area'][0::2,1::2] ...
cab726eecf926233cb1eb5d8b6b3826ad71db756
674,496
import json def filter_as_json(data, filter): """ Takes any string and interprets it as nested json encoded objects which will be filtered by the filter array. The function will return a string with the filtered content :param data: :type data: :param filter: :type filter: :return: ...
4fa1c818066ed2675620d4cd5722c58ff4629fc7
674,497
def dataframe_fill_none(df, val=""): """ dataframe填充空值的值 """ return df.fillna(val)
4411dcac34d4c9575b3c75fc9c41fa0f9086d7d7
674,501
import pickle def checkPickle(obj, verbose=0): """ Check whether an object can be pickled Args: obj (object): object to be checked Returns: c (bool): True of the object can be pickled """ try: _ = pickle.dumps(obj) except Exception as ex: if verbose: ...
5272b4769ac511a534029efa7ed0bad69d62e047
674,502
def insert_index(array): """ add first column to 2D array with index :param array: array to which we want to add index :return: array with indexes in in first column """ for i in range(len(array)): array[i].insert(0, i) return array
597ce73ffff5d3e061ce3db3115bb90a896dfdbf
674,503
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter def get_parser(): """Get parser object for create_random_image.py.""" parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-f", "--file", ...
60e0319c44b37f03147d6b55b36433269caad73c
674,504
def opacity(token): """Validation for the ``opacity`` property.""" if token.type == 'number': return min(1, max(0, token.value))
04099d1d919ff59f9f2d4b8d9a228cbf1d03e3c9
674,505
def gradient_color(min_val, max_val, val, color_palette): """ Computes intermediate RGB color of a value in the range of min_val to max_val (inclusive) based on a color_palette representing the range. """ max_index = len(color_palette)-1 delta = max_val - min_val if delta == 0: # del...
ea6a9366d2a245b09bd724b2cb98673f2e516f46
674,506
def empty(): """Chain where the policy is empty""" return []
b6b98836dce24581ed6fc933598a02a53561ca02
674,508
def get_start_type(start_types): """Get the Start_Type section of the input file Parameters ---------- start_types : list list of start_type with one for each box """ inp_data = """ # Start_Type""" for start_type in start_types: inp_data += """ {start_type}""".format( ...
118bf3c61f60b80277166fcd6b1eddd4860944f2
674,509
def get_default_alignment_parameters(adjustspec): """ Helper method to extract default alignment parameters as passed in spec and return values in a list. for e.g if the params is passed as "key=value key2=value2", then the returned list will be: ["key=value", "key2=value2"] """ default_al...
79ab15863ef12269c3873f41020d5f6d6a15d745
674,510
def solution(A): # O(N/2) """ Write a function to reverse a list without affecting special characters and without using the built-in function. >>> solution(['a', ',', 'b', '$', 'c']) ['c', ',', 'b', '$', 'a'] >>> solution(['A', 'b', ',', 'c', '...
b43af45288f8d05031ba5c2b51edeb5610de20d5
674,511
def goldstein_price(x): """ Goldstein-Price function (2-D). Global Optimum: 3.0 at (0.0, -1.0). Parameters ---------- x : array 2 x-values. `len(x)=2`. `x[i]` bound to [-2, 2] for i=1 and 2. Returns ------- float Value of Goldstein-Price function. """ ...
b19f4a5e884a0f9520ced7f698a5996b2188857e
674,512
def get_titles(_stories): """ function extract titles from received stories :param _stories: list of stories including story title, link, unique id, published time :return: list of titles """ # Get the stories titles titles = [] for story in _stories: titles.append(story['title']...
280e9803ab87ef76fea4b778c638a5bde6906ade
674,514
def get_gramopts(): """Find all Grammar and token inflection options from the NLG library. Primarily used for creating the select box in the template settings dialog.""" funcs = {} module = globals().copy() for attrname in module: obj = module[attrname] if obj and getattr(obj, 'gramo...
6e43edba4bba1a8261019d4806683b2fbc92c88a
674,515
import numpy def get_vector_magnitude(a): """ Returns magnitute of a specified vector (numpy array) """ return numpy.linalg.norm(a)
c78c05b8c17a6f3f999edf551c9a1c3c92073ae4
674,516
def rgbToHex(rgb: tuple[int, int, int]) -> str: """ convert rgb tuple to hex """ return "#{0:02x}{1:02x}{2:02x}".format(rgb[0], rgb[1], rgb[2])
3a2c69c98852e449c0e0fff9b0e1483c93e1edfe
674,517
def make_sleep_profile_colnames(df): """ Create list of ordered column names for dataframe to be created from sleep_profile dictionary """ colnames = ['Time'] for i in range(11,16): colnames.append(df.columns[i] + ' MR Sum') colnames.append(df.columns[i] + ' Avg Sleep') ...
c7588a72cfd86f7c57aff6b85c18a426d7d404f5
674,518
def nice_column_names(df): """Convenience function to convert standard names from BigQuery to nice names for plotting""" cols = [ ('Open Access (%)', 'percent_OA'), ('Open Access (%)', 'percent_oa'), ('Open Access (%)', 'percent_total_oa'), ('Total Green OA (%)', 'percent_green'...
ebbeae9b4c6e18b851a181a1748a184dc5fa12b3
674,520
import re def isCarryOrBorrow (exp): """ If there is carry or borrow in tens, return the result of expression; else return 0. Applicable only to addition and subtraction """ v = re.sub('(\d*)(\d)', r'\2', exp) return eval(exp) if eval(v) >= 10 or eval(v) < 0 else 0
e3ad083f94dde2e63300a9519c10c4364f61007d
674,521
def calculate_FCF(r, T): """ Calculate FCF from given information :param r: Is the rate of inflation :param T: Is the time in years :return: No units cost factor """ r = r / 100 den = r * ((1 + r) ** T) num = ((1 + r) ** T) - 1 return den / num
47636ac93242a6ed31ffd1c03e37c88d5747f3d7
674,524
import sqlite3 def write_sqlite_file(plants_dict, filename, return_connection=False): """ Write database into sqlite format from nested dict. Parameters ---------- plants_dict : dict Has the structure inherited from <read_csv_file_to_dict>. filename : str Output filepath; should not exist before function c...
32ede716ae4666cab603c9df857054fef2b87ad1
674,525
import os def getenv(variable, default): """ Get an environment variable value, or use the default provided """ return os.environ.get(variable) or default
a05aa8573cdafe50a87d20bf7893f888938f29b5
674,527
def get_module_by_name(top, name): """Search in top["module"] by name """ module = None for m in top["module"]: if m["name"] == name: module = m break return module
67d5fcd5fbc7dc334f2c3f2867f39843363297df
674,528
def fort_range(*args): """Specify a range Fortran style. For instance, fort_range(1,3) equals range(1,4). """ if len(args) == 2: return range(args[0], args[1]+1) elif len(args) == 3: return range(args[0], args[1]+1, args[2]) else: raise IndexError
9eefea326df71d16610507781f0bcab5a375ff27
674,529
from typing import Counter def determine_sentence_speaker(chunk): """ Validate for a chunk of the transcript (e.g. sentence) that there is one speaker. If not, take a majority vote to decide the speaker """ speaker_ids = [ word[3] for word in chunk ] if len(set(speaker_ids)) != 1: prin...
2e2cae81f7f76d3993b7cd64f67be58716010ccd
674,530
def cursorBoxHit(mouse_x, mouse_y, x1, x2, y1, y2, tab): """Description. More... """ if (mouse_x >= x1) and (mouse_x <= x2) and (mouse_y >= y1) and (mouse_y <= y2) and tab: return True else: return False
61a727ab0f81f7acd5adc8de0d359066a6561c6d
674,532
import socket def get_pc_name(): """ return the PC name (host / machine name) """ try: pcname = socket.gethostname() except Exception: pcname = 'computer' return pcname
2c87f5a855f0d718e5e3a8720b3f2b860a43d494
674,535
import random def random_liste(count): """ Returning a list containing 'count' no. of elements with random values between 0 and 100 (both inclusive) """ #Return a list of len 'count', with random numbers from 0..100 return [random.randint(0, 100) for _ in range(count)]
0514f990644549227313eb45ac2afb8cf732275a
674,536
def module_collapse(z): """ Sets the module to 1. Returns z / |z| = e^(i phi). """ return z / (z.abs() + 1e-6)
15ea76423dce8a7b99ec26a37c31130ff182f588
674,537
import ntpath import os def is_root_dir_writable(path, is_dir=False): """ Check the permission of an exe file """ if is_dir: dirname = path else: dirname = ntpath.dirname(path) new_path = os.path.join(dirname, "a.txt") try: f = open(new_path, "w") f.close(...
5ffc4549edde9b6b285d7bcc6e2d6cbe562b4acc
674,538
def sorted_json_string(json_thing): """Produce a string that is unique to a json's contents.""" if isinstance(json_thing, str): return json_thing elif isinstance(json_thing, list): return '[%s]' % (','.join(sorted(sorted_json_string(s) for s in json_t...
5daecc27c06c51a3cd77888e060b16b6074664e5
674,539
def _find_audio_for_turn(uturn, recs): """ Finds the recording that belongs to a given user turn by comparing time spans. Arguments: uturn -- the XML element "userturn" for which the corresponding recording should be found recs -- a list of XML elements "rec" in the whole lo...
0e3b8201236d27147321f2a41f7fb7efbc671037
674,540
def linear(interval, offset=0): """Creates a linear schedule that tracks when ``{offset + n interval | n >= 0}``. Args: interval (int): The regular tracking interval. offset (int, optional): Offset of tracking. Defaults to 0. Returns: callable: Function that given the global_step r...
0bae3b893312f112edafba15df566d8776efcb2f
674,541
import os def construct_filename(cfg, setting, extension, yr): """Construct a full path with file name and extension to an output file. :param cfg: Configuration object :param setting: str. Either urban, rural, or total :param extension: ...
815ff34f3081de73ef3433c33b05186ca34dffec
674,542
import pickle def read_predictions_and_obs(pickle_file_name): """Reads predicted and observed fronts from Pickle file. :param pickle_file_name: Path to input file. :return: predicted_region_table: See doc for `write_predictions_and_obs`. :return: actual_polyline_table: See doc for `write_predictions_...
9d70e045ab8aae38079ca416b194fe2322087f3b
674,543
def has_children_nodes(data_ref): """ Does this irept have any children. """ has_subs = data_ref["sub"]["_M_impl"]["_M_start"] != data_ref["sub"]["_M_impl"]["_M_finish"] has_named_subs = data_ref["named_sub"]["_M_t"]["_M_impl"]["_M_node_count"] > 0 return has_subs or has_named_subs
52181eca0576f2274679c6893c47c10e394a7dfb
674,544
import numpy import pandas def can_convert_v_to_numeric(x) -> bool: """ check if non-empty vector can convert to numeric :param x: :return: True if can convert to numeric, false otherwise (no string parsing). """ x = numpy.asarray(x) not_bad = numpy.logical_not(pandas.isnull(x)) n_not...
ecf14c9399622f0e57aaa5796f0f49672e41cbfb
674,545
def _is_valid_sub_path(path, parent_paths): """ Check if a sub path is valid given an iterable of parent paths. :param (tuple[str]) path: The path that may be a sub path. :param (list[tuple]) parent_paths: The known parent paths. :return: (bool) Examples: * ('a', 'b', 'c') is a valid ...
f78db91600298d7fd7cfbdc5d54cce1bff201d94
674,546
def get_valid_loss(model, valid_iter, criterion): """ Get the valid loss :param model: RNN classification model :type model: :param valid_iter: valid iterator :type valid_iter: data.BucketIterator :param criterion: loss criterion :type criterion: nn.CrossEntropyLoss :return: valid l...
1e82378ba528a3799058edd2490ec9fb0de16711
674,547
import math def set_decay_rate(decay_type, learning_rate_init, learning_rate_end, num_training): """ Calcualte decay rate for specified decay type Returns: Scalar decay rate """ if decay_type == 'none': return 0 elif decay_type == 'exp': return math.pow((learning_rate_end/learning_rate_init),(1/num_trainin...
c85099d78684629bc0a48e5981d8cec0ce96fbd7
674,548
def _add_base(base, **kwargs): """Return Dockerfile FROM instruction to specify base image. Parameters ---------- base : str Base image. """ return "FROM {}".format(base)
faf523214026cbb5c670dd535b5828e267f5ee4d
674,549
def _parse_param(param): """Work for both numpy and tensor""" p_ = param[:12].reshape(3, -1) p = p_[:, :3] offset = p_[:, -1].reshape(3, 1) alpha_shp = param[12:52].reshape(-1, 1) alpha_exp = param[52:].reshape(-1, 1) return p, offset, alpha_shp, alpha_exp
f4bdcbdb59c9acd7f9d0bf2652955c2f8bfc1670
674,550
import sys def get_architecture(): """ Returns computer architecture: 32 or 64. The guess is based on maxint. """ if sys.maxsize == 2147483647: return 32 elif sys.maxsize == 9223372036854775807: return 64 else: raise RuntimeError("Unknown architecture")
507483fc04deba654c6691215df88972fc75635c
674,551