content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def overlay(*fields: SampledField or Tensor) -> Tensor: """ Specify that multiple fields should be drawn on top of one another in the same figure. The fields will be plotted in the order they are given, i.e. the last field on top. ```python vis.plot(vis.overlay(heatmap, points, veloci...
629eb69c15d814384b70bac2ac78cebdd93ef20d
27,520
def load_identifier(value): """load identifier""" if value == "y": return True return False
0292439c8eeb3788a6b517bb7b340df2c0435b4d
27,521
def IKinSpaceConstrained(screw_list, ee_home, ee_goal, theta_list, position_tolerance, rotation_tolerance, joint_mins, joint_maxs, max_iterations): """ Calculates IK to a certain goal within joint rotation constraints Args: screw_list: screw list ee_home: home end effector position ...
7c59a8eaa7cff24f6c5359b100e006bbc58e8c00
27,522
def add_hidden_range(*args): """ add_hidden_range(ea1, ea2, description, header, footer, color) -> bool Mark a range of addresses as hidden. The range will be created in the invisible state with the default color @param ea1: linear address of start of the address range (C++: ea_t) @param ea2: linear ad...
8f844c14b348bdcf58abe799cb8ed0c91d00aeef
27,523
import json def _fetch_certs(request, certs_url): """Fetches certificates. Google-style cerificate endpoints return JSON in the format of ``{'key id': 'x509 certificate'}``. Args: request (google.auth.transport.Request): The object used to make HTTP requests. certs_url (s...
3141c78d604bbed10236b5ed11cfc2c06a756ef2
27,524
def get_mock_personalization_dict(): """Get a dict of personalization mock.""" mock_pers = dict() mock_pers['to_list'] = [To("test1@example.com", "Example User"), To("test2@example.com", "Example User")] mo...
4be81a67715bc967c8d624d784008ed3cb6775f8
27,525
def load_python_bindings(python_input): """ Custom key bindings. """ bindings = KeyBindings() sidebar_visible = Condition(lambda: python_input.show_sidebar) handle = bindings.add @handle("c-l") def _(event): """ Clear whole screen and render again -- also when the sideb...
2725352272d001da7dc74e7c29819b8ddae5521e
27,526
def batch_retrieve_pipeline_s3(pipeline_upload): """ Data is returned in the form (chunk_object, file_data). """ study = Study.objects.get(id = pipeline_upload.study_id) return pipeline_upload, s3_retrieve(pipeline_upload.s3_path, study.object_id, ...
9f48186a116fab7826dd083ab80e4f5383e813ba
27,527
def gat(gw, feature, hidden_size, activation, name, num_heads=8, feat_drop=0.6, attn_drop=0.6, is_test=False): """Implementation of graph attention networks (GAT) This is an implementation of the paper GRAPH ATTENTION NETWORKS (https://arxiv.o...
c653dc26dc2bb1dccf37481560d93ba7eee63f7c
27,529
def _number(string): """ Extracts an int from a string. Returns a 0 if None or an empty string was passed. """ if not string: return 0 else: try: return int(string) except ValueError: return float(string)
d14a7a04f33f36efd995b74bc794fce2c5f4be97
27,530
def get_email(sciper): """ Return email of user """ attribute = 'mail' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(sciper), attribute=attribute ) try: email = get_attribute(response, attribute) except Exception: raise EpflLdapExce...
5f9ce9f69e4e7c211f404a50b4f420eb6e978d64
27,531
import math def convert_size(size): """ Size should be in bytes. Return a tuple (float_or_int_val, str_unit) """ if size == 0: return (0, "B") KILOBYTE = 1024 size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size, KILOBYTE))) p = math.po...
b2bc18df8ae268e1b03bcc7addadca8e07309f7c
27,532
def _backward(gamma, mask): """Backward recurrence of the linear chain crf.""" gamma = K.cast(gamma, 'int32') # (B, T, N) def _backward_step(gamma_t, states): # print('len(states)=', len(states)) # print(type(states)) # y_tm1 = K.squeeze(states[0], 0) y_tm1 = states[0] ...
ab71548e87023e09ccd28aac81b95a6671384205
27,533
def t3err(viserr, N=7): """ provided visibilities, this put these into triple product""" amparray = populate_symmamparray(viserr, N=N) t3viserr = np.zeros(int(comb(N,3))) nn=0 for kk in range(N-2): for ii in range(N-kk-2): for jj in range(N-kk-ii-2): t3viserr[nn+j...
f5d774bb361c389f470de504adc2a467c71f0ec7
27,534
def safe_sign_and_autofill_transaction( transaction: Transaction, wallet: Wallet, client: Client ) -> Transaction: """ Signs a transaction locally, without trusting external rippled nodes. Autofills relevant fields. Args: transaction: the transaction to be signed. wallet: the wallet...
ce2b898529e15c65c8c84906c12093b9865e4768
27,536
def getMetricValue(glyph, attr): """ Get the metric value for an attribute. """ attr = getAngledAttrIfNecessary(glyph.font, attr) return getattr(glyph, attr)
9637e8c1ee3e295b1d1da67d9a77108b761acddc
27,537
from typing import Optional from typing import Union def temporal_train_test_split( y: ACCEPTED_Y_TYPES, X: Optional[pd.DataFrame] = None, test_size: Optional[Union[int, float]] = None, train_size: Optional[Union[int, float]] = None, fh: Optional[FORECASTING_HORIZON_TYPES] = None, ) -> SPLIT_TYPE:...
4bb59ead5a035114f067ab37c40289d0d660df2d
27,538
import re def split_range_str(range_str): """ Split the range string to bytes, start and end. :param range_str: Range request string :return: tuple of (bytes, start, end) or None """ re_matcher = re.fullmatch(r'([a-z]+)=(\d+)?-(\d+)?', range_str) if not re_matcher or len(re_matcher.groups(...
a6817017d708abf774277bf8d9360b63af78860d
27,539
from typing import Union def get_valid_extent(array: Union[np.ndarray, np.ma.masked_array]) -> tuple: """ Return (rowmin, rowmax, colmin, colmax), the first/last row/column of array with valid pixels """ if not array.dtype == 'bool': valid_mask = ~get_mask(array) else: valid_mask =...
9b906fcd88c901f84ff822d8ba667936d8b623ed
27,540
def epsmu2nz(eps, mu):#{{{ """ Accepts permittivity and permeability, returns effective index of refraction and impedance""" N = np.sqrt(eps*mu) N *= np.sign(N.imag) Z = np.sqrt(mu / eps) return N, Z
7575d4596706f574f2a88627982edfb704d81d94
27,542
from typing import List import re def tokenize_numbers(text_array: List[str]) -> List[str]: """ Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and dots with ' @.@ '. Args: text_array: An already tokenized text as list Returns: ...
f87b94850baeefd242ad2bcc89858fc05662a638
27,543
def main( datapath, kwdpath, in_annot, note_types, batch, ): """ Select notes for an annotation batch, convert them to CoNLL format and save them in folders per annotator. The overview of the batch is saved as a pickled DataFrame. Parameters ---------- datapath: Path pat...
cdbb4a6dbd91adccd4fdfdb2bb7c653d109801f2
27,544
def mask_to_bbox(mask): """ Convert mask to bounding box (x, y, w, h). Args: mask (np.ndarray): maks with with 0 and 255. Returns: List: [x, y, w, h] """ mask = mask.astype(np.uint8) contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) x = 0 y =...
d8fc111bdb3a2c52866ad35b8e930e5ac8ebf0ba
27,545
def find_divisor(n, limit=1000000): """ Use sieve to find first prime divisor of given number :param n: number :param limit: sieve limit :return: prime divisor if exists in sieve limit """ primes = get_primes(limit) for prime in primes: if n % prime == 0: return prime...
c990f25e055d8f8b1053cf94d6f9bb2d4fcff0bb
27,546
def sort_all(batch, lens): """ Sort all fields by descending order of lens, and return the original indices. """ if batch == [[]]: return [[]], [] unsorted_all = [lens] + [range(len(lens))] + list(batch) sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))] return so...
175f97a88371992472f1e65a9403910f404be914
27,547
def bh(p, fdr): """ From vector of p-values and desired false positive rate, returns significant p-values with Benjamini-Hochberg correction """ p_orders = np.argsort(p) discoveries = [] m = float(len(p_orders)) for k, s in enumerate(p_orders): if p[s] <= (k+1) / m * fdr: ...
ace0924fa72b39085d4504c3bb015f81e1c78546
27,548
from datetime import datetime def guess_if_last(lmsg): """Guesses if message is the last one in a group""" msg_day = lmsg['datetime'].split('T')[0] msg_day = datetime.datetime.strptime(msg_day, '%Y-%m-%d') check_day = datetime.datetime.today() - datetime.timedelta(days=1) if msg_day >= check_day: ...
2d62caeb21daff4c5181db4a0b5cd833916fb945
27,550
import time def refine_by_split(featIds, n, m, topo_rules, grid_layer, progress_bar = None, labelIter = None ) : """ Description ---------- Split input_features in grid_layer and check their topology Parameters ---------- featIds : ids of features from grid_layer to be refined n : num...
6a604bbea471d8401cbabe65a04e13a51c389413
27,551
def read_custom_enzyme(infile): """ Create a list of custom RNase cleaving sites from an input file """ outlist = [] with open(infile.rstrip(), 'r') as handle: for line in handle: if '*' in line and line[0] != '#': outlist.append(line.rstrip()) return outlist
144c6de30a04faa2c9381bfd36bc79fef1b78443
27,552
def all_features(movie_id): """Returns the concatenation of visual and audio features for a movie The numbers of frames are not egal for the visual and the audio feature. The overnumerous frame are deleted. """ T_v = all_visual_features(movie_id) T_a = all_audio_features(movie_id) min_ = mi...
df46d70d2023beb0d707d62ef9cf4f2af6f9c102
27,553
def resnet34(pretrained=False, shift='TSM',num_segments = 8, flow_estimation=0,**kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if (shift =='TSM'): model = ResNet(BasicBlock, BasicBlock, [3, 4, 6, 3],num_segments=n...
db8468b1eb0c0d5ed022ee70623c67390dedef15
27,554
def normalize_data_v3(data, cal_zero_points=np.arange(-4, -2, 1), cal_one_points=np.arange(-2, 0, 1), **kw): """ Normalizes data according to calibration points Inputs: data (numpy array) : 1D dataset that has to be normalized cal_zero_points (range) : range specifying ...
3c9017abb58745964cd936db21d79a6df4896b4e
27,555
def read(path, encoding="utf-8"): """Read string from text file. """ with open(path, "rb") as f: return f.read().decode(encoding)
674a20d7dca76f2c18b140cde0e93138b69d94ea
27,556
def min_equals_max(min, max): """ Return True if minimium value equals maximum value Return False if not, or if maximum or minimum value is not defined """ return min is not None and max is not None and min == max
1078e9ed6905ab8b31b7725cc678b2021fc3bc62
27,557
def loadDataSet(fileName): """ 加载数据 解析以tab键分隔的文件中的浮点数 Returns: dataMat : feature 对应的数据集 labelMat : feature 对应的分类标签,即类别标签 """ # 获取样本特征的总数,不算最后的目标变量 numFeat = len(open(fileName).readline().split('\t')) - 1 dataMat = [] labelMat = [] fr = open(fileName) for line...
3c9fd81d1aeb2e3723081e3a1b11d07ec08e2118
27,558
def infer_app_url(headers: dict, register_path: str) -> str: """ ref: github.com/aws/chalice#485 :return: The Chalice Application URL """ host: str = headers["host"] scheme: str = headers.get("x-forwarded-proto", "http") app_url: str = f"{scheme}://{host}{register_path}" return app_url
f3c0d1a19c8a78a0fd2a8663e2cb86427ff8f61b
27,559
def get_index_where_most_spikes_in_unit_list(unit_list): """Returns the position in the list of units that has the most spikes. :param unit_list: list of unit dictionaries :return: index :rtype: int """ return np.argmax(Recordings.count_spikes_in_unit_list(unit_list))
41f4b1f4ae1fc1b813769bf9f4606848cb700c11
27,560
def ocr_boxes( img, boxes, halve=False, resize=False, blur=True, sharpen=False, erode=False, dilate=False, lang='eng', config=None): """ Detect strings in multiple related boxes and concatenate the results. Parameters ---------- halve : bool, optional ...
c273118beb263e6ad837cbb343ad0829bd367d30
27,561
def multiply_inv_gaussians(mus, lambdas): """Multiplies a series of Gaussians that is given as a list of mean vectors and a list of precision matrices. mus: list of mean with shape [n, d] lambdas: list of precision matrices with shape [n, d, d] Returns the mean vector, covariance matrix, and precision m...
d8bdce66668ebf5e94f86310633c699ae7c98e16
27,562
import random def mutationShuffle(individual, indpb): """ Inputs : Individual route Probability of mutation betwen (0,1) Outputs : Mutated individual according to the probability """ size = len(individual) for i in range(size): if random.random() < indpb: swap_...
dea67e03b2905f1169e1c37b3456364fb55c7174
27,563
def best_shoot_angle(agent_coord: tuple, opponents: list): """ Tries to shoot, if it fail, kicks to goal randomly """ # Get best shoot angle: best_angles = [] player_coord = np.array(agent_coord) goal_limits = [np.array([0.9, -0.2]), np.array([0.9, 0]), np.array([0.9, 0.2])] f...
98c7cb90fc28b4063ce6c14a84fe8989907268d6
27,564
from typing import Optional def _parse_line(lineno: int, line: str) -> Optional[UciLine]: # pylint: disable=unsubscriptable-object """Parse a line, raising UciParseError if it is not valid.""" match = _LINE_REGEX.match(line) if not match: raise UciParseError("Error on line %d: unrecognized line t...
eab49cf766b15d769d7b194176276741d197d359
27,567
from django.contrib.auth import login from django.contrib.auth import authenticate from django.contrib.auth import login def login(request, template_name="lfs/checkout/login.html"): """Displays a form to login or register/login the user within the check out process. The form's post request goes to lfs.cu...
33d23ba50cff73580ca45519ad26d218194bd341
27,568
import inspect def _is_valid_concrete_plugin_class(attr): """ :type attr: Any :rtype: bool """ return ( inspect.isclass(attr) and issubclass(attr, BasePlugin) and # Heuristic to determine abstract classes not isinstance(attr.secret_type, abstractpro...
383e0bff4edac6623b9a2d2da45c3c47c982d72e
27,569
def arrQuartiles(arr, arrMap=None, method=1, key=None, median=None): """ Find quartiles. Also supports dicts. This function know about this quartile-methods: 1. Method by Moore and McCabe's, also used in TI-85 calculator. 2. Classical method, also known as "Tukey's hinges". In common cases it use v...
52de942dc59f293a35696579bd35c877e15c091d
27,571
def check_response_status_code(url, response, print_format): """ check and print response status of an input url. Args: url (str) : url text. response (list) : request response from the url request. print_format (str) : format to print the logs according to. """ ...
c16f453174ef48b2e6accfba4ec075bb8f2cad0d
27,572
def make_state_manager(config): """ Parameters ---------- config : dict Parameters for this StateManager. Returns ------- state_manager : StateManager The StateManager to be used by the Controller. """ manager_dict = { "hierarchical": HierarchicalStateManager...
f662b97c052ccc9188b9f7236b79228cfba983c2
27,573
from datetime import datetime def get_books_information(url: str, headers: dict = None) -> list: """ Create list that contains dicts of cleaned data from google book API. Parameters ---------- url: str link to resources (default: link to volumes with q=war, target of recrutment task)...
1643c2368ed452f9f12ea81f25c468c0240404b4
27,574
from typing import Dict from typing import Type import pkg_resources def get_agents() -> Dict[str, Type[Agent]]: """Returns dict of agents. Returns: Dictionary mapping agent entrypoints name to Agent instances. """ agents = {} for entry_point in pkg_resources.iter_entry_points("agents"): ...
5b6959278f0dd4b53d81c38d1ef919b0756a5533
27,575
from typing import MutableMapping from typing import Any from typing import Set import yaml def rewrite_schemadef(document: MutableMapping[str, Any]) -> Set[str]: """Dump the schemadefs to their own file.""" for entry in document["types"]: if "$import" in entry: rewrite_import(entry) ...
d6beec5cb41cef16f23cbcad154998b6d79f1cdb
27,576
def decor(decoration, reverse=False): """ Return given decoration part. :param decoration: decoration's name :type decoration:str :param reverse: true if second tail of decoration wanted :type reverse:bool :return decor's tail """ if isinstance(decoration, str) is False: ra...
c8fb59478f72ab76298361fa2dfa4a8720c5a46b
27,577
def group_data(data, degree=3, hash=hash): """ numpy.array -> numpy.array Groups all columns of data into all combinations of triples """ new_data = [] m,n = data.shape for indicies in combinations(range(n), degree): if 5 in indicies and 7 in indicies: print "feature Xd" elif 2 ...
886afd2f12dc0b4bf0da5648de8bcbf294b74c74
27,578
def get_dataset(dataset_name: str, *args, **kwargs): """Get the Dataset instancing lambda from the dictionary and return its evaluation. This way, a Dataset object is only instanced when this function is evaluated. Arguments: dataset_name: The name of the Dataset to be instanced. Must b...
f3ab44f6ebb9d867bdf9b08d31d70f25832fbb7d
27,579
def _numeric_handler_factory(charset, transition, assertion, illegal_before_underscore, parse_func, illegal_at_end=(None,), ion_type=None, append_first_if_not=None, first_char=None): """Generates a handler co-routine which tokenizes a numeric component (a token or sub-token). Args:...
5033f406918b6e9aeecba9d1470f3b6bc10761fa
27,580
def unsafe_content(s): """Take the string returned by safe_content() and recreate the original string.""" # don't have to "unescape" XML entities (parser does it for us) # unwrap python strings from unicode wrapper if s[:2]==unichr(187)*2 and s[-2:]==unichr(171)*2: s = s[2:-2].encode('us-as...
ec92c977838412ff6fb67297a300cbc77a450661
27,581
def _AcosGrad(op, grad): """Returns grad * -1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad.op]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) inv = math_ops.reciprocal(den) ...
7a6d67e09f6b2997476c41fe37c235349e5c5c79
27,582
def converter(n, decimals=0, base=pi): """takes n in base 10 and returns it in any base (default is pi with optional x decimals""" # your code here result = [] # setting list to capture converted digit # check for a proper base if base <= 0: base = pi # if n is zero then set the sta...
e14b2667ad73ddee13df2dd526c5cdcdfde8a2f5
27,583
import json import requests def mediaAddcastInfo(): """ :return: """ reqUrl = req_url('media', "/filmCast/saveFilmCastList") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/json', 'X-Region-Id': '2', } body...
0826c22acea653234817f9838cd82cbc7045b07b
27,584
def process_register_fns(): # noqa: WPS210 """Registration in FNS process.""" form = RegisterFnsForm() if form.validate_on_submit(): email = current_user.email name = current_user.username phone = form.telephone.data registration_fns(email, name, phone) flash('Ждите ...
f5e7b3b88bbcd610d675aef020538fb87d1a8887
27,585
import socket def validate_args(args): """ Checks if the arguments are valid or not. """ # Is the number of sockets positive ? if not args.number > 0: print("[ERROR] Number of sockets should be positive. Received %d" % args.number) exit(1) # Is a valid IP address or valid name ? tr...
37a77f59ae78e3692e08742fab07f35cf6801e54
27,586
import re def register(request): """注册""" if request.method == 'GET': # 显示注册页面 return render(request, 'register.html') else: # 进行注册处理 # 1.接收参数 username = request.POST.get('user_name') # None password = request.POST.get('pwd') email = request.POST.ge...
54f8a1eb8a0378e18634f0708cc5c4de44b88b20
27,587
def triangulation_to_vedo_mesh(tri, **kwargs): """ Transform my triangulation class to Trimesh class :param kwargs: """ coords = tri.coordinates trias = tri.triangulation m = vedo.Mesh([coords, trias], **kwargs) return m
73c14809269dab93ef3acef973e8727528e7d1bf
27,588
def build_dropout(cfg, default_args=None): """Builder for drop out layers.""" return build_from_cfg(cfg, DROPOUT_LAYERS, default_args)
e04797e311992da39ea2b3b07c90508e3afa44ce
27,589
def conv2d_transpose(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', use_xavier=True, stddev=1e-3, weight_decay=0.0, ...
df0bd44b9ef10ca9af3f1106f314b82cf84358b8
27,590
def open_py_file(f_name): """ :param f_name: name of the .py file (with extension) :return: a new file with as many (1) as needed to not already exist """ try: f = open(f_name, "x") return f, f_name except IOError: return open_py_file(f_name[:-3] + "(1)" + f_name[-3:])
bcc40f7757e0e4573b69b843c5050ad27546be53
27,591
def cast_rays(rays_o, rays_d, z_vals, r): """shoot viewing rays from camera parameters. Args: rays_o: tensor of shape `[...,3]` origins of the rays. rays_d: tensor of shape `[...,3]` directions of the rays. z_vals: tensor of shape [...,N] segments of the rays r: radius of ray c...
a647feda10263755e519e6965517ca311fcf87df
27,592
from typing import Any def ifnone(x: Any, y: Any): """ returns x if x is none else returns y """ val = x if x is not None else y return val
f2c7cf335ff919d610a23fac40d6af61e6a1e595
27,593
def get_session(region, default_bucket): """Gets the sagemaker session based on the region. Args: region: the aws region to start the session default_bucket: the bucket to use for storing the artifacts Returns: `sagemaker.session.Session instance """ boto_session = boto3.Ses...
e4944e2b21f9bc666ad29a8ad1d09ac8c44df390
27,594
def xi_einasto_at_r(r, M, conc, alpha, om, delta=200, rhos=-1.): """Einasto halo profile. Args: r (float or array like): 3d distances from halo center in Mpc/h comoving M (float): Mass in Msun/h; not used if rhos is specified conc (float): Concentration alpha (float): Profile ex...
68b86aabc08bd960e1fa25691a1f421414dc25fa
27,595
import re def _rst_links(contents: str) -> str: """Convert reStructuredText hyperlinks""" links = {} def register_link(m: re.Match[str]) -> str: refid = re.sub(r"\s", "", m.group("id").lower()) links[refid] = m.group("url") return "" def replace_link(m: re.Match[str]) -> str:...
c7c937cdc04f9d5c3814538978062962e6407d65
27,596
def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using naive recursive implementation. :param n: the index into the sequence :return: The nth Fibonacci number is returned. """ if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
08de1ff55f7cada6a940b4fb0ffe6ba44972b42d
27,597
def validator_msg(msg): """Validator decorator wraps return value in a message container. Usage: @validator_msg('assert len(x) <= 2') def validate_size(x): return len(x) <= 2 Now, if `validate_size` returns a falsy value `ret`, for instance if provided with range(4), we wi...
1913408a9e894fbe3ca70a4b6529322958e75678
27,598
def iter_fgsm_t(x_input_t, preds_t, target_labels_t, steps, total_eps, step_eps, clip_min=0.0, clip_max=1.0, ord=np.inf, targeted=False): """ I-FGSM attack. """ eta_t = fgm(x_input_t, preds_t, y=target_labels_t, eps=step_eps, ord=ord, clip_min=clip_min, clip_max=clip_max, tar...
381f50b66ce3105c13f31afae5127e8574346a36
27,599
def list_rbd_volumes(pool): """List volumes names for given ceph pool. :param pool: ceph pool name """ try: out, err = _run_rbd('rbd', '-p', pool, 'ls') except processutils.ProcessExecutionError: # No problem when no volume in rbd pool return [] return [line.strip() for...
4c80b6c952a19834a79622c31453af62db12e740
27,600
from typing import Optional from datetime import datetime def parse_date(string: Optional[str]) -> Optional[date]: """ Parse a string to a date. """ if not string or not isinstance(string, str): return None try: return isoparse(string[:10]).date() except ValueError: pas...
f29bb415a0f8d08dbcefe8ae95b5d08f898eecfb
27,601
def butter_bandpass(lowcut, highcut, fs, order=5): """ Taken from https://scipy-cookbook.readthedocs.io/items/ButterworthBandpass.html Creates a butterworth bandpass filter of order 'order', over frequency band [lowcut, highcut]. :param lowcut: Lowcut frequency in Hz :param highcut: Highcut...
148f581e36a0d1a53f931b5ce2301db8dd2cde17
27,602
def get_archives_to_prune(archives, hook_data): """Return list of keys to delete.""" files_to_skip = [] for i in ['current_archive_filename', 'old_archive_filename']: if hook_data.get(i): files_to_skip.append(hook_data[i]) archives.sort(key=itemgetter('LastModified'), ...
7701e7b145ea28148b77eb63475d7b0e9127d2f0
27,604
def tf_pad(tensor, paddings, mode): """ Pads a tensor according to paddings. mode can be 'ZERO' or 'EDGE' (Just use tf.pad for other modes). 'EDGE' padding is equivalent to repeatedly doing symmetric padding with all pads at most 1. Args: tensor (Tensor). paddings (list of lis...
e2e1e9ac2cbef63c4b12bdf35eb35090973d744a
27,605
def compute_reference_gradient_siemens(duration_ms, bandwidth, csa=0): """ Description: computes the reference gradient for exporting RF files to SIEMENS format, assuming the gradient level curGrad is desired. Theory: the reference gradient is defined as that gradient for which a 1 cm slice is...
65cf8bd8e805e37e5966170daeae90594e45595e
27,606
def schedule_conv2d_NHWC_quantized_native(cfg, outs): """ Interface for native schedule_conv2d_NHWC_quantized""" return _schedule_conv2d_NHWC_quantized(cfg, outs, False)
450b6fb914c8b0c971604319417d56c7148b5737
27,607
def calc_square_dist(a, b, norm=True): """ Calculating square distance between a and b a: [bs, npoint, c] b: [bs, ndataset, c] """ a = tf.expand_dims(a, axis=2) # [bs, npoint, 1, c] b = tf.expand_dims(b, axis=1) # [bs, 1, ndataset, c] a_square = tf.reduce_sum(tf.square(a), axis=-1) # [bs...
d855e438d4bcca4eb43a61fa6761a1cd5afd7731
27,608
def read_config(lines): """Read the config into a dictionary""" d = {} current_section = None for i, line in enumerate(lines): line = line.strip() if len(line) == 0 or line.startswith(";"): continue if line.startswith("[") and line.endswith("]"): current_s...
613ed9291ab6546700b991fc9a5fc301c55ae497
27,609
def get_cert_subject_hash(cert): """ Get the hash value of the cert's subject DN :param cert: the certificate to get subject from :return: The hash value of the cert's subject DN """ try: public_bytes = cert.public_bytes(encoding=serialization.Encoding.PEM) cert_c = crypto.load_...
070284984018ba08f568541a4d7ba815d72bd025
27,610
import requests def icon_from_url(url: str): """ A very simple attempt at matching up a game URL with its representing icon. We attempt to parse the URL and return the favicon. If that fails, return a pre-determined image based on the URL. """ if not url: return # Allow the user ...
85f8a539cacbc86e58cf4e3815babdc744352626
27,611
import numpy def extract_spikes(hd5_file, neuron_num=0): """Extracts the spiking data from the hdf5 file. Returns an array of spike times. Keyword arguments: neuron_num -- the index of the neuron you would like to access. """ with h5py.File(hd5_file, "r+") as f: neuron_list = f['NF'][...
85df1525595c0141dd885d041b54b02aa5dc1283
27,612
def problem_kinked(x): """Return function with kink.""" return np.sqrt(np.abs(x))
12897b83fa4c42cfbe608add92cf5ef0736463ef
27,613
def read_dicom(filename): """Read DICOM file and convert it to a decent quality uint8 image. Parameters ---------- filename: str Existing DICOM file filename. """ try: data = dicom.read_file(filename) img = np.frombuffer(data.PixelData, dtype=np.uint16).copy() i...
e8b621dfb7348e12e1fe8d00ae02009789205e86
27,614
import logging def _filter_all_warnings(record) -> bool: """Filter out credential error messages.""" if record.name.startswith("azure.identity") and record.levelno == logging.WARNING: message = record.getMessage() if ".get_token" in message: return not message return True
f16490ef39f9e3a63c791bddcba1c31176b925b7
27,615
import copy def _to_minor_allele_frequency(genotype): """ Use at your own risk """ g_ = copy.deepcopy(genotype) m_ = g_.metadata clause_ = m_.allele_1_frequency > 0.5 F = MetadataTF m_.loc[clause_,[F.K_ALLELE_0, F.K_ALLELE_1]] = m_.loc[clause_,[F.K_ALLELE_1, F.K_ALLELE_0]].values m_.lo...
424bf40e29f103abea3dd30ee662c3c695545a10
27,616
def ioka(z=0, slope=950, std=None, spread_dist='normal'): """Calculate the contribution of the igm to the dispersion measure. Follows Ioka (2003) and Inoue (2004), with default slope value falling in between the Cordes and Petroff reviews. Args: z (array): Redshifts. slope (float): Slo...
422f0e7d6a7c88b8ea6666e192271db81d966743
27,617
def nn_policy(state_input, policy_arch, dim_action, **kwargs): """ Fully-connected agent policy network """ with tf.variable_scope('policy_net', reuse=tf.AUTO_REUSE): for i, h in enumerate(policy_arch): state_input = layer.Dense(h, activation='tanh', # dtype='float64', ...
8513ba88fe77076711c9aaf6bb148df8d9f18c1a
27,618
def _check_geom(geom): """Check if a geometry is loaded in. Returns the geometry if it's a shapely geometry object. If it's a wkt string or a list of coordinates, convert to a shapely geometry. """ if isinstance(geom, BaseGeometry): return geom elif isinstance(geom, str): # assume it's ...
5f7e1cc405ab6c67cb6f8342e23698d1e330d49c
27,619
from typing import List import glob def read_csvs_of_program(program: str) -> List[pd.DataFrame]: """ Given the name of an algorithm program, collects the list of CVS benchmarks recorded for that particular program. :param program: name of the program which benchmarks should be retrieved :return: ...
de763b5f790150f0340c58fc9d3d53f16d530f34
27,620
from typing import List from typing import Tuple def print_best_metric_found( tuning_status: TuningStatus, metric_names: List[str], mode: str ) -> Tuple[int, float]: """ Prints trial status summary and the best metric found. :param tuning_status: :param metric_names: :param...
e91c3222e66ded7ce3ab4ddcf52a7ae77fe84e9f
27,621
def get_svn_revision(path = '.', branch = 'HEAD'): """ Returns the SVN revision associated with the specified path and git branch/tag/hash. """ svn_rev = "None" cmd = "git log --grep=^git-svn-id: -n 1 %s" % (branch) result = exec_cmd(cmd, path) if result['err'] == '': for line in result['out'].split...
76d94aca9453e1d949bf70fc6bff4b77bb519479
27,622
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool: """ Converts a given string ``val`` into a boolean. :param val: any string representation of boolean :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object :return: ``True`` if...
5ff88bee44b07fb1bd34d1734ba72485a2412b0c
27,623
import csv def print_labels_from_csv(request): """ Generates a PDF with labels from a CSV. """ if request.FILES: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=labels-from-csv.pdf' canvas = Canvas(response, pagesi...
1674d136f5ed183913961fe2f7ce23d4b245f3d7
27,624
def get_ucs_node_list(): """ Get UCS nodes """ nodeList = [] api_data = fit_common.rackhdapi('/api/2.0/nodes') for node in api_data['json']: if node["obms"] != [] and node["obms"][0]["service"] == "ucs-obm-service": nodeList.append(node) return nodeList
4fc81f7e71a33be3670d99916828a2348b0e63cd
27,625
def wysiwyg_form_fields(context): """Returns activity data as in field/value pair""" app = context['app_title'] model = context['entity_title'] try: return wysiwyg_config(app, model) except (KeyError, AttributeError): return None
86abca4a8711c3d5eec425975ee00055d0e78ae2
27,627
def thetagrids(angles=None, labels=None, fmt=None, **kwargs): """ Get or set the theta gridlines on the current polar plot. Call signatures:: lines, labels = thetagrids() lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs) When called with no arguments, `.thetagrids` simply ...
a595c4f0ff5af7dae7e20b261d11c6f690344db1
27,628