content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def part_2(): """Function which calculates the solution to part 2 Arguments --------- Returns ------- """ return None
7b454841494c9f717868eda727b6273fabbf8222
3,630,100
import math def calc_dist_enrichment(ref_pos,spots_pos,img_size,delta_dist = 100, img_density=[],flag_plot=False): """ Calculates the expression level as a function of the distance from a reference point. Args: ref_pos (tuple): position of reference point. spots_pos (np array): RNA posit...
bc224b2116c26ea734dba2ae551c0f86384797a1
3,630,101
def get_single_two_body_file(molecule_file_name): """ Loads the molecule from a file. :param molecule_file_name: Filename :return: Molecule """ molecule = MolecularData(filename=molecule_file_name) molecule.load() # _molecule = run_pyscf(molecule) return molecule.one_body_integrals...
86e83f8afeee21c576f002131e9305be09b87902
3,630,102
def proposition_formatter(propositions): """Returns a list of propositions with selected fields.""" return [ { 'deadline': dateutil_parse(proposition['deadline']).strftime('%Y-%m-%d'), 'status': proposition['status'], 'modified_on': dateutil_parse(prop...
4115349c65eb6eb2ef9ea76131daeabc88a7542f
3,630,103
def CondSphereAnalFunB(x, y, z, R, x0, y0, z0, sig1, sig2, E0, flag): """ test Analytic function for Electro-Static problem. The set up here is conductive sphere in whole-space. * (x0,y0,z0) * (x0, y0, z0 ): is the center location of sphere * r: is the radius of the sphere .. math:: \mathbf{E}_0 = ...
4e80adc4d733fc104b23ccd567159bec02b32f17
3,630,104
def num2hr (num): """Given an integer, return a string with the same amount expressed with a quantifier.""" num = long (num) for quant_abbr, quant_amount in quants_tups_dec: if num >= quant_amount: return "%.2f%s" % (float (num) / quant_amount, quant_abbr...
ff095fecb6747029842a7859d5b41305962140ed
3,630,105
import os def super_resolve_service(path): """ Take the input image and super resolve it """ # check if the post request has the file part if 'file' not in request.files: return BadRequest("File not present in request") file = request.files['file'] if file.filename == '': r...
b03d4bcaac86c6cc03d8104e0fbc062cf100a8fc
3,630,106
import decimal def quarks_to_kin(quarks: int) -> str: """Converts an integer quark amount into a string Kin amount. :param quarks: An amount, in quarks. :return: A string Kin amount. """ kin = (decimal.Decimal(quarks) / _KIN_TO_QUARKS) return str(kin)
4a4a7d2e60f43763de1b6343e6162c889cdcbde1
3,630,107
def get_feature_representations(model, content_path, style_path, num_style_layers): """Helper function to compute our content and style feature representations. This function will simply load and preprocess both the content and style images from their path. Then it will feed them through the network to obt...
d1f65d11df7398c24b7eea2ed486b4f78a51c2aa
3,630,108
def check_string(sql_string, add_semicolon=False): """ Check whether a string is valid PostgreSQL. Returns a boolean indicating validity and a message from ecpg, which will be an empty string if the input was valid, or a description of the problem otherwise. """ prepped_sql = sqlprep.prepare...
111b4fc114ecc8bf315cb9ba28bd56557b9ec08f
3,630,109
def interpolate_freq_stft(Y, F_coef, F_coef_new): """Interpolation of STFT along frequency axis Notebook: C2/C2_STFT-FreqGridInterpol.ipynb Args: Y: Magnitude STFT F_coef: Vector of frequency values F_coef_new: Vector of new frequency values Returns: Y_interpol: Interp...
c3be2354667b92260fab043ee8b88572a1aa7863
3,630,110
import os def save_shapely_shapes_to_file(shapes_list, ref_shp, output_shp,copy_field=None): """ save shapes in shapely format to a file Args: shapes_list: shapes list, can be polygon, line, and so on ref_shp: reference shapefile containing the projection information output_shp: sa...
fb2461e7c5085a6c9e3ac715d5ce3d4dfa1f7798
3,630,111
def get_guide_counts(mags, t_ccd): """ Get guide star fractional count in various ways. - count_9th : fractional stars greater than "9th" magnitude (need 3.0) - count_10th : fractional stars greater than "10th" magnitude (need 6.0) - count_all : weighted fractional count of all stars Parameter...
41c428839d9bcce5db3e4cc48089fa236735f37b
3,630,112
def cal2theta(qmag, energy_kev=17.794): """ Calculate theta at particular energy in keV from |Q| twotheta = cal2theta(Qmag,energy_kev=17.794) """ energy = energy_kev * 1000.0 # energy in eV # Calculate 2theta angles for x-rays twotheta = 2 * np.arcsin(qmag * 1e10 * fg.h * fg.c / (energy *...
1f71d94be21a4ed2871b358b52cc7d1529cb7255
3,630,113
import os import re def convert(df,to_convert,out_file=None,overwrite=False, uid_to_pretty=False): """ Private function wrapped by uid_to_pretty and pretty_to_uid that converts a file or string between uid and pretty. df: dataframe with pretty name data and uid to_convert: content to ...
db31d93011b4237a71360f6823a7d9d50b4c741c
3,630,114
import os import ctypes def _load_lib(): """Load libary by searching possible path.""" curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__))) lib_search = curr_path lib_path = libinfo.find_lib_path(_get_lib_names(), lib_search, optional=True) if lib_path is None: retur...
30660e41f2831df1a6176d529b58531dd4f84c97
3,630,115
from datetime import datetime import os def get_train_data( image_list, gt_list, out_dir=None, name='train-unet', shape=(10, 256, 256), n_each=100, channels=('z-1', 'y-1', 'x-1', 'centreness'), scale=(4, 1, 1), log=True, validation_prop=0.2, ): """ Generate traini...
33410d527e06ef057206919327038f4979d82d87
3,630,116
def data_combiner(n_actions: int, subject_ids: list, n_takes: int, modalities: list, skeleton_pose_model: str): """Combines skeleton point information for all actions, all takes, given list of subject ids and given list of modalities. ...
c210423ad563de2f29a5bdaaabee5ae9920cf4bc
3,630,117
import torch def yolo_eval(yolo_outputs, model_image_size, true_image_size=None, max_boxes=9, score_threshold=.6, iou_threshold=.5, on_true=False): """Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Parameters: ----------- y...
06fe4e2bbdf0b31e510138d28341431b8e719ea9
3,630,118
def input_fn_builder(features, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) ...
c73b4fca8e9fe415a3a6d39831c2a03e37a063a1
3,630,119
import glob def expand_files(files): """Expands a wildcard to a list of paths for Windows compatibility""" # Split at whitespace files = files.split() # Handle wildcard expansion if len(files) == 1 and '*' in files[0]: files = glob.glob(files[0]) # Convert to Path objects return ...
46e2d6e7ee1609c144d04a2d429dc07ff1786cf1
3,630,120
def get_index(): """ Return the index from a loaded index if loaded or from building and loading from files. """ global _LICENSES_INDEX if not _LICENSES_INDEX: _LICENSES_INDEX = get_license_index() return _LICENSES_INDEX
7b75493e03da1eedc107b57809e6e47c45f52282
3,630,121
import typing def historical_daily_discounted_cash_flow( apikey: str, symbol: str, limit: int = DEFAULT_LIMIT ) -> typing.List[typing.Dict]: """ Query FMP /historical-daily-discounted-cash-flow/ API. :param apikey: Your API key. :param symbol: Company ticker. :param limit: Number of rows to r...
1a0b77e2bb342989990f9af1d11cd205ee0b30e5
3,630,122
def split_exon(exon, cds): """Takes an exon and a CDS, and returns a map of regions for each feature (UTR5/3, CDS) that may be inferred from the arguments. Note that the CDS is simply returned as is, to simplify downstream handling of these features.""" results = [cds] if exon["start"] < cds["s...
e2bb12a688bbe3e5c79039c2a9cce4e5aa9e9a1b
3,630,123
def state_dict_to_cpu(state_dict): """Make a copy of the state dict onto the cpu.""" # .state_dict() references tensors, so we detach and copy to cpu return {key: par.detach().cpu() for key, par in state_dict.items()}
2d1fcc07ab8eac192a846cbcdb8d7363ffd8e9e8
3,630,124
def NpapiFromNPVariant(scope, type_defn, input_expr, variable, success, exception_context, npp): """Gets the string to get a value from a NPVariant. This function creates a string containing a C++ code snippet that is used to retrieve a value from a NPVariant. If an error occurs, like if the NPVariant is n...
e17533806bff882408910ad49acbcd30db0c2030
3,630,125
from lane_lines_finder.lane_lines_detector import FindLines def find_lane_lines(): """ FindLines used in Udacity self-driving-car nanodegree. :return: FindLines """ return FindLines(window_number=10, window_width=150, window_min_n_pixels=50, search_width=150, pixels_to_meters=...
7f218a2fd6c063b684dcafb52de35f9abedf61c8
3,630,126
import struct def CollectBmpTermination(sock, msg_length, verbose=False): """Collect a BMP Termination message. Args: sock: socket from which to read. Returns: A list of strings. Raises: ValueError: an unexpected value was found in the message """ print_msg = [] indent_str = indent.Inden...
5d1af7fda44cc1d02b7c970f4d6b35d9492fe196
3,630,127
def near_field_map_vect_vjp(params: NearFieldParams, nu_vect: jnp.ndarray) -> jnp.ndarray: """function to comput the near field in a circle of radious 1, in this case we use the ls_solver_batched_sigma, which already has a custom vjp """ Rhs = -(params.ls_params.omega**2)\ ...
bb81e4328f77ebbb118840e3b50a573d3f5f1eed
3,630,128
import unicodedata def normalize_str(text): """ Normalizes unicode input text (for example remove national characters) :param text: text to normalize :type text: unicode """ # unicodedata NFKD doesn't convert properly polish ł trans_dict = { u'ł': u'l', u'Ł': u'L' } ...
40c8f77cdbf08b12a3867cd4a9d9bb91b323b50b
3,630,129
def start(): """Route for starting the server.""" try: if not session.get('logged_in'): return redirect(url_for('login')) else: do_start_server() return redirect(url_for('home')) except Exception as e: abort(500, {'message': str(e)})
df1e7e2dc6ed295b5960e86fdf161ae9471581bb
3,630,130
def get_context_data(data) -> dict: """Look for 'context' item in 'queries' item.""" if "queries" in data: if "context" in data["queries"]: if isinstance(data["queries"], list): return data["queries"][0]["context"] else: return data["queries"]["con...
4e05d3d9041a8199f32b4201dcfc69d3adef1034
3,630,131
from datetime import datetime def dttm_to_epoch(date_str, frmt='%Y-%m-%dT%H:%M:%SZ'): """Convert a date string to epoch seconds.""" return int((datetime.datetime.strptime(date_str, frmt) - datetime.datetime(1970, 1, 1)).total_seconds())
99dbf72be2e4923c6d8e0010ed75c57b9a2c7ecf
3,630,132
import copy def merge(src: list, dst: list) -> list: """Merge `src` into `dst` and return a copy of `dst`.""" # Avoid side effects. dst = copy.deepcopy(dst) def find_dict(data: list, key: str) -> dict: """Find and return the dictionary in `data` that has the `key`.""" tmp = [_ for _ i...
84976322fda7306d6bc15507750314b6b4fcad44
3,630,133
def restart_component(service_name, template_name): """Stop an component, then start it.""" ret = RefCPSServiceExtent.host_template_instance_operate(service_name, template_name, 'stop') ...
76ecf29bfb09e3ec005dd35598968421f65470c5
3,630,134
import traceback def handle_unknown_errors(exc): """All not HTTP errors should result in a formatted server error.""" return jsonify(dict( traceback=traceback.format_exc(), message=str(exc), )), 500
b20d63a6b956e7c460d8c80dfd5d6eb19ecad5de
3,630,135
def to_device(device, x): """Send an array to a given device. This method sends a given array to a given device. This method is used in :func:`~chainer.dataset.concat_examples`. You can also use this method in a custom converter method used in :class:`~chainer.training.Updater` and :class:`~chainer...
fea2c853ace3ddb843d6deabd389f24ed65d5b56
3,630,136
def grab_receivers(apk) : """ @param apk : an APK instance @rtype : the android:name attribute of all receivers """ return apk.get_elements("receiver", "android:name")
632d6903b63ca9d815a9f9d81ff19b8d6dc12a84
3,630,137
def itos(x): """Converts intergers to strings""" if type(x) != int: raise ValueError("Input value not an integer!") return '{}'.format(x)
96efe311cade41b37c4f671ed0b7e5e2a74f3d0b
3,630,138
import json import re def translate_reference_entities(ref_entities, mappings=None): """Transform MaaS reference data for comparison with test deployment. Positional arguments: ref_entities -- the reference entity data Keyword arguments: mappings -- describe the relationship between the referenc...
8e7a6144b5d51fb25908a70100e0d1e03b10b3d5
3,630,139
def get_data_base(arr): """For a given array, finds the base array that "owns" the actual data.""" base = arr while isinstance(base.base, np.ndarray): base = base.base return base
d66596618eb464ef7267de9fb3911f4afe13743b
3,630,140
import os def file_size_feed(filename): """file_size_feed(filename) -> function that returns given file's size""" def sizefn(filename=filename,os=os): try: return os.stat(filename)[6] except: return 0 return sizefn
da6c5d15df0f3d99022f3d42c95bb33a82065e32
3,630,141
def compute_discriminator_loss(real_logit, fake_logit): """Computes the discriminator hinge loss given logits. Args: real_logit: A list of logits produced from the real image fake_logit: A list of logits produced from the fake image Returns: Scalars discriminator loss, adv_loss, patchwise accuracy o...
17846d008a0c54658af429774849ce3eea35513c
3,630,142
import os def get_ade20_vqa_data(file_name="ade20k_vqa.jsonl"): """ Get the general project configpretrained_dir = conf["captioning"]["pretrained_dir"] :return: """ conf = get_config() vqa_file = conf["ade20k_vqa_dir"] file = os.path.join(vqa_file, file_name) print(f"Reading {file}") ...
1bf762d0b547d14c46a4847332623fd8eeff5e32
3,630,143
def gap_calculator(condition_vector): """ This function calculates max gaps between daily activites in a time series. Requires only a single binary vector describing whether a condition was met. """ # Find the index of all days in which the condition is true max_gap = None indices = np.wher...
ba2fc38505cea38d7e228e8e07b831209e30feb7
3,630,144
def inverse_warp(img, depth, pose, intrinsics, intrinsics_inv, target_image): """Inverse warp a source image to the target image plane Part of the code modified from https://github.com/tensorflow/models/blob/master/transformer/spatial_transformer.py Args: img: the source image (where to ...
bb28cc5e4e29ad50a731bb8b39667e19e96721f4
3,630,145
from keystoneauth1 import session from keystoneauth1.identity import v2 def _get_session_keystone_v2(): """ Returns a keystone session variable. """ user, password, auth_uri, project_name, project_id, user_domain_name = _get_connection_info('2') auth = v2.Password(username=user, password=password,...
577dbf6dc82857dbc4d881643e3821532eb79925
3,630,146
from typing import Dict from typing import Any from typing import List import os def fetch_afl_data(path: str, params: Dict[str, Any] = {}) -> List[Dict[str, Any]]: """ Fetch data from the afl_data service. Params ------ path (string): API endpoint to call. params (dict): Query parameters to ...
e0c713cbae39bf4eb2f4dc6b3b2efd057168c3ee
3,630,147
def mock_diffuser_v1_battery_cartridge(): """Create and return a mock version 1 Diffuser with battery and a cartridge.""" return mock_diffuser(hublot="lot123v1")
4371298c9004b33bd69ae57ccc02220c3b37baf6
3,630,148
def hist(array : np.ndarray): """ given array of integer values, returns the histogram of consecutive integer values without hole """ bins = np.append(np.arange(0,array.max()+1)-0.5,array.max()+0.5) return np.histogram(array, bins = bins)[0]
37bbfa2e313984d93c75c99a786435922b4e8ead
3,630,149
def derive_shared_secret(private_key: bytes, public_key: bytes): """Generate a shared secret from keys in byte format.""" derive = ECDH(curve=NIST256p) derive.load_private_key_bytes(unhexlify(private_key)) derive.load_received_public_key_bytes(unhexlify(public_key)) secret = derive.generate_shared...
e9e398ec26bc7871c43d719e48a1df32a5418737
3,630,150
def process_5p(chrom, positions, strand, vertex_IDs, gene_ID, gene_starts, edge_dict, locations, run_info): """ Conduct permissive match for 5' end and return assigned vertex, edge, and distance """ # First get a permissively matched start vertex start_vertex, diff_5p, known_start = ...
3c97f243a86f6c8b624390d886be17f73cbe2665
3,630,151
def create_salt(length: int = 128) -> bytes: """ Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes """ return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length))
013f0e9ec856c2d89660e3d01069e6f0396186a8
3,630,152
from typing import Dict from typing import List def convert_xclim_inputs_to_pywps(params: Dict, parent=None) -> List[PywpsInput]: """Convert xclim indicators properties to pywps inputs.""" # Ideally this would be based on the Parameters docstring section rather than name conventions. inputs = [] # Ma...
bdab2d3f365a3d1f0c8f3ff4208d38f72ad8d0be
3,630,153
def is_readable_key_pressed(code) -> bool: """ 押されたキーがアルファベットキー、数字キー、「-」キーのいずれかかを判断する。 :param code: pygame.event.get()[n].keyから取得できる文字コード。 :return: 上記の条件に当てはまればTrue、なければFalse """ if chr(code) == "-": return True if not chr(code).isalnum(): return False if not chr(code...
fe708e74068cfee265f782d94f149137e65342c3
3,630,154
from typing import Iterable from typing import List import itertools def extend(sequence: Iterable[_T], minsize: int) -> List[_T]: """ Extend ``sequence`` by repetition until it is at least as long as ``minsize``. .. versionadded:: 2.3.0 :param sequence: :param minsize: :rtype: .. seealso:: :func:`~.extend...
4040f0c415fdfa0d53c53ed3da0e6d0839ed7a92
3,630,155
def admin_view(view, cacheable=False): """ Overwrite the default admin view to return 404 for not logged in users. """ def inner(request, *args, **kwargs): if not request.user.is_active and not request.user.is_staff: raise Http404() return view(request, *args, **kwargs) ...
8fa7d481c8eb3b5d11dce7448a83b3ed9beed051
3,630,156
from datetime import datetime def rtn_dates(beg, end=None, using_weekend=False, rtn_string=True): """ :param beg: Date String, e.g. 20170901, 2017-09-01 :param end: Date String, e.g. 20170901, 2017-09-01, if not specified, using current date :param using_weekend: :param rtn_string: (indicate wheth...
9fd6a9ee30cc901d5de2074c87c49b68d74d86ea
3,630,157
def pr_auc_score(y_true: np.ndarray, y_score: np.ndarray): """ Area under Curve for Precision Recall Curve Args: y_true: Array of actual y values y_score: Array of predicted probability for all y values Returns: Area under Curve for Precision Recall Curve """ assert y_tr...
4e412e911ee14e8d52b042a5b34e03ee26800fad
3,630,158
async def save_legal_person(request: LegalPersonInput): """ ### Recurso que tem por objetivo salvar uma pessoa fisica. """ try: manage_legal_person = ManageLegalPerson() legal_person = LegalPerson(**request.dict()) legal_person = await manage_legal_person.save_legal_person(le...
0d65ae23ee51708918b8bab87068ca1bcdbca55e
3,630,159
def describe_outputs(path): """Return a list of :class:`WorkflowOutput` objects for target workflow.""" workflow = _raw_dict(path) outputs = [] for (order_index, step) in workflow["steps"].items(): step_outputs = step.get("workflow_outputs", []) for step_output in step_outputs: ...
85a45cc4642e885ce260912c8935a0a9a3683e33
3,630,160
from typing import Union def parse_content_length_value(stream: Union[str, int]) -> ContentLengthValue: """Parses the `Content-length` header value. :param stream: String or integer value of the header. :return: A `ContentLengthValue` instance. :raises ParseError: When the value cannot be cast to a...
9f964289b7784f694a50b15b5c4685682f5895e1
3,630,161
import os def is_stale(target, source): """Test whether the target file/directory is stale based on the source file/directory. """ if not os.path.exists(target): return True target_mtime = recursive_mtime(target) or 0 return compare_recursive_mtime(source, cutoff=target_mtime)
3e4311f0e2622008986f5609bd9bb86c48c6d6aa
3,630,162
def newsToEmail(item,eList): """ - item : One news item - eList : A list of all person objects - return : a list of validated email objects """ IDs = [] for e in eList: print getPref(item) if countCommon(getPref(item),e.pref) > 0: IDs.append(e) return I...
c5ce5e670f02a3da8252b5adb56aaa75a45e8c80
3,630,163
def combine(background_img, figure_img): """ :param background_img: (SimpleImage) the original image that will replace the green screen :param figure_img: (SimpleImage) the original image with green screen :return: the updated image with green screen replaced as the background space ship """ bac...
212e69e8c600373017e4c7f9fd1b2125ac1d2e59
3,630,164
def slot_into_containers(container_objects, package_objects, overlap_threshold=0.5, unique_assignment=True, forced_assignment=False): """ Slot a collection of objects into the container they occupy most (the container which holds the largest fraction of the object). """ best_mat...
5c14ea3de0a517f35966f20b782519f39aed1694
3,630,165
def return_function_info_data(data_kind, data_func_name): """ 闭包,返回读取数据库函数 参数: data_kind (str):数据种类,如'futures' data_func_name (str) : 数据表名称,如'futures_date' 示例: info_futures_basic = return_function_info_data(data_kind='futures', data_func_name='futures_date') info_futures_basic为...
f011fcb14e494d9172ea319fe1a66ac696cd305d
3,630,166
def landscapes(request): """ """ images = Landscapes.display_image() return render(request, 'all-photos/landscapes.html', {"images": images})
d3c570febea95a00791d824d2809cc3c8e0fbbc6
3,630,167
def make_sparse_matrix(df): """ Make sparse matrix :param df: train_df [userId, movieId, rating, ...] :return: sparse_matrix (movie_n) * (user_n) """ sparse_matrix = ( df .groupby('movieId') .apply(lambda x: pd.Series(x['rating'].values, index=x['userId'])) .unsta...
90b2cf8e738da4bdca01bb2f29b231b1781bfcf1
3,630,168
from datetime import datetime def genreport(): """Generated report includes taskId, data time, task status and type Args: Examples: >>> genreport() """ taks_list = [] status = ee.data.getTaskList() for items in status: ttype = items["task_type"] tdesc = items["desc...
6bce32d0cb51f8aa322a280e2c6c9b64a89169ff
3,630,169
def input_file(ntemps, formula, delta_h, enthalpy_temp=0.0, break_temp=1000.0): """ Writes a string for the input file for ThermP. :param ntemps: number of temperatures :type ntemps: int :param formula: chemical formula for species :type formula: str :param delta_h: enthalpy...
c1ea1506719d59f570687c6c69ac20c6a499ca8e
3,630,170
import typing def plot_facet_meshfunction(f: dolfin.MeshFunction, names: typing.Optional[IntEnum] = None, invalid_values: typing.Optional[typing.List[int]] = None) -> None: """Plot a `size_t` meshfunction defined on facets of a 2D mesh. Useful for check...
e249382e30e907e2d42ec73b1b690faca32dcdfb
3,630,171
def get_etf_ticker_name(ticker: str) -> str: """종목 이름 조회 Args: ticker (str): 티커 Returns: str: 종목명 >> get_etf_ticker_name("069500") KODEX 200 """ return krx.get_etx_name(ticker)
100141820a830fa6c3299b2aa6a0ed08039db240
3,630,172
import logging def getLogger(name='root') -> logging.Logger: """Method to get logger for tests. Should be used to get correctly initialized logger. """ return logging.getLogger(name)
dde177b07f9d8528d216fbc4c719e5bff9c67939
3,630,173
from pathlib import Path def process_load_magic(path, cell): """Replace load magics with the solution.""" modified = False # Find any load magics load_magics = find_load_magics_in_cell(cell) # Replace load magics with file contents for magic_string in load_magics: path = Path(path) ...
9620f66161ffa2eb293e537021f5e47294b49076
3,630,174
def public_dict(obj): """Same as obj.__dict__, but without private fields.""" return {k: v for k, v in obj.__dict__.items() if not k.startswith('_')}
2edee1a17d0dad6ab4268f80eb565406656a77b4
3,630,175
import time import os import pickle def save_preds( t_params, m_params, li_preds, li_timestamps, li_truevalues, custom_test_loc=None, count=0 ): """Save predictions to file Args: t_params (dict): dictionary for train/test params m_params (dict): dictionary for m params ...
cb21ceb3c7f4232a1e5e0bdb7a1f2c3b6a4e78ef
3,630,176
def first_der_K_mulvar(x, kernel_type='Gaussian'): """ First derivative of Multivariate seperable and isotropic, identity scale kernel( R^d--> R) ∇_c(K(x))=first_der_k_one_dim(x_c)*(Π_(l=1&& l!=c)^(dim) ((k_one_dim(x_l)))) """ dim=x.size loop_range=range(dim) #dimension of x grad...
cd06168abf2a7bd9354b4fa5b16107099857dce4
3,630,177
from typing import Union from typing import List from typing import Dict def _to_serializable_prompt( prompt, at_least_one_token=False ) -> Union[str, List[Dict[str, str]]]: """ Validates that a prompt and emits the format suitable for serialization as JSON """ if isinstance(prompt, str): ...
12e11b85bbcaf9137605f987981ad6e48cc6a949
3,630,178
def lrepeat(elem, n): """ >>> lrepeat(1, 2) [1, 1] """ return list(repeat(elem, n))
ef36f2e62cf8e9c3eb3fecef176a4aee9b60b951
3,630,179
def wer(ref_path, hyp_path): """ Compute Word Error Rate between two files """ with open(ref_path) as ref_fp, open(hyp_path) as hyp_fp: ref_line = ref_fp.readline() hyp_line = hyp_fp.readline() wer_score = 0.0 line_cpt = 0.0 while ref_line and hyp_line: wer_sc...
39860a89d94614aced191049f4dc77031438f0a8
3,630,180
def get_supported_hmac_hash(hash_type_str: str) -> crypto.SupportedHashes: """Return a crypto SupportedHashes enum type from a string hash type Args: hash_type_str: String hashtype, i.e. SHA256 Returns: appropriate crypto.SupportedHashes enum value Raises: ValueError when bad has...
74e3e128268ef3007c4fa9c91af9c103f03523f1
3,630,181
import os def export_cleaned_data(df): """ Function to export merged df into specified folder Args: path (str): Path of the folder filename(str): Name of the file """ path = os.getcwd() filename = 'cleaned_merged_seasons.csv' filepath = join(dirname(dirname("__file__")), path,...
27810bc66a9f7eef88517883dc83a5860e785dc8
3,630,182
import tempfile import os def get_tmpfile_name(): """Get a new temporary file name""" tmp_dir = tempfile._get_default_tempdir() tmp_file = next(tempfile._get_candidate_names()) return os.path.join(tmp_dir, tmp_file)
273f5d90db50f63d6b2320c763e5300e9750d5b6
3,630,183
def adjustEdge(tu, isStart): """ Adjust tu time based on slot edge type """ # Adjust start and end so they don't pick the wrong slot when the end of one slot overlaps # by one minute the start of the next if isStart: t = (tu + timedelta(minutes=1)).time() else: t = (tu - time...
d5aeb868944833b6f9dceb0e42271adb2959c0c0
3,630,184
import struct def parse_extensions(buf): """ Parse TLS extensions in passed buf. Returns an ordered list of extension tuples with ordinal extension type as first value and extension data as second value. Passed buf must start with the 2-byte extensions length TLV. http://www.iana.org/assignments/t...
a93d997ffa72a540a87787cbf185fe0d29b4587f
3,630,185
def COS( number: func_xltypes.XlNumber ) -> func_xltypes.XlNumber: """Returns the cosine of the given angle. https://support.office.com/en-us/article/ cos-function-0fb808a5-95d6-4553-8148-22aebdce5f05 """ return np.cos(float(number))
2b4353caeddd955579be6fdfef7538436acef97c
3,630,186
def validate_name(dataset): """Check wfs/cache and the bcdc api to see if dataset name is valid """ if dataset.upper() in list_tables(): return dataset.upper() else: return get_table_name(dataset.upper())
a2f5c872cbbaddbddfa1985708b1edebe2f891f9
3,630,187
import torch def farthest_point_sample(xyz, npoint): """ Input: xyz: pointcloud data, [B, N, C], where C is probably 3 npoint: number of samples Return: centroids: sampled pointcloud index, [B, npoint] """ device = xyz.device B, N, C = xyz.shape centroids = torch.ze...
3d62a8785bc998970b4ef126b97c3270fa6f3ca6
3,630,188
def auto_scaling(setup_trainer_and_train, config, num_iters=2): """ Auto-scale the number of envs and batch size to maximize GPU utilization. param num_iters: number of iterations to use when performing auto-scaling. """ def launch_process(func, args): """ Run a Python function on a...
100fe0cb9fef8963e1f2e07a8874e6bb7ddefdee
3,630,189
def eta_sat_Vargaftik_and_Yargin_Table(): """Dynamic viscosity of saturated Li vapor Returns ------- array Array of temperature and dynamic viscosity data References ---------- Vargaftik, N B, and V S Yargin. Ch 7.4: Thermal Conductivity and Viscosity of the Gaseous Phase. ...
ef7547e5c106960b2d14ebc9d53cf585c3e0c822
3,630,190
def getColumn(data, colN): """ Return the column colN (counted starting from 0) in the data. """ return transpose(data)[colN]
65151d9a1b79b424a187a425602da5608735398a
3,630,191
def humanize_arrow_date(date): """ Date is internal UTC ISO format string. Output should be "today", "yesterday", "in 5 days", etc. Arrow will try to humanize down to the minute, so we need to catch 'today' as a special case. """ try: then = arrow.get(date) now = arrow.utcnow...
b1ff01887bb45acc75083d90818add9017284875
3,630,192
def file_compare_files_sum(filelist1,filelist2,filetype='blankspace'): """ This is built on file_add_data_files to compare and plot the two list of files by checking if their respective summing is equal. Notes ----- Now only the 1Darray is allowed to contained in each file """ outarr1 = fil...
03f5cfee8a1588dd72654c315d8a152b9a4b165a
3,630,193
def toluene_material_stream(): """ Create a homogeneous material_stream model """ class material_stream(MaterialStream): def __init__(self, name, description, pp = pp_toluene): super().__init__(name, description, property_package=pp()) self.mdot.setValue(100.) ...
71301c6324128c5411abb2d8cd3c49fb6718e86e
3,630,194
def wilight_to_opp_position(value): """Convert wilight position 1..255 to opp.format 0..100.""" return min(100, round((value * 100) / 255))
4f6e4298a77c29ff0375d0ce5e5fd23e77e30622
3,630,195
import sh def has_staged_uncommitted(): """ Return a boolean indicating whether the repository has staged, but uncommitted changes """ try: sh.git('diff', '--cached', '--exit-code') return False except sh.ErrorReturnCode_1: return True
22d3fdb24fcfd0e802ed3e3d1318974f427858ab
3,630,196
def get_transition_matrix(exp, group_name, bnames): """Gets a markov transition matrix for a given FixedCourtshipExperiment and list of behavioral states. Parameters ---------- exp : FixedCourtshipExperiment group_name : string Name of group to get transition matrix for. bnames : ...
b75330c39a3ade485d09084af5e6bb9f5437b533
3,630,197
def get_task_link(task_id, task_df): """Get the link from the PYBOSSA task.""" try: task = task_df.loc[int(task_id)] except KeyError: return None return task['info']['link']
d90e994d2f0a4718bbedf8fd5fd534f6d5d32549
3,630,198
from datetime import datetime def hchart(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'research/bar.html', { 'title':'Chart', 'message':'Highcharts Based', 'year':datetime.now().year, ...
2bceb733c75f1cd65170f7a1352564337820e01b
3,630,199