content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import inspect def is_mass_profile_class(cls): """ Parameters ---------- cls Some object Returns ------- bool: is_mass_profile_class True if cls is a class that inherits from mass profile """ return inspect.isclass(cls) and issubclass(cls, mass_profiles.MassProfile...
d27423ff46d0e548b6cccce3d7f0389ba40c48a0
3,615,700
def superuser_required_or_403(): """ Decorator to make a view only accessible as a superuser or it will raise PermissionDenied. Usage:: @superuser_required_or_403() def a_view(request): # I can assume now that the view is only accessible as a superuser. """ def deco...
ff949d00a987c66b197bc4b16ce682fe1392e74c
3,615,701
def pullback(b, c, d, b_d, c_d, inplace=False): """Find the pullback from b -> d <- c. Given h1 : B -> D; h2 : C -> D returns A, rh1, rh2 with rh1 : A -> B; rh2 : A -> C and A the pullback. """ if inplace is True: a = b else: a = type(b)() # Check homomorphisms check_ho...
d27bcded897f9f2b26bda7b9b5434eb4bcfa59b9
3,615,702
def corr_therm2_sp(omega, x, y, disp=True): """Remove the thermal component in an OMEGA spectrum, with simultaneous retriving of reflectance and temperature. Parameters ========== omega : OMEGAdata The OMEGA observation data. x : int The x-coordinate of the pixel. y : int ...
e097c500274ee6b93a76761a8b39b95f776f2a38
3,615,703
def amplitude_rate_modulation(y, sr, difficulty): """This function uses the average amplitude (i.e., 'loudness') of a beat and the difficulty level to determine how many blocks will be placed within the beat. Returns a list of beat numbers.""" #Make amplitude matrix D = np.abs(librosa.stft(y)) db =...
fc41a59de2f8b2d425ae99350ed22c93cbefb3f6
3,615,704
def _raise_missing_if_result_is_none(function): """ Raise MissingAccountData if function's result is None. adapted from https://github.com/Backblaze/b2-sdk-python/blob/v1.5.0/b2sdk/account_info/in_memory.py """ @wraps(function) def getter_function(*args, **kwargs): assert function.__nam...
97f00a0e1d3038b3d8efb324d9d1e666bcb0122f
3,615,705
def nb_pixels(info_dict): """ Compute the number of pixels affected by the target light Parameters ---------- info_dict: dictionnary wavelength: float wavelength in angstrom Returns -------- npix: float number of pixels affected by the target light (ceiled) ...
b2afabad96183031bb5bba80b030adffeb15fac6
3,615,706
from typing import Optional from typing import Dict from typing import Any def get_rnn_layer(reservoir_weight: Optional[np.ndarray] = None, reservoir_params: Optional[Dict[str, Any]] = None, layer_name: str = "LSTM", units: int = 200, return_sequ...
fb8b4cb891fd3481413ff1ac9d86104412f4c0cf
3,615,707
def generate_regenet_arch(initial_width, width_slope, quantilize, width_m, depth, bottleneck_ratio, group_width): """ Inspired by the observation from AnyNetXd and AnyNetXe """ assert width_m > 0, 'width_m must be greater than 0' # Generate block widths and depths via Eq.2 ~ Eq.4 in the paper w...
2a17f308e972a810c1bfbcbd06e937faf9572841
3,615,708
def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None, cycle=None, chan_full=None, epoch=None, epoch_dur=30, epoch_overlap=0, epoch_step=None, reject_epoch=False, reject_artf=False, min_dur=0, buffer=0): """Create instance of Segments for analysis, complete with info ab...
b52886e2f297a304b5289964a3ea40bff104e567
3,615,709
def polar(a, side="right", compute_p=False): """ Compute the polar decomposition. This is a transcription of the SciPy code - check scipy.linalg.polar for documentation. """ if side not in ['right', 'left']: raise ValueError("must be either 'right' or 'left'") a = np.asarray(a) if a...
cb9cda7922c89e2424cc959a3cde96b55daf62aa
3,615,710
def replace_file_type(file_name, new_type): """ :param file_name: :param new_type: :return: """ file_name_parts = file_name.split(".") return file_name.replace(file_name_parts[len(file_name_parts)-1], new_type)
c6fd9e01befb0e6f1a96f8884fc9d00332741948
3,615,711
from typing import OrderedDict def _text_to_df(text_file, encoding=None): """ Convert a raw E-Prime output text file into a pandas DataFrame. """ # Load the text file as a list. if encoding is None: with open(text_file, 'rb') as fo: text_data = list(fo) # Remove unico...
b3b702c4913978fec5ea15e18c7a63bb525cdf3f
3,615,712
def findmatch1(x, xsearch, tol=1e-4): """RETURNS THE INDEX OF x WHERE xsearch IS FOUND""" i = argmin(abs(x - xsearch)) if tol: if abs(x[i] - xsearch) > tol: print(xsearch, 'NOT FOUND IN findmatch1') i = -1 return i
a3de2eb758d1958bad2baf9dc6cb5128da13418a
3,615,713
import cProfile def profile(func): """Decorator for run function profile""" def wrapper(*args, **kwargs): global i profile_filename = 'profile/' + func.__name__ + '%06d' % i + '.prof' i += 1 profiler = cProfile.Profile() result = profiler.runcall(func, *args, **kwargs) ...
5135f5c7275ba0997bc60a6fc262b841c849f86a
3,615,714
import functools def nonced(method): """ Decorates a handler to only accept requests with nonce header. If the request is missing the request handler we set the status as 400 with a malformed message. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): if self.nonce_servic...
1cfdd6966fdd7986b0ee85a927a6f7f6acbcfdf7
3,615,715
def userToJson(user): """Returns a serializable User dict :param user: User to get info for :type user: User :returns: dict """ obj = { "id": user.id, "username": user.username, "name": user.get_full_name(), "email": user.email, } return obj
da5e11bbc2e8cbdffb25e32e6a47e0ccabe8d33a
3,615,716
def create_checkbox_group(names, kind, button_dict): """Creates a dictionary containing all checkboxes for set selection and a group widget containing all of them for display.""" box_dict = {} if kind == "Sets": names = [set_ for set_ in names if set_ not in ["Intrigue", "Base"]] tooltip...
fa1c5023bd9dde06ad219f58ffecabe9327c7aa6
3,615,717
import ssl import json import sys def cmr_search(short_name, version, time_start, time_end, bounding_box='', polygon='', filename_filter='', quiet=False): """Perform a scrolling CMR query for files matching input criteria.""" cmr_query_url = build_cmr_query_url(short_name=short_name, version=ve...
bb3f8d6b465b8635b762ad9fe568284807657658
3,615,718
from typing import DefaultDict from typing import Set def dijkstra(source: OrientedWay) -> SingleSourceMap: """Dijkstra algorithm.""" info: DefaultDict[OrientedWay, _NodeInfo] node: OrientedWay visited: Set[OrientedWay] queue = FibonacciHeap() visited = set() source_info = _NodeInfo(0.0) ...
e3bccad8885165ca90c515846b1d57d9f0f361bc
3,615,719
def gcv(data, channels=None): """ Calculate the geometric CV of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or...
d1e3caa02705114b2c86bca0cbb10b9f3a8dfe0f
3,615,720
def compute_fail_probability(rankings, mtable): """ This computes experimentally how many of the M rankings fail to satisfy the mtable :param rankings: rankings that are checked (list of lists of FairScoreDoc) :param mtable: an mtable to check against (list of int) :return: the ra...
1bcfd13477918625fa0c50c88f3e98713cddb237
3,615,721
def copy_group(source_globals_file, source_groupname, dest_globals_file, delete_source_group=False): """ This function copies the group source_groupname from source_globals_file to dest_globals_file and renames the new group so that there is no name collision. If delete_source_group is False the cop...
765b2e6926327c75d647181b66deb5911770ce1c
3,615,722
def build_client(username=None): """Build a Spotipy client scoped for use.""" username = get_username(username) auth = util.prompt_for_user_token( username, scope='playlist-modify-private playlist-modify-public', ) return spotipy.Spotify(auth=auth)
6c941033034a36e54e05ae01118446078efdb0de
3,615,723
import os import json import requests def do_declare(): """Makes a f5-declarative-onboarding declaration from the generated file""" if is_rest_worker('/mgmt/shared/declarative-onboarding') and \ os.path.isfile(DO_DECLARATION_FILE): dec_file = open(DO_DECLARATION_FILE, 'r') declarat...
c5f0b9b0542f0282df615d4523a793c9898d92d3
3,615,724
from typing import Callable from typing import Any from typing import Tuple from typing import Dict def write_score(func: Callable[[Any, Any], Any]) -> (Tuple[Any, ...], Dict[str, Any]): """ Save the store data of the decorated function in a file. :param func: a function :precondition: input paramete...
a37ed83f6fc0c2da21ad043fe5855b16478b6d6c
3,615,725
from datetime import datetime def get_places_around_centroid(point, radius, place_type): """ Find places of place_type within a radius around a centroid and add to database. :param point: the centroid, of type Point :param radius: radius (in metres) :param place_type: type of place to be searc...
6f175269838776c854777c80f4d3e8e59081258f
3,615,726
import sys def safe_import(path, default=None): """Import a given path as efficiently as possible and without failure.""" module = sys.modules.get(path, default) for exclude_name in IGNORE_MODULES: if path.startswith(exclude_name): return default if module is default and __import_u...
40232f466970db410ed4836724490610ed2be713
3,615,727
def remove_indices_from_dict(obj): """ Removes indices from a obj dict. """ if not isinstance(obj, dict): raise ValueError(u"Expecting a dict, found: {}".format(type(obj))) result = {} for key, val in obj.items(): bracket_index = key.find('[') key = key[:bracket_index] i...
60842ed62b2d79852661f83699bf3bf92b63084a
3,615,728
def relative_uri(base, to): """Return a relative URL from ``base`` to ``to``.""" if to.startswith(SEP): return to b2 = base.split(SEP) t2 = to.split(SEP) # remove common segments (except the last segment) for x, y in zip(b2[:-1], t2[:-1]): if x != y: break b2....
fb94a8c1e2b4fc383db26657301e8fed0988562c
3,615,729
import sys def MatrixChainMultiplicationDp(array, n): """ n is length of array """ dp = [[None for _ in range(n + 1)] for _ in range(n + 1)] for i in range(n + 1): for j in range(n + 1): if i == j: dp[i][j] = 0 else: dp[i][j] = sys.maxsize ...
327a35e33e1d0ae41a72173a6d773495cbf7f284
3,615,730
def find_block(csv, name): """For an Illumina SampleSheet.csv, return a tuple of the index of the line containing the header specified by name, and the index of the line just past the end of the data block. `range(*r)` will index all lines for the block, starting at the header line. """ start = ...
7a1fc119e6e3e889d9a18884028cb2e6a67e0cd5
3,615,731
def ootf_reverse_BT2100_HLG(F_D, L_B=0, L_W=1000, gamma=None): """ Defines *Recommendation ITU-R BT.2100* *Reference HLG* reverse opto-optical transfer function (OOTF / OOCF). Parameters ---------- F_D : numeric or array_like :math:`F_D` is the luminance of a displayed linear component ...
2d8d0430107c131db9f5a1974d897f15401c7391
3,615,732
def cancel_and_stop_intent_handler(handler_input): """Single handler for Cancel and Stop Intent.""" # type: (HandlerInput) -> Response speech_text = "Alla prossima!" return handler_input.response_builder.speak(speech_text).response
73a9171b5ea01fedb7fc470dd7d6bcd232a605a0
3,615,733
from typing import Union def make_twill_pattern(n:Union[int, tuple[int]] = 2, warp_n:int = 2, weft_n:int = 2) -> np.ndarray: """Returns twill pattern matrix extended for warp and weft patterns. n is the number of over-unders. With n = 1 we get a plain weave. Args: n (int,...
02d080765dfe5577df278c16d04bea34c26f0f00
3,615,734
import operator def assert_no_undefined_references( snapshot=None, soft=False, session=None, df_format="table" ): # type: (Optional[str], bool, Optional[Session], str) -> bool """Assert that there are no undefined references present in the snapshot. :param snapshot: the snapshot on which to check the...
0409b5b814dcfba73779173b279d4c02d5b66e2c
3,615,735
from typing import List def divisors(number: int) -> List[int]: """ This function calculates and returns a list of all divisors that a given number has, e.g. f(number=24) -> [1, 2, 3, 4, 6, 8, 12, 24] :param number: The number whose divisors are to be calculated :return: A list of integer divisors...
1683734989447f40a72f08098e9f08ef62a1cd32
3,615,736
def sim_sym_resp(emotion, ti, tf, t_plot=None, dt=0.1, plot=True, n_periods=1, d_e=None, delay=0.0): """ :param emotion : string that define what emotion is simulated :param ti : time in seconds when eigenmotion starts :param dt : time step in seconds for the simulation ...
b9a29dd89114b3b1ef76ced7680bbbc57724a26c
3,615,737
def timestamp_from_sbs(data): """Create new timestamp from SBS data Args: data (hat.sbs.Data): SBS data Returns: Timestamp: timestamp """ return Timestamp(s=data['s'], us=data['us'])
f42d70886f7eaec64fae6f5787c9b7c8177e86f3
3,615,738
from ostap.math.integral import integral as _integral_ def _h1_cmp_costheta_ ( h1 , h2 , density = False ) : """Compare the 1D-historgams (as functions) Calculate the scalar product and get ``cos(theta)'' from it >>> h1 = ......
ffe1f465dbc123a0cc9ee8d9db06e122b9a2ef23
3,615,739
def buff_exists(name): """ Return true or false if the buffer named `name` exists """ return buffwinnr(name) != -1
5883d97b8c62ce762bc0cd1777264b5d0c921660
3,615,740
import json def load_jsonl(filename): """Load json lines formatted file""" with open(filename, "r") as f: return list(map(json.loads, f))
7acb3513cf885139e62af56d17c19aa87e1c85ca
3,615,741
def IntCurveSurface_TheHCurveTool_FirstParameter(*args): """ :param C: :type C: Handle_Adaptor3d_HCurve & :rtype: float """ return _IntCurveSurface.IntCurveSurface_TheHCurveTool_FirstParameter(*args)
c895ee73b149ebab1d696f88eb3c19f3bebd5dd4
3,615,742
import binascii import os def _get_ecc608_certificate_template_file(ecc_serial_number, cert_type): """ Retrieves a template (/example) ECC608 certificate based :param ecc_serial_number: Serial number of ECC :type ecc_serial_number: binary :param cert_type: Type of certificate ('device' or 'signer...
2cedfb8d489173fa3cfacc269c59123100019dcc
3,615,743
def synthesize_text(text, client): """Synthesizes speech from the input string of text.""" # input format input_text = texttospeech.types.SynthesisInput(text=text) # Note: the voice can also be specified by name. # Names of voices can be retrieved with client.list_voices(). voice = texttospeech.types.Voic...
c2d01c5dfc5bf3ac8e2eef5501bdd38370cdce3f
3,615,744
def plotPotentialObjectToFile(fileobj, lowx, highx, potentialObject, steps=10000): """Convenience function for plotting energy of pair interactions given by instances of :class:`atsim.potentials.Potential` obtained by calling `potential` `.energy()` method. Data is written to a text file as two columns (r and ...
f8ebf6eeae65036017b6114fb5e5aeda8d6ca1b4
3,615,745
def get_test_clinvar_record(): """The test file contains an extract of ClinVar XML for the record RCV000002127.""" return [r for r in clinvar_xml_utils.ClinVarDataset(test_clinvar_record_file)][0]
fe4073ed03af58c0558309393fdd373eadf74360
3,615,746
import random def random_genbank_accession(invalid_data): """ Generate Random GenBank Accession return: string formatted to imitate a GenBank submission accession for viral genome assemlby. """ # prefixs for GenBank direct submissions, excluding single letter 'U' option. prefix = ['AF', 'AY'...
c9bd639e1ef3b10749a0c1c0e8ca3c4cb53c079f
3,615,747
def entropy(p): """Calculate the Entropy for a sample :param p: The probability or proportion of the samples belonging to a class :returns: The Entropy :rtype: float """ return -p * np.log2(p) - (1 - p) * np.log2(1 - p)
b3fd9f442aa30d40e49bbcfeb8f1403644ab2185
3,615,748
import sys def get_rexpro(stype='sync'): """ Obtain the RexPro Socket, Connection and Connection Pool classes for the desired application Options include: - 'sync' - Default, Synchronous python sockets - 'gevent' - with gevent concurrency - 'eventlet' - with eventlet concurrency Exampl...
d260bad95290886b89df1783e060c48b5364047b
3,615,749
def to_xml(number): """Return the XML form of the ISAN as a string.""" number = format(number, strip_check_digits=True, add_check_digits=False) return '<ISAN root="%s" episode="%s" version="%s" />' % ( number[0:14], number[15:19], number[20:])
0c4311d78365d98760b6550b4a1c3eba8d0d6b6c
3,615,750
from typing import Set def extract_requirements(func) -> Set[str]: """TODO: extract PyPI name instead""" res = list() clean_namespace = loads(dumps(func)).__globals__ for obj in clean_namespace.values(): pkg = getpackage(obj) if pkg is not None: pkg_name = pkg.__name__ ...
efcba79793f78a73e237432cf7f260075236290a
3,615,751
def dict_findall(dictionary, element): """ Returns the keys whose values in `dictionary` are `element` or, if none exists, []. >>> d = {1:4, 3:4} >>> dictfindall(d, 4) [1, 3] >>> dictfindall(d, 5) [] """ res = [] for (key, value) in dictionary.iterite...
76d1e0aa73db87da57b3d1129dca0984ff81574f
3,615,752
def set_union(a, b, validate_indices=True): """Compute set union of elements in last dimension of `a` and `b`. All but the last dimension of `a` and `b` must match. Example: ```python import tensorflow as tf import collections # [[{1, 2}, {3}], [{4}, {5, 6}]] a = collections.OrderedDict([ ...
0bee3df212c835d54727a664a34ad0dba78f5977
3,615,753
from operator import eq from typing import Sequence def eq_assoc_args( op, a_args, b_args, n=None, inner_eq=eq, no_ident=False, null_type=etuple ): """Create a goal that applies associative unification to an operator and two sets of arguments. This is a non-relational utility goal. It does assumes that ...
1a72d3a7291cf9fa9bb12e7a4ffda8a833bde1ea
3,615,754
def account_edit(request, pk=None): """ """ return edit( request, report_model=Report, form_model=AccountForm, model=Account, pk=pk )
7b6c2fbbda39242c70c694d27c1abbe432362d12
3,615,755
def oauth2_assertion_config(application_id, application_name, client_string, consumer_key, consumer_secret): """Convenience function for creating an OAuth2 assertion configuration. :param application_id: The unique identifier of the client application...
eed76d2d957b701db0ebce1141de5d0f411c692d
3,615,756
def drop_invalid_trip_durations(data_frame: pd.DataFrame) -> pd.DataFrame: """Remove rows where we couldn't calculate trip duration or it was over 90 minutes.""" data_frame = data_frame.dropna(subset=['trip_duration_minutes']) data_frame = data_frame[data_frame['trip_duration_minutes'] <= 90] return da...
9d60812ba6805571b636d99a843c2c2db2b78fb9
3,615,757
import time import requests from bs4 import BeautifulSoup def epidemic_163(indicator="实时"): """ 网易网页端-新冠状病毒-实时人数统计情况 国内和海外 https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other&#map_block https://news.163.com/special/epidemic/?spssid=93326430940df93a37229...
576615a8e3d0b3bf79cf82babec4c8710e2d11b2
3,615,758
def getPartnerURL(request): """ 파트너 포인트 충전 URL을 반환합니다. - 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다. - https://docs.popbill.com/htcashbill/python/api#GetPartnerURL """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # CHRG-파트너 포인트충전 TOGO = "CHRG" url = htCashbil...
86afa367e4950a7d864763138f2bde1456145bd6
3,615,759
from typing import List def _read_get_graph_source_citation_section(jcamp_dict: dict) -> List[str]: """ Extract and translate from the JCAMP-DX dictionary the SciData JSON-LD citations in the 'sources' section from the '@graph' scection. :param jcamp_dict: JCAMP-DX dictionary to extract citations fro...
dafe4fd793dd0e47b690d6c1fd745ca89265de39
3,615,760
def set_link_state(): """ Set link state :return: 201 if success, a new pending link if fail """ message = request.get_json() if message['state'] == 'crawled': db_manager.operate_on_link_relation('UPDATE_STATE', message['link'], ...
e1de294334de3447cb59b6332e29bb2f7c523491
3,615,761
def print_stdout(): """ whether or not to print to stdout """ return _flag(PRINT_STDOUT_KEY, 'print_stdout', 'p', msgs=('print log to stdout as well?',))
1697caccd978b344c08542002f12ffab98f65c9e
3,615,762
def read_input_lines(): """Open today's input data and return it as a list of lines Returns: [str] Lines in 'input.txt' """ with open('input.txt') as in_file: data = in_file.read().strip().splitlines() return data
83b77f1b64162bc822c9890781bf758e7197c67e
3,615,763
import opcode def payToPubKeyHashScript(pkHash): """ payToAddrScript creates a new script to pay a transaction output to a the specified address. Args: pkHash (ByteArray): The pubkey hash to pay to. Returns: ByteArray: The script that pays to the pubkey hash. """ if len(p...
51786cfc238470d9a69389ffe7c08589896d00c6
3,615,764
def deltaify_traces(traces, final_byte_duration=9999): """Convert absolute start times in traces to durations. Traces returned by `read_traces_csv` pair bytes with start times. This function computes how long each byte remains on the bus and replaces the start time with this value in its output. Note that the ...
8185a9825d4706bdf8a579fcefec5e27ca8c3baa
3,615,765
def lonely_pixel(pixs, pos): """ pixs: image.load() pos: (x,y) """ x,y = pos xy = [-1,0,1] for i in xy: for j in xy: if i==0 and j==0: continue # pixel self try: p = pixs[x+i,y+j] except IndexError: ...
7ddb9bde813e532412d2b4e47d9b61a04569410c
3,615,766
import logging def embedding_lookup_sparse(params, sp_ids, sp_weights, partition_strategy="mod", name=None, combiner=None, max_norm=None): """Comput...
9ff746fe0ab6525e4e3764eefba0e5fe38c5719a
3,615,767
def parse_ldap_file(file_name, entries=None): """ parse the LDAP results into a coherent form (this code is way too complex for what it needs to do ATM) """ f = open(file_name) entries = defaultdict(list) if entries is None else entries entry = {} for line in f: line = line.strip() if line !=...
4a7a3e324c8934dc2c954e3727047c13be79efb1
3,615,768
def load(cookie: str) -> domain.Session: """Load a session by cookie value.""" return current_session().load(cookie)
a58f07c27451c8b548479fea8566e230fae11858
3,615,769
def trnsdeq_iter(h,T): """ Given """ new_h = _np.array([[[trnsdeq_step(h,T,i,j,k) for k in range(h.shape[2])] for j in (range(h.shape[1]))] for i in _tqdm(range(h.shape[0]))]) return new_h/_np.sum(new_h)
509ae4cc7fd300bc47d9697de2a0e6ba7d91239d
3,615,770
def coor2coor(srs_from, srs_to, x, y): """ Transform coordinates from srs_from to srs_to input: srs_from and srs_to are EPSG number (e.g., 4326, 3031) x and y are x-coord and y-coord corresponding to srs_from return: x-coord and y-coord in srs_to """ srs_from = pypro...
e8f03e53078b987b874c5f4901d55b75297b4c28
3,615,771
def rzpad(value, total_length): """ Right zero pad value `x` at least to length `l`. """ return value + b"\x00" * max(0, total_length - len(value))
76a0884e9f8a65e0ff3efac56223dfa2fbed31b4
3,615,772
import unittest def getTestSuite(): """ set up composite test suite """ test_suite = unittest.TestSuite([]) test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestAzureP2P)) #test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestDocStrings)) return test_suit...
a76c925cf6bd99981f7979af85864b99d2a95dcd
3,615,773
import os def read_cube(infile, allow_huge=True): """ Read cube from CASA image file. Includes a switch for large cubes, where getchunk may fail. """ if allow_huge: casaStuff.exportfits(imagename=infile, fitsimage=infile + '.fits', sto...
368faa3e628d743d9432d7a6aae79b2f20ba7479
3,615,774
def visual_map(visual_type='color', visual_range=None, visual_text_color=None, visual_range_text=None, visual_range_color=None, visual_range_size=None, visual_orient='vertical', visual_pos="left", vis...
8e812b50fab992efecaabc8fd5430eb409a4e679
3,615,775
def calc_precision_recall(img_results): """Calculates precision and recall from the set of images Args: img_results (dict): dictionary formatted like: { 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int}, 'img_id2': ... ... ...
b6946bcc83c2c16d91b4413c0d551d421ae2b252
3,615,776
def compose(*funcs): """Returns a function that is the composition of multiple functions.""" def wrapper(x): for func in reversed(funcs): x = func(x) return x return wrapper
d93d59f2f1979fa35638357fcac5130710e0fda3
3,615,777
def svm_model(C=10**1.5, gamma='scale', kernel='rbf'): """SVM""" return svm.SVC(kernel=kernel, gamma=gamma, C=C, probability=True)
19886c1025471dcfceeb829861b44b687cafecc3
3,615,778
def fmgr_set_ha_mode(fmgr, paramgram): """ :param fmgr: The fmgr object instance from fortimanager.py :type fmgr: class object :param paramgram: The formatted dictionary of options to process :type paramgram: dict :return: The response from the FortiManager :rtype: dict """ # INIT A ...
4b7980d1f7fa9f1e2632eac09335a7a2bda33d26
3,615,779
def cinder_client(os_creds): """ Creates and returns a cinder client object :return: the cinder client """ return Client(version=os_creds.volume_api_version, session=keystone_utils.keystone_session(os_creds), region_name=os_creds.region_name)
3b46c0222d9fd8fca6cf2cd4d50df75e5021d849
3,615,780
from functools import reduce def compose(*functions): """ Compose all the function arguments together :param functions: Functions to compose :return: Single composed function """ # pylint: disable=undefined-variable return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
d69ab8953d8e846fffd50aa9c0925935e38e9e38
3,615,781
import os import torch def load(opt): """Select checkpoint to load.""" ckpt = opt.epochNum if ckpt == 0: print("".ljust(4) + "=> No checkpoint to load. Retrain the model.") return None else: if ckpt == -1: print("".ljust(4) + "=> Loading the latest checkpoint.") ...
79b37fb0327468726b54f9a9574561a0a2b118f2
3,615,782
def mul_fft(f_fft, g_fft): """Multiplication of two polynomials (coefficient representation).""" deg = len(f_fft) return [f_fft[i] * g_fft[i] for i in range(deg)]
67db62dc812827b6aa7c7406a068ae9e47f97a65
3,615,783
import struct import os import io def read_info(options): """Load affine transforms and space info of other volumes""" def read_file(fname): o = struct.FileWithInfo() o.fname = fname o.dir = os.path.dirname(fname) or '.' o.base = os.path.basename(fname) o.base, o.ext =...
2e54807fcaecbb8c63435989e39d1c8236114475
3,615,784
def atr_cache_nb(high_ts, low_ts, close_ts, windows, ewms, adjust): """Caching function for `vectorbt.indicators.basic.ATR`.""" # Calculate TR here instead of re-calculating it for each param in atr_apply_nb tr = true_range_nb(high_ts, low_ts, close_ts) cache_dict = dict() for i in range(len(windows...
9937dff358a3f7dc38608e333e3a5c4686ddaf1e
3,615,785
import torch def custom_decode_labels(mask, num_images=1, num_classes=20): """Decode batch of segmentation masks. Args: mask: result of inference after taking argmax. num_images: number of images to decode from the batch. num_classes: number of classes to predict (including background). ...
d4b7d7a95872b3d541b8f011004ae198f0cb508d
3,615,786
from datetime import datetime def populate_runtime_info_for_random_queries( impala, use_kerberos, candidate_queries, query_count, query_timeout_secs, results_dir ): """Returns a list of random queries. Each query will also have its runtime info populated. The runtime info population also serves to validate th...
0d5de1a5013bcfb0e4977b65e205ad5cce07db3e
3,615,787
import re def clean_text(text): """ Cleans abstract text from scopus documents. Args: text (str): Unformatted abstract text. Returns: (str) Abstract text with formatting issues removed. """ if text is None: return None try: cleaned_text = re.sub("© ([0-9])\w*...
7ffbf3a6ebe0c0caac203cea109e939b5c861724
3,615,788
def web_context(req, resource=None, id=False, version=False, parent=False, absurls=False): """Create a rendering context from a request. The `perm` and `href` properties of the context will be initialized from the corresponding properties of the request object. >>> from trac.test impor...
28ac532e37f14fcc84a4daf4372aa496763453bf
3,615,789
def a_vs_b(ship_a, ship_b, trials, attack_range): """This uses a random agent to choose actions during attacks from ship_a to ship_b. Args: ship_a ((Ship, str)): Attacker and hull zone tuple. ship_b ((Ship, str)): Defender and hull zone tuple. trials (int): Number of trials in average calcula...
7545a9b8626b5ab22ae49c22328f3a58fd64c072
3,615,790
def activity_index(windowed_array): """ Compute activity index of windowed tri-axis accelerometer signal. Activity index defined here as: sqrt(mean(vx, vy, vz)) where vx, vy, vz are the variances in x, y, z Activity index accounting for device specific systematic variance is def...
a5af2242f78760a6f343761522cb4e4ec3b1c274
3,615,791
def getPathToRoot(label): """ Returns all the nodes present in all the paths from node 'label' to root. """ path = [label] if len(labelDict[label]['parents'])==0: return path for item in labelDict[label]['parents']: path += getPathToRoot(item) return list(set(path))
7daf1374233504392791707ed5ae7bbde3d20fc5
3,615,792
def macAddress(value): """Return true if mac-address is valid, otherwise - false.""" return False
c7fbedf2975861ce7b8666f72ab497b640e9e611
3,615,793
def merge_channels(x): """ Takes a NxMx4 array and returns a 2Nx2M array by stacking the 4 2D images in a 2x2 grid. :param x: Input array :return: Output array """ return np.vstack((np.hstack((x[:, :, 0], x[:, :, 1])), np.hstack((x[:, :, 2], x[:, :, 3]))))
2cf9f661e1c9f6505e2f38215fd7a35e7e5e9cb2
3,615,794
def collect_inference_outputs(inference_output_uri): """ collect information related to output of inference. """ sagemaker_output_file = "unlabeled.manifest.out" prediction_output_uri = inference_output_uri + sagemaker_output_file prediction_output_s3 = S3Ref.from_uri(prediction_output_uri) ...
9de5aadea8df6757869112d161603ec095e6b9b4
3,615,795
def run_serial(the_config, compdb): """Executes a serial run, one command after another""" commands = compdb_parser.parse_compdb(compdb) facade_lib.apply_checkers_for_commands(commands, the_config) # TODO The global state of summary is hard to test return summary.get_summary()
621ab72ed765f85f08eb708f393235fd9b860ddb
3,615,796
def get_classname(hwnd): """ @return A empty string if failed. """ try: return win32gui.GetClassName(hwnd) except Exception: pass return ''
0a75a5b64b02a6ec99ab0364dbad85f8821b3bb1
3,615,797
def xrecons_single_sample(X, read_attn_params, write_attn_params, args): """ Create a single image containing the output canvas at each of the T time steps. Parameters: ----------- X : X is a batch of image canvases. (T, batch_size, H, W, C) read_attn_params: Tuple containing parameters needed to draw rea...
9db5415be21d456572c0f197562ebc573bc3e0d7
3,615,798
def nanprod(a, axis=None, dtype=None, out=None, keepdims=False): """Returns the product of an array along given axes treating Not a Numbers (NaNs) as zero. Args: a (cupy.ndarray): Array to take product. axis (int or sequence of ints): Axes along which the product is taken. dtype: Da...
863cfcfdc5c2123e4c7448782ee201ea6da3fdf7
3,615,799