content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Sequence from typing import Tuple import itertools def simulate_data( covariates: int, scales: Sequence[int], levels: Sequence[int], singletons: float, state: np.random.RandomState) -> Tuple[Array, Array, Array]: """Simulate IDs and data matrices.""" # simulate fixed effect...
c5fbddde4045b2367975b28bcfc4ded032427505
28,203
def create_strike_ingest_job_message(ingest_id, strike_id): """Creates a message to create the ingest job for a strike :param ingest_id: ID of the ingest :type ingest_id: int :param strike_id: The ID of the strike :type strike_id: int """ message = CreateIngest() message.create_inge...
47e96f6fa53cc934572852cfcaf8ed9455408dec
28,204
def create_data(nfac0, # [Number of facet 0 elements -- rows/persons] nfac1, # [Number of facet 1 elements -- columns/items] ndim, # [Number of dimensions to create] seed = None, # [<None,int,{'Fac0':<None,int,array>,'Fac1':<None,int,array>}> => generates coordinate...
d21b3a9c3172087021ba92caa74b4be95cac993c
28,205
def load_database() -> pd.DataFrame: """ Loads data from hplib_database. Returns ------- df : pd.DataFrame Content of the database """ df = pd.read_csv(cwd()+r'/hplib_database.csv') return df
5bc5ec4e8376493a9d7da9a8782c2e0f4fb8223d
28,206
import re def ensure_windows_file_path_format_encoding_as_url(path: str) -> str: """Relevant for Windows where a file path name should be "file://path/to/file.html" instead of "file://path\\to\\file.html" .""" output = path.replace("\\", "/") # Raw replace backslash with slash. # Handle exception for "f...
84e429c5d8e4b0fc2fd8976b140694f0f7c1c04e
28,207
def index(): """ index page for WebUI Returns: rendered HTML page """ data = load_messages().message_contents return render_template("index.html", data=data, encoded_data=data)
c92515fc49aacded4e9242955f6b2d5ea125897a
28,209
def psnr(x, pred_x, max_val=255): """ PSNR """ val = tf.reduce_mean(tf.image.psnr(x, pred_x, max_val=max_val)) return val
7b5d44917c88d7644e5c1694a6e6d5873c0db952
28,210
def across_series_nearest_neighbors(Ts, Ts_idx, subseq_idx, m): """ For multiple time series find, per individual time series, the subsequences closest to a query. Parameters ---------- Ts : list A list of time series for which to find the nearest neighbor subsequences that are ...
4cf3f8162b33f3b313f07160bab7e8042ce08f2b
28,211
def get_boundary_from_response(response): """ Parses the response header and returns the boundary. :param response: response containing the header that contains the boundary :return: a binary string of the boundary """ # Read only the first value with key 'content-type' (duplicate keys are allowed)...
66a0112598b2210cca1a2210f6af963dfee641f7
28,212
import logging import json def get_message(message): """{ 'pattern': None, 'type': 'subscribe', 'channel': 'my-second-channel', 'data': 1L, }""" if not message: return logging.info('MSG: %s', message) data = message.get('data', {}) return json.loads(dat...
2e79ed94fbfc3fba122e8bd8663e33b124d4d2b6
28,213
def parent_node(selector): """ Finds the parent_node of the given selector. """ if not get_instance(): raise Exception("You need to start a browser first with open_browser()") return parent_node_g(get_instance(), selector)
0d6136aa5262a4b4482166108715b3323328983b
28,214
def getPairCategory(rollSorted): """ Converts a roll's ordered list of frequencies to the pairwise hand category. """ if rollSorted[0] == 6: return "six-of-a-kind" elif rollSorted[0] == 5: return "five-of-a-kind" elif rollSorted[0] == 4 and rollSorted[1] == 2: retur...
1c48abd8d0c1a27a50ce587857852a95e8949e74
28,215
def allocz(size): """Alloc zeros with range""" return [0 for _ in range(size)]
21670a20ea045ee7f2cf0780a011f89f917b7180
28,216
def uint_to_little_endian_bytearray(number, size): """Converts an unsigned interger to a little endian bytearray. Arguments: number -- the number to convert size -- the length of the target bytearray """ if number > (2 ** (8 * size) - 1): raise ValueError("Integer overflow") nle = [...
bd3314fedf0accbc0d15b1bb146f54f52cb3bce1
28,217
import re def to_alu_hlu_map(input_str): """Converter for alu hlu map Convert following input into a alu -> hlu map: Sample input: ``` HLU Number ALU Number ---------- ---------- 0 12 1 23 ``` ALU stands for array LUN number ...
8e211b7efa3f8dd23c042f046d881daf987062bc
28,218
import copy def randomize(jet): """build a random tree""" jet = copy.deepcopy(jet) leaves = np.where(jet["tree"][:, 0] == -1)[0] nodes = [n for n in leaves] content = [jet["content"][n] for n in nodes] nodes = range(len(nodes)) tree = [[-1, -1] for n in nodes] pool = [n for n in node...
d4e8d12f8701d140e965e773e9a2542b133d8535
28,220
from typing import Optional def get_vt_retrohunt_files(vt_key: str, r_id: str, limit: Optional[int] = 100): """Retrieve file objects related to a retrohunt from VT.""" url = f"https://www.virustotal.com/api/v3/intelligence/retrohunt_jobs/{r_id}/matching_files?limit={limit}" data = vt_request(api_key=vt_k...
f29cdd1db8fc1b0559a49422df24a16e4708b493
28,222
import math def proj_make_3dinput_v2(project, angle = 15, start_slice = [0,0,0], crop_slice = [0.75, 0.625, 0.625]): """ This function unprojects 2d data into 3d voxel at different angles/views and do crop. :param project: 2d image input :param angle: the angle of different view. set max(1) as 0. ...
3867cd03cc9c7833a29c9f5d4d078b5caabe2b73
28,223
from ch07.digraph_search import topological_sort as ts def topological_sort(digraph): """Link in with Topological sort.""" return ts(digraph)
bb16ca7c44adf37893d47cfacd7d81ae0d646af6
28,224
def merge_scores(scores_test, scores_val): """ Aggregate scores """ scores_valtest = {} for key in scores_test: key_valtest = "final/" + key.split("/")[1] if key.startswith("test/"): keyval = "val/" + key.split("/")[1] value = 0.5 * (scores_test[key]["value"] ...
be0dded69367e7554c0cc2632946d46954a3cc15
28,225
def validateDate(data, name, published): """ Verify that a date string is valid. """ # Verify that if published exists it's a valid date date = parse_datetime(published) if not date: raise InvalidField(name, published) return published
d8a46a491f54cc571f2560a816d76c93a8af79cf
28,227
def join( group_id: int, db: Session = Depends(get_db), user: UserModel = Depends(get_active_user), ): """Join the group.""" return service.join(db, group_id=group_id, user_id=user.id)
cc3d329b36d04047030e8af4e2c0d0511605aa49
28,229
def calc_correlation(cs, lab): """ calc the spearman's correlation :param cs: :param lab: :return: """ rho, pval = spearmanr(cs, lab) return rho
a1768394ab94d8833cbbbd6eb32d927285bac4b8
28,230
def normalize(df): """Pandas df normalisation Parameters: df (pd df) : input df Returns: result (pd df) : output df """ result = df.copy() for feature_name in df.columns: max_value = df[feature_name].max() min_value = df[feature_name].min() result[feat...
2fc05fc9ef7642ac4b84cb6ed567ec64c1da0836
28,231
def cbv_decorator(decorator): """ Turns a normal view decorator into a class-based-view decorator. Usage: @cbv_decorator(login_required) class MyClassBasedView(View): pass """ def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) retu...
9811cc05bcf31cb5145cc0a4f089e40433446023
28,232
def _shift_anchors(anchors, direction): """Shift anchors to the specified direction """ new_anchors = deepcopy(anchors) if direction == 'center': pass elif direction == 'top': heights = new_anchors[:,3] - new_anchors[:,1] + 1 heights = heights[:,np.newaxis] new_ancho...
fbf48649c846bbb7275cb2a773f637f9bc7023f3
28,233
import itertools def enumerate_all_features(dim: int, num_values: int) -> chex.Array: """Helper function to create all categorical features.""" features = jnp.array(list(itertools.product(range(num_values), repeat=dim))) chex.assert_shape(features, [num_values ** dim, dim]) return features.astype(jnp.int32)
049178afae402a3c73fa3a547afc8be1640efd62
28,234
def convert_pad_shape(pad_shape): """ Used to get arguments for F.pad """ l = pad_shape[::-1] pad_shape = [item for sublist in l for item in sublist] return pad_shape
39e77b3931f29f3ab95a75662187e09df545364f
28,235
def PotentialWalk(pos, tree, softening=0, no=-1, theta=0.7): """Returns the gravitational potential at position x by performing the Barnes-Hut treewalk using the provided octree instance Arguments: pos - (3,) array containing position of interest tree - octree object storing the tree structure ...
6b03d5075df752bd5c7986da76ce8fc7c28ce10c
28,236
import re def GetProjectUserEmail(git_repo): """Get the email configured for the project.""" output = RunGit(git_repo, ['var', 'GIT_COMMITTER_IDENT']).output m = re.search(r'<([^>]*)>', output.strip()) return m.group(1) if m else None
2749a7797b4ef9c2d7532f31e8b8594f0cc9c174
28,237
from typing import Tuple def decode_features(features_ext, resource_attr_range: Tuple[int, int]): """ Given matrix of features from extended configs, corresponding to `ExtendedConfiguration`, split into feature matrix from normal configs and resource values. :param features_ext: Matrix of feature...
ffb709a8ef7f7da91a7b4b99c80b2f32ff66b66e
28,238
def get_event(): """ Get the event information of the group :param room_id: the room_id of the group """ incoming = request.get_json() event = Event.get_event_with_room_id(incoming['room_id']) if event: results = {'event_name': event.name, 'location': event.location, 'start_time'...
d6f9c581b563d3231ef9d40de557eee323025e4b
28,239
def test(model,X, y): """ Predicts given X dataset with given model Returns mse score between predicted output and ground truth output Parameters ---------- X: Test dataset with k features y: Ground truth of X with k features """ return mse(model.predict(X).flatten...
5e27125def948478b98eac997009de29a44a64a9
28,241
def solver(objectives): """Returns a solver for the given objective(s). Either a single objective or a list of objectives can be provided. The result is either an IKSolver or a GeneralizedIKSolver corresponding to the given objective(s). (see klampt.robotsim.IKSolver and klampt.robotsim.Gener...
685bed37629c57a7041f3cdcee0d98c3c93b1d77
28,242
def model_fn_builder(config: NeatConfig): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name...
572ceb93e9907e1bb960e3c66f34c14e8bacce7c
28,243
def solve_case(rectangle, tree, io_obj): """ Main program to recursively fill a rectangle with pentominos """ return tuple(map(_solve_rect_with_x(rectangle)(tree)([ len(rectangle) // 2, len(rectangle) % 2, len(rectangle[0]) // 2, len(rectangle[0]) % 2])(io_obj), tupl...
4afa8b6a1e723e5900d14ec252a131086b1b15f1
28,244
def keras_weights_to_caffemodel(keras_model): """ Only Implement the conv layer and fc layer :param keras_model: :return: """ net = caffe.Net() layers = keras_model.layers for layer in layers: if type(layer) == keras.layers.Convolution2D: w, b = layer.get_weights() ...
088c5040e3c3cba962d4fee7caee74761f9dbb21
28,245
def get_db(): """ :return: """ db = getattr(g, "_database", None) if db is None: db = g._database = connect() db.row_factory = make_dicts return db
d462dd6d82ce1c5f13ab5acfc3f613c4d9bdba33
28,246
import scipy def interpolate(X, Y, Z, x_coords, y_coords, factor=4, method='cubic'): """ :return: Interpolated X, Y, Z coordinate tuples, given by a factor, and a method in `scipy.interpolate.griddata` """ X_f, Y_f, Z_f = X.flatten(), Y.flatten(), Z.flatten() x_inter = scale(x_coords, fact...
6520fb7a9e1c7b25a3030d97ad9a43253fd7b976
28,247
def weighted_rmsd(x, y, weights=None, dim=None, apply_nan_mask=True): """ Compute weighted root-mean-square-deviation between two `xarray.DataArray` objects. Parameters ---------- x, y : `xarray.DataArray` objects xarray objects for which to compute `weighted_rmsd`. weights : array_like, ...
da975ff48dcdee1a7f2c44a58d171d7c4579e553
28,248
def _default_value(argument, default): """Returns ``default`` if ``argument`` is ``None``""" if argument is None: return default else: return argument
52eed8ddaf3c52adba69044cc462fc11279670c5
28,249
def all_feature_functions(): """ Returns all feature functions from the function module :rtype list[callable] :returns List of feature functions """ exclude = ['n_gram_frequency', 'term_frequency'] functions = [] for name in dir(features): feature_function = getattr(features, nam...
3e2fb73def3791a64d1e3868bf5c7188d593e3cf
28,251
def unsupplied_buses(net, mg=None, slacks=None, respect_switches=True): """ Finds buses, that are not connected to an external grid. INPUT: **net** (pandapowerNet) - variable that contains a pandapower network OPTIONAL: **mg** (NetworkX graph) - NetworkX Graph or MultiGraph that rep...
e8f7da1735ab56ad5a4ffd9b4ef27088b7e89fd1
28,252
def is_constant_type(expression_type): """Returns True if expression_type is inhabited by a single value.""" return (expression_type.integer.modulus == "infinity" or expression_type.boolean.HasField("value") or expression_type.enumeration.HasField("value"))
66a3237971299df3c7370f039d87a8b5f4ae2be5
28,254
def compute_tuning_improvement_sds_5_4(): """Compute average improvement during tuning, in sds""" data = _get_tuning_results_df() delta = data['delta'].dropna() result = delta.mean() fn = OUTPUT_DIR.joinpath('5_4_tuning_improvement_sds.txt') with fn.open('w') as f: f.write( ...
b1adc3c2c7f2dd22217ec4be63d8e6c49d5827bc
28,255
def make_grid(batch_imgs, n_rows): """Makes grid of images.""" batch_imgs = np.array(batch_imgs) assert len(batch_imgs.shape) == 4, f'Invalid shape {batch_imgs.shape}' batchsize, height, width, channels = batch_imgs.shape n_cols = (batchsize + n_rows - 1) // n_rows grid = np.zeros((n_rows * height, n_cols...
6da67c75407df6ff1a4b85e5a2c0aa6992a6ffe6
28,256
def jsonUsers(request): """Export user list to JSON""" user_list = list(CustomUser.objects.values()) return JsonResponse(user_list, safe=False)
625669fd38730b9fd759812b11904e5aef3bf76e
28,258
def farthest_point_sample(points, num_points=1024): """ Input: points: a point set, in the format of NxM, where N is the number of points, and M is the point dimension num_points: required number of sampled points """ def compute_dist(centroid, points): return np.sum((centroid - ...
a96ace38c6d2a18cc247e2131fc095eeccca1a84
28,259
def resolve_shx_font_name(font_name: str) -> str: """ Map SHX font names to TTF file names. e.g. 'TXT' -> 'txt_____.ttf' """ # Map SHX fonts to True Type Fonts: font_upper = font_name.upper() if font_upper in SHX_FONTS: font_name = SHX_FONTS[font_upper] return font_name
013e944160f7fc71849e3e7f6869620a1fd6a328
28,260
def select_event_by_name(session, event_name): """ Get an event by name Parameters ---------- session : database connexion session event_name : str name of the RAMP event Returns ------- `Event` instance """ event = session.query(Event).filter(Event.name ==...
779bf47b812fdc920ff4359f4766a63689ced195
28,261
import torch def attention_mask_creator(input_ids): """Provide the attention mask list of lists: 0 only for [PAD] tokens (index 0) Returns torch tensor""" attention_masks = [] for sent in input_ids: segments_ids = [int(t > 0) for t in sent] attention_masks.append(segments_ids) retu...
06a5880069cdc88ea33fe987bf4ac77aceef13eb
28,262
def extension_from_parameters(): """Construct string for saving model with annotation of parameters""" ext = '' ext += '.A={}'.format(ACTIVATION) ext += '.B={}'.format(BATCH_SIZE) ext += '.D={}'.format(DROP) ext += '.E={}'.format(NB_EPOCH) if FEATURE_SUBSAMPLE: ext += '.F={}'.format(...
009bd3dd0b105cbbd060ced37776e011487be415
28,263
def rotateBoard90(b): """b is a 64-bit score4 board consists of 4 layers Return: a 90 degree rotated board as follow (looking from above) C D E F 0 4 8 C 8 9 A B ==> 1 5 9 D 4 5 6 7 2 6 A E 0 1 2 3 3 7 B F """ return rotateLayer90(b & 0xFFFF) \ | rota...
d4069e8f7953abdcf56fc9bc713da69e33f1fdbe
28,265
def register_preset_path(path): """Add filepath to registered presets :param path: the directory of the preset file(s) :type path: str :return: """ if path in _registered_paths: return log.warning("Path already registered: %s", path) _registered_paths.append(path) return path
231d151c0b01e13312539ad592faa9f01acdce42
28,266
def set_pause_orchestration( self, ne_pk_list: list[str], ) -> bool: """Set appliances to pause orchestration .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - pauseOrchestration - POST - /pauseOrchestration ...
72ebb32a6bc1bef1faf09f646dfad90a9b29da32
28,267
def unwrap(value: str, wrap_char: str) -> str: """Unwraps a given string from a character or string. :param value: the string to be unwrapped :param wrap_char: the character or string used to unwrap :return: unwrapped string or the original string if it is not quoted properly with the w...
d1c1aceb0c92e0ccda26f6444eea5056c56d5d44
28,268
def round_to_memory_units(memory_bytes, round_up): """Round bytes to the nearest memory unit.""" return from_memory_units(to_memory_units(memory_bytes, round_up))
9402592d20832dd3149e8b9bc14115711aeee51a
28,269
import gettext import types def clone(translation): """ Clones the given translation, creating an independent copy. """ clone = gettext.GNUTranslations() clone._catalog = translation._catalog.copy() if hasattr(translation, 'plural'): clone.plural = types.FunctionType( translation.p...
269756db03954d7b6539e941fe07db532e81b17d
28,271
def get_general_channel(): """Returns just the general channel of the workspace""" channels = get_all_channels() for channel in channels: if (channel['is_general']): return channel
f350c87a57dc54580729a29b456e25d5b0c6797f
28,272
def nonrigid_rotations(spc_mod_dct_i): """ Determine if the rotational partition function for a certain species should be calculated according to some non-rigid model. This determination solely relies on whether has specified the use of a non-rigid model for the species. :param spc...
5ef94d4dc1b267ffab6bb654d58aae592b69d367
28,273
def general_standing(): """ It gives the general standing based on the current matchday. Note that it depends on the parameters that are imported at the beginning of the notebook, specifically Results, hence in order to refresh it needs to be run after Results is created from the utilities script. T...
2a5f48a34209ff9568b9c4afb447df4eac944391
28,274
def pixwt(xc, yc, r, x, y): """ ; --------------------------------------------------------------------------- ; FUNCTION Pixwt( xc, yc, r, x, y ) ; ; Compute the fraction of a unit pixel that is interior to a circle. ; The circle has a radius r and is centered at (xc, yc). The center of ; t...
35e8937456fa1a4c8ca251ff55449001c6f64859
28,275
def predict(net, inputs, use_GPU=False, in_type='numpy'): """Make predictions using a well-trained network. Parameters ---------- inputs : numpy array or torch tensor The inputs of the network. use_GPU : bool If True, calculate using GPU, otherwise, calculate using CPU. ...
4a07a8171024fe50f56a94a416f4745f8db01759
28,276
def svn_mergeinfo_catalog_merge(*args): """ svn_mergeinfo_catalog_merge(svn_mergeinfo_catalog_t mergeinfo_catalog, svn_mergeinfo_catalog_t changes_catalog, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t """ return _core.svn_mergeinfo_catalog_merge(*args)
dd79ece86fab697b519f4ec2b5b294e085701364
28,279
import numpy def normalize_const(v): """ Normalize a numpy array of floats or doubles. """ return v / numpy.linalg.norm(v)
927ad9d2d94735263ac10a445f4f7fe4b3150c95
28,280
import collections def make_lc_resolver(type_: type[_T], /) -> collections.Callable[..., collections.Awaitable[_T]]: """Make an injected callback which resolves a LazyConstant. Notes ----- * This is internally used by `inject_lc`. * For this to work, a `LazyConstant` must've been set as a type ...
30190cfb0f74eab96bafabfc55ef63d18ea25a0f
28,282
import hashlib def get_md5(string): """ Get md5 according to the string """ byte_string = string.encode("utf-8") md5 = hashlib.md5() md5.update(byte_string) result = md5.hexdigest() return result
968b8f8ec28720e4ed4d020093f815b6af33eea7
28,283
def clean_docs_and_uniquify(docs): """ normalize docs and uniquify the doc :param docs: :return: """ docs = [normalize(t) for t in docs if isinstance(t, str)] docs = dedupe(docs) return docs
6a267c1b5b6744cf28b2b6c73e6cf49f25f95727
28,284
from typing import Any import torch def shard_init_helper_(init_method, tensor: Tensor, **kwargs: Any) -> None: """ Helper function to initialize shard parameters. """ if hasattr(tensor, _PARALLEL_DIM): local_rank = get_rank() group = get_group() world_size = get_world_size() ...
df692b2766ed49d3358c72450aa5d4159915e4b5
28,285
def segment_zentf_tiling(image2d, model, tilesize=1024, classlabel=1, overlap_factor=1): """Segment a singe [X, Y] 2D image using a pretrained segmentation model from the ZEN. The out will be a binary mask from the prediction of ZEN ...
7f88124b86bfe6bde147aeedd9385ea7b19063e3
28,286
def key2cas(key): """ Find the CAS Registry Number of a chemical substance using an IUPAC InChIKey :param key - a valid InChIKey """ if _validkey(key): hits = query('InChIKey=' + key, True) if hits: if len(hits) == 1: return hits[0]['rn'] else:...
d0919e2e6c1b6b149409e2b6333bcd3129c53379
28,288
import time import re def connect_server(server, username, startpage, sleep_func=time.sleep, tracktype='recenttracks'): """ Connect to server and get a XML page.""" if server == "libre.fm": baseurl = 'http://alpha.libre.fm/2.0/?' urlvars = dict(method='user.get%s' % tracktype, ...
694bfa6b1ace0ed51338983b4901f06c78f44afd
28,289
def eigenvalue_nonunitary_diamondnorm(A, B, mxBasis): """ Eigenvalue nonunitary diamond distance between A and B """ d2 = A.shape[0] evA = _np.linalg.eigvals(A) evB = _np.linalg.eigvals(B) return (d2 - 1.0) / d2 * _np.max(_tools.minweight_match(evA, evB, lambda x, y: abs(abs(x) - abs(y)), ...
97716d88829e4bf0beef914f38bd40d24c1fc32a
28,290
def str_to_int(value): """Convert str to int if possible Args: value(str): string to convert Returns: int: converted value. str otherwise """ try: return int(value) except ValueError: return value
30bd55fc34abffa67c79117b0941ba7e6388efeb
28,291
import json def json_response(data): """this function is used for ajax def route(request): return json_response(t.json()) """ header = 'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n' body = json.dumps(data, ensure_ascii=False, indent=8) r = header + '\r\n' + body return r....
8678a8f62fab10d9120d354889387b6d70cddea9
28,292
from operator import sub from operator import add def linePointXY(l,p,inside=True,distance=False,params=False): """ For a point ``p`` and a line ``l`` that lie in the same XY plane, compute the point on ``l`` that is closest to ``p``, and return that point. If ``inside`` is true, then return the clos...
b91f1497ba2dffb72caa4cbf4a6f43972ee3853e
28,293
def config_port_type(dut, interface, stp_type="rpvst", port_type="edge", no_form=False, cli_type="klish"): """ API to config/unconfig the port type in RPVST :param dut: :param port_type: :param no_form: :return: """ commands = list() command = "spanning-tree port type {}".format(port...
a0a8672b3fea945a57367236debd1a420e270185
28,294
def check_strand(strand): """ Check the strand format. Return error message if the format is not as expected. """ if (strand != '-' and strand != '+'): return "Strand is not in the expected format (+ or -)"
9c2e720069ad8dcc8f867a37925f6e27e91dcb3f
28,296
def to_halfpi(rin, za): # match with a shunt input l net, rin > za.real """ """ ra, xa = za.real, za.imag xd = np.sqrt(ra * (rin - ra)) if np.iscomplex(xd): raise ValueError x2 = np.array([-xa - xd, -xa + xd]) x1 = -(ra**2 + (x2 + xa)**2) / (x2 + xa) return np.transpose([x1 * 1j, x2...
210e4bb008cd58323fab1ab66ad6ef84456c569b
28,297
from pathlib import Path import yaml def load_config_or_exit(workdir="."): """Loads the challenge configuration file from the current directory, or prints a message and exits the script if it doesn't exist. Returns: dict: The config """ path = Path(workdir) if (path / "challenge.yml").exi...
e58a7725422d3ae053ab56ae81ab98a7d13be0b5
28,298
def checkOnes(x, y): """ Checks if any of the factors in y = 1 """ _ = BranchingValues() _.x = 1 for i in _range(len(y)): if _if(y[i][0] == 1): _.x = 0 _endif() if _if(y[i][1] == 1): _.x = 0 _endif() _endfor() return _.x
fec6b2aeae13750ec1b37d4b5d187d6836ab5aaa
28,299
def read_fortran_namelist(fileobj): """Takes a fortran-namelist formatted file and returns appropriate dictionaries, followed by lines of text that do not fit this pattern. """ data = {} extralines = [] indict = False fileobj.seek(0) for line in fileobj.readlines(): if indic...
3c3b96ca707c7f0492c2913c6b9496cb57fc969b
28,301
from typing import Tuple import re def check_token(surface: str) -> Tuple[str, str]: """Adopted and modified from coltekin/childes-tr/misc/parse-chat.py For a given surface form of the token, return (surface, clean), where clean is the token form without CHAT codes. """ if surface is None: return None, None ...
c737c8acdce04597506e399a7d2fe0252634edc1
28,302
def remove_media_url(media_path): """ Strip leading MEDIA_URL from a media file url. :param media_path: :return: """ if media_path.startswith(MEDIA_URL): return media_path[len(MEDIA_URL):] else: return media_path
084773d30cc9c534a9347712058c581797a2b05b
28,303
def _map_route_on_graph(ordered_cluster: sp.Cluster, graph: sp.Graph) -> list[sp.Segment]: """Построить маршрут в графе Args: ordered_cluster: Кластер с заданным порядком обхода точек graph: Граф для прокладывания маршрута Returns: Построенный маршрут """ route = [] # Пут...
1ca10abc6f9d88c08dbbbd63b48e62f7077c8a39
28,304
from typing import Tuple from typing import Dict def list_violation_data(client: Client, args) -> Tuple[str, Dict, Dict]: """List violation data. Args: client: Client object with request. args: Usually demisto.args() Returns: Outputs. """ from_ = args.get('from') to_ ...
c7548b7a86bb63855ee5c9fc7ec602ffa39a608b
28,305
def train_add_test(func=lambda a, b: a+b, results_dir=None, reg_weight=5e-2, learning_rate=1e-2, n_epochs=10001): """Addition of two MNIST digits with a symbolic regression network. Withold sums > 15 for test data""" tf.reset_default_graph() # Symbolic regression network to combine the conv net outputs...
9705cfb8cc8a321c16eb6f93dda1878e73e9328f
28,306
def walk_graph(csr_matrix, labels, walk_length=40, num_walks=1, n_jobs=1): """Perform random walks on adjacency matrix. Args: csr_matrix: adjacency matrix. labels: list of node labels where index align with CSR matrix walk_length: maximum length of random walk (default=40) num_w...
4a317aecbc88998469420575346c38da30f8bc90
28,307
def mutate_split(population, config): """ Splitting a non-zero dose (> 0.25Gy) into 2 doses. population - next population, array [population_size, element_size]. """ interval_in_indices = int(2 * config['time_interval_hours']) mutation_config = config['mutations']['mutate_split'] min_dose =...
db737191d5f7c1852410d6f1ad779e8ca58c658a
28,308
def _copy_df(df): """ Copy a DataFrame """ return df.copy() if df is not None else None
263bf1cf9cbdae371ea3e4685b4638e8a5714d7f
28,309
def findPossi(bo): """ Find all possibilities for all fields and add them to a list.""" possis = [] for row,rowVal in enumerate(bo): for col,colVal in enumerate(rowVal): localpossi=newPossiFinder(bo, col, row) if bo[row][col]==0: # Here ujson.loads(ujson.dump...
c504ca243f631af135ae64f97b9f46b2cdb7d789
28,310
def modernforms_exception_handler(func): """Decorate Modern Forms calls to handle Modern Forms exceptions. A decorator that wraps the passed in function, catches Modern Forms errors, and handles the availability of the device in the data coordinator. """ async def handler(self, *args, **kwargs): ...
c486173ef34f4c89fb3138cad989472f01d7bb7c
28,311
def reads_per_insertion(tnpergene_list,readpergene_list,lines): """It computes the reads per insertion following the formula: reads/(insertions-1) if the number of insertions is higher than 5, if not then the reads per insertion will be 0. Parameters ---------- tnpergene_list : list A...
c5a3f06298d2e782d60b20d561d9d5f65a369dcd
28,312
def getCurrDegreeSize(currDegree, spatialDim): """ Computes the number of polynomials of the current spatial dimension """ return np.math.factorial(currDegree + spatialDim - 1) / ( np.math.factorial(currDegree) * np.math.factorial(spatialDim - 1))
754440fde04f7fe30e336cf4d7c5efb75dd1aaac
28,313
def split_last_dimension(x, n): """Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: x: a Tensor with shape [..., m] n: an integer. Returns: a Tensor with shape [..., n, m/n] """ x_shape = shape_list(x) m = x_...
c1f26106e0d11a5722191a52c86f90b9559d32dc
28,314
def get_column_dtype(column, pd_or_sqla, index=False): """ Take a column (sqlalchemy table.Column or df.Series), return its dtype in Pandas or SQLA If it doesn't match anything else, return String Args: column: pd.Series or SQLA.table.column pd_or_sqla: either 'pd' or 'sqla': which kin...
c466405c66b24d48cc37920df2876e876d1d6885
28,316
def _stdlibs(tut): """Given a target, return the list of its standard rust libraries.""" libs = [ lib.static_library for li in tut[CcInfo].linking_context.linker_inputs.to_list() for lib in li.libraries ] stdlibs = [lib for lib in libs if (tut.label.name not in lib.basename)] ...
8098406876684911df5c52413780305bea2d12a7
28,317
def _chebyshev(wcs_dict): """Returns a chebyshev model of the wavelength solution. Constructs a Chebyshev1D mathematical model Parameters ---------- wcs_dict : dict Dictionary containing all the wcs information decoded from the header and necessary for constructing the Chebyshev1D...
3d30fde977351a4e43a0940696c8fc988400ccda
28,318
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except Value...
a4db1dedffdccc44d7747c4743f4f2eaf8dbd81a
28,319
from bs4 import BeautifulSoup import http def request_champion(champion_name: str) -> BeautifulSoup: """ Get http request to website with all statistics about a champion with html format. """ request = http.request( 'GET', f'https://www.leaguespy.gg/league-of-legends/champion/{cham...
f0b5a0b1eb6cceec6c7e1c8c8cd1078a5f2505c3
28,320