content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def dropbox_fileupload(dropbox, request): """ accepts a single file upload and adds it to the dropbox as attachment""" attachment = request.POST['attachment'] attached = dropbox.add_attachment(attachment) return dict( files=[dict( name=attached, type=attachment.type, ...
84a89a8b8a21c3a78105d8ef911ee6aba71206f2
13,939
def series(expr, x, point=0, n=6, dir="+"): """Series expansion of expr around point `x=point`. See the doctring of Basic.series() for complete details of this wrapper. """ return expr.series(x, point, n, dir)
fee3fff7a29136813c7d6bf5d1cf7c576651368d
13,940
def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None): """Process input of the apply_transform_funcs function. :param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple :param dict func_args: function positional arguments, specified as ...
2e9fe4bec55f0a13a0644cfe27ba887f00e85c55
13,942
import math def _get_fov(pillow_image) -> float: """Get the horizontal FOV of an image in radians.""" exif_data = pillow_image.getexif() # 41989 is for 'FocalLengthIn35mmFilm'. focal_length = exif_data[41989] # FOV calculation, note 36 is the horizontal frame size for 35mm # film. return ...
9b8101010a980079d950b6151a3d5280d5eedb73
13,944
import re def validate_str(input,validate): """ This function returns true or false if the strings pass regexp validation. Validate format: substrname: "^\w{5,10}$", Validates that the string matches the regexp. """ if not re.match(validate,input) == None: # If the validation returned something, return...
400fd1cd7b4fa297f5916e80a39d7ef668deab1c
13,945
def pieChartInfoPlus(trips): """ Calculates the total distance per activity mode Parameters ---------- trips : dict - Semantic information (nested) Returns ------- list(data): list - labels of the activity modes list(data.values()): list - distance per activity mode """ la...
ad0306b2561b01a33c509b2c454f464e9c6ff8a3
13,946
import os import subprocess def build_flags(library, type_, path): """Return separated build flags from pkg-config output""" pkg_config_path = [path] if "PKG_CONFIG_PATH" in os.environ: pkg_config_path.append(os.environ['PKG_CONFIG_PATH']) if "LIB_DIR" in os.environ: pkg_config_path.a...
2fc526d4cb2fe6ad12e47bc7abebbcd9dc32780b
13,947
import os import json def getG2Inputs(conf, mnet): """Get dictionaries C, F, and flow info (RTT and path) for each traffic flow. Write these dictionaries to JSON files. Args: conf (ConfigHandler): ConfigHandler object containing user-specified configurations. mnet (NetworkSimulator): The ...
ca356119f3e797085529717c4ecfd46be3bd670a
13,948
def findCharacter(stringList, patternCharacter): """ Find the specific character from the list and return their indices """ return([ind for ind, x in enumerate(list(stringList)) if x == patternCharacter])
32cc8fb5970c6cd3cefd161b9e13e340f1645d13
13,949
def cell_trap_getter_generator(priv_attr): """ Generates a getter function for the cell_trap property. """ def getter(self): if getattr(self, priv_attr) is None: data =\ ( self.gfpffc_bulb_1 - self.gfpffc_bulb_bg )/self.gfpffc_bulb_bg ...
15217adbd96ce44b361444867e5d9c6d202440f4
13,951
import os def docker_compose_files(in_docker_compose, pytestconfig): """ This fixture provides support for `cloudbuild`. By passing the command line argument `--in-docker-compose=cloudbuild`, uses `docker-compose.cloudbuild.yml`. """ dc_type = f".{in_docker_compose}" if in_docker_compose else ...
22aec9c7953955febc6ea52c5fec450b36a1d144
13,953
def bg_trim(im): """ Function to programmatically crop card to edge. `im` is a PIL Image Object. """ # This initial crop is hacky and stupid (should just be able to set device # options) but scanner isn't 'hearing' those settings. # w,h = im.size im = im.crop((443, 0, 1242, 1200)) # ...
b5b59059aa9823cd2be385ead5cc21b135a4e24b
13,954
def get_filtered_query(must_list=None, must_not_list=None): """Get the correct query string for a boolean filter. Accept must and must_not lists. Use MatchList for generating the appropriate lists. """ bool_filter = {} if must_list: bool_filter['must'] = must_list if must_not_list: ...
2190456ad7e91239bb623f7ec3d2c460e521e36f
13,955
def convert_to_letter(grade): """Convert a decimal number to letter grade""" grade = round(grade, 1) if grade >= 82.5: return 'A' elif grade >= 65: return 'B' elif grade >= 55: return 'C' elif grade >= 50: return 'D' else: return 'F'
13ce25275750e7a27e0699078a15ba551674a941
13,956
def time_coord(cube): """ Return the variable attached to time axis. Examples -------- >>> import iris >>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/' ... 'fmrc/us_east/US_East_Forecast_Model_Run_Collection_best.ncd') >>> cube = iris.load_cube(url, 'sea_water_potent...
12a706f956846e8471d0d7f044367c77210c4486
13,957
import re def oneliner(s) -> str: """Collapse any whitespace in stringified `s` into a single space. """ return re.sub(r"[\n ]+", " ", str(s).strip())
ed1d419b4fab8cb2deccdbc2944996ef7be28cc5
13,958
from typing import Counter def diff_counts(values : list[int]) -> dict[int, int]: """Count the gaps between ordered elements in a list, by size.""" ordered = [0] + sorted(values) + [max(values) + 3] return Counter(j - i for i, j in zip(ordered, ordered[1:]))
897cb7fdfed85b37bd8bd7031290e34199c57574
13,960
def get_one_prior_probability(state, segment_df, total_positions): """ Returns the number of genomics positions that are of the state """ state_df = segment_df[segment_df[3] == state] num_pos_this_state = float(sum(state_df['num_occ'])) return num_pos_this_state / float(total_positions)
157666f84d9ba6b7d236bb0f10e331e9315d9efa
13,962
def convert_netdict_to_pydict(dict_in): """Convert a net dictionary to a Python dictionary. Parameters ---------- dict_in : dict Net dictionary to convert. Returns ------- dict Dictionary converted to Python. """ pydict = {} for key in dict_in.Keys: pyd...
6aa9bb5ac00ff92d23ff5a449d096caad0d01c9c
13,963
from typing import List def binary_search(input_array: List[int], target: int): """ Given a sorted input array of integers, the function looks for a target or returns None Returns: Target index or None """ if not input_array or not target: return None left_pointer = 0 ri...
b9f389d1b31e5b95bb885bd638549f7775db207e
13,964
from datetime import datetime def _sort_by_date(time_coord): """ Private sorting function used by _file _sort_by_earliest_date() and sort_by_earl iest_date(). Args: time_coord: Cube time coordinate for each cube to be sorted by. Returns: time_origin: The time origin t...
89c52c40dd8dfa03cbe431a4db6f107b42b22e81
13,965
def is_superuser(view): """Allow access to the view if the requesting user is a superuser.""" return view.request.user.is_superuser
5a15433200634ca326c36bdc17acbc1ada4e6426
13,966
import os def meta(file_dir, file_name=None, deep=1): """ 返回文件的基本信息 :param file_dir: 路径 :param file_name: 文件名称 :param deep: 深度 :return:文件信息 """ return { 'dir': file_dir, 'name': file_name, 'path': file_dir if file_name is None else os.path.join(file_dir, file_na...
d68002a864e255151fe5176bfa20c01a2f554c78
13,967
def tag_row(tag): """Format a tag table row""" return [tag.get('id'), tag.get('name'), tag.get('referenceCount', 0)]
4cd1d0991eae996a52288c6d1d9bb3bd1a368ea6
13,968
from typing import Any import torch import numbers def python_scalar_to_tensor(data: Any, device: torch.device = torch.device("cpu")) -> Any: """ Converts a Python scalar number to a torch tensor and places it on the given device. """ if isinstance(data, numbers.Number): data = torch.tensor([data], de...
83e4ac093a40225f9c5fe121d9b67424f258e039
13,969
def allpath(path): """ return paths """ paths = path.strip("/").split("/") for i in range(1,len(paths)): paths[i] = paths[i-1] + "/" + paths[i] return paths
8b76f70dbae41a1ae46462d0755dbb5c5c0eb4c1
13,970
def LIGHTNING(conf): """Get Lightning Color code from config""" return conf.get_color("colors", "color_lghtn")
08781e469c7262228904e883594e475be634816b
13,971
def chrxor(st1, st2, strf1, ar1, strf2, ar2, fun1, fun2): """Takes two strings and applies a function to each charater in the string. Function is some function that takes characters and turns them into integers. This could be something to turn them into ascii order, or simply map them to another range of integers....
d463e21e55bf41ce9dee612d77810c2000210477
13,972
def is_exists(t): """Whether t is of the form ?x. P x.""" return t.is_comb() and t.fun.is_const() and \ t.fun.name == "exists" and t.arg.is_abs()
7f7c5f32685df636ec2181efd5a1b7dbc8313d4c
13,973
from typing import Tuple def InterpolateValue(x: float, xy0: Tuple[float, float], xy1: Tuple[float, float]) -> float: """Get the position of x on the line between xy0 and xy1. :type x: float :type xy0: Tuple[float, float] :type xy1: Tuple[float, float] :return: y :rtype: float """ if ...
9de4372b593fae65f772c19a8ac369315a8489d0
13,975
def get_subset_with_sum(a, n): """Returns a subset of a with sum equal to n (if exists).""" dp = [[]] * (n + 1) for i in range(len(a)): for j in range(n, a[i] - 1, -1): if j == a[i]: dp[j] = [a[i]] elif dp[j]: continue elif dp[j - a...
c9e2ba7b6ea3b33d839cdad3586ccd8717089ebf
13,976
def boolean(prompt=None, yes='y', no='n', default=None, sensitive=False, partial=True): """Prompt for a yes/no response. Parameters ---------- prompt : str, optional Use an alternative prompt. yes : str, optional Response corresponding to 'yes'. no : str, optional ...
159c8be6004e4e9f2c5a271e36facd3610561b61
13,978
import torch def compute_local_cost(pi, a, dx, b, dy, eps, rho, rho2, complete_cost=True): """Compute the local cost by averaging the distortion with the current transport plan. Parameters ---------- pi: torch.Tensor of size [Batch, size_X, size_Y] transport plan used to compute local cost ...
3d29e8ae5ef14ab30cd676eebeb6507e9cbfafca
13,981
def electron_binding_energy(charge_number): """Return the electron binding energy for a given number of protons (unit is MeV). Expression is taken from [Lunney D., Pearson J. M., Thibault C., 2003, Rev. Mod. Phys.,75, 1021].""" return 1.44381e-5 * charge_number ** 2.39\ + 1.55468e-12 * char...
6d5a845b1b11720b44b62500f979f0a621faca0a
13,985
def parse_generic(data, key): """ Returns a list of (potentially disabled) choices from a dictionary. """ choices = [] for k, v in sorted(data[key].iteritems(), key=lambda item: item[1]): choices.append([v, k]) return choices
90d2f2188d5cca7adb53eebca80a80f2c46b04a7
13,986
def attrs_to_dict(attrs): """ Convert a list of tuples of (name, value) attributes to a single dict of attributes [name] -> value :param attrs: List of attribute tuples :return: Dict of attributes """ out = {} for attr in attrs: if out.get(attr[0]) is None: out[attr[0...
ccf9440d29de2f8556e694f4ab87e95f0bfd9e8a
13,987
def count(i): """List or text. Returns the length as an integer.""" return len(i)
d8daf7cd325ce1acfb382723759ff190becd785f
13,989
def score(hand): """ Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card. hand: full yahtzee hand Returns an integer score """ possible_scores = [] #Add each possible score to the list of possible scores for num in list(hand): ...
da6ff8c5a0c640034ae063bc08a54351f4dd259e
13,990
import math def PlateStiffener (b, t, hw, tw, bf, tf, L, fyp, fyw = 0, fyf = 0, E = 210000): """ """ # plate (flange) section _b = b _t = t # web section _hw = hw _tw = tw # flange section _bf = bf _tf = tf # Fy plate _Fyp = fyp # Fy web if fyw == 0: _Fyw = _Fyp...
13321a27dd3580f99b0128daa859acfeb5dad5d7
13,993
def find_body(view): """ Find first package body declaration. """ return view.find(r'(?im)create\s+(or\s+replace\s+)?package\s+body\s+', 0)
b592199e4ef09d079645fc82ade8efbe3c92a895
13,994
import math def roll(entropy, n): """From 0 to n - 1.""" # Minimum bit depth to cover the full range. # Note that more bits would be more fair. bit_depth = math.ceil(math.log2(n)) x = entropy(bit_depth) # Scale from total range to desired range. # Numbers with higher odds will be evenly...
a714b1636cd6a97fb4d4ccc19e966795cadec76c
13,996
import subprocess import os def get_peatclsm_data_table(variable, expected_header): """Return a tabulated variable as parameterized in PEATCLSM """ output = subprocess.check_output( ['Rscript', '--vanilla', os.path.join( os.path.dirname(__file__), 'peatclsm_hydr...
3d21f05004c5deb77514c7021cd79abf20c325af
13,998
def get_num_objects(tree): """ Get number of objects in an image. Args: tree: Tree element of xml file. Returns: Number of objects. """ num_obj = 0 for e in tree.iter(): if e.tag == 'object': num_obj = num_obj + 1 return num_obj
92f937cbbf2eabdc909ef6bc1f06ccb87e0148b7
13,999
def partition(n, g): """ Returns the number of ways to partitions set of n elements with a partition of size g """ if n == 1: return 1 elif n == g: return 1 elif g>n or g<=0: return 0 else: sum = 0 for i in range(g, n-g+1, 1): sum += pa...
e0af35b413963c6ff600e87e5a55e8f4dbcc4b84
14,000
from typing import Union def _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float: """ Return the tolerance equivalent to the deprecated `check_less_precise` parameter. Parameters ---------- check_less_precise : bool or int Returns ------- float Toler...
375f7918a04fafb4a79f77abd3f0282cdc74e992
14,001
def get_arg(cmds): """Accepts a split string command and validates its size. Args: cmds: A split command line as a list of strings. Returns: The string argument to the command. Raises: ValueError: If there is no argument. """ if len(cmds) != 2: raise ValueError('%s needs an argument.' % c...
a12b9402cb824748127c9a925850a10f6a9fe022
14,003
from pathlib import Path def _resolve_ros_workspace(ros_workspace_input: str) -> Path: """Allow for relative paths to be passed in as a ros workspace dir.""" ros_workspace_dir = Path(ros_workspace_input).resolve() if not (ros_workspace_dir / 'src').is_dir(): raise ValueError( 'specifie...
45c5843a2e34a79f077ae595b100f2d58f903bae
14,004
import os import pickle def _load_scaler_to_memory(path): """ Load a pickle from disk to memory """ if not os.path.exists(path): raise ValueError("File " + path + " does not exist") return pickle.load(open(path, 'rb'))
cbc87a09ce22836ec20f971432d2aa91b584ce6b
14,005
def unscale_daily_temp(mean_temp, scaled_daily_temp, scale_params): """scale back the daily temp""" daily_temp = scaled_daily_temp*\ (scale_params[0] - scale_params[1]*mean_temp) + mean_temp return daily_temp
bbb66eabbfc929d1a9099a07e31ad1bd606d20e7
14,006
import os def find_file(name, path): """File the first file within a given path. Args: name: Name of the file to search for. path: Root of the path to search in. Returns: Full path of the given filename or None if not found. """ for root, dirs, files in os.walk(path): if name in files: ...
608727432f16725f4e334170e1412804175dacf3
14,007
def _magnitude_to_marker_size(v_mag): """Calculate the size of a matplotlib plot marker representing an object with a given visual megnitude. A third-degree polynomial was fit to a few hand-curated examples of marker sizes for magnitudes, as follows: >>> x = np.array([-1.44, -0.5, 0., 1., 2., 3., ...
cb030993c5799da9f84e9bbadb9fe30680d74944
14,009
def upto(limit: str, text: str) -> str: """ return all the text up to the limit string """ return text[0 : text.find(limit)]
0fbe1732954c225fe8d8714badb9126c8ab72a4d
14,010
import torch def generate_part_labels( vertices, faces, cam_t, neural_renderer, part_texture, K, R, part_bins ): """ :param vertices: (torch tensor NVx3) mesh vertices :param faces: (torch tensor NFx3) mesh faces :param cam_t: (Nx3) camera translation :param neural_renderer: renderer :para...
189adf5939bab026c197c84ac07bf8272abc5ca9
14,011
def check_occuring_variables(formula,variables_to_consider,allowed_variables) : """ Checks if the intersection of the variables in <formula> with the variables in <variables_to_consider> is contained in <allowed_variables> Parameters ---------- formula : list of list of integers The formula to cons...
16faf544cc6f4993afb1cad356037820d54225ba
14,012
def classproperty(f): """decorator that registers a function as a read-only property of the class.""" class _ClassProperty: def __get__(self, _, cls): # python will call the __get__ magic function whenever the property is # read from the class. return f(cls) return _ClassProperty()
de5586548b77e8c1c72176690b64df603edacf78
14,014
def _merge_config_dicts(dct1, dct2): """ Return new dict created by merging two dicts, giving dct1 priority over dct2, but giving truthy values in dct2 priority over falsey values in dct1. """ return {str(key): dct1.get(key) or dct2.get(key) for key in set(dct1) | set(dct2)}
9d66c10438027254fbac7d8cc91185a07dd9da65
14,015
def from_list(*args): """ Input: args - variable number of integers represented as lists, e.g. from_list([1,0,2], [5]) Output: new_lst - a Python array of integers represented as strings, e.g. ['102','5'] """ new_lst = [] for lst in args: new_string = '' for digi...
c3c0a2224433104a00ffabdadf612127d1b0ed3c
14,017
def perpetuity_present_value( continuous_cash_payment: float, interest_rate: float, ): """Returns the Present Value of Perpetuity Formula. Parameters ---------- continuous_cash_payment : float Amount of continuous cash payment. interest_rate : float Interest rate, yield or discount r...
26eb398776ce4f74348b23920b99b0390c462ff9
14,018
def fatorial(valor,show=False): """ -> Calcula valor Fatorial de n Param valor: recebe valor para calculo de fatorial Param show: (OPCIONAL) mostra como o calculo foi realizado return: retorna o resultado do fatorial de n """ fat = 1 if show == True: #print(fat,end=' x ')...
e0dacf6102cc38c019f122dd51d25f591c1b047d
14,021
def __avg__(list_): """Return average of all elements in the list.""" return sum(list_) / len(list_)
3204d823e83bd43efccf9886acd3ae8b01e1d7a0
14,022
import os import pickle def load_file(path): """ Load a file :param path: File path :return: file """ fn = os.path.join(os.path.dirname(__file__), path) return pickle.load(open(fn, 'rb'))
aa0b6e44466faf37eca38c8f55a81ac35e48c623
14,024
def combine(main_busytime_list, merging_list): """ given two lists of busytimes, returns list of busytimes that have events of the same day together """ merged = [ ] days = { } current_date = '' #this creates the dates dict for busytime in main_busytime_list: if busytime['date'] ...
978946353dd4d7a57b57e66693a5d396f6e8d7f6
14,025
def _make_final_gr(x): """Apply function to do graduation rates""" race, sixyrgr, sixyrgraah, comments = x first_gr = sixyrgraah if race in ["B", "H", "M", "I"] else sixyrgr if comments == "Posse": return (first_gr + 0.15) if first_gr < 0.7 else (1.0 - (1.0 - first_gr) / 2) else: ret...
600157433efe8a1689d81c2e17114c1578c43c21
14,026
import requests def check_hash(h): """ Do the heavy lifting. Take the hash, poll the haveibeenpwned API, and check results. :param h: The sha1 hash to check :return: The number of times the password has been found (0 is good!) """ if len(h) != 40: raise ValueError("A sha1 hash should be 30 characters.") h = ...
965dd75b5da095bc24ce6a6d733b271d9ec7aa80
14,028
def get_field_hint(config, field): """Get the hint given by __field_hint__ or the field name if not defined.""" return getattr(config, '__{field}_hint__'.format(field=field), field)
0d374daf93646caf55fe436c8eb2913d22151bbc
14,030
def btc(value): """Format value as BTC.""" return f"{value:,.8f}"
1d883384a6052788e8fa2bedcddd723b8765f44f
14,032
def parse_sbd_devices(options): """Returns an array of all sbd devices. Key arguments: options -- options dictionary Return Value: devices -- array of device paths """ devices = [str.strip(dev) \ for dev in str.split(options["--devices"], ",")] return devices
d706efd6a456e2279b30492b634e018ebd8e873f
14,033
def pull_from_js(content, key): """Pull a value from some ES6.""" # we have to parse fucking ES6 because ES6 cannot natively import fucking JSON return list(filter(lambda x: f"{key}:" in x, content.split("\n")))[0].split('"')[1]
0b5f7fae68e1f5d376c22cd18a6799c4c76a71f7
14,034
import time def nagios_from_file(results_file): """Returns a nagios-appropriate string and return code obtained by parsing the desired file on disk. The file on disk should be of format %s|%s % (timestamp, nagios_string) This file is created by various nagios checking cron jobs such as check-rab...
02697105ad5e9d01dd0eb504e232314f4d15a6a9
14,035
import math def _width2wing(width, x, min_wing=3): """Convert a fractional or absolute width to integer half-width ("wing"). """ if 0 < width < 1: wing = int(math.ceil(len(x) * width * 0.5)) elif width >= 2 and int(width) == width: # Ensure window width <= len(x) to avoid TypeError ...
38bdb809167b19b0ef5c7fad6858d2f7016ec310
14,036
def mb_bl_ind(tr1, tr2): """Returns the baseline index for given track indices. By convention, tr1 < tr2. Otherwise, a warning is printed, and same baseline returned. """ if tr1 == tr2: print("ERROR: no baseline between same tracks") return None if tr1 > tr2: print("WARN...
7d1bc958ca9928f54e51935510d62c45f7fc927f
14,037
from pathlib import Path def check_installed(installed="/media/mmcblk0p1/installed"): """Check if LNCM-Box is installed""" if Path(installed).is_file(): with open(installed, "r") as file: lines = file.readlines() for line in lines: print(line) return Tru...
31f73b8927e0a23c6d70ab13791ead9cf5d55b8c
14,038
def sliding_window(image_width,image_height, patch_w,patch_h,adj_overlay_x=0,adj_overlay_y=0): """get the subset windows of each patch Args: image_width: width of input image image_height: height of input image patch_w: the width of the expected patch patch_h: the height of the e...
42af883927a72f313eb7804e9d99bd6ec37fa7f3
14,039
def datetime_format_to_js_datetime_format(format): """ Convert a Python datetime format to a time format suitable for use with the datetime picker we use, http://www.malot.fr/bootstrap-datetimepicker/. """ converted = format replacements = { '%Y': 'yyyy', '%y': 'yy', '%m'...
a037146b17aae21831bc4c76d4500b12bc34feba
14,040
def make_data(current_data): """ Formats the given data into the required form """ x = [] n = len(current_data) for i in range(n - 1): x.append(current_data[i]) x.append(1) return x, current_data[n - 1]
04ff4ba93445895451c4c710e7aae59b9787a07d
14,042
def average_over_dictionary(mydict): """ Average over dictionary values. """ ave = sum([x for x in mydict.values()])/len(mydict) return ave
584e8cb073c298b3790a96e2649dbacfd5716987
14,043
def concat_complex(list_complex, width_in_bits, imreOrder=True): """ Concatenates the real and imaginary part into one integer. The specifed width counts for both the real and imaginary part. Real part is mapped on the LSB. Imaginary part is shifted to the MSB. """ # PD if imreOrder: ...
831275da0695a477f9f75da1e238f231ea8d39df
14,044
import os def get_best_model(dir_name): """Get the best model from model checkpoint folder. Normally it's the last saved model in folder. Args: dir (String, optional): Directory to get the best trained model. Defaults to Config.checkpoint_model_path. Returns: str: name of best model ...
29603d001b28d0081c5128c375ba97e716b38eac
14,046
def treat_category(category: str) -> str: """ Treats a list of string Args: category (str): the category of an url Returns: str: the category treated """ return category.lower().strip()
a4c08383bdfb40e5e64bbf576df53a7f46fc07da
14,047
def _get_fully_qualified_class_name(obj): """ Obtains the fully qualified class name of the given object. """ return obj.__class__.__module__ + "." + obj.__class__.__name__
e427991067254c2ac1963c5ae59468ec2c0835e2
14,049
import subprocess def ping(hostname, n=3): """ standard Windows ping """ output = subprocess.run(["ping", hostname, "-n", str(n)], stdout=subprocess.PIPE) result = output.stdout.decode() #and then check the response... if 'Reply from ' + hostname + ': bytes=' in result: return True el...
5ad250bff210dac9c8a3571e9214f527e93f1851
14,050
import decimal def new_decimal(value): """Builds a Decimal using the cleaner float `repr`""" if isinstance(value, float): value = repr(value) return decimal.Decimal(value)
023809d3db3e863f66559913f125e61236520a6a
14,051
def add_frac(zaeler1, nenner1, zaeler2, nenner2): """Dieses Programm addiert 2 Brüche miteinander und kürzt sie mit ihrem größten gemeinsamen Teiler (ggt)""" #Variablen einführen zaeler=0 nennerg=0 ggt = 1 #überprüfen ob die Eingabe eine Ganzzahl ist if not(isinstance(zaeler1,int) and isinstance(ne...
c77734b40f83121656e49a7029cfe73c073ee45d
14,053
import os def make_docker_cmd(image, exe, flags='', **kwargs): """Create command list to pass to subprocess Parameters ---------- image : str Name of docker image exe : str path to executable in docker workdir : str, optional working directory in docker container v...
e3ac438bb00fb83da31d0512da2b580daafe164c
14,054
def BFS_MIN(graph, start): """最短路径问题, 树的结构""" queue = [] queue.append(start) seen = set() seen.add(start) parent = {start:None} # 开始BFS搜索 while len(queue) > 0: vertex = queue.pop(0) nodes = graph[vertex] for w in nodes: if w not in seen: ...
91013649e813dd582b08d092f6f5c5c66e4cc92a
14,055
def sol(arr, n, p): """ If we have more chocolates than cost we just pay from the balance otherwise we use all the balance and add the remaining to the total cost also making bal 0 """ bal = 0 res = 0 for i in range(n): d = arr[i-1]-arr[i] if i > 0 else 0-arr[i] # Careful...
75592d2783eba2e4721721b03f84ea5cebffbc78
14,056
import subprocess def get_stdout(*args): """Runs the subprocess and returns the stdout as a string""" result = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True) result.check_returncode() return result.stdout
e55b30a05caff148330f88aae961b2da20902d90
14,057
def ncol(self): """ return the number of cols """ return len(self.columns)
723567269cf2779eef991c35f00814d7b541d75e
14,058
def insertionsort(arr): """ In a given iteration: 1. swap arr[lo] with each larger entry to the left. 2. Increment lo pointer """ lo = 0 hi = len(arr) - 1 while lo <= hi: curr = lo while curr - 1 >= 0: if arr[curr] < arr[curr - 1]: arr...
64a44af7b563e708053f04da3970429dc05c4745
14,059
def add_method(cls): """Decorator. @add_method(cls) binds the following function to the class cls.""" def decorator(func): #method = MethodType(func,cls) #setattr(cls, func.__name__, method) setattr(cls, func.__name__, func) return func ret...
b6f350651dddf90c1c9f88467d04fa7f53b8204f
14,060
import unicodedata def unidecode(s: str) -> str: """ Return ``s`` with unicode diacritics removed. """ combining = unicodedata.combining return "".join( c for c in unicodedata.normalize("NFD", s) if not combining(c) )
589dc0403c95e29f340070e3a9e81a6f14950c8e
14,061
def AutoUpdateUpgradeRepairMessage(value, flag_name): """Messaging for when auto-upgrades or node auto-repairs. Args: value: bool, value that the flag takes. flag_name: str, the name of the flag. Must be either autoupgrade or autorepair Returns: the formatted message string. """ action =...
7153b7aa44d6d798aa58d9328ac49097016c0879
14,062
import ast import collections import logging def _get_ground_truth_detections(instances_file, allowlist_file=None, num_images=None): """Processes the annotations JSON file and returns ground truth data corresponding to allowlisted image IDs. Args:...
2650ff4ffeb13d0a7874164474fa47a82880d45d
14,063
import re def combine_placeholders(string, placeholders, _placeholder_re=re.compile(r'%\(([^)]+)\)')): """Replace ``%(blah)`` placeholders in a string. Each placeholder may contain other placeholders. :param string: A string that may contain placeholders :param placeholders: A dict containing placeh...
f75dc1cd7b9c1c1d036dbdc60221b426bd56d012
14,065
def quadratic(a, b, c): """ Always returns the smallest root as t0 """ discrim = b**2 - 4 * a * c if discrim < 0: return (False, 0, 0) rootd = discrim**(1/2) if b < 0: q = -0.5*(b - rootd) else: q = -0.5*(b + rootd) t0 = q / a t1 = c / q if t1 > t0: tm...
3acafea305892bc6d303a3c090411d3eb4eb2204
14,066
def comparison_total(bst): """ ------------------------------------------------------- Sums the comparison values of all Letter objects in bst. ------------------------------------------------------- Preconditions: bst - a binary search tree of Letter objects (BST) Postconditions: ...
2fe199d5364c79fd969dbfb2a3dfb7efd62c599a
14,068
from os.path import dirname, join, abspath, isdir def find_test_interop_dir(): """Find the common tests directory relative to this script""" f = dirname(dirname(dirname(dirname(abspath(__file__))))) f = join(f, "tests", "interop") if not isdir(f): raise Exception("Cannot find tests/interop dir...
46f41da24de5491543fde5b30fd86ad0758430c9
14,070
import os def input_path(fp): """make fp an absolute path and checks it exist""" cwd = os.path.abspath(os.getcwd()) fp = os.path.normpath(os.path.join(cwd, fp)) if not os.path.exists(fp): raise ValueError("Invalid path !") return fp
b439649b8b4603b76e46a9aded54fa08890c5e66
14,071
def aggregate_results(tweets, results): """ Aggregates results based on actual tweet labeling and the classified sentiment. @param tweets: the list of labeled tweets. @param results: the results form the classification. @return: """ #print "INFO -- Aggregating results" classification_res...
d51bc4b173ca1b4fec632fef68a0f1537a19d799
14,073
import os import tempfile def database_files_path(test_tmpdir, prefix="GALAXY"): """Create a mock database/ directory like in GALAXY_ROOT. Use prefix to default this if TOOL_SHED_TEST_DBPATH or GALAXY_TEST_DBPATH is set in the environment. """ environ_var = f"{prefix}_TEST_DBPATH" if environ_...
415d671a177330a52fa275ac8cd28873130883a5
14,074