content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _warp_dir(intuple, nlevels=3): """ Extract the ``restrict_deformation`` argument from metadata. Example ------- >>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "i-"})) [[1, 0, 0], [1, 0, 0], [1, 0, 0]] >>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "j-"}), nlevels=2) ...
a5558dcdb4d7f0893789a2f6ba98acb2fa10f303
688,094
def update_position(dir, x, y): """Returns the updated coordinates depending on the direction of the path""" if dir == 'DOWN': return x, y + 1 elif dir == 'UP': return x, y - 1 elif dir == 'LEFT': return x - 1, y elif dir == 'RIGHT': return x + 1, y
5a12004c41012dd7ab70891367734495dad12177
688,095
from typing import Callable from typing import Any def lazy_property(function: Callable) -> Any: """Allows to avoid recomputing a property over and over. The result gets stored in a local var. Computation of the property will happen once, on the first call of the property. All succeeding calls will u...
0974d69d4335a4edb702175b73f0ac6456adeae7
688,096
import socket def device(): """ Return the name of the host machine """ return socket.getfqdn(socket.gethostname())
05c0e235f8cb657ed83e4efc46ee03466aa6e4ea
688,097
def region_mapping(region): """Map the user supplied region to the hostname for the AMP for Endpoints console """ region_map = { "apjc": "console.apjc.amp.cisco.com", "eu": "console.eu.amp.cisco.com", "nam": "console.amp.cisco.com", } return region_map[region.lower()]
11773a9b26700ba55c38c306123feebff997ba50
688,098
import torch def get_accuracy(outputs, labels): """From Binary cross entropy outputs to accuracy""" mask = outputs >= 0.5 accuracy = 1. - torch.mean(torch.abs(mask.float() - labels)).item() return accuracy
d2e02c517f193d58785f7a2b0a6c602924b88f5f
688,099
from typing import Tuple def get_choosen_building( building: Tuple[str, str], choice: str ) -> str: """ Get the specific building that have been selected by the user. Parameters ---------- building: Tuple[str, str] A tuple containing 2 randomly selected buildin...
da43ebfaa68137eb2970eb959084e76c15d1674a
688,101
def make_var_scope_custom_getter_for_ema(ema): """Makes variable scope custom getter.""" def _custom_getter(getter, name, *args, **kwargs): var = getter(name, *args, **kwargs) ema_var = ema.average(var) return ema_var if ema_var is not None else var return _custom_getter
f5ac4f9c399a9c9e11af8163d85adc206ee68177
688,102
def hasnext(it): """Implementation of `hasnext`.""" return it.__myia_hasnext__()
4c968f458f7be5c6d5c955d5937b11aef9fdb05b
688,104
def unique_list(input_, key=lambda x:x): """Return the unique elements from the input, in order.""" seen = set() output = [] for x in input_: keyx = key(x) if keyx not in seen: seen.add(keyx) output.append(x) return output
1616f89dbd0e3e65af28d8210fb201cb309d3ce8
688,105
def pos_neg_split(df): """ Splits DataFrame into two separate positive and negative DataFrames for the creation of two separate models for LDAvis. INPUT: Sentiment-analyzed DataFrame OUTPUT: A positive DataFrame and negative DataFrame """ neg = df[df['Analysis'] == 'Negative'] pos ...
84ca8c810d7ec5a65792050b169f5b34cc3aaf78
688,106
def collapse_complexes(data, conjugate_flag=False): """Given a list or other iterable that's a series of (real, imaginary) pairs, returns a list of complex numbers. For instance, given this list -- [a, b, c, d, e, f] this function returns -- [complex(a, b), complex(c, d), complex(e, f)] T...
12d089ebc6b1fb882e0ae32fc71740794b595f00
688,107
def T_(message): """For translation with gettext""" return message
feed253bd8014fc1517c1f003016e883548f6193
688,108
def _code_in_list(code, codelist): """Tells if `code` is contained in `codelist` Examples: - 401 is not contained in ['3xx', '404', '5xx'] - 404 is contained in ['3xx', '404', '5xx'] - 503 is contained in ['3xx', '404', '5xx'] """ # status codes to exclude exact_codes = [co...
6168f158a1852d67475d63acc4f72d2f089ae1bd
688,109
def reflect_y(x, y, matrix): """Reflect the index horizontally.""" return x, matrix.rows - 1 - y
311306632a8abd3080ec51e21ffffe96c2aa417f
688,110
def make_complete_graph(num_nodes): """Makes complete graph with num_nodes """ if num_nodes <= 0: return {} if num_nodes == 1: return {0: set([])} dicts = {} for key1 in range(0, num_nodes): for key2 in range(0, num_nodes): if key1!=key2: if k...
b48586c71663b43f4d433a9d9084906c00d2089d
688,111
import torch def logical_or(left, right): """Element-wise `logical or: x || y`. Args: left (Tensor): input boolean tensor right (Tensor): input boolean tensor Returns: A Tensor of type bool with the same size as that of x . """ return torch.logical_or(left, right)
15b0ce7ce9db89bbd163fdc907b00c734976a9ef
688,112
def _phaser_succeeded(llg, tfz): """Check values for job success""" return llg > 120 and tfz > 8
aad7211980df60c559dfbf4e59745c3b0e55b7f3
688,113
async def _pinned(db, community): """Get a list of pinned post `id`s in `community`.""" sql = """SELECT id FROM hive_posts WHERE is_pinned = '1' AND is_deleted = '0' AND community = :community ORDER BY id DESC""" return await db.query_col(sql, commun...
194a071e19fb0fdef008b55b13584e8818c7fa03
688,114
from typing import List from typing import Dict def get_user_inputs(title: str, captions: List[str], retvals_size: int = 1024) -> Dict[str, str]: """Show text inputs to user and get values from them. Parameters ---------- title : str Popup title. ca...
463945a187327d704edca20a75c2cb408592feff
688,115
def is_prime(n): """ Def: A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a ...
78ecdf5cf67825dd6141521e05da9a8d5df41c7d
688,116
def parse_yaml_beam_args(pipeline_args): """Converts yaml beam args to list of args TFX accepts Args: pipeline_args: dict specified in the config.yml Returns: list of strings, where each string is a beam argument """ return ['--{}={}'.format(key, value) for key, value in ...
583f9d911502daf1bd78ab70955695d41379a1ac
688,117
def find_levels(variable_names): """This method... .. note: Might need the dataframe to check ints! Returns ------- list Variables with the word levels in it. """ return [c for c in variable_names if 'level' in c]
73805ae22f9fcc1dc3701979a07217ce27261b16
688,118
def are_you_sure(question: str): """ Loop while asking a Y/N question. Adds str(" (Y/N): ") to the end of the provided question. """ while True: answer = str(input(question + " (Y/N): ")).lower() if answer.startswith("y"): result = True break el...
a37d95f0a90fdf5380e01c4c18180f72b11ae28f
688,119
def first_string(group): """Return the first value in the group.""" for item in group: if item: return item return ''
8ee218fbfa8be328f304b5fdddb94e491b09bf45
688,121
def tensor_to_op_name(tensor_name): """Strips tailing ':N' part from a tensor name. For example, 'dense/kernel:0', which is a tensor name, is converted to 'dense/kernel' which is the operation that outputs this tensor. Args: tensor_name: tensor name. Returns: Corresponding op name. """ parts = ...
c582931a4e5b3bf07b0a5628b47a26cdeced88db
688,123
import numpy def splitting_confidence(matrix): """ Index the units by i and the parts by j. The splitting confidence vector is the vector whose ith coordinate is the maximum over all j of the probability of being in part j, given that you are in unit i. (The maximum over j of prob_j_given_i). ...
da8b4d6a2e8b800745258f2143575e96fcb2bfec
688,124
def minimum_absolute_difference(arr): """https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array""" sorted_array = sorted(arr) return min(abs(x - y) for x, y in zip(sorted_array, sorted_array[1:]))
97cb660bf606c1240f807cd2159fd9b73dd6fb59
688,125
def remove(list_, item): """Removes an item from a list.""" return [i for i in list_ if i != item]
b651e51ce60aa077dc908ada1564e44158be2352
688,126
def check_public_interface_namespace(namespace, valid_interface, checkdoc_flag=True, print_flag=True): """Check function used in unittests to test module's public interface. This function checks only static public interface symbols. It d...
ebfed0c46e2f5807401223dc17430b2a166aa722
688,127
def search_typedef(stmt, name): """Search for a typedef in scope First search the hierarchy, then the module and its submodules.""" orig_stmt = stmt mod = stmt.i_orig_module while stmt is not None: if name in stmt.i_typedefs: t = stmt.i_typedefs[name] if (mod is not N...
592db5dc90d2439fa6934229975d98dc608b5a0f
688,128
def dictify_df(frame): """ dictify_df converts a frame with columns col1 | col2 | .... | coln | value ... to a dictionary that maps values valX from colX { val1 -> { val2 -> { ... { valn -> value } } } } """ ret = {} for row in frame.values: cur_level = ret ...
ab022d6ad748b51582e610841f39bcbe893e808d
688,129
from pathlib import Path import fileinput def set_metadata_language(dir): """ Set the language code in the metadata <dc:language> tag by going recursively over every metadata.opf file in the Calibre library. Some Catalan ebooks have the language metadata incorrectly coded as: <dc:language>cat</d...
f109d4497bbdf643c296786b21f69f399c8be609
688,130
def _buildSpectrumFromQIisotopes(mz, isotopeDistribution, delta=1.0033550000000009): """ Build a mass spectrum from a QI mz value, and isotopic distribution pattern. :param float mz: m/z of the lightest isotope :param str isotopeDistribution: Hyphenated list of isotopic abundances ordered by 1Da intervals :param ...
36295828edd0a9459474445a0d6ce1370e6e4b88
688,131
import json def listDrills(bot, trigger): """Lists all current rats waiting for a drill, and their drill type.""" #Argument parsing if trigger.group(3) != None: arg = trigger.group(3).lower() else: arg = '' if arg == '-r': patchdrills = False ratdrills = True ...
5cf1c26e0e40f2db8724cf88d50be82e0ae3672c
688,132
def generate_path(start, ref, nonref, stop): """ Given source, sink, and ref/non-ref nodes enumerate all possible paths """ ref_path = [x for x in [start, ref, stop] if x != "0"] nonref_path = [x for x in [start, nonref, stop] if x != "0"] return [ref_path, nonref_path]
82dd488efe95fc3986890229ca5673f62cec6066
688,133
def valid_ci_number_list(): """ from DESI-3347 page 2 CI# labels """ return [0, 2, 3, 5, 7, 8]
fcd2e1b726d9f0332e372e3cd2c19ae7c4391699
688,135
def grid_from_data(da): """Given a dataset, extract only the grid information. Parameters ---------- da : xarray.DataArray DataArray to extract grid information from. Must have "ocw" conventions, ie 2D lats and lons variables. Returns ------- ds : xarray.Dataset Dat...
e2cab8d978f40372540d379087e1a835a9e6521f
688,136
import torch def interpolate_irreg_grid(interpfunc, pos): """Interpolate the funtion Args: interpfunc (callable): function to interpolate the data points pos (torch.tensor): positions of the walkers Nbatch x 3*Nelec Returns: torch.tensor: interpolated values of the function eval...
3509f7a102211b43b4964ef908a0ce0a68579e53
688,137
from typing import Union def cast_to(type_hint, value) -> Union[str, float, int]: """Cast a value to the corresponding type_hint. If it fails, it will give a ValueError. Args: type_hint ([type]): The desired final type. value : Value to be casted into the desired final type. Returns...
f941aa459badd65e4e6e693572af654288175ecf
688,138
import networkx def subgraphs2tree(Subgraphs): """ Creates a tree (*networkx.DiGraph*) *G* from the list *Subgraphs* such that each node of *G* is a subgraph and there is an edge from *x* to *y* if *x* is the smallest superset of *y*. It is required that the node sets of any *x,y* of *Subgraphs* are e...
05ae6e36c023c4eeee2c8ff231f393af69afc994
688,139
from os import environ def getEnv( env_variable, default): """return environment variable of env_variable if possible, otherwise return default""" try: variable = environ[env_variable] except: variable = default return variable
f878c02841ded190323697f366684038ea0aa10e
688,140
def get_cv(m1: float, m2: float) -> float: """Compute coefficient of variation. """ return (m2 - m1**2)**0.5 / m1
becf1149bdef4cd2906d86e7e304f2f4f64ada18
688,141
def _get_train_steps(num_examples, train_epochs, train_batch_size): """Determine the number of training steps.""" return num_examples * train_epochs // train_batch_size + 1
8fe187059e2050f599fcec0d707a0c3fcb4f857e
688,143
def make_synteny(genes, isoforms): """Return synteny for a list of genes and dict of isoforms.""" return len(list(set([isoforms.get(gene) for gene in genes])))
2ad56624ee2268d9bbf76e2af98977819fd89526
688,144
import json def assessment_json(group_json, page_json, campaign_json): """Return an Assessment JSON.""" assessment_str = json.dumps( { "id": "RVXXX1", "timezone": "US/Eastern", "domain": "bad.domain", "target_domains": ["target.domain"], "sta...
fc1c37aa86a9ec8b7297ad7a9fe84f7fbc2f312d
688,145
def reverse_complement(kmer): """ Returns the reverse complement of the specified string kmer. """ d = {"A": "T", "C": "G", "G": "C", "T": "A"} # This is very slow and nasty! s = "" for c in kmer: s += d[c] return s[::-1]
6c80748f0fa072daacaff42def333e7bce395692
688,146
import torch def view_as_real(data): """Named version of `torch.view_as_real()`""" names = data.names return torch.view_as_real(data.rename(None)).refine_names(*names + ("complex",))
8ae3c540ca1e3cda62ecc3099b930c8b35a8687c
688,147
def bitstring_readable(data, batch_size, model_output=None, whole_batch=False): """Produce a human readable representation of the sequences in data. Args: data: data to be visualised batch_size: size of batch model_output: optional model output tensor to visualize alongside data. whole_batch: wheth...
342b6720dd30b1f8d8b984a5d49b09913050fd40
688,148
def parse_crs_string(string: str) -> str: """Parses a string to determine the CRS/spatial projection format. Args: string: a string with CRS/projection data. Returns: crs_type: Str in ["wkt", "proj4", "epsg", "string"]. """ if "epsg:" in string.lower(): return "epsg" el...
6e730d767924be39244a9d1e08fe6895f1d4b1db
688,149
def unite_bounds(bounds1: dict[str, float], bounds2: dict[str, float], resolution: float, min_bounds=False) -> dict[str, float]: """Unite two bounding boxes to encompass both of them.""" # Create new bounding coordinates that encompass both datasets lower_func = min if not min_bounds else max upper_func...
ff95ff67ef81080f42070e8b52f8366ebfb3aa15
688,150
def count_ones(a_byte): """ count_ones(a_byte) : Counts the number of 1 bits in the input byte a byte returns number_of_ones which is the number of bytes in a_byte """ val = 0 # loop until there are no more 1s while a_byte > 0: # if a_byte is odd then there is a 1 in the 1st bit if a_byte % 2 > 0: val += ...
8c4d3c8098c0ed18cea339b69ead2853752ce0ac
688,151
def get_color(i, r_off=1, g_off=1, b_off=1): """Assign a color to a vertex.""" n = 16 low, high = 0.1, 0.9 span = high - low r = low + span * (((i + r_off) * 3) % n) / (n - 1) g = low + span * (((i + g_off) * 5) % n) / (n - 1) b = low + span * (((i + b_off) * 7) % n) / (n - 1) return (r,...
1ee58a6370ce28c1f2f094747a4acf0218c4c239
688,152
def storage_inter_max_constraint_rule(backend_model, node, tech, datestep): """ When clustering days, to reduce the timeseries length, set maximum limit on the intra-cluster and inter-date stored energy. intra-cluster = all timesteps in a single cluster datesteps = all dates in the unclustered times...
bb73d34bab2b17e3033cd0cb216bf4cf5705ae35
688,153
import re def filter_example(elem, text, *args, **kwargs): """Example function for filtering arbitrary documents from wikipedia dump. The custom filter function is called _before_ tokenisation and should work on the raw text and/or XML element information. The filter function gets the entire contex...
f37f85abb6d5b03c4c52d49a60c0ca2a9061351f
688,154
import os import json def get_file_id_lst(env_name, pack_file_name): """ Returns the file_id_lst for the pack_file_name Args: env_name: pack_file_name (string or list(string)): path to the file(s) containing the pack info """ if not isinstance(pack_file_name, list): ...
7544a40b879bb8b9414322197c2c798c29c58bc2
688,155
def bytes_to_int(s): """Return converted bytestring to integer. Args: s: str of bytes Returns: int: numeric interpretation of binary string `s` """ # int type casts may return a long type return int(s.encode('hex'), 16)
dc50db3af4e19ac6d9fe93c969590ead96e628a3
688,156
def make_space(space_padding=0): """ Return string with x number of spaces. Defaults to 0. """ space = '' for i in range(space_padding): space += ' ' return space
db846fdb426bc04526744daac8487e2a90320200
688,157
def rename_bindnames(tqry, li_adjust): """use this to alter the query template to match expected attribute names in bind objects/dictionaries For example, a predefined query may be: "select * from customers where custid = %(custid)s" But you are repeatedly passing bind dictionaries like {"customer" ...
5e2d79772e1495d215f81166652b4449cb04a788
688,158
def combine_epsilon(eps1, eps2): """ Combine the epsilon values of two species. :param eps1: epsilon of species 1 :type eps1: float :param eps2: epsilon of species 2 :type eps2: float :return: eps_comb :rtpye: float """ if eps1 is not None and eps2 is not No...
2ef8c358994ab92a3696a158c2d0ac9cf3f4c0be
688,159
def _format(string): """ Formats a class name correctly for checking function and class names. Strips all non-alphanumeric chars and makes lowercase. """ return ''.join(list(filter(str.isalnum, string))).lower()
0fbff1d0da8c3bd4b318613dfa039dcef664f11f
688,160
import re def validate_version(accept_header): """ Ensure the client is requesting a valid version for this resource It is valid to not specify a version (the latest will be used) """ # Currently, this backend only supports one version for all resources if not accept_header: return Tr...
ff14690fe88bdc1b3eb3d63c0e99feff2895b35e
688,161
def twoDListMin(elements): """Return the min of a 2D list. Input: A list of lists of numbers. It can not be empty.""" if len(elements)>1: theMin=min(twoDListMin(elements[0 : (len(elements)//2)]),\ twoDListMin(elements[(len(elements)//2) : len(elements)])) else: if len(e...
9c335655826a58f76e6e6d3b353d2c8483d19262
688,162
def moa_imatinib(): """Create a test fixture for MOA Imatinib Therapy Descriptor.""" return { "id": "moa.normalize.therapy:Imatinib", "type": "TherapyDescriptor", "label": "Imatinib", "value": { "id": "rxcui:282388", "type": "Drug" } }
a7418c551f1c5718e5a10d259b7e00b389d1e910
688,163
def _euler_masceroni(): """ The Euler-Masceroni constant Returns ------- float The Euler-Mascheroni constant Notes ----- The Euler–Masceroni constant (also called Euler's constant) is a mathematical constant recurring in analysis and number theory. It is defined as the ...
cb3f74aa4af4c92a85f0ad4d19717268a153c591
688,164
def calc_add_bits(len, val): """ Calculate the value from the "additional" bits in the huffman data. """ if (val & (1 << len - 1)): pass else: val -= (1 << len) - 1 return val
2625fd13df3e7ed0151825232f169aa3ff54b3e0
688,165
def _normalize_dictionary(dictionary): """Wraps every value of dictionary in a list if it isn't one already.""" for key, value in dictionary.items(): if type(value) != type([]): dictionary[key] = [value] return dictionary
4b8ecd2f3aa5e3562414b50ac7887dea8992c8a6
688,168
def rldecode(A, n, axis=0): """ Decompresses run length encoding of array A along axis. Synopsis: B = rldecode(A, n, axis) B = rldecode(A, n) # axis assumed to be 0 Arguments: A (np.ndarray): Encoded array n (np.ndarray): Repetition of each layer along an axis. ...
9ffa16774905f6c869eae719f6ff8b06d2a7fb13
688,169
def albedo(alphaw, alphab, alphag, aw, ab, ag): """Caluclate the average planetary albedo. alphaw*aw + alphab*ab + alphag*ag Arguments --------- alphaw : float Surface fraction of white daisies. alphab : float Surface fraction of black daisies. alphag : float Surface...
680aecfb315cb4a18044b16355781854247a1933
688,170
def decode_response(response, module): """Unstructures the request from accountId + rest of request""" if 'name' not in response: return response response['name'] = response['name'].split('/')[-1] return response
607e850cacf005459ae6293365360817364a8359
688,171
from typing import Callable from typing import Optional import inspect def is_param_in_hook_signature( hook_fx: Callable, param: str, explicit: bool = False, min_args: Optional[int] = None ) -> bool: """ Args: hook_fx: the hook callable param: the name of the parameter to check exp...
0498270f67c2f2f691de7f70ced5d23e512722be
688,172
def get_module_path(module_name): """ 获得一个模块的路径 :param module_name: pyobject :return: 路径字符串 """ return module_name.__path__[0]
0d79b074327d108ef7560d2e00ba29dbbd3d73b2
688,173
def __enamldef_newobj__(cls, *args): """ An enamldef pickler function. This function is not part of the public Enaml api. """ instance = cls.__new__(cls, *args) cls.__node__(instance) return instance
ba6d1c14514c46d43ca175a723f5d314a9a21028
688,174
def describe(table): """Get the table description if the table exists, assume that any exception means that the table does not exist and return None. """ try: return table.describe() except: return None
463667b53a79c15de557979e363a991372714a9d
688,175
def frame_height(frame): """Get the frame's width.""" try: return int(frame.place_info().get('height')) except AttributeError: return int(frame.winfo_height())
704ef936dfd34f6469b7c1c0cd3b195030578ac7
688,176
import mpmath def delta_P(P_old, P_new): """ Compute the difference between two density matrices. INTPUT: P_OLD: Olde density matrix P_NEW: New density matrix OUTPUT: DELTA: difference between the two density matrices Source: Modern Quantum Chemistry Szabo...
17c23093e72f7e72f1b96a685691b449e2312e2e
688,177
def batch_norm_relu(inputs, is_training, data_format): """Performs a batch normalization followed by a ReLU.""" # We set fused=True for a significant performance boost. See # https://www.tensorflow.org/performance/performance_guide#common_fused_ops #inputs = tf.layers.batch_normalization( # inputs=inputs, ...
681306729445a0cbd3fe352becf85fb9a09b57e7
688,178
def open_and_read_file(file_path): """Read the entire contents of the file in as a string.""" contents = open(file_path).read() return contents
21b5bc501a59f4e0d97839122a2b822b2988a1d0
688,179
import requests def request_dataset_metadata(api_url, api_user, api_pass, did): """ This function does an HTTP request to EGA API to get dataset metadata and returns it as a stream :api_url: address of ega api_url :api_user: username to access api :api_pass: password for :api_user: :d...
ff1ad82a8708f9ac84bf0cf711da1f723bd16e02
688,181
def getsuffixes(S): """ Satellite function of getroot""" suf=[] for i in range(1,len(S)): suf.append(S[i:len(S)]) return suf
07aa7c49c5db2cc30f708da7041d1119804b5153
688,182
def make_fit_metrics(fittedmodel): """ Parameters ---------- fittedmodel Returns ------- """ ci = fittedmodel.conf_int(.05).to_dict(orient='index') m_ci = {} for var, vals in ci.items(): m_ci[var] = {'low': vals[0], 'high': vals[1], 'range': vals[1]- vals[0]} ...
f9839ba9d5a95fdfac78d8a0befbffab9fe85c9f
688,183
def split_into_words(subword_sent, max_subwords, transform, delimiter='@@'): """Take a subworded sentence and build a space-separated sequence of subwords for each word. >>> s = 'A@@ re@@ as of the fac@@ tory' >>> split_into_words(s) ['A@@ re@@ as', 'of', 'the', 'fac@@ tory'] """ words = []...
535f3165206b56d6a83e2bdf661c5924256827f0
688,184
def createFromDocument(doc): """ Create an empty JS range from a document @param doc DOM document @return a empty JS range """ return doc.createRange()
3bd55c4f60b25bb089b592f9dfe65ea299230be8
688,185
def _lsb_2fold(aa, bit): """ This function embeds a pair of bits in 2/3 fold degenerative codon. :param aa: amino acid information. :param bit: bit (character 2 e.g. 0) which should be embedded in codon. :return: watermarked codon (string) e.g. AGA. """ if bit == '0': return aa["codo...
9730ddb9f13d9d3fe1191d7fd0bc81172ee5cfcd
688,186
def encoder_type(encode): """ Takes the value sent from the user encoding menu and returns the actual value to be used. """ return { '0': "", '1': "shikata_ga_nai", '2': "", '3': "MULTIENCODE", '4': "BACKDOOR", }.get(encode, "ERROR")
a64d7df749296af7b5bfc02f6db19fc75b2465de
688,187
def bounding_box_circle(svg, node, font_size): """Bounding box for circle node.""" cx, cy = svg.point(node.get('cx'), node.get('cy'), font_size) r = svg.length(node.get('r'), font_size) return cx - r, cy - r, 2 * r, 2 * r
babbafb71e5fbf3e63c4a6ec31ba72545501cffb
688,188
import torch def batch_sinkhorn_loss(C, C_mask, epsilon=1, niter=100): """ :param C: Batch size by MSL by MSL :param C_mask: Batch size by MSL by MSL :param epsilon: :param n: :param niter: :return: """ # B by MSL mu = C_mask[:,:,0] mu = mu / mu.sum(dim=1, keepdim...
7a8e1426de322048313ec399ac069d4e7cdb6f02
688,189
def create_tokens_and_tokentypes(tokens_a, tokens_b, cls_id, sep_id): """Merge segments A and B, add [CLS] and [SEP] and build tokentypes.""" tokens = [] tokentypes = [] # [CLS]. tokens.append(cls_id) tokentypes.append(0) # Segment A. for token in tokens_a: tokens.append(token) ...
0f72f261ff1e0ee2d304321cd0bbc0af9c662b4b
688,190
def create_search_context_from_results(results): """Converts SQL query results to dictionary for HTML template. """ search_results = {} if results: search_results['search_results'] = [] search_results['script_hits'] = len(results) search_results['snippet_hits'] = 0 for result in results: ...
58ca50d8282dcc1e3507dffa0bd3738dc7e61cd9
688,191
def _get_parameters_proto(host_calls_dictionary): """Get the FormalParameterProtos for the first host call in the dictionary.""" return host_calls_dictionary['host_calls'][0].parameters
7d62ee04bc52fe29bd36a14366c96e8ce5542c46
688,192
def sql_flush(style, connection, only_django=False): """ Returns a list of the SQL statements used to flush the database. If only_django is True, then only table names that have associated Django models and are in INSTALLED_APPS will be included. """ if only_django: tables = connection....
11ddd9a59bd03cf5e529984797325442f8dcf3cd
688,194
def append_folder_path_to_doc_list(doc_list, folder_path): """Given a list of documents, returns the concatenated text contained in all of them Keyword arguments: text -- given text window_size - number of characters in a window step_size - number of characters to skip be...
f937e79e9e9dff1da16d39ed92a968a5ac64b647
688,195
def _conv_dict_to_array(a_dict, feats): """Converts a_dict to an array """ return [a_dict(feat) for feat in feats]
ee13aea95facb4d624278e1cbbd5a9fe005a27d9
688,196
import pickle def load_pickle_files(input_file_path): """ load parameters created by instance_clipping_and_mixing.py :Variables: input_file_path : str A path to a pickle file. :RType: :Returns: loaded file """ with open(input_file_path, "rb") as f: tmp...
1686d1adaeb95c3803835f1b008bb778adfee289
688,197
def lit_eq(lit1,lit2): """ Returns true lits are syntactically equal """ return lit1 == lit2
8346510f743c8639336a20d7101ffb95e33d494f
688,199
def extract_header_sequence(graph): """extract_header_sequence.""" header = graph.graph['header'] # extract the list of labels for the nodes in sequence seq_tokens = [graph.node[u]['label'] for u in graph.nodes()] seq = ''.join(seq_tokens) return header, seq
d9f13c946116037d93ed87fafb062fc357e0984f
688,201
def greedy_action(q, state): """ Computes the greedy action. :param q: action-value table. :type q: bidimensional numpy array. :param state: current state. :type state: int. :return: greedy action. :rtype: int. """ greedy_act = 0 q_max = q[state][greedy_act] for action i...
00ead3adb1da74bbe9ca0aef24793c6bd711aa83
688,203
import warnings def _determine_plot_height(figure_height, data, group_cols): """Calculate the height alloted to each plot in pixels. Args: figure_height (int): height of the entire figure in pixels data (pd.DataFrame): the data to be plotted Returns: plot_height (int): Plot heigh...
a92c3054cadf0818d3e1cc157c2f0e1966f71ddf
688,204
import torch def clone_input(x): """copy while preserving strides""" with torch.no_grad(): needed_size = sum( (shape - 1) * stride for shape, stride in zip(x.size(), x.stride()) ) buffer = torch.empty(needed_size + 32, dtype=x.dtype, device=x.device) cache_line_offs...
464b5298c5cb61a7dfc8b5ed0b45218b578ffb79
688,205
import yaml def load_config_file(path): """ Load and parser yaml file. Parameters: path (str): full yaml path location Returns: dict: yaml file in parsed into a dict """ with open(path) as file: return yaml.load(file, Loader=yaml.FullLoader)
f0343b876a7b34b75986ebe7ff8cd2b8c8df3ac2
688,206