content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import sys def get_student_from_name(name, users): """given a name, find the slack ID associated with it and return the post string""" student = None for u in users: if name in u.name: if student is None: student = u else: sys.exit(f"Erro...
d36feb79085eaabb3344507dd54ccff7f7ccae6b
669,360
import yaml def get_yaml_overcloud(ip, release, cinder_backend, network_backend, dvr, tls_everywhere, infra_type, ml2_driver=None, ironic_inspector=None, cleaning_network=None, security_group=None, overcloud_templates=None): """Provide a yaml re...
229842e9e09edd93d7aaf30c67d5d6f79e781240
669,361
import six def to_text(s, encoding="utf-8"): """ Converts the bytes to a text type, if not already. :s: the bytes to convert to text :returns: `unicode` on Python2 and `str` on Python3. """ if isinstance(s, six.text_type): return s else: return six.binary_type(s).decode(en...
c06273f73a6b7dde03196e1d0355fa87528ad959
669,362
def filter_cancel_replace_by_oid(cr, oid): """ :param cr: :type cr: :class:`tests.testapp.testapp.trading.models.CancelReplace` :param oid: :return: """ return cr.xr_tid == oid
58956278e71121b090109edde0a517c17a9df2d7
669,363
def find_between( s, first, last ): """Find a string between two characters.""" try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return ""
737941dd48a31c048ce3fe0583e13c893febb5ed
669,364
import os def saveArticleDisk(title, article_text, paper, name, folder=None, path=None): """ Save some articles to disk in a txt form """ # Set the path for the file base_path = os.path.abspath('') base_path = os.path.join(base_path, "downloaded_articles") if path is not None: fil...
0538a81eb816e5164086a19458d9164dfc80e35d
669,365
def get_name_value(line): """Get benchmark name and result from a text line""" name = line.split()[1] value = int(line.split()[4]) return name,value
7bc1a29a761c25963144fd1b94ca7e7b81f288b8
669,366
import os def fullsplit(path, ignore_empty=True): """ Split path into list. If ``ignore_empty==True``, omit empty folder names. """ names=[] while True: path,name=os.path.split(path) if name!="" or not ignore_empty: names.append(name) if path=="" or pat...
d09d6d279339926af173ed629ad503c79b13cb27
669,368
def is_sunday(date): """Is the specified date (a datetime.date object) a Sunday?""" return date.weekday() == 6
167ec36a372cf64646b4dabae46867515f71337d
669,369
def query_registry(model, registry): """Performs a lookup on a content type registry. Args: model: a Django model class registry: a python dictionary like ``` { "my_app_label": True, "my_other_model": { "my_model": True,...
7c410c5baa8d20792ee7f49423da000fee34d001
669,370
def addKey(target, fieldname): """Adds the key of the specified field. """ result = target.copy() result['%s_key' % fieldname] = target[fieldname].key().name() return result
d6b4dc541cffc7d7970e54dd9b9c5d7ec79ad164
669,371
import numpy def _downsize_predictor_images( predictor_matrix, center_row, center_column, num_rows_in_half_window, num_columns_in_half_window): """Downsizes the original images into smaller images ("windows"). This procedure is done independently for each spatial grid (i.e., each example,...
d55abc6245fdc617982a5246de73ce5cf25b7cb1
669,372
import json def load_json_from_string(_string: str) -> dict: """ Function: load_json_from__string Summary: loads json from _string Examples: InsertHere Attributes: @param (_string:str):InsertHere Returns: InsertHere """ if not isinstance(_string, str): try: ...
2bc82adafc4254efe91b85cc49d30e92a29b6695
669,373
def id_for_src(value): """generate a test id for src""" return f"src->{value.comment}"
fe1fc5aade0fd7885c71618341f2635bb9f6f3ae
669,374
import re def GetWeights(fp): """ Get the regions and weights from a weights file. @return lists of regions and weights """ weight_list = [] weight_regions = [] for line in fp.readlines(): field = re.match('(0\.\d+).*(\d+)', line) # Look for the special case where the fi...
4f0837b364af492a88aba1b6aa654d1e51f70a98
669,375
from datetime import datetime def strtime_to_datetime(timestr): """将字符串格式的时间 (含毫秒) 转为 datetiem 格式 :param timestr: {str}'2016-02-25 20:21:04.242' :return: {datetime}2016-02-25 20:21:04.242000 """ local_datetime = datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f") return local_datetime
0ed27729689b546e4175612d57848b1bc76d9011
669,376
import hashlib def get_md5(payload): """ Generate md5 hash of a payload :param payload: The payload to be hashed. :returns: md5 hash :rtype: str """ return hashlib.md5(payload).hexdigest()
9ec3ba40f2046340391ba355d9d1cc6398002c4d
669,377
def in_to(dims, scale=1): """ dims is a tuple in inches (x, y) `scale` = scale factor, e.g. if scale = 1e-3, 1e-3 * cm/in * in = mm """ s = scale/2.54 if isinstance(dims, tuple): return (dims[0]/s, dims[1]/s) else: return dims/s
4c2dc32c9c2a6d5ecd54dfaa4474ef41eed9e2cf
669,378
import subprocess def count_file_lines(path): """ Run the wc command to count lines in a file, as shown here: https://gist.github.com/zed/0ac760859e614cd03652 """ wc_output = subprocess.check_output(['wc', '-l', path]) return int(wc_output.split()[0])
71be113b5414e2bdff096278727f8a7b0aea5816
669,379
def scores(L): """Get the scores (position * alphabet score) for all words in list.""" scores = [] for key, val in enumerate(L): scores.append(val * (key + 1)) return scores
98327f6ff050b160deff683009750424bf60b35c
669,380
def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col, choice_col, availability_vars, wide_data): """ Checks whether or not each ob...
9398d83e188c317d2289d074851a848488a15ea0
669,382
import torch def image_meshgrid(bounds,resol): """ bounds in 3x2 resol in 3x1 """ # he,wi,de = resol # minw,maxw = bounds[0] # minh,maxh = bounds[1] # mind,maxd = bounds[2] axis = [ ((torch.arange(sz).float())/(sz-1))*(b[1]-b[0])+b[0] \ for sz,b in zip(resol,bounds) ] return torch.stack(torch.mes...
816bc96be18fc38438bf8a35458e4ceb893a5a58
669,383
from typing import Dict def get_service_name(query: str, service_aliases: Dict) -> str: """The service name must always be the first word in the query string.""" if not query: return "" service = query.split()[0] if service in service_aliases: return service_aliases[service] return...
cb3cd77aec24e60f005c87ed7cf7f9b75b0778fa
669,384
import re def parse_path_info(path_info): """ Parse path info formatted like a/c/f where c and f are optional and a leading / accepted. Return tuple (a, c, f). If invalid path_info a is set to None. If c or f are omitted they are set to None. """ mo = re.match(r'^/?(?P<a>\w+)(/(?P<c>\w+)(...
0cb000b1b57c3e0b100b2f1dbea60dab4d6f04ca
669,385
import socket def isTipcAvailable(): """Check if the TIPC module is loaded The TIPC module is not loaded automatically on Ubuntu and probably other Linux distros. """ if not hasattr(socket, "AF_TIPC"): return False try: f = open("/proc/modules") except (FileNotFoundError, ...
3222830fbd0e9a9b66ac51a6b9bafe55c0d34b92
669,386
def do_check(func, files, status): """ Generic do_check helper method Args: func (function): Specific function to call files (list): list of files to run against status (list): list of pre-receive check failures to eventually print to the user Returns: ...
ec642743906a0523a5421237d62b83f0643201e2
669,387
def _feet_to_meters(SI): # type: (bool) -> float """converts m -> ft""" if SI: factor = 0.3048 else: factor = 1. return factor
b4a2830db03ad4ebfb35db5cf96d352dfdec9879
669,388
def checkscheme(arglist, arg): """Returns index of arg in arglist or if not found returns -1. """ return arglist.index(arg) if arg in arglist else -1
1401edebaca7c764c992c6fdf5073795f9cff25d
669,389
def invert_bloblist(bloblist): """ Returns a dictionary on the form md5sum -> [blobinfo, blobinfo, ...] """ result = {} for bi in bloblist: if bi['md5sum'] not in result: result[bi['md5sum']] = [] result[bi['md5sum']].append(bi) return result
d2978c9b2d727e39016966514ca89855f8723745
669,390
def total_number_of_clusters(tree) -> int: """Get the number of leaves in the tree.""" if tree is None: return 1 return sum(total_number_of_clusters(subtree) for subtree in tree.subregions)
0ffffe5dd0a315f76778eed51ba44401994f28ad
669,391
def send_url(ev, url, message_error, message_valid): """if response had status 404 it's valid """ if ev.target.readyState == 4: if ev.target.status == 404: if message_valid: return(True, url, message_valid) else: return(True, url) else: ...
b1a79c34f70dbf721bb3f4b73d69d7d79e76c6cb
669,392
import math def round_to_n(x: float, n_digits: int) -> float: """Round a floating point to n significant digits Args: x (float): Number to round n_digits (int): Number of digits to keep Returns: float: Rounded version of x with n_digits digits """ ...
e7eab22122f741ed6b583fb6e4ce3abb0fa91271
669,393
def __curse_list_flatten(self): """ Flatten a list. Only the type `list` is affected. >>> [1, [2], [[3]], (4, 5)].flatten() [1, 2, 3, (4, 5)] """ def __flatten(x): return __flatten(x[0]) + (__flatten(x[1:]) if len(x) > 1 else []) if type(x) is list else [x] return __flatten(self)
135f75d4a6b1351c5f0b8a8c296bd00fd8737352
669,394
def loword(dword): """ Low order word :param dword: :return: """ return dword & 0x0000ffff
b853428f590f26a82522c86c72b867a965eb1d7e
669,395
import re def find_all_paddle_api_from_code_block(cbstr): """ Find All Paddle Api """ # case 1.1: import paddle.abs # ignore # case 1.2: from paddle.vision.transforms import ToTensor # case 1.3: import paddle.vision.transforms.ToTensor as ToTensor # ignore # case 2: train_dataset = paddl...
3518631e7b76a675ad5a881d05e624b27bd7898d
669,396
from collections import defaultdict def group_position(*args): """ Get group position """ table = defaultdict(int) result = [] for tup in zip(*args): result.append(table[tup]) table[tup] += 1 return result
663e05f5c1af7c13ac0cea36a02448c0d9e978a8
669,397
import time def log_tail(contents=''): """return a string, which can be write to the tail of a log files""" s = '================================================================\n' s += '[time] ' + time.asctime(time.localtime()) + '\n' s += '[program finish succeed!]\n' s += contents s += '=...
f03c68285ea8cf335a7eb8475085501eeb1c1eee
669,398
def disk_update(context, disk_id, values): """Update a disk withe the values dictionary.""" return NotImplemented
40e80598a127d6002451591a322f4d0a96363197
669,399
import socket def __try_op__(op_name, op, retries, *args): """ A helper function to retry an operation that timed out on a socket. After the retries are expired a socket.timeout is raised. Parameters ---------- op_name : str The operations name op : Callable The operation ...
3720f781106138f74a189f0bead4897148b307b5
669,400
def eddy_flux_coarse(unresolved_flux, total_resolved_flux, omega, field): """Compute re-coarsened eddy flux divergence from re-coarsed data """ return unresolved_flux + (total_resolved_flux - omega * field)
2cc978b1b65e3fc9d13b2d05f8193770c1a52b77
669,401
from datetime import datetime def get_current_time(): """ :return current system time from the datetime module in HH:MM:SS format :rtype str """ return datetime.now().strftime("%H:%M:%S")
f971ffed7b250187e57018545d4788143ccc820c
669,403
import time def delay(ticks: int) -> int: """pause the program for an amount of time Will pause for a given number of nanoseconds. This function will use the processor (rather than sleeping) in order to make the delay more accurate than nygame.time.wait(). Parameters ---------- ticks ...
6b060f82e6fdaa9fd5e233b40b96ece2856ab851
669,404
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
4985df3ec7c92081a416c0bedd6d65df482a4b9e
669,405
def name(data): """ Get the assigned name of the entry. """ return data["marker_name"]
55e5d2d4defebf1b391d1f27a03de3fa7d0de331
669,407
import json def dumps_json(value): """ dumps json value to indented string Args: value (dict): raw json data Returns: str: indented json dump string """ return json.dumps(value, indent=2, ensure_ascii=False)
b1c40c3fef82a7c3fde05aaa793c72012e04cd5a
669,408
def fn_example(values): """ function / method with built-in unit test example; this example computes the arithmetic mean of a list of numbers. Args: values: list of integers Returns: integer Examples: >>> print(fn_example([20, 30, 70])) 40.0 """ return sum(values) / len(values)
fc0356a975f25f690ada357f78e0a336b37859c0
669,409
def log_state(state, config, log): """ Log the current state """ log.update(state) return state
f7bf67c518541392f0b01b92b15d1e364b98fb09
669,410
def force_immutable(item): """ Forces mutable items to be immutable """ try: hash(item) return item except Exception: return tuple(item)
27090f804dbe6bdbb4650c63d0d7c86e15d81410
669,411
import math def blackjack_probability(deck, full_deck): """Calculates the odds of hitting blackjack and compares it to full deck odds. This calculation is made with this formula: Probability of a blackjack: (A * T) / C(R, 2), where A = remaining aces, T = remaining tens, C(R, 2) is all combinations of 2 o...
293144a47f416bc2d7e572953ba2c913887b3192
669,412
def GameDone(board, current_icon): """Determine if the game has been won or not, return True or False""" #win = a boolean variable for if the game has been won #Check if previous move caused a win on horizontal line for x in range(len(board)): win = True for y in range(len(board))...
5723c0355e2120dc0d8cb7e1586cfe07ba541bf0
669,413
def stack_super_ensemble(ds, by_lead): """ Stack into super ensemble """ def _stack(ds, sample_dims): for dim in sample_dims: ds = ds.assign_coords({dim: range(len(ds[dim]))}) ds_stack = ds.stack(sample=sample_dims).dropna('sample').drop('lead_time') return ds_stack.assign_co...
7b2664e38f43fd9d5b3909a34f229d9bed53a6e9
669,414
def data2int(data): """ To compare data as an integer, this helps. """ return int(data.encode('hex'), 16)
31ae499d0937883a5f1c7f667bdfac76746caf15
669,415
from typing import Iterable from typing import Hashable from typing import List def _unique_order_preserving(iterable: Iterable[Hashable]) -> List[Hashable]: """Remove items from an iterable while preserving the order.""" seen = set() return [i for i in iterable if i not in seen and not seen.add(i)]
f5b3384e2c8812341b246fc05972bc9c1b13f255
669,416
def _tests_in_suite(suite_name, tests): """Check if the suite includes tests. :param suite_name: Name of the suite to be checked. :param tests: Set of tests :type suite_name: str :type tests: pandas.Series :returns: True if the suite includes tests. :rtype: bool """ for key in test...
53d3e1a1cc3e12d698f8a2a5eb4e246ce4e53ea9
669,417
def get_service_plan_guid(cf_client, service_guid, plan_name): """ get service plan guid """ for plan in cf_client.service_plans: # pprint(service) if plan['entity']['service_guid'] == service_guid: if plan['entity']['name'] == plan_name: return plan['metadata...
469541346c17a01c781d5d1fb0a8f5c18842cd18
669,418
import sys import contextlib def print_context(console, opts): """ Returns a printing context Args: console: The console to print paged (bool): Wheter to page the output style (bool): Whether to force the use of styled pager """ if opts.get("paged"): # Internally p...
3e9d7a32d7c724d350c59d4b5b64a203d4f603f9
669,419
def _make_precision_recall_eval(scores, na_probs, num_true_pos, qid_to_has_ans): """Make evaluation dictionary containing average recision recall.""" qid_list = sorted(na_probs, key=lambda k: na_probs[k]) true_pos = 0.0 cur_p = 1.0 cur_r = 0.0 precisions = [1.0] recalls = [0.0] avg_prec = 0.0 for i, q...
ec3224bd2363bd4d77b857959c656364748ff071
669,420
import itertools def _create_turnout_scenarios(scenario_dict): """ Convert the dictionary to a list of 24 integers for each appliance being put off the run. Parameters: List of scenarios (dict): The dictionary of the scenario to run Returns: List of 24 integers for each hour of the day for ...
01cccdc6c0978c40ad91d5536005a39d83804b72
669,421
import re def fixFlagsQuoting(text): """Replaces e.g. /DFOO with /D "FOO" and /DFOO=X with /D FOO=X.""" return re.sub(r'\/([DIid]) ([^ \"=]+)([ $])', r'/\1 "\2"\3', re.sub(r'\/([DIid]) ([^ \"=]+)=([^ \"]*)([ $])', r'/\1 \2=\3\4', text))
ab60d5cf539d7a3753e457838989ab3be520d6b3
669,422
from typing import Optional from typing import Dict def create_field_list_query(field_type: Optional[str] = None, field_documentation: bool = True) -> Dict: """Create a FieldListRequest dictionary request. Args: field_type: One of {'All', 'Static', 'RealTime'} field_documentation: Return fiel...
fc1ebcc4f7ba5af77e0dab0adf2719396b25fbac
669,423
def parse_videos(video): """ Parse data from the video JSON structure Parameters ---------- video : JSON object of strings The video search result requested from YouTube API v3 Returns ---------- video_dict : dictionary of strings The dictionary contianing video titl...
b9b2a243f7e1740bc449e7a37a6efa6fe76f7c02
669,424
import os def script_name_to_module(file_name: str) -> str: """ Converts python file name to importable module name """ if file_name[-3:] != '.py': raise ValueError('Script name "%s" should end in ".py' % file_name) parts = file_name[:-3].split(os.path.sep) return '.'.join(parts)
80589629767f368c9c23a2da1a5eacf71e79213e
669,426
import yaml def read_yaml(config_name, config_path): """ 读取yaml格式的配置文件 :param config_name: <str>需要读取的具体某项配置内容 :param config_path: <str>配置文件的路径 :return : 具体配置项对应的值 """ if config_path and config_name: with open(config_path, "r") as f: conf = yaml.safe_load(f.read()) ...
96accafdedfbb1d509e077000b254ddbc538a428
669,427
def create_log_line(log_msg): """ Create a line for the log files from a LogMessage """ # determine log line contents tstamp = round(log_msg.tstamp.timestamp()) direction = "IN" sender = log_msg.sender if log_msg.own: direction = "OUT" sender = "you" msg = log_msg.ms...
3d88c147d14d3cc485cb19f54147c5fcf0df5c1f
669,428
def upload_pipeline(s3, pipeline): """ Responsible for uploading the object (global.yml) to S3 and returning the URL that can be referenced in the CloudFormation create_stack call. """ s3_object_path = s3.put_object( "pipelines/{0}/global.yml".format( pipeline.name), "{0}/{1}...
d1f9e767277bd3d17d72137d403645a52dded023
669,429
def getHKLv2(inp_str): """ Return a list of hkls. Functional Programming style.""" headerEnd_markup = "!END_OF_HEADER\n" dataEnd_markup = "!END_OF_DATA\n" id_endHead = inp_str.find(headerEnd_markup)+len(headerEnd_markup) hklOnly = lambda s: map(int, s.split()[:3]) lines = inp_str[id_endHead:-len...
7b64493005bdfd724899a06b9fa24e413ef35074
669,430
def is_valid_v6addr(addr): """check if ipv6 addr is valid""" if addr.find(':') != -1: addr_list = addr.split(':') if len(addr_list) > 6: return False if addr_list[1] == "": return False return True return False
100e2d98a766acf94c599d436362aa5f588e406d
669,431
import math def func(x): """ Исследуемая функция. :param x: :return: """ y = math.asin((x - 1) ** 2) return y
65cb943cbc2c745f7456de991f9a96fd16548454
669,432
import torch def topk(cdist, pids, k): """Calculates the top-k accuracy. Args: k: k smallest value """ with torch.no_grad(): batch_size = cdist.size()[0] if k >= batch_size: k = batch_size - 1 index = torch.topk(cdist, k+1, largest=False, dim=1)[1] #topk...
8ed432dd2e105c0cafb37e9d109d28b9e44a101b
669,433
def rgb_to_hex(rgb): """Convert an RGB tuple into a 6-digit hexadecimal RGB number. Args: rgb (Tuple[ :obj:`int` ]): Tuple to convert to hex. Returns: :obj:`int`: RGB hex. """ if not all(isinstance(n, int) and 0 <= n < 256 for n in rgb) or len(rgb) != 3: raise ValueError(f"...
c8e56b7877f94922d94c2f7545ce4e3b8459dcfa
669,434
def intersection(A, B): """ Returns an intersection of two lists. Keyword arguments: A -- the first list B -- the second list """ ia = 0 ib = 0 output = [] while ia < len(A) and ib < len(B): a = A[ia] b = B[ib] if a == b: # Don't add duplic...
9bcef9ecb23f27c4e4d69d8cbac6fec7869e3c4d
669,435
def split_lattice_and_source(source): """ for flat source: ssss xxx, 123 ssss xxxxx,132131 return: ["sss", "sss"] , [ "xxx,123", "xxxxx, 132131" ] """ res, lattice = [], [] for i in range(0, len(source), 2): res.append(source[i]) lattic...
525c67c1ba0979c0aa671ebcc9ed704e7a5bc6f1
669,436
def _filter(regex, expr): """ Build an `filter(<regex>, <expr>)` type query expression. `regex` is a regex matched on the rule names from `expr` `expr` is a query expression of any supported type. """ return "filter('{}', {})".format(regex, expr)
719d47de4670eb6ddc9b8238d5a903a7a89f5649
669,437
def getAuthorAndName(ctx): """ Takes the context variable from the calling function and returns the author object and the author display name, formatted. @param ctx the context passed to the calling function @return author the author object @return authorName the display name of the author "...
ba9c7674b21d42a95df0f01ab6ccbcaca276c777
669,438
def calculate_text_size(text, font_size): """Returns width and height of specified text at specified font size :param text: Text for which size is to be calculated :type text: str :param font_size: Font size :type: font_size: int """ if type(text) is str: text = [text] BASE_FONT...
2921276a83f32077d455338e10add976da858b1e
669,439
def format_percentage(number): """ Formats a number into a percentage string :param number: a number assumed to be between 0 and 1 :return: str """ return '{}%'.format(round(number * 100))
5736b141b316d2de63804ddb248a45d9e4748ba4
669,440
def codegen_link(func, env): """ Link the llvm function into """ lfunc = env["flypy.state.llvm_func"] return lfunc, env #global_mod.link_in(lfunc.module, preserve=True) #new_lfunc = global_mod.get_function_named(lfunc.name) # #env["flypy.state.llvm_func"] = new_lfunc #return new...
0426b7e993cb8241e5cc9b5b00b25efae68ad622
669,441
def is_numeric(s): """ It's a useful function for checking if a data is a numeric. This function could identify any kinds of numeric: e.g. '0.1', '10', '-2.', 2.5, etc Parameters ---------- s : int, float or string. The input could be any kind of single value except the scalable ...
9b5bbc267dc5e4dad97df5446743d6c4c7e49a8c
669,442
def rgb2html(rgb, alpha=None): """ method will convert given rgb tuple to html representation rgb(R, G, B) if alpha is set, it will be included rgb(R, G, B, ) """ if alpha is not None: return 'rgba({0:d}, {1:d}, {2:d}, {3:s})'.format( *rgb, alpha if isinstance...
eac0c7a115fec447a9b2bfc893d5fb7763f3493a
669,443
def acs(concept, paragraph, model, min_length, stop_words=[]): """ :param concept: str, the concept word for the concept :param paragraph: list, a list of the tokens in the paragraph :param model: gensim.models.Word2Vec, model containing word vectors :return: float, the distance between the concept ...
4af462fb970fed1b7e8f42576e5cceac6b912ad6
669,444
import re def get_tab_info(root): """ Returns the prefix, separator, and max index for a set of jQueryUI tabs """ hrefs = [y.attrib['href'] for y in [x.find('a') for x in root.find('ul').findall('li')] ] splits = [r.groups() for r in [re.match('#(.*)([-_...
375f8cfc2b6f3467ae0d958c20daa8978a558fd0
669,445
def get_variable_interp_method_dict(): """Interpolation method dictionary for each variable.""" d = {'dynamic_variables': 'conservative', 'topography': 'conservative', 'land_sea_mask': 'conservative', 'soil_type': 'largest_area_fraction'} return d
9e5fb4f792125f66efff423cbc1d6472947d3400
669,447
def ramp_harmonic(phi, A): """ Weighted harmonic mean according to phi. """ return (A[0]**(-1)*0.5*(1.+phi) + A[1]**(-1)*0.5*(1.-phi))**(-1)
ae6fa50d044a5b4ede7fd848660f92823a710ee5
669,448
def InternalCycles(model, allowedreacs=None, reacsbounds={}, tol=1e-10): """ pre: reacsbounds={reac:(lo,hi)}, all external reactions blocked post: model with reactions in internal cycles (for doing elementary modes) """ state = model.GetState() model.SetConstraints(reacsbounds) if allowedreacs ==...
8f4342d61915beac3ae5a0f85187080fb53139b1
669,449
import base64 def base64_decrypt(meg_data): """ meg_data: bytes return: str """ meg = base64.b64decode(meg_data) return meg.decode("utf-8")
e9b4a7ac5c63f8b0ef16b71dc96790d5f4d16ffb
669,450
import json def read_json_file(path): """ Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list. """ with open(path, 'r', encoding='utf-8') as f: data = json.load(f) re...
e197c67811fe33c71ee92ce3e7d6a1dab0940f75
669,451
def omp_get_schedule(): """ The omp_get_schedule routine returns the schedule that is applied when the runtime schedule is used. Results ------- kind : int chunk_size : int """ return 1,0
213163d63fd8a81a7bfee4da9065d335207d6cb4
669,452
def stitch_format(with_sub_inventions): """ takes an invention in dreamcoder format that does NOT have nested inventions (ie they've already been rewritten from `#(...)` to `fn_i`) and rewrites it into stitch format. Specifically: - remove any `(lambda (lambda (...)))` wrapping the whole invention, trea...
f2d923d9c84d216f278cb3157b33188986308cc5
669,453
import torch def compute_distance3D(train_embs, val_embs, dist_fn='eucl', log_path=None, step=None): """All the args are same as below, but dist is computed using euclidean norm for each val with every train embs.""" major_dist = list() for i, v in enumerate(val_embs): curr_v = v ...
434c7369ad0f426f64f6a43600fa0ff11ba98a79
669,454
def get_block_device_mapping(image): """ Retrieves block device mapping from AMI """ bdm_dict = dict() if image is not None and hasattr(image, 'block_device_mapping'): bdm = getattr(image, 'block_device_mapping') for device_name in bdm.keys(): bdm_dict[device_name] = { ...
8b29871bf10c3c7e705f0228c1698c1d669cf1c5
669,455
def valid_arguments(opts, args): """ checks if the supplied arguments are adequate """ if (opts.input_fp == None and opts.output_dir ==None ) or\ opts.output_dir == None: return True else: return False
2edf681c78eb77c447192c1ae9b17b3e0c4920f4
669,456
def start_emulator(emulator, params): """ Creates and starts the selected emulator with the parameters """ i = emulator("localhost", params[0], params[1]) i.start() return i
b457a3565f046af732cc611532b8ffa4d2bb147a
669,457
def select_elements(dom,names): """ returns a list of elements accoding to a list of hierarchical tag names, i.e. <names[0]><names[1]><names[2]>... """ elements = [ dom ] for name in names: child_elements = [] for element in elements: all_child_elements = element.childNodes ...
16721a1352861f4c6d738d92c348d209846bed33
669,458
def split_with_square_brackets(input_str): """ Split a string using "," as delimiter while maintaining continuity within "[" and "]" Args: input_str: Input string Returns: substrings: List of substrings """ substrings = [] bracket_level = 0 current_substr = [] for ne...
0bdf0849019401f7bd0d702045ee4ad3fc5750c8
669,460
import string def splitNum(name, digits=string.digits): """ Split a string that ends with a number between the 'body' of the string and its numeric suffix. Both parts are returned as strings. :param name: The string to split. :keyword digits: The set of numeric characters. Default...
dd96edc9135623206735771e23c5afc80f4ceaea
669,461
from typing import Tuple def get_nb_tile_from_img(img_shape: Tuple[int, int], tile_size: int) -> int: """ return the number of tile inside an image currently the number of tile are computed without overlaping and by rounding so union of all tiles are smaller than image. Tile are square. Para...
363503a2285107d6f65c48acd26ff66c63af528f
669,462
def cambridge_get_perms(arr): """ cut down each ballot to a (partial) permutation of the candidates rules according to: truncate as soon as two undervotes or an overvote remove occurrences of a candidate after the first appearance remove undervotes results are placed in a dictionary with ke...
34566cb68a8f95b459294b09c930523f917f2020
669,463
def init_meta(): """Creates a general meta dictionary Returns ------- meta : dict """ meta = dict() meta['JNAME'] = 'unknown' meta['ALTNAME'] = 'unknown' meta['RA'] = 0. meta['DEC'] = 0. meta['zem'] = 0. meta['Instrument'] = 'unknown' meta['Creator'] = 'unknown' ...
8efa94da6c3a62a72e307de62a75708dc8cbf76d
669,464
from numpy import nan def info_from_header(header): """Returns mb, ms, sequence extracted from header in logfile.""" # If present in header information, extract mb, ms, and sequence mb = nan ms = nan sequence = '' header = str(header).replace(' ','') # remove spaces before splitting ...
9ee4ff53dd5e5444371e88afaab7e5a8e6b71942
669,465
def get_negation(token): """Get the negation of some token""" sign = True for child in token.children: if child.dep_ == "neg": sign = False break return sign
2f7bda6b753d4345319fd2739f7663c94928e609
669,467