content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json import os def fontwidth(string, font='sans-serif'): """Function: Returns the px width of a string assuming a base size of 16px.""" _fontwidth = json.load(open(os.path.join(abs_path(), 'fonts.json'), encoding='utf-8')) codes_len = 127 default_width = 32 default_width_idx = 120 for _...
1fa6b71881c8711908935bc97a06b7cbbca0e809
5,600
def create_model(): """ResNet34 inspired analog model. Returns: nn.Modules: created model """ block_per_layers = (3, 4, 6, 3) base_channel = 16 channel = (base_channel, 2*base_channel, 4*base_channel) l0 = nn.Sequential( nn.Conv2d(3, channel[0], kernel_size=3, stride=1, pad...
fa9157c457b31b8bd0c3ca0b5dac8f68734486ec
5,601
from typing import Union from typing import Optional def kv_get(key: Union[str, bytes], *, namespace: Optional[str] = None) -> bytes: """Fetch the value of a binary key.""" if isinstance(key, str): key = key.encode() assert isinstance(key, bytes) retu...
03be836a3d42f39f2b28b2f3ea557cdf39918bcd
5,602
def construct_model(data, local_settings, covariate_multipliers, covariate_data_spec): """Makes a Cascade model from EpiViz-AT settings and data. Args: data: An object with both ``age_specific_death_rate`` and ``locations``. local_settings: A settings object from ``cascade_plan``. covar...
eb4287dcaceb1cf320bf8761143c96ffadc148b2
5,603
def set_off(): """ Turns OFF the lamp. """ unicorn.set_status(False) return OK
e82ab948a1656c343237a11e048c1ed38487353b
5,604
def get_all_active_bets(): """ Gets all the active bets for all active discord ritoman users """ return session.query(LoLBets).filter(LoLBets.completed == false()).all()
844b36b695bf67db3cff82711b9e17da3db20c8e
5,605
def get_quantize_pos_min_diffs(inputs, f_min, f_max, q_min, q_max, bit_width): """Get quantize pos which makes min difference between float and quantzed. """ with tf.name_scope("GetQuantizePosMinDiffs"): min_scale_inv = tf.math.divide(f_min, q_min) max_scale_inv = tf.math.divide(f_max, q_max) float_scal...
63cc0b8ac370513ecfbe3068d02299a3d3016638
5,606
def _non_string_elements(x): """ Simple helper to check that all values of x are string. Returns all non string elements as (position, element). :param x: Iterable :return: [(int, !String), ...] """ problems = [] for i in range(0, len(x)): if not isinstance(x[i], str): p...
974715622949157693084823a52a88973b51d100
5,607
from pathlib import Path def configure_dirs(base_path: str, config_name: str, dataset_name: str) -> str: """ Performs configuration of directories for storing vectors :param base_path: :param config_name: :param dataset_name: :return: Full configuration path """ base_path = Path(base_...
b4791f836d0414ed582c3093b3dac1727f82a39c
5,608
def config_entry_version_fixture(): """Define a config entry version fixture.""" return 2
cac78c1f02668c95ce918d6219cadd5f08ab21c9
5,609
def edge_dfs(G, source=None, orientation=None): """A directed, depth-first-search of edges in `G`, beginning at `source`. Yield the edges of G in a depth-first-search order continuing until all edges are generated. Parameters ---------- G : graph A directed/undirected graph/multigraph....
8e7f1ba137f0392768e5b814a8898842bf2e5c2f
5,610
import hashlib async def _md5_by_reading(filepath: str, chunk_size: int = DEFAULT_BUFFER_SIZE) -> str: """ Compute md5 of a filepath. """ file_hash = hashlib.md5() async with async_open(filepath, "rb") as reader: async for chunk in reader.iter_chunked(chunk_size): file_hash.upd...
d42e3f6ba994bc35c32cab48cdc4b78e44f678d1
5,611
def client_authenticator_factory(mechanism,password_manager): """Create a client authenticator object for given SASL mechanism and password manager. :Parameters: - `mechanism`: name of the SASL mechanism ("PLAIN", "DIGEST-MD5" or "GSSAPI"). - `password_manager`: name of the password manager...
93fccb21f71a31fed953f6260f5906b240669033
5,612
def wait_for_cell_data_connection( log, ad, state, timeout_value=EventDispatcher.DEFAULT_TIMEOUT): """Wait for data connection status to be expected value for default data subscription. Wait for the data connection status to be DATA_STATE_CONNECTED or DATA_STATE_D...
f2e2474af757c5a36cb054afe1f429638641f2e6
5,613
import configparser def _parse_lists(config_parser: configparser.ConfigParser, section: str = '') -> t.Dict: """Parses multiline blocks in *.cfg files as lists.""" config = dict(config_parser.items(section)) for key, val in config.items(): if '/' in val and 'parameters' not in section: ...
d591a9eeb656dff9c4fbbce9964575cd7ce15352
5,614
def get_filename_pair(filename): """ Given the name of a VASF data file (*.rsd) or parameter file (*.rsp) return a tuple of (parameters_filename, data_filename). It doesn't matter if the filename is a fully qualified path or not. - assumes extensions are all caps or all lower """ param_file...
f6eb5a64cf472f230c5806447d9c2ee8ae43a71d
5,615
async def get_reposet(client, headers, reposet_id): """Get the reposet by id.""" url = f"https://api.athenian.co/v1/reposet/{reposet_id}" return await do_request(client, url, headers)
b97262bf1f246bc563abe352f1122a9ad61705c3
5,616
import sys import re import os import google def conditions(converted: str) -> bool: """Conditions function is used to check the message processed. Uses the keywords to do a regex match and trigger the appropriate function which has dedicated task. Args: converted: Takes the voice recognized sta...
3113a35b0a77fff3531238c0d0223ca806a5dba0
5,617
def detect_os_flavour(os_type): """Detect Linux flavours and return the current version""" if os_type: # linux try: return platform.linux_distribution()[0] except Exception, e: return None else: # windows return platform.platform()
4ab3ebec3683fc99a99e70540ea29d049b54347d
5,618
def straightenImage(im, imextent, mvx=1, mvy=None, verbose=0, interpolation=cv2_interpolation): """ Scale image to make square pixels Arguments --------- im: array input image imextend: list of 4 floats coordinates of image region (x0, x1, y0, y1) mvx, mvy : float number...
ab46e394011a8a2d9ed8974504e4e28b725ead78
5,619
import math def H(r2, H_s, H_d, a_s, a_d, gamma_s, gamma_d, G, v): """ """ pi = math.pi sqrt = math.sqrt r = sqrt(r2) H2_s = H_s**2 H2_d = H_d**2 R2_s = r2 + H2_s R2_d = r2 + H2_d alpha_s = 1.0 if gamma_s == 1.0 else 4 * H2_s / (pi*R2_s) alpha_d = 1.0 if gamma_d == 1.0 ...
0fa1606212278def22075692a56468d41a8c7a3c
5,620
from datetime import datetime def parse_time(event_time): """Take a string representation of time from the blockchain, and parse it into datetime object.""" return datetime.strptime(event_time, '%Y-%m-%dT%H:%M:%S')
df5af3a20acbeaa8e7424291d26055d3f38219ed
5,621
import os def do_pdftk_cat_first_page(pdf_file): """The cmd_args magick identify is very slow on page pages hence it examines every page. We extract the first page to get some informations about the dimensions of the PDF file.""" output_file = os.path.join(tmp_dir, 'identify.pdf') cmd_args = ['pdf...
f0c0b01411bcc6e66bc2450a5b81f2c1b7dd33ca
5,622
def addBenchmark(df): """Add benchmark to df.""" # Compute the inverse of the distance distance_inv = (1. / df.filter(regex='^distance*', axis=1)).values # Extract the value at the nearest station values = df.filter(regex='value_*', axis=1) # Compute the benchmark numer = (distance_inv * ...
62c63215d622c46bed8200f97ad55b985e2beb20
5,623
def is_file_like(f): """Check to see if ```f``` has a ```read()``` method.""" return hasattr(f, 'read') and callable(f.read)
9eee8c8f4a6966d1db67fb4aa9149e2fbd390fb9
5,624
def _string_to_days_since_date(dateStrings, referenceDate='0001-01-01'): """ Turn an array-like of date strings into the number of days since the reference date """ dates = [_string_to_datetime(string) for string in dateStrings] days = _datetime_to_days(dates, referenceDate=referenceDate) ...
114883cf0f2e48812a580c4cd8ae64671a4fc126
5,625
def safe_as_int(val, atol=1e-3): """ Attempt to safely cast values to integer format. Parameters ---------- val : scalar or iterable of scalars Number or container of numbers which are intended to be interpreted as integers, e.g., for indexing purposes, but which may not carry integ...
cbaff1fb1568fd43a4dd3a7a2054a805788b912c
5,626
def check_protocol(protocol): """ Check if a given protocol works by computing the qubit excitation probabilities """ qubit_weight = {} qubit_weight[protocol[0][0][0]] = 1.0 for pair_set in protocol: for i, j, p in pair_set: qubit_weight[j] = qubit_weight[i] * (1.0 - p) ...
8b9d0a8e329a340718d37bc79066be4a05cf2d20
5,627
def detachVolume(**kargs): """ detachVolume your Additional Volume * Args: - zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2] - id(String, Required) : Volume disk ID * Examples : print(server.detachVolume(zone='KR-M', id='7f933f86-e8bf-4600-9423-09e8f1c84460')) """ my_apikey,...
9c837559052fb41f4e40d18c211a497c7de3ca63
5,628
from typing import List from typing import Type from typing import Optional from typing import Dict from typing import Any from typing import Callable import time import traceback def observe(metric: str, accept_on: List[Type[Exception]] = [], # pylint: disable=E1136 decline_on: List[Type[Exc...
501fbaf8b4b3f77e334d7579834162f0393d1b5d
5,629
import pathlib import os def append_subdirs_to_mypy_paths(root_directory: str) -> str: """ Appends all immediate sudirs of the root_directory to the MYPYPATH , separated by column ':' TODO: Windows ? in order to be able to use that in a shellscript (because the ENV of the subshell gets lost) we also r...
d7b3e600c73eb6c9c968060f4162620d996144b3
5,630
import numpy def spherical_to_cartesian(lons, lats, depths): """ Return the position vectors (in Cartesian coordinates) of list of spherical coordinates. For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html. Parameters are components of spherical coordinates in a form of sca...
107899c23eeb7fb2cf79fbaa6650b4584543260a
5,631
import time def get_remote_webdriver(hub_url, browser, browser_ver, test_name): """ This functions returns remote web-driver instance created in selenoid machine. :param hub_url :param browser: browser name :param browser_ver: version for browser :param test_name: test name :return: re...
2f467f38f2fda6e7f95343e842ea42c3bb551181
5,632
def process_images(rel_root_path, item_type, item_ids, skip_test, split_attr, gen_image_specs_func, trafo_image_func, trafo_image_extra_kwargs=None, img_obj_type=None, img_attr=None, dimensions=(256, 256), max_valset_size=10000): """ Th...
9d9d6d53ed6a93c2c8b3f7c70d6cda54277b42b1
5,633
import typing import os def evaluate(config: Config) -> typing.Dict[str, float]: """ Load and evaluate model on a list generator Return: dict of metrics for the model run """ logger.info('Running evaluation process...') net_name = config.net_name pp_dir = config.paths['preprocess...
5773acd85bfacc4170fdf4e961a6a39141d32639
5,634
from typing import Callable def get_transform_dict(args, strong_aug: Callable): """ Generates dictionary with transforms for all datasets Parameters ---------- args: argparse.Namespace Namespace object that contains all command line arguments with their corresponding values strong_aug...
17ecc3ee611a9fa73176f9a9f354e293d7e4cc39
5,635
def choose_first_not_none(*args): """ Choose first non None alternative in args. :param args: alternative list :return: the first non None alternative. """ for a in args: if a is not None: return a return None
fe3efba85251161cd0a6ecb50583cc443cd04dc0
5,636
def _format_compact(value, short=True): """Compact number formatting using proper suffixes based on magnitude. Compact number formatting has slightly idiosyncratic behavior mainly due to two rules. First, if the value is below 1000, the formatting should just be a 2 digit decimal formatting. Second, the number...
3f2a2b034cbe1e8a3f21ded743ec328a692cc039
5,637
def matrix(mat,nrow=1,ncol=1,byrow=False): """Given a two dimensional array, write the array in a matrix form""" nr=len(mat) rscript='m<-matrix(data=c(' try: nc=len(mat[0]) for m in mat: rscript+=str(m)[1:-1]+ ', ' rscript=rscript[:-2]+'), nrow=%d, ncol=%d, by...
a28d91d797238857dd2ff58f24655504a936d4a7
5,638
from re import T def all(x, axis=None, keepdims=False): """Bitwise reduction (logical AND). """ return T.all(x, axis=axis, keepdims=keepdims)
b01891385c2b41d42b976beaf0ee8922b632d705
5,639
def config_find_permitted(cookie, dn, in_class_id, in_filter, in_hierarchical=YesOrNo.FALSE): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ConfigFindPermitted") method.cookie = cookie method.dn = dn method.in_class_id = in_class_id method.in_filter = in_filter method....
0367fb6d208b4a03ea4c1cc79e14faabe038cba6
5,640
def reformat_medication_statuses(data: FilteredData) -> FilteredData: """ Reformats medication statuses to binary indicators. Args: data: The data containing medication statuses to reformat. Returns: Data with reformatted medication statuses. """ for j in data.medications.colu...
4428d7e65893dfea33490de28e77dffe66562c31
5,641
def segmentwidget(img, params=None, alg=None): """Generate GUI. Produce slider for each parameter for the current segmentor. Show both options for the masked image. Keyword arguments: img -- original image gmask -- ground truth segmentation mask for the image params -- list of parameter o...
721cb1ddb55a90364593b53c3fdf3b650397a91c
5,642
import json def list_daemons(dut): """Get daemon table from ovsdb-server.""" daemon_list = {} c = ovs_vsctl + "--format json list daemon" out = dut(c, shell="bash") json_out = json.loads(out)['data'] # The output is in the following format # [["uuid","19b943b0-096c-4d7c-bc0c-5b6ac2f83014"...
35b28e8c38cd48a93f642b0e2820d0ff2ff87450
5,643
import math import collections def Cleanse(obj, encoding="utf-8"): """Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Turns byte strings into unicode strings. - Turns sets into sorted lists. - Turns tuples into lists. Arg...
e50e44bd3aa685838ea2e68537e2df288e9a058f
5,644
import time def wait_no_exception(lfunction, exc_class=None, exc_matcher=None): """Stops waiting on success.""" start_time = time.time() if exc_matcher is not None: exc_class = boto.exception.BotoServerError if exc_class is None: exc_class = BaseException while True: resul...
be5e9798570dd3f6ca6f9b78d136179f68a4ad3c
5,645
def testapp(app, init_database): """Create Webtest app.""" testapp = TestApp(app) #testapp = TestApp(app, extra_environ=dict(REMOTE_USE='test')) # testapp.set_authorization(('Basic', (app.config['USERNAME'],app.config['PASSWORD']))) # testapp.get_authorization() return testapp
01a579ae22c0eedfaac7d6dd5aeffd1b63f34612
5,646
def dois(self, key, value): """Translates dois fields.""" _identifiers = self.get("identifiers", []) for v in force_list(value): material = mapping( MATERIALS, clean_val("q", v, str, transform="lower"), raise_exception=True, ) doi = { "...
b7635815c451856d249feebeb1084ad28f0357d9
5,647
def transition(src, dest, state=None, permissions=None, required=None, commit_record=True, **kwargs): """Decorator that marks the wrapped function as a state transition. :params parameters for transition object, see docum...
309ffca49c2dd2af4dabb084c5f642d40e9d34e8
5,648
def get_html(url): """Returns HTML object based on given Gumtree URL. :param url: Offer URL. :return: Offer HTML object. """ session = HTMLSession() try: r = session.get(url) return r.html except ParserError: return None
6fd3aa8e7f2ff81f912e0d7050872a6e2de14827
5,649
def _get_lattice_parameters(lattice): """Return basis vector lengths Parameters ---------- lattice : array_like Basis vectors given as column vectors shape=(3, 3), dtype='double' Returns ------- ndarray, shape=(3,), dtype='double' """ return np.array(np.sqrt(np.do...
405111d5052307dd995e64c2ff7936481db4f34d
5,650
def save_batches(current_memory, id_tmp_dir, batch_num): """ batch_num : corresponds to the gradient update number """ target_csv = id_tmp_dir + "/batch" + str(batch_num) + ".csv" obs_copy = deepcopy(current_memory['current_obs']) reward_copy = deepcopy(current_memory['rewards']) cur...
311bf2c1083156dc26acb855f2cc61f142a1586b
5,651
def ikrvea_mm( reference_point: np.ndarray, individuals: np.ndarray, objectives: np.ndarray, uncertainity: np.ndarray, problem: MOProblem, u: int) -> float: """ Selects the solutions that need to be reevaluated with the original functions. This model management is based on the following ...
f9959cf7ddfcc2aa3aa2fc8c3062cfb63082b242
5,652
def homepage(request): """Main view of app. We will display page with few step CTA links? :param request: WSGIRequest instance """ if logged_as_admin(request): offers = Offer.objects.get_for_administrator() else: offers = Offer.objects.get_weightened() return render( ...
003e6f86ab09ede87e7f1c86910808c2da9c1e9d
5,653
def add_dict(dct1, dct2): """Returns a new dictionaries where the content of the dictionaries `dct1` and `dct2` are merged together.""" result = dct1.copy() result.update(dct2) return result
eba785e4d00534e94c1bdde413603d64e18aac05
5,654
import tempfile from pathlib import Path def edit_temp(contents="", name=""): """ Create a temporary file and open it in the system's default editor for the user to edit. The saved contents of the file will be returned when the editor is closed. :param contents: Pre-fill the file with the given t...
174acda4961cc945b917be6c66d1218d3e46914d
5,655
def _new_primitive_control( rabi_rotation=None, azimuthal_angle=0., maximum_rabi_rate=2. * np.pi, **kwargs): """ Primitive driven control. Parameters ---------- rabi_rotation : float, optional The total rabi rotation to be performed by the driven control. ...
dcaab9ace0269a0404435639d0e9e9e025f1013a
5,656
from typing import Optional from typing import Any from typing import Tuple def check_fit_params( X: TwoDimArrayLikeType, y: OneDimArrayLikeType, sample_weight: Optional[OneDimArrayLikeType] = None, estimator: Optional[BaseEstimator] = None, **kwargs: Any ) -> Tuple[TwoDimArrayLikeType, OneDimArra...
f385fb9db06d1bd0ee0a9ecef74fbca8f0754a4d
5,657
async def example_quest(request: web.Request) -> web.Response: """ Example quest handler that handles a POST request with a computer science trivia question :param request: The request object """ # Verify that it is a POST request, since that's what this quest is supposed to handle if request....
fed5ad72d9343c1fd420d98e638bf3f0de995670
5,658
import matplotlib.pyplot as plt def view_api_image(image_type, catalog_name, source_id): """Source spectrum image.""" catalog = source_catalogs[catalog_name] source = catalog[source_id] plt.style.use('fivethirtyeight') if image_type == 'spectrum': fig, ax = plt.subplots() source...
8137b0ca42b3e161fbd77d5f73beb2adeefa1fd3
5,659
def get_record_base_model(type_enum): """Return the dimension model class for a DimensionType.""" dim_model = _DIMENSION_TO_MODEL.get(type_enum) if dim_model is None: raise DSGInvalidDimension(f"no mapping for {type_enum}") return dim_model
dc232a173ea92bcb6ee2bafcd9eeae46862da5ec
5,660
import subprocess def cmd(command): """ Run a command and return its stdout """ try: completed = subprocess.run( command.split(" "), stdout=subprocess.PIPE, ) except FileNotFoundError: panic(f"Command `{command}` not found.") if completed.returncode > 0: panic(f"Command `...
cd378b564844988d1dd9fbd674b21cde0c071964
5,661
from io import StringIO def sas_to_pandas(sas_code, wrds_id, fpath): """Function that runs SAS code on WRDS or local server and returns a Pandas data frame.""" p = get_process(sas_code, wrds_id, fpath) if wrds_id: df = pd.read_csv(StringIO(p.read().decode('utf-8'))) else: df = pd...
50806526e1f44e58c227472ced3b5884d8b9f2d5
5,662
import subprocess def subprocess_run(*popenargs, input=None, timeout=None, check=False, **kwargs): # pylint: disable=redefined-builtin """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout a...
aef8e69ef7f09be414a941cc58a3d174242a1537
5,663
def _client_ip_address(request): """Return client ip address for flask `request`. """ if request.headers.getlist("X-PNG-Query-For"): ip_addr = request.headers.getlist("X-PNG-Query-For")[0] if ip_addr.startswith('::ffff:'): ip_addr = ip_addr[7:] elif request.headers.getlist("...
eb1b41ee707bac5aefaacdbb1958cd26a47fe288
5,664
def create_bb_points(vehicle): """ Extract the eight vertices of the bounding box from the vehicle. Parameters ---------- vehicle : opencda object Opencda ObstacleVehicle that has attributes. Returns ------- bbx : np.ndarray 3d bounding box, shape:(8, 4). """ b...
2cf2e2b1e9d64a246369ff9b182199ed64fb71b9
5,665
import tempfile import os import io def mkstemp( open_kwargs=None, # type: Optional[Dict[Text, Any]] text=True, # type: bool name_only=False, # type: bool *args, **kwargs): # type: (...) -> Union[(IO[AnyStr], Text), Text] """ WARNING: the returned file ob...
c13b2d41a74e1ee8bbfd0e090d083d7e1446fb34
5,666
def featuredrep_set_groups(sender, **kwargs): """Set permissions to groups.""" app_label = sender.label if (isinstance(app_label, basestring) and app_label != 'featuredrep'): return True perms = {'can_edit_featured': ['Admin', 'Council', 'Peers'], 'can_delete_featured': ['Admin', '...
354731d88ed6633d6cd62b73c6d1ea4cae97ca73
5,667
def download(loc, rem): """download rem to loc""" # does the remote file exist if not rem.exists(): return ReturnCode.NO_SOURCE # does the local file exist # if it doesnt, copy rem to loc, isLogged = False if not loc.is_file(): return do_copy(rem, loc, False) # is the local...
ff7421674f97a6923bbee6fa9be27d132d0095e3
5,668
from utils import publish_event def read_dict (conf_dict = {}, filename = "SWIM_config"): """ Open and read a dictionary of key-value pairs from the file given by filename. Use the read-in values to augment or update the dictionary passed in, then return the new dictionary. """ try: ...
655699cf8c0c007c8e66f15a75bf778686c7d8d9
5,669
def ordinals_to_ordinals(s): """ Example: 'third' -> '3rd' Up to 31st (intended for dates) """ for val in ordinals.keys(): s = s.replace(val, ordinals[val]) return s
4d45a9cfa0171a42deaf99d2e34e41dd5be6c96c
5,670
def create_dataframe_schema(): """ Create dataframe schema """ return pd.DataFrame(columns=['Station_id', 'Name'])
9f15aa5fb72716e0e398554caabafb972261e5ca
5,671
import requests def shutdown_check_handler(): """This checks the AWS instance data URL to see if there's a pending shutdown for the instance. This is useful for AWS spot instances. If there is a pending shutdown posted to the instance data URL, we'll use the result of this function break out of t...
dd5a7c3b3ab856d72afe01a19b2389071c4e70f3
5,672
def cal_d(date=cal_date.today(), zf=True): """ Month, optionally left-padded with zeroes (default: pad) """ day_num = "d" if zf else "-d" # optionally zero fill return date.strftime(f"%{day_num}")
c0501449035c10f3c4b05a8f9088b30d5789f662
5,673
from typing import Mapping from typing import Sequence from typing import Tuple def get_max_total(map_of_maps: Mapping[Sequence[str], Mapping[Tuple, float]]) -> float: """ >>> df = get_sample_df() >>> get_max_total(calculate_kls_for_attackers(df, [1])) 1.3861419037664793 >>> get_max_total(calculat...
6480676c3960e36e434dd8b229ddbd840fbcaa7a
5,674
import requests def get_keeper_token(host: str, username: str, password: str) -> str: """Get a temporary auth token from LTD Keeper. Parameters ---------- host : `str` Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``). username : `str` Username. password :...
4c1feb095b3409786c5bac62aed41939f31a1431
5,675
import json def edit_comment(post_id, comment_id): """Edit a comment from a specific post""" post = posts.get(post_id) if not post: return json.dumps({"error": "Post Not Found"}), 404 comments = post["comments"] comment = comments.get(comment_id) if not comment: return json.d...
dba79ed0bbdbc48b804a5a9f446c289f47606a75
5,676
def update_transition_dirichlet( pB, B, actions, qs, qs_prev, lr=1.0, return_numpy=True, factors="all" ): """ Update Dirichlet parameters that parameterize the transition model of the generative model (describing the probabilistic mapping between hidden states over time). Parameters ----------...
3b41320f20abee2cec4cfa651d932a388c4595c2
5,677
def MRP2Euler231(q): """ MRP2Euler231(Q) E = MRP2Euler231(Q) translates the MRP vector Q into the (2-3-1) euler angle vector E. """ return EP2Euler231(MRP2EP(q))
09929b4858eb0f8a755b623fa86b6d77333e9f6b
5,678
def _convert_from_node_attribute( G, attr_name, node_types, node_type_name=None, node_type_default=None, dtype="f" ): """ Transform the node attributes to feature vectors, for use with machine learning models. Each node is assumed to have a numeric array stored in the attribute_name and which is su...
1c1ae2ab8d1a3da31829ee48ee4017fb45ca73b0
5,679
import argparse import socket from pathlib import Path import requests def handle_args(parser: argparse.ArgumentParser, section: Text) -> argparse.Namespace: """ Verify default arguments """ hostname = socket.gethostname() hostname_short = socket.gethostname().split(".")[0] host_config_name = f"{CON...
a150360799879f1fae56a94936d87473378d6f37
5,680
def get_entry_or_none(base: dict, target, var_type=None): """Helper function that returns an entry or None if key is missing. :param base: dictionary to query. :param target: target key. :param var_type: Type of variable this is supposed to be (for casting). :return: entry or None. """ if ...
b3855be0c7d2c3bdd42e57ae959bb97409abe828
5,681
def group_list(request): """ List all gourps, or create a new group. """ if request.method == 'GET': tasks = Group.objects.all() serializer = GroupSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': unique_name = request.data....
39e3d67aa88008541898aea2d21d5a811ec17699
5,682
def CreateBooleanSplit(meshesToSplit, meshSplitters, multiple=False): """ Splits a set of meshes with another set. Args: meshesToSplit (IEnumerable<Mesh>): A list, an array, or any enumerable set of meshes to be split. If this is null, None will be returned. meshSplitters (IEnumerable<Mesh>...
56f8956b9cce7bd9467ac23b80a7573a889c05bf
5,683
def template14(): """Simple ML workflow""" script = """ ## (Enter,datasets) << host = chemml << function = load_cep_homo >> smiles 0 >> homo 4 ## (Store,file) << host = chemml ...
d321d2016f0894d0a0538a09f6bc17f3f690317b
5,684
def get_group_selector(*args): """ get_group_selector(grpsel) -> sel_t Get common selector for a group of segments. @param grpsel: selector of group segment (C++: sel_t) @return: common selector of the group or 'grpsel' if no such group is found """ return _ida_segment.get_group_selector(*...
6b750702186d70f2b21b64c13145d8da7bfd0b9c
5,685
import textwrap def wrap(text=cert_text) -> str: """Wraps the given text using '\n' to fit the desired width.""" wrapped_text = textwrap.fill(text, fit_char()) return wrapped_text
a6e42a7ca8fa78e7be89e31a920e8b3baa95245e
5,686
def encode(data): """calls simplejson's encoding stuff with our needs""" return simplejson.dumps( data, cls=CahootsEncoder, ensure_ascii=False, encoding='utf8', indent=4 )
d3577e87b830b17222614d978d78eaa8329843bd
5,687
def SE_HRNet_W48_C(pretrained=False, use_ssld=False, **kwargs): """ SE_HRNet_W48_C Args: pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. If str, means the path of the pretrained model. use_ssld: bool=False. Whether using distillatio...
0204ff852a18e6319c0454c5fd81d748626fcf78
5,688
from typing import Union from typing import Any from typing import List def manifest(argument: Union[Any, List[Any]], data: bytearray) -> Union[Any, List[Any]]: """ Returns the manifestation of a `refinery.lib.argformats.LazyEvaluation` on the given data. This function can change the data. """ if ...
b8c5335494fda972c09a6d1937344783fb91ea80
5,689
def get_child_hwnd_by_class(hwnd: int, window_class: str) -> int: """Enumerates the child windows that belong to the specified parent window by passing the handle to each child window. :param hwnd: HWND in decimal :param window_class: window class name :return: window handle (HWND) """ def...
0d6b7cb56b483c88305611520e9787ed4321b6ac
5,690
def uniq(lst): """ this is like list(set(lst)) except that it gets around unhashability by stringifying everything. If str(a) == str(b) then this will get rid of one of them. """ seen = {} result = [] for item in lst: if str(item) not in seen: result.append(item) ...
706ec44f340fbfca36cb1a605391e9fc32d38ca0
5,691
def as_datetime(dct): """Decode datetime objects in data responses while decoding json.""" try: type, val = dct['__jsonclass__'] if type == 'datetime': # trac doesn't specify an offset for its timestamps, assume UTC return dateparse(val).astimezone(utc) except KeyErro...
858f3229ea8b14797a0ed1c4f45159881eb08fe4
5,692
def is_open(state: int) -> bool: """Return whether a given position (x, y) is open.""" return state == states_id.OPEN
b5f056929a5ffed8dea8167402a652b01e2b3202
5,693
import xmpp def sendJabber(sender, password, receivers, body, senderDomain=NOTIFY_IM_DOMAIN_SENDER, receiverDomain=NOTIFY_IM_DOMAIN_RECEIVER): """ Sends an instant message to the inputted receivers from the given user. The senderD...
b38865b6414f3d4d88f65c49b3601000b9cee20a
5,694
def directory_log_summary(config): """ Summarise the input and out diretories and key information as text log from matsim config When submitting jobs via the Bitsim Orchestration """ message = [] # add the date message.append(f"Date:{date.today()}") # add paths of the input files me...
47708958817b22f92f685ba380bf388b352a563d
5,695
import json def search(): """ Searches for users with their name. Excludes the logged in user. """ data = json.loads(request.data) search_term = data['search_term'] this_user = interface.get_user_by_id(get_jwt_identity()) users = interface.search_users(search_term) result = [user.ge...
954288d19f29bbad7182f6b23e5c62b0e75df602
5,696
def get_optics_mode(optics_mode, energy=energy): """Return magnet strengths of a given opics mode.""" if optics_mode == 'M0': # 2019-08-01 Murilo # tunes fitted to [19.20433 7.31417] for new dipoles segmented model qf_high_en = 1.65458216649285 qd_high_en = -0.11276026973021 ...
6a62bcaad3a6aa4a06d44072258aa09116c07107
5,697
import os from datetime import datetime def load_stock_order(): """加载csv文件,导入并备份为 [.yyyy-mm-dd HH_MM_SS.bak 结尾的文件""" base_dir = './auto_order_dir' file_name_list = os.listdir(base_dir) if file_name_list is None: log.info('No file') data_df = None for file_name in file_name_list: ...
cb7472d2f403bf7f845c2b9af85f7181bf778563
5,698
from typing import Dict def _get_last_block_in_previous_epoch( constants: ConsensusConstants, sub_height_to_hash: Dict[uint32, bytes32], sub_blocks: Dict[bytes32, SubBlockRecord], prev_sb: SubBlockRecord, ) -> SubBlockRecord: """ Retrieves the last block (not sub-block) in the previous epoch, ...
63742082b6cfb65c5683a0047531b039d3841219
5,699