language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings("deprecation") protected String getExpressionUrl(String expression) { String template = _config.getValue(Property.AUDIT_METRIC_URL_TEMPLATE.getName(), Property.AUDIT_METRIC_URL_TEMPLATE.getDefaultValue()); try { expression = URLEncoder.encode(expression, "UTF-8"); } catch (Exception ex) { ...
python
def equals(self, other): ''' Structural equality of models. Args: other (HasProps) : the other instance to compare to Returns: True, if properties are structurally equal, otherwise False ''' # NOTE: don't try to use this to implement __eq__. Because th...
java
@SuppressWarnings("unused") private void initalizeReferences(Collection<Bean> beans) { Map<BeanId, Bean> userProvided = BeanUtils.uniqueIndex(beans); for (Bean bean : beans) { for (String name : bean.getReferenceNames()) { List<BeanId> values = bean.getReference(name); ...
python
def block_view(self, mri): # type: (str) -> Block """Get a Block view from a Controller with given mri""" controller = self.get_controller(mri) block = controller.block_view() return block
python
def install_certs(ssl_dir, certs, chain=None, user='root', group='root'): """Install the certs passed into the ssl dir and append the chain if provided. :param ssl_dir: str Directory to create symlinks in :param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}} :param chain: str Chain to be appen...
python
def root_item_selected(self, item): """Root item has been selected: expanding it and collapsing others""" if self.show_all_files: return for root_item in self.get_top_level_items(): if root_item is item: self.expandItem(root_item) else: ...
python
def get_killer(args): """Returns a KillerBase instance subclassed based on the OS.""" if POSIX: log.debug('Platform: POSIX') from killer.killer_posix import KillerPosix return KillerPosix(config_path=args.config, debug=args.debug) elif WINDOWS: log.debug('Platform: Windows') ...
java
public void marshall(SetVaultNotificationsRequest setVaultNotificationsRequest, ProtocolMarshaller protocolMarshaller) { if (setVaultNotificationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
java
public static <T extends Comparable<T>> T lt(T value) { reportMatcher(new LessThan<T>(value)); return null; }
java
private Locale getLocale(String acceptLanguage) { if (acceptLanguage == null) { acceptLanguage = "fr"; } String[] langs = acceptLanguage.split(","); return Locale.forLanguageTag(langs[0].split("-")[0]); }
python
def get_name_record(self, name, include_expired=False, include_history=False): """ Get the whois-related info for a name (not a subdomain). Optionally include the history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ if not ...
java
public static boolean isInternationalPhoneNumber(String s) { if (isEmpty(s)) return defaultEmptyOK; String normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters); return isPositiveInteger(normalizedPhone); }
python
def _format_playlist_line(self, lineNum, pad, station): """ format playlist line so that if fills self.maxX """ line = "{0}. {1}".format(str(lineNum + self.startPos + 1).rjust(pad), station[0]) f_data = ' [{0}, {1}]'.format(station[2], station[1]) if version_info < (3, 0): if...
java
public Observable<Page<DenyAssignmentInner>> listForResourceNextAsync(final String nextPageLink) { return listForResourceNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<DenyAssignmentInner>>, Page<DenyAssignmentInner>>() { @Override publ...
python
def assign_floating_ip(self, ip_addr, droplet_id): """ Assigns a Floating IP to a Droplet. """ if self.api_version == 2: params = {'type': 'assign','droplet_id': droplet_id} json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST'...
java
@Override public SparseTensor elementwiseProduct(Tensor other) { int[] dimensionNums = getDimensionNumbers(); int[] dimensionSizes = getDimensionSizes(); int[] otherDimensions = other.getDimensionNumbers(); int[] otherSizes = other.getDimensionSizes(); // Check that dimensionNums contains a s...
python
def interpolate(self, lons, lats, zdata, order=1): """ Base class to handle nearest neighbour, linear, and cubic interpolation. Given a triangulation of a set of nodes on the unit sphere, along with data values at the nodes, this method interpolates (or extrapolates) the value at...
python
def extract_tokens(representation, separators=SEPARATOR_CHARACTERS): """Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string """ ...
java
public void setSnapshotIdentifierList(java.util.Collection<String> snapshotIdentifierList) { if (snapshotIdentifierList == null) { this.snapshotIdentifierList = null; return; } this.snapshotIdentifierList = new com.amazonaws.internal.SdkInternalList<String>(snapshotIdent...
python
def Barati_high(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9....
java
private void zSetParentSelectedDate(LocalDate dateValue) { if (parentDatePicker != null) { parentDatePicker.setDate(dateValue); } if (parentCalendarPanel != null) { parentCalendarPanel.setSelectedDate(dateValue); } }
python
def parse_record(self, node): """ Parses <Record> @param node: Node containing the <Record> element @type node: xml.etree.Element """ if self.current_simulation == None: self.raise_error('<Record> must be only be used inside a ' + ...
java
@Override protected void introspectWrapperSpecificInfo(com.ibm.ws.rsadapter.FFDCLogger info) { info.append("Underlying Statement: " + AdapterUtil.toString(stmtImpl), stmtImpl); info.append("Statement properties have changed? " + haveStatementPropertiesChanged); info.append("Poolability ...
python
async def on_raw_cap_list(self, params): """ Update active capabilities. """ self._capabilities = { capab: False for capab in self._capabilities } for capab in params[0].split(): capab, value = self._capability_normalize(capab) self._capabilities[capab] = value if value ...
java
public double viterbiDecode(Instance instance, int[] guessLabel) { final int[] allLabel = featureMap.allLabels(); final int bos = featureMap.bosTag(); final int sentenceLength = instance.tagArray.length; final int labelSize = allLabel.length; int[][] preMatrix = new int[sent...
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case KEY: return isSetKey(); case COUNT: return isSetCount(); } throw new IllegalStateException(); }
java
public void run() { LOGGER.debug("begin scan for config file changes ..."); try { Date lastModified = new Date(_xmlConfigFile.lastModified()); if (_lastTimeRead == null || lastModified.after(_lastTimeRead)) { LOGGER.info("loading config file changes ..."); this.loadServiceConfigFile...
java
public DataSetBuilder sequence(String column, double initial, double step) { return sequence(column, (Double) initial, x -> x + step); }
java
public void setCostAdjustment(com.google.api.ads.admanager.axis.v201811.CostAdjustment costAdjustment) { this.costAdjustment = costAdjustment; }
java
public double getLowerBound(final int numStdDev) { if (!isEstimationMode()) { return getRetainedEntries(); } return BinomialBoundsN.getLowerBound(getRetainedEntries(), getTheta(), numStdDev, isEmpty_); }
java
public Color scaleCopy(float value) { Color copy = new Color(r,g,b,a); copy.r *= value; copy.g *= value; copy.b *= value; copy.a *= value; return copy; }
python
def file_is_attached(self, url): '''return true if at least one book has file with the given url as attachment ''' body = self._get_search_field('_attachments.url', url) return self.es.count(index=self.index_name, body=body)['count'] > 0
python
def setup(channel, direction, initial=None, pull_up_down=None): """ You need to set up every channel you are using as an input or an output. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param...
python
def add_annotation_layer(self, annotation_file, layer_name): """ adds all markables from the given annotation layer to the discourse graph. """ assert os.path.isfile(annotation_file), \ "Annotation file doesn't exist: {}".format(annotation_file) tree = etree.p...
java
public static CommerceOrderNote remove(long commerceOrderNoteId) throws com.liferay.commerce.exception.NoSuchOrderNoteException { return getPersistence().remove(commerceOrderNoteId); }
python
def _load_instance(self, instance_id): """ Return instance with the given id. For performance reasons, the instance ID is first searched for in the collection of VM instances started by ElastiCluster (`self._instances`), then in the list of all instances known to the clo...
java
public static LocalTime now(Clock clock) { Jdk8Methods.requireNonNull(clock, "clock"); // inline OffsetTime factory to avoid creating object and InstantProvider checks final Instant now = clock.instant(); // called once ZoneOffset offset = clock.getZone().getRules().getOffset(now); ...
python
def get_http_info(self, request): """ Determine how to retrieve actual data by using request.mimetype. """ if self.is_json_type(request.mimetype): retriever = self.get_json_data else: retriever = self.get_form_data return self.get_http_info_with_re...
java
public static <T> void forEach(T[] input,boolean[] inputSkip,T[] output ,int outPutIndex,ForEachController<T> controller) { for(int i=0;i<input.length;i++) { if(inputSkip[i]) { continue; } output[outPutIndex]=input[i];//输出当前位锁定值 ComputeStatus status=controller.onOutEvent(output, outPutI...
python
def one_of(*args): "Verifies that only one of the arguments is not None" for i, arg in enumerate(args): if arg is not None: for argh in args[i+1:]: if argh is not None: raise OperationError("Too many parameters") else: return ...
python
def read(self, n=CHUNK_SIZE): """ Read up to `n` bytes from the file descriptor, wrapping the underlying :func:`os.read` call with :func:`io_op` to trap common disconnection conditions. :meth:`read` always behaves as if it is reading from a regular UNIX file; socket, pip...
java
public final void entryRuleXExpressionInClosure() throws RecognitionException { try { // InternalXbaseWithAnnotations.g:934:1: ( ruleXExpressionInClosure EOF ) // InternalXbaseWithAnnotations.g:935:1: ruleXExpressionInClosure EOF { if ( state.backtracking==0 ) { ...
java
private void execute() { for (Client client : clientMap.values()) { if (client != null && client instanceof Batcher) { // if no batch operation performed{may be running in // transaction?} if (((Batcher) client).getBatchSize() =...
python
def comparison(self, username): """ Get a comparison of scores between the "base user" and ``username``. A Key-Value returned will consist of the following: .. code-block:: none { ANIME_ID: [BASE_USER_SCORE, OTHER_USER_SCORE], ... ...
java
protected void checkExistingRestore(SnapshotIdentifier snapshotIdentifier) { Iterator<String> currentSpaces = snapshotProvider.getSpaces(); while (currentSpaces.hasNext()) { String spaceId = currentSpaces.next(); if (spaceId.equals(snapshotIdentifier.getRestoreSpaceId())) { ...
python
def _set_map_fport(self, v, load=False): """ Setter method for map_fport, mapped from YANG variable /rbridge_id/ag/nport_menu/nport_interface/nport/map/map_fport (container) If this variable is read-only (config: false) in the source YANG file, then _set_map_fport is considered as a private method. ...
java
public void deleteMergeRequestDiscussionNote(Object projectIdOrPath, Integer mergeRequestIid, Integer discussionId, Integer noteId) throws GitLabApiException { delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "discu...
java
public Iterable<Page> getPagesContainingTemplateNames(List<String> templateNames) throws WikiApiException{ return getFilteredPages(templateNames, true); }
python
def datetime_format(desired_format, datetime_instance=None, *args, **kwargs): """ Replaces format style phrases (listed in the dt_exps dictionary) with this datetime instance's information. .. code :: python reusables.datetime_format("Hey, it's {month-full} already!") "Hey, it's March...
python
def ensure_path(path, mode=0o777): """Ensure that path exists in a multiprocessing safe way. If the path does not exist, recursively create it and its parent directories using the provided mode. If the path already exists, do nothing. The umask is cleared to enable the mode to be set, and then re...
python
def _link_for_value(self, value): '''Returns the linked key if `value` is a link, or None.''' try: key = Key(value) if key.name == self.sentinel: return key.parent except: pass return None
java
public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.geo.GetGeoDetails [place id]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); Place place = twitter....
python
def _get_fashion_mnist(directory): """Download all FashionMNIST files to directory unless they are there.""" # Fashion mnist files have the same names as MNIST. # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir. for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_...
java
protected boolean fail(Throwable e) { if (done.compareAndSet(false, true)) { onErrorCore(e); return true; } return false; }
python
def do_startInstance(self,args): """Start specified instance""" parser = CommandArgumentParser("startInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] force = args['force'] ...
python
def help_center_article_show(self, locale, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/articles#show-article" api_path = "/api/v2/help_center/{locale}/articles/{id}.json" api_path = api_path.format(locale=locale, id=id) return self.call(api_path, **kwargs)
java
@Override public synchronized DatabaseEngine duplicate(Properties mergeProperties, final boolean copyEntities) throws DuplicateEngineException { if (mergeProperties == null) { mergeProperties = new Properties(); } final PdbProperties niwProps = properties.clone(); niwPro...
python
def toggle_lock(self, value): """Lock/Unlock dockwidgets and toolbars""" self.interface_locked = value CONF.set('main', 'panes_locked', value) # Apply lock to panes for plugin in (self.widgetlist + self.thirdparty_plugins): if self.interface_locked: ...
java
public void changeSelected(String selectNode, ServletRequest request) { _selectedNode = TreeHelpers.changeSelected(this, _selectedNode, selectNode, request); }
python
def validate(ctx, schema, all_schemata): """Validates all objects or all objects of a given schema.""" database = ctx.obj['db'] if schema is None: if all_schemata is False: log('No schema given. Read the help', lvl=warn) return else: schemata = database....
python
def unreserve_resources(role): """ Unreserves all the resources for all the slaves for the role. """ state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not unreserve_resource(agent, role): ...
java
private static Geometry splitPolygonWithLine(Polygon polygon, LineString lineString) throws SQLException { Collection<Polygon> pols = polygonWithLineSplitter(polygon, lineString); if (pols != null) { return FACTORY.buildGeometry(polygonWithLineSplitter(polygon, lineString)); } ...
python
def tmpl_if(condition, trueval, falseval=u''): """If ``condition`` is nonempty and nonzero, emit ``trueval``; otherwise, emit ``falseval`` (if provided). * synopsis: ``%if{condition,truetext}`` or \ ``%if{condition,truetext,falsetext}`` * description: If condition is nonempt...
java
public ConfigBase fromXml(final InputStream is, final Class cl) throws ConfigException { try { return fromXml(parseXml(is), cl); } catch (final ConfigException ce) { throw ce; } catch (final Throwable t) { throw new ConfigException(t); } }
java
protected List<ManagedModule> createAndStartModules() { final List<ManagedModule> managedModuleInstances = new ArrayList<>(); // create and start each managed module for(final Class<? extends ManagedModule> module:managedModules) { final ManagedModule mm = injector.getInstance(modul...
java
private boolean isSpecTopicMetaData(final String key, final String value) { if (ContentSpecUtilities.isSpecTopicMetaData(key)) { // Abstracts can be plain text so check an opening bracket exists if (key.equalsIgnoreCase(CommonConstants.CS_ABSTRACT_TITLE) || key.equalsIgnoreCase( ...
java
public static CPDefinitionLink findByUUID_G(String uuid, long groupId) throws com.liferay.commerce.product.exception.NoSuchCPDefinitionLinkException { return getPersistence().findByUUID_G(uuid, groupId); }
java
public boolean isLocalCache(String cacheContainerName, String localCacheName) throws Exception { if (!isCacheContainer(cacheContainerName)) { return false; } Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_INFINISPAN, CACHE_CONTAINER, cacheContainerName); String hayst...
java
public com.google.api.ads.admanager.axis.v201805.Date getEndDate() { return endDate; }
python
def set_metadata(self, container, metadata, clear=False, prefix=None): """ Accepts a dictionary of metadata key/value pairs and updates the specified container metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Othe...
python
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.v...
python
def _generate_struct_cstor_default(self, struct): """Emits struct convenience constructor. Default arguments are omitted.""" if not self._struct_has_defaults(struct): return fields_no_default = [ f for f in struct.all_fields if not f.has_default and not is_nu...
java
CacheResourceCore createCore(String path, String name, int type) throws IOException { CacheResourceCore value = new CacheResourceCore(type, path, name); getCache().put(toKey(path, name), value, null, null); return value; }
java
protected final long getClassLastModified() throws IOException, SQLException { String dir=getServletContext().getRealPath("/WEB-INF/classes"); if(dir!=null && dir.length()>0) { // Try to get from the class file long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastMo...
python
def insert(self, packet, time=None, **kwargs): ''' Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database time Optional parameter specifying the time value to use w...
java
static <S extends ScopeType<S>> boolean isScopeAncestor(ScopeWrapper<S> scope, ScopeWrapper<S> possibleAncestor) { Queue<ScopeWrapper<S>> ancestors = new LinkedList<>(); ancestors.add(scope); while (true) { if (ancestors.isEmpty()) { return false; } if (ancestors.peek().equals(poss...
python
def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ ...
java
public void cancel() { if (!isCancelled) { isCancelled = true; IntSet segmentsCopy = getUnfinishedSegments(); synchronized (segments) { unfinishedSegments.clear(); } if (trace) { log.tracef("Cancelling inbound state transfer from %s with unfini...
python
def _fake_openassociatorinstancepaths(self, namespace, **params): # pylint: disable=invalid-name """ Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenAssociatorInstancePaths` with data from the instance repository. """ self._validate_namespac...
python
def run(name, chip_bam, input_bam, genome_build, out_dir, method, resources, data): """ Run macs2 for chip and input samples avoiding errors due to samples. """ # output file name need to have the caller name config = dd.get_config(data) out_file = os.path.join(out_dir, name + "_peaks_macs2....
java
public ServiceFuture<GetPersonalPreferencesResponseInner> getPersonalPreferencesAsync(String userName, PersonalPreferencesOperationsPayload personalPreferencesOperationsPayload, final ServiceCallback<GetPersonalPreferencesResponseInner> serviceCallback) { return ServiceFuture.fromResponse(getPersonalPreferences...
python
def p_assignlist(self,t): "assignlist : assignlist ',' assign \n | assign" if len(t)==4: t[0] = t[1] + [t[3]] elif len(t)==2: t[0] = [t[1]] else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover
java
public static void cacheCriteriaByMapping(Class<?> targetClass, Criteria criteria) { Mapping m = GrailsDomainBinder.getMapping(targetClass); if (m != null && m.getCache() != null && m.getCache().getEnabled()) { criteria.setCacheable(true); } }
java
public static boolean isAbsolutePath(String systemId) { if(systemId == null) return false; final File file = new File(systemId); return file.isAbsolute(); }
java
public static int parseIntOrDefault(final String value, final int defaultValue) { if (null == value) { return defaultValue; } return Integer.parseInt(value); }
java
public int filterObject(CaptureSearchResult r) { recordsScanned++; if(recordsScanned > maxRecordsToScan) { LOGGER.warning("Hit max results on " + r.getUrlKey() + " " + r.getCaptureTimestamp()); return FILTER_ABORT; } return FILTER_INCLUDE; }
python
def fetch_datatype(self, bucket, key, r=None, pr=None, basic_quorum=None, notfound_ok=None, timeout=None, include_context=None): """ Fetches a Riak Datatype. """ raise NotImplementedError
java
private static int getMultiplier(final String unit) { int multiplier = 1; if(!StringUtils.isBlank(unit)) { if(UNIT_MILLION.equalsIgnoreCase(unit.trim())) { multiplier = 1000000; } if(UNIT_THOUSAND.equalsIgnoreCase(unit.trim())) { multiplier = 1000; } } return mult...
java
@Override public CommerceDiscount findByLtE_S_First(Date expirationDate, int status, OrderByComparator<CommerceDiscount> orderByComparator) throws NoSuchDiscountException { CommerceDiscount commerceDiscount = fetchByLtE_S_First(expirationDate, status, orderByComparator); if (commerceDiscount != null) { ...
python
def round(self, decimals=0, *args, **kwargs): """ Round each value in Panel to a specified number of decimal places. .. versionadded:: 0.18.0 Parameters ---------- decimals : int Number of decimal places to round to (default: 0). If decimals is n...
java
public String getTrack(int type) { if (allow(type&ID3V1)) { return Integer.toString(id3v1.getTrack()); } if (allow(type&ID3V2)) { return id3v2.getFrameDataString(ID3v2Frames.TRACK_NUMBER); } return null; }
python
def long2ip(l): """Convert a network byte order 32-bit integer to a dotted quad ip address. >>> long2ip(2130706433) '127.0.0.1' >>> long2ip(MIN_IP) '0.0.0.0' >>> long2ip(MAX_IP) '255.255.255.255' >>> long2ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call l...
java
public com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerServiceErrorReason getReason() { return reason; }
java
public static <T extends Tree> Matcher<T> isSubtypeOf(Class<?> clazz) { return new IsSubtypeOf<>(typeFromClass(clazz)); }
java
static <T1> Flowable<Notification<CallableResultSet1<T1>>> createWithOneResultSet(Single<Connection> connection, String sql, Flowable<List<Object>> parameterGroups, List<ParameterPlaceholder> parameterPlaceholders, Function<? super ResultSet, ? extends T1> f1, int fetchSize) { return con...
python
def CopyMicrosecondsToFractionOfSecond(cls, microseconds): """Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ...
java
private String[] extractAndDecodeHeader(String header) throws IOException { byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException e) { throw new BadCre...
java
public NYTCorpusDocument parseNYTCorpusDocumentFromFile(File file, boolean validating) { Document document = null; if (validating) { document = loadValidating(file); } else { document = loadNonValidating(file); } return parseNYTCorpusDocumentFromDOMDocument(file, document); }
java
private static AbstractPlanNode injectIndexedJoinWithMaterializedScan( AbstractExpression listElements, IndexScanPlanNode scanNode) { MaterializedScanPlanNode matScan = new MaterializedScanPlanNode(); assert(listElements instanceof VectorValueExpression || listElements instanceof ParameterVa...
python
def suits_with_dtype(mn, mx, dtype): """ Check whether range of values can be stored into defined data type. :param mn: range minimum :param mx: range maximum :param dtype: :return: """ type_info = np.iinfo(dtype) if mx <= type_info.max and mn >= type_info.min: return True ...