max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
356
<filename>utils/glutil.c #include "glutil.h" #include <stdio.h> #include <candle.h> #include <stdlib.h> #include <string.h> void _check_gl_error(const char *file, int line) { #ifdef DEBUG static char last_error[512] = ""; static int count = 0; char message[512]; GLenum err = glGetError(); int got_error = 0; while(err!=GL_NO_ERROR) { char *error = NULL; switch(err) { case GL_INVALID_OPERATION: error="INVALID_OPERATION"; break; case GL_INVALID_ENUM: error="INVALID_ENUM"; break; case GL_INVALID_VALUE: error="INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error="OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error="INVALID_FRAMEBUFFER_OPERATION"; break; } sprintf(message, "GL_%s - %s:%d", error, file, line); if(!strncmp(last_error, message, sizeof(last_error))) { printf("\b\b\r%s%6d\n", message, ++count); } else { count = 0; printf("%s\n", message); strncpy(last_error, message, sizeof(last_error)); } err=glGetError(); got_error = 1; } if(got_error) { printf("Exiting due to opengl error\n"); exit(1); } #ifndef __EMSCRIPTEN__ if(!is_render_thread()) { printf("glerr called in non render thread\n"); exit(1); } #endif #endif } void glInit() { #ifndef __EMSCRIPTEN__ if(ogl_LoadFunctions() == ogl_LOAD_FAILED) { printf("Exiting due to opengl failing to init\n"); exit(1); } #else GLenum err; err = glewInit(); if (err != GLEW_OK) { printf("Glew failed to initialize.\n"); exit(1); } if (!GLEW_VERSION_2_1) /* check that the machine supports the 2.1 API. */ { printf("Glew version.\n"); exit(1); } #endif }
805
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/IMAVCore.framework/IMAVCore */ #import <IMAVCore/XXUnknownSuperclass.h> #import <IMAVCore/NSCoding.h> @class NSString, NSDictionary; __attribute__((visibility("hidden"))) @interface AVChatParticipantStatusNugget : XXUnknownSuperclass <NSCoding> { NSString *_imHandleName; // 4 = 0x4 NSString *_imHandleID; // 8 = 0x8 NSString *_invitedBy; // 12 = 0xc NSString *_vcPartyID; // 16 = 0x10 BOOL _sendingAudio; // 20 = 0x14 BOOL _sendingVideo; // 21 = 0x15 BOOL _usingICE; // 22 = 0x16 unsigned _ardRole; // 24 = 0x18 unsigned _state; // 28 = 0x1c int _error; // 32 = 0x20 unsigned _reason; // 36 = 0x24 } @property(readonly, assign, nonatomic) unsigned reason; // G=0x6141; @property(readonly, assign, nonatomic) int error; // G=0x6131; @property(readonly, assign, nonatomic) unsigned state; // G=0x6121; @property(readonly, assign, nonatomic) unsigned ardRole; // G=0x6111; @property(readonly, assign, nonatomic) BOOL isUsingICE; // G=0x6101; @property(readonly, assign, nonatomic) BOOL sendingVideo; // G=0x60f1; @property(readonly, assign, nonatomic) BOOL sendingAudio; // G=0x60e1; @property(readonly, assign, nonatomic) NSString *vcPartyID; // G=0x60d1; @property(readonly, assign, nonatomic) NSString *invitedBy; // G=0x60c1; @property(readonly, assign, nonatomic) NSString *ID; // G=0x60b1; @property(readonly, assign, nonatomic) NSString *name; // G=0x60a1; @property(readonly, assign, nonatomic) NSDictionary *dictionaryDescription; // G=0x5ddd; + (id)nuggetWithDictionaryDescription:(id)dictionaryDescription; // 0x5fc5 + (id)filterNuggets:(id)nuggets filterEndedState:(BOOL)state convertFromDict:(BOOL)dict; // 0x592d - (void)encodeWithCoder:(id)coder; // 0x62a5 - (id)initWithCoder:(id)coder; // 0x6195 - (void)setVCPartyID:(id)anId; // 0x6151 // declared property getter: - (unsigned)reason; // 0x6141 // declared property getter: - (int)error; // 0x6131 // declared property getter: - (unsigned)state; // 0x6121 // declared property getter: - (unsigned)ardRole; // 0x6111 // declared property getter: - (BOOL)isUsingICE; // 0x6101 // declared property getter: - (BOOL)sendingVideo; // 0x60f1 // declared property getter: - (BOOL)sendingAudio; // 0x60e1 // declared property getter: - (id)vcPartyID; // 0x60d1 // declared property getter: - (id)invitedBy; // 0x60c1 // declared property getter: - (id)ID; // 0x60b1 // declared property getter: - (id)name; // 0x60a1 - (void)dealloc; // 0x6019 // declared property getter: - (id)dictionaryDescription; // 0x5ddd - (void)_configureWithDictionaryDescription:(id)dictionaryDescription; // 0x5be9 - (id)initWithParticipant:(id)participant; // 0x5a29 @end
1,066
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iPodUI.framework/iPodUI */ #import <iPodUI/iPodUI-Structs.h> #import <iPodUI/IUMediaQueriesDataSource.h> @interface IUPodcastTracksDataSource : IUMediaQueriesDataSource { unsigned _hideVideoIcon : 1; // 93 = 0x5d } @property(assign, nonatomic) BOOL hideVideoIcon; // G=0x493c5; S=0x493d9; + (int)mediaEntityType; // 0x49405 - (id)viewControllerContextForActionRow:(id)actionRow; // 0x49811 - (id)viewControllerContextForIndex:(unsigned)index; // 0x49801 - (void)reloadActionRows; // 0x49785 - (void)createGlobalContexts; // 0x49475 - (Class)cellConfigurationClassForEntity:(id)entity; // 0x49459 - (BOOL)shouldDisplayWhenEmpty; // 0x49455 - (BOOL)allowsDeletion; // 0x49409 // declared property setter: - (void)setHideVideoIcon:(BOOL)icon; // 0x493d9 // declared property getter: - (BOOL)hideVideoIcon; // 0x493c5 @end
355
1,444
<reponame>GabrielSturtevant/mage<gh_stars>1000+ package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BeginningOfUpkeepTriggeredAbility; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.constants.TargetController; import mage.filter.common.FilterCreaturePermanent; import mage.game.Game; import mage.players.Player; /** * * @author LevelX2 */ public final class ScourgeOfNumai extends CardImpl { public ScourgeOfNumai(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{B}"); this.subtype.add(SubType.DEMON); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(4); this.toughness = new MageInt(4); // At the beginning of your upkeep, you lose 2 life if you don't control an Ogre. this.addAbility(new BeginningOfUpkeepTriggeredAbility(new ScourgeOfNumaiEffect(), TargetController.YOU, false)); } private ScourgeOfNumai(final ScourgeOfNumai card) { super(card); } @Override public ScourgeOfNumai copy() { return new ScourgeOfNumai(this); } } class ScourgeOfNumaiEffect extends OneShotEffect { public ScourgeOfNumaiEffect() { super(Outcome.LoseLife); this.staticText = "you lose 2 life if you don't control an Ogre."; } public ScourgeOfNumaiEffect(final ScourgeOfNumaiEffect effect) { super(effect); } @Override public ScourgeOfNumaiEffect copy() { return new ScourgeOfNumaiEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { if (game.getBattlefield().countAll(new FilterCreaturePermanent(SubType.OGRE, "Ogre"), source.getControllerId(), game) < 1) { controller.loseLife(2, game, source, false); } return true; } return false; } }
859
1,837
<reponame>xincao9/Zebra /* * Copyright (c) 2011-2018, <NAME>. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * *    http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.zebra.group.config.datasource.entity; import com.dianping.zebra.group.config.ReadOrWriteRole; import com.dianping.zebra.group.config.datasource.BaseEntity; import com.dianping.zebra.group.config.datasource.IVisitor; import java.util.LinkedHashMap; import java.util.Map; public class GroupDataSourceConfig extends BaseEntity<GroupDataSourceConfig> { private String m_filters = ""; private String m_routerStrategy = "WeightRouter"; private Map<String, DataSourceConfig> m_dataSourceConfigs = new LinkedHashMap(); public GroupDataSourceConfig() { } public void accept(IVisitor visitor) { visitor.visitGroupDataSourceConfig(this); } public GroupDataSourceConfig addDataSourceConfig(DataSourceConfig dataSourceConfig) { this.m_dataSourceConfigs.put(dataSourceConfig.getId(), dataSourceConfig); return this; } public boolean equals(Object obj) { if (!(obj instanceof GroupDataSourceConfig)) { return false; } else { GroupDataSourceConfig _o = (GroupDataSourceConfig) obj; String filters = _o.getFilters(); String routerStrategy = _o.getRouterStrategy(); Map<String, DataSourceConfig> dataSourceConfigs = _o.getDataSourceConfigs(); boolean result = true; result &= this.m_filters == filters || this.m_filters != null && this.m_filters.equals(filters); result &= this.m_routerStrategy == routerStrategy || this.m_routerStrategy != null && this.m_routerStrategy.equals(routerStrategy); result &= this.m_dataSourceConfigs == dataSourceConfigs || this.m_dataSourceConfigs != null && this.m_dataSourceConfigs.equals(dataSourceConfigs); return result; } } public DataSourceConfig findDataSourceConfig(String id) { return (DataSourceConfig) this.m_dataSourceConfigs.get(id); } public DataSourceConfig findOrCreateDataSourceConfig(String id) { DataSourceConfig dataSourceConfig = (DataSourceConfig) this.m_dataSourceConfigs.get(id); if (dataSourceConfig == null) { synchronized (this.m_dataSourceConfigs) { dataSourceConfig = (DataSourceConfig) this.m_dataSourceConfigs.get(id); if (dataSourceConfig == null) { dataSourceConfig = new DataSourceConfig(id); this.m_dataSourceConfigs.put(id, dataSourceConfig); } } } return dataSourceConfig; } public DataSourceConfig findOrCreateDataSourceConfig(ReadOrWriteRole role) { return findOrCreateDataSourceConfig(role.getReadOrWriteDsName()); } public Map<String, DataSourceConfig> getDataSourceConfigs() { return this.m_dataSourceConfigs; } public String getFilters() { return this.m_filters; } public String getRouterStrategy() { return this.m_routerStrategy; } public int hashCode() { int hash = 0; hash = hash * 31 + (this.m_filters == null ? 0 : this.m_filters.hashCode()); hash = hash * 31 + (this.m_routerStrategy == null ? 0 : this.m_routerStrategy.hashCode()); hash = hash * 31 + (this.m_dataSourceConfigs == null ? 0 : this.m_dataSourceConfigs.hashCode()); return hash; } public void mergeAttributes(GroupDataSourceConfig other) { if (other.getFilters() != null) { this.m_filters = other.getFilters(); } if (other.getRouterStrategy() != null) { this.m_routerStrategy = other.getRouterStrategy(); } } public boolean removeDataSourceConfig(String id) { if (this.m_dataSourceConfigs.containsKey(id)) { this.m_dataSourceConfigs.remove(id); return true; } else { return false; } } public GroupDataSourceConfig setFilters(String filters) { this.m_filters = filters; return this; } public GroupDataSourceConfig setRouterStrategy(String routerStrategy) { this.m_routerStrategy = routerStrategy; return this; } }
1,513
965
// The string to match. LPCTSTR lpszmyExactString = _T("item 5"); // Delete all items that exactly match the specified string. int nDex = 0; while ((nDex = m_pComboBox->FindStringExact(nDex, lpszmyExactString)) != CB_ERR) { m_pComboBox->DeleteString(nDex); }
99
348
{"nom":"Villelongue-d'Aude","circ":"3ème circonscription","dpt":"Aude","inscrits":235,"abs":106,"votants":129,"blancs":11,"nuls":3,"exp":115,"res":[{"nuance":"REM","nom":"<NAME>","voix":60},{"nuance":"SOC","nom":"<NAME>","voix":55}]}
95
2,151
<reponame>google-ar/chromium<gh_stars>1000+ { "name": "mus_demo_unittests", "display_name": "MUS Demo Unittests", "interface_provider_specs": { "service_manager:connector": { "requires": { "*": [ "app", "test" ] } } } }
122
1,073
package org.saiku; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ArrayMapDeserializer extends JsonDeserializer<Map<String, String>> { @Override public Map<String, String> deserialize(JsonParser jp, DeserializationContext context) throws IOException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)) { return mapper.readValue(jp, new TypeReference<HashMap<String, String>>() { }); } else { //consume this stream mapper.readTree(jp); return new HashMap<>(); } } }
405
308
# [Backward compatibility]: keep importing modules functions from ..internal.utils.deprecation import deprecation from ..internal.utils.importlib import func_name from ..internal.utils.importlib import module_name from ..internal.utils.importlib import require_modules deprecation( name="ddtrace.contrib.util", message="`ddtrace.contrib.util` module will be removed in 1.0.0", version="1.0.0", ) __all__ = [ "require_modules", "func_name", "module_name", ]
160
1,133
<reponame>vincentschut/isce2 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2014 California Institute of Technology. ALL RIGHTS RESERVED. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # United States Government Sponsorship acknowledged. This software is subject to # U.S. export control laws and regulations and has been classified as 'EAR99 NLR' # (No [Export] License Required except when exporting to an embargoed country, # end user, or in support of a prohibited end use). By downloading this software, # the user agrees to comply with all applicable U.S. export laws and regulations. # The user has the responsibility to obtain export licenses, or other export # authority as may be required before exporting this software to any 'EAR99' # embargoed foreign country or citizen of those countries. # # Author: <NAME> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """Define the RDF Entries as: RDFRecord = (key, RDFField)""" ## \namespace rdf.data.entries Usable data objects for lines (records). import collections import sys #from functools import partial #from operator import methodcaller from iscesys.Parsers.rdf.reserved import glyphs from iscesys.Parsers.rdf.language import errors from iscesys.Parsers.rdf.language.grammar import punctuation # A space character S = " " ## Decorator to cast values ## \param magicmethodbinding A function that binds to a magic method and ## casts instances (for example: float) ## \retval cast_method An instance method that cast ala magicmethodbinding def _cast(magicmethodbinding): """decorator for magic method/function casting""" def cast_method(self): """__int__ --> int(self.value) --for example""" return magicmethodbinding(self.value) return cast_method ## Base RDF Field named tuple -it's all in here -note, it's assigned (public) ## name dIffers from its variable (private) name, so that users never need to ## know about this private assignemnt _RDFField = collections.namedtuple('RDFField', 'value units dimensions element comments') ## Add methods and constants to _RDFField so that it lives up to its name. class RDFField(_RDFField): """RDFField(value, units=None, dimensions=None, element=None, comments=None) represents a fully interpreted logical entry in an RDF file (sans key) """ ## (units) Brackets _Units = punctuation.UNITS ## {dim} Brackets _Dimensions = punctuation.DIMENSIONS ## [elements] Brackets _Element = punctuation.ELEMENT ## (-) appears as default _default_units = ("-", "&") ## non-private version: it is used in units.py default_units = _default_units ## does not appear b/c it's False _default_comments = "" ## _ditto_ _default_dimensions = "" ## _dito_ _default_element = "" _operator = glyphs.OPERATOR _comment = glyphs.COMMENT ## Do a namedtuple with defaults as follows... ## \param [cls] class is implicity passed... ## \param value Is the value of the rdf field ## \param [units] defaults to RDFField._default_units ## \param [dimensions] defaults to RDFField._default_dimensions ## \param [element] defaults to RDFField._default_element ## \param [comments] defaults to RDFField._default_comments def __new__(cls, value, units=None, dimensions=None, element=None, comments=None): # Order unit conversion value, units = cls._handle_units(value, units) return _RDFField.__new__(cls, value, str(units or cls._default_units), str(dimensions or cls._default_dimensions), str(element or cls._default_element), str(comments or cls._default_comments)) ## Do the unit conversion @classmethod def _handle_units(cls, value, units): from iscesys.Parsers.rdf.units import SI # convert units, If they're neither None nor "-". if units and units not in cls._default_units: try: value, units = SI(value, units) except errors.UnknownUnitWarning: print("UnknownUnitWarning:" + (cls._Units << str(units)), file=sys.stderr) return value, units ## eval(self.value) -with some protection/massage ## safe for list, tuples, nd.arrays, set, dict, ## anything that can survive repr - this is really a work in progress, ## since there is a lot of python subtly involved. ## \returns evaluated version of RDFField.value def eval(self): """eval() uses eval built-in to interpert value""" try: result = eval(str(self.value)) except (TypeError, NameError, AttributeError, SyntaxError): try: result = eval(repr(self.value)) except (TypeError, NameError, AttributeError, SyntaxError): result = self.value return result def index(self): return len(self.left_field()) ## Construct string on the left side of OPERATOR def left_field(self, index=0): """Parse left of OPERATOR place OPERATOR at index or don't """ result = ((self.units >> self._Units) + (self.dimensions >> self._Dimensions) + (self.element >> self._Element)) short = max(0, index-len(result)) x = result + (" "*short) # print len(x) return x ## Construct string on the right side of OPERATOR (w/o an IF) def right_field(self): """Parse right of operator""" return ( str(self.value) + (" " + self._comment) * bool(self.comments) + (self.comments or "") ) ## FORMAT CONTROL TBD def __str__(self, index=0): """place OPERATOR at index or don't""" return ( self.left_field(index=index) + self._operator + S + self.right_field() ) ## Call returns value ## \param [func] = \f$ f(x):x \rightarrow x\f$ A callable (like float). ## \returns \f$ f(x) \f$ with x from eval() method. def __call__(self, func=lambda __: __): """You can cast with call via, say: field(float)""" return func(self.eval()) __index__ = _cast(bin) __hex__ = _cast(hex) __oct__ = _cast(oct) __int__ = _cast(int) __long__ = _cast(int) __float__ = _cast(float) __complex__ = _cast(complex) ## key + field --> _RDFPreRecord, the whole thing is private. def __radd__(self, key): return RDFPreRecord(key, self) ## This assignment is a bit deeper: Just a key and a field _RDFRecord = collections.namedtuple("RDFRecord", "key field") ## The pre Record is built from data and is a len=1 iterator: iterating builds ## the final product: RDFRecord-- thus line reads or include file reads yield ## the same (polymorphic) result: iterators that yield Records. class RDFPreRecord(_RDFRecord): """Users should not see this class""" ## iter() is about polymorphism - since an INCLUDE can yield a whole list ## of records - the client needs to be able to iterate it w/o typechecking ## this does it- you iter it once, and builds the FINAL form of the record ## that's polymorphism: ## \retval RDFRecord iter(RDFPreRecord) finalizes the object. def __iter__(self): return iter( (RDFRecord(*super(RDFPreRecord, self).__iter__()),) ) ## This is a fully parsed RDF record, and is an _RDFRecord with a formatable ## string. class RDFRecord(_RDFRecord): """RDFRecord(key, field) is the parsed RDF file line. Key is a string (or else), and field is an RDFField. """ def __int__(self): from iscesys.Parsers.rdf.reserved import glyphs return str(self).index(glyphs.OPERATOR) ## FORMAT CONTROL TBD def __str__(self, index=0): """place OPERATOR at index or don't""" key = str(self.key) field = self.field.__str__(max(0, index-len(key))) return key + field ## The RDF Comment is a comment string, endowed with False RDF-ness class RDFComment(str): """This is string that always evaluates to False. Why? False gets thrown out before being sent to the RDF constructor But! It is not None, so you can keep it in your RDFAccumulator """ ## RDF comments are False in an RDF sense--regardless of their content # \retval < <a href= # "http://docs.python.org/2/library/constants.html?highlight=false#False"> # False</a> Always returns False-- ALWAYS def __nonzero__(self): return False ## Iter iterates over nothing-NOT the contents of the string. ## \retval iter(()) An empty iterator that passes a for-loop silently def __iter__(self): return iter(())
3,513
1,467
<reponame>mattdanielbrown/userbase #import <Cordova/CDVPlugin.h> @interface ScryptPlugin : CDVPlugin - (void)scrypt:(CDVInvokedUrlCommand*)command; @property (nonatomic, copy) NSString *callbackId; @end
77
17,375
<filename>jaxlib/cusolver.cc /* Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <cstdint> #include <stdexcept> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_format.h" #include "third_party/gpus/cuda/include/cuda.h" #include "third_party/gpus/cuda/include/cuda_runtime_api.h" #include "third_party/gpus/cuda/include/cusolverDn.h" #include "jaxlib/cuda_gpu_kernel_helpers.h" #include "jaxlib/cusolver_kernels.h" #include "jaxlib/kernel_pybind11_helpers.h" #include "include/pybind11/numpy.h" #include "include/pybind11/pybind11.h" #include "include/pybind11/stl.h" namespace jax { namespace { namespace py = pybind11; // Converts a NumPy dtype to a Type. CusolverType DtypeToCusolverType(const py::dtype& np_type) { static auto* types = new absl::flat_hash_map<std::pair<char, int>, CusolverType>({ {{'f', 4}, CusolverType::F32}, {{'f', 8}, CusolverType::F64}, {{'c', 8}, CusolverType::C64}, {{'c', 16}, CusolverType::C128}, }); auto it = types->find({np_type.kind(), np_type.itemsize()}); if (it == types->end()) { throw std::invalid_argument( absl::StrFormat("Unsupported dtype %s", py::repr(np_type))); } return it->second; } // potrf: Cholesky decomposition // Returns the workspace size and a descriptor for a potrf operation. std::pair<int, py::bytes> BuildPotrfDescriptor(const py::dtype& dtype, bool lower, int b, int n) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; std::int64_t workspace_size; cublasFillMode_t uplo = lower ? CUBLAS_FILL_MODE_LOWER : CUBLAS_FILL_MODE_UPPER; if (b == 1) { switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnSpotrf_bufferSize(handle.get(), uplo, n, /*A=*/nullptr, /*lda=*/n, &lwork))); workspace_size = lwork * sizeof(float); break; case CusolverType::F64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnDpotrf_bufferSize(handle.get(), uplo, n, /*A=*/nullptr, /*lda=*/n, &lwork))); workspace_size = lwork * sizeof(double); break; case CusolverType::C64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnCpotrf_bufferSize(handle.get(), uplo, n, /*A=*/nullptr, /*lda=*/n, &lwork))); workspace_size = lwork * sizeof(cuComplex); break; case CusolverType::C128: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnZpotrf_bufferSize(handle.get(), uplo, n, /*A=*/nullptr, /*lda=*/n, &lwork))); workspace_size = lwork * sizeof(cuDoubleComplex); break; } } else { // We use the workspace buffer for our own scratch space. workspace_size = sizeof(void*) * b; } return {workspace_size, PackDescriptor(PotrfDescriptor{type, uplo, b, n, lwork})}; } // getrf: LU decomposition // Returns the workspace size and a descriptor for a getrf operation. std::pair<int, py::bytes> BuildGetrfDescriptor(const py::dtype& dtype, int b, int m, int n) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnSgetrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; case CusolverType::F64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnDgetrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; case CusolverType::C64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnCgetrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; case CusolverType::C128: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnZgetrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; } return {lwork, PackDescriptor(GetrfDescriptor{type, b, m, n})}; } // geqrf: QR decomposition // Returns the workspace size and a descriptor for a geqrf operation. std::pair<int, py::bytes> BuildGeqrfDescriptor(const py::dtype& dtype, int b, int m, int n) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnSgeqrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; case CusolverType::F64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnDgeqrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; case CusolverType::C64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnCgeqrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; case CusolverType::C128: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnZgeqrf_bufferSize(handle.get(), m, n, /*A=*/nullptr, /*lda=*/m, &lwork))); break; } return {lwork, PackDescriptor(GeqrfDescriptor{type, b, m, n, lwork})}; } // orgqr/ungqr: apply elementary Householder transformations // Returns the workspace size and a descriptor for a geqrf operation. std::pair<int, py::bytes> BuildOrgqrDescriptor(const py::dtype& dtype, int b, int m, int n, int k) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnSorgqr_bufferSize(handle.get(), m, n, k, /*A=*/nullptr, /*lda=*/m, /*tau=*/nullptr, &lwork))); break; case CusolverType::F64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnDorgqr_bufferSize(handle.get(), m, n, k, /*A=*/nullptr, /*lda=*/m, /*tau=*/nullptr, &lwork))); break; case CusolverType::C64: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnCungqr_bufferSize(handle.get(), m, n, k, /*A=*/nullptr, /*lda=*/m, /*tau=*/nullptr, &lwork))); break; case CusolverType::C128: JAX_THROW_IF_ERROR( JAX_AS_STATUS(cusolverDnZungqr_bufferSize(handle.get(), m, n, k, /*A=*/nullptr, /*lda=*/m, /*tau=*/nullptr, &lwork))); break; } return {lwork, PackDescriptor(OrgqrDescriptor{type, b, m, n, k, lwork})}; } // Symmetric (Hermitian) eigendecomposition, QR algorithm: syevd/heevd // Returns the workspace size and a descriptor for a syevd operation. std::pair<int, py::bytes> BuildSyevdDescriptor(const py::dtype& dtype, bool lower, int b, int n) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; cusolverEigMode_t jobz = CUSOLVER_EIG_MODE_VECTOR; cublasFillMode_t uplo = lower ? CUBLAS_FILL_MODE_LOWER : CUBLAS_FILL_MODE_UPPER; switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnSsyevd_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork))); break; case CusolverType::F64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnDsyevd_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork))); break; case CusolverType::C64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCheevd_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork))); break; case CusolverType::C128: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnZheevd_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork))); break; } return {lwork, PackDescriptor(SyevdDescriptor{type, uplo, b, n, lwork})}; } // Symmetric (Hermitian) eigendecomposition, Jacobi algorithm: syevj/heevj // Supports batches of matrices up to size 32. // Returns the workspace size and a descriptor for a syevj_batched operation. std::pair<int, py::bytes> BuildSyevjDescriptor(const py::dtype& dtype, bool lower, int batch, int n) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; syevjInfo_t params; JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCreateSyevjInfo(&params))); std::unique_ptr<syevjInfo, void (*)(syevjInfo*)> params_cleanup( params, [](syevjInfo* p) { cusolverDnDestroySyevjInfo(p); }); cusolverEigMode_t jobz = CUSOLVER_EIG_MODE_VECTOR; cublasFillMode_t uplo = lower ? CUBLAS_FILL_MODE_LOWER : CUBLAS_FILL_MODE_UPPER; if (batch == 1) { switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnSsyevj_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params))); break; case CusolverType::F64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnDsyevj_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params))); break; case CusolverType::C64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCheevj_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params))); break; case CusolverType::C128: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnZheevj_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params))); break; } } else { switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnSsyevjBatched_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params, batch))); break; case CusolverType::F64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnDsyevjBatched_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params, batch))); break; case CusolverType::C64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCheevjBatched_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params, batch))); break; case CusolverType::C128: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnZheevjBatched_bufferSize( handle.get(), jobz, uplo, n, /*A=*/nullptr, /*lda=*/n, /*W=*/nullptr, &lwork, params, batch))); break; } } return {lwork, PackDescriptor(SyevjDescriptor{type, uplo, batch, n, lwork})}; } // Singular value decomposition using QR algorithm: gesvd // Returns the workspace size and a descriptor for a gesvd operation. std::pair<int, py::bytes> BuildGesvdDescriptor(const py::dtype& dtype, int b, int m, int n, bool compute_uv, bool full_matrices) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR(JAX_AS_STATUS( cusolverDnSgesvd_bufferSize(handle.get(), m, n, &lwork))); break; case CusolverType::F64: JAX_THROW_IF_ERROR(JAX_AS_STATUS( cusolverDnDgesvd_bufferSize(handle.get(), m, n, &lwork))); break; case CusolverType::C64: JAX_THROW_IF_ERROR(JAX_AS_STATUS( cusolverDnCgesvd_bufferSize(handle.get(), m, n, &lwork))); break; case CusolverType::C128: JAX_THROW_IF_ERROR(JAX_AS_STATUS( cusolverDnZgesvd_bufferSize(handle.get(), m, n, &lwork))); break; } signed char jobu, jobvt; if (compute_uv) { if (full_matrices) { jobu = jobvt = 'A'; } else { jobu = jobvt = 'S'; } } else { jobu = jobvt = 'N'; } return {lwork, PackDescriptor(GesvdDescriptor{type, b, m, n, lwork, jobu, jobvt})}; } // Singular value decomposition using Jacobi algorithm: gesvdj // Returns the workspace size and a descriptor for a gesvdj operation. std::pair<int, py::bytes> BuildGesvdjDescriptor(const py::dtype& dtype, int batch, int m, int n, bool compute_uv) { CusolverType type = DtypeToCusolverType(dtype); auto h = SolverHandlePool::Borrow(); JAX_THROW_IF_ERROR(h.status()); auto& handle = *h; int lwork; cusolverEigMode_t jobz = compute_uv ? CUSOLVER_EIG_MODE_VECTOR : CUSOLVER_EIG_MODE_NOVECTOR; gesvdjInfo_t params; JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCreateGesvdjInfo(&params))); std::unique_ptr<gesvdjInfo, void (*)(gesvdjInfo*)> params_cleanup( params, [](gesvdjInfo* p) { cusolverDnDestroyGesvdjInfo(p); }); if (batch == 1) { switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnSgesvdj_bufferSize( handle.get(), jobz, /*econ=*/0, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params))); break; case CusolverType::F64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnDgesvdj_bufferSize( handle.get(), jobz, /*econ=*/0, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params))); break; case CusolverType::C64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCgesvdj_bufferSize( handle.get(), jobz, /*econ=*/0, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params))); break; case CusolverType::C128: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnZgesvdj_bufferSize( handle.get(), jobz, /*econ=*/0, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params))); break; } } else { switch (type) { case CusolverType::F32: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnSgesvdjBatched_bufferSize( handle.get(), jobz, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params, batch))); break; case CusolverType::F64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnDgesvdjBatched_bufferSize( handle.get(), jobz, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params, batch))); break; case CusolverType::C64: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnCgesvdjBatched_bufferSize( handle.get(), jobz, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params, batch))); break; case CusolverType::C128: JAX_THROW_IF_ERROR(JAX_AS_STATUS(cusolverDnZgesvdjBatched_bufferSize( handle.get(), jobz, m, n, /*A=*/nullptr, /*lda=*/m, /*S=*/nullptr, /*U=*/nullptr, /*ldu=*/m, /*V=*/nullptr, /*ldv=*/n, &lwork, params, batch))); break; } } return {lwork, PackDescriptor(GesvdjDescriptor{type, batch, m, n, lwork, jobz})}; } py::dict Registrations() { py::dict dict; dict["cusolver_potrf"] = EncapsulateFunction(Potrf); dict["cusolver_getrf"] = EncapsulateFunction(Getrf); dict["cusolver_geqrf"] = EncapsulateFunction(Geqrf); dict["cusolver_orgqr"] = EncapsulateFunction(Orgqr); dict["cusolver_syevd"] = EncapsulateFunction(Syevd); dict["cusolver_syevj"] = EncapsulateFunction(Syevj); dict["cusolver_gesvd"] = EncapsulateFunction(Gesvd); dict["cusolver_gesvdj"] = EncapsulateFunction(Gesvdj); return dict; } PYBIND11_MODULE(_cusolver, m) { m.def("registrations", &Registrations); m.def("build_potrf_descriptor", &BuildPotrfDescriptor); m.def("build_getrf_descriptor", &BuildGetrfDescriptor); m.def("build_geqrf_descriptor", &BuildGeqrfDescriptor); m.def("build_orgqr_descriptor", &BuildOrgqrDescriptor); m.def("build_syevd_descriptor", &BuildSyevdDescriptor); m.def("build_syevj_descriptor", &BuildSyevjDescriptor); m.def("build_gesvd_descriptor", &BuildGesvdDescriptor); m.def("build_gesvdj_descriptor", &BuildGesvdjDescriptor); } } // namespace } // namespace jax
10,583
3,782
""" Script that trains Sklearn multitask models on nci dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import numpy as np import shutil from deepchem.molnet import load_nci from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestRegressor from deepchem.data import Dataset from deepchem.models.multitask import SingletaskToMultitask from deepchem import metrics from deepchem.metrics import Metric from deepchem.models.sklearn_models import SklearnModel from deepchem.utils.evaluate import Evaluator np.random.seed(123) # Set some global variables up top verbosity = "high" nci_tasks, nci_dataset, transformers = load_nci() (train_dataset, valid_dataset, test_dataset) = nci_dataset classification_metric = Metric( metrics.roc_auc_score, np.mean, mode="classification") def model_builder(model_dir): sklearn_model = RandomForestRegressor(n_estimators=500) return SklearnModel(sklearn_model, model_dir) model = SingletaskToMultitask(nci_tasks, model_builder) # Fit trained model model.fit(train_dataset) train_evaluator = Evaluator( model, train_dataset, transformers, verbosity=verbosity) train_scores = train_evaluator.compute_model_performance( [classification_metric]) print("Train scores") print(train_scores) valid_evaluator = Evaluator( model, valid_dataset, transformers, verbosity=verbosity) valid_scores = valid_evaluator.compute_model_performance( [classification_metric]) print("Validation scores") print(valid_scores)
519
310
<reponame>dreeves/usesthis { "name": "Scrollz", "description": "A command-line IRC client.", "url": "http://www.scrollz.com/" }
53
1,830
<reponame>thirteen13Floor/zeebe /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.1. You may not use this file * except in compliance with the Zeebe Community License 1.1. */ package io.camunda.zeebe.it.network; import static org.assertj.core.api.Assertions.assertThat; import io.camunda.zeebe.broker.test.EmbeddedBrokerRule; import io.camunda.zeebe.it.util.GrpcClientRule; import io.camunda.zeebe.model.bpmn.Bpmn; import io.camunda.zeebe.protocol.record.intent.JobIntent; import io.camunda.zeebe.protocol.record.intent.VariableIntent; import io.camunda.zeebe.test.util.record.RecordingExporter; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.RuleChain; import org.springframework.util.unit.DataSize; public class SmallMessageSizeTest { private static final int VARIABLE_COUNT = 4; private static final DataSize MAX_MESSAGE_SIZE = DataSize.ofKilobytes(12); private static final String LARGE_TEXT = "x".repeat((int) (MAX_MESSAGE_SIZE.toBytes() / VARIABLE_COUNT)); private static final EmbeddedBrokerRule BROKER_RULE = new EmbeddedBrokerRule( b -> { b.getNetwork().setMaxMessageSize(MAX_MESSAGE_SIZE); b.getGateway().getLongPolling().setEnabled(false); }); private static final GrpcClientRule CLIENT_RULE = new GrpcClientRule(BROKER_RULE); @ClassRule public static RuleChain ruleChain = RuleChain.outerRule(BROKER_RULE).around(CLIENT_RULE); private long processInstanceKey; private String jobType; @Before public void givenProcessWithLargeVariables() { // given a process with a job jobType = UUID.randomUUID().toString(); final var processDefinitionKey = CLIENT_RULE.deployProcess( Bpmn.createExecutableProcess("PROCESS_" + jobType) .startEvent() .serviceTask("task", t -> t.zeebeJobType(jobType)) .endEvent() .done()); processInstanceKey = CLIENT_RULE.createProcessInstance(processDefinitionKey); Awaitility.await("job CREATED") .until( () -> RecordingExporter.jobRecords(JobIntent.CREATED) .withProcessInstanceKey(processInstanceKey) .withType(jobType) .exists()); // with variables that are greater than the message size for (int i = 0; i < VARIABLE_COUNT; i++) { CLIENT_RULE .getClient() .newSetVariablesCommand(processInstanceKey) .variables(Map.of(String.format("large-%d", i), LARGE_TEXT)) .send() .join(); } Awaitility.await("large variables CREATED") .until( () -> RecordingExporter.variableRecords(VariableIntent.CREATED) .withProcessInstanceKey(processInstanceKey) .filter(v -> v.getValue().getName().startsWith("large")) .limit(4) .count(), n -> n == 4); } @Test public void shouldSkipJobsThatExceedMessageSize() { // when (we activate jobs) final var response = CLIENT_RULE .getClient() .newActivateJobsCommand() .jobType(jobType) .maxJobsToActivate(1) .send() .join(10, TimeUnit.SECONDS); // then the job of the process which is too big for the message is ignored assertThat(response.getJobs()).isEmpty(); } @Test public void shouldActivateJobIfRequestVariablesFitIntoMessageSize() { // when (we activate job, but select only a subset of the variables - a subset that fits into // the message size) final var response = CLIENT_RULE .getClient() .newActivateJobsCommand() .jobType(jobType) .maxJobsToActivate(1) .fetchVariables("0") .send() .join(10, TimeUnit.SECONDS); // then (the job is activated) assertThat(response.getJobs()).hasSize(1); assertThat(response.getJobs().get(0).getProcessInstanceKey()).isEqualTo(processInstanceKey); } }
1,854
14,668
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser.accessibility; import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH; import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX; import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY; import android.annotation.TargetApi; import android.graphics.Rect; import android.graphics.RectF; import android.os.Build; import android.os.Bundle; import android.view.accessibility.AccessibilityNodeInfo; import org.chromium.base.annotations.JNINamespace; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Subclass of WebContentsAccessibility for O */ @JNINamespace("content") @TargetApi(Build.VERSION_CODES.O) public class OWebContentsAccessibility extends WebContentsAccessibilityImpl { // static instances of the two types of actions that can be added to nodes as the array is not // node-specific and this will save on recreation of many lists per page. private static List<String> sTextCharacterLocation = Arrays.asList(EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY); private static List<String> sRequestImageData = Arrays.asList(EXTRAS_DATA_REQUEST_IMAGE_DATA_KEY); // Set of all nodes that have received a request to populate image data. The request only needs // to be run once per node, and it completes asynchronously. We track which nodes have already // started the async request so that if downstream apps request the same node multiple times // we can avoid doing the extra work. private final Set<Integer> mImageDataRequestedNodes = new HashSet<Integer>(); OWebContentsAccessibility(AccessibilityDelegate delegate) { super(delegate); } @Override public void clearNodeInfoCacheForGivenId(int virtualViewId) { if (mImageDataRequestedNodes != null) { mImageDataRequestedNodes.remove(virtualViewId); } super.clearNodeInfoCacheForGivenId(virtualViewId); } @Override protected void setAccessibilityNodeInfoOAttributes(AccessibilityNodeInfo node, boolean hasCharacterLocations, boolean hasImage, String hint) { node.setHintText(hint); if (hasCharacterLocations) { node.setAvailableExtraData(sTextCharacterLocation); } else if (hasImage) { node.setAvailableExtraData(sRequestImageData); } } @Override public void addExtraDataToAccessibilityNodeInfo( int virtualViewId, AccessibilityNodeInfo info, String extraDataKey, Bundle arguments) { switch (extraDataKey) { case EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY: getExtraDataTextCharacterLocations(virtualViewId, info, arguments); break; case EXTRAS_DATA_REQUEST_IMAGE_DATA_KEY: getImageData(virtualViewId, info); break; } } private void getExtraDataTextCharacterLocations( int virtualViewId, AccessibilityNodeInfo info, Bundle arguments) { if (!areInlineTextBoxesLoaded(virtualViewId)) { loadInlineTextBoxes(virtualViewId); } int positionInfoStartIndex = arguments.getInt(EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX, -1); int positionInfoLength = arguments.getInt(EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH, -1); if (positionInfoLength <= 0 || positionInfoStartIndex < 0) return; int[] coords = getCharacterBoundingBoxes( virtualViewId, positionInfoStartIndex, positionInfoLength); if (coords == null) return; assert coords.length == positionInfoLength * 4; RectF[] boundingRects = new RectF[positionInfoLength]; for (int i = 0; i < positionInfoLength; i++) { Rect rect = new Rect( coords[4 * i + 0], coords[4 * i + 1], coords[4 * i + 2], coords[4 * i + 3]); convertWebRectToAndroidCoordinates(rect, info.getExtras()); boundingRects[i] = new RectF(rect); } info.getExtras().putParcelableArray(EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY, boundingRects); } private void getImageData(int virtualViewId, AccessibilityNodeInfo info) { boolean hasSentPreviousRequest = mImageDataRequestedNodes.contains(virtualViewId); // If the below call returns true, then image data has been set on the node. if (!WebContentsAccessibilityImplJni.get().getImageData(mNativeObj, OWebContentsAccessibility.this, info, virtualViewId, hasSentPreviousRequest)) { // If the above call returns false, then the data was missing. The native-side code // will have started the asynchronous process to populate the image data if no previous // request has been sent. Add this |virtualViewId| to the list of requested nodes. mImageDataRequestedNodes.add(virtualViewId); } } }
1,959
852
<gh_stars>100-1000 /*---------------------------------------------------------------------- Toy EDProducers and EDProducts for testing purposes only. ----------------------------------------------------------------------*/ #include <stdexcept> #include <string> #include <iostream> #include <fstream> #include <map> #include <vector> #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/CSCObjects/interface/CSCChamberTimeCorrections.h" #include "CondFormats/DataRecord/interface/CSCChamberTimeCorrectionsRcd.h" using namespace std; namespace edmtest { class CSCReadChamberTimeCorrectionsValuesAnalyzer : public edm::EDAnalyzer { public: explicit CSCReadChamberTimeCorrectionsValuesAnalyzer(edm::ParameterSet const& p) {} explicit CSCReadChamberTimeCorrectionsValuesAnalyzer(int i) {} virtual ~CSCReadChamberTimeCorrectionsValuesAnalyzer() {} virtual void analyze(const edm::Event& e, const edm::EventSetup& c); private: }; void CSCReadChamberTimeCorrectionsValuesAnalyzer::analyze(const edm::Event& e, const edm::EventSetup& context) { using namespace edm::eventsetup; // Context is not used. std::cout << " I AM IN RUN NUMBER " << e.id().run() << std::endl; std::cout << " ---EVENT NUMBER " << e.id().event() << std::endl; edm::ESHandle<CSCChamberTimeCorrections> pChamberTimeCorrections; context.get<CSCChamberTimeCorrectionsRcd>().get(pChamberTimeCorrections); const CSCChamberTimeCorrections* myChamberTimeCorrections = pChamberTimeCorrections.product(); // std::map<int,CSCMapItem::MapItem>::const_iterator it; std::vector<CSCChamberTimeCorrections::ChamberTimeCorrections>::const_iterator it; int count = 0; for (it = myChamberTimeCorrections->chamberCorrections.begin(); it != myChamberTimeCorrections->chamberCorrections.end(); ++it) { count = count + 1; // std::cout<<"Key: ddu_crate*10+ddu_input "<<it->first<<std::endl; std::cout << count << ") "; // std::cout<<it->chamber_label<<" "; std::cout << it->cfeb_length * 1. / myChamberTimeCorrections->factor_precision << " "; std::cout << it->cfeb_rev << " "; std::cout << it->alct_length * 1. / myChamberTimeCorrections->factor_precision << " "; std::cout << it->cfeb_tmb_skew_delay * 1. / myChamberTimeCorrections->factor_precision << " "; std::cout << it->cfeb_timing_corr * 1. / myChamberTimeCorrections->factor_precision << " "; std::cout << "delay " << it->cfeb_cable_delay << std::endl; } } DEFINE_FWK_MODULE(CSCReadChamberTimeCorrectionsValuesAnalyzer); } // namespace edmtest
1,047
1,179
<reponame>fengjixuchui/hypervisor-2 /// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #ifndef MOCK_BF_SYSCALL_IMPL_HPP #define MOCK_BF_SYSCALL_IMPL_HPP #include <bf_constants.hpp> #include <bf_reg_t.hpp> #include <iostream> #include <string> #include <string_view> #include <bsl/char_type.hpp> #include <bsl/convert.hpp> #include <bsl/discard.hpp> #include <bsl/safe_integral.hpp> #include <bsl/touch.hpp> #include <bsl/unlikely.hpp> #include <bsl/unordered_map.hpp> #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wexit-time-destructors" namespace syscall { /// NOTE: /// - In general, this set of mocked "impl" APIs should not be used /// directly. Most of these APIs should be used through the bf_syscall_t /// wrapper, and the mocked version of that wrapper should be used /// instead as it was far more capable. /// - There are some APIs in this library that provide some facilities. /// These specifically include the control ops and the debug ops. /// The syscall library provides these ops outside of the bf_syscall_t /// so that they can be used by an extension on their own. /// - The control ops APIs should only be used in a single unit test /// designed to ensure the main.cpp (or whatever file the entry points /// are located in) are tested as this is the only file that should /// contain these control ops. /// - The debug ops should only be used by whatever runtime library is /// used. This runtime library will provide the logic for how to /// handle the platform BSL functions. All other extension logic can /// simply use the BSL as it is, as the BSL already provides platform /// support for Windows and Linux which is what the unit tests will /// run on, meaning these libraries are only needed to support unit /// testing of the code that implements the syscall version of the /// BSL platform logic. /// // ------------------------------------------------------------------------- // global variables used by the impl mocks // ------------------------------------------------------------------------- /// @brief stores the data to return for an API constinit inline bsl::unordered_map<std::string, bsl::safe_u64> g_mut_data{}; // GRCOV_EXCLUDE_BR /// @brief stores the error code to return for an API constinit inline bsl::unordered_map<std::string, bsl::safe_u64> g_mut_errc{}; // GRCOV_EXCLUDE_BR /// @brief stores the pointers to return for an API constinit inline bsl::unordered_map<std::string, void *> g_mut_ptrs{}; // GRCOV_EXCLUDE_BR /// @brief stores whether or not bf_control_op_exit_impl was executed constinit inline bool g_mut_bf_control_op_exit_impl_executed{}; /// @brief stores whether or not bf_control_op_wait_impl was executed constinit inline bool g_mut_bf_control_op_wait_impl_executed{}; /// @brief stores whether or not bf_control_op_again_impl was executed constinit inline bool g_mut_bf_control_op_again_impl_executed{}; /// @brief stores whether or not bf_debug_op_out_impl was executed constinit inline bool g_mut_bf_debug_op_out_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_vm_impl was executed constinit inline bool g_mut_bf_debug_op_dump_vm_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_vp_impl was executed constinit inline bool g_mut_bf_debug_op_dump_vp_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_vs_impl was executed constinit inline bool g_mut_bf_debug_op_dump_vs_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_vmexit_log_impl was executed constinit inline bool g_mut_bf_debug_op_dump_vmexit_log_impl_executed{}; /// @brief stores whether or not bf_debug_op_write_c_impl was executed constinit inline bool g_mut_bf_debug_op_write_c_impl_executed{}; /// @brief stores whether or not bf_debug_op_write_str_impl was executed constinit inline bool g_mut_bf_debug_op_write_str_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_ext_impl was executed constinit inline bool g_mut_bf_debug_op_dump_ext_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_page_pool_impl was executed constinit inline bool g_mut_bf_debug_op_dump_page_pool_impl_executed{}; /// @brief stores whether or not bf_debug_op_dump_huge_pool_impl was executed constinit inline bool g_mut_bf_debug_op_dump_huge_pool_impl_executed{}; // ------------------------------------------------------------------------- // Bootstrap Callback Handler Type // ------------------------------------------------------------------------- /// @brief Defines the signature of the bootstrap callback handler // NOLINTNEXTLINE(bsl-non-safe-integral-types-are-forbidden) using bf_callback_handler_bootstrap_t = void (*)(bsl::uint16); // ------------------------------------------------------------------------- // VMExit Callback Handler Type // ------------------------------------------------------------------------- /// @brief Defines the signature of the VM exit callback handler // NOLINTNEXTLINE(bsl-non-safe-integral-types-are-forbidden) using bf_callback_handler_vmexit_t = void (*)(bsl::uint16, bsl::uint64); // ------------------------------------------------------------------------- // Fast Fail Callback Handler Type // ------------------------------------------------------------------------- /// @brief Defines the signature of the fast fail callback handler // NOLINTNEXTLINE(bsl-non-safe-integral-types-are-forbidden) using bf_callback_handler_fail_t = void (*)(bsl::uint64, bsl::uint64); // ------------------------------------------------------------------------- // dummy callbacks // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements a dummy bootstrap entry function. /// /// <!-- inputs/outputs --> /// @param ppid the physical process to bootstrap /// extern "C" inline void dummy_bootstrap_entry(bsl::uint16 const ppid) noexcept { bsl::discard(ppid); } /// <!-- description --> /// @brief Implements a dummy VMExit entry function. /// /// <!-- inputs/outputs --> /// @param vsid the ID of the VS that generated the VMExit /// @param exit_reason the exit reason associated with the VMExit /// extern "C" inline void dummy_vmexit_entry(bsl::uint16 const vsid, bsl::uint64 const exit_reason) noexcept { bsl::discard(vsid); bsl::discard(exit_reason); } /// <!-- description --> /// @brief Implements a dummy fast fail entry function. /// /// <!-- inputs/outputs --> /// @param errc the reason for the failure, which is CPU /// specific. On x86, this is a combination of the exception /// vector and error code. /// @param addr contains a faulting address if the fail reason /// is associated with an error that involves a faulting address ( /// for example like a page fault). Otherwise, the value of this /// input is undefined. /// extern "C" inline void dummy_fail_entry(bsl::uint64 const errc, bsl::uint64 const addr) noexcept { bsl::discard(errc); bsl::discard(addr); } // ------------------------------------------------------------------------- // TLS ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_tls_rax. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rax_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rax").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rax. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rax_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rax") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_rbx. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rbx_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rbx").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rbx. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rbx_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rbx") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_rcx. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rcx_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rcx").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rcx. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rcx_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rcx") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_rdx. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rdx_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rdx").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rdx. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rdx_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rdx") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_rbp. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rbp_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rbp").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rbp. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rbp_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rbp") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_rsi. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rsi_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rsi").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rsi. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rsi_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rsi") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_rdi. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_rdi_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_rdi").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_rdi. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_rdi_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_rdi") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r8. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r8_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r8").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r8. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r8_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r8") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r9. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r9_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r9").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r9. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r9_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r9") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r10. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r10_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r10").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r10. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r10_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r10") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r11. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r11_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r11").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r11. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r11_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r11") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r12. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r12_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r12").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r12. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r12_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r12") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r13. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r13_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r13").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r13. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r13_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r13") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r14. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r14_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r14").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r14. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r14_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r14") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_r15. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_r15_impl() noexcept -> bsl::uint64 { return g_mut_data.at("bf_tls_r15").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_set_r15. /// /// <!-- inputs/outputs --> /// @param val n/a /// extern "C" inline void bf_tls_set_r15_impl(bsl::uint64 const val) noexcept { g_mut_data.at("bf_tls_r15") = val; } /// <!-- description --> /// @brief Implements the ABI for bf_tls_extid. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_extid_impl() noexcept -> bsl::uint16 { return bsl::to_u16(g_mut_data.at("bf_tls_extid")).get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_vmid. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_vmid_impl() noexcept -> bsl::uint16 { return bsl::to_u16(g_mut_data.at("bf_tls_vmid")).get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_vpid. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_vpid_impl() noexcept -> bsl::uint16 { return bsl::to_u16(g_mut_data.at("bf_tls_vpid")).get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_vsid. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_vsid_impl() noexcept -> bsl::uint16 { return bsl::to_u16(g_mut_data.at("bf_tls_vsid")).get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_ppid. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_ppid_impl() noexcept -> bsl::uint16 { return bsl::to_u16(g_mut_data.at("bf_tls_ppid")).get(); } /// <!-- description --> /// @brief Implements the ABI for bf_tls_online_pps. /// /// <!-- inputs/outputs --> /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_tls_online_pps_impl() noexcept -> bsl::uint16 { return bsl::to_u16(g_mut_data.at("bf_tls_online_pps")).get(); } // ------------------------------------------------------------------------- // bf_control_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_control_op_exit. /// extern "C" inline void bf_control_op_exit_impl() noexcept { g_mut_bf_control_op_exit_impl_executed = true; } /// <!-- description --> /// @brief Implements the ABI for bf_control_op_wait. /// extern "C" inline void bf_control_op_wait_impl() noexcept { g_mut_bf_control_op_wait_impl_executed = true; } /// <!-- description --> /// @brief Implements the ABI for bf_control_op_again. /// extern "C" inline void bf_control_op_again_impl() noexcept { g_mut_bf_control_op_again_impl_executed = true; } // ------------------------------------------------------------------------- // bf_handle_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_handle_op_open_handle. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_handle_op_open_handle_impl( bsl::uint32 const reg0_in, bsl::uint64 *const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_handle_op_open_handle_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = g_mut_data.at("bf_handle_op_open_handle_impl_reg0_out").get(); } else { bsl::touch(); } return g_mut_errc.at("bf_handle_op_open_handle_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_handle_op_close_handle. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_handle_op_close_handle_impl(bsl::uint64 const reg0_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); return g_mut_errc.at("bf_handle_op_close_handle_impl").get(); } // ------------------------------------------------------------------------- // bf_debug_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_out. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// extern "C" inline void bf_debug_op_out_impl(bsl::uint64 const reg0_in, bsl::uint64 const reg1_in) noexcept { g_mut_bf_debug_op_out_impl_executed = true; // NOLINTNEXTLINE(bsl-function-name-use) std::cout << std::hex << "0x" << reg0_in << " 0x" << reg1_in << '\n'; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_vm. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// extern "C" inline void bf_debug_op_dump_vm_impl(bsl::uint16 const reg0_in) noexcept { g_mut_bf_debug_op_dump_vm_impl_executed = true; // NOLINTNEXTLINE(bsl-function-name-use) std::cout << std::hex << "vm [0x" << reg0_in << "] dump: mock empty\n"; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_vp. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// extern "C" inline void bf_debug_op_dump_vp_impl(bsl::uint16 const reg0_in) noexcept { g_mut_bf_debug_op_dump_vp_impl_executed = true; // NOLINTNEXTLINE(bsl-function-name-use) std::cout << std::hex << "vp [0x" << reg0_in << "] dump: mock empty\n"; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_vs. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// extern "C" inline void bf_debug_op_dump_vs_impl(bsl::uint16 const reg0_in) noexcept { g_mut_bf_debug_op_dump_vs_impl_executed = true; // NOLINTNEXTLINE(bsl-function-name-use) std::cout << std::hex << "vs [0x" << reg0_in << "] dump: mock empty\n"; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_vmexit_log. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// extern "C" inline void bf_debug_op_dump_vmexit_log_impl(bsl::uint16 const reg0_in) noexcept { g_mut_bf_debug_op_dump_vmexit_log_impl_executed = true; // NOLINTNEXTLINE(bsl-function-name-use) std::cout << std::hex << "vmexit log for pp [0x" << reg0_in << "]: mock empty\n"; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_write_c. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// extern "C" inline void bf_debug_op_write_c_impl(bsl::char_type const reg0_in) noexcept { g_mut_bf_debug_op_write_c_impl_executed = true; std::cout << reg0_in; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_write_str. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// extern "C" inline void bf_debug_op_write_str_impl( bsl::char_type const *const reg0_in, bsl::uintmx const reg1_in) noexcept { g_mut_bf_debug_op_write_str_impl_executed = true; std::cout << std::string_view{reg0_in, reg1_in}; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_ext. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// extern "C" inline void bf_debug_op_dump_ext_impl(bsl::uint16 const reg0_in) noexcept { g_mut_bf_debug_op_dump_ext_impl_executed = true; // NOLINTNEXTLINE(bsl-function-name-use) std::cout << std::hex << "ext [0x" << reg0_in << "] dump: mock empty\n"; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_page_pool. /// extern "C" inline void bf_debug_op_dump_page_pool_impl() noexcept { g_mut_bf_debug_op_dump_page_pool_impl_executed = true; std::cout << "page pool dump: mock empty\n"; } /// <!-- description --> /// @brief Implements the ABI for bf_debug_op_dump_huge_pool. /// extern "C" inline void bf_debug_op_dump_huge_pool_impl() noexcept { g_mut_bf_debug_op_dump_huge_pool_impl_executed = true; std::cout << "huge pool dump: mock empty\n"; } // ------------------------------------------------------------------------- // bf_callback_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_callback_op_register_bootstrap. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param pmut_reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_callback_op_register_bootstrap_impl( bsl::uint64 const reg0_in, bf_callback_handler_bootstrap_t const pmut_reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(pmut_reg1_in); return g_mut_errc.at("bf_callback_op_register_bootstrap_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_callback_op_register_vmexit. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param pmut_reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_callback_op_register_vmexit_impl( bsl::uint64 const reg0_in, bf_callback_handler_vmexit_t const pmut_reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(pmut_reg1_in); return g_mut_errc.at("bf_callback_op_register_vmexit_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_callback_op_register_fail. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param pmut_reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_callback_op_register_fail_impl( bsl::uint64 const reg0_in, bf_callback_handler_fail_t const pmut_reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(pmut_reg1_in); return g_mut_errc.at("bf_callback_op_register_fail_impl").get(); } // ------------------------------------------------------------------------- // bf_vm_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_vm_op_create_vm. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vm_op_create_vm_impl(bsl::uint64 const reg0_in, bsl::uint16 *const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_vm_op_create_vm_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = bsl::to_u16(g_mut_data.at("bf_vm_op_create_vm_impl_reg0_out")).get(); } else { bsl::touch(); } return g_mut_errc.at("bf_vm_op_create_vm_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vm_op_destroy_vm. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vm_op_destroy_vm_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vm_op_destroy_vm_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vm_op_map_direct. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vm_op_map_direct_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint64 const reg2_in, void **const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); bsl::discard(pmut_reg0_out); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_vm_op_map_direct_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = g_mut_ptrs.at("bf_vm_op_map_direct_impl_reg0_out"); } else { bsl::touch(); } return g_mut_errc.at("bf_vm_op_map_direct_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vm_op_unmap_direct. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vm_op_unmap_direct_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint64 const reg2_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); return g_mut_errc.at("bf_vm_op_unmap_direct_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vm_op_unmap_direct_broadcast. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vm_op_unmap_direct_broadcast_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint64 const reg2_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); return g_mut_errc.at("bf_vm_op_unmap_direct_broadcast_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vm_op_tlb_flush. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vm_op_tlb_flush_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vm_op_tlb_flush_impl").get(); } // ------------------------------------------------------------------------- // bf_vp_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_vp_op_create_vp. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vp_op_create_vp_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 *const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_vp_op_create_vp_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = bsl::to_u16(g_mut_data.at("bf_vp_op_create_vp_impl_reg0_out")).get(); } else { bsl::touch(); } return g_mut_errc.at("bf_vp_op_create_vp_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vp_op_destroy_vp. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vp_op_destroy_vp_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vp_op_destroy_vp_impl").get(); } // ------------------------------------------------------------------------- // bf_vs_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_create_vs. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_create_vs_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 const reg2_in, bsl::uint16 *const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_vs_op_create_vs_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = bsl::to_u16(g_mut_data.at("bf_vs_op_create_vs_impl_reg0_out")).get(); } else { bsl::touch(); } return g_mut_errc.at("bf_vs_op_create_vs_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_destroy_vs. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_destroy_vs_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vs_op_destroy_vs_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_init_as_root. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_init_as_root_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vs_op_init_as_root_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_read_impl. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_read_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bf_reg_t const reg2_in, bsl::uint64 *const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_vs_op_read_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = g_mut_data.at("bf_vs_op_read_impl_reg0_out").get(); } else { bsl::touch(); } return g_mut_errc.at("bf_vs_op_read_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_write. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param reg3_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_write_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bf_reg_t const reg2_in, bsl::uint64 const reg3_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); if (g_mut_errc.at("bf_vs_op_write_impl") == BF_STATUS_SUCCESS) { g_mut_data.at("bf_vs_op_write_impl") = reg3_in; } else { bsl::touch(); } return g_mut_errc.at("bf_vs_op_write_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_run. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param reg3_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_run_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 const reg2_in, bsl::uint16 const reg3_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); bsl::discard(reg3_in); return g_mut_errc.at("bf_vs_op_run_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_run_current. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_run_current_impl(bsl::uint64 const reg0_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); return g_mut_errc.at("bf_vs_op_run_current_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_advance_ip_and_run_impl. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param reg3_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_advance_ip_and_run_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 const reg2_in, bsl::uint16 const reg3_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); bsl::discard(reg3_in); return g_mut_errc.at("bf_vs_op_advance_ip_and_run_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_advance_ip_and_run_current. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_advance_ip_and_run_current_impl(bsl::uint64 const reg0_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); return g_mut_errc.at("bf_vs_op_advance_ip_and_run_current_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_promote. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_promote_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vs_op_promote_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_clear. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_clear_impl(bsl::uint64 const reg0_in, bsl::uint16 const reg1_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); return g_mut_errc.at("bf_vs_op_clear_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_migrate. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_migrate_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 const reg2_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); return g_mut_errc.at("bf_vs_op_migrate_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_set_active. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param reg3_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_set_active_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 const reg2_in, bsl::uint16 const reg3_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); bsl::discard(reg3_in); return g_mut_errc.at("bf_vs_op_set_active_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_advance_ip_and_set_active. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @param reg3_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_advance_ip_and_set_active_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint16 const reg2_in, bsl::uint16 const reg3_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); bsl::discard(reg3_in); return g_mut_errc.at("bf_vs_op_advance_ip_and_set_active_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_vs_op_tlb_flush. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_vs_op_tlb_flush_impl( bsl::uint64 const reg0_in, bsl::uint16 const reg1_in, bsl::uint64 const reg2_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); bsl::discard(reg2_in); return g_mut_errc.at("bf_vs_op_tlb_flush_impl").get(); } // ------------------------------------------------------------------------- // bf_intrinsic_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_intrinsic_op_rdmsr. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param pmut_reg0_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_intrinsic_op_rdmsr_impl( bsl::uint64 const reg0_in, bsl::uint32 const reg1_in, bsl::uint64 *const pmut_reg0_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_intrinsic_op_rdmsr_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = g_mut_data.at("bf_intrinsic_op_rdmsr_impl_reg0_out").get(); } else { bsl::touch(); } return g_mut_errc.at("bf_intrinsic_op_rdmsr_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_intrinsic_op_wrmsr. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param reg2_in n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_intrinsic_op_wrmsr_impl( bsl::uint64 const reg0_in, bsl::uint32 const reg1_in, bsl::uint64 const reg2_in) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); if (g_mut_errc.at("bf_intrinsic_op_wrmsr_impl") == BF_STATUS_SUCCESS) { g_mut_data.at("bf_intrinsic_op_wrmsr_impl") = reg2_in; } else { bsl::touch(); } return g_mut_errc.at("bf_intrinsic_op_wrmsr_impl").get(); } // ------------------------------------------------------------------------- // bf_mem_ops // ------------------------------------------------------------------------- /// <!-- description --> /// @brief Implements the ABI for bf_mem_op_alloc_page. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param pmut_reg0_out n/a /// @param pmut_reg1_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_mem_op_alloc_page_impl( bsl::uint64 const reg0_in, void **const pmut_reg0_out, bsl::uint64 *const pmut_reg1_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (bsl::unlikely(nullptr == pmut_reg1_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_mem_op_alloc_page_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = g_mut_ptrs.at("bf_mem_op_alloc_page_impl_reg0_out"); *pmut_reg1_out = g_mut_data.at("bf_mem_op_alloc_page_impl_reg1_out").get(); } else { bsl::touch(); } return g_mut_errc.at("bf_mem_op_alloc_page_impl").get(); } /// <!-- description --> /// @brief Implements the ABI for bf_mem_op_alloc_huge. /// /// <!-- inputs/outputs --> /// @param reg0_in n/a /// @param reg1_in n/a /// @param pmut_reg0_out n/a /// @param pmut_reg1_out n/a /// @return n/a /// extern "C" [[nodiscard]] inline auto bf_mem_op_alloc_huge_impl( bsl::uint64 const reg0_in, bsl::uint64 const reg1_in, void **const pmut_reg0_out, bsl::uint64 *const pmut_reg1_out) noexcept -> bsl::uint64 { bsl::discard(reg0_in); bsl::discard(reg1_in); if (bsl::unlikely(nullptr == pmut_reg0_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (bsl::unlikely(nullptr == pmut_reg1_out)) { return BF_STATUS_FAILURE_UNKNOWN.get(); } if (g_mut_errc.at("bf_mem_op_alloc_huge_impl") == BF_STATUS_SUCCESS) { *pmut_reg0_out = g_mut_ptrs.at("bf_mem_op_alloc_huge_impl_reg0_out"); *pmut_reg1_out = g_mut_data.at("bf_mem_op_alloc_huge_impl_reg1_out").get(); } else { bsl::touch(); } return g_mut_errc.at("bf_mem_op_alloc_huge_impl").get(); } } #endif
22,307
505
package sample; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.List; import org.junit.Test; public class SampleTest { @Test public void testLists() { List<String> stringList = Arrays.asList("java", "jdk", "jre"); assertThat(stringList, hasItem("java")); assertThat(stringList, hasItems("java", "jdk")); assertThat(stringList, everyItem(containsString("j"))); } @Test public void testWithHamcrest() { String result = "HelloWorld!"; assertThat(result, is("HelloWorld!")); } }
306
3,058
<filename>Common_3/ThirdParty/OpenSource/TaskScheduler/Scheduler/Include/MTConfig.h // The MIT License (MIT) // // Copyright (c) 2015 <NAME>, <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #pragma once // Target Platform //////////////////////////////////////////////////////////////////////// #if defined(_DURANGO) || defined(_GAMING_XBOX) #define MT_PLATFORM_DURANGO (1) #elif defined(__ORBIS__) #define MT_PLATFORM_ORBIS (1) #elif defined(_WIN32) #define MT_PLATFORM_WINDOWS (1) #elif defined(__APPLE__) #define MT_PLATFORM_OSX (1) #elif defined(NX64) #define MT_PLATFORM_NX64 (1) #else #define MT_PLATFORM_POSIX (1) #endif // Compiler support for SSE intrinsics //////////////////////////////////////////////////////////////////////// #if (defined(__SSE__) || defined(_M_IX86) || defined(_M_X64)) && !defined(__aarch64__) #define MT_SSE_INTRINSICS_SUPPORTED (1) #endif // Compiler support for C++11 //////////////////////////////////////////////////////////////////////// #if __STDC_VERSION__ >= 201112L #define MT_CPP11_SUPPORTED (1) #endif // Compiler family //////////////////////////////////////////////////////////////////////// #ifdef __clang__ #define MT_CLANG_COMPILER_FAMILY (1) #define MT_GCC_COMPILER_FAMILY (1) #elif __GNUC__ #define MT_GCC_COMPILER_FAMILY (1) #elif defined(_MSC_VER) #define MT_MSVC_COMPILER_FAMILY (1) #endif // Debug / Release //////////////////////////////////////////////////////////////////////// #if defined(_DEBUG) || defined(DEBUG) #define MT_DEBUG (1) #else #define MT_RELEASE (1) #endif // x64 / x86 //////////////////////////////////////////////////////////////////////// #if defined(_M_X64) #define MT_PTR64 (1) #endif // // x86-64 CPU has strong memory model, so we don't need to define acquire/release fences here // // // Acquire semantics is a property which can only apply to operations which read from shared memory, // whether they are read-modify-write operations or plain loads. The operation is then considered a read-acquire. // Acquire semantics prevent memory reordering of the read-acquire with any read or write operation which follows it in program order. // // Acquire fence is a fence which does not permit subsequent memory operations to be advanced before it. // #if MT_MSVC_COMPILER_FAMILY // MSVC compiler barrier #define mt_acquire_fence() _ReadWriteBarrier() #elif MT_GCC_COMPILER_FAMILY // GCC compiler barrier #define mt_acquire_fence() asm volatile("" ::: "memory") #else #error Platform is not supported! #endif // // Release semantics is a property which can only apply to operations which write to shared memory, // whether they are read-modify-write operations or plain stores. The operation is then considered a write-release. // Release semantics prevent memory reordering of the write-release with any read or write operation which precedes it in program order. // // Release fence is a fence which does not permit preceding memory operations to be delayed past it. // #if MT_MSVC_COMPILER_FAMILY // MSVC compiler barrier #define mt_release_fence() _ReadWriteBarrier() #elif MT_GCC_COMPILER_FAMILY // GCC compiler barrier #define mt_release_fence() asm volatile("" ::: "memory") #else #error Platform is not supported! #endif // // mt_forceinline // #if MT_MSVC_COMPILER_FAMILY #define mt_forceinline __forceinline #elif MT_GCC_COMPILER_FAMILY #define mt_forceinline __attribute__((always_inline)) inline #else #error Can not define mt_forceinline. Unknown platform. #endif // Enable Windows XP support (disable conditional variables) //#if !MT_PTR64 && MT_PLATFORM_WINDOWS //#define MT_ENABLE_LEGACY_WINDOWSXP_SUPPORT (1) //#endif
1,454
2,053
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package scouterx.webapp.framework.exception; import lombok.Getter; import javax.ws.rs.core.Response; /** * Created by <NAME>(<EMAIL>) on 2017. 8. 25. */ @Getter public enum ErrorState { //For System SESSION_CLOSED(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "internal server error"), CLIENT_SOCKET_CLOSED(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "internal server error"), //For User INTERNAL_SERVER_ERROR(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "internal server error"), COLLECTOR_NOT_CONNECTED(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "scouter collector not connected"), COLLECTOR_INVALID_SESSION(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "internal server error"), ILLEGAL_KEY_ACCESS(Response.Status.BAD_REQUEST, Response.Status.BAD_REQUEST.getStatusCode(), "illegal key access error"), LOGIN_REQUIRED(Response.Status.UNAUTHORIZED, Response.Status.UNAUTHORIZED.getStatusCode(), "login required."), LOGIN_FAIL(Response.Status.NOT_FOUND, Response.Status.NOT_FOUND.getStatusCode(), "id or password is incorrect."), SESSION_EXPIRED(Response.Status.UNAUTHORIZED, Response.Status.UNAUTHORIZED.getStatusCode(), "authorization token or session is expired."), NOT_IMPLEMENTED(Response.Status.NOT_IMPLEMENTED, Response.Status.NOT_IMPLEMENTED.getStatusCode(), "This API is not yet implemented."), VALIDATE_ERROR(Response.Status.BAD_REQUEST, Response.Status.BAD_REQUEST.getStatusCode(), "fail to validate input parameters. : "), ; private final Response.Status status; private final int errorCode; private final String errorMessage; ErrorState(Response.Status status, int errorCode, String errorMessage) { this.status = status; this.errorCode = errorCode; this.errorMessage = errorMessage; } public ErrorStateException newException() { return new ErrorStateException(this); } public ErrorStateException newException(String message) { return new ErrorStateException(this, message); } public ErrorStateException newException(String message, Throwable t) { return new ErrorStateException(this, message, t); } public ErrorStateBizException newBizException() { return new ErrorStateBizException(this); } public ErrorStateBizException newBizException(String message) { return new ErrorStateBizException(this, message); } public ErrorStateBizException newBizException(String message, Throwable t) { return new ErrorStateBizException(this, message, t); } public static void throwNotImplementedException() { throw NOT_IMPLEMENTED.newBizException(); } }
1,059
595
<filename>lib/bsp/standalone/src/arm/cortexr5/xil_cache.h /****************************************************************************** * Copyright (c) 2014 - 2021 Xilinx, Inc. All rights reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ /*****************************************************************************/ /** * * @file xil_cache.h * * @addtogroup r5_cache_apis Cortex R5 Processor Cache Functions * * Cache functions provide access to cache related operations such as flush * and invalidate for instruction and data caches. It gives option to perform * the cache operations on a single cacheline, a range of memory and an entire * cache. * * @{ * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ----------------------------------------------- * 5.00 pkp 02/20/14 First release * 6.2 mus 01/27/17 Updated to support IAR compiler * </pre> * ******************************************************************************/ #ifndef XIL_CACHE_H #define XIL_CACHE_H #include "xil_types.h" #ifdef __cplusplus extern "C" { #endif /** *@cond nocomments */ #if defined (__GNUC__) #define asm_inval_dc_line_mva_poc(param) __asm__ __volatile__("mcr " \ XREG_CP15_INVAL_DC_LINE_MVA_POC :: "r" (param)) #define asm_clean_inval_dc_line_sw(param) __asm__ __volatile__("mcr " \ XREG_CP15_CLEAN_INVAL_DC_LINE_SW :: "r" (param)) #define asm_clean_inval_dc_line_mva_poc(param) __asm__ __volatile__("mcr " \ XREG_CP15_CLEAN_INVAL_DC_LINE_MVA_POC :: "r" (param)) #define asm_inval_ic_line_mva_pou(param) __asm__ __volatile__("mcr " \ XREG_CP15_INVAL_IC_LINE_MVA_POU :: "r" (param)) #elif defined (__ICCARM__) #define asm_inval_dc_line_mva_poc(param) __asm volatile("mcr " \ XREG_CP15_INVAL_DC_LINE_MVA_POC :: "r" (param)) #define asm_clean_inval_dc_line_sw(param) __asm volatile("mcr " \ XREG_CP15_CLEAN_INVAL_DC_LINE_SW :: "r" (param)) #define asm_clean_inval_dc_line_mva_poc(param) __asm volatile("mcr " \ XREG_CP15_CLEAN_INVAL_DC_LINE_MVA_POC :: "r" (param)) #define asm_inval_ic_line_mva_pou(param) __asm volatile("mcr " \ XREG_CP15_INVAL_IC_LINE_MVA_POU :: "r" (param)) #endif /** *@endcond */ void Xil_DCacheEnable(void); void Xil_DCacheDisable(void); void Xil_DCacheInvalidate(void); void Xil_DCacheInvalidateRange(INTPTR adr, u32 len); void Xil_DCacheFlush(void); void Xil_DCacheFlushRange(INTPTR adr, u32 len); void Xil_DCacheInvalidateLine(INTPTR adr); void Xil_DCacheFlushLine(INTPTR adr); void Xil_DCacheStoreLine(INTPTR adr); void Xil_ICacheEnable(void); void Xil_ICacheDisable(void); void Xil_ICacheInvalidate(void); void Xil_ICacheInvalidateRange(INTPTR adr, u32 len); void Xil_ICacheInvalidateLine(INTPTR adr); #ifdef __cplusplus } #endif #endif /** * @} End of "addtogroup r5_cache_apis". */
1,096
5,169
{ "name": "open-ecard", "version": "2.1.1-rc.2", "summary": "ecard framework", "description": "Open source framework implementing the eCard-API-Framework (BSI-TR-03112) through which arbitrary applications can utilize authentication and signatures with arbitrary chip cards", "homepage": "https://dev.openecard.org", "authors": { "Name": "<EMAIL>" }, "license": { "type": "GPLv3", "file": "LICENSE" }, "source": { "http": "https://github.com/ecsec/open-ecard/releases/download/2.1.1-rc.2/OpenEcard-CocoaPod.zip" }, "platforms": { "ios": "13.0" }, "ios": { "vendored_frameworks": "OpenEcard.framework" } }
260
6,989
/* * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "eng_local.h" #include <openssl/evp.h> static ENGINE_TABLE *pkey_meth_table = NULL; void ENGINE_unregister_pkey_meths(ENGINE *e) { engine_table_unregister(&pkey_meth_table, e); } static void engine_unregister_all_pkey_meths(void) { engine_table_cleanup(&pkey_meth_table); } int ENGINE_register_pkey_meths(ENGINE *e) { if (e->pkey_meths) { const int *nids; int num_nids = e->pkey_meths(e, NULL, &nids, 0); if (num_nids > 0) return engine_table_register(&pkey_meth_table, engine_unregister_all_pkey_meths, e, nids, num_nids, 0); } return 1; } void ENGINE_register_all_pkey_meths(void) { ENGINE *e; for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) ENGINE_register_pkey_meths(e); } int ENGINE_set_default_pkey_meths(ENGINE *e) { if (e->pkey_meths) { const int *nids; int num_nids = e->pkey_meths(e, NULL, &nids, 0); if (num_nids > 0) return engine_table_register(&pkey_meth_table, engine_unregister_all_pkey_meths, e, nids, num_nids, 1); } return 1; } /* * Exposed API function to get a functional reference from the implementation * table (ie. try to get a functional reference from the tabled structural * references) for a given pkey_meth 'nid' */ ENGINE *ENGINE_get_pkey_meth_engine(int nid) { return engine_table_select(&pkey_meth_table, nid); } /* Obtains a pkey_meth implementation from an ENGINE functional reference */ const EVP_PKEY_METHOD *ENGINE_get_pkey_meth(ENGINE *e, int nid) { EVP_PKEY_METHOD *ret; ENGINE_PKEY_METHS_PTR fn = ENGINE_get_pkey_meths(e); if (!fn || !fn(e, &ret, NULL, nid)) { ENGINEerr(ENGINE_F_ENGINE_GET_PKEY_METH, ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD); return NULL; } return ret; } /* Gets the pkey_meth callback from an ENGINE structure */ ENGINE_PKEY_METHS_PTR ENGINE_get_pkey_meths(const ENGINE *e) { return e->pkey_meths; } /* Sets the pkey_meth callback in an ENGINE structure */ int ENGINE_set_pkey_meths(ENGINE *e, ENGINE_PKEY_METHS_PTR f) { e->pkey_meths = f; return 1; } /* * Internal function to free up EVP_PKEY_METHOD structures before an ENGINE * is destroyed */ void engine_pkey_meths_free(ENGINE *e) { int i; EVP_PKEY_METHOD *pkm; if (e->pkey_meths) { const int *pknids; int npknids; npknids = e->pkey_meths(e, NULL, &pknids, 0); for (i = 0; i < npknids; i++) { if (e->pkey_meths(e, &pkm, NULL, pknids[i])) { EVP_PKEY_meth_free(pkm); } } } }
1,516
1,676
<filename>chat-sdk-core/src/main/java/sdk/chat/core/types/ReadStatus.java package sdk.chat.core.types; /** * Created by ben on 10/5/17. */ public class ReadStatus { public static int Hide = -2; public static int None = 0; public static int Delivered = 1; public static int Read = 2; private int status; public static ReadStatus hide() { return new ReadStatus(Hide); } public static ReadStatus none() { return new ReadStatus(None); } public static ReadStatus delivered() { return new ReadStatus(Delivered); } public static ReadStatus read () { return new ReadStatus(Read); } public ReadStatus (int status) { this.status = status; } public int getValue() { return status; } public boolean is (ReadStatus status) { return status.getValue() == getValue(); } public boolean is (ReadStatus... statuses) { for (ReadStatus status: statuses) { if (is(status)) { return true; } } return false; } }
448
435
{ "description": "", "duration": 1531, "language": "lit", "recorded": "2015-06-11", "speakers": [ "<NAME>\u016bnas" ], "thumbnail_url": "https://i.ytimg.com/vi/3_1_GZaXvY0/hqdefault.jpg", "title": "Apache Mesos ir artimos ateities python aplikacijos", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=3_1_GZaXvY0" } ] }
189
348
<filename>docs/data/leg-t2/074/07403278.json {"nom":"Thyez","circ":"3ème circonscription","dpt":"Haute-Savoie","inscrits":3925,"abs":2411,"votants":1514,"blancs":147,"nuls":0,"exp":1367,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":700},{"nuance":"REM","nom":"M. <NAME>","voix":667}]}
121
14,668
<reponame>zealoussnow/chromium // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_AUDIO_TEST_MOCK_LOG_H_ #define SERVICES_AUDIO_TEST_MOCK_LOG_H_ #include <string> #include "base/bind.h" #include "media/base/audio_parameters.h" #include "media/mojo/mojom/audio_logging.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gmock/include/gmock/gmock.h" namespace audio { class MockLog : public media::mojom::AudioLog { public: MockLog(); MockLog(const MockLog&) = delete; MockLog& operator=(const MockLog&) = delete; ~MockLog() override; // Should only be called once. mojo::PendingRemote<media::mojom::AudioLog> MakeRemote() { mojo::PendingRemote<media::mojom::AudioLog> remote; receiver_.Bind(remote.InitWithNewPipeAndPassReceiver()); receiver_.set_disconnect_handler(base::BindOnce( &MockLog::BindingConnectionError, base::Unretained(this))); return remote; } void CloseBinding() { receiver_.reset(); } MOCK_METHOD2(OnCreated, void(const media::AudioParameters& params, const std::string& device_id)); MOCK_METHOD0(OnStarted, void()); MOCK_METHOD0(OnStopped, void()); MOCK_METHOD0(OnClosed, void()); MOCK_METHOD0(OnError, void()); MOCK_METHOD1(OnSetVolume, void(double)); MOCK_METHOD1(OnProcessingStateChanged, void(const std::string&)); MOCK_METHOD1(OnLogMessage, void(const std::string&)); MOCK_METHOD0(BindingConnectionError, void()); private: mojo::Receiver<media::mojom::AudioLog> receiver_; }; } // namespace audio #endif // SERVICES_AUDIO_TEST_MOCK_LOG_H_
660
350
package ar.rulosoft.custompref; /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created by Johndeep on 22.08.15. */ import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import ar.rulosoft.mimanganu.R; public class ArrayAdapterDirectory extends ArrayAdapter<String> { private final Context mContext; private final ArrayList<String> mList; private final int mResource; static class ViewHolder { public LinearLayout object; public TextView text; public ImageView image; } public ArrayAdapterDirectory(Context context, int resource, ArrayList<String> itemList) { super(context, resource, itemList); this.mContext = context; this.mList = itemList; this.mResource = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; // reuse views if (rowView == null) { LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); rowView = inflater.inflate(this.mResource, null); // configure view holder ViewHolder viewHolder = new ViewHolder(); viewHolder.object = rowView.findViewById(R.id.dirObject); viewHolder.image = rowView.findViewById(R.id.dirIcon); viewHolder.text = rowView.findViewById(R.id.dirText); rowView.setTag(viewHolder); } // fill data ViewHolder holder = (ViewHolder) rowView.getTag(); if (position % 2 == 0) { holder.object.setBackgroundColor(0x10121212); } else { holder.object.setBackgroundColor(0); } holder.text.setText(mList.get(position)); holder.image.setImageResource(R.drawable.ic_folder); holder.image.setColorFilter(0xFF545454); return rowView; } }
997
416
// HMEvent.h // HomeKit // // Copyright (c) 2015 Apple Inc. All rights reserved. #import <Foundation/Foundation.h> @class HMHome; NS_ASSUME_NONNULL_BEGIN /*! * @brief This class is used to represent a generic HomeKit event. */ NS_CLASS_AVAILABLE_IOS(9_0) __WATCHOS_AVAILABLE(2_0) __TVOS_AVAILABLE(10_0) @interface HMEvent : NSObject /*! * @brief A unique identifier for the event. */ @property(readonly, copy, nonatomic) NSUUID *uniqueIdentifier; /*! * @brief Specifies whether the HMEvent can be added to HMEventTrigger on the given home. */ + (BOOL)isSupportedForHome:(HMHome *)home API_AVAILABLE(ios(11.0), watchos(4.0), tvos(11.0)); @end NS_ASSUME_NONNULL_END
261
380
<filename>Classes/UVHelpTopicViewController.h // // UVHelpTopicViewController.h // UserVoice // // Created by <NAME> on 11/16/12. // Copyright (c) 2012 UserVoice Inc. All rights reserved. // #import "UVBaseViewController.h" @class UVHelpTopic; @interface UVHelpTopicViewController : UVBaseViewController<UITableViewDataSource,UITableViewDelegate> @property (nonatomic, retain) UVHelpTopic *topic; - (id)initWithTopic:(UVHelpTopic *)theTopic; @end
152
398
package com.ruiyun.example; import com.ruiyun.jvppeteer.core.Puppeteer; import com.ruiyun.jvppeteer.core.browser.Browser; import com.ruiyun.jvppeteer.core.browser.BrowserFetcher; import com.ruiyun.jvppeteer.core.page.ElementHandle; import com.ruiyun.jvppeteer.core.page.JSHandle; import com.ruiyun.jvppeteer.core.page.Page; import com.ruiyun.jvppeteer.core.page.PageExtend; import com.ruiyun.jvppeteer.options.LaunchOptions; import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder; import org.junit.Test; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; public class PageExtendExample { @Test public void test1() throws Exception { //自动下载,第一次下载后不会再下载 BrowserFetcher.downloadIfNotExist(null); LaunchOptions launchOptions = new LaunchOptionsBuilder().withIgnoreDefaultArgs(Arrays.asList("--enable-automation")).withHeadless(false).build(); Browser browser = Puppeteer.launch(launchOptions); Page page = browser.newPage(); page.goTo("https://www.baidu.com"); ElementHandle ele1 = PageExtend.byId(page, "s_tab"); ElementHandle ele2 = PageExtend.byClass(page, "s_tab"); ElementHandle ele3 = PageExtend.byTag(page, "a"); List<ElementHandle> eleList1 = PageExtend.byTagList(page, "a"); String html = PageExtend.html(page); browser.close(); } }
583
1,350
[{"id":"FSRB","type":"radio","calc":false,"value":"FS1"},{"id":"FSRB","type":"radio","calc":false,"value":"FS2"},{"id":"FSRB","type":"radio","calc":false,"value":"FS3"},{"id":"FSRB","type":"radio","calc":false,"value":"FS4"},{"id":"FSRB","type":"radio","calc":false,"value":"FS5"},{"id":"L9AX","type":"box","calc":false,"value":""},{"id":"L10AX","type":"box","calc":false,"value":""},{"id":"L15AX","type":"box","calc":false,"value":""},{"id":"L17AX","type":"box","calc":false,"value":""},{"id":"NAME","type":"alpha","calc":true,"value":""},{"id":"SSN","type":"ssn","calc":true,"value":""},{"id":"PNAM","type":"alpha","calc":false,"value":""},{"id":"PMI","type":"mask","calc":false,"value":""},{"id":"PLNM","type":"alpha","calc":false,"value":""},{"id":"PSFX","type":"alpha","calc":false,"value":""},{"id":"PSSN","type":"ssn","calc":false,"value":""},{"id":"LCW","type":"alpha","calc":false,"value":""},{"id":"L1","type":"number","calc":false,"value":""},{"id":"L2","type":"number","calc":false,"value":""},{"id":"L3","type":"number","calc":true,"value":""},{"id":"L4","type":"number","calc":false,"value":""},{"id":"L5","type":"number","calc":true,"value":""},{"id":"L6","type":"number","calc":false,"value":""},{"id":"L7","type":"number","calc":false,"value":""},{"id":"L8","type":"number","calc":true,"value":""},{"id":"L9","type":"number","calc":false,"value":""},{"id":"L10","type":"number","calc":false,"value":""},{"id":"L11","type":"number","calc":true,"value":""},{"id":"L12A","type":"number","calc":true,"value":""},{"id":"L12B","type":"percent","calc":true,"value":""},{"id":"L13","type":"number","calc":true,"value":""},{"id":"L14","type":"number","calc":true,"value":""},{"id":"L15","type":"number","calc":false,"value":""},{"id":"L16","type":"number","calc":true,"value":""},{"id":"L17","type":"number","calc":false,"value":""},{"id":"L18","type":"number","calc":true,"value":""}]
602
460
<reponame>MarianMacik/thorntail<filename>fractions/netflix/archaius/src/main/java/org/wildfly/swarm/netflix/archaius/runtime/ArchaiusCustomizer.java package org.wildfly.swarm.netflix.archaius.runtime; import java.util.HashSet; import java.util.Set; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.inject.Inject; import com.netflix.config.ConfigurationManager; import org.apache.commons.configuration.AbstractConfiguration; import org.wildfly.swarm.container.runtime.ConfigurableHandle; import org.wildfly.swarm.container.runtime.ConfigurableManager; import org.wildfly.swarm.spi.api.Customizer; import org.wildfly.swarm.spi.api.config.ConfigKey; import org.wildfly.swarm.spi.runtime.annotations.Post; /** * @author <NAME> */ @Post @ApplicationScoped public class ArchaiusCustomizer implements Customizer { @Inject ConfigurableManager configurableManager; @Inject @Any Instance<ArchaiusLinkage> links; Set<String> linkable = new HashSet<>(); @PostConstruct protected void buildLinkNameSet() { for (ArchaiusLinkage link : this.links) { this.linkable.add(link.name() + "."); } } @Override public void customize() { AbstractConfiguration config = ConfigurationManager.getConfigInstance(); Set<ConfigKey> seen = new HashSet<>(); this.configurableManager.configurables().stream() .filter(this::shouldLink) .forEach(e -> { try { Object value = e.currentValue(); if (value != null) { config.setProperty(e.key().subkey(1).name(), e.currentValue()); } seen.add(e.key()); } catch (Exception ex) { throw new RuntimeException(ex); } }); this.configurableManager.configView().allKeysRecursively() .filter(this::shouldLink) .filter(k -> !seen.contains(k)) .forEach(k -> { Object value = this.configurableManager.configView().valueOf(k); if (value != null) { config.setProperty(k.subkey(1).name(), value); } }); } protected boolean shouldLink(ConfigKey key) { if (!key.head().name().equals("thorntail")) { return false; } return linkable.stream().anyMatch(e -> key.subkey(1).name().startsWith(e)); } protected boolean shouldLink(ConfigurableHandle configurable) { return shouldLink(configurable.key()); } }
1,257
594
<reponame>pmp-p/vmir /* This program tests a data flow bug that would cause constant propagation to propagate constants through function calls. */ foo (int *p) { *p = 10; } main() { int *ptr = alloca (sizeof (int)); *ptr = 5; foo (ptr); if (*ptr == 5) abort (); exit (0); }
113
307
<filename>src/test/java/com/appslandia/common/cdi/CDIExtensionTest.java // The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.common.cdi; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Set; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.inject.Qualifier; import org.junit.Assert; import org.junit.Test; import com.appslandia.common.utils.CollectionUtils; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> * */ public class CDIExtensionTest { @Test public void test_willExcludeClasses() { Set<Class<?>> excludedClasses = CollectionUtils.toSet(UserService.class); boolean excluded = CDIExtension.willExcludeClasses(excludedClasses, UserService.class); Assert.assertTrue(excluded); excluded = CDIExtension.willExcludeClasses(excludedClasses, UserServiceWithQualifier.class); Assert.assertFalse(excluded); excluded = CDIExtension.willExcludeClasses(excludedClasses, UserServiceFactory.class); Assert.assertTrue(excluded); excluded = CDIExtension.willExcludeClasses(excludedClasses, UserServiceFactoryWithQualifier.class); Assert.assertTrue(excluded); excluded = CDIExtension.willExcludeClasses(excludedClasses, UserServiceFactoryWithQualifierOnProduce.class); Assert.assertTrue(excluded); } @Test public void test_willExcludeAnnotations() { Set<Class<? extends Annotation>> excludedAnnotations = CollectionUtils.toSet(TestQualifier.class); boolean excluded = CDIExtension.willExcludeAnnotations(excludedAnnotations, UserService.class); Assert.assertFalse(excluded); excluded = CDIExtension.willExcludeAnnotations(excludedAnnotations, UserServiceWithQualifier.class); Assert.assertTrue(excluded); excluded = CDIExtension.willExcludeAnnotations(excludedAnnotations, UserServiceFactory.class); Assert.assertFalse(excluded); excluded = CDIExtension.willExcludeAnnotations(excludedAnnotations, UserServiceFactoryWithQualifier.class); Assert.assertTrue(excluded); excluded = CDIExtension.willExcludeAnnotations(excludedAnnotations, UserServiceFactoryWithQualifierOnProduce.class); Assert.assertTrue(excluded); } static class UserService { } @TestQualifier static class UserServiceWithQualifier extends UserService { } static class UserServiceFactory implements CDIFactory<UserService> { @Produces @ApplicationScoped @Override public UserService produce() { return new UserService(); } @Override public void dispose(@Disposes UserService t) { } } @TestQualifier static class UserServiceFactoryWithQualifier implements CDIFactory<UserService> { @Produces @ApplicationScoped @Override public UserService produce() { return new UserService(); } @Override public void dispose(@Disposes UserService t) { } } static class UserServiceFactoryWithQualifierOnProduce implements CDIFactory<UserService> { @Produces @ApplicationScoped @TestQualifier @Override public UserService produce() { return new UserService(); } @Override public void dispose(@Disposes @TestQualifier UserService t) { } } @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER }) @Documented public @interface TestQualifier { } }
1,426
1,617
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json import pytest from schema import Use from flask import Flask from app.utils.validator import Validator from app.utils.ResponseUtil import standard_response from . import success, load_data v = Validator() @v.register('even') def even(): return Use(int, lambda value: value % 2) SCHEMA = { 'name': v.str(), 'age': v.int(min=18, max=99), 'sex': v.enum('男', '女'), 'number': v.even(), v.optional('email'): v.email() } EXPECT = { 'user_id': 123, 'name': 'kk', 'age': 21, 'sex': '男', 'number': 2, 'email': '<EMAIL>' } DATA = { 'name': 'kk', 'age': '21', 'sex': '男', 'number': 2, 'email': '<EMAIL>' } JSONDATA = json.dumps(DATA) app = Flask(__name__) @app.route('/<int:user_id>', methods=['GET', 'POST']) @v.param(SCHEMA) def index(**kwargs): return standard_response(1, kwargs) @pytest.fixture def client(): with app.test_client() as c: yield c # def load_data(resp): # if resp.status_code != 200: # print(resp.data) # assert resp.status_code == 200 # return json.loads(resp.data) def test_form_ok(client): resp = client.post('/123', data=DATA) assert load_data(resp) == EXPECT def test_json_ok(client): headers = {'Content-Type': 'application/json'} resp = client.post('/123', data=JSONDATA, headers=headers) assert load_data(resp) == EXPECT def test_args_ok(client): resp = client.get('/123', query_string=DATA) assert load_data(resp) == EXPECT def test_optional(client): data = DATA.copy() data.pop('email') resp = client.post('/123', data=data) expect = EXPECT.copy() expect['email'] = None load_data(resp) == expect def test_required(client): data = DATA.copy() data.pop('name') resp = client.post('/123', data=data) assert not success(resp) def test_error(client): data = DATA.copy() data['age'] = '17' resp = client.post('/123', data=data) assert not success(resp)
852
575
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_IMAGE_FETCHER_IMAGE_DECODER_IMPL_H_ #define CHROME_BROWSER_IMAGE_FETCHER_IMAGE_DECODER_IMPL_H_ #include <memory> #include <vector> #include "chrome/browser/image_decoder/image_decoder.h" #include "components/image_fetcher/core/image_decoder.h" // image_fetcher::ImageDecoder implementation. class ImageDecoderImpl : public image_fetcher::ImageDecoder { public: ImageDecoderImpl(); ~ImageDecoderImpl() override; void DecodeImage(const std::string& image_data, const gfx::Size& desired_image_frame_size, image_fetcher::ImageDecodedCallback callback) override; private: class DecodeImageRequest; // Removes the passed image decode |request| from the internal request queue. void RemoveDecodeImageRequest(DecodeImageRequest* request); // All active image decoding requests. std::vector<std::unique_ptr<DecodeImageRequest>> decode_image_requests_; DISALLOW_COPY_AND_ASSIGN(ImageDecoderImpl); }; #endif // CHROME_BROWSER_IMAGE_FETCHER_IMAGE_DECODER_IMPL_H_
424
422
print("111" == "111")
8
675
/* * Copyright 2017 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.python.resolve.provider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import javax.annotation.Nullable; /** Provides a psi element, given a {@link PsiManager}. */ interface PsiElementProvider { @Nullable PsiElement get(PsiManager manager); static PsiElementProvider getParent(PsiElementProvider provider) { return (manager) -> { PsiElement psi = provider.get(manager); return psi != null ? psi.getParent() : null; }; } }
336
508
// The MIT License (MIT) // // Copyright (c) 2014 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <PEGKit/PKTokenizerState.h> /*! @class PKWordState @brief A word state returns a word from a reader. @details <p>Like other states, a tokenizer transfers the job of reading to this state, depending on an initial character. Thus, the tokenizer decides which characters may begin a word, and this state determines which characters may appear as a second or later character in a word. These are typically different sets of characters; in particular, it is typical for digits to appear as parts of a word, but not as the initial character of a word.</p> <p>By default, the following characters may appear in a word. The method setWordChars() allows customizing this.</p> @code From To 'a' 'z' 'A' 'Z' '0' '9' @endcode <p>as well as: minus sign <tt>-</tt>, underscore <tt>_</tt>, and apostrophe <tt>'</tt>.</p> */ @interface PKWordState : PKTokenizerState /*! @brief Establish characters in the given range as valid characters for part of a word after the first character. Note that the tokenizer must determine which characters are valid as the beginning character of a word. @param yn true if characters in the given range are word characters @param start the "start" character. e.g. <tt>'a'</tt> or <tt>65</tt>. @param end the "end" character. <tt>'z'</tt> or <tt>90</tt>. */ - (void)setWordChars:(BOOL)yn from:(PKUniChar)start to:(PKUniChar)end; /*! @brief Informs whether the given character is recognized as a word character by this state. @param cin the character to check @result true if the given chracter is recognized as a word character */ - (BOOL)isWordChar:(PKUniChar)c; @end
921
653
// Copyright (c) 2020 by Chrono // // g++ algo.cpp -std=c++11 -o a.out;./a.out // g++ algo.cpp -std=c++14 -o a.out;./a.out // g++ algo.cpp -std=c++14 -I../common -o a.out;./a.out #include <cassert> #include <iostream> #include <array> #include <vector> #include <set> #include <algorithm> using namespace std; void case1() { vector<int> v = {1,3,1,7,5}; auto n1 = std::count( begin(v), end(v), 1 ); int n2 = 0; for(auto x : v) { if (x == 1) { n2++; } } assert(n1 == n2); auto n = std::count_if( begin(v), end(v), [](auto x) { return x > 2; } ); assert(n == 3); } void case2() { vector<int> v = {1,2,3,4,5}; auto iter1 = v.begin(); auto iter2 = v.end(); auto iter3 = std::begin(v); auto iter4 = std::end(v); assert(iter1 == iter3); assert(iter2 == iter4); } void case3() { array<int, 5> arr = {0,1,2,3,4}; auto b = begin(arr); auto e = end(arr); assert(distance(b, e) == 5); auto p = next(b); assert(distance(b, p) == 1); assert(distance(p, b) == -1); advance(p, 2); assert(*p == 3); assert(p == prev(e, 2)); } void case4() { #if 1 vector<int> v = {3,5,1,7,10}; for(const auto& x : v) { cout << x << ","; } #endif cout << endl; #if 1 auto print = [](const auto& x) { cout << x << ","; }; for_each(cbegin(v), cend(v), print); #endif cout << endl; #if 1 for_each( cbegin(v), cend(v), [](const auto& x) { cout << x << ","; } ); #endif cout << endl; } void case5() { vector<int> v = {3,5,1,7,10,99,42}; auto print = [](const auto& x) { cout << x << ","; }; // total sort std::sort(begin(v), end(v)); for_each(cbegin(v), cend(v), print); cout << endl; // top3 std::partial_sort( begin(v), next(begin(v), 3), end(v)); for_each(cbegin(v), cend(v), print); cout << endl; // best3 std::nth_element( begin(v), next(begin(v), 3), end(v)); for_each(cbegin(v), cend(v), print); cout << endl; // Median auto mid_iter = next(begin(v), v.size()/2); std::nth_element( begin(v), mid_iter, end(v)); for_each(cbegin(v), cend(v), print); cout << "median is " << *mid_iter << endl; // partition auto pos = std::partition( begin(v), end(v), [](const auto& x) { return x > 9; } ); for_each(begin(v), pos, print); cout << endl; for_each(cbegin(v), cend(v), print); cout << endl; // min/max auto value = std::minmax_element( cbegin(v), cend(v) ); cout << *value.first << "," << *value.second << endl; } void case6() { vector<int> v = {3,5,1,7,10,99,42}; auto print = [](const auto& x) { cout << x << ","; }; // total sort std::sort(begin(v), end(v)); for_each(cbegin(v), cend(v), print); cout << endl; auto found = binary_search( cbegin(v), cend(v), 7 ); cout << "found: " << found << endl; decltype(cend(v)) pos; pos = std::lower_bound( cbegin(v), cend(v), 7 ); //assert(pos != cend(v)); //assert(*pos == 7); found = (pos != cend(v)) && (*pos == 7); assert(found); pos = std::lower_bound( cbegin(v), cend(v), 9 ); //assert(pos != cend(v)); //cout << *pos << endl; found = (pos != cend(v)) && (*pos == 9); assert(!found); pos = std::upper_bound( cbegin(v), cend(v), 9 ); //cout << *pos << endl; auto range = std::equal_range( cbegin(v), cend(v), 9 ); //cout << *range.first << endl; //cout << *range.second << endl; for_each( range.first, std::next(range.second), print ); cout << endl; } void case7() { multiset<int> s = {3,5,1,7,7,7,10,99,42}; auto print = [](const auto& x) { cout << x << ","; }; auto pos = s.find(7); assert(pos != s.end()); auto lower_pos = s.lower_bound(7); auto upper_pos = s.upper_bound(7); for_each( lower_pos, upper_pos, print ); cout << endl; } void case8() { vector<int> v = {1,9,11,3,5,7}; decltype(v.end()) pos; pos = std::find( begin(v), end(v), 3 ); assert(pos != end(v)); pos = std::find_if( begin(v), end(v), [](auto x) { return x % 2 == 0; } ); assert(pos == end(v)); array<int, 2> arr = {3,5}; pos = std::find_first_of( begin(v), end(v), begin(arr), end(arr) ); assert(pos != end(v)); } int main() { case1(); case2(); case3(); case4(); case5(); case6(); case7(); case8(); using namespace std; cout << "algorithm demo" << endl; }
2,517
527
import errno import json import os import shutil import subprocess import requests DEFAULT_MODEL_PATH = "model_archiver/tests/integ_tests/resources/regular_model" DEFAULT_HANDLER = "service:handle" DEFAULT_RUNTIME = "python" DEFAULT_MODEL_NAME = "model" DEFAULT_EXPORT_PATH = "/tmp/model" MANIFEST_FILE = "MAR-INF/MANIFEST.json" def update_tests(test): test["modelName"] = test.get("modelName", DEFAULT_MODEL_NAME) test["modelPath"] = test.get("modelPath", DEFAULT_MODEL_PATH) test["handler"] = test.get("handler", DEFAULT_HANDLER) test["runtime"] = test.get("runtime", DEFAULT_RUNTIME) test["exportPath"] = test.get("exportPath", DEFAULT_EXPORT_PATH) test["archiveFormat"] = test.get("archiveFormat", "default") return test def create_file_path(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def delete_file_path(path): try: if os.path.isfile(path): os.remove(path) if os.path.isdir(path): shutil.rmtree(path) except OSError: pass def run_test(test, cmd): it = test.get("iterations") if test.get("iterations") is not None else 1 for i in range(it): try: subprocess.check_call(cmd, shell=True) except subprocess.CalledProcessError as exc: if test.get("expectError") is not True: assert 0, "{}".format(exc.output) else: return 0 return 1 def validate_archive_exists(test): fmt = test.get("archiveFormat") if fmt == "tgz": assert os.path.isfile(os.path.join(test.get("exportPath"), test.get("modelName")+".tar.gz")) elif fmt == "no-archive": assert os.path.isdir(os.path.join(test.get("exportPath"), test.get("modelName"))) else: assert os.path.isfile(os.path.join(test.get("exportPath"), test.get("modelName")+".mar")) def validate_manifest_file(manifest, test): """ Validate the MANIFEST file :param manifest: :param test: :return: """ assert manifest.get("runtime") == test.get("runtime") assert manifest.get("model").get("modelName") == test.get("modelName") assert manifest.get("model").get("handler") == test.get("handler") def validate_files(file_list, prefix, regular): assert os.path.join(prefix, MANIFEST_FILE) in file_list assert os.path.join(prefix, "service.py") in file_list if regular: assert os.path.join(prefix, "dummy-artifacts.txt") in file_list assert os.path.join(prefix, "dir/1.py") in file_list else: assert os.path.join(prefix, "model.onnx") in file_list def validate_tar_archive(test_cfg): import tarfile file_name = os.path.join(test_cfg.get("exportPath"), test_cfg.get("modelName") + ".tar.gz") f = tarfile.open(file_name, "r:gz") manifest = json.loads(f.extractfile(os.path.join(test_cfg.get("modelName"), MANIFEST_FILE)).read()) validate_manifest_file(manifest, test_cfg) validate_files(f.getnames(), test_cfg.get("modelName"), "regular_model" in test_cfg.get("modelPath")) def validate_noarchive_archive(test): file_name = os.path.join(test.get("exportPath"), test.get("modelName"), MANIFEST_FILE) manifest = json.loads(open(file_name).read()) validate_manifest_file(manifest, test) def validate_mar_archive(test): import zipfile file_name = os.path.join(test.get("exportPath"), test.get("modelName") + ".mar") zf = zipfile.ZipFile(file_name, "r") manifest = json.loads(zf.open(MANIFEST_FILE).read()) validate_manifest_file(manifest, test) def validate_archive_content(test): fmt = test.get("archiveFormat") if fmt == "tgz": validate_tar_archive(test) if fmt == "no-archive": validate_noarchive_archive(test) if fmt == "default": validate_mar_archive(test) def validate(test): validate_archive_exists(test) validate_archive_content(test) def test_model_archiver(): f = open("model_archiver/tests/integ_tests/configuration.json", "r") tests = json.loads(f.read()) for t in tests: try: delete_file_path(t.get("exportPath")) create_file_path(t.get("exportPath")) t = update_tests(t) cmd = "model-archiver " \ "--model-name {} " \ "--model-path {} " \ "--handler {} " \ "--runtime {} " \ "--export-path {} " \ "--archive-format {}".format(t.get("modelName"), t.get("modelPath"), t.get("handler"), t.get("runtime"), t.get("exportPath"), t.get("archiveFormat")) if t.get("force"): cmd += " -f" # TODO: Add tests to check for "convert" functionality if run_test(t, cmd): validate(t) finally: delete_file_path(t.get("exportPath")) if __name__ == "__main__": test_model_archiver()
2,402
26,932
<reponame>OsmanDere/metasploit-framework #include "interfaces.h" #include <vector> bstr_t GetTemp(LPCWSTR name); bstr_t GetTempPath(); bstr_t WriteTempFile(LPCWSTR name, unsigned char* buf, size_t len); std::vector<unsigned char> ReadFileToMem(LPCWSTR name); void DebugPrintf(LPCSTR lpFormat, ...); bstr_t GetUserSid(); void DisableImpersonation(IUnknown* pUnk); void SetCloaking(IUnknown* pUnk); IIEUserBrokerPtr CreateBroker(); IShdocvwBroker* CreateSHDocVw(); bstr_t GetWindowsSystemDirectory(); bstr_t GetExecutableFileName(HMODULE hModule); extern "C" int DeleteLink(LPCWSTR par_src); extern "C" int CreateLink(LPCWSTR par_src, LPCWSTR par_dst, int opt_volatile); bstr_t GetSessionPath(); LSTATUS CreateRegistryValueString(HKEY hKey, LPCWSTR lpName, LPCWSTR lpString); LSTATUS CreateRegistryValueDword(HKEY hKey, LPCWSTR lpName, DWORD d);
325
348
{"nom":"Trévron","circ":"2ème circonscription","dpt":"Côtes-d'Armor","inscrits":537,"abs":306,"votants":231,"blancs":20,"nuls":6,"exp":205,"res":[{"nuance":"REM","nom":"<NAME>","voix":119},{"nuance":"LR","nom":"<NAME>","voix":86}]}
94
1,975
// Copyright 2008-2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== // Constants for the statsreport library. #ifndef OMAHA_COMMON_STATS_UPLOADER_H__ #define OMAHA_COMMON_STATS_UPLOADER_H__ #include <windows.h> #include <tchar.h> namespace omaha { // The product name is chosen so that the stats are persisted under // the Google Update registry key for the machine or user, respectively. const TCHAR* const kMetricsProductName = _T("Update"); const TCHAR* const kMetricsServerParamSourceId = _T("sourceid"); const TCHAR* const kMetricsServerParamVersion = _T("v"); const TCHAR* const kMetricsServerParamIsMachine = _T("ismachine"); const TCHAR* const kMetricsServerTestSource = _T("testsource"); const TCHAR* const kMetricsServerUserId = _T("ui"); // Metrics are uploaded every 25 hours. const int kMetricsUploadIntervalSec = 25 * 60 * 60; // Deletes existing metrics and initializes 'LastTransmission' to current time. HRESULT ResetMetrics(bool is_machine); // Aggregates metrics by saving them in registry. HRESULT AggregateMetrics(bool is_machine); // Aggregates and reports the metrics if needed, as defined by the metrics // upload interval. The interval is ignored when 'force_report' is true. HRESULT AggregateAndReportMetrics(bool is_machine, bool force_report); } // namespace omaha #endif // OMAHA_COMMON_STATS_UPLOADER_H__
597
1,521
<filename>interactive_engine/groot/src/main/java/com/alibaba/graphscope/groot/coordinator/SnapshotNotifier.java /** * Copyright 2020 Alibaba Group Holding Limited. * * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.graphscope.groot.coordinator; import com.alibaba.graphscope.groot.discovery.MaxGraphNode; import com.alibaba.graphscope.groot.discovery.NodeDiscovery; import com.alibaba.maxgraph.common.RoleType; import com.alibaba.graphscope.groot.rpc.RoleClients; import java.util.HashMap; import java.util.Map; public class SnapshotNotifier implements NodeDiscovery.Listener { private NodeDiscovery nodeDiscovery; private SnapshotManager snapshotManager; private SchemaManager schemaManager; private RoleClients<FrontendSnapshotClient> frontendSnapshotClients; private Map<Integer, QuerySnapshotListener> listeners; public SnapshotNotifier( NodeDiscovery nodeDiscovery, SnapshotManager snapshotManager, SchemaManager schemaManager, RoleClients<FrontendSnapshotClient> frontendSnapshotClients) { this.nodeDiscovery = nodeDiscovery; this.snapshotManager = snapshotManager; this.schemaManager = schemaManager; this.frontendSnapshotClients = frontendSnapshotClients; } public void start() { this.listeners = new HashMap<>(); this.nodeDiscovery.addListener(this); } public void stop() { this.nodeDiscovery.removeListener(this); } @Override public void nodesJoin(RoleType role, Map<Integer, MaxGraphNode> nodes) { if (role != RoleType.FRONTEND) { return; } nodes.forEach( (id, node) -> { QuerySnapshotListener notifyFrontendListener = new NotifyFrontendListener( id, frontendSnapshotClients.getClient(id), this.schemaManager); this.snapshotManager.addListener(notifyFrontendListener); this.listeners.put(id, notifyFrontendListener); }); } @Override public void nodesLeft(RoleType role, Map<Integer, MaxGraphNode> nodes) { if (role != RoleType.FRONTEND) { return; } nodes.forEach( (id, node) -> { QuerySnapshotListener removeListener = listeners.remove(id); this.snapshotManager.removeListener(removeListener); }); } }
1,171
777
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_EXPORT_PASSWORD_EXPORTER_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_EXPORT_PASSWORD_EXPORTER_H_ #include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" namespace autofill { struct PasswordForm; } namespace base { class TaskRunner; } namespace password_manager { // Static-only class bundling together the API for exporting passwords into a // file. class PasswordExporter { public: // Exports |passwords| into a file at |path|, overwriting any existing file. // Blocking IO tasks will be posted to |blocking_task_runner|. The format of // the export will be selected based on the file extension in |path|. static void Export( const base::FilePath& path, const std::vector<std::unique_ptr<autofill::PasswordForm>>& passwords, scoped_refptr<base::TaskRunner> blocking_task_runner); // Returns the file extensions corresponding to supported formats. // Inner vector indicates equivalent extensions. For example: // { { "html", "htm" }, { "csv" } } static std::vector<std::vector<base::FilePath::StringType>> GetSupportedFileExtensions(); private: DISALLOW_IMPLICIT_CONSTRUCTORS(PasswordExporter); }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_EXPORT_PASSWORD_EXPORTER_H_
515
1,914
<reponame>erikbfeeley/concerto<filename>packages/concerto-core/test/data/id-cards/valid-v0/metadata.json { "name": "name", "description": "A valid ID card", "businessNetwork": "org-acme-biznet", "enrollmentId": "conga", "enrollmentSecret": "<PASSWORD>" }
113
348
<gh_stars>100-1000 {"nom":"Suizy-le-Franc","circ":"3ème circonscription","dpt":"Marne","inscrits":106,"abs":47,"votants":59,"blancs":9,"nuls":0,"exp":50,"res":[{"nuance":"FN","nom":"<NAME>","voix":27},{"nuance":"REM","nom":"<NAME>","voix":23}]}
101
2,586
<filename>samurai-examples/movie/movie/network/MoviesClient.h // // MoviesClient.h // demo // // Created by QFish on 4/7/15. // Copyright (c) 2015 Geek-Zoo Studio. All rights reserved. // #import "STIHTTPSessionManager.h" #import "NSObject+AutoCoding.h" #import "Movies.h" @interface MoviesClient : STIHTTPSessionManager + (instancetype)sharedClient; @end @interface NSObject (APIExtension) <AutoModelCoding> @end @interface GET_A_MOVIE_API (APIExtension) @end
175
6,098
<reponame>vishalbelsare/h2o-3 package water; import org.apache.commons.io.output.NullOutputStream; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import water.util.ArrayUtils; import java.io.Serializable; import java.util.Arrays; import static org.junit.Assert.*; public class AutoBufferTest extends TestUtil { @BeforeClass() public static void setup() { stall_till_cloudsize(1); } @Test public void testPutA8ArrayWithJustZeros() { long[] arr = new long[AutoBuffer.BBP_SML._size * 2]; AutoBuffer ab = new AutoBuffer(H2O.SELF, (byte) 1); ab.putA8(arr); assertTrue(ab._bb.hasArray()); assertFalse(ab._bb.isDirect()); assertEquals(ab._bb.array().length, 16); } @Test public void testPutA8SmallBufferAfterTrimmed() { long[] arr = new long[AutoBuffer.BBP_SML._size * 2]; arr[1000] = 42; AutoBuffer ab = new AutoBuffer(H2O.SELF, (byte) 1); ab.putA8(arr); assertTrue(ab._bb.hasArray()); assertFalse(ab._bb.isDirect()); assertEquals(ab._bb.array().length, 16); } @Test public void testPutA8BigBufferAfterTrimmed() { long[] arr = new long[AutoBuffer.BBP_SML._size * 2]; Arrays.fill(arr, Long.MAX_VALUE); AutoBuffer ab = new AutoBuffer(H2O.SELF, (byte) 1); ab.putA8(arr); assertFalse(ab._bb.hasArray()); assertTrue(ab._bb.isDirect()); } @Test public void testOutputStreamBigDataBigChunks() { // don't run if the JVM doesn't have enough memory Assume.assumeTrue("testOutputStreamBigDataBigChunks: JVM has enough memory (~4GB)", Runtime.getRuntime().maxMemory() > 4e9); final int dataSize = (Integer.MAX_VALUE - 8) /*=max array size*/ - 5 /*=array header size*/; byte[] data = new byte[dataSize - 1]; AutoBuffer ab = new AutoBuffer(NullOutputStream.NULL_OUTPUT_STREAM, false); // make sure the buffer can take the full array ab.putA1(data); // now try to stream 1TB of data through the buffer for (int i = 0; i < 512; i++) { if (i % 10 == 0) System.out.println(i); ab.putA1(data); } ab.close(); } @Test public void testOutputStreamBigDataSmallChunks() { final int dataSize = 100 * 1024; byte[] data = new byte[dataSize - 1]; AutoBuffer ab = new AutoBuffer(NullOutputStream.NULL_OUTPUT_STREAM, false); // make sure the buffer can take full array ab.putA1(data); // try to stream 1TB of data made of small chunks through AutoBuffer for (int i = 0; i < 1e12 / dataSize; i++) ab.putA1(data); ab.close(); } @Test public void testOutputStreamSmallData() { final int dataSize = 100 * 1024; byte[] data = new byte[dataSize]; AutoBuffer ab = new AutoBuffer(NullOutputStream.NULL_OUTPUT_STREAM, false); // stream bite-size data to AutoBuffer for (int i = 0; i < Integer.MAX_VALUE / dataSize; i++) ab.putA1(data); ab.close(); } static class XYZZY implements Serializable { int i = 1; String s = "hi"; } @Test public void testNameOfClass() { byte[] bytes = AutoBuffer.javaSerializeWritePojo(new XYZZY()); assertEquals("water.AutoBufferTest$XYZZY", AutoBuffer.nameOfClass(bytes)); bytes[7] = 127; assertEquals("water.AutoBufferTest$XYZZY\ufffd\27\142\51\140\ufffd\ufffd\174\2\0\2I\0\1", AutoBuffer.nameOfClass(bytes)); bytes[7] = 1; assertEquals("wat", AutoBuffer.nameOfClass(bytes)); bytes[7] = -10; assertEquals("wat", AutoBuffer.nameOfClass(bytes)); assertEquals("(null)", AutoBuffer.nameOfClass(null)); assertEquals("(no name)", AutoBuffer.nameOfClass(new byte[]{0,0,0,0,0})); } @Test public void testSerializeBootstrapFreezable() { MyCustomBootstrapFreezable freezable = new MyCustomBootstrapFreezable("payload42"); byte[] bytes = AutoBuffer.serializeBootstrapFreezable(freezable); assertNotNull(bytes); byte[] expectedPayload = freezable._data.getBytes(); byte[] expectedMessage = ArrayUtils.append( new byte[]{ 0, // marker (byte) (freezable.frozenType() + 1), // +1 because of compressed integer coding, see AutoBuffer#put1 (byte) (expectedPayload.length + 1) // ditto }, expectedPayload ); assertArrayEquals(expectedMessage, bytes); } @Test public void testDeserializeBootstrapFreezable() { int typeId = new MyCustomBootstrapFreezable("anything").frozenType(); String data = "my test data 42"; byte[] payload = data.getBytes(); byte[] bytes = ArrayUtils.append( new byte[]{ 0, // marker (byte) (typeId + 1), // +1 because of compressed integer coding, see AutoBuffer#put1 (byte) (payload.length + 1) // ditto }, payload ); MyCustomBootstrapFreezable freezable = (MyCustomBootstrapFreezable) AutoBuffer.deserializeBootstrapFreezable(bytes); assertEquals(data, freezable._data); } @Test public void testMaliciousFreezable() { int typeId = TypeMap.onIce(MaliciousFreezable.class.getName()); byte[] payload = "any data - it doesn't matter what is here".getBytes(); byte[] bytes = ArrayUtils.append( new byte[]{ 0, // marker (byte) (typeId + 1), // +1 because of compressed integer coding, see AutoBuffer#put1 (byte) (payload.length + 1) // ditto }, payload ); IllegalStateException ise = null; try { AutoBuffer.deserializeBootstrapFreezable(bytes); } catch (IllegalStateException e) { ise = e; } finally { assertEquals("we are safe", MaliciousFreezable.GLOBAL_STATE); // global state was not modified } assertNotNull(ise); assertEquals( "Class with frozenType=" + typeId + " cannot be deserialized because it is not part of the TypeMap.", ise.getMessage() ); } public static class MyCustomBootstrapFreezable extends Iced<MyCustomBootstrapFreezable> implements BootstrapFreezable<MyCustomBootstrapFreezable> { private final String _data; MyCustomBootstrapFreezable(String data) { _data = data; } } public static class MaliciousFreezable implements Freezable<MaliciousFreezable> { public static String GLOBAL_STATE = "we are safe"; @Override public AutoBuffer write(AutoBuffer ab) { GLOBAL_STATE = "hacked!"; return null; } @Override public MaliciousFreezable read(AutoBuffer ab) { GLOBAL_STATE = "hacked!"; return null; } @Override public AutoBuffer writeJSON(AutoBuffer ab) { GLOBAL_STATE = "hacked!"; return null; } @Override public MaliciousFreezable readJSON(AutoBuffer ab) { GLOBAL_STATE = "hacked!"; return null; } @Override public int frozenType() { GLOBAL_STATE = "hacked!"; return 0; } @Override public byte[] asBytes() { GLOBAL_STATE = "hacked!"; return new byte[0]; } @Override public MaliciousFreezable reloadFromBytes(byte[] ary) { GLOBAL_STATE = "hacked!"; return null; } @Override public MaliciousFreezable clone() { GLOBAL_STATE = "hacked!"; return null; } } public static class MyCustomTypeMapExtension implements TypeMapExtension { @Override public String[] getBoostrapClasses() { return new String[]{MyCustomBootstrapFreezable.class.getName()}; } } }
3,051
14,668
#ifndef PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_ #define PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_ #include "google/protobuf/message.h" #include "google/protobuf/descriptor.h" using google::protobuf::FieldDescriptor; using google::protobuf::Message; using google::protobuf::Reflection; namespace google { namespace protobuf { namespace util { class DataStripper { public: void StripMessage(Message *message) { std::vector<const FieldDescriptor*> set_fields; const Reflection* reflection = message->GetReflection(); reflection->ListFields(*message, &set_fields); for (size_t i = 0; i < set_fields.size(); i++) { const FieldDescriptor* field = set_fields[i]; if (ShouldBeClear(field)) { reflection->ClearField(message, field); continue; } if (field->type() == FieldDescriptor::TYPE_MESSAGE) { if (field->is_repeated()) { for (int j = 0; j < reflection->FieldSize(*message, field); j++) { StripMessage(reflection->MutableRepeatedMessage(message, field, j)); } } else { StripMessage(reflection->MutableMessage(message, field)); } } } reflection->MutableUnknownFields(message)->Clear(); } private: virtual bool ShouldBeClear(const FieldDescriptor *field) = 0; }; class GogoDataStripper : public DataStripper { private: virtual bool ShouldBeClear(const FieldDescriptor *field) { return field->type() == FieldDescriptor::TYPE_GROUP; } }; class Proto3DataStripper : public DataStripper { private: virtual bool ShouldBeClear(const FieldDescriptor *field) { return field->type() == FieldDescriptor::TYPE_GROUP || field->is_extension(); } }; } // namespace util } // namespace protobuf } // namespace google #endif // PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_
733
7,258
<reponame>alclol/modin<filename>stress_tests/kaggle/kaggle6.py import matplotlib matplotlib.use("PS") import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns np.random.seed(2) from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import itertools from keras.utils.np_utils import to_categorical # convert to one-hot-encoding from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras.optimizers import RMSprop from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ReduceLROnPlateau sns.set(style="white", context="notebook", palette="deep") train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") Y_train = train["label"] X_train = train.drop(labels=["label"], axis=1) del train g = sns.countplot(Y_train) Y_train.value_counts() X_train.isnull().any().describe() test.isnull().any().describe() X_train = X_train / 255.0 test = test / 255.0 X_train = X_train.values.reshape(-1, 28, 28, 1) test = test.values.reshape(-1, 28, 28, 1) Y_train = to_categorical(Y_train, num_classes=10) random_seed = 2 X_train, X_val, Y_train, Y_val = train_test_split( X_train, Y_train, test_size=0.1, random_state=random_seed ) g = plt.imshow(X_train[0][:, :, 0]) model = Sequential() model.add( Conv2D( filters=32, kernel_size=(5, 5), padding="Same", activation="relu", input_shape=(28, 28, 1), ) ) model.add(Conv2D(filters=32, kernel_size=(5, 5), padding="Same", activation="relu")) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(filters=64, kernel_size=(3, 3), padding="Same", activation="relu")) model.add(Conv2D(filters=64, kernel_size=(3, 3), padding="Same", activation="relu")) model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation="relu")) model.add(Dropout(0.5)) model.add(Dense(10, activation="softmax")) optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) model.compile( optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy"] ) learning_rate_reduction = ReduceLROnPlateau( monitor="val_acc", patience=3, verbose=1, factor=0.5, min_lr=0.00001 ) epochs = 1 # Turn epochs to 30 to get 0.9967 accuracy batch_size = 86 datagen = ImageDataGenerator( featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) zoom_range=0.1, # Randomly zoom image width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=False, # randomly flip images vertical_flip=False, ) # randomly flip images datagen.fit(X_train) history = model.fit_generator( datagen.flow(X_train, Y_train, batch_size=batch_size), epochs=epochs, validation_data=(X_val, Y_val), verbose=2, steps_per_epoch=X_train.shape[0] // batch_size, callbacks=[learning_rate_reduction], ) fig, ax = plt.subplots(2, 1) ax[0].plot(history.history["loss"], color="b", label="Training loss") ax[0].plot(history.history["val_loss"], color="r", label="validation loss", axes=ax[0]) legend = ax[0].legend(loc="best", shadow=True) ax[1].plot(history.history["acc"], color="b", label="Training accuracy") ax[1].plot(history.history["val_acc"], color="r", label="Validation accuracy") legend = ax[1].legend(loc="best", shadow=True) def plot_confusion_matrix( cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues ): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation="nearest", cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 2.0 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text( j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black", ) plt.tight_layout() plt.ylabel("True label") plt.xlabel("Predicted label") Y_pred = model.predict(X_val) Y_pred_classes = np.argmax(Y_pred, axis=1) Y_true = np.argmax(Y_val, axis=1) confusion_mtx = confusion_matrix(Y_true, Y_pred_classes) plot_confusion_matrix(confusion_mtx, classes=range(10)) errors = Y_pred_classes - Y_true != 0 Y_pred_classes_errors = Y_pred_classes[errors] Y_pred_errors = Y_pred[errors] Y_true_errors = Y_true[errors] X_val_errors = X_val[errors] def display_errors(errors_index, img_errors, pred_errors, obs_errors): """ This function shows 6 images with their predicted and real labels""" n = 0 nrows = 2 ncols = 3 fig, ax = plt.subplots(nrows, ncols, sharex=True, sharey=True) for row in range(nrows): for col in range(ncols): error = errors_index[n] ax[row, col].imshow((img_errors[error]).reshape((28, 28))) ax[row, col].set_title( "Predicted label :{}\nTrue label :{}".format( pred_errors[error], obs_errors[error] ) ) n += 1 Y_pred_errors_prob = np.max(Y_pred_errors, axis=1) true_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1)) delta_pred_true_errors = Y_pred_errors_prob - true_prob_errors sorted_dela_errors = np.argsort(delta_pred_true_errors) most_important_errors = sorted_dela_errors[-6:] display_errors( most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors ) results = model.predict(test) results = np.argmax(results, axis=1) results = pd.Series(results, name="Label") submission = pd.concat([pd.Series(range(1, 28001), name="ImageId"), results], axis=1) submission.to_csv("cnn_mnist_datagen.csv", index=False)
2,630
1,352
<reponame>Arsenal821/incubator-pegasus /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pegasus.client; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.apache.pegasus.rpc.Cluster; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class PegasusAbstractClient { private static final Logger LOGGER = LoggerFactory.getLogger(PegasusAbstractClient.class); protected final ClientOptions clientOptions; protected Cluster cluster; public PegasusAbstractClient(Properties properties) throws PException { this(ClientOptions.create(properties)); } public PegasusAbstractClient(String configPath) throws PException { this(ClientOptions.create(configPath)); } protected PegasusAbstractClient(ClientOptions options) throws PException { this.clientOptions = options; this.cluster = Cluster.createCluster(clientOptions); LOGGER.info( "Create Pegasus{}Client Instance By ClientOptions : {}", this.clientType(), this.clientOptions.toString()); } protected String clientType() { return ""; } @Override public void finalize() { close(); } public void close() { synchronized (this) { if (null != this.cluster) { String metaList = StringUtils.join(cluster.getMetaList(), ","); LOGGER.info("start to close pegasus {} client for [{}]", clientType(), metaList); cluster.close(); cluster = null; LOGGER.info("finish to close pegasus {} client for [{}]", clientType(), metaList); } } } }
717
14,668
<gh_stars>1000+ // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/extensions/login_screen/login/cleanup/print_jobs_cleanup_handler.h" #include <utility> #include "base/bind.h" #include "chrome/browser/ash/printing/print_management/printing_manager.h" #include "chrome/browser/ash/printing/print_management/printing_manager_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace chromeos { PrintJobsCleanupHandler::PrintJobsCleanupHandler() = default; PrintJobsCleanupHandler::~PrintJobsCleanupHandler() = default; void PrintJobsCleanupHandler::Cleanup(CleanupHandlerCallback callback) { DCHECK(callback_.is_null()); Profile* profile = ProfileManager::GetActiveUserProfile(); if (!profile) { std::move(callback).Run("There is no active user"); return; } callback_ = std::move(callback); ash::printing::print_management::PrintingManagerFactory::GetForProfile( profile) ->DeleteAllPrintJobs( base::BindOnce(&PrintJobsCleanupHandler::OnDeleteAllPrintJobsDone, base::Unretained(this))); } void PrintJobsCleanupHandler::OnDeleteAllPrintJobsDone(bool success) { if (!success) { std::move(callback_).Run("Failed to delete all print jobs"); return; } std::move(callback_).Run(absl::nullopt); } } // namespace chromeos
538
432
<filename>binutils-2.21.1/gcc-4.5.1/gcc/omega.h /* Source code for an implementation of the Omega test, an integer programming algorithm for dependence analysis, by <NAME>, appeared in Supercomputing '91 and CACM Aug 92. This code has no license restrictions, and is considered public domain. Changes copyright (C) 2005, 2006, 2007, 2009 Free Software Foundation, Inc. Contributed by <NAME> <<EMAIL>> This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "params.h" #ifndef GCC_OMEGA_H #define GCC_OMEGA_H #define OMEGA_MAX_VARS PARAM_VALUE (PARAM_OMEGA_MAX_VARS) #define OMEGA_MAX_GEQS PARAM_VALUE (PARAM_OMEGA_MAX_GEQS) #define OMEGA_MAX_EQS PARAM_VALUE (PARAM_OMEGA_MAX_EQS) #define pos_infinity (0x7ffffff) #define neg_infinity (-0x7ffffff) /* Results of the Omega solver. */ enum omega_result { omega_false = 0, omega_true = 1, /* Value returned when the solver is unable to determine an answer. */ omega_unknown = 2, /* Value used for asking the solver to simplify the system. */ omega_simplify = 3 }; /* Values used for labeling equations. Private (not used outside the solver). */ enum omega_eqn_color { omega_black = 0, omega_red = 1 }; /* Structure for equations. */ typedef struct eqn_d { int key; int touched; enum omega_eqn_color color; /* Array of coefficients for the equation. The layout of the data is as follows: coef[0] is the constant, coef[i] for 1 <= i <= OMEGA_MAX_VARS, are the coefficients for each dimension. Examples: the equation 0 = 9 + x + 0y + 5z is encoded as [9 1 0 5], the inequality 0 <= -8 + x + 2y + 3z is encoded as [-8 1 2 3]. */ int *coef; } *eqn; typedef struct omega_pb_d { /* The number of variables in the system of equations. */ int num_vars; /* Safe variables are not eliminated during the Fourier-Motzkin simplification of the system. Safe variables are all those variables that are placed at the beginning of the array of variables: PB->var[1, ..., SAFE_VARS]. PB->var[0] is not used, as PB->eqs[x]->coef[0] represents the constant of the equation. */ int safe_vars; /* Number of elements in eqs[]. */ int num_eqs; /* Number of elements in geqs[]. */ int num_geqs; /* Number of elements in subs[]. */ int num_subs; int hash_version; bool variables_initialized; bool variables_freed; /* Index or name of variables. Negative integers are reserved for wildcard variables. Maps the index of variables in the original problem to the new index of the variable. The index for a variable in the coef array of an equation can change as some variables are eliminated. */ int *var; int *forwarding_address; /* Inequalities in the system of constraints. */ eqn geqs; /* Equations in the system of constraints. */ eqn eqs; /* A map of substituted variables. */ eqn subs; } *omega_pb; extern void omega_initialize (void); extern omega_pb omega_alloc_problem (int, int); extern enum omega_result omega_solve_problem (omega_pb, enum omega_result); extern enum omega_result omega_simplify_problem (omega_pb); extern enum omega_result omega_simplify_approximate (omega_pb); extern enum omega_result omega_constrain_variable_sign (omega_pb, enum omega_eqn_color, int, int); extern void debug_omega_problem (omega_pb); extern void omega_print_problem (FILE *, omega_pb); extern void omega_print_red_equations (FILE *, omega_pb); extern int omega_count_red_equations (omega_pb); extern void omega_pretty_print_problem (FILE *, omega_pb); extern void omega_unprotect_variable (omega_pb, int var); extern void omega_negate_geq (omega_pb, int); extern void omega_convert_eq_to_geqs (omega_pb, int eq); extern void omega_print_eqn (FILE *, omega_pb, eqn, bool, int); extern bool omega_problem_has_red_equations (omega_pb); extern enum omega_result omega_eliminate_redundant (omega_pb, bool); extern void omega_eliminate_red (omega_pb, bool); extern void omega_constrain_variable_value (omega_pb, enum omega_eqn_color, int, int); extern bool omega_query_variable (omega_pb, int, int *, int *); extern int omega_query_variable_signs (omega_pb, int, int, int, int, int, int, bool *, int *); extern bool omega_query_variable_bounds (omega_pb, int, int *, int *); extern void (*omega_when_reduced) (omega_pb); extern void omega_no_procedure (omega_pb); /* Return true when variable I in problem PB is a wildcard. */ static inline bool omega_wildcard_p (omega_pb pb, int i) { return (pb->var[i] < 0); } /* Return true when variable I in problem PB is a safe variable. */ static inline bool omega_safe_var_p (omega_pb pb, int i) { /* The constant of an equation is not a variable. */ gcc_assert (0 < i); return (i <= pb->safe_vars); } /* Print to FILE equality E from PB. */ static inline void omega_print_eq (FILE *file, omega_pb pb, eqn e) { omega_print_eqn (file, pb, e, false, 0); } /* Print to FILE inequality E from PB. */ static inline void omega_print_geq (FILE *file, omega_pb pb, eqn e) { omega_print_eqn (file, pb, e, true, 0); } /* Print to FILE inequality E from PB. */ static inline void omega_print_geq_extra (FILE *file, omega_pb pb, eqn e) { omega_print_eqn (file, pb, e, true, 1); } /* E1 = E2, make a copy of E2 into E1. Equations contain S variables. */ static inline void omega_copy_eqn (eqn e1, eqn e2, int s) { e1->key = e2->key; e1->touched = e2->touched; e1->color = e2->color; memcpy (e1->coef, e2->coef, (s + 1) * sizeof (int)); } /* Initialize E = 0. Equation E contains S variables. */ static inline void omega_init_eqn_zero (eqn e, int s) { e->key = 0; e->touched = 0; e->color = omega_black; memset (e->coef, 0, (s + 1) * sizeof (int)); } /* Allocate N equations with S variables. */ static inline eqn omega_alloc_eqns (int s, int n) { int i; eqn res = (eqn) (xcalloc (n, sizeof (struct eqn_d))); for (i = n - 1; i >= 0; i--) { res[i].coef = (int *) (xcalloc (OMEGA_MAX_VARS + 1, sizeof (int))); omega_init_eqn_zero (&res[i], s); } return res; } /* Free N equations from array EQ. */ static inline void omega_free_eqns (eqn eq, int n) { int i; for (i = n - 1; i >= 0; i--) free (eq[i].coef); free (eq); } /* Returns true when E is an inequality with a single variable. */ static inline bool single_var_geq (eqn e, int nv ATTRIBUTE_UNUSED) { return (e->key != 0 && -OMEGA_MAX_VARS <= e->key && e->key <= OMEGA_MAX_VARS); } /* Allocate a new equality with all coefficients 0, and tagged with COLOR. Return the index of this equality in problem PB. */ static inline int omega_add_zero_eq (omega_pb pb, enum omega_eqn_color color) { int idx = pb->num_eqs++; gcc_assert (pb->num_eqs <= OMEGA_MAX_EQS); omega_init_eqn_zero (&pb->eqs[idx], pb->num_vars); pb->eqs[idx].color = color; return idx; } /* Allocate a new inequality with all coefficients 0, and tagged with COLOR. Return the index of this inequality in problem PB. */ static inline int omega_add_zero_geq (omega_pb pb, enum omega_eqn_color color) { int idx = pb->num_geqs; pb->num_geqs++; gcc_assert (pb->num_geqs <= OMEGA_MAX_GEQS); omega_init_eqn_zero (&pb->geqs[idx], pb->num_vars); pb->geqs[idx].touched = 1; pb->geqs[idx].color = color; return idx; } /* Initialize variables for problem PB. */ static inline void omega_initialize_variables (omega_pb pb) { int i; for (i = pb->num_vars; i >= 0; i--) pb->forwarding_address[i] = pb->var[i] = i; pb->variables_initialized = true; } /* Free problem PB. */ static inline void omega_free_problem (omega_pb pb) { free (pb->var); free (pb->forwarding_address); omega_free_eqns (pb->geqs, OMEGA_MAX_GEQS); omega_free_eqns (pb->eqs, OMEGA_MAX_EQS); omega_free_eqns (pb->subs, OMEGA_MAX_VARS + 1); free (pb); } /* Copy omega problems: P1 = P2. */ static inline void omega_copy_problem (omega_pb p1, omega_pb p2) { int e, i; p1->num_vars = p2->num_vars; p1->hash_version = p2->hash_version; p1->variables_initialized = p2->variables_initialized; p1->variables_freed = p2->variables_freed; p1->safe_vars = p2->safe_vars; p1->num_eqs = p2->num_eqs; p1->num_subs = p2->num_subs; p1->num_geqs = p2->num_geqs; for (e = p2->num_eqs - 1; e >= 0; e--) omega_copy_eqn (&(p1->eqs[e]), &(p2->eqs[e]), p2->num_vars); for (e = p2->num_geqs - 1; e >= 0; e--) omega_copy_eqn (&(p1->geqs[e]), &(p2->geqs[e]), p2->num_vars); for (e = p2->num_subs - 1; e >= 0; e--) omega_copy_eqn (&(p1->subs[e]), &(p2->subs[e]), p2->num_vars); for (i = p2->num_vars; i >= 0; i--) p1->var[i] = p2->var[i]; for (i = OMEGA_MAX_VARS; i >= 0; i--) p1->forwarding_address[i] = p2->forwarding_address[i]; } #endif /* GCC_OMEGA_H */
3,643
844
{ "github-username": "andikaputraputu", "favourite-emoji": "😂", "favourite-music": "https://soundcloud.com/greenday/holiday-boulevard-of-broken-1", "favourite-color": "#347ff7" }
87
749
// // StatsCell.h // Organic // // Created by Mike on 1/19/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import "OrganicCell.h" @interface StatsCell : OrganicCell - (instancetype)initWithFollowers:(NSNumber *)followers repos:(NSNumber *)repos following:(NSNumber *)following; @end
104
879
package com.bookstore.repository; import java.util.List; import javax.persistence.LockModeType; import javax.persistence.QueryHint; import com.bookstore.entity.Book; import com.bookstore.entity.BookStatus; import org.hibernate.LockOptions; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.QueryHints; import org.springframework.stereotype.Repository; @Repository public interface BookRepository extends JpaRepository<Book, Long> { @Lock(LockModeType.PESSIMISTIC_WRITE) @QueryHints({ @QueryHint(name = "javax.persistence.lock.timeout", value = "" + LockOptions.SKIP_LOCKED)}) public List<Book> findTop3ByStatus(BookStatus status, Sort sort); }
283
839
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.systest.jaxrs.security.jose.jwejws; import java.net.URL; import java.security.Security; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Properties; import javax.annotation.Priority; import javax.ws.rs.BadRequestException; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import org.apache.cxf.Bus; import org.apache.cxf.bus.spring.SpringBusFactory; import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.rs.security.jose.jaxrs.JweClientResponseFilter; import org.apache.cxf.rs.security.jose.jaxrs.JweWriterInterceptor; import org.apache.cxf.rs.security.jose.jaxrs.JwsClientResponseFilter; import org.apache.cxf.rs.security.jose.jaxrs.JwsWriterInterceptor; import org.apache.cxf.rs.security.jose.jaxrs.Priorities; import org.apache.cxf.rs.security.jose.jwa.ContentAlgorithm; import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; import org.apache.cxf.rs.security.jose.jwe.AesCbcHmacJweDecryption; import org.apache.cxf.rs.security.jose.jwe.AesCbcHmacJweEncryption; import org.apache.cxf.rs.security.jose.jwe.AesWrapKeyDecryptionAlgorithm; import org.apache.cxf.rs.security.jose.jwe.AesWrapKeyEncryptionAlgorithm; import org.apache.cxf.rs.security.jose.jws.HmacJwsSignatureProvider; import org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider; import org.apache.cxf.rt.security.rs.PrivateKeyPasswordProvider; import org.apache.cxf.systest.jaxrs.security.Book; import org.apache.cxf.systest.jaxrs.security.jose.BookStore; import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class JAXRSJweJwsTest extends AbstractBusClientServerTestBase { public static final String PORT = BookServerJwt.PORT; private static final String CLIENT_JWEJWS_PROPERTIES = "org/apache/cxf/systest/jaxrs/security/bob.rs.properties"; private static final String SERVER_JWEJWS_PROPERTIES = "org/apache/cxf/systest/jaxrs/security/alice.rs.properties"; private static final String ENCODED_MAC_KEY = "<KEY>" + "aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"; @BeforeClass public static void startServers() throws Exception { assertTrue("server did not launch correctly", launchServer(BookServerJwt.class, true)); registerBouncyCastleIfNeeded(); } private static void registerBouncyCastleIfNeeded() throws Exception { // Still need it for Oracle Java 7 and Java 8 Security.addProvider(new BouncyCastleProvider()); } @AfterClass public static void unregisterBouncyCastleIfNeeded() throws Exception { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); } @Test public void testJweJwkPlainTextRSA() throws Exception { String address = "https://localhost:" + PORT + "/jwejwkrsa"; BookStore bs = createJweBookStore(address, null); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweJwkBookBeanRSA() throws Exception { String address = "https://localhost:" + PORT + "/jwejwkrsa"; BookStore bs = createJweBookStore(address, Collections.singletonList(new JacksonJsonProvider())); Book book = bs.echoBook(new Book("book", 123L)); assertEquals("book", book.getName()); assertEquals(123L, book.getId()); } private BookStore createJweBookStore(String address, List<?> mbProviders) throws Exception { JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); providers.add(jweWriter); providers.add(new JweClientResponseFilter()); if (mbProviders != null) { providers.addAll(mbProviders); } bean.setProviders(providers); bean.getProperties(true).put("rs.security.encryption.out.properties", "org/apache/cxf/systest/jaxrs/security/bob.jwk.properties"); bean.getProperties(true).put("rs.security.encryption.in.properties", "org/apache/cxf/systest/jaxrs/security/alice.jwk.properties"); return bean.create(BookStore.class); } @Test public void testJweJwkAesWrap() throws Exception { String address = "https://localhost:" + PORT + "/jwejwkaeswrap"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); providers.add(jweWriter); providers.add(new JweClientResponseFilter()); bean.setProviders(providers); bean.getProperties(true).put("rs.security.encryption.properties", "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties"); bean.getProperties(true).put("jose.debug", true); BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweJwkAesCbcHMacInlineSet() throws Exception { doTestJweJwkAesCbcHMac("org/apache/cxf/systest/jaxrs/security/secret.aescbchmac.inlineset.properties"); } @Test public void testJweJwkAesCbcHMacInlineSingleKey() throws Exception { doTestJweJwkAesCbcHMac("org/apache/cxf/systest/jaxrs/security/secret.aescbchmac.inlinejwk.properties"); } private void doTestJweJwkAesCbcHMac(String propFile) throws Exception { String address = "https://localhost:" + PORT + "/jwejwkaescbchmac"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); providers.add(jweWriter); providers.add(new JweClientResponseFilter()); bean.setProviders(providers); bean.getProperties(true).put("rs.security.encryption.properties", propFile); PrivateKeyPasswordProvider provider = new PrivateKeyPasswordProviderImpl("Thus from my lips, by yours, my sin is purged."); bean.getProperties(true).put("rs.security.key.password.provider", provider); BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweRsaJwsRsa() throws Exception { String address = "https://localhost:" + PORT + "/jwejwsrsa"; BookStore bs = createJweJwsBookStore(address, null, null); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweRsaJwsRsaEncryptThenSign() throws Exception { String address = "https://localhost:" + PORT + "/jwejwsrsaencrsign"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JweWriterInterceptor jweWriter = new EncrSignJweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); providers.add(jweWriter); JwsWriterInterceptor jwsWriter = new EncrSignJwsWriterInterceptor(); jwsWriter.setUseJwsOutputStream(true); providers.add(jwsWriter); bean.setProviders(providers); bean.getProperties(true).put("rs.security.encryption.out.properties", SERVER_JWEJWS_PROPERTIES); bean.getProperties(true).put("rs.security.signature.out.properties", CLIENT_JWEJWS_PROPERTIES); PrivateKeyPasswordProvider provider = new PrivateKeyPasswordProviderImpl(); bean.getProperties(true).put("rs.security.signature.key.password.provider", provider); BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweRsaJwsRsaCert() throws Exception { String address = "https://localhost:" + PORT + "/jwejwsrsacert"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); providers.add(jweWriter); providers.add(new JweClientResponseFilter()); JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor(); jwsWriter.setUseJwsOutputStream(true); providers.add(jwsWriter); providers.add(new JwsClientResponseFilter()); bean.setProviders(providers); bean.getProperties(true).put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt"); bean.getProperties(true).put("rs.security.signature.out.properties", CLIENT_JWEJWS_PROPERTIES); bean.getProperties(true).put("rs.security.encryption.in.properties", CLIENT_JWEJWS_PROPERTIES); PrivateKeyPasswordProvider provider = new PrivateKeyPasswordProviderImpl(); bean.getProperties(true).put("rs.security.signature.key.password.provider", provider); bean.getProperties(true).put("rs.security.decryption.key.password.provider", provider); BookStore bs = bean.create(BookStore.class); WebClient.getConfig(bs).getRequestContext().put("rs.security.keystore.alias.jwe.out", "AliceCert"); WebClient.getConfig(bs).getRequestContext().put("rs.security.keystore.alias.jws.in", "AliceCert"); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweRsaJwsRsaCertInHeaders() throws Exception { String address = "https://localhost:" + PORT + "/jwejwsrsaCertInHeaders"; BookStore bs = createJweJwsBookStore(address, null, null); WebClient.getConfig(bs).getRequestContext().put("rs.security.signature.include.cert", "true"); WebClient.getConfig(bs).getRequestContext().put("rs.security.encryption.include.cert", "true"); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweRsaJwsPlainTextHMac() throws Exception { String address = "https://localhost:" + PORT + "/jwejwshmac"; HmacJwsSignatureProvider hmacProvider = new HmacJwsSignatureProvider(ENCODED_MAC_KEY, SignatureAlgorithm.HS256); BookStore bs = createJweJwsBookStore(address, hmacProvider, null); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweRsaJwsBookHMac() throws Exception { String address = "https://localhost:" + PORT + "/jwejwshmac"; HmacJwsSignatureProvider hmacProvider = new HmacJwsSignatureProvider(ENCODED_MAC_KEY, SignatureAlgorithm.HS256); BookStore bs = createJweJwsBookStore(address, hmacProvider, Collections.singletonList(new JacksonJsonProvider())); Book book = bs.echoBook(new Book("book", 123L)); assertEquals("book", book.getName()); assertEquals(123L, book.getId()); } @Test public void testJwsJwkPlainTextHMac() throws Exception { String address = "https://localhost:" + PORT + "/jwsjwkhmac"; BookStore bs = createJwsBookStore(address, null); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJwsJwkPlainTextHMacHttpHeaders() throws Exception { String address = "https://localhost:" + PORT + "/jwsjwkhmacHttpHeaders"; BookStore bs = createJwsBookStore(address, null, true, true); String text = bs.echoText("book"); assertEquals("book", text); } @Test(expected = BadRequestException.class) public void testJwsJwkPlainTextHMacHttpHeadersModified() throws Exception { String address = "https://localhost:" + PORT + "/jwsjwkhmacHttpHeaders"; BookStore bs = createJwsBookStore(address, null, true, true); WebClient.client(bs).header("Modify", "true"); bs.echoText("book"); } @Test public void testJwsJwkPlainTextHMacUnencoded() throws Exception { String address = "https://localhost:" + PORT + "/jwsjwkhmac"; BookStore bs = createJwsBookStore(address, null, false, false); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJwsJwkBookHMac() throws Exception { String address = "https://localhost:" + PORT + "/jwsjwkhmac"; BookStore bs = createJwsBookStore(address, Collections.singletonList(new JacksonJsonProvider())); Book book = bs.echoBook(new Book("book", 123L)); assertEquals("book", book.getName()); assertEquals(123L, book.getId()); } private BookStore createJwsBookStore(String address, List<?> mbProviders) throws Exception { return createJwsBookStore(address, mbProviders, true, false); } private BookStore createJwsBookStore(String address, List<?> mbProviders, boolean encodePayload, boolean protectHttpHeaders) throws Exception { JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor(); jwsWriter.setProtectHttpHeaders(protectHttpHeaders); jwsWriter.setEncodePayload(encodePayload); jwsWriter.setUseJwsOutputStream(true); providers.add(jwsWriter); providers.add(new JwsClientResponseFilter()); if (mbProviders != null) { providers.addAll(mbProviders); } bean.setProviders(providers); bean.getProperties(true).put("rs.security.signature.properties", "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties"); return bean.create(BookStore.class); } @Test public void testJwsJwkEC() throws Exception { String address = "https://localhost:" + PORT + "/jwsjwkec"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor(); jwsWriter.setUseJwsOutputStream(true); providers.add(jwsWriter); providers.add(new JwsClientResponseFilter()); bean.setProviders(providers); bean.getProperties(true).put("rs.security.signature.out.properties", "org/apache/cxf/systest/jaxrs/security/jws.ec.private.properties"); bean.getProperties(true).put("rs.security.signature.in.properties", "org/apache/cxf/systest/jaxrs/security/jws.ec.public.properties"); BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJwsJwkRSA() throws Exception { doTestJwsJwkRSA("https://localhost:" + PORT + "/jwsjwkrsa", false, false); } @Test public void testJwsJwkInHeadersRSA() throws Exception { doTestJwsJwkRSA("https://localhost:" + PORT + "/jwsjwkrsa", true, true); } @Test public void testJwsJwkKidOnlyInHeadersRSA() throws Exception { doTestJwsJwkRSA("https://localhost:" + PORT + "/jwsjwkrsa", false, true); } private void doTestJwsJwkRSA(String address, boolean includePublicKey, boolean includeKeyId) throws Exception { JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor(); jwsWriter.setUseJwsOutputStream(true); providers.add(jwsWriter); providers.add(new JwsClientResponseFilter()); bean.setProviders(providers); bean.getProperties(true).put("rs.security.signature.out.properties", "org/apache/cxf/systest/jaxrs/security/alice.jwk.properties"); bean.getProperties(true).put("rs.security.signature.in.properties", "org/apache/cxf/systest/jaxrs/security/bob.jwk.properties"); if (includePublicKey) { bean.getProperties(true).put("rs.security.signature.include.public.key", true); } if (includeKeyId) { bean.getProperties(true).put("rs.security.signature.include.key.id", true); } BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } private BookStore createJweJwsBookStore(String address, JwsSignatureProvider jwsSigProvider, List<?> mbProviders) throws Exception { JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); providers.add(jweWriter); providers.add(new JweClientResponseFilter()); JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor(); if (jwsSigProvider != null) { jwsWriter.setSignatureProvider(jwsSigProvider); } jwsWriter.setUseJwsOutputStream(true); providers.add(jwsWriter); providers.add(new JwsClientResponseFilter()); if (mbProviders != null) { providers.addAll(mbProviders); } bean.setProviders(providers); bean.getProperties(true).put("rs.security.encryption.out.properties", SERVER_JWEJWS_PROPERTIES); bean.getProperties(true).put("rs.security.signature.out.properties", CLIENT_JWEJWS_PROPERTIES); bean.getProperties(true).put("rs.security.encryption.in.properties", CLIENT_JWEJWS_PROPERTIES); bean.getProperties(true).put("rs.security.signature.in.properties", SERVER_JWEJWS_PROPERTIES); PrivateKeyPasswordProvider provider = new PrivateKeyPasswordProviderImpl(); bean.getProperties(true).put("rs.security.signature.key.password.provider", provider); bean.getProperties(true).put("rs.security.decryption.key.password.provider", provider); return bean.create(BookStore.class); } @Test public void testJweAesGcmDirect() throws Exception { String address = "https://localhost:" + PORT + "/jweaesgcmdirect"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); // writer JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); // reader JweClientResponseFilter jweReader = new JweClientResponseFilter(); providers.add(jweWriter); providers.add(jweReader); bean.setProviders(providers); bean.getProperties(true).put("rs.security.encryption.properties", "org/apache/cxf/systest/jaxrs/security/jwe.direct.properties"); BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } @Test public void testJweAesCbcHmac() throws Exception { String address = "https://localhost:" + PORT + "/jweaescbchmac"; JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean(); SpringBusFactory bf = new SpringBusFactory(); URL busFile = JAXRSJweJwsTest.class.getResource("client.xml"); Bus springBus = bf.createBus(busFile.toString()); bean.setBus(springBus); bean.setServiceClass(BookStore.class); bean.setAddress(address); List<Object> providers = new LinkedList<>(); // writer JweWriterInterceptor jweWriter = new JweWriterInterceptor(); jweWriter.setUseJweOutputStream(true); final String cekEncryptionKey = "<KEY>"; AesWrapKeyEncryptionAlgorithm keyEncryption = new AesWrapKeyEncryptionAlgorithm(cekEncryptionKey, KeyAlgorithm.A128KW); jweWriter.setEncryptionProvider(new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256, keyEncryption)); // reader JweClientResponseFilter jweReader = new JweClientResponseFilter(); jweReader.setDecryptionProvider(new AesCbcHmacJweDecryption( new AesWrapKeyDecryptionAlgorithm(cekEncryptionKey))); providers.add(jweWriter); providers.add(jweReader); bean.setProviders(providers); BookStore bs = bean.create(BookStore.class); String text = bs.echoText("book"); assertEquals("book", text); } // Test signing and encrypting an XML payload @Test public void testJweRsaJwsRsaXML() throws Exception { String address = "https://localhost:" + PORT + "/jwejwsrsa"; BookStore bs = createJweJwsBookStore(address, null, null); Book book = new Book(); book.setName("book"); book = bs.echoBookXml(book); assertEquals("book", book.getName()); } private static class PrivateKeyPasswordProviderImpl implements PrivateKeyPasswordProvider { private String password = "password"; PrivateKeyPasswordProviderImpl() { } PrivateKeyPasswordProviderImpl(String password) { this.password = password; } @Override public char[] getPassword(Properties storeProperties) { return password.toCharArray(); } } // Switch the priorities to have encryption run before signature @Priority(Priorities.JWS_WRITE_PRIORITY) private static class EncrSignJweWriterInterceptor extends JweWriterInterceptor { } // Switch the priorities to have encryption run before signature @Priority(Priorities.JWE_WRITE_PRIORITY) private static class EncrSignJwsWriterInterceptor extends JwsWriterInterceptor { } }
10,869
1,391
#include <u.h> #include <libc.h> #include <bio.h> #define mkdir plan9mkdir enum{ LEN = 8*1024, NFLDS = 6, /* filename, modes, uid, gid, mtime, bytes */ }; int selected(char*, int, char*[]); void mkdirs(char*, char*); void mkdir(char*, ulong, ulong, char*, char*); void extract(char*, ulong, ulong, char*, char*, uvlong); void seekpast(uvlong); void error(char*, ...); void warn(char*, ...); void usage(void); #pragma varargck argpos warn 1 #pragma varargck argpos error 1 Biobuf bin; uchar binbuf[2*LEN]; char linebuf[LEN]; int uflag; int hflag; int vflag; int Tflag; void main(int argc, char **argv) { Biobuf bout; char *fields[NFLDS], name[2*LEN], *p, *namep; char *uid, *gid; ulong mode, mtime; uvlong bytes; quotefmtinstall(); namep = name; ARGBEGIN{ case 'd': p = ARGF(); if(strlen(p) >= LEN) error("destination fs name too long\n"); strcpy(name, p); namep = name + strlen(name); break; case 'h': hflag = 1; Binit(&bout, 1, OWRITE); break; case 'u': uflag = 1; Tflag = 1; break; case 'T': Tflag = 1; break; case 'v': vflag = 1; break; default: usage(); }ARGEND Binits(&bin, 0, OREAD, binbuf, sizeof binbuf); while(p = Brdline(&bin, '\n')){ p[Blinelen(&bin)-1] = '\0'; strcpy(linebuf, p); p = linebuf; if(strcmp(p, "end of archive") == 0){ Bterm(&bout); fprint(2, "done\n"); exits(0); } if (gettokens(p, fields, NFLDS, " \t") != NFLDS){ warn("too few fields in file header"); continue; } p = unquotestrdup(fields[0]); strcpy(namep, p); free(p); mode = strtoul(fields[1], 0, 8); uid = fields[2]; gid = fields[3]; mtime = strtoul(fields[4], 0, 10); bytes = strtoull(fields[5], 0, 10); if(argc){ if(!selected(namep, argc, argv)){ if(bytes) seekpast(bytes); continue; } mkdirs(name, namep); } if(hflag){ Bprint(&bout, "%q %luo %q %q %lud %llud\n", name, mode, uid, gid, mtime, bytes); if(bytes) seekpast(bytes); continue; } if(mode & DMDIR) mkdir(name, mode, mtime, uid, gid); else extract(name, mode, mtime, uid, gid, bytes); } fprint(2, "premature end of archive\n"); exits("premature end of archive"); } int fileprefix(char *prefix, char *s) { while(*prefix) if(*prefix++ != *s++) return 0; if(*s && *s != '/') return 0; return 1; } int selected(char *s, int argc, char *argv[]) { int i; for(i=0; i<argc; i++) if(fileprefix(argv[i], s)) return 1; return 0; } void mkdirs(char *name, char *namep) { char buf[2*LEN], *p; int fd; strcpy(buf, name); for(p = &buf[namep - name]; p = utfrune(p, '/'); p++){ if(p[1] == '\0') return; *p = 0; fd = create(buf, OREAD, 0775|DMDIR); close(fd); *p = '/'; } } void mkdir(char *name, ulong mode, ulong mtime, char *uid, char *gid) { Dir *d, xd; int fd; char *p; char olderr[256]; fd = create(name, OREAD, mode); if(fd < 0){ rerrstr(olderr, sizeof(olderr)); if((d = dirstat(name)) == nil || !(d->mode & DMDIR)){ free(d); warn("can't make directory %q, mode %luo: %s", name, mode, olderr); return; } free(d); } close(fd); d = &xd; nulldir(d); p = utfrrune(name, L'/'); if(p) p++; else p = name; d->name = p; if(uflag){ d->uid = uid; d->gid = gid; } if(Tflag) d->mtime = mtime; d->mode = mode; if(dirwstat(name, d) < 0) warn("can't set modes for %q: %r", name); if(uflag||Tflag){ if((d = dirstat(name)) == nil){ warn("can't reread modes for %q: %r", name); return; } if(Tflag && d->mtime != mtime) warn("%q: time mismatch %lud %lud\n", name, mtime, d->mtime); if(uflag && strcmp(uid, d->uid)) warn("%q: uid mismatch %q %q", name, uid, d->uid); if(uflag && strcmp(gid, d->gid)) warn("%q: gid mismatch %q %q", name, gid, d->gid); } } void extract(char *name, ulong mode, ulong mtime, char *uid, char *gid, uvlong bytes) { Dir d, *nd; Biobuf *b; char buf[LEN]; char *p; ulong n; uvlong tot; if(vflag) print("x %q %llud bytes\n", name, bytes); b = Bopen(name, OWRITE); if(!b){ warn("can't make file %q: %r", name); seekpast(bytes); return; } for(tot = 0; tot < bytes; tot += n){ n = sizeof buf; if(tot + n > bytes) n = bytes - tot; n = Bread(&bin, buf, n); if(n <= 0) error("premature eof reading %q", name); if(Bwrite(b, buf, n) != n) warn("error writing %q: %r", name); } nulldir(&d); p = utfrrune(name, '/'); if(p) p++; else p = name; d.name = p; if(uflag){ d.uid = uid; d.gid = gid; } if(Tflag) d.mtime = mtime; d.mode = mode; Bflush(b); if(dirfwstat(Bfildes(b), &d) < 0) warn("can't set modes for %q: %r", name); if(uflag||Tflag){ if((nd = dirfstat(Bfildes(b))) == nil) warn("can't reread modes for %q: %r", name); else{ if(Tflag && nd->mtime != mtime) warn("%q: time mismatch %lud %lud\n", name, mtime, nd->mtime); if(uflag && strcmp(uid, nd->uid)) warn("%q: uid mismatch %q %q", name, uid, nd->uid); if(uflag && strcmp(gid, nd->gid)) warn("%q: gid mismatch %q %q", name, gid, nd->gid); free(nd); } } Bterm(b); } void seekpast(uvlong bytes) { char buf[LEN]; long n; uvlong tot; for(tot = 0; tot < bytes; tot += n){ n = sizeof buf; if(tot + n > bytes) n = bytes - tot; n = Bread(&bin, buf, n); if(n < 0) error("premature eof"); } } void error(char *fmt, ...) { char buf[1024]; va_list arg; sprint(buf, "%q: ", argv0); va_start(arg, fmt); vseprint(buf+strlen(buf), buf+sizeof(buf), fmt, arg); va_end(arg); fprint(2, "%s\n", buf); exits(0); } void warn(char *fmt, ...) { char buf[1024]; va_list arg; sprint(buf, "%q: ", argv0); va_start(arg, fmt); vseprint(buf+strlen(buf), buf+sizeof(buf), fmt, arg); va_end(arg); fprint(2, "%s\n", buf); } void usage(void) { fprint(2, "usage: mkext [-h] [-u] [-v] [-d dest-fs] [file ...]\n"); exits("usage"); }
2,935
350
<filename>src/py2.x/ml/jqxxsz/8.Regression/regression.py<gh_stars>100-1000 #!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : regression.py @Time : 2019/07/01 19:02:32 @Author : <NAME> @Version : 1.0 @Contact : <EMAIL> @Desc : 简单的线性回归和局部加权线性回归 @github : https://github.com/aimi-cn/AILearners ''' # here put the import lib import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties ''' @description: 加载数据 @param: fileName - 文件名 @return: xArr - x数据集 yArr - y数据集 ''' def loadDataSet(fileName): numFeat = len(open(fileName).readline().split('\t')) - 1 xArr = []; yArr = [] fr = open(fileName) for line in fr.readlines(): lineArr =[] curLine = line.strip().split('\t') for i in range(numFeat): lineArr.append(float(curLine[i])) xArr.append(lineArr) yArr.append(float(curLine[-1])) return xArr, yArr ''' @description: 绘制数据集 @param: None @return: None ''' def plotDataSet(): xArr, yArr = loadDataSet('C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/ex0.txt') #加载数据集 n = len(xArr) #数据个数 xcord = []; ycord = [] #样本点 for i in range(n): xcord.append(xArr[i][1]); ycord.append(yArr[i]) #样本点 fig = plt.figure() ax = fig.add_subplot(111) #添加subplot ax.scatter(xcord, ycord, s = 20, c = 'blue',alpha = .5) #绘制样本点 plt.title('DataSet') #绘制title plt.xlabel('X') plt.show() ''' @description: 计算回归系数w @param: xArr - x数据集 yArr - y数据集 @return: ws - 回归系数 ''' def standRegres(xArr,yArr): xMat = np.mat(xArr); yMat = np.mat(yArr).T #根据文中推导的公示计算回归系数 xTx = xMat.T * xMat if np.linalg.det(xTx) == 0.0: print("矩阵为奇异矩阵,不能求逆").decode('utf-8').encoding('gb2312') return ws = xTx.I * (xMat.T*yMat) return ws def plotRegression(): xArr, yArr = loadDataSet('C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/ex0.txt') #加载数据集 ws = standRegres(xArr, yArr) #计算回归系数 xMat = np.mat(xArr) #创建xMat矩阵 yMat = np.mat(yArr) #创建yMat矩阵 xCopy = xMat.copy() #深拷贝xMat矩阵 xCopy.sort(0) #排序 yHat = xCopy * ws #计算对应的y值 fig = plt.figure() ax = fig.add_subplot(111) #添加subplot ax.plot(xCopy[:, 1], yHat, c = 'red') #绘制回归曲线 ax.scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue',alpha = .5) #绘制样本点 plt.title('DataSet') #绘制title plt.xlabel('X') plt.show() ''' @description:使用局部加权线性回归计算回归系数w @param: testPoint - 测试样本点 xArr - x数据集 yArr - y数据集 k - 高斯核的k,自定义参数 @return: ws - 回归系数 ''' def lwlr(testPoint, xArr, yArr, k = 1.0): xMat = np.mat(xArr); yMat = np.mat(yArr).T m = np.shape(xMat)[0] weights = np.mat(np.eye((m))) #创建权重对角矩阵 for j in range(m): #遍历数据集计算每个样本的权重 diffMat = testPoint - xMat[j, :] weights[j, j] = np.exp(diffMat * diffMat.T/(-2.0 * k**2)) xTx = xMat.T * (weights * xMat) if np.linalg.det(xTx) == 0.0: print("矩阵为奇异矩阵,不能求逆").decode('utf-8').encode('gb2312') return ws = xTx.I * (xMat.T * (weights * yMat)) #计算回归系数 return testPoint * ws ''' @description: 局部加权线性回归测试 @param: testArr - 测试数据集 xArr - x数据集 yArr - y数据集 k - 高斯核的k,自定义参数 @return: yHat 回归系数 ''' def lwlrTest(testArr, xArr, yArr, k=1.0): m = np.shape(testArr)[0] #计算测试数据集大小 yHat = np.zeros(m) for i in range(m): #对每个样本点进行预测 yHat[i] = lwlr(testArr[i],xArr,yArr,k) return yHat ''' @description: 绘制多条局部加权回归曲线 @param: None @return: None ''' def plotlwlrRegression(): font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) xArr, yArr = loadDataSet('C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/ex0.txt') #加载数据集 yHat_1 = lwlrTest(xArr, xArr, yArr, 1.0) #根据局部加权线性回归计算yHat yHat_2 = lwlrTest(xArr, xArr, yArr, 0.01) #根据局部加权线性回归计算yHat yHat_3 = lwlrTest(xArr, xArr, yArr, 0.003) #根据局部加权线性回归计算yHat xMat = np.mat(xArr) #创建xMat矩阵 yMat = np.mat(yArr) #创建yMat矩阵 srtInd = xMat[:, 1].argsort(0) #排序,返回索引值 xSort = xMat[srtInd][:,0,:] fig, axs = plt.subplots(nrows=3, ncols=1,sharex=False, sharey=False, figsize=(10,8)) axs[0].plot(xSort[:, 1], yHat_1[srtInd], c = 'red') #绘制回归曲线 axs[1].plot(xSort[:, 1], yHat_2[srtInd], c = 'red') #绘制回归曲线 axs[2].plot(xSort[:, 1], yHat_3[srtInd], c = 'red') #绘制回归曲线 axs[0].scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue', alpha = .5) #绘制样本点 axs[1].scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue', alpha = .5) #绘制样本点 axs[2].scatter(xMat[:,1].flatten().A[0], yMat.flatten().A[0], s = 20, c = 'blue', alpha = .5) #绘制样本点 #设置标题,x轴label,y轴label axs0_title_text = axs[0].set_title(u'局部加权回归曲线,k=1.0',FontProperties=font) axs1_title_text = axs[1].set_title(u'局部加权回归曲线,k=0.01',FontProperties=font) axs2_title_text = axs[2].set_title(u'局部加权回归曲线,k=0.003',FontProperties=font) plt.setp(axs0_title_text, size=8, weight='bold', color='red') plt.setp(axs1_title_text, size=8, weight='bold', color='red') plt.setp(axs2_title_text, size=8, weight='bold', color='red') plt.xlabel('X') plt.show() if __name__ == "__main__": # plotDataSet() # plotRegression() # xArr, yArr = loadDataSet('C:/Users/Administrator/Desktop/blog/github/AILearners/data/ml/jqxxsz/8.Regression/ex0.txt') # ws = standRegres(xArr, yArr) #计算回归系数 # xMat = np.mat(xArr) #创建xMat矩阵 # yMat = np.mat(yArr) #创建yMat矩阵 # yHat = xMat * ws # print(np.corrcoef(yHat.T, yMat)) plotlwlrRegression()
5,282
4,403
<filename>hutool-extra/src/main/java/cn/hutool/extra/ssh/package-info.java /** * Jsch封装,包括端口映射、SFTP封装等,入口为JschUtil * * @author looly * */ package cn.hutool.extra.ssh;
104
1,403
<filename>sources/Renderer/OpenGL/GLRenderSystem.cpp /* * GLRenderSystem.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by <NAME>) * See "LICENSE.txt" for license information. */ #include "GLRenderSystem.h" #include "GLProfile.h" #include "Texture/GLMipGenerator.h" #include "Texture/GLTextureViewPool.h" #include "Ext/GLExtensions.h" #include "Ext/GLExtensionRegistry.h" #include "RenderState/GLStatePool.h" #include "../RenderSystemUtils.h" #include "GLTypes.h" #include "GLCore.h" #include "Buffer/GLBufferWithVAO.h" #include "Buffer/GLBufferArrayWithVAO.h" #include "../CheckedCast.h" #include "../TextureUtils.h" #include "../../Core/Helper.h" #include "../../Core/Assertion.h" #include "GLRenderingCaps.h" #include "Command/GLImmediateCommandBuffer.h" #include "Command/GLDeferredCommandBuffer.h" #include "RenderState/GLGraphicsPSO.h" #include "RenderState/GLComputePSO.h" namespace LLGL { #ifdef LLGL_OPENGLES3 #define LLGL_GLES3_NOT_IMPLEMENTED \ throw std::runtime_error("not implemented for GLES3: " + std::string(__FUNCTION__)) #endif /* ----- Common ----- */ GLRenderSystem::GLRenderSystem(const RenderSystemDescriptor& renderSystemDesc) { /* Extract optional renderer configuartion */ if (auto rendererConfigGL = GetRendererConfiguration<RendererConfigurationOpenGL>(renderSystemDesc)) config_ = *rendererConfigGL; } GLRenderSystem::~GLRenderSystem() { /* Clear all render state containers first, the rest will be deleted automatically */ GLTextureViewPool::Get().Clear(); GLMipGenerator::Get().Clear(); GLStatePool::Get().Clear(); } /* ----- Render Context ----- */ // private GLRenderContext* GLRenderSystem::GetSharedRenderContext() const { return (!renderContexts_.empty() ? renderContexts_.begin()->get() : nullptr); } RenderContext* GLRenderSystem::CreateRenderContext(const RenderContextDescriptor& desc, const std::shared_ptr<Surface>& surface) { return AddRenderContext(MakeUnique<GLRenderContext>(desc, config_, surface, GetSharedRenderContext())); } void GLRenderSystem::Release(RenderContext& renderContext) { RemoveFromUniqueSet(renderContexts_, &renderContext); } /* ----- Command queues ----- */ CommandQueue* GLRenderSystem::GetCommandQueue() { return commandQueue_.get(); } /* ----- Command buffers ----- */ CommandBuffer* GLRenderSystem::CreateCommandBuffer(const CommandBufferDescriptor& desc) { /* Get state manager from shared render context */ if (auto sharedContext = GetSharedRenderContext()) { if ((desc.flags & (CommandBufferFlags::DeferredSubmit | CommandBufferFlags::MultiSubmit)) != 0) { /* Create deferred command buffer */ return TakeOwnership( commandBuffers_, MakeUnique<GLDeferredCommandBuffer>(desc.flags) ); } else { /* Create immediate command buffer */ return TakeOwnership( commandBuffers_, MakeUnique<GLImmediateCommandBuffer>(sharedContext->GetStateManager()) ); } } else throw std::runtime_error("cannot create OpenGL command buffer without active render context"); } void GLRenderSystem::Release(CommandBuffer& commandBuffer) { RemoveFromUniqueSet(commandBuffers_, &commandBuffer); } /* ----- Buffers ------ */ static GLbitfield GetGLBufferStorageFlags(long cpuAccessFlags) { #ifdef GL_ARB_buffer_storage GLbitfield flagsGL = 0; /* Allways enable dynamic storage, to enable usage of 'glBufferSubData' */ flagsGL |= GL_DYNAMIC_STORAGE_BIT; if ((cpuAccessFlags & CPUAccessFlags::Read) != 0) flagsGL |= GL_MAP_READ_BIT; if ((cpuAccessFlags & CPUAccessFlags::Write) != 0) flagsGL |= GL_MAP_WRITE_BIT; return flagsGL; #else return 0; #endif // /GL_ARB_buffer_storage } static GLenum GetGLBufferUsage(long miscFlags) { return ((miscFlags & MiscFlags::DynamicUsage) != 0 ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); } static void GLBufferStorage(GLBuffer& bufferGL, const BufferDescriptor& desc, const void* initialData) { bufferGL.BufferStorage( static_cast<GLsizeiptr>(desc.size), initialData, GetGLBufferStorageFlags(desc.cpuAccessFlags), GetGLBufferUsage(desc.miscFlags) ); } Buffer* GLRenderSystem::CreateBuffer(const BufferDescriptor& desc, const void* initialData) { AssertCreateBuffer(desc, static_cast<std::uint64_t>(std::numeric_limits<GLsizeiptr>::max())); auto bufferGL = CreateGLBuffer(desc, initialData); /* Store meta data for certain types of buffers */ if ((desc.bindFlags & BindFlags::IndexBuffer) != 0 && desc.format != Format::Undefined) bufferGL->SetIndexType(desc.format); return bufferGL; } // private GLBuffer* GLRenderSystem::CreateGLBuffer(const BufferDescriptor& desc, const void* initialData) { /* Create either base of sub-class GLBuffer object */ if ((desc.bindFlags & BindFlags::VertexBuffer) != 0) { /* Create buffer with VAO and build vertex array */ auto bufferGL = MakeUnique<GLBufferWithVAO>(desc.bindFlags); { GLBufferStorage(*bufferGL, desc, initialData); bufferGL->BuildVertexArray(desc.vertexAttribs.size(), desc.vertexAttribs.data()); } return TakeOwnership(buffers_, std::move(bufferGL)); } else { /* Create generic buffer */ auto bufferGL = MakeUnique<GLBuffer>(desc.bindFlags); { GLBufferStorage(*bufferGL, desc, initialData); } return TakeOwnership(buffers_, std::move(bufferGL)); } } BufferArray* GLRenderSystem::CreateBufferArray(std::uint32_t numBuffers, Buffer* const * bufferArray) { AssertCreateBufferArray(numBuffers, bufferArray); auto refBindFlags = bufferArray[0]->GetBindFlags(); if ((refBindFlags & BindFlags::VertexBuffer) != 0) { /* Create vertex buffer array and build VAO */ auto vertexBufferArray = MakeUnique<GLBufferArrayWithVAO>(refBindFlags); vertexBufferArray->BuildVertexArray(numBuffers, bufferArray); return TakeOwnership(bufferArrays_, std::move(vertexBufferArray)); } return TakeOwnership(bufferArrays_, MakeUnique<GLBufferArray>(refBindFlags, numBuffers, bufferArray)); } void GLRenderSystem::Release(Buffer& buffer) { RemoveFromUniqueSet(buffers_, &buffer); } void GLRenderSystem::Release(BufferArray& bufferArray) { RemoveFromUniqueSet(bufferArrays_, &bufferArray); } void GLRenderSystem::WriteBuffer(Buffer& dstBuffer, std::uint64_t dstOffset, const void* data, std::uint64_t dataSize) { auto& dstBufferGL = LLGL_CAST(GLBuffer&, dstBuffer); dstBufferGL.BufferSubData(static_cast<GLintptr>(dstOffset), static_cast<GLsizeiptr>(dataSize), data); } void* GLRenderSystem::MapBuffer(Buffer& buffer, const CPUAccess access) { auto& bufferGL = LLGL_CAST(GLBuffer&, buffer); return bufferGL.MapBuffer(GLTypes::Map(access)); } void GLRenderSystem::UnmapBuffer(Buffer& buffer) { auto& bufferGL = LLGL_CAST(GLBuffer&, buffer); bufferGL.UnmapBuffer(); } /* ----- Textures ----- */ //private void GLRenderSystem::ValidateGLTextureType(const TextureType type) { /* Validate texture type for this GL device */ switch (type) { case TextureType::Texture1D: case TextureType::Texture2D: break; case TextureType::Texture3D: LLGL_ASSERT_FEATURE_SUPPORT(has3DTextures); break; case TextureType::TextureCube: LLGL_ASSERT_FEATURE_SUPPORT(hasCubeTextures); break; case TextureType::Texture1DArray: case TextureType::Texture2DArray: LLGL_ASSERT_FEATURE_SUPPORT(hasArrayTextures); break; case TextureType::TextureCubeArray: LLGL_ASSERT_FEATURE_SUPPORT(hasCubeArrayTextures); break; case TextureType::Texture2DMS: case TextureType::Texture2DMSArray: LLGL_ASSERT_FEATURE_SUPPORT(hasMultiSampleTextures); break; default: throw std::invalid_argument("failed to create texture with invalid texture type"); break; } } Texture* GLRenderSystem::CreateTexture(const TextureDescriptor& textureDesc, const SrcImageDescriptor* imageDesc) { ValidateGLTextureType(textureDesc.type); /* Create <GLTexture> object; will result in a GL renderbuffer or texture instance */ auto texture = MakeUnique<GLTexture>(textureDesc); /* Initialize either renderbuffer or texture image storage */ texture->BindAndAllocStorage(textureDesc, imageDesc); return TakeOwnership(textures_, std::move(texture)); } #if 0//TODO Texture* GLRenderSystem::CreateTextureView(Texture& sharedTexture, const TextureViewDescriptor& textureViewDesc) { LLGL_ASSERT_FEATURE_SUPPORT(hasTextureViews); auto& sharedTextureGL = LLGL_CAST(GLTexture&, sharedTexture); auto texture = MakeUnique<GLTexture>(textureViewDesc.type); /* Initialize texture as texture-view */ texture->TextureView(sharedTextureGL, textureViewDesc); /* Initialize texture swizzle (if specified) */ if (!IsTextureSwizzleIdentity(textureViewDesc.swizzle)) { /* Bind texture */ GLStateManager::Get().BindGLTexture(*texture); /* Initialize texture parameters for the first time */ auto target = GLTypes::Map(textureViewDesc.type); glTexParameteri(target, GL_TEXTURE_SWIZZLE_R, GLTypes::Map(textureViewDesc.swizzle.r)); glTexParameteri(target, GL_TEXTURE_SWIZZLE_G, GLTypes::Map(textureViewDesc.swizzle.g)); glTexParameteri(target, GL_TEXTURE_SWIZZLE_B, GLTypes::Map(textureViewDesc.swizzle.b)); glTexParameteri(target, GL_TEXTURE_SWIZZLE_A, GLTypes::Map(textureViewDesc.swizzle.a)); } return TakeOwnership(textures_, std::move(texture)); } #endif void GLRenderSystem::Release(Texture& texture) { RemoveFromUniqueSet(textures_, &texture); } void GLRenderSystem::WriteTexture(Texture& texture, const TextureRegion& textureRegion, const SrcImageDescriptor& imageDesc) { /* Bind texture and write texture sub data */ auto& textureGL = LLGL_CAST(GLTexture&, texture); textureGL.TextureSubImage(textureRegion, imageDesc, false); } void GLRenderSystem::ReadTexture(Texture& texture, const TextureRegion& textureRegion, const DstImageDescriptor& imageDesc) { /* Bind texture and write texture sub data */ LLGL_ASSERT_PTR(imageDesc.data); auto& textureGL = LLGL_CAST(GLTexture&, texture); textureGL.GetTextureSubImage(textureRegion, imageDesc, false); } /* ----- Sampler States ---- */ Sampler* GLRenderSystem::CreateSampler(const SamplerDescriptor& desc) { #ifdef LLGL_GL_ENABLE_OPENGL2X /* If GL_ARB_sampler_objects is not supported, use emulated sampler states */ if (!HasNativeSamplers()) { auto samplerGL2X = MakeUnique<GL2XSampler>(); samplerGL2X->SetDesc(desc); return TakeOwnership(samplersGL2X_, std::move(samplerGL2X)); } #endif /* Create native GL sampler state */ LLGL_ASSERT_FEATURE_SUPPORT(hasSamplers); auto sampler = MakeUnique<GLSampler>(); sampler->SetDesc(desc); return TakeOwnership(samplers_, std::move(sampler)); } void GLRenderSystem::Release(Sampler& sampler) { #ifdef LLGL_GL_ENABLE_OPENGL2X /* If GL_ARB_sampler_objects is not supported, release emulated sampler states */ if (!HasNativeSamplers()) RemoveFromUniqueSet(samplersGL2X_, &sampler); else RemoveFromUniqueSet(samplers_, &sampler); #else RemoveFromUniqueSet(samplers_, &sampler); #endif } /* ----- Resource Heaps ----- */ ResourceHeap* GLRenderSystem::CreateResourceHeap(const ResourceHeapDescriptor& desc) { return TakeOwnership(resourceHeaps_, MakeUnique<GLResourceHeap>(desc)); } void GLRenderSystem::Release(ResourceHeap& resourceHeap) { RemoveFromUniqueSet(resourceHeaps_, &resourceHeap); } /* ----- Render Passes ----- */ RenderPass* GLRenderSystem::CreateRenderPass(const RenderPassDescriptor& desc) { AssertCreateRenderPass(desc); return TakeOwnership(renderPasses_, MakeUnique<GLRenderPass>(desc)); } void GLRenderSystem::Release(RenderPass& renderPass) { RemoveFromUniqueSet(renderPasses_, &renderPass); } /* ----- Render Targets ----- */ RenderTarget* GLRenderSystem::CreateRenderTarget(const RenderTargetDescriptor& desc) { LLGL_ASSERT_FEATURE_SUPPORT(hasRenderTargets); AssertCreateRenderTarget(desc); return TakeOwnership(renderTargets_, MakeUnique<GLRenderTarget>(desc)); } void GLRenderSystem::Release(RenderTarget& renderTarget) { RemoveFromUniqueSet(renderTargets_, &renderTarget); } /* ----- Shader ----- */ Shader* GLRenderSystem::CreateShader(const ShaderDescriptor& desc) { AssertCreateShader(desc); /* Validate rendering capabilities for required shader type */ switch (desc.type) { case ShaderType::Geometry: LLGL_ASSERT_FEATURE_SUPPORT(hasGeometryShaders); break; case ShaderType::TessControl: case ShaderType::TessEvaluation: LLGL_ASSERT_FEATURE_SUPPORT(hasTessellationShaders); break; case ShaderType::Compute: LLGL_ASSERT_FEATURE_SUPPORT(hasComputeShaders); break; default: break; } /* Make and return shader object */ return TakeOwnership(shaders_, MakeUnique<GLShader>(desc)); } ShaderProgram* GLRenderSystem::CreateShaderProgram(const ShaderProgramDescriptor& desc) { AssertCreateShaderProgram(desc); return TakeOwnership(shaderPrograms_, MakeUnique<GLShaderProgram>(desc)); } void GLRenderSystem::Release(Shader& shader) { RemoveFromUniqueSet(shaders_, &shader); } void GLRenderSystem::Release(ShaderProgram& shaderProgram) { RemoveFromUniqueSet(shaderPrograms_, &shaderProgram); } /* ----- Pipeline Layouts ----- */ PipelineLayout* GLRenderSystem::CreatePipelineLayout(const PipelineLayoutDescriptor& desc) { return TakeOwnership(pipelineLayouts_, MakeUnique<GLPipelineLayout>(desc)); } void GLRenderSystem::Release(PipelineLayout& pipelineLayout) { RemoveFromUniqueSet(pipelineLayouts_, &pipelineLayout); } /* ----- Pipeline States ----- */ PipelineState* GLRenderSystem::CreatePipelineState(const Blob& /*serializedCache*/) { return nullptr;//TODO } PipelineState* GLRenderSystem::CreatePipelineState(const GraphicsPipelineDescriptor& desc, std::unique_ptr<Blob>* /*serializedCache*/) { return TakeOwnership(pipelineStates_, MakeUnique<GLGraphicsPSO>(desc, GetRenderingCaps().limits)); } PipelineState* GLRenderSystem::CreatePipelineState(const ComputePipelineDescriptor& desc, std::unique_ptr<Blob>* /*serializedCache*/) { return TakeOwnership(pipelineStates_, MakeUnique<GLComputePSO>(desc)); } void GLRenderSystem::Release(PipelineState& pipelineState) { RemoveFromUniqueSet(pipelineStates_, &pipelineState); } /* ----- Queries ----- */ QueryHeap* GLRenderSystem::CreateQueryHeap(const QueryHeapDescriptor& desc) { return TakeOwnership(queryHeaps_, MakeUnique<GLQueryHeap>(desc)); } void GLRenderSystem::Release(QueryHeap& queryHeap) { RemoveFromUniqueSet(queryHeaps_, &queryHeap); } /* ----- Fences ----- */ Fence* GLRenderSystem::CreateFence() { return TakeOwnership(fences_, MakeUnique<GLFence>()); } void GLRenderSystem::Release(Fence& fence) { RemoveFromUniqueSet(fences_, &fence); } /* * ======= Protected: ======= */ RenderContext* GLRenderSystem::AddRenderContext(std::unique_ptr<GLRenderContext>&& renderContext) { /* Create devices that require an active GL context */ if (renderContexts_.empty()) CreateGLContextDependentDevices(*renderContext); /* Use uniform clipping space */ GLStateManager::Get().DetermineExtensionsAndLimits(); #ifdef LLGL_OPENGL GLStateManager::Get().SetClipControl(GL_UPPER_LEFT, GL_ZERO_TO_ONE); #endif /* Take ownership and return raw pointer */ return TakeOwnership(renderContexts_, std::move(renderContext)); } /* * ======= Private: ======= */ void GLRenderSystem::CreateGLContextDependentDevices(GLRenderContext& renderContext) { const bool hasGLCoreProfile = (config_.contextProfile == OpenGLContextProfile::CoreProfile); /* Load all OpenGL extensions */ LoadGLExtensions(hasGLCoreProfile); /* Enable debug callback function */ if (debugCallback_) SetDebugCallback(debugCallback_); /* Create command queue instance */ commandQueue_ = MakeUnique<GLCommandQueue>(renderContext.GetStateManager()); } void GLRenderSystem::LoadGLExtensions(bool hasGLCoreProfile) { /* Load OpenGL extensions if not already done */ if (!AreExtensionsLoaded()) { /* Query extensions and load all of them */ auto extensions = QueryExtensions(hasGLCoreProfile); LoadAllExtensions(extensions, hasGLCoreProfile); /* Query and store all renderer information and capabilities */ QueryRendererInfo(); QueryRenderingCaps(); } } #ifdef GL_KHR_debug void APIENTRY GLDebugCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { /* Generate output stream */ std::stringstream typeStr; typeStr << "OpenGL debug callback (" << GLDebugSourceToStr(source) << ", " << GLDebugTypeToStr(type) << ", " << GLDebugSeverityToStr(severity) << ")"; /* Call debug callback */ auto debugCallback = reinterpret_cast<const DebugCallback*>(userParam); (*debugCallback)(typeStr.str(), message); } #endif // /GL_KHR_debug void GLRenderSystem::SetDebugCallback(const DebugCallback& debugCallback) { #ifdef GL_KHR_debug if (HasExtension(GLExt::KHR_debug)) { debugCallback_ = debugCallback; if (debugCallback_) { GLStateManager::Get().Enable(GLState::DEBUG_OUTPUT); GLStateManager::Get().Enable(GLState::DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(GLDebugCallback, &debugCallback_); } else { GLStateManager::Get().Disable(GLState::DEBUG_OUTPUT); GLStateManager::Get().Disable(GLState::DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(nullptr, nullptr); } } #endif // /GL_KHR_debug } static std::string GLGetString(GLenum name) { auto bytes = glGetString(name); return (bytes != nullptr ? std::string(reinterpret_cast<const char*>(bytes)) : ""); } void GLRenderSystem::QueryRendererInfo() { RendererInfo info; info.rendererName = GLProfile::GetAPIName() + std::string(" ") + GLGetString(GL_VERSION); info.deviceName = GLGetString(GL_RENDERER); info.vendorName = GLGetString(GL_VENDOR); info.shadingLanguageName = GLProfile::GetShadingLanguageName() + std::string(" ") + GLGetString(GL_SHADING_LANGUAGE_VERSION); SetRendererInfo(info); } void GLRenderSystem::QueryRenderingCaps() { RenderingCapabilities caps; GLQueryRenderingCaps(caps); SetRenderingCaps(caps); } } // /namespace LLGL // ================================================================================
7,082
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ios/chrome/browser/ui/overlays/test/fake_overlay_request_coordinator_delegate.h" FakeOverlayRequestCoordinatorDelegate::FakeOverlayRequestCoordinatorDelegate() = default; FakeOverlayRequestCoordinatorDelegate:: ~FakeOverlayRequestCoordinatorDelegate() = default; bool FakeOverlayRequestCoordinatorDelegate::HasUIBeenPresented( OverlayRequest* request) const { return states_.find(request) != states_.end() && states_.at(request) == PresentationState::kPresented; } bool FakeOverlayRequestCoordinatorDelegate::HasUIBeenDismissed( OverlayRequest* request) const { return states_.find(request) != states_.end() && states_.at(request) == PresentationState::kDismissed; } void FakeOverlayRequestCoordinatorDelegate::OverlayUIDidFinishPresentation( OverlayRequest* request) { states_[request] = PresentationState::kPresented; } void FakeOverlayRequestCoordinatorDelegate::OverlayUIDidFinishDismissal( OverlayRequest* request) { states_[request] = PresentationState::kDismissed; }
387
2,133
<reponame>uavosky/uavosky-qgroundcontrol<filename>src/QtLocationPlugin/qtlocation/src/location/maps/qgeoroutesegment.h /**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL3$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPLv3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or later as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information to ** ensure the GNU General Public License version 2.0 requirements will be ** met: http://www.gnu.org/licenses/gpl-2.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QGEOROUTESEGMENT_H #define QGEOROUTESEGMENT_H #include <QtCore/QExplicitlySharedDataPointer> #include <QtCore/QList> #include <QtLocation/qlocationglobal.h> QT_BEGIN_NAMESPACE class QGeoCoordinate; class QGeoManeuver; class QGeoRouteSegmentPrivate; class Q_LOCATION_EXPORT QGeoRouteSegment { public: QGeoRouteSegment(); QGeoRouteSegment(const QGeoRouteSegment &other); ~QGeoRouteSegment(); QGeoRouteSegment &operator= (const QGeoRouteSegment &other); bool operator ==(const QGeoRouteSegment &other) const; bool operator !=(const QGeoRouteSegment &other) const; bool isValid() const; void setNextRouteSegment(const QGeoRouteSegment &routeSegment); QGeoRouteSegment nextRouteSegment() const; void setTravelTime(int secs); int travelTime() const; void setDistance(qreal distance); qreal distance() const; void setPath(const QList<QGeoCoordinate> &path); QList<QGeoCoordinate> path() const; void setManeuver(const QGeoManeuver &maneuver); QGeoManeuver maneuver() const; protected: QGeoRouteSegment(QExplicitlySharedDataPointer<QGeoRouteSegmentPrivate> &d_ptr); private: QExplicitlySharedDataPointer<QGeoRouteSegmentPrivate> d_ptr; }; QT_END_NAMESPACE #endif
955
505
from PyQt4.Qt import QPushButton, SIGNAL, QTextEdit, QScrollArea, QTabWidget,\ QLineEdit from qtdefines import QRichLabel, makeHorizFrame, GETFONT, relaxedSizeNChar, \ makeVertFrame from armoryengine.ArmoryUtils import addrStr_to_hash160, LOGINFO,\ BadAddressError, binary_to_hex, coin2str, isLikelyDataType, DATATYPE,\ hex_to_binary, ph, BIGENDIAN from armoryengine.BDM import TheBDM from armoryengine.Transaction import PyTx from qtdialogs import DlgAddressInfo, DlgDispTxInfo class PluginObject(object): tabName = 'Armory Search' maxVersion = '0.93.99' ############################################################################# def __init__(self, main): def searchItem(): searchString = str(self.searchEntry.text()) if len(searchString) > 0: likelyDataType = isLikelyDataType(searchString) for wltID, wlt in self.main.walletMap.iteritems(): if wlt.hasAddr(searchString): searchHash = searchString if likelyDataType == DATATYPE.Hex \ else addrStr_to_hash160(searchString)[1] dialog = DlgAddressInfo(wlt, searchHash, main=self.main) dialog.exec_() break if likelyDataType == DATATYPE.Hex: walletLedger = wlt.cppWallet.getTxLedger() txHashToFind = hex_to_binary(searchString, endOut=BIGENDIAN) txFound = False for entry in walletLedger: if entry.getTxHash() == txHashToFind: cppTx = TheBDM.getTxByHash(txHashToFind) serializedCppTx = cppTx.serialize() pytx = PyTx().unserialize(serializedCppTx) DlgDispTxInfo(pytx, wlt, self.main, self.main).exec_() txFound = True break if txFound: break self.main = main lblHeader = QRichLabel(tr("""<b>Search Armory: </b>"""), doWrap=False) self.searchButton = QPushButton("Search") self.searchEntry = QLineEdit() self.main.connect(self.searchButton, SIGNAL('clicked()'), searchItem) topRow = makeHorizFrame([lblHeader, self.searchEntry, self.searchButton, 'stretch']) self.searchPanel = makeVertFrame([topRow, 'stretch' ]) # Now set the scrollarea widget to the layout self.tabToDisplay = QScrollArea() self.tabToDisplay.setWidgetResizable(True) self.tabToDisplay.setWidget(self.searchPanel) ############################################################################# def getTabToDisplay(self): return self.tabToDisplay
1,248
1,023
import argparse import matplotlib.pyplot as plt import numpy as np import seaborn from matplotlib.ticker import FuncFormatter from stable_baselines.results_plotter import load_results, ts2xy def millions(x, pos): """ Formatter for matplotlib The two args are the value and tick position :param x: (float) :param pos: (int) tick position (not used here :return: (str) """ return '{:.1f}M'.format(x * 1e-6) def moving_average(values, window): """ Smooth values by doing a moving average :param values: (numpy array) :param window: (int) :return: (numpy array) """ weights = np.repeat(1.0, window) / window return np.convolve(values, weights, 'valid') def smooth(xy, window=50): x, y = xy if y.shape[0] < window: return x, y original_y = y.copy() y = moving_average(y, window) if len(y) == 0: return x, original_y # Truncate x x = x[len(x) - len(y):] return x, y # Init seaborn seaborn.set() parser = argparse.ArgumentParser() parser.add_argument('-i', '--log-dirs', help='Log folder(s)', nargs='+', required=True, type=str) parser.add_argument('--title', help='Plot title', default='Learning Curve', type=str) parser.add_argument('--smooth', action='store_true', default=False, help='Smooth Learning Curve') args = parser.parse_args() results = [] algos = [] for folder in args.log_dirs: timesteps = load_results(folder) results.append(timesteps) if folder.endswith('/'): folder = folder[:-1] algos.append(folder.split('/')[-1]) min_timesteps = np.inf # 'walltime_hrs', 'episodes' for plot_type in ['timesteps']: xy_list = [] for result in results: x, y = ts2xy(result, plot_type) if args.smooth: x, y = smooth((x, y), window=50) n_timesteps = x[-1] if n_timesteps < min_timesteps: min_timesteps = n_timesteps xy_list.append((x, y)) fig = plt.figure(args.title) for i, (x, y) in enumerate(xy_list): print(algos[i]) plt.plot(x[:min_timesteps], y[:min_timesteps], label=algos[i], linewidth=2) plt.title(args.title) plt.legend() if plot_type == 'timesteps': if min_timesteps > 1e6: formatter = FuncFormatter(millions) plt.xlabel('Number of Timesteps') fig.axes[0].xaxis.set_major_formatter(formatter) plt.show()
1,076
1,396
<reponame>YR1044/NCalendar<filename>app/src/main/java/com/necer/ncalendar/activity/TestMiui10Activity.java package com.necer.ncalendar.activity; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import androidx.annotation.Nullable; import android.util.Log; import android.widget.TextView; import com.necer.calendar.BaseCalendar; import com.necer.calendar.Miui10Calendar; import com.necer.entity.CalendarDate; import com.necer.entity.Lunar; import com.necer.enumeration.DateChangeBehavior; import com.necer.enumeration.MultipleCountModel; import com.necer.listener.OnCalendarChangedListener; import com.necer.listener.OnCalendarMultipleChangedListener; import com.necer.ncalendar.R; import com.necer.painter.CalendarBackground; import com.necer.painter.InnerPainter; import com.necer.utils.CalendarUtil; import org.joda.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by necer on 2018/11/12. */ public class TestMiui10Activity extends BaseActivity { private Miui10Calendar miui10Calendar; private TextView tv_result; private TextView tv_data; private TextView tv_desc; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_miui10); tv_result = findViewById(R.id.tv_result); tv_data = findViewById(R.id.tv_data); tv_desc = findViewById(R.id.tv_desc); List<String> pointList = Arrays.asList("2018-10-01", "2018-11-19", "2018-11-20", "2018-05-23", "2019-01-01", "2018-12-23"); miui10Calendar = findViewById(R.id.miui10Calendar); miui10Calendar.setCheckMode(checkModel); InnerPainter innerPainter = (InnerPainter) miui10Calendar.getCalendarPainter(); innerPainter.setPointList(pointList); // Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher); // miui10Calendar.setMonthCalendarBackground(new CalendarBackground() { // @Override // public Drawable getBackgroundDrawable(LocalDate localDate, int currentDistance, int totalDistance) { // return drawable; // } // }); Map<String, String> strMap = new HashMap<>(); strMap.put("2019-01-25", "测试"); strMap.put("2019-01-23", "测试1"); strMap.put("2019-01-24", "测试2"); innerPainter.setReplaceLunarStrMap(strMap); Map<String, Integer> colorMap = new HashMap<>(); colorMap.put("2019-08-25", Color.RED); colorMap.put("2019-08-5", Color.parseColor("#000000")); innerPainter.setReplaceLunarColorMap(colorMap); List<String> holidayList = new ArrayList<>(); holidayList.add("2019-7-20"); holidayList.add("2019-7-21"); holidayList.add("2019-7-22"); List<String> workdayList = new ArrayList<>(); workdayList.add("2019-7-23"); workdayList.add("2019-7-24"); workdayList.add("2019-7-25"); innerPainter.setLegalHolidayList(holidayList, workdayList); miui10Calendar.setOnCalendarChangedListener(new OnCalendarChangedListener() { @Override public void onCalendarChange(BaseCalendar baseCalendar, int year, int month, LocalDate localDate, DateChangeBehavior dateChangeBehavior) { tv_result.setText(year + "年" + month + "月" + " 当前页面选中 " + localDate); Log.d(TAG, " 当前页面选中 " + localDate); Log.d(TAG, " dateChangeBehavior " + dateChangeBehavior); Log.e(TAG, "baseCalendar::" + baseCalendar); if (localDate != null) { CalendarDate calendarDate = CalendarUtil.getCalendarDate(localDate); Lunar lunar = calendarDate.lunar; tv_data.setText(localDate.toString("yyyy年MM月dd日")); tv_desc.setText(lunar.chineseEra + lunar.animals + "年" + lunar.lunarMonthStr + lunar.lunarDayStr); } else { tv_data.setText(""); tv_desc.setText(""); } } }); miui10Calendar.setOnCalendarMultipleChangedListener(new OnCalendarMultipleChangedListener() { @Override public void onCalendarChange(BaseCalendar baseCalendar, int year, int month, List<LocalDate> currPagerCheckedList, List<LocalDate> totalCheckedList, DateChangeBehavior dateChangeBehavior) { tv_result.setText(year + "年" + month + "月" + " 当前页面选中 " + currPagerCheckedList.size() + "个 总共选中" + totalCheckedList.size() + "个"); Log.d(TAG, year + "年" + month + "月"); Log.d(TAG, "当前页面选中::" + currPagerCheckedList); Log.d(TAG, "全部选中::" + totalCheckedList); } }); } }
2,228
14,668
<filename>components/sync/base/invalidation_interface.cc // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/base/invalidation_interface.h" namespace syncer { bool InvalidationInterface::LessThanByVersion(const InvalidationInterface& a, const InvalidationInterface& b) { if (a.IsUnknownVersion() && !b.IsUnknownVersion()) return true; if (!a.IsUnknownVersion() && b.IsUnknownVersion()) return false; if (a.IsUnknownVersion() && b.IsUnknownVersion()) return false; return a.GetVersion() < b.GetVersion(); } InvalidationInterface::InvalidationInterface() = default; InvalidationInterface::~InvalidationInterface() = default; } // namespace syncer
284
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.spi.project; import java.net.URI; import org.netbeans.api.project.Project; import org.openide.filesystems.FileObject; /** * Knowledge of which project some files belong to. * <p>An implementation must attempt to return a result quickly and avoid * blocking on foreign locks. In particular, it should not call {@code OpenProjects}. * @see org.netbeans.api.project.FileOwnerQuery * @author <NAME> */ public interface FileOwnerQueryImplementation { /** * Decide which project, if any, "owns" a given file. * @param file an absolute URI to some file (typically on disk; need not currently exist) * @return a project which owns it, or null for no response */ Project getOwner(URI file); /** * Decide which project, if any, "owns" a given file. * @param file FileObject of an existing file * @return a project which owns it, or null for no response */ Project getOwner(FileObject file); }
500
2,151
/* * * Copyright 2016 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/channel/channel_stack_builder.h" #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/string_util.h> typedef struct filter_node { struct filter_node* next; struct filter_node* prev; const grpc_channel_filter* filter; grpc_post_filter_create_init_func init; void* init_arg; } filter_node; struct grpc_channel_stack_builder { // sentinel nodes for filters that have been added filter_node begin; filter_node end; // various set/get-able parameters grpc_channel_args* args; grpc_transport* transport; grpc_resource_user* resource_user; char* target; const char* name; }; struct grpc_channel_stack_builder_iterator { grpc_channel_stack_builder* builder; filter_node* node; }; grpc_channel_stack_builder* grpc_channel_stack_builder_create(void) { grpc_channel_stack_builder* b = static_cast<grpc_channel_stack_builder*>(gpr_zalloc(sizeof(*b))); b->begin.filter = nullptr; b->end.filter = nullptr; b->begin.next = &b->end; b->begin.prev = &b->end; b->end.next = &b->begin; b->end.prev = &b->begin; return b; } void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b, const char* target) { gpr_free(b->target); b->target = gpr_strdup(target); } const char* grpc_channel_stack_builder_get_target( grpc_channel_stack_builder* b) { return b->target; } static grpc_channel_stack_builder_iterator* create_iterator_at_filter_node( grpc_channel_stack_builder* builder, filter_node* node) { grpc_channel_stack_builder_iterator* it = static_cast<grpc_channel_stack_builder_iterator*>( gpr_malloc(sizeof(*it))); it->builder = builder; it->node = node; return it; } void grpc_channel_stack_builder_iterator_destroy( grpc_channel_stack_builder_iterator* it) { gpr_free(it); } grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_create_iterator_at_first( grpc_channel_stack_builder* builder) { return create_iterator_at_filter_node(builder, &builder->begin); } grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_create_iterator_at_last( grpc_channel_stack_builder* builder) { return create_iterator_at_filter_node(builder, &builder->end); } bool grpc_channel_stack_builder_iterator_is_end( grpc_channel_stack_builder_iterator* iterator) { return iterator->node == &iterator->builder->end; } const char* grpc_channel_stack_builder_iterator_filter_name( grpc_channel_stack_builder_iterator* iterator) { if (iterator->node->filter == nullptr) return nullptr; return iterator->node->filter->name; } bool grpc_channel_stack_builder_move_next( grpc_channel_stack_builder_iterator* iterator) { if (iterator->node == &iterator->builder->end) return false; iterator->node = iterator->node->next; return true; } bool grpc_channel_stack_builder_move_prev( grpc_channel_stack_builder_iterator* iterator) { if (iterator->node == &iterator->builder->begin) return false; iterator->node = iterator->node->prev; return true; } grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find( grpc_channel_stack_builder* builder, const char* filter_name) { GPR_ASSERT(filter_name != nullptr); grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_create_iterator_at_first(builder); while (grpc_channel_stack_builder_move_next(it)) { if (grpc_channel_stack_builder_iterator_is_end(it)) break; const char* filter_name_at_it = grpc_channel_stack_builder_iterator_filter_name(it); if (strcmp(filter_name, filter_name_at_it) == 0) break; } return it; } bool grpc_channel_stack_builder_move_prev( grpc_channel_stack_builder_iterator* iterator); void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder, const char* name) { GPR_ASSERT(builder->name == nullptr); builder->name = name; } void grpc_channel_stack_builder_set_channel_arguments( grpc_channel_stack_builder* builder, const grpc_channel_args* args) { if (builder->args != nullptr) { grpc_channel_args_destroy(builder->args); } builder->args = grpc_channel_args_copy(args); } const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments( grpc_channel_stack_builder* builder) { return builder->args; } void grpc_channel_stack_builder_set_transport( grpc_channel_stack_builder* builder, grpc_transport* transport) { GPR_ASSERT(builder->transport == nullptr); builder->transport = transport; } grpc_transport* grpc_channel_stack_builder_get_transport( grpc_channel_stack_builder* builder) { return builder->transport; } void grpc_channel_stack_builder_set_resource_user( grpc_channel_stack_builder* builder, grpc_resource_user* resource_user) { GPR_ASSERT(builder->resource_user == nullptr); builder->resource_user = resource_user; } grpc_resource_user* grpc_channel_stack_builder_get_resource_user( grpc_channel_stack_builder* builder) { return builder->resource_user; } bool grpc_channel_stack_builder_append_filter( grpc_channel_stack_builder* builder, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, void* user_data) { grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_create_iterator_at_last(builder); bool ok = grpc_channel_stack_builder_add_filter_before( it, filter, post_init_func, user_data); grpc_channel_stack_builder_iterator_destroy(it); return ok; } bool grpc_channel_stack_builder_remove_filter( grpc_channel_stack_builder* builder, const char* filter_name) { grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_iterator_find(builder, filter_name); if (grpc_channel_stack_builder_iterator_is_end(it)) { grpc_channel_stack_builder_iterator_destroy(it); return false; } it->node->prev->next = it->node->next; it->node->next->prev = it->node->prev; gpr_free(it->node); grpc_channel_stack_builder_iterator_destroy(it); return true; } bool grpc_channel_stack_builder_prepend_filter( grpc_channel_stack_builder* builder, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, void* user_data) { grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_create_iterator_at_first(builder); bool ok = grpc_channel_stack_builder_add_filter_after( it, filter, post_init_func, user_data); grpc_channel_stack_builder_iterator_destroy(it); return ok; } static void add_after(filter_node* before, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, void* user_data) { filter_node* new_node = static_cast<filter_node*>(gpr_malloc(sizeof(*new_node))); new_node->next = before->next; new_node->prev = before; new_node->next->prev = new_node->prev->next = new_node; new_node->filter = filter; new_node->init = post_init_func; new_node->init_arg = user_data; } bool grpc_channel_stack_builder_add_filter_before( grpc_channel_stack_builder_iterator* iterator, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, void* user_data) { if (iterator->node == &iterator->builder->begin) return false; add_after(iterator->node->prev, filter, post_init_func, user_data); return true; } bool grpc_channel_stack_builder_add_filter_after( grpc_channel_stack_builder_iterator* iterator, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, void* user_data) { if (iterator->node == &iterator->builder->end) return false; add_after(iterator->node, filter, post_init_func, user_data); return true; } void grpc_channel_stack_builder_destroy(grpc_channel_stack_builder* builder) { filter_node* p = builder->begin.next; while (p != &builder->end) { filter_node* next = p->next; gpr_free(p); p = next; } if (builder->args != nullptr) { grpc_channel_args_destroy(builder->args); } gpr_free(builder->target); gpr_free(builder); } grpc_error* grpc_channel_stack_builder_finish( grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs, grpc_iomgr_cb_func destroy, void* destroy_arg, void** result) { // count the number of filters size_t num_filters = 0; for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) { num_filters++; } // create an array of filters const grpc_channel_filter** filters = static_cast<const grpc_channel_filter**>( gpr_malloc(sizeof(*filters) * num_filters)); size_t i = 0; for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) { filters[i++] = p->filter; } // calculate the size of the channel stack size_t channel_stack_size = grpc_channel_stack_size(filters, num_filters); // allocate memory, with prefix_bytes followed by channel_stack_size *result = gpr_zalloc(prefix_bytes + channel_stack_size); // fetch a pointer to the channel stack grpc_channel_stack* channel_stack = reinterpret_cast<grpc_channel_stack*>( static_cast<char*>(*result) + prefix_bytes); // and initialize it grpc_error* error = grpc_channel_stack_init( initial_refs, destroy, destroy_arg == nullptr ? *result : destroy_arg, filters, num_filters, builder->args, builder->transport, builder->name, channel_stack); if (error != GRPC_ERROR_NONE) { grpc_channel_stack_destroy(channel_stack); gpr_free(*result); *result = nullptr; } else { // run post-initialization functions i = 0; for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) { if (p->init != nullptr) { p->init(channel_stack, grpc_channel_stack_element(channel_stack, i), p->init_arg); } i++; } } grpc_channel_stack_builder_destroy(builder); gpr_free(const_cast<grpc_channel_filter**>(filters)); return error; }
3,944
778
<gh_stars>100-1000 import KratosMultiphysics as Kratos from KratosMultiphysics import KratosUnittest from KratosMultiphysics.testing.utilities import ReadModelPart from KratosMultiphysics.StatisticsApplication.test_utilities import InitializeModelPartVariables class StatisticsTestCase(KratosUnittest.TestCase): """This test case is designed for performing multiple test with the same modelparts this way the partitioning has to be done only once The values in the ModelParts are re-initialized after every test """ @classmethod def setUpModelParts(cls, mdpa_file_name): cls.current_model = Kratos.Model() cls.model_part = cls.current_model.CreateModelPart("test_model_part") cls.model_part.SetBufferSize(1) cls.model_part.ProcessInfo.SetValue(Kratos.DOMAIN_SIZE, 2) cls.AddVariables() with KratosUnittest.WorkFolderScope(".", __file__): ReadModelPart(mdpa_file_name, cls.model_part) @classmethod def AddVariables(cls): pass def setUp(self): InitializeModelPartVariables(self.model_part) def GetModelPart(self): return self.model_part def GetModel(self): return self.current_model
460
577
// // CWActivityMonitor.h // PlainReader // // Created by guojiubo on 10/22/14. // Copyright (c) 2014 guojiubo. All rights reserved. // #import <Foundation/Foundation.h> @interface PRActivityMonitor : NSObject + (instancetype)sharedMonitor; - (void)start; - (void)stop; @end
109
764
<filename>erc20/0x73468010eFda36A42662F000fce2c2A4Ef175097.json { "symbol": "LFC", "address": "0x73468010eFda36A42662F000fce2c2A4Ef175097", "overview":{ "en": "LiFe Chain is a decentralized digital medical network system developed based on blockchain technology. It is committed to solving the problems encountered by medical industry practitioners and institutions, and provides individuals, institutions with safe, convenient, and stable underlying network technology.", "zh": "LiFe Chain是基于区块链技术开发的去中心化数字医疗网络系统,致力于解决目前医疗行业从业者、机构所遇到的问题,为个人及机构提供安全、便捷、稳定的底层网络技术。" }, "email": "<EMAIL>", "website": "http://www.lfc.world/", "whitepaper": "http://www.lfc.world/white-paper/cn.pdf", "state": "NORMAL", "published_on": "2019-08-05", "links": { "telegram": "https://t.me/lifechainc", "twitter": "https://twitter.com/lifechain1" } }
485
354
from dataclasses import dataclass import functools from numbers import Number import os from pathlib import Path import shutil import tempfile from typing import Any, Optional, List, Callable, Dict, Type from werkzeug.datastructures import FileStorage from .predictor import Predictor _VALID_INPUT_TYPES = frozenset([str, int, float, bool, Path]) UNSPECIFIED = object() @dataclass class InputSpec: name: str type: Type default: Any = UNSPECIFIED min: Optional[Number] = None max: Optional[Number] = None options: Optional[List[Any]] = None help: Optional[str] = None class InputValidationError(Exception): pass def input(name, type, default=UNSPECIFIED, min=None, max=None, options=None, help=None): """ A decorator that defines an input for a predict() method. """ type_name = get_type_name(type) if type not in _VALID_INPUT_TYPES: type_list = ", ".join([type_name(t) for t in _VALID_INPUT_TYPES]) raise ValueError( f"{type_name} is not a valid input type. Valid types are: {type_list}" ) if (min is not None or max is not None) and not _is_numeric_type(type): raise ValueError(f"Non-numeric type {type_name} cannot have min and max values") if options is not None and type == Path: raise ValueError(f"File type cannot have options") if options is not None and len(options) < 2: raise ValueError(f"Options list must have at least two items") def wrapper(f): if not hasattr(f, "_inputs"): f._inputs = [] if name in (i.name for i in f._inputs): raise ValueError(f"{name} is already defined as an argument") if type == Path and default is not UNSPECIFIED and default is not None: raise TypeError("Cannot use default with Path type") # Insert at start of list because decorators are run bottom up f._inputs.insert( 0, InputSpec( name=name, type=type, default=default, min=min, max=max, options=options, help=help, ), ) @functools.wraps(f) def wraps(self, **kwargs): if not isinstance(self, Predictor): raise TypeError("{self} is not an instance of cog.Predictor") return f(self, **kwargs) return wraps return wrapper def get_type_name(typ: Type) -> str: if typ == str: return "str" if typ == int: return "int" if typ == float: return "float" if typ == bool: return "bool" if typ == Path: return "Path" return str(typ) def _is_numeric_type(typ: Type) -> bool: return typ in (int, float) def validate_and_convert_inputs( predictor: Predictor, raw_inputs: Dict[str, Any], cleanup_functions: List[Callable] ) -> Dict[str, Any]: input_specs = predictor.predict._inputs inputs = {} for input_spec in input_specs: if input_spec.name in raw_inputs: val = raw_inputs[input_spec.name] if input_spec.type == Path: if not isinstance(val, FileStorage): raise InputValidationError( f"Could not convert file input {input_spec.name} to {get_type_name(input_spec.type)}", ) if val.filename is None: raise InputValidationError( f"No filename is provided for file input {input_spec.name}" ) temp_dir = tempfile.mkdtemp() cleanup_functions.append(lambda: shutil.rmtree(temp_dir)) temp_path = os.path.join(temp_dir, val.filename) with open(temp_path, "wb") as f: f.write(val.stream.read()) converted = Path(temp_path) elif input_spec.type == int: try: converted = int(val) except ValueError: raise InputValidationError( f"Could not convert {input_spec.name}={val} to int" ) elif input_spec.type == float: try: converted = float(val) except ValueError: raise InputValidationError( f"Could not convert {input_spec.name}={val} to float" ) elif input_spec.type == bool: if val.lower() not in ["true", "false"]: raise InputValidationError( f"{input_spec.name}={val} is not a boolean" ) converted = val.lower() == "true" elif input_spec.type == str: if isinstance(val, FileStorage): raise InputValidationError( f"Could not convert file input {input_spec.name} to str" ) converted = val else: raise TypeError( f"Internal error: Input type {input_spec} is not a valid input type" ) if _is_numeric_type(input_spec.type): if input_spec.max is not None and converted > input_spec.max: raise InputValidationError( f"Value {converted} is greater than the max value {input_spec.max}" ) if input_spec.min is not None and converted < input_spec.min: raise InputValidationError( f"Value {converted} is less than the min value {input_spec.min}" ) if input_spec.options is not None: if converted not in input_spec.options: valid_str = ", ".join([str(o) for o in input_spec.options]) raise InputValidationError( f"Value {converted} is not an option. Valid options are: {valid_str}" ) else: if input_spec.default is not UNSPECIFIED: converted = input_spec.default else: raise InputValidationError( f"Missing expected argument: {input_spec.name}" ) inputs[input_spec.name] = converted expected_names = set(s.name for s in input_specs) raw_keys = set(raw_inputs.keys()) extraneous_keys = raw_keys - expected_names if extraneous_keys: raise InputValidationError( f"Extraneous input keys: {', '.join(extraneous_keys)}" ) return inputs
3,270
12,824
<reponame>tanishiking/dotty package p; class J { J() {} }
27
11,628
<filename>proxylib/proxylib/types.h /* * Copyright 2018 Authors of Cilium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PROXYLIB_TYPES_H #define PROXYLIB_TYPES_H #include <stdint.h> typedef enum { FILTEROP_MORE, // Need more data FILTEROP_PASS, // Pass N bytes FILTEROP_DROP, // Drop N bytes FILTEROP_INJECT, // Inject N>0 bytes FILTEROP_ERROR, // Protocol parsing error } FilterOpType; typedef enum { FILTEROP_ERROR_INVALID_OP_LENGTH = 1, // Parser returned invalid operation length FILTEROP_ERROR_INVALID_FRAME_TYPE, FILTEROP_ERROR_INVALID_FRAME_LENGTH, } FilterOpError; typedef struct { uint64_t op; // FilterOpType int64_t n_bytes; // >0 } FilterOp; typedef enum { FILTER_OK, // Operation was successful FILTER_POLICY_DROP, // Connection needs to be dropped due to (L3/L4) policy FILTER_PARSER_ERROR, // Connection needs to be dropped due to parser error FILTER_UNKNOWN_PARSER, // Connection needs to be dropped due to unknown parser FILTER_UNKNOWN_CONNECTION, // Connection needs to be dropped due to it being unknown FILTER_INVALID_ADDRESS, // Destination address in invalid format FILTER_INVALID_INSTANCE, // Destination address in invalid format FILTER_UNKNOWN_ERROR, // Error type could not be cast to an error code } FilterResult; #endif
633
1,443
{ "copyright": "<NAME>", "url": "http://www.mattclements.co.uk/", "email": "<EMAIL>" }
43
1,681
<gh_stars>1000+ package com.easytoolsoft.easyreport.mybatis.data; import java.util.List; import org.apache.ibatis.annotations.Param; /** * @param <T> * @author <NAME> * @date 2017-03-25 */ public interface InsertRepository<T> { /** * 插入一条数据,忽略record中的ID * * @param record * @return 影响的记录数 */ int insert(@Param("record") T record); /** * @param records * @return 影响的记录数 */ int batchInsert(@Param("records") List<T> records); /** * 使用mysql on duplicate key 语句插入与修改 * * @param records pojo记录集 * @return 影响的记录数 */ int batchInsertOnDuplicateKey(@Param("records") List<T> records); }
358
719
package org.springframework.security.config.annotation.web.configuration; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented public @interface EnableWebSecurity { boolean debug() default false; }
126
854
<gh_stars>100-1000 __________________________________________________________________________________________________ 4ms class Solution { public: string fractionToDecimal(int numerator, int denominator) { if (numerator == 0) return "0"; string result = ""; if (numerator < 0 ^ denominator < 0) result += "-"; long n = labs(numerator); long d = labs(denominator); result += to_string(n / d); long r = n % d; if (r == 0) return result; result += "."; unordered_map<int, int> last_position; while (r != 0) { if (r != 0 && last_position.find(r) != last_position.end()) { result.insert(last_position[r], "("); result += ")"; return result; } else { last_position[r] = result.size(); } r *= 10; result += to_string(r / d); r = r % d; } return result; } }; __________________________________________________________________________________________________ 8540 kb class Solution { public: string fractionToDecimal(int numerator, int denominator) { if (!numerator || !denominator) return string("0"); bool minus = (numerator < 0) ^ (denominator < 0); long long q = ((long long)numerator) * (minus ? -1 : 1) / denominator; long long r = ((long long)numerator) * (minus ? -1 : 1) % denominator; vector<long long> vQs; vector<int> vRs; vQs.push_back(q); if (r) vRs.push_back(r); bool bRecurr = false; vector<int>::iterator it; while (r) { r = r * 10; q = r / denominator; r = r % denominator; vQs.push_back(q); if (!r) break; else if ((it = find(vRs.begin(), vRs.end(), r)) != vRs.end()) { bRecurr = true; break; } vRs.push_back(r); } // string ret; ret.append(itoa(vQs.front())); if (!vRs.empty()) { ret.append(1, '.'); for (int i = 1; i < vQs.size(); i++) { if (bRecurr && vRs[i - 1] == *it) ret.append(1, '('); ret.append(itoa(vQs[i])); } if (bRecurr) ret.append(1, ')'); } if (minus) ret = string("-") + ret.c_str(); return ret; } char * itoa(long long num) { static char buffer[32]; memset(buffer, NULL, sizeof(buffer)); // int i = 0; if (num < 0) { buffer[0] = '-'; num = num * -1; i++; } do { buffer[i++] = (num % 10) + '0'; num = num / 10; } while (num); // reverse int begin = 0, end = i - 1; while (begin < end) { char tmp = buffer[begin]; buffer[begin] = buffer[end]; buffer[end] = tmp; begin++; end--; } return buffer; } }; __________________________________________________________________________________________________
1,129
7,482
<gh_stars>1000+ /*************************************************************************//** * @file dmdif_ssd2119_ebi.c * @brief Dot matrix display interface using EBI * @author Energy Micro AS ****************************************************************************** * @section License * <b>(C) Copyright 2012 Energy Micro AS, http://www.energymicro.com</b> ****************************************************************************** * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * 4. The source and compiled code may only be used on Energy Micro "EFM32" * microcontrollers and "EFR4" radios. * * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Energy Micro AS has no * obligation to support this Software. Energy Micro AS is providing the * Software "AS IS", with no express or implied warranties of any kind, * including, but not limited to, any implied warranties of merchantability * or fitness for any particular purpose or warranties against infringement * of any proprietary rights of a third party. * * Energy Micro AS will not be liable for any consequential, incidental, or * special damages, or any other relief, or for any claim by any third party, * arising from your use of this Software. * *****************************************************************************/ #include <stdint.h> #include "dmd_ssd2119_registers.h" #include "dmd_ssd2119.h" #include "dmdif_ssd2119_ebi.h" #include "dvk.h" /* Local function prototypes */ static EMSTATUS setNextReg(uint8_t reg); static volatile uint16_t *command_register; static volatile uint16_t *data_register; /**************************************************************************//** * @brief * Initializes the data interface to the LCD controller SSD2119 * * * @param cmdRegAddr * The address in memory where data to the command register in the display * controller are written * @param dataRegAddr * The address in memory where data to the data register in the display * controller are written * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ EMSTATUS DMDIF_init(uint32_t cmdRegAddr, uint32_t dataRegAddr) { command_register = (volatile uint16_t*) cmdRegAddr; data_register = (volatile uint16_t*) dataRegAddr; return DMD_OK; } /**************************************************************************//** * @brief * Writes a value to a control register in the LCD controller * * @param reg * The register that will be written to * @param data * The value to write to the register * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ EMSTATUS DMDIF_writeReg(uint8_t reg, uint16_t data) { setNextReg(reg); *data_register = data; return DMD_OK; } /**************************************************************************//** * @brief * Reads the device code of the LCD controller * DOESN'T WORK * * @return * The device code of the LCD controller ******************************************************************************/ uint16_t DMDIF_readDeviceCode(void) { uint16_t deviceCode; /* Reading from the oscillation control register gives the device code */ setNextReg(DMD_SSD2119_DEVICE_CODE_READ); deviceCode = *data_register; return deviceCode; } /**************************************************************************//** * @brief * Sends the data access command to the LCD controller to prepare for one or more * writes or reads using the DMDIF_writeData() and DMDIF_readData() * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ EMSTATUS DMDIF_prepareDataAccess(void) { setNextReg(DMD_SSD2119_ACCESS_DATA); return DMD_OK; } /**************************************************************************//** * @brief * Writes one pixel to the LCD controller. DMDIF_prepareDataAccess() needs to be * called before writing data using this function. * * @param data * The color value of the pixel to be written in 18bpp format * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ EMSTATUS DMDIF_writeData(uint32_t data) { *data_register = (data & 0x0000FFFF); return DMD_OK; } /**************************************************************************//** * @brief * Writes one pixel to the LCD controller. DMDIF_prepareDataAccess() needs to be * called before writing data using this function. * * @param data * The color value of the pixel to be written in 18bpp format * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ EMSTATUS DMDIF_writeDataRepeated( uint32_t data, int len ){ uint16_t pixelData; int i; /* Write bits [8:0] of the pixel data to bits [8:0] on the output lines */ pixelData = data & 0x0000FFFF; for (i=0; i<len; i++) { *data_register = pixelData; } return DMD_OK; } /**************************************************************************//** * @brief * Writes one pixel to the LCD controller. DMDIF_prepareDataAccess() needs to be * called before writing data using this function. * * @param a * The upper 9 bits of color value of the pixel to be written in 18bpp format * * @param b * The low 9 bits of color value of the pixel to be written in 18bpp format * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ EMSTATUS DMDIF_writeDataConverted( uint16_t a, uint16_t b ){ uint16_t pixel; pixel = b >> 1; pixel |= (a << 8) & 0xFF00; *data_register = pixel; return DMD_OK; } /**************************************************************************//** * @brief * Reads a byte of data from the memory of the LCD controller. * DMDIF_prepareDataAccess() needs to be called before using this function. * DOESN'T WORK * * @return * 18bpp value of pixel ******************************************************************************/ uint32_t DMDIF_readData(void) { uint32_t data; data = *data_register; return data; } /**************************************************************************//** * \brief * Sets the register in the LCD controller to write commands to * * \param reg * The next register in the LCD controller to write to * * @return * DMD_OK on success, otherwise error code ******************************************************************************/ static EMSTATUS setNextReg(uint8_t reg) { uint16_t data; data = reg & 0xff; /* Write the register address to bits [8:1] in the index register */ *command_register = data; return DMD_OK; }
1,992
587
// // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) Contributors to the OpenEXR Project. // #ifndef INCLUDED_IEXNAMESPACE_H #define INCLUDED_IEXNAMESPACE_H // // The purpose of this file is to make it possible to specify an // IEX_INTERNAL_NAMESPACE as a preprocessor definition and have all of the // Iex symbols defined within that namespace rather than the standard // Iex namespace. Those symbols are made available to client code through // the IEX_NAMESPACE in addition to the IEX_INTERNAL_NAMESPACE. // // To ensure source code compatibility, the IEX_NAMESPACE defaults to Iex // and then "using namespace IEX_INTERNAL_NAMESPACE;" brings all of the // declarations from the IEX_INTERNAL_NAMESPACE into the IEX_NAMESPACE. This // means that client code can continue to use syntax like Iex::BaseExc, but // at link time it will resolve to a mangled symbol based on the // IEX_INTERNAL_NAMESPACE. // // As an example, if one needed to build against a newer version of Iex and // have it run alongside an older version in the same application, it is now // possible to use an internal namespace to prevent collisions between the // older versions of Iex symbols and the newer ones. To do this, the // following could be defined at build time: // // IEX_INTERNAL_NAMESPACE = Iex_v2 // // This means that declarations inside Iex headers look like this (after the // preprocessor has done its work): // // namespace Iex_v2 { // ... // class declarations // ... // } // // namespace Iex { // using namespace Iex_v2; // } // // // Open Source version of this file pulls in the IexConfig.h file // for the configure time options. // #include "IexConfig.h" #ifndef IEX_NAMESPACE # define IEX_NAMESPACE Iex #endif #ifndef IEX_INTERNAL_NAMESPACE # define IEX_INTERNAL_NAMESPACE IEX_NAMESPACE #endif // // We need to be sure that we import the internal namespace into the public one. // To do this, we use the small bit of code below which initially defines // IEX_INTERNAL_NAMESPACE (so it can be referenced) and then defines // IEX_NAMESPACE and pulls the internal symbols into the public namespace. // namespace IEX_INTERNAL_NAMESPACE {} namespace IEX_NAMESPACE { using namespace IEX_INTERNAL_NAMESPACE; } // // There are identical pairs of HEADER/SOURCE ENTER/EXIT macros so that // future extension to the namespace mechanism is possible without changing // project source code. // #define IEX_INTERNAL_NAMESPACE_HEADER_ENTER \ namespace IEX_INTERNAL_NAMESPACE \ { #define IEX_INTERNAL_NAMESPACE_HEADER_EXIT } #define IEX_INTERNAL_NAMESPACE_SOURCE_ENTER \ namespace IEX_INTERNAL_NAMESPACE \ { #define IEX_INTERNAL_NAMESPACE_SOURCE_EXIT } #endif // INCLUDED_IEXNAMESPACE_H
1,059
3,246
package com.polidea.rxandroidble2.internal.scan; import androidx.annotation.RestrictTo; import com.polidea.rxandroidble2.internal.operations.Operation; import io.reactivex.ObservableTransformer; @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class ScanSetup { /** * The scan operation for the device API level */ public final Operation<RxBleInternalScanResult> scanOperation; /** * Some functionality (behaviour) is not supported by hardware on older APIs. scanOperationBehaviourEmulatorTransformer is returned * by {@link ScanSetupBuilder} from combined emulation transformers provided by {@link ScanSettingsEmulator} */ public final ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> scanOperationBehaviourEmulatorTransformer; public ScanSetup( Operation<RxBleInternalScanResult> scanOperation, ObservableTransformer<RxBleInternalScanResult, RxBleInternalScanResult> scanOperationBehaviourEmulatorTransformer ) { this.scanOperation = scanOperation; this.scanOperationBehaviourEmulatorTransformer = scanOperationBehaviourEmulatorTransformer; } }
365
3,266
import numpy as np import matplotlib from matplotlib import pyplot as plt import keras from keras.models import Sequential from keras.optimizers import Adam, SGD from keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard from keras.constraints import maxnorm from keras.models import load_model from keras.layers import GlobalAveragePooling2D, Lambda, Conv2D, MaxPooling2D, Dropout, Dense, Flatten, Activation from keras.preprocessing.image import ImageDataGenerator from keras.datasets import cifar10 from networks.train_plot import PlotLearning # A pure CNN model from https://arxiv.org/pdf/1412.6806.pdf # Code taken from https://github.com/09rohanchopra/cifar10 class PureCnn: def __init__(self, epochs=350, batch_size=128, load_weights=True): self.name = 'pure_cnn' self.model_filename = 'networks/models/pure_cnn.h5' self.num_classes = 10 self.input_shape = 32, 32, 3 self.batch_size = batch_size self.epochs = epochs self.learn_rate = 1.0e-4 self.log_filepath = r'networks/models/pure_cnn/' if load_weights: try: self._model = load_model(self.model_filename) print('Successfully loaded', self.name) except (ImportError, ValueError, OSError): print('Failed to load', self.name) def count_params(self): return self._model.count_params() def color_preprocessing(self, x_train, x_test): x_train = x_train.astype('float32') x_test = x_test.astype('float32') mean = [125.307, 122.95, 113.865] std = [62.9932, 62.0887, 66.7048] for i in range(3): x_train[:,:,:,i] = (x_train[:,:,:,i] - mean[i]) / std[i] x_test[:,:,:,i] = (x_test[:,:,:,i] - mean[i]) / std[i] return x_train, x_test def pure_cnn_network(self, input_shape): model = Sequential() model.add(Conv2D(96, (3, 3), activation='relu', padding = 'same', input_shape=input_shape)) model.add(Dropout(0.2)) model.add(Conv2D(96, (3, 3), activation='relu', padding = 'same')) model.add(Conv2D(96, (3, 3), activation='relu', padding = 'same', strides = 2)) model.add(Dropout(0.5)) model.add(Conv2D(192, (3, 3), activation='relu', padding = 'same')) model.add(Conv2D(192, (3, 3), activation='relu', padding = 'same')) model.add(Conv2D(192, (3, 3), activation='relu', padding = 'same', strides = 2)) model.add(Dropout(0.5)) model.add(Conv2D(192, (3, 3), padding = 'same')) model.add(Activation('relu')) model.add(Conv2D(192, (1, 1),padding='valid')) model.add(Activation('relu')) model.add(Conv2D(10, (1, 1), padding='valid')) model.add(GlobalAveragePooling2D()) model.add(Activation('softmax')) return model def train(self): (x_train, y_train), (x_test, y_test) = cifar10.load_data() y_train = keras.utils.to_categorical(y_train, self.num_classes) y_test = keras.utils.to_categorical(y_test, self.num_classes) # color preprocessing x_train, x_test = self.color_preprocessing(x_train, x_test) model = self.pure_cnn_network(self.input_shape) model.summary() # Save the best model during each training checkpoint checkpoint = ModelCheckpoint(self.model_filename, monitor='val_loss', verbose=0, save_best_only= True, mode='auto') plot_callback = PlotLearning() tb_cb = TensorBoard(log_dir=self.log_filepath, histogram_freq=0) cbks = [checkpoint, plot_callback, tb_cb] # set data augmentation print('Using real-time data augmentation.') datagen = ImageDataGenerator(horizontal_flip=True, width_shift_range=0.125,height_shift_range=0.125,fill_mode='constant',cval=0.) datagen.fit(x_train) model.compile(loss='categorical_crossentropy', # Better loss function for neural networks optimizer=Adam(lr=self.learn_rate), # Adam optimizer with 1.0e-4 learning rate metrics = ['accuracy']) # Metrics to be evaluated by the model model.fit_generator(datagen.flow(x_train, y_train, batch_size = self.batch_size), epochs = self.epochs, validation_data= (x_test, y_test), callbacks=cbks, verbose=1) model.save(self.model_filename) self._model = model def color_process(self, imgs): if imgs.ndim < 4: imgs = np.array([imgs]) imgs = imgs.astype('float32') mean = [125.307, 122.95, 113.865] std = [62.9932, 62.0887, 66.7048] for img in imgs: for i in range(3): img[:,:,i] = (img[:,:,i] - mean[i]) / std[i] return imgs def predict(self, img): processed = self.color_process(img) return self._model.predict(processed, batch_size=self.batch_size) def predict_one(self, img): return self.predict(img)[0] def accuracy(self): (x_train, y_train), (x_test, y_test) = cifar10.load_data() y_train = keras.utils.to_categorical(y_train, self.num_classes) y_test = keras.utils.to_categorical(y_test, self.num_classes) # color preprocessing x_train, x_test = self.color_preprocessing(x_train, x_test) return self._model.evaluate(x_test, y_test, verbose=0)[1]
2,851
8,599
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.bpmn.converter.export; import javax.xml.stream.XMLStreamWriter; import org.activiti.bpmn.constants.BpmnXMLConstants; import org.activiti.bpmn.model.BpmnModel; import org.activiti.bpmn.model.DataStore; import org.apache.commons.lang3.StringUtils; public class DataStoreExport implements BpmnXMLConstants { public static void writeDataStores(BpmnModel model, XMLStreamWriter xtw) throws Exception { for (DataStore dataStore : model.getDataStores().values()) { xtw.writeStartElement(ELEMENT_DATA_STORE); xtw.writeAttribute(ATTRIBUTE_ID, dataStore.getId()); xtw.writeAttribute(ATTRIBUTE_NAME, dataStore.getName()); if (StringUtils.isNotEmpty(dataStore.getItemSubjectRef())) { xtw.writeAttribute(ATTRIBUTE_ITEM_SUBJECT_REF, dataStore.getItemSubjectRef()); } if (StringUtils.isNotEmpty(dataStore.getDataState())) { xtw.writeStartElement(ELEMENT_DATA_STATE); xtw.writeCharacters(dataStore.getDataState()); xtw.writeEndElement(); } xtw.writeEndElement(); } } }
591
3,372
<filename>aws-java-sdk-lookoutmetrics/src/main/java/com/amazonaws/services/lookoutmetrics/model/AlertSummary.java<gh_stars>1000+ /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lookoutmetrics.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Provides a summary of an alert's configuration. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lookoutmetrics-2017-07-25/AlertSummary" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AlertSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ARN of the alert. * </p> */ private String alertArn; /** * <p> * The ARN of the detector to which the alert is attached. * </p> */ private String anomalyDetectorArn; /** * <p> * The name of the alert. * </p> */ private String alertName; /** * <p> * The minimum severity for an anomaly to trigger the alert. * </p> */ private Integer alertSensitivityThreshold; /** * <p> * The type of the alert. * </p> */ private String alertType; /** * <p> * The status of the alert. * </p> */ private String alertStatus; /** * <p> * The time at which the alert was last modified. * </p> */ private java.util.Date lastModificationTime; /** * <p> * The time at which the alert was created. * </p> */ private java.util.Date creationTime; /** * <p> * The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. * </p> */ private java.util.Map<String, String> tags; /** * <p> * The ARN of the alert. * </p> * * @param alertArn * The ARN of the alert. */ public void setAlertArn(String alertArn) { this.alertArn = alertArn; } /** * <p> * The ARN of the alert. * </p> * * @return The ARN of the alert. */ public String getAlertArn() { return this.alertArn; } /** * <p> * The ARN of the alert. * </p> * * @param alertArn * The ARN of the alert. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withAlertArn(String alertArn) { setAlertArn(alertArn); return this; } /** * <p> * The ARN of the detector to which the alert is attached. * </p> * * @param anomalyDetectorArn * The ARN of the detector to which the alert is attached. */ public void setAnomalyDetectorArn(String anomalyDetectorArn) { this.anomalyDetectorArn = anomalyDetectorArn; } /** * <p> * The ARN of the detector to which the alert is attached. * </p> * * @return The ARN of the detector to which the alert is attached. */ public String getAnomalyDetectorArn() { return this.anomalyDetectorArn; } /** * <p> * The ARN of the detector to which the alert is attached. * </p> * * @param anomalyDetectorArn * The ARN of the detector to which the alert is attached. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withAnomalyDetectorArn(String anomalyDetectorArn) { setAnomalyDetectorArn(anomalyDetectorArn); return this; } /** * <p> * The name of the alert. * </p> * * @param alertName * The name of the alert. */ public void setAlertName(String alertName) { this.alertName = alertName; } /** * <p> * The name of the alert. * </p> * * @return The name of the alert. */ public String getAlertName() { return this.alertName; } /** * <p> * The name of the alert. * </p> * * @param alertName * The name of the alert. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withAlertName(String alertName) { setAlertName(alertName); return this; } /** * <p> * The minimum severity for an anomaly to trigger the alert. * </p> * * @param alertSensitivityThreshold * The minimum severity for an anomaly to trigger the alert. */ public void setAlertSensitivityThreshold(Integer alertSensitivityThreshold) { this.alertSensitivityThreshold = alertSensitivityThreshold; } /** * <p> * The minimum severity for an anomaly to trigger the alert. * </p> * * @return The minimum severity for an anomaly to trigger the alert. */ public Integer getAlertSensitivityThreshold() { return this.alertSensitivityThreshold; } /** * <p> * The minimum severity for an anomaly to trigger the alert. * </p> * * @param alertSensitivityThreshold * The minimum severity for an anomaly to trigger the alert. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withAlertSensitivityThreshold(Integer alertSensitivityThreshold) { setAlertSensitivityThreshold(alertSensitivityThreshold); return this; } /** * <p> * The type of the alert. * </p> * * @param alertType * The type of the alert. * @see AlertType */ public void setAlertType(String alertType) { this.alertType = alertType; } /** * <p> * The type of the alert. * </p> * * @return The type of the alert. * @see AlertType */ public String getAlertType() { return this.alertType; } /** * <p> * The type of the alert. * </p> * * @param alertType * The type of the alert. * @return Returns a reference to this object so that method calls can be chained together. * @see AlertType */ public AlertSummary withAlertType(String alertType) { setAlertType(alertType); return this; } /** * <p> * The type of the alert. * </p> * * @param alertType * The type of the alert. * @return Returns a reference to this object so that method calls can be chained together. * @see AlertType */ public AlertSummary withAlertType(AlertType alertType) { this.alertType = alertType.toString(); return this; } /** * <p> * The status of the alert. * </p> * * @param alertStatus * The status of the alert. * @see AlertStatus */ public void setAlertStatus(String alertStatus) { this.alertStatus = alertStatus; } /** * <p> * The status of the alert. * </p> * * @return The status of the alert. * @see AlertStatus */ public String getAlertStatus() { return this.alertStatus; } /** * <p> * The status of the alert. * </p> * * @param alertStatus * The status of the alert. * @return Returns a reference to this object so that method calls can be chained together. * @see AlertStatus */ public AlertSummary withAlertStatus(String alertStatus) { setAlertStatus(alertStatus); return this; } /** * <p> * The status of the alert. * </p> * * @param alertStatus * The status of the alert. * @return Returns a reference to this object so that method calls can be chained together. * @see AlertStatus */ public AlertSummary withAlertStatus(AlertStatus alertStatus) { this.alertStatus = alertStatus.toString(); return this; } /** * <p> * The time at which the alert was last modified. * </p> * * @param lastModificationTime * The time at which the alert was last modified. */ public void setLastModificationTime(java.util.Date lastModificationTime) { this.lastModificationTime = lastModificationTime; } /** * <p> * The time at which the alert was last modified. * </p> * * @return The time at which the alert was last modified. */ public java.util.Date getLastModificationTime() { return this.lastModificationTime; } /** * <p> * The time at which the alert was last modified. * </p> * * @param lastModificationTime * The time at which the alert was last modified. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withLastModificationTime(java.util.Date lastModificationTime) { setLastModificationTime(lastModificationTime); return this; } /** * <p> * The time at which the alert was created. * </p> * * @param creationTime * The time at which the alert was created. */ public void setCreationTime(java.util.Date creationTime) { this.creationTime = creationTime; } /** * <p> * The time at which the alert was created. * </p> * * @return The time at which the alert was created. */ public java.util.Date getCreationTime() { return this.creationTime; } /** * <p> * The time at which the alert was created. * </p> * * @param creationTime * The time at which the alert was created. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withCreationTime(java.util.Date creationTime) { setCreationTime(creationTime); return this; } /** * <p> * The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. * </p> * * @return The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. */ public java.util.Map<String, String> getTags() { return tags; } /** * <p> * The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. * </p> * * @param tags * The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags; } /** * <p> * The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. * </p> * * @param tags * The alert's <a href="https://docs.aws.amazon.com/lookoutmetrics/latest/dev/detectors-tags.html">tags</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } /** * Add a single Tags entry * * @see AlertSummary#withTags * @returns a reference to this object so that method calls can be chained together. */ public AlertSummary addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new java.util.HashMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public AlertSummary clearTagsEntries() { this.tags = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAlertArn() != null) sb.append("AlertArn: ").append(getAlertArn()).append(","); if (getAnomalyDetectorArn() != null) sb.append("AnomalyDetectorArn: ").append(getAnomalyDetectorArn()).append(","); if (getAlertName() != null) sb.append("AlertName: ").append(getAlertName()).append(","); if (getAlertSensitivityThreshold() != null) sb.append("AlertSensitivityThreshold: ").append(getAlertSensitivityThreshold()).append(","); if (getAlertType() != null) sb.append("AlertType: ").append(getAlertType()).append(","); if (getAlertStatus() != null) sb.append("AlertStatus: ").append(getAlertStatus()).append(","); if (getLastModificationTime() != null) sb.append("LastModificationTime: ").append(getLastModificationTime()).append(","); if (getCreationTime() != null) sb.append("CreationTime: ").append(getCreationTime()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AlertSummary == false) return false; AlertSummary other = (AlertSummary) obj; if (other.getAlertArn() == null ^ this.getAlertArn() == null) return false; if (other.getAlertArn() != null && other.getAlertArn().equals(this.getAlertArn()) == false) return false; if (other.getAnomalyDetectorArn() == null ^ this.getAnomalyDetectorArn() == null) return false; if (other.getAnomalyDetectorArn() != null && other.getAnomalyDetectorArn().equals(this.getAnomalyDetectorArn()) == false) return false; if (other.getAlertName() == null ^ this.getAlertName() == null) return false; if (other.getAlertName() != null && other.getAlertName().equals(this.getAlertName()) == false) return false; if (other.getAlertSensitivityThreshold() == null ^ this.getAlertSensitivityThreshold() == null) return false; if (other.getAlertSensitivityThreshold() != null && other.getAlertSensitivityThreshold().equals(this.getAlertSensitivityThreshold()) == false) return false; if (other.getAlertType() == null ^ this.getAlertType() == null) return false; if (other.getAlertType() != null && other.getAlertType().equals(this.getAlertType()) == false) return false; if (other.getAlertStatus() == null ^ this.getAlertStatus() == null) return false; if (other.getAlertStatus() != null && other.getAlertStatus().equals(this.getAlertStatus()) == false) return false; if (other.getLastModificationTime() == null ^ this.getLastModificationTime() == null) return false; if (other.getLastModificationTime() != null && other.getLastModificationTime().equals(this.getLastModificationTime()) == false) return false; if (other.getCreationTime() == null ^ this.getCreationTime() == null) return false; if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAlertArn() == null) ? 0 : getAlertArn().hashCode()); hashCode = prime * hashCode + ((getAnomalyDetectorArn() == null) ? 0 : getAnomalyDetectorArn().hashCode()); hashCode = prime * hashCode + ((getAlertName() == null) ? 0 : getAlertName().hashCode()); hashCode = prime * hashCode + ((getAlertSensitivityThreshold() == null) ? 0 : getAlertSensitivityThreshold().hashCode()); hashCode = prime * hashCode + ((getAlertType() == null) ? 0 : getAlertType().hashCode()); hashCode = prime * hashCode + ((getAlertStatus() == null) ? 0 : getAlertStatus().hashCode()); hashCode = prime * hashCode + ((getLastModificationTime() == null) ? 0 : getLastModificationTime().hashCode()); hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public AlertSummary clone() { try { return (AlertSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.lookoutmetrics.model.transform.AlertSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
7,570
10,997
import shlex def parse_cli_args_to_dict(cli_args: str): args_dict = {} for arg in shlex.split(cli_args): if '=' in arg: key, value = arg.split('=') args_dict[key] = value else: args_dict[arg] = None return args_dict
142
473
/* xerbla.f -- translated by f2c (version 20061008) */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <float.h> #include <assert.h> /* Subroutine */ int oerbla(char *srname, int *info) { /* -- LAPACK auxiliary routine (version 3.2) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* OERBLA is an error handler for the LAPACK routines. */ /* It is called by an LAPACK routine if an input parameter has an */ /* invalid value. A message is printed and execution stops. */ /* Installers may consider modifying the STOP statement in order to */ /* call system-specific exception-handling facilities. */ /* Arguments */ /* ========= */ /* SRNAME (input) CHARACTER*(*) */ /* The name of the routine which called OERBLA. */ /* INFO (input) INT */ /* The position of the invalid parameter in the parameter list */ /* of the calling routine. */ /* ===================================================================== */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ printf("** On entry to %6s, parameter number %2i had an illegal value\n", srname, *info); /* End of OERBLA */ return 0; } /* oerbla_ */
484
513
<reponame>mbachry/exxo<filename>setup.py<gh_stars>100-1000 #!/usr/bin/env python3 from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'jinja2', ] test_requirements = [ 'pytest', ] setup( name='exxo', version='0.0.7', description="Build portable Python apps", long_description=readme, author="<NAME>", author_email='<EMAIL>', url='https://github.com/mbachry/exxo', packages=['exxo'], package_dir={'exxo': 'exxo'}, include_package_data=True, install_requires=requirements, license="ISCL", zip_safe=True, entry_points={ 'console_scripts': [ 'exxo = exxo.exxo:main', ] }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', ] )
495
879
<reponame>qianfei11/zstack<filename>sdk/src/main/java/org/zstack/sdk/SharedBlockGroupType.java package org.zstack.sdk; public enum SharedBlockGroupType { LvmVolumeGroupBasic, }
70
335
<filename>N/Noninflammatory_adjective.json { "word": "Noninflammatory", "definitions": [ "Not accompanied by or associated with inflammation.", "Not controversial or contentious." ], "parts-of-speech": "Adjective" }
89
32,544
package com.baeldung.jpa.postgresql_schema; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.postgresql.ds.PGSimpleDataSource; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; import java.util.Properties; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class PostgresqlSchemaLiveTest { //This tests require running Docker application with working internet connection to fetch //Postgres image if the image is not available locally. @ClassRule public static PostgresqlTestContainer container = PostgresqlTestContainer.getInstance(); @BeforeClass public static void setup() throws Exception { Properties properties = new Properties(); properties.setProperty("user", container.getUsername()); properties.setProperty("password", container.getPassword()); Connection connection = DriverManager.getConnection(container.getJdbcUrl(), properties); connection.createStatement().execute("CREATE SCHEMA store"); connection.createStatement().execute("CREATE TABLE store.product(id SERIAL PRIMARY KEY, name VARCHAR(20))"); connection.createStatement().execute("INSERT INTO store.product VALUES(1, 'test product')"); } @Test public void settingUpSchemaUsingJdbcURL() throws Exception { Properties properties = new Properties(); properties.setProperty("user", container.getUsername()); properties.setProperty("password", container.getPassword()); Connection connection = DriverManager.getConnection(container.getJdbcUrl().concat("&currentSchema=store"), properties); ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM product"); resultSet.next(); assertThat(resultSet.getInt(1), equalTo(1)); assertThat(resultSet.getString(2), equalTo("test product")); } @Test public void settingUpSchemaUsingPGSimpleDataSource() throws Exception { int port = Integer.parseInt(container.getJdbcUrl().substring(container.getJdbcUrl().lastIndexOf(":") + 1, container.getJdbcUrl().lastIndexOf("/"))); PGSimpleDataSource ds = new PGSimpleDataSource(); ds.setServerNames(new String[]{container.getHost()}); ds.setPortNumbers(new int[]{port}); ds.setUser(container.getUsername()); ds.setPassword(<PASSWORD>()); ds.setDatabaseName("test"); ds.setCurrentSchema("store"); ResultSet resultSet = ds.getConnection().createStatement().executeQuery("SELECT * FROM product"); resultSet.next(); assertThat(resultSet.getInt(1), equalTo(1)); assertThat(resultSet.getString(2), equalTo("test product")); } @Test public void settingUpSchemaUsingTableAnnotation() { Map<String, String> props = new HashMap<>(); props.put("hibernate.connection.url", container.getJdbcUrl()); props.put("hibernate.connection.user", container.getUsername()); props.put("hibernate.connection.password", <PASSWORD>()); EntityManagerFactory emf = Persistence.createEntityManagerFactory("postgresql_schema_unit", props); EntityManager entityManager = emf.createEntityManager(); Product product = entityManager.find(Product.class, 1); assertThat(product.getName(), equalTo("test product")); } }
1,226
2,151
<gh_stars>1000+ // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_SHELL_DELEGATE_H_ #define ASH_SHELL_DELEGATE_H_ #include <memory> #include <string> #include "ash/ash_export.h" #include "base/callback.h" #include "base/strings/string16.h" class GURL; namespace aura { class Window; } namespace keyboard { class KeyboardUI; } namespace service_manager { class Connector; } namespace ui { class InputDeviceControllerClient; } namespace ash { class AccessibilityDelegate; class NetworkingConfigDelegate; class ScreenshotDelegate; // Delegate of the Shell. class ASH_EXPORT ShellDelegate { public: // The Shell owns the delegate. virtual ~ShellDelegate() {} // Returns the connector for the mojo service manager. Returns null in tests. virtual service_manager::Connector* GetShellConnector() const = 0; // Returns true if |window| can be shown for the delegate's concept of current // user. virtual bool CanShowWindowForUser(aura::Window* window) const = 0; // Called before processing |Shell::Init()| so that the delegate // can perform tasks necessary before the shell is initialized. virtual void PreInit() = 0; // Create a shell-specific keyboard::KeyboardUI. virtual std::unique_ptr<keyboard::KeyboardUI> CreateKeyboardUI() = 0; // Opens the |url| in a new browser tab. virtual void OpenUrlFromArc(const GURL& url) = 0; // Returns the delegate. May be null in tests. virtual NetworkingConfigDelegate* GetNetworkingConfigDelegate() = 0; // TODO(jamescook): Replace with a mojo-compatible interface. virtual std::unique_ptr<ScreenshotDelegate> CreateScreenshotDelegate() = 0; // Creates a accessibility delegate. Shell takes ownership of the delegate. virtual AccessibilityDelegate* CreateAccessibilityDelegate() = 0; virtual void OpenKeyboardShortcutHelpPage() const {} // Creator of Shell owns this; it's assumed this outlives Shell. virtual ui::InputDeviceControllerClient* GetInputDeviceControllerClient() = 0; }; } // namespace ash #endif // ASH_SHELL_DELEGATE_H_
641
2,962
package com.pushtorefresh.storio3.contentresolver.annotations; public class NestedClass { @StorIOContentResolverType(uri = "content://uri") public static class ActualClass { @StorIOContentResolverColumn(name = "id", key = true) long id; @StorIOContentResolverColumn(name = "author") String author; @StorIOContentResolverColumn(name = "content") String content; } }
167
2,695
<reponame>yxcde/RTP_MIT_RECODED // Copyright (C) 2003 <NAME> (<EMAIL>) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_DIR_NAV_KERNEL_1_CPp_ #define DLIB_DIR_NAV_KERNEL_1_CPp_ #include "../platform.h" #ifdef WIN32 #include "dir_nav_kernel_1.h" #include "../string.h" #ifdef __BORLANDC__ // Apparently the borland compiler doesn't define this. #define INVALID_FILE_ATTRIBUTES ((DWORD)-1) #endif namespace dlib { // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // file object implementation // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- void file:: init ( const std::string& name ) { using namespace std; char buf[3000]; char* str; if (GetFullPathNameA(name.c_str(),sizeof(buf),buf,&str) == 0) { // the file was not found throw file_not_found("Unable to find file " + name); } state.full_name = buf; string::size_type pos = state.full_name.find_last_of(directory::get_separator()); if (pos == string::npos) { // no valid full path has no separator characters. throw file_not_found("Unable to find file " + name); } state.name = state.full_name.substr(pos+1); // now find the size of this file WIN32_FIND_DATAA data; HANDLE ffind = FindFirstFileA(state.full_name.c_str(), &data); if (ffind == INVALID_HANDLE_VALUE || (data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) != 0) { throw file_not_found("Unable to find file " + name); } else { uint64 temp = data.nFileSizeHigh; temp <<= 32; temp |= data.nFileSizeLow; state.file_size = temp; FindClose(ffind); } } // ---------------------------------------------------------------------------------------- bool file:: operator == ( const file& rhs ) const { using namespace std; if (state.full_name.size() != rhs.state.full_name.size()) return false; // compare the strings but ignore the case because file names // are not case sensitive on windows return tolower(state.full_name) == tolower(rhs.state.full_name); } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // directory object implementation // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- void directory:: init ( const std::string& name ) { using namespace std; char buf[3000]; char* str; if (GetFullPathNameA(name.c_str(),sizeof(buf),buf,&str) == 0) { // the directory was not found throw dir_not_found("Unable to find directory " + name); } state.full_name = buf; const char sep = get_separator(); if (is_root_path(state.full_name) == false) { // ensure that thre is not a trialing separator if (state.full_name[state.full_name.size()-1] == sep) state.full_name.erase(state.full_name.size()-1); // pick out the directory name string::size_type pos = state.full_name.find_last_of(sep); state.name = state.full_name.substr(pos+1); } else { // ensure that there is a trailing separator if (state.full_name[state.full_name.size()-1] != sep) state.full_name += sep; } // now check that this is actually a valid directory DWORD attribs = GetFileAttributesA(state.full_name.c_str()); if (attribs == INVALID_FILE_ATTRIBUTES || (attribs&FILE_ATTRIBUTE_DIRECTORY) == 0) { // the directory was not found throw dir_not_found("Unable to find directory " + name); } } // ---------------------------------------------------------------------------------------- char directory:: get_separator ( ) { return '\\'; } // ---------------------------------------------------------------------------------------- bool directory:: operator == ( const directory& rhs ) const { using namespace std; if (state.full_name.size() != rhs.state.full_name.size()) return false; // compare the strings but ignore the case because file names // are not case sensitive on windows return tolower(state.full_name) == tolower(rhs.state.full_name); } // ---------------------------------------------------------------------------------------- const directory directory:: get_parent ( ) const { using namespace std; // if *this is the root then just return *this if (is_root()) { return *this; } else { directory temp; const char sep = get_separator(); string::size_type pos = state.full_name.find_last_of(sep); temp.state.full_name = state.full_name.substr(0,pos); if ( is_root_path(temp.state.full_name)) { temp.state.full_name += sep; } else { pos = temp.state.full_name.find_last_of(sep); if (pos != string::npos) { temp.state.name = temp.state.full_name.substr(pos+1); } else { temp.state.full_name += sep; } } return temp; } } // ---------------------------------------------------------------------------------------- bool directory:: is_root_path ( const std::string& path ) const { using namespace std; const char sep = get_separator(); bool root_path = false; if (path.size() > 2 && path[0] == sep && path[1] == sep) { // in this case this is a windows share path string::size_type pos = path.find_first_of(sep,2); if (pos != string::npos) { pos = path.find_first_of(sep,pos+1); if (pos == string::npos && path[path.size()-1] != sep) root_path = true; else if (pos == path.size()-1) root_path = true; } } else if ( (path.size() == 2 || path.size() == 3) && path[1] == ':') { // if this is a valid windows path then it must be a root path root_path = true; } return root_path; } // ---------------------------------------------------------------------------------------- } #endif // WIN32 #endif // DLIB_DIR_NAV_KERNEL_1_CPp_
3,201
683
<reponame>aphex3k/specter-desktop from ..addresslist import * from embit.liquid.addresses import addr_decode, to_unconfidential class LAddress(Address): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._unconfidential = to_unconfidential(self.address) @property def unconfidential(self): return self._unconfidential or self.address @property def is_confidential(self): return self.address != self.unconfidential class LAddressList(AddressList): AddressCls = LAddress def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # scriptpubkey dict for lookups of unconf addresses self._scripts = {} self._update_scripts() def _update_scripts(self): for addr in list(self.keys()): sc, _ = addr_decode(addr) if sc and sc not in self._scripts: self._scripts[sc] = super().__getitem__(addr) def add(self, *args, **kwargs): res = super().add(*args, **kwargs) # update scriptpubkey dict for lookups of unconf addresses self._update_scripts() return res def __contains__(self, addr): """finds address by confidential or unconfidential address by converting to scriptpubkey""" try: # can fail if addr is "Fee", "Dummy" or hex-scriptpubkey sc, _ = addr_decode(addr) if sc and self._scripts.__contains__(sc): return True except: pass return super().__contains__(addr) def __getitem__(self, addr): """finds address by confidential or unconfidential address by converting to scriptpubkey""" sc, _ = addr_decode(addr) if sc in self._scripts: return self._scripts[sc] return super().__getitem__(addr) def get(self, addr, default=None): try: return self[addr] except KeyError: return default
834