content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def filter_endpoints(end_points): """ Keep only conv layers and reshape into [Nl x Ml] matrixes """ d = {} for k, v in end_points.items(): if 'conv' in k: el = tf.squeeze(v) n_f = el.shape[-1] el = tf.reshape(el, (-1, n_f)) el = tf.transp...
1e0088d489dfebfb2d0b60f6324954017d1a2771
3,598,246
def validate(X, Y): """ 校验X和Y的格式是否正常,如果不正常,返回False;否则返回True :param X: :param Y: :return: """ m1, n1 = np.shape(X) m2, n2 = np.shape(Y) if m1 != m2: return False else: if n2 != 1: return False else: return True
44de6cb937b6e0db810fb569b654b91dcea7a361
3,598,248
def quote_aware_split(string, delim=',', quote='"'): """ Split outside of quotes (i.e. ignore delimiters within quotes.""" out = [] s = '' open_quote=False for c in string: if c == quote: open_quote = not open_quote if c == delim and not open_quote: out += [s...
0ef5f7040eee2a041fa1b6e6d8bf3a773a80f5f9
3,598,249
def NormalizarSerie(SR): """ Descripción: ----------- Normaliza una serie basandose en maximo y minimo Haciendo que la misma se encuentre entre 0 y 1 Un ejemplo de uso seria normalizar el DPO y operar en 0.2 para la compra y 0.5 para la venta (estrategia comprado) Parametros ...
6e7a9f0b2dd9be0fd82712ab5c9176e245e34549
3,598,250
def is_const(array, *, is_const=_speedups and _speedups.is_const): """Returns if the given array is constant""" if is_const: res = is_const(array) if res is not None: return res if array.size == 0: return True else: return (array == array[0]).all()
d5a5ceb519b3f0a7433ea6ff7860a9650a4b6d8f
3,598,251
def entropy(x): """ calculate shanno ent of x """ x_value_list = set([x[i] for i in range(x.shape[0])]) ent = 0.0 for x_value in x_value_list: p = float(x[x == x_value].shape[0]) / x.shape[0] logp = np.log2(p) ent -= p * logp return ent
86e3e999501a38e3143c244c736a51855dfcc431
3,598,252
def MinMaxScaler(x, min_value=0, max_value=1): """ :brief: Normalizes data using the min max scaling. :param x: are the data :param min_value: is the minimum value :param max_value: is the maximum value :return: scaled data """ data_size = len(x) dimensions = len(x[0]...
88e11f79cb84800cef56950f8e120eaa6de6ee3f
3,598,253
def _define_rt_plan(ds: Dataset) -> Dataset: """Return an RT PLAN directory record from `ds`.""" _check_dataset(ds, ["InstanceNumber", "RTPlanLabel"]) record = Dataset() record.InstanceNumber = ds.InstanceNumber record.RTPlanLabel = ds.RTPlanLabel record.RTPlanDate = ds.get("RTPlanDate") re...
aad48d9b4317151fd973b41f0a2331377d42adaa
3,598,254
def NcbiTaxonomyFromFiles(nodes_file, names_file, strict=False): """Returns new NcbiTaxonomy fron nodes and names files.""" taxa = NcbiTaxonLookup(NcbiTaxonParser(nodes_file)) names = NcbiNameLookup(NcbiNameParser(names_file)) return NcbiTaxonomy(taxa, names, strict)
a4ff1dc311b9c3aa0505304585bdc2e3354da591
3,598,256
def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): """ Get all execution minutes for the days between start and end, inclusive. """ start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day ...
514c7a1dfc28579cbb0c4203599eb80d7480df61
3,598,257
def new_action(parent, text, slot=None, shortcut=None, icon=None, tip=None, enabled=True): """actionの設定と取得""" # アクション取得 a = QAction(text, parent) # icon設定 iconsフォルダから取得 if icon is not None: a.setIcon(QIcon('icons/'+icon)) # ショートカット作成 if shortcut is not None: if isinstance(sho...
a02051154fec7d69ddca8a01073e9367e3e695ba
3,598,258
def _millis(when): """Convert a zone-aware datetime to integer milliseconds. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: int :returns: milliseconds since epoch for ``when`` """ micros = _microseconds_from_datetime(when) return micros // 1000
4eed9d17bf127d9b0794a539e58f4118dca415bd
3,598,259
import re import code def clean_python_code(python_code, isort=True, black=True, autoflake=True): """Clean Python code.""" # Temporarily comment out IPython %magic to avoid Black errors. python_code = re.sub("^%", "##%##", python_code, flags=re.M) # Run source code string through autoflake, isort, an...
5c9e875c5de8b688331467392c8011633d69adee
3,598,260
from re import T def check_opt_isinstance(item: T, classinfo: _ClassInfo) -> T: """ Checks something is ether None or an instance of a given class. Raises a TypeError otherwise """ if item and not isinstance(item, classinfo): raise TypeError( "Expected instance of type {!r} bu...
d6d4a439ded2aedd3a243e48b8c2e101be18f5bd
3,598,261
def getcwd(): """Return a string representing the current working directory. :rtype: string """ return ''
31ba3c781dad707ef5feaa15a841d8d528ded3e3
3,598,262
def getRenamingCommands(): """ Get all available L{renamer.irenamer.IRenamingCommand}s. """ return getPlugins(IRenamingCommand, plugins)
60b9a11d04ccab30d2dbadeb6103932115950b64
3,598,263
def _tess_ffi_file(file_name): """ TESS FFI File """ # tess2018229142941-s0001-4-3-0120-s_ffic.fits # yyyyddd sssss ccc # s0001/2018/229/4-3 # 18-23 4-8 8-11 24-27 sector = file_name[18:23] year = file_name[4:8] day_number = file_name[8:11] camera_chip = file_name[24:27] ...
8a0381c1c6566ecd518e8e7c0033453a1a9e66fe
3,598,264
def pairwise_distance(feature, squared=False): """Computes the pairwise distance matrix with numerical stability. output[i, j] = || feature[i, :] - feature[j, :] ||_2 Args: feature: 2-D Tensor of size [number of data, feature dimension]. squared: Boolean, whether or not to square the pairwise ...
eb53830e8e11309c17ea2b3e5e0bae5d87aeafee
3,598,266
def path_specific_constraints(prefix, constraints, var_mapping): """Creates duplicate constraints with all variables replaced with path specific copies""" new_constraints = [] for cs in constraints: new_cs = [path_specific_expr(prefix, c, var_mapping) for c in cs] new_constraints.append...
0a0344f7e811dd1bdfa04fe251359bea23b74472
3,598,267
import torch def get_style_grams(style_im, cfg): """ Computes the style grams for the vgg activations of the given style image. Args: --style_im: <tensor> The pre-processed style image. Should have shape (ch, h, w) --cfg: <dict> The training config dictionary Returns: <list> The ...
c2f9e30cd42d99b548875860fb6ff6c3373c81bc
3,598,268
import torch def fft_shift(input: torch.Tensor) -> torch.Tensor: """ PyTorch version of np.fftshift Args - input: (Bx)CxHxWx2 Return - ret: (Bx)CxHxWx2 """ dims = [i for i in range(1 if input.dim() == 4 else 2, input.dim() - 1)] # H, W shift = [input.size(dim) // 2 for dim in dim...
9a08c3e33516378b80a7a53cf17915d9baa5d290
3,598,269
from typing import Callable def fcn_from_str(name: str) -> Callable: """ Get the matching function. This method is a workaround / utility tool to intended to work with optuna. Since we can not pass functions directly, we pass a sting. :param name: name of the function :return: the function ""...
abcf93d1c13e484d375d55550e3e0e599cdbdeba
3,598,270
from typing import Mapping from typing import Any import json def get_config(config_path: str = "secrets/config_oauth.json") -> Mapping[str, Any]: """ Get the config from /test_input """ with open(config_path, "r") as f: return json.loads(f.read())
9ad1726bc5b1017f47872ce422d1c7a6fbf5d59c
3,598,271
def flop(x): """ Flops each 1/2 byte with the adjacent 1/2 byte. Flop is its own inverse. """ left = x & FLOP_MASK right = x & ~FLOP_MASK return ((right << 4) | (left >> 4)) & ID_MASK
8b0208c11cbab8a92671de2ccdc94f7c030bce9a
3,598,272
def get_view_proxy_registration_name(proxy): """Assuming the given proxy is registered in the group 'views', lookup the proxy's registration name with the servermanager""" return servermanager.ProxyManager().GetProxyName("views", proxy)
a85cd2dfbc83e2d94a14413a9174ce0f288e7529
3,598,273
def LMpM_total_size(ell_min, ell_max): """Total array size of Wigner D matrix Assuming an array (e.g., Wigner D matrices) in the order [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] this function returns the tot...
7a6175640236ec3bc905d3b458f99eedbc792e09
3,598,274
def get_signature_locals(f, loc): """Filters locals to only include keys in original method signature""" return {k: v for k, v in loc.items() if k in signature(f).parameters}
d157623fc0af02e2de6518697b2f2c8a59a72f96
3,598,275
def filter_factory(global_conf, **local_conf): """ paste.deploy app factory for creating WSGI proxy apps. """ conf = global_conf.copy() conf.update(local_conf) if config_true_value(conf.get('read_only')): register_swift_info('read_only') def read_only_filter(app): return Re...
d6ea8e82d61b38f37f8400f0534a063452bc28fc
3,598,276
def map_obs_subfields(epochs_selec, obs_fieldID, obs_subfield, mapdic): """Return boolean array corresponding to observed subfields. Parameters ---------- epochs_selec : numpy.array(bool) Actual observations selection. obs_fieldID : bool Id of pre selected observed fields. obs_s...
a27b1c37ec827b4a2f1dee0a6cc930c253676739
3,598,277
def value_at_depht_in_BT(tree, depth): """ O(n) time O(n) space """ if depth == 0: return [tree.value] if tree.left and tree.right: return []+value_at_depht_in_BT(tree.left, depth-1)+value_at_depht_in_BT(tree.right, depth-1) if tree.left: return []+value_at_depht_in_BT(tree.left, depth-1) if tree.right:...
dc4bcc8398fe1357d0fb8a903b26828cd20c093d
3,598,278
def load_base_library(): """Load style library defined in this package.""" library = read_style_directory(BASE_LIBRARY_PATH) return library
b027dfcbc8a622a37689470ecb3a1d3a83edffd7
3,598,279
def hdbx_keymap(): """ HDBX配列 デフォルトレイヤーをこの配列にしたい場合は、AdjustレイヤーでK (Lower + Raise + K) ,----------------------------------. ,----------------------------------. | Q | W | E | , | . | | Y | D | P | F | : | |------+------+------+------+------| ...
3cd38fc34ffc4a76398d04163478a8db4791f873
3,598,280
def get_fcurve_data_path_property(fcurve): """ Gets fcurve's data path property Example fcurve's data_path: 'sequence_editor.sequences_all["Transform"].scale_start_x' For that example path this function will return 'scale_start_x' :param fcurve: Fcurve instance to get data path from :return: The la...
0a7ce5fecdaa5cb1fe0024a18f6b6f057b5fe6cb
3,598,281
import torch import tqdm def train(config_path, model_path, model_type, src_filename, trg_filename): """ flags: saveto: str reload: store_true config_path: str pretrain_path: str, default="" model_name: str log_path: str """ # ==========================...
c1d085c9cd458543c6978bb919c806ccc816560e
3,598,282
import ctypes import numpy def ctypes2numpy(cptr, length, dtype): """convert a ctypes pointer array to numpy array """ assert isinstance(cptr, ctypes.POINTER(ctypes.c_float)) res = numpy.zeros(length, dtype=dtype) assert ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]) return res
d4f85de74946e5477f2f29bfa5cce119d3fe66a3
3,598,284
def align(offset, alignment): """ Return the offset aligned to the nearest greater given alignment Arguments: - `offset`: An integer - `alignment`: An integer """ if offset % alignment == 0: return offset return offset + (alignment - (offset % alignment))
1f9d8fd4d4ac7798e14ee92d83510bb4b0ba09aa
3,598,285
def update_path(alpha, beta, gradE, delta, T=100, k=5): """ Update the path along the direction -gradE :param alpha: numpy ndarray of shape (2,M) of M samples :param beta: numpy ndarray of shape (2,M) of M samples :param gradE: numpy ndarray of shape (2,M) of M samples :param delta: gradient pa...
b570d447dbc1eabc5b58e3be8fe68577b0c572fb
3,598,286
def convert_str_length_to_int(length): """ Convert a position in char to integer """ if type(length) is int: return length if length in "0123456789": return int(length) elif length <= "Z" and length >= "A": return ord(length) - ord("A") + 10 elif length == "z": return...
d89a56bbf542f8c76cee219b1759a054c6894119
3,598,287
from typing import Tuple def angles(a: float, e: float, r: float) -> Tuple[float, float]: """ theta = arccos((a * (1 - e * e) - r) / (e * r)) :param a: semi-major axis :type a: float :param e: eccentricity :type e: float :param r: radius vector :type r: float :return: the two thet...
8a6796dbcef6f9044d4f51811462087ad0b59e76
3,598,288
def parse_property_string(prop_str): """ Generate valid property string for extended xyz files. (ref. https://libatoms.github.io/QUIP/io.html#extendedxyz) Args: prop_str (str): Valid property string, or appendix of property string Returns: valid property string """ if prop_...
24a865dcf2cba5b5f840e3e682fd58486b658355
3,598,289
def getPacketKey(opCode): """ Gets the packet key for a given instruction Input: - opCode: The opcode of instruction for which the packet key has to be generated Output: - The packet keys initialized in packetDict function for the given opcode """ if opCode in ["00000", "00001", "0001...
c7730a444a4e8dacc20ae83038ddfc04ca5ba721
3,598,290
import torch def stack_sample(sample): """Stack a sample from multiple sensors""" # If there is only one sensor don't do anything if len(sample) == 1: return sample[0] # Otherwise, stack sample stacked_sample = {} for key in sample[0]: # Global keys (do not stack) if k...
1b17f43b048a86759409ee5b6cdbc506c36a588b
3,598,291
def map_to_legacy_object_map(m): """Converts a Soy map to a Soy legacy_object_map. legacy_object_maps must have string keys, but maps do not have this restriction. Args: m: Map to convert. Returns: An equivalent legacy_object_map, with keys coerced to strings. """ return {str(key): m[key] for k...
17423488a85011c7be5429af58a5baf26ab8e30a
3,598,292
def getLastRecords(desde, hasta): """ Esta tabla retorna una lista de tuplas de la forma (id_segment, data, timestamp) con los ultimos registros agregados a la tabla "historical" """ # realizando una consulta # desde = datetime.datetime.strptime(desde, '%Y-%m-%dT%H:%M:%S-03:00') # hasta = da...
eaa41ea6ba981701dfe21c3108723b2240e940bf
3,598,293
def Terrahawk(): # A.K.A. the Dillon Mayhew Matroid """ Return the Terrahawk matroid. The Terrahawk is a binary matroid that is a sporadic exception in a chain theorem for internally 4-connected binary matroids. See [CMO2011]_. EXAMPLES:: sage: M = matroids.named_matroids.Terrahawk() ...
c48dfda7e7ac4132aa274f2e83f61a9ccf83baca
3,598,294
def session_mm_secondary_master_tcp_master_publish_pull(): """ Returns an unused localhost port """ return get_unused_localhost_port()
a01d291f9ba18cd87e7d2a6ffc292bc004386b16
3,598,295
def MikotaPair(n): """Build a pair of full diagonal matrices for the generalized eigenvalue problem. The Mikota pair acts as a nice test since the eigenvalues are the squares of the integers n, n=1,2,... """ x = np.arange(1, n+1) B = diag(1./x) y = np.arange(n-1, 0, -1) z = np.arange(2*n...
3091f54c44a910a787748d204bb692d425f62a6c
3,598,296
def as_composite(identifier: str) -> str: """ Translate the identifier of a mapry composite to a composite name in C++. :param identifier: mapry identifier of a composite :return: translated to a C++ identifier of a composite >>> as_composite(identifier='Some_URL_class') 'SomeURLClass' ""...
9a702dbd2f9b4dfb65102a18f4924be432a85282
3,598,297
def create_rsa_public_and_private_from_pem(pem, passphrase=None): """ <Purpose> Generate public and private RSA keys from an optionally encrypted PEM. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ... ---...
1c11fa3d8e761992fdc4212e90f373465a103907
3,598,298
def notas(*n, sit=False): """ -> Função para avaliar a situação de varios alunos :param n: uma ou mais notas dos aluno :param sit: valor opcional, indica se deve ou não colocar a sitação :return: dicionário com várias informaçoes sobre a sitação da turma """ bib = dict() soma = 0 bib...
d10baf761af8ece8eaa1a7e2afce2299643e474f
3,598,300
def get_user_from_token(token): """ Return user from authorization token. Args: token: authorization token instance. Returns: user instance or AnonymousUser. """ if token: backend_path = token.backend if backend_path in django_settings.AUTHENTICATION_BACKENDS and...
c6aeb7ef73d45eec447fa28eeb1e47e249243e30
3,598,302
from typing import List def _format_plugin_names_and_versions(plugininfo) -> List[str]: """Format name and version of loaded plugins.""" values: List[str] = [] for _, dist in plugininfo: # Gets us name and version! name = f"{dist.project_name}-{dist.version}" # Questionable conveni...
2313f2f60e71be2209ebb201297d44e8dcad513a
3,598,303
def ix_neighbors(site, dims=None, radius=1): """ use np.ix_ instead of np.meshgrid -- requires less memory """ index = np.unravel_index(site, dims=dims) id_range = [np.arange(idx-radius, idx+radius+1) for idx in index] neighs = np.ravel_multi_index(np.ix_(*id_range), ...
896c126d7afbf36c76d81ad0b4c614ef6e262dbc
3,598,304
from typing import Dict from typing import Callable from typing import Set def state_enumeration(init_dist: Dict[State, int], rule: Callable[[State, State], Output]) -> Set[State]: """Finds all reachable states by breadth-first search. Args: init_dist: dictionary mapping states to counts ...
39c73e4536d6e614c8b7d73d527ac2bcf7d36127
3,598,305
def make_datagrid(x): """returns a MyDataGrid object""" return MyDataGrid(x)
e6292d5c7f564a12acc7c071ea22b0685686b1d9
3,598,306
def dist_string(dist): """Formats a distance (a float) as a colorized similarity percentage string. """ out = u'%.1f%%' % ((1 - dist) * 100) if dist <= config['match']['strong_rec_thresh'].as_number(): out = ui.colorize('text_success', out) elif dist <= config['match']['medium_rec_thresh...
1a316130d3fe71e41fae077b9ae06014e96aeb9b
3,598,307
def do_category_choice(available_categories, dice): """ Ask the player to interactively choose a scoring category, on the command-line. :param available_categories: the categories available for the player to choose from :param dice: the dice the player previously rolled :return: the category chosen...
f401a772636f0b5699e5b076b689cc46a4f9cc53
3,598,308
def star_sub_sections(body:str): """ Change \subsection \subsubsection To: \subsection* \subsubsection* """ body = body.replace(r'\subsection',r'\subsection*') body = body.replace(r'\subsubsection',r'\subsubsection*') return body
06583d16c76393edb614955c4e3786b292c5fa51
3,598,311
def clean_temerature_usa_data(temperature_usa_df: psd.DataFrame, spark: pss.SparkSession) -> psd.DataFrame: """[This cleans temperature data in USA. It casts date, city, average recorded temperature, and port entry.] Args: temperature_usa_df (psd.DataFrame): [spark dataframe that describes average temp...
4d3880609cc1465db108f451ea132814aa160536
3,598,313
def rjd_to_mjd(rjd): """ RJD (Reduced Julian Date) days elapsed since 1858-11-16T12Z (JD 2400000.0) MJD (Modified Julian Date) days elapsed since 1858-11-17T00Z (JD 2400000.5) This function transforms RJD in MJD """ return rjd - 0.5
2b1f4d830670f754fbbc2259face4d261877d335
3,598,314
from typing import List from typing import Dict from typing import Optional from typing import Tuple from typing import Iterable async def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects total attac...
3f5d2f9022ae2eab8ebcc4215248749eafe686ab
3,598,315
def combine_last_two_dimensions(x): """Reshape x so that the last two dimension become one. Args: x: a Tensor with shape [..., a, b] Returns: a Tensor with shape [..., ab] """ old_shape = x.get_shape().dims a, b = old_shape[-2:] new_shape = old_shape[:-2] + [a * b if a and b else Non...
c059f577848f0d83c7c7b8536678151c4cbf1029
3,598,316
def discretizer(df_list, names, config): """ concat the df_list as one pd.DataFrame then using sklean.KBinsDiscretizer depart it, Parameters ---------- df_list: object a collection of one or more pd.DataFrame. they must have one column named 'id' for indexing. names : list a lis...
946549faafaa79cf5a2e3c50244be7381dcea64b
3,598,317
import torch def MixtureDensityLSTMLoss(trueLatents, predMu, predSigma, predMDLogProbs): """Computes the loss for a MixtureDensityLSTM model Loss per sample is defined as the negative of the log probability, which is then reduced across the batch Args: trueLatents: Actual latents observed (th...
52e680ce0dca62952ea1e4c870463b9893e2aa72
3,598,318
def post_key(name="default"): """It builds a new Key object from posts.""" return db.Key.from_path("posts", name)
09d080f5ca2810b45bb408428240b89e98c8a379
3,598,319
def arg_xor_dict(args_array, opt_xor_dict): """Function: arg_xor_dict Description: Does a Xor check between a key in opt_xor_dict and its values using args_array for the check. Therefore, the key can be in args_array or one or more of its values can be in arg_array, but both can not...
08001050d5e542bcd09343920c49e8bb59c9c7a6
3,598,321
from typing import List def process_ancrubadan_data(ac_file: str) -> List[str]: """Processes An Crubadan file into list of strings for normalization. An Crubadan data format is the word, followed by a space, followed by the total count of that word in the corpora that were crawled. For example: ...
84714cabc078f08cc95c4ee255431e506df74c5c
3,598,322
def cbin(n): """Return `n` as a clean 32-bit binary number, without a leading '0b'.""" if n < 0: n = UMAX + n return '{0:0>32}'.format(bin(n)[2:])
d54e270fa3844c84096c7fd40ce832d97bd96646
3,598,323
def import_module_by_path(mod_path, mod_name, sys_add=True, sys_use=True): """Import a module by module file path. @param mod_path: module file path. @param mod_name: module name to be imported as. @param sys_use: see func |import_module_by_code|'s same name arg. @param sys_add: see func |import...
5e8c8e3cf59121a5f3e8add8ad5590d98ea5fa50
3,598,325
def example_function(a: int) -> int: """Takes an integer as input and return it's square Parameters ---------- a : int input number Returns ------- int square of a """ return a ** 2
fd519e72ec385aa905868facee198b3eaf57f778
3,598,326
import random def sample_params(params): """Randomly sample hyper-parameters stored in a dictionary on a predefined range and scale. Useful for hyper-parameter random search. Args: params (dict): hyper-parameters to sample. Dictionary value-type parsing: - :python:`[1e3, 1e...
516aadec130a8f83ccd920c06ca4317736ddfa75
3,598,327
def _richardson_lucy(img, psf, otf, iterations=10, accelerate=True, **kwargs): """Perform actual RL deconvolution. assumes that img, psf, and otf have been prepared. Typically, you would call richardson_lucy (see docstring there) """ eps = finfo(img.dtype).eps t = img tm1 = zeros_like(t) ...
a1d302437e5980043e7e6cdf24bef19bfc533691
3,598,328
def wrapTo180(lon): """Wrap longitude to 180 deg """ q = (lon < -180.0) | (180.0 < lon) lon[q] = wrapTo360(lon[q] + 180.0) - 180.0 return lon
601700dae1cd76524e6f2ab4161727445ae82db5
3,598,329
def free_color(wks_id,index): """ Removes a color entry from a workstation. Ngl.free_color(workstation, color_index) workstation -- An identifier returned from calling Ngl.open_wks. color_index -- An integer scalar specifying a color index. """ NhlFreeColor(_int_id(wks_id),index) return None
366b48b738f9513eb092abe87a667300052b5f3e
3,598,330
def prepare_pre_actual_for_prestg(unnested_df): """ preparing preprocessed data to be pushed into prestg table """ pre_actual_old_columns=['nodeid','section','module','ts','nodename']+[f"preprocessed_output_{i}" for i in range(0,5)] pre_actual_df=unnested_df.cols.select(pre_actual_old_columns) ...
10ff80f213df117b14ab8fb25dc2067bfcd83d72
3,598,331
def run(audit_files=None, tags='*', labels=None, verbose=None, show_compliance=None): """ :param audit_files: Profile to execute. Can have one or more files (python list or comma separated) (default: {None}) :param tags: Can be used to target a subset ...
e09bde6b91fa2e379f933e60c9070872e0be6d14
3,598,332
def get_file_mode(fd): """ Returns access mode with which file was opened. :Arguments: fd - file descriptor got from open_file :Return: mode """ mode = "" try: mode = fd.mode except ValueError: print_error("file is already closed...") except Exception ...
2c6ff465c680aec845d1b6761298a60c7cea7c69
3,598,333
import random def normal12(startt,endt,money,first,second,third,forth,fifth,sixth,seventh,ff1,ff2,mm1,mm2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(ff1) idgirande=...
c13d1a535d061e9631337bba1d1d57ff841e6a05
3,598,334
def read_xml(path_to_file): """XML read :param path_to_file: path to yaml file :type path_to_file: str :return: XML datastructure :rtype: dict """ return xmltodict.parse(read_plain_text(path_to_file))
3b9153cb837ec9c0dddc4ae572869738e8ceffa6
3,598,335
def distance_matrix(points): """return NxN point to point distance matrix this works but is not needed for USR """ points = N.array(points) num, dim = points.shape delta = N.zeros((num, num), "d") for d in range(dim): data = points[:, d] delta += (data - data[:, N.NewAxis]) *...
5e1a1c1922fb0a6d027665341e91e62aa469cf8e
3,598,336
def merge_dicts(*args): """ Creates a new dictionary that merges those passed as arguments. """ if not args: return {} d = args[0].copy() for extra in args[1:]: d.update(extra) return d
f23aeac179bd3ae16c0b1c141f8c918d87075396
3,598,337
def register_get(): """ If a user is logged in redirect to the home page. Otherwise displays a registration page. """ if 'logged_in' in session: return redirect('/', code=303) else: # templates are stored in the templates folder return render_template('register.html', mes...
2de743ce92b561ed2d18ac1ab2b1280d7fed7b83
3,598,338
from pathlib import Path def job_output(): """Return job_output protobuf message""" job_output_correct_answer = pb.JobOutput() with open( Path(__file__).parent / "answers" / "cisno_casci_result.pbmsg", "rb" ) as f: job_output_correct_answer.ParseFromString(f.read()) return job_outp...
90deb64b0249d66d7127199e0e8f633bc19c9a58
3,598,339
import doctest def _quiet_testmod(module): """ Run all of a modules doctests, not producing any output to stdout. Return a tuple with the number of failures and the number of tries. """ finder = doctest.DocTestFinder(exclude_empty=False) runner = doctest.DocTestRunner(verbose=False) for te...
2c788dd128214e7c230124636aad3b0630060dd1
3,598,340
def ionizing_luminosity_fraction(temp, cutoff=13.6): """Calculate the total ionizing luminosity given a temp/cutoff energey.""" nulow = cutoff * eV / h nuhi = 100 * nulow value = (2.0 * h / cc ** 2) * quad( lambda nu: nu ** 3 / (np.expm1( h * nu / (kb * temp))), nulow, nuhi)[0] / ( ...
dc0a28baa4348ab10c36d0125053f4d8c7922e6b
3,598,343
def _pango_attr_list_types(attributes): """Returns the types of all attributes in the given Pango.AttrList.""" # Pango.AttrList does not appear to have any normal ways to access its # contents, so this is a bit of a hack. types = [] attributes.filter(lambda attribute: types.append(attribute.klass.ty...
d14a28fd88eb60cbe8190efaf09e1b5081c437c5
3,598,344
def transform_to_recurrent(arr,sequence_length,num_features): """ @param arr: The 2D numpy array to be transformed to a 3D array of size (arr.shape[0],sequence_length,num_features). This format is amenable for use with a recurrent network architecture. @param...
acdc104996520c6e19d936458aeb8a7da3639e21
3,598,345
def get_required_setting(setting, value_re, invalid_msg): """ Return a constant from ``django.conf.settings``. The `setting` argument is the constant name, the `value_re` argument is a regular expression used to validate the setting value and the `invalid_msg` argument is used as exception message ...
2219ee5a2c27215857e86c0c4ea24b2c9a90d1f0
3,598,346
def process_and_mask_ids( data, seq_len=256, padding='left', keep='start', start_token=1, end_token=2 ): """ Takes data that contains a list of lines in string form, and returns a numpy array of shape [nb_sentences, seq_len], as well as a mask for the...
28e457662e1b8f9367e03fdb5a0e8e03f1b8de06
3,598,347
def randKrausSet_Haar(d,r,rK): """! Generates random set of Kraus operators Parameters ------- d : int Number of gates r : int Superoperator dimension of the gates given by the square of the physical dimension rK : int Number of Kraus operators per gate ("Kraus rank...
580e6a59e603b3c22c3f1b63495f895f2a185d95
3,598,348
def MtriangleConting(graph_dict, mia = 1.0, Sparse = False): """ Caculate 3-order triangle motif number. Input: graph_dict: (dictionary) the neighbor dictionary of each node in graph mia: (float) motif information retention ratio (hyperparametric) Sparse: (bool) need...
c3d59a081bdd6f330b3aa41466ce898243be6bd7
3,598,349
def is_street_name(elem): """This unction will get the elements in the file (i.e. the tag element) and return the attributes in that element for which their key is equal to 'addr:street'. """ return (elem.attrib['k'] == "addr:street")
72c751c903cf346548be59dc35c4d0b7345aea7e
3,598,350
import colorsys def hue_sat_to_cmap(hue, sat): """Mkae a color map from a hue and saturation value. """ # normalize to floats hue = float(hue) / 360.0 sat = float(sat) / 100.0 res = [] for val in range(256): hsv_val = float(val) / 255.0 r, g, b = colorsys.hsv_to_rgb(hue, ...
816cee4bbf69ee466cdade149b4f4b4547e9b29a
3,598,351
def create_particle_velocities(particle_size, v_min=-4, v_max=4): """ Create the velocities associated with a particle :param particle_size: :param v_min: :param v_max: :return: """ velocities = v_min + (v_max - v_min) * np.random.uniform(low=0, high=1, size=particle_size) return vel...
ce7bb37d1b80a57c84143933f395ff9c928d0c09
3,598,352
def mine(user_address): """ Function that mines the block into block-chain. """ block = blockchain.mine_block(user_address, node_address) response = {'status': True, 'message': 'Successfully Mined the new Block', 'block_data': block} return response
facfc3c86bfe81d3e87e707c6df318f3f212782b
3,598,353
from localtileserver import TileClient def local_tile_bands(source): """Get band names from COG. Args: source (str | TileClient): A local COG file path or TileClient Returns: list: A list of band names. """ check_package("localtileserver", "https://github.com/banesullivan/localti...
37b9762ca37985f314b813908f0438eeef5ca60f
3,598,354
def wage_hourly_counts(year, num, source_long): """This function returns counts for each of the bins of the variable.""" bins = [] bins += [(0, 1), (1, 99), (100, 199), (200, 299), (300, 399), (400, 499), (500, 599)] bins += [(600, 699), (700, 799), (800, 899), (900, 999), (1000, np.inf)] counts = ...
d021e89b6103374a6fe3b042abdb209d9e135f95
3,598,355
def get_data_frame(root, stn, level, columns=slice(None), years='all'): """ Return a pandas data frame and mapping header information (one entry per year) for all available data for a given *stn* and data product *level* at repo...
9d0d284255d2dc8465162388be35c4e0338ed017
3,598,358
def prepend_error_from_dir(sourcefile, function, errordirlist, destfile=None): """ Wrapper around the prepend error pass """ # Reject empty error lists assert errordirlist # If no destfile is given, just modify the source file if destfile is None: destfile = sourcefile errordir...
395b1655f98c2518e6ec1106fee7677bfa702e75
3,598,361
async def get_user(user_id: int): """ Get user from database :param user_id: User id :return: Ready to use UserClass """ cur.execute("SELECT * from users WHERE userId=?", (user_id,)) res = cur.fetchall() if len(res) > 0: res = res[0] return UserClass(int(res['userId']), ...
229796f091211f36e73f9eecf9a9764b9b85d27d
3,598,363