content
stringlengths
22
815k
id
int64
0
4.91M
def tofits(outfilename, pixelarray, hdr=None, verbose=True): """ Takes a 2D numpy array and write it into a FITS file. If you specify a header (astropy.io.fits format, as returned by fromfits()) it will be used for the image. You can give me boolean numpy arrays, I will convert them into 8 bit integers. """ ...
5,312,700
def may_data(): """ Values of a few transport coefficients calculated with the closed analytic Fermi-Dirac expressions for the free electron mass at 300 K. The values assume acoustic phonon scattering. Parameters ---------- None Returns ------- data : ndarray | Dime...
5,312,701
def and_nominal_group(sentence): """ add 'and' between nominal groups separated with nothing Input=sentence Output=sentence """ # init i = 0 list_nominal_group = our_list = [] while i < len(sentence): # We start by finding the first nominal g...
5,312,702
def decompressData(contentData): """ Handles the actual decompression of Base64 data. Args: contentData: String of Base64 content Returns: contentData: Decompressed content of ASCII printable """ decoded = base64.b64decode(contentData) # IO.Compression.DeflateStream tr...
5,312,703
def inject_middleware(): """Make sure AppMap middleware is added to the stack""" if 'appmap.django.Middleware' not in settings.MIDDLEWARE: settings.MIDDLEWARE.insert(0, 'appmap.django.Middleware')
5,312,704
def compute_edge_measures(ntwk): """ These return edge-based measures """ iflogger.info("Computing edge measures:") measures = {} # iflogger.info('...Computing google matrix...' #Makes really large networks (500k+ edges)) # measures['google_matrix'] = nx.google_matrix(ntwk) # iflogger.in...
5,312,705
def gen_new_axis(x_axis, expr, precision): """evaluate lagrange interpolation""" new_x = np.arange(min(x_axis), max(x_axis), precision) f = lambdify('x', expr, "numpy") new_y = f(new_x) return new_x, new_y
5,312,706
def report_table_plot(args, teacher_seed_dir, student_dirs): """This is for reporting a table. See spinup.teaching.plot_offline_rl for details and documentation. The input is the same as the plot method. NOTE(daniel) As I've reiterated to myself many times, we need to ensure that for any runs that used...
5,312,707
def calc_fresnel_coefficients(n1, n2, cos_theta1, cos_theta2 = None) -> Tuple: """ Args: n1: Refractive index in first medium. n2: Refractive index in second medium cos_theta1: Cosine of angle of incidence. Returns: """ assert np.all(cos_theta1>=0) if cos_theta2 is Non...
5,312,708
def _fetch_detailed_dataset(args=None): """ Fetch detailed info by crawling the detailed artwork pages, using the links from the basic dataset. Parallelized with vislab.utils.distributed.map_through_rq. """ basic_df = get_basic_df(args) print("Fetching detailed Wikipaintings dataset by scr...
5,312,709
def crop_image(image): """ Crop an image that has a padding of 0 value so that there is no empty margin. Return the cropped image, and the x, y offsets of the new image coordinates relative to the uncropped image. If there is no non-zero value in the image, returns False. Parameters -------...
5,312,710
def create_node_from_server(server): """ Translate AWS EC2 Instance representation into a Node object. """ return Node( id=server.id, ip=server.private_ip_address, extIp=server.public_ip_address, az=server.placement['AvailabilityZone'], name="", state=server_s...
5,312,711
def main(): """Runs the GUI and reports what the user enters, for debugging.""" configdata = config_gui.Config_GUI().activate() for key, value in configdata.items(): print(str(key) + ' : ' + str(value))
5,312,712
def test_cancel_timeout_on_hook(monkeypatch, hook_name) -> None: """Make sure that we are cancelling any scheduled traceback dumping due to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any other interactive exception (pytest-dev/pytest-faulthandler#14).""" import faulthandler f...
5,312,713
def if_nametoindex(name): """ Converts interface name to ifindex @name - inteface name @return - ifindex in case of success, else raises exception """ ret = libc.if_nametoindex(name) if not ret: raise RuntimeError("Invalid Name") return ret
5,312,714
def upgrade(): """Add 'modified_at' column for Collection/Permission/User, and 'last_login_at' for User.""" with op.batch_alter_table('collections', schema=None) as batch_op: batch_op.add_column(sa.Column('modified_at', sa.DateTime(), nullable=True)) with op.batch_alter_table('permissions', schema=...
5,312,715
def run_export(export_s3_uri, export_id): """Run spark export Args: export_s3_uri (str): location of job definition export_id (str): ID of export job to process """ status_uri = "s3://{}/export-statuses/{}".format( os.getenv("DATA_BUCKET"), export_id ) command = [ ...
5,312,716
def gauss_seidel_split(A): """ split A matrix in additive lower and upper triangular matrices Args: A (ndarray): input matrix Returns: L (ndarray): lower triangular matrix U (ndarray): upper triangular matrix (zero diagonal) """ L = np.tril(A) U = np.triu(A) np....
5,312,717
def _define_annuli(angle_list, ann, n_annuli, fwhm, radius_int, annulus_width, delta_rot, n_segments, verbose, strict=False): """ Function that defines the annuli geometry using the input parameters. Returns the parallactic angle threshold, the inner radius and the annulus center for each...
5,312,718
def write_geonames (mapping_table, output=None): """ Write the mapping table out to line-oriented JSON. @param mapping_table: the mapping table to write @param output: the output stream (defaults to standard output) @see read_geonames """ if output is None: output = sys.stdout ...
5,312,719
def train(cfg: dict): """ Train a model for multiple epochs with a given configuration. """ global_seed = cfg.get('global_seed') if global_seed is not None: torch.manual_seed(global_seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False data = Tra...
5,312,720
def main(): """ Execute the examples. """ miller_rabin_is_prime(5) start, end = 2, 200 for n in range(start, end) + [randint(1000, 100000) for _ in range(100)]: probably_prime = miller_rabin_is_prime(n) if is_prime(n): if probably_prime: print 'PROBABLY PRIME...
5,312,721
def get_links_from_html(html_body): """ Extract all <a></a> links from html body :returns: list of dicts with links data :param html_body: """ from HTMLParser import HTMLParser links = [] from pip.index import HTMLPage class MyHTMLParser(HTMLParser): def handle_starttag...
5,312,722
def adj_to_networkx(graphs): """Convert adj matrices to networkx graphs.""" return [nx.from_numpy_array(g) for g in graphs]
5,312,723
async def add_datasource(request: Request, call_next): """ Attach the data source to the request.state. """ # Retrieve the datas ource from query param. source = data_source(request.query_params.get("source", default="jhu")) # Abort with 404 if source cannot be found. if not source: ...
5,312,724
def summary( data, var_names: Optional[List[str]] = None, fmt: str = "wide", kind: str = "all", round_to=None, include_circ=None, stat_funcs=None, extend=True, credible_interval=None, order="C", index_origin=None, skipna=False, coords: Optional[CoordSpec] = None, ...
5,312,725
def matrix_multiply(MM): """Multiplies a list of matrices: M[0] * M[1] * M[2]...""" P = MM[0] for M in MM[1:]: P = dot(P, M) return P
5,312,726
def urban_lookup(word): """ returns definitions for a given word from urban dictionary """ resp = requests.get(UD_URL % word) if resp.ok: # check for 200 doc = html.fromstring(resp.read()) return [d.text for d in doc.xpath('//div[@class="definition"]')] return []
5,312,727
def encode_sequences( sequences: List[str], vocab: Dict[str, int], target_size: Optional[int] = None, eos: int = -1, sos: Optional[int] = None, pad: Optional[int] = None, **kwargs: Any, ) -> np.ndarray: """Encode character sequences using a given vocab as mapping Args: seque...
5,312,728
def test_only_url(only_url_item: JSONDict) -> None: """Test validation of upload items without guid""" validated = UploadItem(**only_url_item) assert validated.dict() == only_url_item
5,312,729
def form_columns(form): """ :param form: Taken from requests.form :return: columns: list of slugified column names labels: dict mapping string labels of special column types (observed_date, latitude, longitude, location) to names of columns """ labels = {} ...
5,312,730
def build_dataloaders(config): """ Wrapper for build functions to other datasets. :return: DataLoaders for dataset """ # Initialize dataset dataset = None if 'MNIST' in config.dataset: dataset = torchvision.datasets.MNIST elif 'CIFAR100' in config.dataset: ...
5,312,731
def resolve_bbox_order(bbox, crs, size): """ Utility that puts the OGC WMS/WCS BBox in the order specified by the CRS. """ crs = pyproj.CRS(crs) r = 1 if crs.axis_info[0].direction != "north": r = -1 lat_start, lon_start = bbox[:2][::r] lat_stop, lon_stop = bbox[2::][::r] siz...
5,312,732
def _r(val): """ Convert val to valid R code """ if isinstance(val, str): # no quoting quote if val.startswith("quote("): return val return '"{0}"'.format(val) if val is True: return "TRUE" if val is False: return "FALSE" if isinstance(v...
5,312,733
def bin2int(buf): """the reverse of int2bin, convert a binary buffer to an integer""" x = 0 for b in bytearray(buf): x <<= 8 x |= b return x
5,312,734
def main() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]: """Vapoursynth filtering""" from vardefunc.noise import decsiz from vsutil import get_y src = JP_BD.clip_cut panorama = flt.panner_x(src, JP_BD.workdir.to_str() + r"/assets/ED/FGCBD_NCED1_panorama.png") denoise = decsiz(panorama, min...
5,312,735
def UrlSafeB64Decode(message): """wrapper of base64.urlsafe_b64decode. Helper method to avoid calling six multiple times for preparing b64 strings. Args: message: string or binary to decode Returns: decoded data in string format. """ data = base64.urlsafe_b64decode(six.ensure_binary(message)) re...
5,312,736
def crypto_box_open_afternm(ciphertext, nonce, k): """ Decrypts and returns the encrypted message ``ciphertext``, using the shared key ``k`` and the nonce ``nonce``. :param ciphertext: bytes :param nonce: bytes :param k: bytes :rtype: bytes """ if len(nonce) != crypto_box_NONCEBYTES...
5,312,737
def imei_parse_nibble(nibble): """Parse one nibble of an IMEI and return its ASCII representation.""" if nibble < 10: return chr(nibble + ord('0')) if nibble == 0xa: return '*' if nibble == 0xb: return '#' if nibble == 0xc: return 'C' if nibble == 0xd: ret...
5,312,738
def laplacianpyramid(gpyramid, f): """ Build Laplacian pyramid from Gaussian pyramid Args: gpyramid: Gaussian pyramid f: 2d filter kernel Returns: Laplacian pyramid, pyramid levels as (H, W) np.array in a list sorted from fine to coarse """ # # You code here ...
5,312,739
def check_command_succeeded(reply): """ Return true if command succeeded, print reason and return false if command rejected param reply: BinaryReply return: boolean """ from zaber.serial import BinarySerial, BinaryDevice, BinaryCommand, BinaryReply import time if reply.co...
5,312,740
def format_interval(seconds): """ Format an integer number of seconds to a human readable string.""" units = [ (('week', 'weeks'), 604800), (('day', 'days'), 86400), (('hour', 'hours'), 3600), (('minute', 'minutes'), 60), #(('second', 'seconds'), 1) ] result = [] ...
5,312,741
def hdf5_load_plotels(model, elements_group, encoding): """loads the plotels from an HDF5 file""" for card_type in elements_group.keys(): elements = elements_group[card_type] if card_type == 'PLOTEL': eids = _cast(elements['eid']) nodes = _cast(elements['nodes']).tolist()...
5,312,742
def make_arguments_parser(): """Build and return a command line agument parser.""" parser = ArgumentParser(description=__doc__, epilog="""CSS-HTML-JS-Minify: Takes a file or folder full path string and process all CSS/HTML/JS found. If argument is not file/folder will fail. Check Updates works on Python...
5,312,743
def split_on_comma(tokens): """Split a list of tokens on commas, ie ``,`` DELIM tokens. Only "top-level" comma tokens are splitting points, not commas inside a function or other :class:`ContainerToken`. :param tokens: An iterable of :class:`~.token_data.Token` or :class:`~.token_data.C...
5,312,744
def filter_grps(grps, rcs, irr_col, low, high, **kwargs): """ Apply irradiance filter around passsed reporting irradiances to groupby. For each group in the grps argument the irradiance is filtered by a percentage around the reporting irradiance provided in rcs. Parameters ---------- grps ...
5,312,745
async def get_weapon_plug_hashes(perk_socket_set: SocketSet) -> list[PerkColumn]: """ get perks for all random and origin perk sockets :param perk_socket_set: weapon's perk sockets :return: weapon perks as List of PerkColumn """ from readDB import query_plug_set plug_sets: list[PlugSet] = [...
5,312,746
def export_inventory_information(): """export the inventory search result to cvs, html or excel format.""" db_session = DBSession() export_results_form = ExportInventoryInformationForm(request.form) export_data = dict() export_data['export_format'] = export_results_form.export_format.data expor...
5,312,747
def decide_unsat(K: Set[CNFClause]) -> bool: """ Returns if given set of clauses is in CNF, or not :param K: Set of Clauses in CNF :return: bool, whether this formula is undecidable or not """ R: set[CNFClause] = set() S: set[CNFClause] = K while R != S: R = S S = Res(R) ...
5,312,748
def find(db, user): """ find the notelist :param db: :param user: :return: """ document = db.notelist.find_one({"_id": user}) return document
5,312,749
def clip(x, xmin, xmax, dtype=None): """ Clips (limits) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of :math:`[0, 1]` is specified, values smaller than 0 become 0, and values larger than 1 become 1. Note:...
5,312,750
def jump(distance, delta_piece_y): """ 跳跃一定的距离 """ # 计算程序长度与截图测得的距离的比例 scale = 0.945 * 2 / head_diameter actual_distance = distance * scale * (math.sqrt(6) / 2) press_time = (-945 + math.sqrt(945 ** 2 + 4 * 105 * 36 * actual_distance)) / (2 * 105) * 1000 ...
5,312,751
def get_mean_hourly_sleep_mr_df(sleep_profile, colnames): """ Creates summary df for mean hourly sleeping metabolic rate for each fly. Exported as sheet to excel. """ mr_hourly = sleep_profile.iloc[:,1::3] # sleep profile is split into top half: day; bottom half: night night_bool_list = [x >...
5,312,752
def get_files_in_traverse_dir(a_dir, patterns): # type: (str, str) -> List[str] """ return list of all files in directory which matches 'patterns' support Unix filename pattern matching ('*', '?', [seq], [!seq]) and multiple option in 'patterns' (space delimetered) """ return list(set([ # throw awa...
5,312,753
def characters(probabilities): """Turn a 1-hot encoding or a probability distribution over the possible characters back into its (most likely) character representation.""" return [id2char(c) for c in np.argmax(probabilities, 1)]
5,312,754
def system(t, state, u): """ differential system equation :param t: time :param state: current state :param u: input :return: derivative of the current state """ x = state[0] y = state[1] result = np.array([3 * x + 5 * y - 2 * x * y + 3 * x ** 2 - 0.5 * y ** 2, ...
5,312,755
def LR_classifier(train_set, train_labels, test_set, test_labels, n_way): """ Wrapper function which trains a logistic regression on train_set/train_labels and return the accuracy on test_set. Parameters: train_set -- torch.tensor (n_sample, n_feature), contains training data train_labels -- tor...
5,312,756
def json_file_content_check(package_info): """Check the content of json file.""" if package_info['category'] == '': logging.warning('The category of ' + package_info['name'] + ' package is lost.') return False if 'enable' not in package_info or package_info['enable'] == '': logging...
5,312,757
def movemap(Da, Db, nodes, com_a=None, com_b=None, tweens=12, clr_a=(0.,.5,1.), clr_b=(1.,0.5,0.), ax=None): """ Plot node trajectories on top of an onion skin background. The first four nodes are ignored, as those are supposed to be frame corners. """ # Start with an overla...
5,312,758
def debug(msg): """This is a function for debugging statements in jinja2 templates""" if args.DEBUG: return msg return ""
5,312,759
def bootstrap_tree(config): """Create the client directories tree.""" bootstrap_list = [ BootstrapDirectory("$data_path", "landscape", "root", 0755), BootstrapDirectory("$annotations_path", "landscape", "landscape", 0755)] BootstrapList(bootstrap_list).bootstrap( ...
5,312,760
def test_create_connection(): """ test case for method create_connection in SpackHelper """ assert isinstance(S.create_connection(), SparkSession) assert S.create_connection( ).conf.get('spark.some.config.option') == 'some-value'
5,312,761
def preprocess_image(x, mode='caffe'): """ Preprocess an image by subtracting the ImageNet mean. Args x: numpy.array of shape (None, None, 3) or (3, None, None). mode: One of "caffe" or "tf". - caffe: will zero-center each color channel with respect to the ImageNet da...
5,312,762
def calculate_metric(threshold, args): """ 给定阈值得到预测类别后,计算precision和recall,其中precision是avg_sample(hit_cnt/pred_cnt), recall是avg_sample(hit_cnt/label_cnt),在当前场景下label_cnt恒等于1 """ # 格式:label:pred_cls,pred_score;pred_cls,pred_score; # 78089261739417600:78089261739417600,0.995399; # 获取label_list...
5,312,763
def load_data(): """Load data from the Quora dataset.""" # Partition off part of the train data for evaluation with open(os.path.join('data', 'quora', 'train.csv'), 'r') as train_file: train_data = [row for row in csv.reader(train_file, delimiter=',', quotechar='"')][1:] random.shuffle(train...
5,312,764
def current_time() -> datetime: """Return timezone-aware current time as datetime.""" return datetime.now().astimezone()
5,312,765
def test_metamodel_callable_must_return_a_metamodel(): """ Test that meta-model callable must return an instance of TextXMetaModel. """ def invalid_metamodel_callable(): return 42 clear_language_registrations() register_language('test-lang', pattern='*.test', ...
5,312,766
def xml_list_music(xml_name): """ Create a XML (Music List) file with the content of the Mucic list in 'dict_artists'. XML (Music List) format: <music format="music-list"> <artist name="author-1"> <album title="album-1_1"> <track>track_1_1_1</track> ...
5,312,767
def Reynold(V, D): """ Calculate Reynold number Parameters ---------- V : float velocity D : float diameter Returns ------- Re : float Reynold number """ nu = 1.004e-6 # kinematic viscosity [m^2/s] Re = np.abs(V*D/nu) return Re
5,312,768
def build_lb_image_for_env_conda(mock_config_with_repo): """A fixture that installs an old version of matplotlib and latest version of requests to increase code coverage""" im = InventoryManager() lb = im.create_labbook('unittester', 'unittester', "containerunittestbookenvconda", ...
5,312,769
def compile(self): """Compile AssignNode.""" global register_index register_type = "" if '"' not in self.children[1].compile(): register_type = "$N" else: register_type = "$S" byte_code = register_type + "%s = " % register_index byte_code += self.children[1].compile() + "\...
5,312,770
def test_downsample_in_time(hera_uvh5, future_shapes): """Test the downsample_in_time method""" uv_object = hera_uvh5 if future_shapes: uv_object.use_future_array_shapes() uv_object.phase_to_time(Time(uv_object.time_array[0], format="jd")) # reorder to make sure we get the right value late...
5,312,771
def create_client(*args): """ Create an EC2 client for downstream use. Must have a valid AWS configuration for boto3 to use. :param args: optional profile name for the AWS shared config file. :return: returns a boto3 EC2 client. """ try: if len(args) == 0: client = boto3.Ses...
5,312,772
def Uint32ToUint8(z, lsb_first=True): """ Example: np.all(Uint32ToUint8([0x01020304, 0x05060708]) == np.array([4,3,2,1,8,7,6,5], 'uint8')) """ return BinToUint8(Uint32ToBin(z, lsb_first))
5,312,773
def solve(move_group, start_state, pose_goal, path_constraints): """Convenience function not used by the main tutorial""" move_group.set_start_state(start_state) move_group.set_pose_target(pose_goal) # Don't forget the path constraints! That's the whole point of this tutorial. move_group.set_path_c...
5,312,774
def _decode(encoding: Encoding, decoder: Decoder) -> List[int]: """Generic decoder using subcalsses to decode different formats. It works by nitializing a list of timestamps and the decoder with the initial timestamp from the encoding data structure. The stateful decoder is then called on all the valu...
5,312,775
def _load_python(test_dir, ctxs): """Loads the Python library and samples for the given APIs. Args: test_dir: The parent directory. ctxs: The list of Contexts to load. Returns: list: A list of Commands to run samples. """ sample_cmds = {} for ctx in ctxs: sample...
5,312,776
def test_spa_get(app, client): """ Test 'single-page-application' style redirects This uses json only. """ with capture_flashes() as flashes: with capture_registrations() as registrations: response = client.post( "/register", data='{"email": "dude@...
5,312,777
def merge_diff( initial_config=None, initial_path=None, merge_config=None, merge_path=None, saltenv="base", ): """ Return the merge diff, as text, after merging the merge config into the initial config. initial_config The initial configuration sent as text. This argument is ...
5,312,778
def test_1entry_bypass_queue_tv( dump_vcd, test_verilog ): """Single-Element Bypass Queue Test Vector Tests Directed performance tests for single element queue. We use the TestVectorSimulator to do some white box testing. """ test_vectors = [ # Enqueue one element and then dequeue it # enq.val enq....
5,312,779
def make_label(label_text): """ returns a label object conforming to api specs given a name """ return { 'messageListVisibility': 'show', 'name': label_text, 'labelListVisibility': 'labelShow' }
5,312,780
def ip_to_str(address): """Print out an IP address given a string Args: address (inet struct): inet network address Returns: str: Printable/readable IP address """ return socket.inet_ntop(socket.AF_INET, address)
5,312,781
def _empty_memory(memory_dim): """Get a empty memory, assuming the memory is a row vector """ return torch.zeros(1, memory_dim)
5,312,782
def initiate(): """The top-level method to serve as the entry point of T_System. This method is the entry point defined in `setup.py` for the `t_system` executable that placed a directory in `$PATH`. This method parses the command-line arguments and handles the top-level initiations accordingly. """ ...
5,312,783
def label_to_roi(label, expansion_mm=[0, 0, 0], return_as_list=False): """Generates a region of interest (ROI), defined by a starting index (z,y,x) and size (s_z, s_y, s_x). This can be used to crop images/labels. Args: label (sitk.Image | list): Binary label image/mask/structure to define to ROI ...
5,312,784
def delete_workspace(name: str, arango: ArangoClient) -> None: """Delete the workspace named `name`.""" sysdb = db("_system", arango=arango) if sysdb.has_database(name): sysdb.delete_database(name)
5,312,785
def get_topk_correct(outputs, targets, ks=(1,)): """ Computes the precision@K for the specified values of K """ maxk = max(ks) _, pred = outputs.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(targets.view(1, -1).expand_as(pred)) res = [] for k in ks: correct_k =...
5,312,786
def _create_spectrogram(signal: np.ndarray, should_graph: bool = False) -> np.ndarray: """Creates spectrogram for signal, and returns it. Shows graph for the signal with a Gaussian filter overlayed, the filtered signal, and the FFT of the signal. """ n = len(signal) # 128 ...
5,312,787
def update_env( state: sqm.states.RobotState, solver: KinematicSolver, *, reset: bool = False, ) -> None: """Updates the PyBullet environment/robot to the given state.""" for leg in state.legs: j_pre = f"{leg.leg.name.lower()}_j_" if reset: t_h = leg.hip_theta ...
5,312,788
def clear_txt_file(file_path: str): """ Clears the .txt file that contains the contacts. Raises a FileNotFoundError if file does not exist :param file_path: absolute or relative path to the datafile :returns: None """ if os.path.isfile(file_path): with open(file_path, mode='w') as dataf...
5,312,789
def test_reblocking(): """ Tests reblocking against known distribution. """ import scipy.stats def corr_data(N, L): """ Creates correlated data. Taken from https://pyblock.readthedocs.io/en/latest/tutorial.html. """ return np.convolve(np.random.randn(2 ** N),...
5,312,790
def get_rproj_czdisp(galaxyra, galaxydec, galaxycz, galaxygrpid, HUBBLE_CONST=70.): """ Compute the observational projected radius, in Mpc/h, and the observational velocity dispersion, in km/s, for a galaxy group catalog. Input should match the # of galaxies, and the output will as well. Based on FoF4 c...
5,312,791
def colormap_to_ev_blocks_equidistant(colormap, stops): """ For a given number of stops, the colormap is divided into equal length segments. The colors are sampled at the start and end of these segments. They are then used to create "blocks", a constant color for a range between two exposure values. ...
5,312,792
def turn_acs_into_acsK(actions_taken_so_far, all_samples, K, N, horizon): """ start with array, where each entry is (a_t) end with array, where each entry is (a_{t-(K-1)}..., a_{t-1}, a_{t}) """ #this will become [K-1, acDim] past_Kminus1_actions = actions_taken_so_far[-(K - 1):] #[K-1, ac...
5,312,793
def parse_scripting_log(script_type: str) -> Dict[str, Any]: """Parse a log to run to create a sequence of XEM commands.""" file_name = f"xem_{script_type}.txt" relative_path = os.path.join("src", "xem_scripts", file_name) absolute_path = os.path.normcase(os.path.join(get_current_file_abs_directory(), o...
5,312,794
def fetch_top_chapter_checkins(): """ Show checkin count of chapters in this week """ re = frappe.db.sql( """ SELECT sc.parent_chapter, c.sub_chapter, COUNT(*) AS checkin_count FROM `tabCheckin` c JOIN `tabSub Chapter` sc ON c.sub_chapter=sc.name WHERE c.creation ...
5,312,795
def Entry_Callback( e ) : """Called whenever the <Return> key is pressed in certain entry window.""" Replot( )
5,312,796
def get_api_base(): """ Get the api base url :return: string """ from bitcodin import api_base return api_base
5,312,797
def parallelwork(fn, inputq, outputq): """Run unary `fn` in parallel on data taken from `inputq` and save results to `outputq`. :param fn: function :param inputq: multiprocessing.Queue :param outputq: multiprocessing.Queue """ while True: i, x = inputq.get() if i is None: ...
5,312,798
def simple_reduce_error( filename, conservative, precision, target_error, convergence_rate_scale_factor, ): """Determine points to add (first) or extend (second) to meet target error. FILENAME is the data file containing lambda, dhdl_average, and error_est. """ points = np.loadtxt(f...
5,312,799