content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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_problem_cause(token): """ :param token: Token :return: Throwable """ if isinstance(token, Problem): return token.cause() else: raise exceptions.BugOrBroken( "tried to get problem cause from " + token)
d443434a57d6b21cda67e13906675f16b1d5d31c
3,598,301
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
import os import tempfile import subprocess import shutil def render_abc(self, abc_source): """ Render abc_source with abcm2ps.""" # Don't try again if we had an error before. if hasattr(self.builder, '_abcnotation_warned'): return None, None # Generate unique base filename base_filename...
b1b20f07b9a4144adfe9d2074a9f310c43a94646
3,598,309
import asyncio def exclusive(fun): """Make an async function call exclusive.""" lock = asyncio.Lock() log.debug("Locking function: %s -> %s", lock, fun) async def _locked_fun(*args, **kwargs): log.debug("Wait for lock releasing: %s -> %s", lock, fun) async with lock: log.d...
bad804cc3f2fde775bc2d74dd1e4528a380858e0
3,598,310
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
import subprocess def clear_terminal() -> None: """Clears the terminal window. Returns None.""" subprocess.run(["clear"]) return None
be15e4cdb4d0a28c4718b1fe28955a47fd3c672c
3,598,312
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
import os from re import DEBUG def get_logging_level(): """get_logging_level will configure a logging to standard out based on the user's selected level, which should be in an environment variable called MESSAGELEVEL. if MESSAGELEVEL is not set, the maximum level (5) is assumed (all messages). """...
0fae0254938e68a7975e26b84a0cabb38309c95c
3,598,320
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 alpha_variant(x, blockset): """find a simple variant of string x that isn't in blocklist. Try adding numbers to the end, basically. side effect WARNING: updates blocklist itself to include the new variable.""" if not x in blockset: return x split = utils.vname_split(x) if len(sp...
2a85565ef90648aa9e74806bd44cfe78e5ecb2c3
3,598,324
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
import os def _RecursiveProbe(path, read_method): """Recursively probes in path and all the subdirectory using read_method. Args: path: Root path of the recursive probing. read_method: The method used to probe device information. This method accepts an input path and returns a string. e.g. _R...
f8cf6198f086f7e902f30b1fd20dc286c80c3c19
3,598,341
def set_thousands_separator(axes: plt.axes, which: str = 'both', nb_decimals: int = 1) -> plt.axes: """ Set thousands separator on the axes. Parameters ---------- axes : plt.axes Axes from matplotlib, can be a single ax or an array of axes. which : str, defau...
66025aff1c5a877ec26a35f6902185f2e2a5161c
3,598,342
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
import torch from typing import Optional def channel_weight( layer: str, weight: torch.Tensor, batch: Optional[int] = None, ) -> Objective: """ Linearly weighted channel activation as objective :param layer: Name of the layer :type layer: str :param weight: A torch.Tensor of same le...
12edb9a40076a19943b046523eea96e747645bdd
3,598,356
import sys def get_cal(service, name): """Get calendar ID by name.""" cals = service.calendarList().list( showHidden=True, minAccessRole="writer").execute() for entry in cals['items']: if entry['summary'] == name: return entry['id'] print("Calendar not found") sys.exit(...
dc81eedd88bbe49ad8c61de9e3ba624cc5361957
3,598,357
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
import tempfile import os def classify_one(): """ Classify one image and return the top 5 classifications Returns JSON when requested: {predictions: {category: confidence,...}} """ model_job = job_from_request() remove_image_path = False if 'image_path' in flask.request.form and flask.re...
da51913b06414a1d61c5742bf7c4a4955301a821
3,598,359
import os def create_files_folder(path, change_to_directory=True): """ This function creates the directories on the given path if they don't exist. :param path: Path for directory creation :param change_to_directory: Flag indicating whether program should switch to given directory as working direc...
6fbfbc0da5037d9b714ffd1de7badc22d34f3c39
3,598,360
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
def validaNascimento(mensagem='Data nasc. (DD/MM/AAAA): '): """ Função que valida datas de forma a verificar se todos os caracteres, entre as '/' são numéricos e não outros tipos de dados. Também verifica se o dia, mês e ano estão dentro dos limites válidos. :param mensagem: recebe uma mensagem...
5564483e6a4966537fd0f3844485ffeaa4378332
3,598,362
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
def sin_potential2(z): """Modified sin potential.""" z = tf.transpose(z) logterm1 = tf.math.exp(-0.5 * ((z[1] - w1(z)) / 0.4) ** 2) logterm2 = tf.math.exp(-0.5 * ((z[1] - w1(z) + w3(z)) / 0.35) ** 2) term3 = 0.1 * tf.math.abs(z[0]) output = -1. * tf.math.log(logterm1 + logterm2) + term3 ret...
843f4ca43ab2f2e464d8759cae8a1504b32992d8
3,598,364
def map_crystal_to_sim(CRYS_PDB, SIM_PDB): """ Map resid of crystallographic water to resid of corresponding simulation water """ crys_molid = molecule.load('pdb', CRYS_PDB) sim_molid = molecule.load('pdb', SIM_PDB) # align_crys_to_sim_structures(crys_molid, sim_molid) # coordinate_selection = "noh and wate...
23989ed343b23dcc3a38120536bec36b81829206
3,598,365
def export_estimator_savedmodel(estimator, export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, ...
161b0773c76550e62643454e932eb6c4755f7b1e
3,598,366
def fetch_w(*, wid): """Get all the files on a workspace""" workspace = Workspace.get_or_404(wid) if not ReadWorkspacePermission(wid).can(): raise APIException(status=codes.forbidden, title='Forbidden', detail='You are not authorized to read met...
7bb42d77c1d8a9111bcb9c648b1e1c4ed21b5922
3,598,367
def _extract_lr(labels_in, dat_type): """Pull out the L/R information from ROI label. Parameters ---------- labels_in : list of str ROI labels. dat_type : {'anat', 'elec'} Whether ROI label comes from anat or elec data. Returns ------- labels : list of str Clean...
0dd503dbc37bab9fec6b389a22b6561f725a6757
3,598,368
def _parse_raw_day(fragment): """ Taking all the info we need from the object Args: fragment: 'BeautifulSoup' objects contains day info ('div' with class 'col-md-6') Returns: tuple: (str, str, list): Tuple contains date, day and list of the lessons """ header = fragment.find_n...
0b236022889bffc2dbfa9479015dfa1545a2b4c0
3,598,369
import glob import platform def get_targetNames2(target, inputFolder): """ -> return the list of center or the list of date occuring in patient file present in data folder -> target is a string, could be: - center - date - disease """ listOfPatientFiles = glob.glob(str(inputFolder)+"/*.csv") listOfCente...
00945dd882fb28ed5b60f0f65371fada64ed45ac
3,598,370
import io def binospec_read_amp(inp, ext): """ Read one amplifier of an MMT BINOSPEC multi-extension FITS image Parameters ---------- inp: tuple (str,int) filename, extension (hdu,int) FITS hdu, extension Returns ------- data predata postdata x1 y1 ;-...
52d2af087f44d7c2335a2807feb220fb89462d2a
3,598,371
import logging def list_to_dataframe(file_list): """ Convert a list of ctf files, that are named in the the standard format 'year_month_day_hours' to a pandas dataframe Args: file_list (list): a list of files Returns: pd.DataFrame: Pandas DataFrame containing a list of files """ ...
c33851e88c6ee6681ca727cbb880416733fcdfc4
3,598,372
def pull_courses(): """Retrieve list of JSON objects describing all the courses.""" # return query_endpoint('courses') return query_endpoint('accounts/1/courses')
aa362dd8888f6fdea33afa4fa60e849aa92ad651
3,598,373
def ev_annot_freq(bootstrap_rng=None): """Compute binned frequencies of event boundary annotations Parameters ---------- bootstrap_ng : Generator (from numpy.random.default_rng()) If provided, bootstrap resample event annotations Returns ------- ndarray Proportion of raters...
37d265c751dddbf6dfd3c8bd3780da5a860adb66
3,598,374
import torch def collect_samples( rand_init, queue, env, policy, custom_reward, mean_action, render, running_state, min_batch_size, ): """Helper function - Collect batch of action and log depends on the batch size Args: rand_init: random initialization for reproduc...
1a7da3a571f7ea7bb2ed739a4ddaaa1f98ee3664
3,598,375
def frame_id_unpack(frame_id): """Unpack given frame id and return a tuple of priority, reserved, data page, PDU format, PDU specific and source address. """ try: packed = bitstruct.pack('u29', frame_id) except bitstruct.Error: raise Error( 'Expected a frame id 0..0x1ff...
12e860863e6f9036a9bbf050bb2d7c4c1afd0ee1
3,598,376
import random import time import json def fetch_job_states(): """ dummy function returning random dictionaries with job names and job states for the purpose of simulating the actual long running tasks :return: """ job1 = [{'job_name': 'job1', 'job_state': 'running'}, {'job_name...
d872edb4ada47a59b0137ba45e3a0611ff99b0a8
3,598,377
from datetime import datetime def generate_download_signed_url_v4(bucket_name, blob_name, sa_name): """Generates a v4 signed URL for downloading a blob. Note that this method requires a service account key file. You can not use this if you are using Application Default Credentials from Google Compute ...
b742354de82ffe266ced5555b23c582031411373
3,598,378
import tokenize def simple_lesk(gloss: str, word: str): """":returns the sense most suited to the given word as per the Simple LESK Algorithm""" # converting everything to lowercase gloss = gloss.lower() word = word.lower() # obtaining tokens from the gloss gloss_tokens = tokenize(gloss, wor...
3fc717c83f0293d077392294fbed2a3e4aba0c42
3,598,379
from typing import Optional def check_change_full_name( user_profile: UserProfile, full_name_raw: str, acting_user: Optional[UserProfile] ) -> str: """Verifies that the user's proposed full name is valid. The caller is responsible for checking check permissions. Returns the new full name, which may ...
c1806233263024d8c6b18e079829e2ee0c0005c4
3,598,380
def get_course_exam_all(course_id, prev_years=False): """ Return a summary of information about all current exams in the course {id, course, name, description, start, duration, end, type} """ assert isinstance(course_id, int) assert isinstance(prev_years, bool) if prev_years: key = "...
b9822bbd4e060d1eae7ea72a98053e526d023d8c
3,598,381
import jinja2 def render_template(template_file, template_vars, searchpath="./templates/"): """ Render a jinja2 template """ templateLoader = jinja2.FileSystemLoader(searchpath=searchpath) template_env = jinja2.Environment(loader=templateLoader) template = template_env.get_template(template_fi...
d15f5d6e120a22ee5735dbf5b1f8c324a5cae861
3,598,382
def getAxes(): """ Get each of the axes over which the data is measured. """ df = load_file("atyeo_covid") df = df.filter(regex='SampleID|Ig|Fc|SNA|RCA', axis=1) axes = df.filter(regex='Ig|Fc|SNA|RCA', axis=1) axes = axes.columns.str.split(" ", expand = True) subject = df['SampleID'] subje...
5e2abcbd7458978378faa5865268c5721afd4645
3,598,383
def summarize_power(power_summary, sim_num, test, colors): """Generates a dataframe describing a power calculation run Please note, this function is primarily designed for use with the simulation notebooks. Parameters ---------- power_summary : dict A dictionary summarizing the power s...
46c5d051193d2c87d1a1301f8c06217b5c33551e
3,598,384
def head(r, t, h0, Q, delz, K, S): """ Compute the head around a pumping well according to the THEIS model. Source: SHEMAT-Book Clauser2003, section 2.6.1, p.57. Parameters ---------- r : float Distance from well [m] t : float time [s] h0 : float Undisturbed he...
7409211ddff0905ce4b07cad2176ef87609e4aee
3,598,385
import subprocess def get_media_encoding(path): """Execute external mediainfo command and find the video encoding library.""" # Get mediainfo output process = subprocess.run( ['mediainfo', '--Output=XML', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) root = etree...
27dd43dbe07d49a4d566ec6bd134aa93de69776b
3,598,386
def pagerank_weighted(graph, damping=0.85): """Get dictionary of `graph` nodes and its ranks. Parameters ---------- graph : :class:`~gensim.summarization.graph.Graph` Given graph. damping : float Damping parameter, optional Returns ------- dict Nodes of `graph` ...
4a6ee1c6ea3c402e84b5a3e246a66ff004e96aab
3,598,387
def crate_data_for_linear_regression_weighted(initial_proj_nodes, dict_intial_projections, dict_enode_enode_in, dict_enode_enode_out, dim, G): """ In order to find the best parameters to calculate a node's vector, we perform linear regression. In this function w...
8858589d1f8a6eea6d9036126d83b4b3ea1e6f90
3,598,388
from typing import Any from typing import List def search_commands(*args: Any) -> List[Any]: """Pass find_commands function from C.""" return actually_calls(args, find_commands)
f8471e6160ba2cd37f2ae99240f4db7f00a9bb86
3,598,389
def subtract(x, y): """Subtract two objects and return the result >>> from methods import subtract >>> subtract(2, 1) 1 """ return x - y
00fd9bff041879b372ab7b0d8aa536e3aecb8378
3,598,390
def query_for_user(user): """Queries for information about user from the database. :param user: Object User to query for. :return: Data about the user. """ database = connect_to_cloudsql() cursor = database.cursor() cursor.execute("SELECT * FROM Users WHERE username='" + user.username + "'"...
4b17b111efd9e4bc230fbcd9ff22637ce014b1f1
3,598,391
def RunDistributed(module_name, package_root, num_ps, num_workers, start_port, user_args=None): """Create a cluster configuration and start processes for the cluster. Args: module_name: str. Python module to use as t...
edab626aa6b09a1bb039da2d3db051e9d578859d
3,598,392
import logging import sys def main(): """Entry point""" logging.basicConfig() odl = ODLTests() parser = ODLParser() args = parser.parse_args(sys.argv[1:]) try: result = odl.run_suites(ODLTests.default_suites, **args) if result != testcase.TestCase.EX_OK: return resu...
e6d396f8d95070453d303a8328ff8fd7192c8420
3,598,393
from operator import add from operator import concat def normalA(x, p, filters, scope=None): """Normal cell for NASNet-A (Fig. 4 in the paper)""" p = adjust(p, x, filters) h = relu(x) h = conv(h, filters, 1, scope='1x1') x1 = add(sconv(h, filters, 3, scope='left1'), h, name='add1') x2 = add(...
23908563b584db0fa66b4b24da3f050c2be45406
3,598,394
def DEFAULT_THRESHOLDING(phenotype): """ Threshold function for a phenotype for each gene, >0 becomes 1 and <0 becomes -1 """ # verification, sign declaration, return thresholded phenotype assert(phenotype.shape == (DEFAULT_GENE_NUMBER, 1)) def sign(x): return (1 if x > 0 else (-1 if x < 0 e...
bca278e17c96668f260fbfad004619c24881f5f0
3,598,395
def dict_sort(dictionary: dict) -> list: """Takes in a dictionary with integer values and outputs a list of the keys sorted by their associated values in descending order.""" return list(reversed(sorted(dictionary, key=dictionary.__getitem__)))
330e6033a9e511341e5d9216a385b366a09eed9c
3,598,396
import re def get_citation_form(attributes): """ Compute the citation form of a pronominal mention. Args: attributes (dict(str, object)): Attributes of the mention, must contain the key "tokens". Returns: str: The citation form of the pronoun, one of "i", "you", "he", "she", ...
2e02063ae0694e7ce76e3be8ce111d9550de7697
3,598,397
def SINH(df): """ 函数名:SINH 名称:双曲正弦函数,三角函数 python API real=SINH(close) :return: """ close = df['close'] return talib.SINH(close)
b40dd33fd7a41f5219dfb84631695435da4241a6
3,598,398
def completion_formatter_factory(subsec_precision=2): """ Formatter factory Parameters ---------- subsec_precision : int (Default : 2) The number of decimal digits for the second in the time formatting Return ------ :func:`completion_formatter` """ def completion_format...
91d3c28e59f78a5addf04247d35d2bd84dfefef9
3,598,399