content
stringlengths
22
815k
id
int64
0
4.91M
def add_gaussian_noise(images: list, var: list, random_var: float=None, gauss_noise: list=None): """ Add gaussian noise to input images. If random_var and gauss_noise are given, use them to compute the final images. Otherwise, compute random_var and gauss_noise. :param images: list of images :param ...
30,000
def get_sso_backend(): """ Return SingleSignOnBackend class instance. """ return get_backend_instance(cfg.CONF.auth.sso_backend)
30,001
def conv_relu_pool_forward(x, w, b, conv_param, pool_param): """ Convenience layer that performs a convolution, a ReLU, and a pool. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer - pool_param: Parameters for the pooling layer Returns a tuple...
30,002
def ConnectWithReader(readerName, mode): """ ConnectWithReader """ hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, readerName, mode, SCARD_PROTOC...
30,003
def interpolate(points: type_alias.TensorLike, weights: type_alias.TensorLike, indices: type_alias.TensorLike, normalize: bool = True, allow_negative_weights: bool = False, name: str = "weighted_interpolate") -> type_alias.TensorLike: """...
30,004
def main( argv, install_path=INSTALL_PATH, service_class=WindowsService, namespace='winservice.WindowsService'): """Method to handle direct server invocation.""" win32serviceutil.HandleCommandLine( service_class, '%s%s' % (install_path, namespace), argv=argv)
30,005
def calcADPs(atom): """Calculate anisotropic displacement parameters (ADPs) from anisotropic temperature factors (ATFs). *atom* must have ATF values set for ADP calculation. ADPs are returned as a tuple, i.e. (eigenvalues, eigenvectors).""" linalg = importLA() if not isinstance(atom, ...
30,006
def _create_groups(properties): """Create a tree of groups from a list of properties. Returns: Group: The root group of the tree. The name of the group is set to None. """ # We first convert properties into a dictionary structure. Each dictionary # represents a group. The None key correspon...
30,007
def activate_move_mode(layer): """Activate move tool.""" layer.mode = Mode.MOVE
30,008
def bitset(array, bits): """ To determine if the given bits are set in an array. Input Parameters ---------------- array : array A numpy array to search. bits : list or array A list or numpy array of bits to search. Note that the "first" bit is denoted as zero, w...
30,009
def test1(): """ Test FancyHelloWorld2 """ pre = __name__ + "test1 :" print(pre, "test1") print(pre, "Let's test FancyHelloWorlds") print(pre, "FancyHelloWorld") try: hw = FancyHelloWorld(address="Helsinki", age=40) except AttributeError as e: print(e) else: ...
30,010
def build_classifier_pipeline( input_files, output_files, config, use_fake_tables = False, converter_impl = ConverterImplType.PYTHON, ): """Pipeline for converting finetuning examples.""" if len(output_files) != len(input_files): raise ValueError(f'Size mismatch: {output_files} {input_files...
30,011
def sample_gene_matrix(request, variant_annotation_version, samples, gene_list, gene_count_type, highlight_gene_symbols=None): """ highlight_gene_symbols - put these genes 1st """ # 19/07/18 - Plotly can't display a categorical color map. See: https://github.com/plotly/plotly.js/issues/17...
30,012
def dcm2json(ctx, inpath, outpath): """Convert a DICOM file or directory of files at INPATH into dictionaries and save result in json format at OUTPATH.""" click.echo(click.style('Covert DICOM to JSON', underline=True, bold=True)) def convert_file(infile: Path, outfile: Path): dixel = DcmDir()...
30,013
def validate_yaml_online(data, schema_uri=None): """ Validates the given data structure against an online schema definition provided by schema_uri. If schema_uri is not given, we try to get it from the 'descriptor_schema' field in 'data'. Returns: True/False """ if schema_uri is None: ...
30,014
def normal218(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(zz2) idgirande=r...
30,015
def get_fast_loaders(dataset, batch_size, test, device, data_path=None, train_transform=None, validation_transform=None, train_percentage=0.85, workers=4): """Return :class:`FastLoader` for training and validation, outfitted with a random sampler. If set to run on the test set, :param:`tra...
30,016
def find_paths(root: TreeNode, required_sum: int) -> List[List[int]]: """ Time Complexity: O(N^2) Space Complexity: O(N) Parameters ---------- root : TreeNode Input binary tree. required_sum : int Input number 'S'. Returns ------- all_paths : List[List[int]] ...
30,017
def test_prepareHostConfig(settings, detectSystemDevices): """ Test paradrop.core.config.hostconfig.prepareHostConfig """ from paradrop.core.config.hostconfig import prepareHostConfig devices = { 'wan': [{'name': 'eth0'}], 'lan': list(), 'wifi': list() } detectSystem...
30,018
def macro_bank_switzerland_interest_rate(): """ 瑞士央行利率决议报告, 数据区间从20080313-至今 https://datacenter.jin10.com/reportType/dc_switzerland_interest_rate_decision https://cdn.jin10.com/dc/reports/dc_switzerland_interest_rate_decision_all.js?v=1578582240 :return: 瑞士央行利率决议报告-今值(%) :rtype: pandas.Series ...
30,019
def create_dataframe(message): """Create Pandas DataFrame from CSV.""" dropdowns = [] df = pd.DataFrame() if message != "": df = pd.read_csv(message) df = df.sample(n = 50, random_state = 2) # reducing Data Load Running on Heroku Free !!!! if len(df) == 0: return pd.D...
30,020
def test_str_special(): """Test type of __str__ method results.""" s = str(m) assert_true(type(s) is str)
30,021
async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the HomematicIP Cloud weather sensor.""" pass
30,022
def load_model(path): """ This function ... :param path: :return: """ # Get the first line of the file with open(path, 'r') as f: first_line = f.readline() # Create the appropriate model if "SersicModel" in first_line: return SersicModel.from_file(path) elif "ExponentialDiskMo...
30,023
def add_metaclass(metaclass): """ Class decorator for creating a class with a metaclass. Borrowed from `six` module. """ @functools.wraps(metaclass) def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if i...
30,024
def setup_logging(): """Configure the logger.""" log.propagate = False log.setLevel(logging.INFO) # Log to stdout console_handler = logging.StreamHandler(sys.stdout) console_handler.setLevel(logging.INFO) formatter = logging.Formatter('[%(levelname)s] %(message)s') console_handler.setFormatter(formatte...
30,025
def iter_repl(seq, subseq, repl): """ Replace sub-list `subseq` in `seq` with `repl`. """ seq, subseq, repl = list(seq), list(subseq), list(repl) subseq_len = len(subseq) rem = seq[:] while rem: if rem[:subseq_len] == subseq: for c in repl: yield c ...
30,026
def test_checkpoint_horovod(tmpdir, ray_start_4_cpus): """Tests if Tune checkpointing works with HorovodRayAccelerator.""" accelerator = HorovodRayAccelerator( num_hosts=1, num_slots=2, use_gpu=False) checkpoint_test(tmpdir, accelerator)
30,027
def max_pool_nd_inverse(layer, relevance_in : torch.Tensor, indices : torch.Tensor = None, max : bool = False) -> torch.Tensor : """ Inversion of LogSoftmax layer Arguments --------- relevance : torch.Tensor Input relavance indices : torch.Tensor Max...
30,028
def write_done(): """ Tells the user that we're done with the previous action. Does not print to the logger """ if not LOG_ONLY: global _LEVEL, _LAST_CLOSED _LEVEL -= 1 # If there has been actions in between, write tabs if _LAST_CLOSED > _LEVEL: for _inde...
30,029
def aroon_up(close, n=25, fillna=False): """Aroon Indicator (AI) Identify when trends are likely to change direction (uptrend). Aroon Up - ((N - Days Since N-day High) / N) x 100 https://www.investopedia.com/terms/a/aroon.asp Args: close(pandas.Series): dataset 'Close' column. n(...
30,030
def exists(): """real_abs.c exists""" check50.exists("real_abs.c")
30,031
def hash_file(filename): """ computes hash value of file contents, to simplify pytest assert statements for complex test cases that output files. For cross-platform compatibility, make sure files are read/written in binary, and use unix-style line endings, otherwise hashes will not match despite co...
30,032
def spatial_batchnorm_forward(x, gamma, beta, bn_param): """ Computes the forward pass for spatial batch normalization. Inputs: - x: Input data of shape (N, C, H, W) - gamma: Scale parameter, of shape (C,) - beta: Shift parameter, of shape (C,) - bn_param: Dictionary with the following keys...
30,033
def load_sheet_2(workbook, db_name, collection_name, mongo=False, startrow=32, startcol='M', lastcol='Y'): """ """ columns = ['parameter', 'cas', 'contaminant', 'cancer_risk_residential', 'cancer_risk_ci', 'cancer_risk_workers', 'hard_quotient', 'metal', 'volatile', 'persistent', 'modeled_koc', 'code', 'notes'] df...
30,034
def triangulate(points): """ triangulate the plane for operation and visualization """ num_points = len(points) indices = np.arange(num_points, dtype=np.int) segments = np.vstack((indices, np.roll(indices, -1))).T tri = pymesh.triangle() tri.points = np.array(points) tri.segments = seg...
30,035
def immutable(): """ Get group 1. """ allowed_values = {'NumberOfPenguins', 'NumberOfSharks'} return ImmutableDict(allowed_values)
30,036
def traceroute_udp(addr, hops, q, timeout, ttl, wait, port): # {{{1 """trace route to dest using UDP""" sock = S.socket(S.AF_INET, S.SOCK_RAW, S.IPPROTO_UDP) try: for x in traceroute(send_probe_udp, recv_probe_udp, [sock], addr, hops, q, timeout, ttl, wait, port): yield x f...
30,037
def parse(meta, recipe, args): """ Parses metadata, creates headers, content, and footer, and yields these to be written into a file consecutively """ clsmodule = cls_module(args.cls) ## HEADER yield COMMENT.format( now = datetime.now().strftime("%d-%m-%Y %H:%M:%S"), ti...
30,038
def test_plot_colors_sizes_proj(data, region): """ Plot the data using z as sizes and colors with a projection. """ fig = Figure() fig.coast(region=region, projection="M15c", frame="af", water="skyblue") fig.plot( x=data[:, 0], y=data[:, 1], color=data[:, 2], size...
30,039
def test_get_buffer_mode(): """ ensures that strings passed to get_buffer_mode are properly handled """ # None cases assert ConfigdocsHelper.get_buffer_mode('') == BufferMode.REJECTONCONTENTS assert ConfigdocsHelper.get_buffer_mode( None) == BufferMode.REJECTONCONTENTS # valid cases...
30,040
def predict_to_score(predicts, num_class): """ Checked: the last is for 0 === Example: score=1.2, num_class=3 (for 0-2) (0.8, 0.2, 0.0) * (1, 2, 0) :param predicts: :param num_class: :return: """ scores = 0. i = 0 while i < num_class: scores += i * ...
30,041
def quasi_diagonalize(link): """sort clustered assets by distance""" link = link.astype(int) sort_idx = pd.Series([link[-1, 0], link[-1, 1]]) num_items = link[-1, 3] # idx of original items while sort_idx.max() >= num_items: sort_idx.index = list(range(0, sort_idx.shape[0] * 2, 2)) # make ...
30,042
def dataset_files(rootdir, pattern): """Returns a list of all image files in the given directory""" matches = [] for root, dirnames, filenames in os.walk(rootdir): for filename in fnmatch.filter(filenames, pattern): matches.append(os.path.join(root, filename)) return matches
30,043
def keyword(variable): """ Verify that the field_name isn't part of know Python keywords :param variable: String :return: Boolean """ for backend in ADAPTERS: if variable.upper() in ADAPTERS[backend]: msg = ( f'Variable "{variable}" is a "{backend.upper()}" ' ...
30,044
def cli(): """Historical commandline for managing historical functions.""" pass
30,045
def gcp_api_main(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.mak...
30,046
def box_area_3d(boxes: Tensor) -> Tensor: """ Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2, z1, z2) coordinates. Arguments: boxes (Union[Tensor, ndarray]): boxes for which the area will be computed. They are expected to be in (x1, y1, ...
30,047
def set_device_parameters(request): """Set up the class.""" def fin(): request.cls.device.close() request.addfinalizer(fin) request.cls.driver = ftos.FTOSDriver request.cls.patched_driver = PatchedFTOSDriver request.cls.vendor = 'ftos' parent_conftest.set_device_parameters(request)
30,048
def mock_engine(dialect_name=None): """Provides a mocking engine based on the current testing.db. This is normally used to test DDL generation flow as emitted by an Engine. It should not be used in other cases, as assert_compile() and assert_sql_execution() are much better choices with fewer m...
30,049
def get_feedback_thread_reply_info_by_reply_to_id(reply_to_id): """Gets the domain object corresponding to the model which is fetched by reply-to-id field. Args: reply_to_id: str. The reply_to_id to search for. Returns: FeedbackThreadReplyInfo or None. The corresponding domain object. ...
30,050
def _cross_correlations(n_states): """Returns list of crosscorrelations Args: n_states: number of local states Returns: list of tuples for crosscorrelations >>> l = _cross_correlations(np.arange(3)) >>> assert l == [(0, 1), (0, 2), (1, 2)] """ l = n_states cross_corr =...
30,051
def select_interface(worker): """ It gets a worker interface channel to do something. """ interfaces = worker.interfaces_list() if len(interfaces) == 0: print ' Error. Worker without interface known.' return -1 elif len(interfaces) == 1: return 1 option = raw_input('...
30,052
def save_trained_model( model_name: str, theModel: keras.models.Sequential, trainHistory: cbacks.History ) -> None: """Saves a tensorflow model and training history to local file storage""" with open( f"{CONFIG['Modelling']['ModelDir']}/{model_name}/trainHistoryDict.p", "wb" ) as fp: pic...
30,053
def get_middle(arr): """ Get middle point ???? """ n_val = np.array(arr.shape) / 2.0 n_int = n_val.astype(np.int0) # print(n_int) if n_val[0] % 2 == 1 and n_val[1] % 2 == 1: return arr[n_int[0], n_int[1]] if n_val[0] % 2 == 0 and n_val[1] % 2 == 0: return np.average(arr[...
30,054
def annotate_segmentation(image, segmentation): """Return annotated segmentation.""" annotation = AnnotatedImage.from_grayscale(image) for i in segmentation.identifiers: region = segmentation.region_by_identifier(i) color = pretty_color() annotation.mask_region(region.border.dilate()...
30,055
def get_champ_data(champ: str, tier: int, rank: int): """ Gives Champ Information by their champname, tier, and rank. """ champ_info = NewChampsDB() try: champ_info.get_data(champ, tier, rank) champs_dict = { "name": f"{champ_info.name}", "released": champ_i...
30,056
def create_jobs(source, valid_affinities, externally_blocked=False): """ Create jobs for Source `source`, using the an architecture matching `valid_affinities` for any arch "all" jobs. """ aall = None for arch in source.group_suite.arches: if arch.name == "all": aall = arch ...
30,057
def handler(event, context): """ Handler method for insert resource function. """ if event is None: return response(http.HTTPStatus.BAD_REQUEST, Constants.error_insufficient_parameters()) if event is None or Constants.event_body() not in event or Constants.event_http_method() not in event: ...
30,058
def _topic_scores(run_scores): """ Helping function returning a generator for determining the topic scores for each measure. @param run_scores: The run scores of the previously evaluated run. @return: Generator with topic scores for each trec_eval evaluation measure. """ measures_all = list(lis...
30,059
def doctest_ObjectWriter_get_state_sub_doc_object_with_no_pobj(): """ObjectWriter: get_state(): Called with a sub-document object and no pobj While this should not really happen, we want to make sure we are properly protected against it. Usually, the writer sets the jar of the parent object equal to it...
30,060
def serving_input_receiver_fn(): """This is used to define inputs to serve the model. Returns: A ServingInputReciever object. """ csv_row = tf.placeholder(shape=[None], dtype=tf.string) features, _ = _make_input_parser(with_target=False)(csv_row) return tf.estimator.export.ServingInputReceiver(features...
30,061
def offsetTimer(): """ 'Starts' a timer when called, returns a timer function that returns the time in seconds elapsed since the timer was started """ start_time = time.monotonic() def time_func(): return time.monotonic() - start_time return time_func
30,062
def _get_sender(pusher_email): """Returns "From" address based on env config and default from.""" use_author = 'GITHUB_COMMIT_EMAILER_SEND_FROM_AUTHOR' in os.environ if use_author: sender = pusher_email else: sender = os.environ.get('GITHUB_COMMIT_EMAILER_SENDER') return sender
30,063
def test_report_a_tag_anlger_report_create_report_link_not_authenticated( client, db_setup ): """If an unauthorized user accessess the view the angler reports through the report-a-tag url, they should NOT see the link to create reports """ angler = JoePublic.objects.get(first_name="Homer") res...
30,064
def main(): """Main execution when called as a script.""" warnings.filterwarnings('ignore') profile = 'asc' pseudo_family_id = 'SSSP/1.1/PBE/efficiency' load_profile(profile) controller = PwBaseSubmissionController( pw_code_id='pw-6.7MaX_conda', structure_group_id='structures/...
30,065
def find_resolution(func: Callable = None) -> Callable: """Decorator that gives the decorated function the image resolution.""" @functools.wraps(func) def wrapper(self: MultiTraceChart, *args, **kwargs): if 'width' not in kwargs: kwargs['width'] = self.resolution[0] if 'height' ...
30,066
def transform_spikes_to_isi(self, spikes, time_epoch, last_event_is_spike=False): """Convert spike times to data array, which is a suitable format for optimization. Parameters ---------- spikes : numpy array (num_neuron,N), dtype=np.ndarray A sequence of spike times for each neuron on each tri...
30,067
def api_github_v2(user_profile, event, payload, branches, default_stream, commit_stream, issue_stream, topic_focus = None): """ processes github payload with version 2 field specification `payload` comes in unmodified from github `default_stream` is set to what `stream` is in v1 above `commit_stream...
30,068
def concatenate( iterable: Iterable[Results], callback: Optional[Callable] = None, modes: Iterable[str] = ("val", "test"), reduction: str = "none", ) -> Results: """Returns a concatenated Results. Args: iterable (iterable of Results): Iterable of `Results` instance. callback (ca...
30,069
def parse_version(s: str) -> tuple[int, ...]: """poor man's version comparison""" return tuple(int(p) for p in s.split('.'))
30,070
def test_match_dict_index(): """aski dict for first item""" kid1=JsonNode('dict',start=1,end=2,name='e') node = JsonNode('dict', start=0, end=2, kids=[ kid1 ]) pattern = '{0}' ret=list(matcher.match(node, pattern)) assert ret == [kid1]
30,071
def replay_train(DQN, train_batch): """ 여기서 train_batch는 minibatch에서 가져온 data들입니다. x_stack은 state들을 쌓는 용도로이고, y_stack은 deterministic Q-learning 값을 쌓기 위한 용도입니다. 우선 쌓기전에 비어있는 배열로 만들어놓기로 하죠. """ x_stack = np.empty(0).reshape(0, DQN.input_size) # array(10, 4) y_stack = np.empty(0).reshape(0, DQN.output_size) # arr...
30,072
def make_reverse_macro_edge_name(macro_edge_name): """Autogenerate a reverse macro edge name for the given macro edge name.""" if macro_edge_name.startswith(INBOUND_EDGE_FIELD_PREFIX): raw_edge_name = macro_edge_name[len(INBOUND_EDGE_FIELD_PREFIX) :] prefix = OUTBOUND_EDGE_FIELD_PREFIX elif ...
30,073
def unescaped_split(pattern, string, max_split=0, remove_empty_matches=False, use_regex=False): """ Splits the given string by the specified pattern. The return character (\\n) is not a natural split pattern (if you don't specif...
30,074
def download_coco(args, overwrite=False): """download COCO dataset and Unzip to download_dir""" _DOWNLOAD_URLS = [ ('http://images.cocodataset.org/zips/train2017.zip', '10ad623668ab00c62c096f0ed636d6aff41faca5'), ('http://images.cocodataset.org/annotations/annotations_trainval2017.zip',...
30,075
def citation_distance_matrix(graph): """ :param graph: networkx graph :returns: distance matrix, node labels """ sinks = [key for key, outdegree in graph.out_degree() if outdegree==0] paths = {s: nx.shortest_path_length(graph, target=s) for s in sinks} paths_df = pd.DataFrame(paths)#, index...
30,076
def read_into_dataframe(file: IO, filename: str = "", nrows: int = 100,max_characters: int = 50) -> pd.DataFrame: """Reads a file into a DataFrame. Infers the file encoding and whether a header column exists Args: file (IO): file buffer. filename (str): filename. Used to infer compression. ...
30,077
def load_generator(config: dict): """ Create the generator and load its weights using the function `load_weights`. Args: config (dict): Dictionary with the configurations. Returns: BigGAN.Generator: The generator. """ # GPU device = "cuda" torch.backends.cudnn.benchmark...
30,078
def Navigatev0_action_to_tensor(act: OrderedDict, task=1): """ Creates the following (batch_size, seq_len, 11) action tensor from Navigatev0 actions: 0. cam left 1. cam right 2. cam up 3. cam down 4. place + jump 5. place 6. forward + attack 7. attack 8. fo...
30,079
def asfarray(a, dtype=mstype.float32): """ Similar to asarray, converts the input to a float tensor. If non-float dtype is defined, this function will return a float32 tensor instead. Args: a (Union[int, float, bool, list, tuple, numpy.ndarray]): Input data, in any form that can be...
30,080
def test_fail_when_no_template( testdata_dir: pathlib.Path, tmp_trestle_dir: pathlib.Path, monkeypatch: MonkeyPatch ) -> None: """Test that validation fails when template does not exists.""" task_template_folder = tmp_trestle_dir / '.trestle/author/test_task/' source_instance = testdata_dir / 'author/0....
30,081
def _verify_option(value: Optional[str], value_proc: Callable) -> Optional[str]: """Verifies that input value via click.option matches the expected value. This sets ``value`` to ``None`` if it is invalid so the rest of the prompt can flow smoothly. Args: value (Optional[str]): Input value. ...
30,082
def test_external_server(): """ Test starting up an external server and accessing with a client with start_server=False """ corenlp_home = os.getenv('CORENLP_HOME') start_cmd = f'java -Xmx5g -cp "{corenlp_home}/*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9001 ' \ f'-timeout 6000...
30,083
def batch_jacobian(output, inp, use_pfor=True, parallel_iterations=None): """Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`. e.g. x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) y = x * x jacobian = batch_jacobian(y, x) # => [[[2, 0], [0, 4]], [[6, 0], [0, 8]]] ...
30,084
def test_phono3py_ltc_lbte( fixture_sandbox, fixture_code, generate_calc_job, generate_inputs, generate_settings, generate_fc3_filedata, generate_fc2_filedata, ): """Test a phonopy calculation.""" entry_point_calc_job = "phonoxpy.phono3py" inputs = generate_inputs( metad...
30,085
def declare(baseFamily=None, baseDefault=0, derivedFamily=None, derivedDefault=""): """ Declare a pair of components """ # the declaration class base(pyre.component, family=baseFamily): """a component""" b = pyre.properties.int(default=baseDefault) class derived(base, family=der...
30,086
def parse_iso8601(dtstring: str) -> datetime: """naive parser for ISO8061 datetime strings, Parameters ---------- dtstring the datetime as string in one of two formats: * ``2017-11-20T07:16:29+0000`` * ``2017-11-20T07:16:29Z`` """ return datetime.strptime( dtst...
30,087
def CalcCurvature(vertices,faces): """ CalcCurvature recives a list of vertices and faces and the normal at each vertex and calculates the second fundamental matrix and the curvature by least squares, by inverting the 3x3 Normal matrix INPUT: vertices -nX3 array of vertices faces ...
30,088
def query_abstracts( q: Optional[str] = None, n_results: Optional[int] = None, index: str = "agenda-2020-1", fields: list = ["title^2", "abstract", "fullname", "institution"], ): """ Query abstracts from a given Elastic index q: str, query n_results: int, number of results from inde...
30,089
def PretrainedEmbeddingIndicesDictionary() -> typing.Dict[str, int]: """Read and return the embeddings indices dictionary.""" with open(INST2VEC_DICITONARY_PATH, "rb") as f: return pickle.load(f)
30,090
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val < 0 else 'black' return 'color: %s' % color
30,091
async def test_form_cannot_connect(hass: HomeAssistant) -> None: """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.surepetcare.config_flow.surepy.c...
30,092
def globpattern(dir, pattern): """ Return leaf names in the specified directory which match the pattern. """ if not hasglob(pattern): if pattern == '': if os.path.isdir(dir): return [''] return [] if os.path.exists(util.normaljoin(dir, pattern)):...
30,093
def test_basic_if_statement(): """TEST 3.2: If statements are the basic control structures. The `if` should first evaluate its first argument. If this evaluates to true, then the second argument is evaluated and returned. Otherwise the third and last argument is evaluated and returned instead. """ ...
30,094
def get_student_discipline(person_id: str = None): """ Returns student discipline information for a particular person. :param person_id: The numeric ID of the person you're interested in. :returns: String containing xml or an lxml element. """ return get_anonymous('getStudentDiscipline', perso...
30,095
def main(): """evaluate gpt-model fine-tune on qa dataset""" parser = argparse.ArgumentParser() parser.add_argument( '--model_name', type=str, default='gpt2', help='pretrained model name') parser.add_argument("--using_cache", type=bool, default=False) parser.add_argum...
30,096
def dot(p1, p2): """ Dot product :param p1: :param p2: :return: """ return p1[X] * p2[X] + p1[Y] * p2[Y]
30,097
def logout(): """View function which handles a logout request.""" tf_clean_session() if current_user.is_authenticated: logout_user() # No body is required - so if a POST and json - return OK if request.method == "POST" and _security._want_json(request): return _security._render_jso...
30,098
def _lookup_configuration(): """Lookup the configuration file. :return: opened configuration file :rtype: stream """ for pth in CONFIG_PATH: path = os.path.abspath(os.path.expanduser(pth)) LOGGER.debug('Checking for %s', path) if os.path.exists(path): LOGGER.info...
30,099