content
stringlengths
22
815k
id
int64
0
4.91M
def get_mxnet_module_arg_params(x): """ given parameter name, get the updated value from mxnet module arg_params :param x: parameter values to (e.g. kernels, bias) :return: updated parameter values """ # retrieve from bind values first, which is up to date with # arg_params in mxnet mod...
53,200
def psnr_denoise(y_true, y_pred): """"Calculating peak signal-to-noise ratio (PSNR) between two images.""" return tf.image.psnr(y_pred, y_true, max_val=1.0)
53,201
def test_ast_eval(): """ Ensure that `ast.literal_eval()` doesn't get caught. """ assert noeval.main([build_path("fixture_05.py")]) == 0
53,202
def _count_files_to_amber(tumor_counts, normal_counts, work_dir, data): """Converts tumor and normal counts from GATK CollectAllelicCounts into Amber format. """ amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd.get_sample_name(data)) ...
53,203
def humanize_duration(time_delta, show=None, sep=" "): """ Humanize a timedelta object. :param time_delta: the timedelta object to humanize. :param sep: specify a separator for days, hours, minutes and seconds in the final string. :return: a dict with keys: ``days``, ``hours``, ``mi...
53,204
def bind(function_name, function, method): """ Helper function to bind the function and class method defined in a custom indicator module to the active pandas_ta instance. Args: function_name (str): The name of the indicator within pandas_ta function (fcn): The indicator function ...
53,205
def process_stats(args): """Process the VPP Stats. :param args: Command line arguments passed to VPP PAPI Provider. :type args: ArgumentParser :returns: JSON formatted string. :rtype: str :raises RuntimeError: If PAPI command error occurs. """ try: stats = VPPStats(args.socket)...
53,206
def reload(cnx): """Reload kernel modules for `ath9k` Args: cnx (Connection): fabric connection context """ custom_modules = [ "cfg80211", "mac80211", "ath", "ath9k_hw", "ath9k_common", "ath9k", ] for mod in reversed(custom_modules): ...
53,207
def authenticate(): """ Authenticates user, unlocks the vault and exports session token """ if not is_user_logged_in(): token = log_in_and_get_token() export_token(token) elif is_vault_locked(): token = unlock_and_get_token() export_token(token)
53,208
def print_node_health(report): """ Prints a node health report """ if report is None: print('? Report not implemented.') print() return print('Overall Status:') print('\u2705 Healthy' if report.is_healthy else '\u274C Unhealthy') print('Checklist:') print(report.message) print()
53,209
def test_rules(): """Test if RULES contain attributes as expected.""" assert RULES.git_folder assert RULES.conda_cmds assert RULES.conda_cmds.remove assert RULES.conda_cmds.export assert RULES.conda_cmds.create assert RULES.conda_cmds.clone assert RULES.conda_cmds.restore assert RULE...
53,210
def loads(s, **kwargs): """ Deserialize an object from a bytestring. :param bytes s: the bytestring to deserialize :param kwargs: keyword arguments passed to :class:`CBORDecoder` :return: the deserialized object """ with BytesIO(s) as fp: return CBORDecoder(f...
53,211
def TsvToXY(filePath): """This method reads .tsv file and returns the data, XY split in a tuple""" with open(filePath, 'r') as file: lines = list(csv.reader(file, delimiter='\t')) data = [] for line in lines: # for each line, split the PCM into a list listedLine = [] for column in line[:-1]: if len...
53,212
def nondimensional(): """ Factory associated with Nondimensional. """ return Nondimensional()
53,213
def attach(file_id, trunk, branch=None): """Insert a branch of directories on its trunk.""" if branch is None: branch = file_id.filename parts = branch.split('/', 1) if len(parts) == 1: # branch is a file if file_id: found = False for _, fid in trunk[FILE_MARKER...
53,214
def rest_target_debug_resume(args): """ :param argparse.Namespace args: object containing the processed command line arguments; need args.target :raises: IndexError if target not found """ for target in args.target: rtb, rt = _rest_target_find_by_id(target) rtb.rest_tb_target_d...
53,215
def patch_configuration(client, configuration_id, patches): """ :param patches: List of patches in format [ {"op": op, "path": path, "value": value}, {"op": op, "path": path, "value": value} ] :return: requests Response """ data = [] data = patches return client._patch("/compa...
53,216
def distributed_grads_and_ops_dedicated_workers( task_id, is_chief, num_worker_tasks, num_ps_tasks, master, checkpoint_dir, loss, accuracy, layer_collection): """Minimize loss with a synchronous implementation of K-FAC. Different workers are responsible for different parts of K-FAC's Ops. The first 60% o...
53,217
def f_next_point_zeta(f2new: float,free_energyb: np.ndarray,za: np.ndarray,zb: np.ndarray,cova: np.ndarray,covb: np.ndarray,f1new: float,fa: np.ndarray,fb: np.ndarray) -> float: """ Free energy difference function of the next point to be optimized if the Number of points is greater than 1 Specialized for t...
53,218
async def async_setup(opp, config): """Set up ZHA from config.""" opp.data[DATA_ZHA] = {} if DOMAIN not in config: return True conf = config[DOMAIN] opp.data[DATA_ZHA][DATA_ZHA_CONFIG] = conf if not opp.config_entries.async_entries(DOMAIN): opp.async_create_task( o...
53,219
def isort(): """Runs isort.""" _sorted = subprocess.call(['isort', '--gitignore', '.', ]) == 0 if _sorted: print('OK') sys.exit(_sorted)
53,220
def choice(*args, **kwargs): """ Wraps numpy random.choice call in ASPIRE Random context. """ seed = None if "seed" in kwargs: seed = kwargs.pop("seed") with Random(seed): return np.random.choice(*args, **kwargs)
53,221
def convert_state_quara_to_qiskit( quara_state: State, ) -> np.ndarray: """converts Quara State to densitymatrix in Qiskit. Parameters ---------- quara_state: State Quara State. Returns ------- np.ndarray Qiskit density matrix of quantum state. """ qiskit_state...
53,222
def plot(df): """One click plotting function to dump all registration data into plots.""" for elx in df["elastix_trans"]: plt.suptitle("Downsample") plt.imshow(sitk.GetArrayFromImage(elx.GetResultImage())) plt.show() for img in df["region"]: plt.suptitle("Region") pl...
53,223
def camel2snake(name): """ Args: name (str): camelCase Returns: str: snake_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
53,224
def UpdateIssueWithIssueGenerator(issue_id, issue_generator, reopen=False): """Updates an existing issue with a given issue generator. Args: issue_id: Id of the issue to be updated. issue_generator: A FlakyTestIssueGenerator object. reopen: True to reopen a closed bug, otherwise False. """ issue = ...
53,225
def create_state_types( tator_api, project) -> None: """ """ state_types = tator_api.get_state_type_list(project=project) assert len(state_types) == 0 media_types = tator_api.get_media_type_list(project=project) media_type_ids = [media_type.id for media_type in media_types] ...
53,226
def calc_nu_b(b): """Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss. This is in cycles per second not radians per second; i.e. there is a 2π in the denominator: ν_B = e B / (2π m_e c) """ return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c)
53,227
def test_mismatched_shape_exception(): """Tests that the expected exception is raised for cloud and convection cubes of different shapes.""" cloud = set_up_variable_cube( np.ones((2, 2)).astype(FLOAT_DTYPE), name="low_and_medium_type_cloud_area_fraction", ) convection = set_up_variab...
53,228
def checking_if_table_exists(): """ Checking if table exists or not """ conn = connect(dbpath) c = conn.cursor() try: c.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name='webhooks'; """) res = c.fetchall() ...
53,229
def can_represent_dtype(dtype): """ Can we build an AdjustedArray for a baseline of `dtype``? """ return dtype in REPRESENTABLE_DTYPES or dtype.kind in STRING_KINDS
53,230
def calc_apply(operator, args): """Apply the named operator to a list of args. >>> calc_apply('+', as_scheme_list(1, 2, 3)) 6 >>> calc_apply('-', as_scheme_list(10, 1, 2, 3)) 4 >>> calc_apply('-', as_scheme_list(10)) -10 >>> calc_apply('*', nil) 1 >>> calc_apply('*', as_scheme_l...
53,231
def build_mpo_list(single_mpo, site_num, regularize=False): """ build MPO list for MPS. :param single_mpo: a numpy ndarray with ndim=4. The first 2 dimensions reprsents the square shape of the MPO and the last 2 dimensions are physical dimensions. :param site_num: the total number of sites :para...
53,232
def efun_git_status(paths: ldmud.Array) -> ldmud.Array: """ SYNOPSIS mixed** git_status(string* paths) DESCRIPTION For the given directories or files list any changes that are not committed. Returns an array for each such file: [0] Repository ...
53,233
async def test_nersc_mover_run(config, mocker): """Test the NerscMover does the work the nersc_mover should do.""" logger_mock = mocker.MagicMock() p = NerscMover(config, logger_mock) p._do_work = AsyncMock() await p.run() p._do_work.assert_called()
53,234
async def tx_t(context): """ PagerMaid universal translator. """ reply = await context.get_reply_message() message = context.arguments lang = 'zh' if message: pass elif reply: message = reply.text else: await context.edit("出错了呜呜呜 ~ 无效的参数。") return try: ...
53,235
def resize_convex_hull_polygon(_convex_hull_points, _resize_ratio): """ 对凸包的多边形进行缩放 Args: _convex_hull_points: 凸包多边形的轮廓 _resize_ratio: 缩放比例 Returns: 缩放后的点 """ center_point = np.mean(_convex_hull_points, axis=0) diff_points = _convex_hull_points - center_point r ...
53,236
def convert_xyz_to_rgb(source_color_xyz: tuple) -> tuple: """ Converts a color from the CIE XYZ 1931 to the RGB colorspace. Args: source_color_xyz: a tuple with X, Y and Z values of the color. Returns: a tuple with the R, G and B values of the color. """ logger.trace("Convert...
53,237
def _lower_triangular_solve_sparse(M, rhs, dotprodsimp=None): """Solves ``Ax = B``, where A is a lower triangular matrix. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control exp...
53,238
def clip_to_frames_all(lena_mappings, human_mappings, consider_overlapped, frame_length=10): """ Returns the accumulated labelled frames for all 60 clips. """ total_lena = [] total_human = [] for i in range(1, 61): y_lena, y_human = clip_to_frames_single(i, lena_mappings, human_mappings, ...
53,239
def _cart_id(request): """ If the user is logged in, retrieve the user associated cart_id from the database. If the user is anonym, then use the session to retrieve the cart_id. """ if request.session.get(CART_ID_SESSION_KEY, '') == '': request.session[CART_ID_SESSION_KEY] = _genera...
53,240
def flatpage_nav(_): """ Context processor which adds data required for the main navigation of flatpages to the context. """ categories = flatpages_models.Category.objects.all() pages = flatpages_models.Flatpage.objects_without_category.all() return {'all_categories': categories, 'pages_withou...
53,241
def ortho(left, right, bottom, top, znear, zfar): """Create orthographic projection matrix Parameters ---------- left : float Left coordinate of the field of view. right : float Right coordinate of the field of view. bottom : float Bottom coordinate of the field of view....
53,242
def say_it(text, file): """Generates audio file containing text-to-speach conversion""" # Instantiates a client client = texttospeech.TextToSpeechClient() # Set the text input to be synthesized synthesis_input = texttospeech.types.SynthesisInput(text=text) # Build the voice request, select th...
53,243
def to_str(bit_str): """Transform bit string in a string of characters""" chars = [] for i in range(int(len(bit_str) / 8)): byte = bit_str[i * 8:(i + 1) * 8] if byte == "11111111": break chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(cha...
53,244
def embed(parent_locals=None, parent_globals=None, exec_lines=None, remove_pyqt_hook=True, n=0): """ Starts interactive session. Similar to keyboard command in matlab. Wrapper around IPython.embed """ import IPython if parent_globals is None: parent_globals = get_parent_frame...
53,245
def get_scale_factor(value_dict, max_length=os.get_terminal_size().columns): """ Gets the scale factor from a dict of keys with numerical values """ max_value = max(value_dict.values(), key=abs) try: scale = max_length / abs(max_value) except ZeroDivisionError: scale = 1 retu...
53,246
def compute_coeffs(track_y, track_t): """ Least squares polynomial fit to obtain step size. Parameters ---------- track_y : 1-D array with shape (3, ) Array containing the three smallest function values from applying either forward or backward tracking. Mus...
53,247
def get_debug_switch(): """The debug switcher >>> import os, jumon >>> os.environ['JUMON_DEBUG'] = 'True' >>> jumon.get_debug_switch() True >>> os.environ['JUMON_DEBUG'] = '' >>> jumon.get_debug_switch() None >>> value = os.environ.pop('JUMON_DEBUG') >>> jumon.get_debug_swit...
53,248
def test_project_repo_for_path(project_a): """ Return the first repo found with a checkout path that contains the given path. """ repos = [ RepositoryFactory.create(type="file", project=project_a, url="testrepo%s" % i,) for i in range(0, 3) ] path = os.path.join(repos[1].chec...
53,249
def test_model_supports_lt_with_expected_types(model_with_ordered_bytes): """ Assert that any of the model types support "less than" comparisons against expected types. """ model_type, less_than_bytes, greater_than_bytes = model_with_ordered_bytes model = model_type(less_than_bytes) assert mode...
53,250
async def test_route_message_with_existing_route(base_central_system, boot_notification_call): """ Test if the correct handler is called when routing a message. Also test if payload of request is injected correctly in handler. """ @on(Action.BootNotifica...
53,251
def PyTmYDSminusYDS(y1, d1, s1, y2, d2, s2): """ Get difference between two year-day-seconds entries NOTE: the original Caris function doesn't take leap seconds into account Parameters ---------- y1: int, year 1 d1: int, day 1 s1: int, seconds 1 y2: int, year 2 d2: int, day 2 ...
53,252
def random_pos(z_offset=0.2): """generate random position for dropping sphare Parameters ---------- z_offset : float, optional z offset, by default 0.2 Returns ------- pos list [x, y, z] random position """ pos = [np.random.randn() * 0.05, np.random.rand...
53,253
def filter2D(input, kernel, border_type='reflect', normalized=False): """ Convolve a tensor with a 2d kernel. """ if not isinstance(input, torch.Tensor): raise TypeError("Input border_type is not torch.Tensor. Got {}" .format(type(input))) if not isinst...
53,254
def get_all(ip_string): """ @ date: 2017-12-2 @ author: wxw @ function: 接口函数,产生num个线程,在队列中取出IP进行爬取 @ input: C段地址 如:182.40.12 @ output: 完成标志 0 (int) """ global queue_ip, mutex_href_get, mutex_href_put threads = [] # 线程数量 num = THREAD_NUM class_ip = ip_string proxy_ip...
53,255
def scale(df, resolution=0.5): """ :param df: 5d-array [sample, steps, height, width, channels] :param resolution: float (0,1) """ df = ndimage.zoom(input=df, zoom=(1, 1, resolution, resolution, 1), order=1) print("Scaled") return df
53,256
def execute_coverage(): #pragma: no cover """Run coverage for the whole project""" #An instance of the configuration config = Configuration.get_instance() coverage_config = os.path.join(config.base_dir, ".coveragerc") coverage_run_cmd = "coverage run --append --rcfile=%s %s " % (coverage_config, con...
53,257
def view_image(): """ View a Fullscreen version of an Image - called from Reports """ try: _id = request.args[0] except: return "Need to provide the id of the Image" table = s3db.doc_image record = db(table.id == _id).select(table.name, ...
53,258
def bits_ip_to_str(bit_ip : bitarray) -> str: """ 将比特形式的ip转成字符串形式,形如 '192.168.3.5' """ bytes_ip = bit_ip.tobytes() ip_num_list = struct.unpack('!BBBB', bytes_ip) str_ip = '' # 首次循环标志,如果不是首次循环的话就加一个'.' first_flag = 1 for i in range(0,4): if(1-first_flag): str_ip += '.' ...
53,259
def resolve_user_by_user_id(slack_wrapper, user_id): """ Resolve a user id to an user object. """ return slack_wrapper.get_member(parse_user_id(user_id))
53,260
def get_handler( theme: str, # noqa: W0613 (unused argument config) custom_templates: Optional[str] = None, setup_commands: Optional[List[str]] = None, **config: Any, ) -> PythonHandler: """Simply return an instance of `PythonHandler`. Arguments: theme: The theme to use when rendering ...
53,261
def extract_temperature( df, value_threshold = 0, grad_threshold = 10, curve_threshold = 1e5, side = 'high', mask_window = 75, ): """ Finds the temperature coefficient from a PL curve. Performs a linear fit on the log of PL spectra on the low or high energy side. The fit is perfo...
53,262
def near_eye_init( shape: tuple, is_complex: bool = False, noise: float = 1e-3 ) -> Tensor: """ Initialize an MPS core tensor with all slices close to identity matrix Args: shape: Shape of the core tensor being initialized. is_complex: Whether to initialize a complex core tensor. ...
53,263
def extractPolygon2Snap2FromNDVI(NDVI, LatLon, NDVI_tresh = 0, path = 'Polygon2Snap2.kml'): """ Function to extract Polygon2Snap2 from a NDVI image @params: NDVI - Required: 2d numpy array of NDVI LatLon - Required: 3d (rowsxcolsx2) numpy array with latitudes and longitudes of the ND...
53,264
def stft( # pylint: disable=unused-argument signal, ax=None, limits=None, log=True, colorbar=True, batch=0, sample_rate=None, stft_size=None, stft_shift=None, x_label=None, y_label=None, z_label=None, z_scale=None, ): """ Plots a spectrogram from an stft signal as input. This is a wrapp...
53,265
def main(args): """ The mainpoint, the decorator makes this module resolvable by reflect.qual() used by our Function argument type. Here we define the steps of our processing and we execute them. """ directory_names = [fp.FilePath(name) for name in args[2:]] results = fp.FilePath(args[1]) ...
53,266
def match_text(pattern: str) -> Predicate: """ predicate for filtering messages which text matches the given regex :param pattern: regex to match :type pattern: str :return: Predicate :rtype: Predicate """ return match(pattern, "text")
53,267
def create_optimizer_config(args: argparse.Namespace, source_vocab_sizes: List[int]) -> OptimizerConfig: """ Returns an OptimizerConfig. :param args: Arguments as returned by argparse. :param source_vocab_sizes: Source vocabulary sizes. :return: The optimizer type and its parameters as well as the ...
53,268
def centerWindow(pdf, flag): """Set the center window flag.""" libc.pycpdf_centerWindow(pdf.pdf, flag) checkerror() return
53,269
def compute_lane_following_features( scene_df: pd.DataFrame, agent_list: list, precomputed_lanes: pd.DataFrame, raw_data_format: list, map_inst: ArgoverseMap, seq_id: int, obs_len: int, precomputed_physics: pd.DataFrame, # Configurable constants num_points: int = 7, # Number of p...
53,270
def identify_operating_system(): """identify current operating system Returns: (str): 'Windows', 'Linux', or 'Darwin' for mac """ return platform.system()
53,271
def main(): """This is tacky""" args = get_args() for line in args.file: word1, word = line.split() line_no = abs(len(word1) - len(word)) char = list(zip(word1, word)) dist = 0 for pre, post in char: if pre != post: dist += 1 tot_...
53,272
def vlog_exd(v:np.ndarray,t:np.ndarray,FileHeader:dict): """ Interpolation function used in genereatevmodel2 """ dt=FileHeader['dt'] nt=FileHeader['ns'] t2 = np.arange(0,nt*dt,dt) return np.interp(t2,t,v)
53,273
def unpad(outputs, lengths): """Unpads a padded batch of waveforms to their initial lengths args: outputs ([B, num_samples_max] array): padded waveforms lens (list of ints): initial lengths before padding in features space. This needs to be multiplied by hop length to...
53,274
def quote_preview_pdf(request, pk): """ This view returns a preview of our PDF file for a given quote """ # we get the selected item to use as the "object" context to be able to have some mockup data quote_instance = invoice.models.Quote.objects.get(pk=pk) quote_pdf_name = "quote-%s.pdf" % str(quote...
53,275
def check_uniq(X): """Checks whether all input data values are unique. Parameters ---------- X: array-like, shape (n_samples, ) Vector to check whether it cointains unique values. Returns ------- bool """ s = set() return not any(x in s or s.add(x) for x in X)
53,276
def print_field_def(field): """ Print the C type from a field """ # check if there are any upper case letters in the field name assert not any(a.isupper() for a in field.name), "%r field contains uppercase letters" % field.name type_name = field.type # detect embedded ty...
53,277
def PrettyPrint(oData=None, hOutputFile=None, bToConsole=True, nIndent=0, sPrefix=None, bHexFormat=False): """ | **Function:** **PrettyPrint** Wrapper function to create and use a ``CTypePrint`` object. This wrapper function is responsible for printing out the content to console and to a file (depending on ...
53,278
def _get_object(lst, _id): """ Internal function to grab data referenced inside response['included'] """ for item in lst: if item['id'] == _id: return item
53,279
def test_install_special_deps(venv, mocker, actioncls): """ Test that nothing is called when there are no deps """ action = actioncls(venv) venv.deps = ["foo-package", "foo-two-package"] mocker.patch.object(os, "environ", autospec=True) mocker.patch("subprocess.Popen") result = tox_test...
53,280
def cli_execution(): """read, parse, and execute cli arguments """ parser = argparse.ArgumentParser( prog="imgproc.py", formatter_class=argparse.RawTextHelpFormatter, description="python package providing functions of image process.\n" + "Output data is generated in 'cv2' directory under c...
53,281
def projected_projectedLinearEccentricity(a,e,W,w,inc): """ Args: a (numpy array): semi-major axis in AU e (numpy array): eccentricity W (numpy array): Longitude of the Ascending Node in Radians w (numpy array): Argument of periapsi...
53,282
def isAntiCapability(capability): """Returns True if capability is an anticapability; False otherwise.""" if isChannelCapability(capability): (_, capability) = fromChannelCapability(capability) return isCapability(capability) and capability[0] == '-'
53,283
def parse_args(): """ Parse input arguments """ global arguments parser = argparse.ArgumentParser( description='extract all the called apis from md or reST files.') parser.add_argument( 'dir', type=str, help='travel all the files include this directory', d...
53,284
def decrypt_accession_id(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. <http://flask.pocoo.org/docs/1.0/api/#flask.Request> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` ...
53,285
def search_astroph(keywords, arxiv_channel, old_id=None): """ do the actual search though astro-ph by first querying astro-ph for the latest papers and then looking for keyword matches""" today = dt.date.today() day = dt.timedelta(days=1) max_papers = 1000 # we pick a wide-enough search r...
53,286
async def test_beta_version_beta_week_pagination( aresponses, event_loop, docker_response_beta_week_page1, docker_response_beta_week_page2, ): """Test docker beta during beta week.""" aresponses.add( "registry.hub.docker.com", "/v2/repositories/homeassistant/home-assista...
53,287
def _parse_args(argv): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--dataset", help="""Dataset to use for training and evaluation. """, required=True, ) parser.add_argument( "--job-dir", help="Ou...
53,288
def make_cdl_pars_data_from_linregress( Cdl_dataprep: pd.DataFrame, xcol="scanrate", ycol="j_A_cm2", grpbykeys=[EvRHE, "SweepType"], ) -> Tuple[pd.DataFrame, pd.DataFrame]: """ Parameters ---------- Cdl_dataprep : pd.DataFrame A frame that is prepared from the N2_CV raw data. ...
53,289
def increment_version(image_name: str, current_version: str, increment: str) -> str: """ :brief: increment app version. :param: current_version - current app version :param: increment - number to add to minor part of the current version :example: number - 2, 2+ 0.1.40(current version) = 0.1.42 :...
53,290
def getfrom(v): """ pass through function for using the filter_for decorator directly """ return v
53,291
def projected_distance(ra1, ra2, dec1, dec2): """ Function that returns the projected distance (in arcminutes) between two points. """ if ra1 == ra2 and dec1 == dec2: return 0.0 else: dist = math.acos(math.sin(deg2rad(dec1)) * math.sin(deg2rad(dec2)) + math.cos(deg2rad(dec1)) * math.cos(deg2r...
53,292
def test_profile(tmpdir): """ Check whether we can call sim.profile() and whether it saves profiling data to th expected files. """ os.chdir(str(tmpdir)) sim = barmini() sim.profile('run_until(1e-12)') os.path.exists('barmini.prof') sim.profile('relax()', filename='foobar.prof', so...
53,293
def get_dishes(restaurant, data): """ :type restaurant: meican.models.Restaurant :type data: dict :rtype: list[meican.models.Dish] """ sections = {} for section_data in data.get("sectionList", []): section = Section(section_data) sections[section.id] = section dishes = []...
53,294
def hindered_rotor_scans( zma, spc_info, mod_thy_info, scn_run_fs, scn_save_fs, rotors, tors_model, method_dct, overwrite, saddle=False, increment=0.5235987756, retryfail=True): """ Perform scans over each of the torsional coordinates """ if tors_mode...
53,295
def cut_into_cells(input_path, output_path, labels_source, image_source, prediction_features, cell_shape, __test__=False, verbose=False): """ Divides a large image into cells fit for training using the data in the geojsons. :return X: the image data returned cut into cells as de...
53,296
def get_remote_output_files(partitions, username, destination_dict): """ Collects partition results once estimation is finished. :param partitions: String. List containing aws partition addresses. :param username: String. aws user name. :param destination_dict: String. Folder where results are save...
53,297
def test_search_view(product_fixture): """Creates a test client. Make a request on the URL retrieved using the reverse () function. Check that the HTTP status code is 200. Check that the template used is the expected one""" client = Client() path = reverse("product-search") response = client.get(pat...
53,298
def setup_logger(level): """ Setup a logger for the REST handler """ logger = logging.getLogger('splunk.appserver.service_account_keys_rest_handler.rest_handler') logger.propagate = False # Prevent the log messages from being duplicated in the python.log file logger.setLevel(level) log_fil...
53,299