content
stringlengths
22
815k
id
int64
0
4.91M
def is_anaconda_5(): """ anaconda 5 has conda version 4.4.0 or greater... obviously :/ """ vers = conda_version() if not vers: return False ma = vers['major'] >= 4 mi = vers['minor'] >= 4 return ma and mi
5,328,800
def mkdir(path): """create a single empty directory if it didn't exist Parameters: path (str) -- a single directory path """ if not os.path.exists(path): os.makedirs(path)
5,328,801
def relay_array_map(c, fn, *array): """Implementation of array_map for Relay.""" assert fn.is_constant(Primitive) fn = fn.value if fn is P.switch: rfn = relay.where else: rfn = SIMPLE_MAP[fn] return rfn(*[c.ref(a) for a in array])
5,328,802
def output_to_csv(results, results_file_name): """ Output a line to a CSV file. """ with open(results_file_name, mode='a') as results_file: writer = csv.writer(results_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(results)
5,328,803
def test_StructlogUtils_graypy_structlog_processor( structlog_utils, event_kwargs ): """ Tests if event dictionary can be converted to a Graylog handler compatible format, to be passed as arguments/keyword arguments # C1: Check that the position-based arguments are formatted correct # c2: ...
5,328,804
def select_sort(alist): """ 选择排序:从无序队列中选择最小的放到前面去,有序部分和无序部分 首先认为最小的元素就是第一个元素,不断比较更新这个min的数值 """ for j in range(0, len(alist)-1): min_index = j # 因为j要和剩余的部分作比较也就是从j+1到最后一个元素,n的索引为n-1,闭区间所以到n for i in range(j+1, len(alist)): if alist[min_index] > alist[i]:...
5,328,805
def get_multi_objects_dict(*args, params=None): """Convertir un array de objetos en diccionarios""" object_group = [] result = {} for data_object in args: if params is not None and params['fields']: fields = params['fields'] else: fields = [attr for attr in data_o...
5,328,806
def assert_never_inf(tensor): """Make sure there are no Inf values in the given tensor. Parameters ---------- tensor : torch.tensor input tensor Raises ------ InfTensorException If one or more Inf values occur in the given tensor """ try: assert torch.isfinite(...
5,328,807
def aspuru(weights, x, wires, n_layers=1): """ Circuits ID = 5 in arXiv:1905.10876 paper :param weights: trainable weights :param x: input, len(x) is <= len(wires) :param wires: list of wires on which the feature map acts :param n_layers: number of repetitions of the first layer """ data_size = len(x)...
5,328,808
def test_function_ping_now_bytes(): """ Picking the 'ping_now' function and return as bytes. """ from btu.manual_tests import ping_now queue_args = { "site": frappe.local.site, "user": frappe.session.user, "method": ping_now, "event": None, "job_name": "ping_now", "is_async": True, # always true; we ...
5,328,809
def test_missing_data(): """Test loading and parsing invalid json file; missing data fields.""" file = open('tests/json/buienradar_missing.json', 'r') data = file.read() file.close() latitude = 51.50 longitude = 6.20 result = parse_data(data, None, latitude, longitude, usexml=False) pri...
5,328,810
def post_equals_form(post, json_response): """ Checks if the posts object is equal to the json object """ if post.title != json_response['title']: return False if post.deadline != json_response['deadline']: return False if post.details != json_response['details']: retu...
5,328,811
def get_shield(plugin: str) -> dict: """ Generate shield json for napari plugin. If the package is not a valid plugin, display 'plugin not found' instead. :param plugin: name of the plugin :return: shield json used in shields.io. """ shield_schema = { "color": "#0074B8", "la...
5,328,812
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == expectedUN and password == expectedPW
5,328,813
def Lambda(t, y): """Original Arnett 1982 dimensionless bolometric light curve expression Calculates the bolometric light curve due to radioactive decay of 56Ni, assuming no other energy input. t: time since explosion in days y: Arnett 1982 light curve width parameter (typical 0.7 <...
5,328,814
def vectordump(): """Dump all vector data to ``.csv`` files. """ client = MongoClient(mongoUri, tz_aware=True) db = client.fisb currentPath = '.' # Delete any existing .csv files so we don't get confused as # to what is new and what is old. for x in OUTPUT_FILES: csvPath = os.p...
5,328,815
def get_utcnow_time(format: str = None) -> str: """ Return string with current utc time in chosen format Args: format (str): format string. if None "%y%m%d.%H%M%S" will be used. Returns: str: formatted utc time string """ if format is None: format = "%y%m%d.%H%M%S" ...
5,328,816
def test_search(script): """ End to end test of search command. """ output = script.pip('search', 'pip') assert ( 'The PyPA recommended tool for installing ' 'Python packages.' in output.stdout )
5,328,817
def repair_branch(cmorph, cut, rmorph, rep, force=False): """Attempts to extend cut neurite using intact branch. Args: cmorph (treem.Morph): cut morphology. cut (treem.Node): cut node, from cmorph. rmorph (treem.Morph): repair morphology. rep (treem.Node): undamaged branch start...
5,328,818
async def test_create_read(http_client): """Create a new product and read it.""" name, description = "Some item name", "Some item description" prod_id = await create_product(http_client, name=name, description=description) read_resp = await http_client.get(f"/products/{prod_id}") assert read_resp.s...
5,328,819
def ValidateDisplayName(display_name): """Validates the display name.""" if display_name is not None and not display_name: raise exceptions.InvalidArgumentException( '--display-name', 'Display name can not be empty.')
5,328,820
def parse_patient_dob(dob): """ Parse date string and sanity check. expects date string in YYYYMMDD format Parameters ---------- dob : str dob as string YYYYMMDD Returns ------- dob : datetime object """ try: dob = datetime.datetime.strptime(dob, '%Y%m%d')...
5,328,821
def us2cycles(us): """ Converts microseconds to integer number of tProc clock cycles. :param cycles: Number of microseconds :type cycles: float :return: Number of tProc clock cycles :rtype: int """ return int(us*fs_proc)
5,328,822
def test_DCAFFT_error(noise_dataset): """Test that a DCAFFT raises an error for d>1. """ with pytest.raises(ValueError): X = noise_dataset model = DCAFFT(d=2, T=10) model.fit(X)
5,328,823
def date_range(begin_date, end_date): """ 获取一个时间区间的list """ dates = [] dt = datetime.datetime.strptime(begin_date, "%Y-%m-%d") date = begin_date[:] while date <= end_date: dates.append(date) dt = dt + datetime.timedelta(1) date = dt.strftime("%Y-%m-%d") return...
5,328,824
def scalar(name): """ Create a scalar variable with the corresponding name. The 'name' will be during code generation, so should match the variable name used in the C++ code. """ tname = name return symbols(tname)
5,328,825
def add(number1, number2): """ This functions adds two numbers Arguments: number1 : first number to be passed number2 : second number to be passed Returns: number1*number2 the result of two numbers Examples: >>> add(0,0) 0 >>> add(1,1) 2 >>> add(1.1,2.2) ...
5,328,826
def warn_and_skip(message): """ Prints warning and skips the test """ warnings.warn(message) pytest.skip(message)
5,328,827
def calculate_timeout(start_point, end_point, planner): """ Calucaltes the time limit between start_point and end_point considering a fixed speed of 5 km/hr. Args: start_point: initial position end_point: target_position planner: to get the shortest part between start_point and ...
5,328,828
def overview(request): """Returns the overview for a daterange. GET paramaters: * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y) Returns an overview dict with a count for all action types. """ form = OverviewAPIForm(request.GET) if not form.is_valid(): return {'success': False, 'er...
5,328,829
def func_parallel(func, list_inputs, leave_cpu_num=1): """ :param func: func(list_inputs[i]) :param list_inputs: each element is the input of func :param leave_cpu_num: num of cpu that not use :return: [return_of_func(list_inputs[0]), return_of_func(list_inputs[1]), ...] """ cpu_cores = mp.c...
5,328,830
def get_mean(jsondata): """Get average of list of items using numpy.""" if len(jsondata['results']) > 1: return mean([float(price.get('price')) for price in jsondata['results'] if 'price' in price]) # key name from itunes # [a.get('a') for a in alist if 'a' in a] else: return float(...
5,328,831
def evaluate_with_trajectory( sc_dataset: SingleCellDataset, n_samples: int, trajectory_type: str, trajectory_coef: Dict, types: DeconvolutionDatatypeParametrization, deconvolution_params: Dict, n_iters=5_000, ): """Evaluate L1_error and measure fit time for fitting on a simulated datase...
5,328,832
def main(argv=None): """ """ if argv == None: argv = sys.argv[1:] try: pdb_file = argv[0] data_file = argv[1] except IndexError: err = "Incorrect number of arguments!\n\n%s\n\n" % __usage__ raise PerturbPdbError(err) out = perturbPdb(pdb_file,data_f...
5,328,833
def del_rw(action, name, exc): """ Removes the readonly flag from a file and deletes it. Useful for shutil.rmtree """ os.chmod(name, stat.S_IWRITE) os.remove(name)
5,328,834
def plot_diffraction_1d(result, deg): """ Returns this result instance in PlotData1D representation. :param deg: if False the phase is expressed in radians, if True in degrees. """ # Distinguish between the strings "phase in deg" and "phase in rad". if deg: phase_string = "Phase in deg" ...
5,328,835
def prepare_go_environ(): """Returns dict with environment variables to set to use Go toolset. Installs or updates the toolset and vendored dependencies if necessary. """ bootstrap(LAYOUT, logging.INFO) return get_go_environ(LAYOUT)
5,328,836
def get_subnets(client, name='tag:project', values=[ec2_project_name,], dry=True): """ Get VPC(s) by tag (note: create_tags not working via client api, use cidr or object_id instead ) https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_subnets """ ...
5,328,837
def get_object_handler(s3_client, request_context, user_request): """ Handler for the GetObject Operation :param s3_client: s3 client :param request_context: GetObject request context :param user_request: user request :return: WriteGetObjectResponse """ # Validate user request and retur...
5,328,838
async def test_get_triggers_for_invalid_device_id(hass, device_reg, coap_wrapper): """Test error raised for invalid shelly device_id.""" assert coap_wrapper config_entry = MockConfigEntry(domain=DOMAIN, data={}) config_entry.add_to_hass(hass) invalid_device = device_reg.async_get_or_create( ...
5,328,839
def NormalizePath(path): """Returns a path normalized to how we write DEPS rules and compare paths.""" return os.path.normcase(path).replace(os.path.sep, posixpath.sep)
5,328,840
def libritts( target_dir: Pathlike, ): """LibriTTS data download.""" download_libritts(target_dir)
5,328,841
def eval_imgs_output_dets(opt, data_loader, data_type, result_f_name, out_dir, save_dir=None, show_image=True): """ :param opt: :param data_loader: ...
5,328,842
def decline_agreement(supplier_code): """Decline agreement (role=supplier) --- tags: - seller edit parameters: - name: supplier_code in: path type: number required: true responses: 200: description: Agreement declined. 400: ...
5,328,843
def load_model(model, model_path): """ Load model from saved weights. """ if hasattr(model, "module"): model.module.load_state_dict(torch.load(model_path, map_location="cpu"), strict=False) else: model.load_state_dict(torch.load(model_path, map_location="cpu"), strict=False) retu...
5,328,844
def push_to_drive_as_child(drive, local_meta, filename, parent_id): """ Upload an image to Google Drive and store drive file id in queue. Concurrently executed by many threadpool workers in parallel. Args: drive (GoogleDrive object): [description] local_meta (pandas.DataFrame): Pandas dataf...
5,328,845
def get_file_size(filepath: str): """ Not exactly sure how os.stat or os.path.getsize work, but they seem to get the total allocated size of the file and return that while the file is still copying. What we want, is the actual file size written to disk during copying. With standard Windows file copyin...
5,328,846
def get_aws_regions_from_file(region_file): """ Return the list of region names read from region_file. The format of region_file is as follows: { "regions": [ "cn-north-1", "cn-northwest-1" ] } """ with open(region_file) as r_file: region_data = j...
5,328,847
def item_pack(): """ RESTful CRUD controller """ s3db.configure("supply_item_pack", listadd = False, ) return s3_rest_controller()
5,328,848
def add_config_vars_to_argparse(args): """ Import all defined config vars into `args`, for parsing command line. :param args: A container for argparse vars :type args: argparse.ArgumentParser or argparse._ArgumentGroup :return: """ global _groups for group_name, group in _groups.items()...
5,328,849
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) ...
5,328,850
def get_channel_output(channel_id: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[Optional[str]]] = None, site_id: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetChannelResult]:...
5,328,851
def get_version(module='spyder_terminal'): """Get version.""" with open(os.path.join(HERE, module, '__init__.py'), 'r') as f: data = f.read() lines = data.split('\n') for line in lines: if line.startswith('VERSION_INFO'): version_tuple = ast.literal_eval(line.split('=')[-1].s...
5,328,852
def _ptrarray_to_list(ptrarray): """Converts a ptr_array structure from SimpLL into a Python list.""" result = [] for i in range(0, ptrarray.len): result.append(ptrarray.arr[i]) lib.freePointerArray(ptrarray) return result
5,328,853
def perform_modifications(statemachine,amount=1,possible_modifications=[]): """Starting point for modifications upon interfaces. Performs modifications as specified in the peramaters. N (amount) of modifications are selected at random from possible_modiifcations and then attempted to be applied upon t...
5,328,854
def endpoint(path: str) -> Callable[[], Endpoint]: """Decorator for creating an Arguments: path: The path to the API endpoint (relative to the API's ``base_url``). Returns: The wrapper for the endpoint method. """ def wrapper(method): return Endpoint(path, build_conver...
5,328,855
def from_string_to_bytes(a): """ Based on project: https://github.com/chaeplin/dashmnb. """ return a if isinstance(a, bytes) else bytes(a, 'utf-8')
5,328,856
def test_folder_detail_view_contains_folder_data(client, user, folder): """ Tests if FolderDetailView displays the correct folder object :param client: :param user: :param folder: A Folder object created by the FolderFactory fixture :return: """ client.force_login(user) response = c...
5,328,857
def split(x, divider): """Split a string. Parameters ---------- x : any A str object to be split. Anything else is returned as is. divider : str Divider string. """ if isinstance(x, str): return x.split(divider) return x
5,328,858
def file_info(file_name): """Displays the name and shape of all available series in file_name Args: file_name (str): path to file """ JVM().start() meta_data = metadata(file_name) with bf.ImageReader(file_name) as reader: n_series = reader.rdr.getSeriesCount() for s in...
5,328,859
def despesa_update(despesa_id): """ Editar uma despesa. Args: despesa_id (int): ID da despesa a ser editada. Lógica matemática é chamada de utils.py: adicionar_registro() Returns: Template renderizado: despesa.html Redirecionamento: aplication.transacoes """ desp...
5,328,860
def _convert_format(partition): """ Converts the format of the python-louvain into a numpy array Parameters ---------- partition : dict Standard output from python-louvain package Returns ------- partition: np.array Partition as a numpy array """ return np.arra...
5,328,861
def populate_intercom_user(profile): """ Creates or updates an intercom user with information from TffProfile (from UserDetails) """ intercom_plugin = get_intercom_plugin() if not intercom_plugin: return intercom_user = upsert_intercom_user(profile.username, profile) tag_intercom_use...
5,328,862
def settingsdir(): """In which directory to save to the settings file""" return module_dir()+"/settings"
5,328,863
def _is_iqn_attached(sess, iqn): """ Verify if oci volume with iqn is attached to this instance. Parameters ---------- sess: OCISession The OCISession instance. iqn: str The iSCSI qualified name. Returns ------- str: the ocid """ _logger.debug('Verifying...
5,328,864
def test_total(snaptype): """Test total analysis functions.""" filename = DIR / snaptype.filename snap = plonk.load_snap(filename) total.accreted_mass(snap=snap) total.angular_momentum(snap=snap) total.center_of_mass(snap=snap) total.kinetic_energy(snap=snap) total.mass(snap=snap) t...
5,328,865
def run_range_mcraptor( timetable: Timetable, origin_station: str, dep_secs_min: int, dep_secs_max: int, max_rounds: int, ) -> Dict[str, List[Journey]]: """ Perform the McRAPTOR algorithm for a range query """ # Get stops for origins and destinations from_stops = timetable.stati...
5,328,866
def test_invert_image_filter_with_numpy(): """ Test the invert image filter works correctly with NumpyImageContainer""" invert_image_filter = InvertImageFilter() array = np.ones(shape=(3, 3, 3, 1), dtype=np.float32) nifti_image_container = NumpyImageContainer(image=array) invert_image_filter.add_i...
5,328,867
def _choose_node_type(w_operator, w_constant, w_input, t): """ Choose a random node (from operators, constants and input variables) :param w_operator: Weighting of choosing an operator :param w_constant: Weighting of choosing a constant :param w_input: Weighting of cho...
5,328,868
def plot_prisma_diagram(save_cfg=cfg.saving_config): """Plot diagram showing the number of selected articles. TODO: - Use first two colors of colormap instead of gray - Reduce white space - Reduce arrow width """ # save_format = save_cfg['format'] if isinstance(save_cfg, dict) else 'svg' ...
5,328,869
def get_script(software): """ Gets the path of the post install script of a software. :rtype: str """ dir_scripts = get_scripts_location() scripts = os.listdir(dir_scripts) for script in scripts: if script == software: return os.path.join(dir_scripts, script) retur...
5,328,870
def _plat_idx_to_val(idx: int , edge: float = 0.5, FIO_IO_U_PLAT_BITS: int = 6, FIO_IO_U_PLAT_VAL: int = 64) -> float: """ Taken from fio's stat.c for calculating the latency value of a bin from that bin's index. idx : the value of the index into the histogram bins edge : fractiona...
5,328,871
def is_blank(value): """ Returns True if ``value`` is ``None`` or an empty string. >>> is_blank("") True >>> is_blank(0) False >>> is_blank([]) False """ return value is None or value == ""
5,328,872
def overload_check(data, min_overload_samples=3): """Check data for overload :param data: one or two (time, samples) dimensional array :param min_overload_samples: number of samples that need to be equal to max for overload :return: overload status """ if data.n...
5,328,873
def main(): """Main function""" args = parse_args() print('Called with args:') print(args) if not torch.cuda.is_available(): sys.exit("Need a CUDA device to run the code.") if args.cuda or cfg.NUM_GPUS > 0: cfg.CUDA = True else: raise ValueError("Need Cuda device to...
5,328,874
def test_error_responses(run_response, expected_exception_class, acl_tool): """When the icacls process responds, but yields some non-0 return code """ with patch("icaclswrap.foldertool.subprocess.run") as mock_run: mock_run.return_value = run_response with pytest.raises(expected_exception_class...
5,328,875
def unknown_cruise_distance(segment): """This is a method that allows your vehicle to land at prescribed landing weight Assumptions: N/A Source: N/A Inputs: segment.cruise_tag [string] state.unknowns.cruise_distance [meters] Outputs: segment.distance ...
5,328,876
def send_packet_to_capture_last_one(): """ Since we read packets from stdout of tcpdump, we do not know when a packet is finished Hence you should send an additional packet after you assume all interesting packets were sent """ def send(): conf = get_netconfig() sock = socket(AF_PAC...
5,328,877
def diss( demos: Demos, to_concept: Identify, to_chain: MarkovChainFact, competency: CompetencyEstimator, lift_path: Callable[[Path], Path] = lambda x: x, n_iters: int = 25, reset_period: int = 5, cooling_schedule: Callable[[int], float] | None = None, size_weight: float = 1.0, ...
5,328,878
def expand_gelu(expand_info): """Gelu expander""" # get op info. input_desc = expand_info['input_desc'][0] graph_builder = builder.GraphBuilder() # generate a graph. with graph_builder.graph_scope('main') as graph_scope: # create tensor input. input_x = graph_builder.tensor(inp...
5,328,879
def cache_mixin(cache, session): """CacheMixin factory""" hook = EventHook([cache], session) class _Cache(CacheMixinBase): _hook = hook _cache_client = cache _db_session = session return _Cache
5,328,880
def _read_output(path): """Read CmdStan output csv file. Parameters ---------- path : str Returns ------- Dict[str, Any] """ # Read data columns, data, comments = _read_output_file(path) pconf = _process_configuration(comments) # split dataframe to warmup and draws ...
5,328,881
def linear_chance_constraint_noinit(a,M,N,risk,num_gpcpoly,n_states,n_uncert,p): """ Pr{a^\Top x + b \leq 0} \geq 1-eps Converts to SOCP """ a_hat = np.kron(a.T,M) a_dummy = np.zeros((n_states,n_states)) for ii in range(n_states): a_dummy[ii,ii] = a[ii,0] #print(a_dummy) ...
5,328,882
def patroni(response: responses.Response, session: sqlalchemy.orm.Session = fastapi.Depends(models.patroni.get_session)): """ Returns a health check for the reachability of the Patroni database. """ return db_health(response, session, 'Patroni')
5,328,883
def authorization_code_grant_step1(request): """ Code grant step1 short-cut. This will return url with code. """ django_request = oauth2_request_class()(request) grant = CodeGrant(oauth2_server, django_request) return grant.authorization()
5,328,884
def test_weighted_means(gid, resolution, excl_dict, time_series): """ Test Supply Curve Point exclusions weighted mean calculation """ with SupplyCurvePoint(gid, F_EXCL, TM_DSET, excl_dict=excl_dict, resolution=resolution) as point: shape = (point._gids.max() + 1, ) ...
5,328,885
async def activity( guild_id: int, discord_id: int, activity_input: DestinyActivityInputModel, db: AsyncSession = Depends(get_db_session), ): """Return information about the user their stats in the supplied activity ids""" user = await discord_users.get_profile_from_discord_id(discord_id) ...
5,328,886
def patch_diff_tarfile( base_path, diff_tarfile, restrict_index=() ): """Patch given Path object using delta tarfile (as in tarfile.TarFile) If restrict_index is set, ignore any deltas in diff_tarfile that don't start with restrict_index. """ if base_path.exists(): path_iter = selection.Se...
5,328,887
def put_topoverlays(image, rects, alpha=0.3): """ a function for drawing some rectangles with random color Args: image: an opencv image with format of BGR rects: a list of opencv rectangle alpha: a float, blend level Return: An opencv image """ h, w, _ = image.shape im = np.ones(shape=image...
5,328,888
def extract_next_token(link): """Use with paginated endpoints for extracting token which points to next page of data.""" clean_link = link.split(";")[0].strip("<>") token = clean_link.split("?token=")[1] # token is already quoted we have to unqoute so it can be passed to params return unquote(t...
5,328,889
def get_host_country(host_ip): """Gets country of the target's IP""" country = 'NOT DEFINED' try: response_body = urllib.request.urlopen(f'https://ipinfo.io/{host_ip}').read().decode('utf8') response_data = json.loads(response_body) country = response_data['country'] except: ...
5,328,890
def feed_many_stdins(fp, processes): """ :param fp: input file :param processes: list of processes to be written to. """ while True: data = fp.read(8192) if not data: break for proc in processes: proc.stdin.write(data)
5,328,891
def astng_wrapper(func, modname): """wrapper to give to ASTNGManager.project_from_files""" print 'parsing %s...' % modname try: return func(modname) except ASTNGBuildingException, exc: print exc except Exception, exc: import traceback traceback.print_exc()
5,328,892
def clean(s): """Clean text!""" return patList.do(liblang.fixRepetedVowel(s))
5,328,893
def extract_narr_aux_data(espa_metadata, aux_path): """Extracts the required NARR data from the auxiliary archive Args: espa_metadata <espa.Metadata>: The metadata structure for the scene aux_path <str>: Path to base auxiliary (NARR) data """ logger = logging.getLogger(__name__) (...
5,328,894
def filename(s, errors="strict"): """Same as force_unicode(s, sys.getfilesystemencoding(), errors) """ return force_unicode(s, sys.getfilesystemencoding(), errors)
5,328,895
def elastic_transform(image, alpha=1000, sigma=30, spline_order=1, mode='nearest', random_state=np.random): """Elastic deformation of image as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", ...
5,328,896
def format_search_log(json_string): """ usage example {{ model_object|format_search_log }} """ query_json = json.loads(json_string) attributes_selected = sorted(query_json.get('_source')) context = {} context['attributes_selected'] = attributes_selected return attributes_selected
5,328,897
def set_variable(value,variable=None): """Load some value into session memory by creating a new variable. If an existing variable is given, load the value into the given variable. """ sess = get_session() if variable is not None: assign_op = tf.assign(variable,value) sess.run(...
5,328,898
def matrix ( mtrx , i , j ) : """Get i,j element from matrix-like object >>> mtrx = ... >>> value = matrix ( m , 1 , 2 ) """ if isinstance ( mtrx , ROOT.TMatrix ) : if i < mtrx.GetNrows () and j < mtrx.GetNcols () : return mtrx ( i , j ) if callable ( mtrx ) : ...
5,328,899