text
stringlengths
4
6.14k
/* Copyright 2014-2016 Maurice Laveaux * * 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 OGLR_OPENGL_SHADER_SHADERPROGRAM_H_ #define OGLR_OPENGL_SHADER_SHADERPROGRAM_H_ #include "core/Log.h" #include "core/NonCopyable.h" #include "opengl/shader/Shader.h" #include "opengl/shader/ShaderUniform.h" #include <string> #include <memory> #include <map> namespace oglr { /** * A shader program contains of several attached shaders that * are linked together. */ class ShaderProgram : private NonCopyable { public: /** A shared point type for the shader program */ typedef std::shared_ptr<ShaderProgram> Ptr; /** * Create a shader program object from shaders. */ ShaderProgram(Shader::Ptr vertexShader, Shader::Ptr fragmentShader); ~ShaderProgram(); /** * Enables the shader program to use it for rendering. */ void use(); /** Unload the linked shaders from this program such that they can be destroyed. */ void unload(); /** Reload the uniforms and attach the new loaded shaders. */ void reload(); /** Check whether this shader program (and associated shader objects) are valid for rendering. */ bool isValid(); /** * Obtain a shader uniform from this program. * * @param[in] name The name of the uniform. */ ShaderUniform* getUniformLocation(const std::string& name); /** @return The resource name string. */ const std::string& getResourceName(); /** Retrieve the individual shaders attached to this program. */ Shader::Ptr getVertexShader(); Shader::Ptr getFragmentShader(); private: Shader::Ptr m_vertexShader; Shader::Ptr m_fragmentShader; std::map<std::string, ShaderUniform> m_uniformLocations; // Hashmap of known uniform locations. std::string m_resourceName; unsigned int m_shaderProgram = 0; // The opengl shader program index. }; } // oglr namespace #endif // OGLR_OPENGL_SHADER_SHADERPROGRAM_H_
/** Atomix project, BlockTZ_i.c, TODO: insert summary here Copyright (c) 2015 Stanford University Released under the Apache License v2.0. See the LICENSE file for details. Author(s): Manu Bansal */ #include <osl/inc/swpform.h> #include <oros/sfifos/fifoFactory.h> #include <oros/sfifos/fifoManager.h> #include "BlockTZ_t.h" void BlockTZ_i ( IN FIFO_BufferState * bh_src, OUT FIFO_BufferState * bh_dst, CF BlockTZ_Conf * conf ){ Uint32 linkNum = conf->linkNum; FIFO_clearTC(linkNum); //****************************************// //** sfifos v3.1 - isTCCValid bit added **// //****************************************// bh_src->isTCCValid = 1; bh_dst->isTCCValid = 1; bh_src->linkNum = linkNum; bh_dst->linkNum = linkNum; //DEBUG(printf("TZ: transfer from buffer seqNo %d to buffer seqNo %d over linkNum %d\n", bh_src->seqNo, bh_dst->seqNo, linkNum);) DEBUG(printf("TZ: transfer over linkNum %d\n", linkNum);) //IPC_dma_transfer(linkNum, (Uint32 *)bh_src->mem_ga, (Uint32 *)bh_dst->mem_ga, bh_src->lengthInBytes/8); IPC_dma_transfer(linkNum, (Uint32 *)bh_src->mem, (Uint32 *)bh_dst->mem, conf->lengthInDblWords); //No readDone and writeDone are declared since this is an asynchronous //transfer. These events will be automatically deduced by the fifo manager. } void BlockTZ_i_conf ( CF BlockTZ_Conf * conf, IN Uint32 lengthInDblWords, IN Uint32 linkNum ){ conf->linkNum = linkNum; conf->lengthInDblWords = lengthInDblWords; }
/************************************************************************************************** * File name : Calculator.h * Description : Declare the class of Calculator. * Creator : Frederick Hsu * Creation date: Wed. 13 July, 2016 * Copyright(C) 2016 All rights reserved. * **************************************************************************************************/ #ifndef CALCULATOR_H #define CALCULATOR_H #import <Foundation/Foundation.h> @interface Calculator : NSObject { } -(double)pi; -(double)square : (double)number; -(double)sumOfNumbers : (double)num1 : (double)num2; @end #endif /* CALCULATOR_H */
#ifndef PARSER #define PARSER #include <string> #include <forward_list> #include "Token.h" #include "Node.h" namespace lyrics { using std::string; using std::forward_list; class Parser { public: BlockNode *Parse(const forward_list<Token> *tokenList); private: forward_list<Token>::const_iterator mToken; BlockNode *Block(); StatementNode *Statement(); ExpressionNode *PrimaryExpression(); ArrayLiteralNode *ArrayLiteral(); HashLiteralNode *HashLiteral(); FunctionLiteralNode *FunctionLiteral(forward_list<Token>::const_iterator token); ParenthesizedExpressionNode *ParenthesizedExpression(); ExpressionNode *PostfixExpression(); ExpressionNode *UnaryExpression(); ExpressionNode *MultiplicativeExpression(); ExpressionNode *AdditiveExpression(); ExpressionNode *ShiftExpression(); ExpressionNode *AndExpression(); ExpressionNode *OrExpression(); ExpressionNode *RelationalExpression(); ExpressionNode *EqualityExpression(); ExpressionNode *LogicalAndExpression(); ExpressionNode *LogicalOrExpression(); ExpressionNode *AssignmentExpression(); AssignmentExpressionNode *Class(); IncludeNode *Include(); AssignmentExpressionNode *Package(); ExpressionNode *Expression(); ImportNode *Import(); IfNode *If(); CaseNode *Case(); WhileNode *While(); ForNode *For(); ForEachNode *ForEach(); BreakNode *Break(); NextNode *Next(); ReturnNode *Return(); }; } #endif
// // AppDelegate.h // oneLine // // Created by Aditya Narayan on 6/24/15. // Copyright (c) 2015 Guang. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
#pragma once #include "BaseChunk.h" class CPramChunk : public CBaseChunk { public: typedef std::vector<std::string> StringTable; struct PARAMETER { std::string name; bool isPixelShaderParam = false; uint8 unknown2 = 0; uint8 numValues = 0; uint8 unknown3 = 0; uint32 unknown4 = 0; uint32 unknown5 = 0; uint32 unknown6 = 0; float valueX = 0; float valueY = 0; float valueZ = 0; float valueW = 0; }; typedef std::vector<PARAMETER> ParameterArray; struct SAMPLER { std::string name; StringTable strings; }; typedef std::vector<SAMPLER> SamplerArray; CPramChunk(); virtual ~CPramChunk(); virtual void Read(Framework::CStream&) override; int16 GetRenderMode() const; const ParameterArray& GetParameters() const; const SamplerArray& GetSamplers() const; private: typedef std::vector<uint32> OffsetArray; OffsetArray ReadOffsets(Framework::CStream&, uint32); void ReadParameters(Framework::CStream&, uint32, const OffsetArray&, const OffsetArray&); void ReadSamplers(Framework::CStream&, uint32, const OffsetArray&, const OffsetArray&); uint32 m_numParameters; uint32 m_parameterNameStart; uint32 m_numSamplers; uint32 m_samplerDataStart; uint32 m_samplerNameStart; int16 m_renderMode; ParameterArray m_parameters; SamplerArray m_samplers; }; typedef std::shared_ptr<CPramChunk> PramChunkPtr;
// Copyright (c) 2015, Doru Budai. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef JASS_DRAWABLES_BITMAP_H_ #define JASS_DRAWABLES_BITMAP_H_ #include <glad/glad.h> #include <boost/filesystem.hpp> #include <string> #include <memory> #include "jass/drawables/drawable.h" namespace GL { class VertexArrayObject; class VertexBufferObject; class Texture; class Program; } namespace Drawables { class Bitmap : public Drawable { public: explicit Bitmap(boost::filesystem::path const &path); virtual ~Bitmap(void); void Create(void) override; void Render(void) override; GLfloat width(void) { return width_; } GLfloat height(void) { return height_; } private: std::shared_ptr<GL::Program> program_; std::shared_ptr<GL::Texture> texture_; boost::filesystem::path path_; GLfloat width_; GLfloat height_; std::shared_ptr<GL::VertexArrayObject> vao_; std::shared_ptr<GL::VertexBufferObject> vbo_; }; } // namespace Drawables #endif // JASS_DRAWABLES_BITMAP_H_
#define CTR_MSG_LANG_CODE "xh" #define CTR_MSG_WELCOME "Citrine/XH\n" #define CTR_MSG_COPYRIGHT "Gabor de Mooij ©, Licensed BSD\n" #define CTR_MSG_USAGE_G "Akukho ziphikiso zaneleyo Ukusetyenziswa:: ctr -g file1.h file2.h" #define CTR_MSG_USAGE_T "Akukho ziphikiso zaneleyo Ukusetyenziswa:: ctr -t d.dict program.ctr" #define CTR_ERR_LEX " %s  kumgca: %d " #define CTR_ERR_TOKBUFF "Ithokheni Buffer Exaigue Iipokotshi mazingabi ngaphezulu kwe-255 yeesiti" #define CTR_ERR_OOM "Ngapha kokungagcinwanga" #define CTR_ERR_SYNTAX "Iphutha lomhlaba okungalindelekanga %s  ( %s : %d )" #define CTR_ERR_LONG "Umyalezo mde kakhulu" #define CTR_ERR_EXP_COLON "Ilindelwe [:].\n" #define CTR_ERR_EXP_MSG "Ilindelwe [umyalezo].\n" #define CTR_ERR_EXP_PCLS "Ilindelwe [)].\n" #define CTR_ERR_EXP_DOT "Ukuphela komgca olindelekileyo" #define CTR_ERR_EXP_KEY "Isitshixo kufuneka sihlale silandelwa ngegama lepropathi!" #define CTR_ERR_EXP_VAR "Isandla sesikhombi kufuneka sihlale silandelwa ngokwahluka!" #define CTR_ERR_EXP_RCP "Ilindelwe ukuba ifumane umyalezo" #define CTR_ERR_EXP_MSG2 "Umamkeli akanakulandelwa yikholoni" #define CTR_ERR_INV_LAS "Umsebenzi ongasasebenziyo" #define CTR_ERR_EXP_BLK "Ilindelwe [Ikhowudi]." #define CTR_ERR_EXP_ARR "Ilindelwe [Uluhlu]." #define CTR_ERR_EXP_NUM "Ilindelwe [Inani]." #define CTR_ERR_EXP_STR "Ilindelwe [Umtya]." #define CTR_ERR_DIVZERO "Yahlula ngokwe-zero" #define CTR_ERR_BOUNDS "Isalathiso esiphuma kwimida" #define CTR_ERR_REGEX "Ayikwazanga ukudibanisa intetho eqhelekileyo" #define CTR_ERR_SIPHKEY "Isitshixo kufuneka sibengu-16 ubude" #define CTR_SYM_OBJECT "[Object]" #define CTR_SYM_BLOCK "[Block]" #define CTR_SYM_FILE "[File (no path)]" #define CTR_ERR_OPEN "Ayikwazi ukuvula: %s " #define CTR_ERR_DELETE "Ayikwazi ukucima" #define CTR_ERR_FOPENED "Ifayile sele ivuliwe" #define CTR_ERR_SEEK "Ukufuna akuphumelelanga" #define CTR_ERR_LOCK "Ayikwazi ukukhiya" #define CTR_ERR_RET "Inkcazo yokubuya engasebenziyo" #define CTR_ERR_SEND "Ayikwazi ukuthumela umyalezo kumamkeli wohlobo: %d " #define CTR_ERR_KEYINX "Isitshixo sokubhaliweyo siphelelwe lixesha" #define CTR_ERR_ANOMALY "Inqanaba lomyalezo lifunyenwe" #define CTR_ERR_UNCAUGHT "Impazamo engathunyelwanga yenzekile" #define CTR_ERR_NODE "Ixesha lokuqhuba linempazamo Indawo yokungasebenzi yepharse: %d %s " #define CTR_ERR_MISSING "Indawo engekhoyo yeparse" #define CTR_ERR_FOPEN "Impazamo ngelixa kuvulwa ifayile" #define CTR_ERR_RNUM "Kufuneka ubuye [Inani].\n" #define CTR_ERR_RSTR "Kufuneka ubuye [Umtya].\n" #define CTR_ERR_RBOOL "Kufuneka ubuye [Boolean].\n" #define CTR_ERR_NESTING "Iifowuni ezininzi kakhulu ezenzelwe indawo" #define CTR_ERR_KNF "Isitshixo asifumaneki:" #define CTR_ERR_ASSIGN "Ayinakusebenzisa umahluko ongachazwanga:" #define CTR_ERR_EXEC "Ayikwazi ukwenza umyalelo" #define CTR_MSG_DSC_FILE "file" #define CTR_MSG_DSC_FLDR "folder" #define CTR_MSG_DSC_SLNK "symbolic link" #define CTR_MSG_DSC_CDEV "character device" #define CTR_MSG_DSC_BDEV "block device" #define CTR_MSG_DSC_SOCK "socket" #define CTR_MSG_DSC_NPIP "named pipe" #define CTR_MSG_DSC_OTHR "other" #define CTR_MSG_DSC_TYPE "type" #define CTR_TERR_LMISMAT "Language mismatch." #define CTR_TERR_LONG "Translation error, message too long." #define CTR_TERR_DICT "Error opening dictionary." #define CTR_TERR_KMISMAT "Error: key mismatch %s %s on line %d\n" #define CTR_TERR_ELONG "Dictionary entry too long." #define CTR_TERR_AMWORD "Ambiguous word in dictionary: %s." #define CTR_TERR_AMTRANS "Ambiguous translation in dictionary: %s." #define CTR_TERR_TMISMAT "Keyword/Binary mismatch:" #define CTR_TERR_BUFF "Unable to copy translation to buffer." #define CTR_TERR_WARN "Warning: Not translated: " #define CTR_TERR_TOK "Token length exceeds maximum buffer size." #define CTR_TERR_PART "Inxalenye yegama eliphambili lomyalezo wegama eliphambili lidlula umda we-buffer" #define CTR_TERR_COLONS "Different no. of colons." #define CTR_MSG_ERROR "Impazamo" #define CTR_MERR_OOM "Ngapha kokungagcinwanga Ayiphumelelanga ukwaba %lu  i-byte\n" #define CTR_MERR_MALLOC "Ngapha kokungagcinwanga Ayiphumelelanga ukwaba %lu  i-byte (malloc). \n" #define CTR_MERR_POOL "Unable to allocate memory pool.\n" #define CTR_STDDATEFRMT "%Y-%m-%d %H:%M:%S" #define CTR_STDTIMEZONE "UTC"
#include <PiDxe.h> #include <Library/DebugLib.h> #include <Library/ResetSystemLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/LKEnvLib.h> #include <Library/IoLib.h> #include <Protocol/QcomPm8921.h> #include <Platform/iomap.h> STATIC QCOM_PM8921_PROTOCOL *mPm8921 = NULL; STATIC VOID shutdown_device(VOID) { mPm8921->pm8921_config_reset_pwr_off(0); // Actually reset the chip writel(0, MSM_PSHOLD_CTL_SU); mdelay(5000); DEBUG((EFI_D_ERROR, "Shutdown failed.\n")); } STATIC VOID reboot_device(UINTN reboot_reason) { writel(reboot_reason, RESTART_REASON_ADDR); // Actually reset the chip mPm8921->pm8921_config_reset_pwr_off(1); writel(0, MSM_PSHOLD_CTL_SU); mdelay(10000); DEBUG((EFI_D_ERROR, "PSHOLD failed, trying watchdog reset\n")); writel(1, MSM_WDT0_RST); writel(0, MSM_WDT0_EN); writel(0x31F3, MSM_WDT0_BT); writel(3, MSM_WDT0_EN); dmb(); writel(3, MSM_TCSR_BASE + TCSR_WDOG_CFG); mdelay(10000); DEBUG((EFI_D_ERROR, "Rebooting failed\n")); } VOID EFIAPI ResetCold ( VOID ) { reboot_device(0); } VOID EFIAPI ResetWarm ( VOID ) { ResetCold (); } VOID EFIAPI ResetShutdown ( VOID ) { shutdown_device(); } VOID EFIAPI EnterS3WithImmediateWake ( VOID ) { // not implemented } VOID EFIAPI ResetPlatformSpecific ( IN UINTN DataSize, IN VOID *ResetData ) { ResetCold (); } RETURN_STATUS EFIAPI ResetLibConstructor ( VOID ) { EFI_STATUS Status; Status = gBS->LocateProtocol (&gQcomPm8921ProtocolGuid, NULL, (VOID **)&mPm8921); ASSERT_EFI_ERROR (Status); return EFI_SUCCESS; }
/* jgfs2 * (c) 2013 Justin Gottula * The source code of this project is distributed under the terms of the * simplified BSD license. See the LICENSE file for details. */ #include "../tree.h" #include "../../debug.h" /* modify parameters and then run benchmarks on (1) avg node utilization, * (2) percentage of insertions/deletions that resulted in balance operations, * and (3) avg length of time for a balance operation */ // for branch nodes (fixed key weight): // B = 0 // 2Q = node_space_usable() / sizeof(node_ref) // P = node_space_usable() // for leaf nodes (variable key weight): /*#define B 2 // locality parameter: nodes per sweep #define Q ??? // order: min keys per node #define P 4077 // rank: max node weight #define MU_MAX_K 256 // max key weight #define NEIGHBORS B #define SWEEP_LEN (B + 1) #define CANDIDATES ((B * 2) - 1)*/ node_ptr tree_split_single(node_ptr node, const key *key, uint32_t space_needed) { // split in 1:2 fashion (normal btree split) // split to the right always // make space for the insertion key when splitting // insert the key in that spot // handle root, of course // need to update parent refs (recursive split concern: before or after?) // make sure to update this node's ref if we inserted into index 0 // return pointer to node with spot for the key // caller needs to fill the elem data afterward (if appropriate) return NULL; } node_ptr tree_split_pair(node_ptr nodes[2], const key *key, uint32_t space_needed) { // similar to tree_split_single // can put the new node to the left, in the middle, or to the right // optimally, we choose whichever direction results in the least transfers // update this node's ref if we inserted into index 0 return NULL; } void tree_merge_single(node_ptr nodes[2], const key *key) { // merge 2->1 // at the same time, remove the key given // caller needs to pre-zero elem data beforehand if necessary } void tree_merge_pair(node_ptr nodes[3], const key *key) { }
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * 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. * */ // Copyright (c) 2022, WNProject 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 ROCKETCOREELEMENTIMAGE_H #define ROCKETCOREELEMENTIMAGE_H #include "../../Include/Rocket/Core/Element.h" #include "../../Include/Rocket/Core/Geometry.h" #include "../../Include/Rocket/Core/Texture.h" namespace Rocket { namespace Core { class TextureResource; /** The 'img' element. The image element can have a rectangular sub-region of its source texture specified with the 'coords' attribute; the element will render this region rather than the entire image. The 'coords' attribute is similar to that of the HTML imagemap. It takes four comma-separated integer values, specifying the top-left and the bottom right of the region in pixel-coordinates, in that order. So for example, the attribute "coords" = "0, 10, 100, 210" will render a 100 x 200 region, beginning at (0, 10) and rendering through to (100, 210). No clamping to the dimensions of the source image will occur; rendered results in this case will depend on the texture addressing mode. The intrinsic dimensions of the image can now come from three different sources. They are used in the following order: 1) 'width' / 'height' attributes if present 2) pixel width / height given by the 'coords' attribute 3) width / height of the source texture This has the result of sizing the element to the pixel-size of the rendered image, unless overridden by the 'width' or 'height' attributes. @author Peter Curry */ class ElementImage : public Element { public: ROCKET_RTTI_DefineWithParent(Element); /// Constructs a new ElementImage. This should not be called directly; use the /// Factory instead. /// @param[in] tag The tag the element was declared as in RML. ElementImage(Core::Context* _context, const String& tag); virtual ~ElementImage(); /// Returns the element's inherent size. /// @param[out] The element's intrinsic dimensions. /// @return True. virtual bool GetIntrinsicDimensions(Vector2f& dimensions) override; protected: /// Renders the image. virtual void OnRender() override; /// Checks for changes to the image's source or dimensions. /// @param[in] changed_attributes A list of attributes changed on the element. virtual void OnAttributeChange( const AttributeNameList& changed_attributes) override; /// Called when properties on the element are changed. /// @param[in] changed_properties The properties changed on the element. virtual void OnPropertyChange( const PropertyNameList& changed_properties) override; /// Regenerates the element's geometry on a resize event. /// @param[in] event The event to process. virtual void ProcessEvent(Event& event) override; private: // Generates the element's geometry. void GenerateGeometry(); // Loads the element's texture, as specified by the 'src' attribute. bool LoadTexture(); // Resets the values of the 'coords' attribute to mark them as unused. void ResetCoords(); // The texture this element is rendering from. Texture texture; // True if we need to refetch the texture's source from the element's // attributes. bool texture_dirty; // The element's computed intrinsic dimensions. If either of these values are // set to -1, then // that dimension has not been computed yet. Vector2f dimensions; // The integer coords extracted from the 'coords' attribute. using_coords will // be false if // these have not been specified or are invalid. int coords[4]; bool using_coords; // The geometry used to render this element. Geometry geometry; bool geometry_dirty; }; } // namespace Core } // namespace Rocket #endif
/** * Copyright (C) 2016, Vadim Fedorov <coderiks@gmail.com> * * This program is free software: you can use, modify and/or * redistribute it under the terms of the simplified BSD * License. You should have received a copy of this license along * this program. If not, see * <http://www.opensource.org/licenses/bsd-license.html>. */ #ifndef GRID_INFO_H #define GRID_INFO_H #include <memory> namespace msas { /** * Represents coordinates of a node of a regular grid. */ struct GridCoord { float x; // real x coordinate within a grid float y; // real y coordinate within a grid int index_x; // column id of the node in a grid int index_y; // row id of the node in a grid }; /** * Represents a regular grid. * @see EllipseNormalization::create_regular_grid() for construction details. */ struct GridInfo { float step; // distance between the nodes int size; // number of nodes along each dimension std::unique_ptr<GridCoord[]> nodes; // array of nodes' coordinates size_t nodes_length; // total number of nodes std::unique_ptr<int[]> index; // mapping between position of a node and its id in the nodes array size_t index_length; // length of the index array GridInfo() : step(0.0f), size(0), nodes_length(0), index_length(0) { } }; } #endif //GRID_INFO_H
/* * cguess - C/C++/Java(tm) auto-completion tool for VIM * Copyright (C) 2005 Andrzej Zaborowski <balrog@zabor.org> * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* */ #ifndef __context_h_ # define __context_h_ 1 # include "symbols.h" # include "identifier.h" /* TODO: some of these can be macros */ void context_init(); void context_open(const struct symbol_table_s *context); void context_close(); void context_done(); struct symbol_table_s *context_local(); struct symbol_table_s *context_global(); struct identifier_s *context_lookup(const char *key); #endif /* __context_h_ */
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2012 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_COMMON_IO #define PX_PHYSICS_COMMON_IO #include "PxIO.h" #include "../Source/shared/general/PxIOStream/public/PxFileBuf.h" #include "CmPhysXCommon.h" #include "PxAssert.h" #include "CmLegacyStream.h" namespace physx { // wrappers for IO classes so that we can add extra functionality (byte counting, buffering etc) namespace Cm { class InputStreamReader { public: InputStreamReader(PxInputStream& stream) : mStream(stream) { } PxU32 read(void* dest, PxU32 count) { PxU32 readLength = mStream.read(dest, count); // zero the buffer if we didn't get all the data if(readLength<count) Ps::memZero(reinterpret_cast<PxU8*>(dest)+readLength, count-readLength); return readLength; } template <typename T> T get() { T val; PxU32 length = mStream.read(&val, sizeof(T)); PX_ASSERT(length == sizeof(T)); return val; } protected: PxInputStream &mStream; }; class InputDataReader : public InputStreamReader { public: InputDataReader(PxInputData& data) : InputStreamReader(data) {} PxU32 length() const { return getData().getLength(); } void seek(PxU32 offset) { getData().seek(offset); } PxU32 tell() { return getData().tell(); } private: PxInputData& getData() { return static_cast<PxInputData&>(mStream); } const PxInputData& getData() const { return static_cast<const PxInputData&>(mStream); } }; class OutputStreamWriter { public: PX_INLINE OutputStreamWriter(PxOutputStream& stream) : mStream(stream) , mCount(0) {} PX_INLINE PxU32 write(const void* src, PxU32 offset) { PxU32 count = mStream.write(src, offset); mCount += count; return count; } PX_INLINE PxU32 getStoredSize() { return mCount; } template<typename T> void put(const T& val) { PxU32 length = write(&val, sizeof(T)); PX_ASSERT(length == sizeof(T)); } private: PxOutputStream& mStream; PxU32 mCount; }; class LegacySerialStream : public PxSerialStream { public: LegacySerialStream(OutputStreamWriter& writer) : mWriter(writer) {} void storeBuffer(const void* buffer, PxU32 size) { mWriter.write(buffer, size); } PxU32 getTotalStoredSize() { return mWriter.getStoredSize(); } private: OutputStreamWriter& mWriter; }; } } #endif
#ifdef E_TYPEDEFS typedef enum _E_Fm2_Op_Status { E_FM2_OP_STATUS_UNKNOWN = 0, E_FM2_OP_STATUS_IN_PROGRESS, E_FM2_OP_STATUS_SUCCESSFUL, E_FM2_OP_STATUS_ABORTED, E_FM2_OP_STATUS_ERROR } E_Fm2_Op_Status; typedef struct _E_Fm2_Op_Registry_Entry E_Fm2_Op_Registry_Entry; #else #ifndef E_FM_OP_REGISTRY_H #define E_FM_OP_REGISTRY_H typedef void (*E_Fm2_Op_Registry_Abort_Func)(E_Fm2_Op_Registry_Entry *entry); struct _E_Fm2_Op_Registry_Entry { int id; int percent; /* XXX use char? */ off_t done; off_t total; Evas_Object *e_fm; const char *src; /* stringshared */ const char *dst; /* stringshared */ double start_time; int eta; /* XXX use double? */ E_Fm_Op_Type op; E_Fm2_Op_Status status; Eina_Bool needs_attention E_BITFIELD; E_Dialog *dialog; Eina_Bool finished E_BITFIELD; // service callbacks struct { E_Fm2_Op_Registry_Abort_Func abort; } func; }; extern E_API int E_EVENT_FM_OP_REGISTRY_ADD; extern E_API int E_EVENT_FM_OP_REGISTRY_DEL; extern E_API int E_EVENT_FM_OP_REGISTRY_CHANGED; E_API int e_fm2_op_registry_entry_ref(E_Fm2_Op_Registry_Entry *entry); E_API int e_fm2_op_registry_entry_unref(E_Fm2_Op_Registry_Entry *entry); E_API Ecore_X_Window e_fm2_op_registry_entry_xwin_get(const E_Fm2_Op_Registry_Entry *entry); E_API E_Fm2_Op_Registry_Entry *e_fm2_op_registry_entry_get(int id); E_API void e_fm2_op_registry_entry_listener_add(E_Fm2_Op_Registry_Entry *entry, void (*cb)(void *data, const E_Fm2_Op_Registry_Entry *entry), const void *data, void (*free_data)(void *data)); E_API void e_fm2_op_registry_entry_listener_del(E_Fm2_Op_Registry_Entry *entry, void (*cb)(void *data, const E_Fm2_Op_Registry_Entry *entry), const void *data); E_API Eina_Iterator *e_fm2_op_registry_iterator_new(void); E_API Eina_List *e_fm2_op_registry_get_all(void); E_API void e_fm2_op_registry_get_all_free(Eina_List *list); E_API Eina_Bool e_fm2_op_registry_is_empty(void); E_API int e_fm2_op_registry_count(void); E_API void e_fm2_op_registry_entry_abort(E_Fm2_Op_Registry_Entry *entry); EINTERN unsigned int e_fm2_op_registry_init(void); EINTERN unsigned int e_fm2_op_registry_shutdown(void); /* E internal/private functions, symbols not exported outside e binary (e_fm.c mainly) */ Eina_Bool e_fm2_op_registry_entry_add(int id, Evas_Object *e_fm, E_Fm_Op_Type op, E_Fm2_Op_Registry_Abort_Func abort); Eina_Bool e_fm2_op_registry_entry_del(int id); void e_fm2_op_registry_entry_changed(const E_Fm2_Op_Registry_Entry *entry); void e_fm2_op_registry_entry_e_fm_set(E_Fm2_Op_Registry_Entry *entry, Evas_Object *e_fm); void e_fm2_op_registry_entry_files_set(E_Fm2_Op_Registry_Entry *entry, const char *src, const char *dst); #endif #endif
// // GIUserViewController.h // Github Issues // // Created by Matt Clarke on 18/12/2016. // Copyright © 2016 Matt Clarke. All rights reserved. // #import <UIKit/UIKit.h> @interface GIUserViewController : UIViewController @property (nonatomic, strong) UIImageView *backgroundAvatarView; @property (nonatomic, strong) UIVisualEffectView *effectView; @property (nonatomic, strong) UIVisualEffectView *vibrancyView; @property (nonatomic, strong) UIView *centraliserView; @property (nonatomic, strong) UIImageView *foregroundAvatarView; @property (nonatomic, strong) UILabel *nameLabel; @property (nonatomic, strong) UILabel *emailLabel; @property (nonatomic, strong) UIView *separatorView; @property (nonatomic, strong) UIButton *logoutButton; @end
////////////////////////////////////////////////////////////////////////////// // NOTICE: // // ADLib, Prop and their related set of tools and documentation are in the // public domain. The author(s) of this software reserve no copyrights on // the source code and any code generated using the tools. You are encouraged // to use ADLib and Prop to develop software, in both academic and commercial // settings, and are free to incorporate any part of ADLib and Prop into // your programs. // // Although you are under no obligation to do so, we strongly recommend that // you give away all software developed using our tools. // // We also ask that credit be given to us when ADLib and/or Prop are used in // your programs, and that this notice be preserved intact in all the source // code. // // This software is still under development and we welcome any suggestions // and help from the users. // // Allen Leung // 1994 ////////////////////////////////////////////////////////////////////////////// #ifndef ordered_hashing_based_map_h #define ordered_hashing_based_map_h #include <AD/contain/hashmap.h> #include <AD/hash/ohash.h> ///////////////////////////////////////////////////////////////////////// // Class OHMap ///////////////////////////////////////////////////////////////////////// template <class K, class V> class OHMap : public HashMap<K, V, OHashTable<K,V> > { public: ////////////////////////////////////////////////////////////////// // Constructors and destructor ////////////////////////////////////////////////////////////////// OHMap(int size = 64, double max_load = 1000.0) : HashMap<K,V,OHashTable<K,V> >(size,max_load) {} OHMap(const V& v, int size = 64, double max_load = 1000.0) : HashMap<K,V,OHashTable<K,V> >(v,size,max_load) {} ~OHMap() {} ////////////////////////////////////////////////////////////////// // Everything else is inherited from HashMap ////////////////////////////////////////////////////////////////// typedef HashMap<K, V, OHashTable<K,V> > Super; typedef Super::Key Key; typedef Super::Value Value; typedef Super::Element Element; }; #endif
// // Copyright 1997 Nicholas J. Irias. All rights reserved. // // // ZimbabweSplitter.h : // Splitter to remember the height of the lowest splitter pane, even if // the splitter is sized smaller than that pane. This class is called // a Zimbabwe splitter because it is not in any way generic. It is intended // only for use with a horizontal two pane splitter. Making this class // generic is left as an exercise for someone with spare time. #ifndef __ZIMBABWESPLITTER__ #define __ZIMBABWESPLITTER__ ///////////////////////////////////////////////////////////////////////////// // CSplitter frame with splitter #ifndef __AFXEXT_H__ #include <afxext.h> #endif #include "FlatSplitter.h" class CZimbabweSplitter : public CFlatSplitter { DECLARE_DYNCREATE(CZimbabweSplitter) public: CZimbabweSplitter(); RECT m_ZimbabweRect; int m_BarAndBorders; int m_cyCur0; int m_cyCur1; BOOL m_Sizing; // Operations public: void RecalcLayout(); void Resized(); void SetSizing(BOOL sizing) { m_Sizing= sizing; } // Implementation public: virtual ~CZimbabweSplitter(); DECLARE_MESSAGE_MAP() }; #endif //__ZIMBABWESPLITTER__ /////////////////////////////////////////////////////////////////////////////
#ifndef _IO_PORTS_H_ #define _IO_PORTS_H_ #include <types.h> extern uint_8 inb(uint_16 port); extern uint_16 inw(uint_16 port); extern uint_32 inl(uint_16 port); extern void outb(uint_16 port, uint_8 value); extern void outw(uint_16 port, uint_16 value); extern void outl(uint_16 port, uint_32 value); #endif
#include <arm_neon.h> #include "scale.h" int neon_orig(DATA32* _p0, DATA32* _p1, DATA32* _p2, DATA32* _p3, DATA32* _ax, DATA32 _ay, DATA32* result, int len) { #ifdef __arm__ int ay = _ay; int i; DATA32* pbuf = result; __asm__ __volatile__(".fpu neon \n\t");; __asm__ __volatile__("vdup.16 d12, %[val] \n\t" :: [val] "r" (ay) : "d12");; __asm__ __volatile__("vmov.i16 q2, #255 \n\t" ::: "q2");; for(i = 0; i < len; i++) { DATA32 p0 = *_p0++; DATA32 p1 = *_p1++; DATA32 p2 = *_p2++; DATA32 p3 = *_p3++; int ax = *_ax++; if (p0 | p1 | p2 | p3) { __asm__ __volatile__(".fpu neon \n\t");; __asm__ __volatile__("vmov.32 d8[0], %[val] \n\t" :: [val] "r" (p0) : "d8");; __asm__ __volatile__("veor q0, q0, q0 \n\t" ::: "q0");; __asm__ __volatile__("vmov.32 d9[0], %[val] \n\t" :: [val] "r" (p2) : "d9");; __asm__ __volatile__("vmov.32 d10[0], %[val] \n\t" :: [val] "r" (p1) : "d10");; __asm__ __volatile__("veor q1, q1, q1 \n\t" ::: "q1");; __asm__ __volatile__("vmov.32 d11[0], %[val] \n\t" :: [val] "r" (p3) : "d11");; __asm__ __volatile__("vdup.16 q3, %[val] \n\t" :: [val] "r" (ax) : "q3");; __asm__ __volatile__("vzip.8 q4, q0 \n\t" ::: "q4" , "q0");; __asm__ __volatile__("vzip.8 q5, q1 \n\t" ::: "q5" , "q1");; __asm__ __volatile__("vmov d9, d0 \n\t" ::: "d9");; __asm__ __volatile__("vmov d11, d2 \n\t" ::: "d11");; __asm__ __volatile__( "vsub.i16 q5, q5, q4 \n\t" "vmul.u16 q5, q5, q3 \n\t" "vsri.16 q5, q5, #8 \n\t" "vadd.i16 q5, q5, q4 \n\t" "vand q4, q5, q2 \n\t" ::: "q5", "q4" );; __asm__ __volatile__( "vsub.i16 d9, d9, d8 \n\t" "vmul.u16 d9, d9, d12 \n\t" "vsri.16 d9, d9, #8 \n\t" "vadd.i16 d9, d9, d8 \n\t" "vand d8, d9, d5 \n\t" ::: "d9", "d8" );; __asm__ __volatile__( "vqmovn.u16 d8, q4 \n\t" "vst1.32 {d8[0]}, [%[p]] \n\t" :: [p] "r" (pbuf) : "d8", "memory");; pbuf++; } else *pbuf++ = p0; } #endif return 0; }
#ifndef __SANCUS_STRING_H__ #define __SANCUS_STRING_H__ #include <string.h> static inline ssize_t sancus_memcpy(char *dest, ssize_t dest_size, const char *src, size_t n) { ssize_t ret; if ((ssize_t)n > dest_size) { n = (size_t)dest_size; ret = -ENOBUFS; } else { ret = (ssize_t)n; } if (n > 0) memcpy(dest, src, n); return ret; } static inline ssize_t sancus_strncpy(char *dest, ssize_t dest_size, const char *src, size_t n) { ssize_t ret = -ENOBUFS; if (dest_size > 0) { size_t sz = (size_t)dest_size; if (n < sz) ret = (ssize_t)n; else n = sz - 1; if (n > 0) memcpy(dest, src, n); dest[n] = '\0'; } return ret; } static inline ssize_t sancus_strcpy(char *dest, ssize_t dest_size, const char *src) { size_t n; if (src != NULL && *src != '\0') n = strlen(src); else n = 0; return sancus_strncpy(dest, dest_size, src, n); } #endif
/*- * BSD 2-Clause License * * Copyright (c) 2012-2018, Jan Breuer * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file scpi_units.h * @date Thu Nov 15 10:58:45 UTC 2012 * * @brief SCPI Units * * */ #ifndef SCPI_UNITS_H #define SCPI_UNITS_H #include "scpi/types.h" #ifdef __cplusplus extern "C" { #endif extern const scpi_unit_def_t scpi_units_def[]; extern const scpi_choice_def_t scpi_special_numbers_def[]; scpi_bool_t SCPI_ParamNumber(scpi_t * context, const scpi_choice_def_t * special, scpi_number_t * value, scpi_bool_t mandatory); scpi_bool_t SCPI_ParamTranslateNumberVal(scpi_t * context, scpi_parameter_t * parameter); size_t SCPI_NumberToStr(scpi_t * context, const scpi_choice_def_t * special, scpi_number_t * value, char * str, size_t len); #ifdef __cplusplus } #endif #endif /* SCPI_UNITS_H */
extern void p_extension_init(void *(*gl_GetProcAddress)(const char* proc)); extern boolean p_extension_test(const char *string); extern void p_shader_init(void); extern void p_shader_param_load(ENode *parent, uint32 node_id, void *array, uint count, uint environment, uint diffuse_environment); extern uint p_shader_get_param_count(ENode *node); extern VMatFrag *p_shader_get_param(ENode *node, uint nr); extern char p_shader_get_source_vertex(ENode *node); extern char p_shader_get_source_frag(ENode *node); extern boolean p_shader_transparancy(uint32 node_id); extern void p_shader_bind(uint32 node_id); extern void p_shader_unbind(uint32 node_id); extern boolean p_shaders_supported(void); extern boolean p_shader_shadow_bind(void);
// // UIAlertView+Blocks.h // Popups+Blocks // // Created by Johannes Schriewer on 08.03.2013. // Copyright (c) 2013 Johannes Schriewer. All rights reserved. // #import <UIKit/UIKit.h> #import "Popups+DSTBlocks.h" @interface UIAlertView (DSTBlocks) - (UIAlertView *)initWithTitle:(NSString *)title message:(NSString *)message cancelButton:(DSTBlockButton *)cancelButton otherButtons:(NSArray *)otherButtons; - (void)addButton:(DSTBlockButton *)button; - (void)setWillPresentBlock:(DSTWillPresentPopupBlock)block; - (void)setDidPresentBlock:(DSTPopupPresentedBlock)block; @end
// (c) Partha Dasgupta 2009 // permission to use and distribute granted. #define _GNU_SOURCE #include <sched.h> #include <stdio.h> #include <stdlib.h> void *stack; int x=1; void func1() {int i = 0; printf("Thread 1 - running\n"); for (i=0; i<100000000; i++) x++; printf("Thread 1: x = %d\n", x); printf("Thread 1 - done\n"); } int func2(void* arg) {int i = 0; printf(" Thread 2 - running\n"); for (i=0; i<100000000; i++) x++; printf(" Thread 2: x = %d\n", x); printf(" Thread 2 - done\n"); return i; } int main() { stack = malloc(60000); printf("starting\n"); int pid = clone(&func2, stack+10000, CLONE_VM|CLONE_FS, 0); printf("cloned: %d\n", pid); func1(); sleep(1); printf("final value %d\n", x); }
#ifndef GEOLITE2UPDATERTHREAD_H #define GEOLITE2UPDATERTHREAD_H #include <QThread> #include "maxmind.h" class Geolite2UpdaterThread : public QThread { Q_OBJECT private: MaxMind* mm; protected: void run(); public: Geolite2UpdaterThread(MaxMind* mm); signals: void errMsg(QString brief, QString message); }; #endif // GEOLITE2UPDATERTHREAD_H
/* $NetBSD: in6_offload.c,v 1.6 2011/04/25 22:07:57 yamt Exp $ */ /*- * Copyright (c)2006 YAMAMOTO Takashi, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <special_includes/sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: in6_offload.c,v 1.6 2011/04/25 22:07:57 yamt Exp $"); #include <special_includes/sys/param.h> #include <special_includes/sys/mbuf.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <netinet6/in6_var.h> #include <netinet6/nd6.h> #include <netinet6/in6_offload.h> struct ip6_tso_output_args { struct ifnet *ifp; struct ifnet *origifp; const struct sockaddr_in6 *dst; struct rtentry *rt; }; static int ip6_tso_output_callback(void *, struct mbuf *); static int ip6_tso_output_callback(void *vp, struct mbuf *m) { struct ip6_tso_output_args *args = vp; return nd6_output(args->ifp, args->origifp, m, args->dst, args->rt); } int ip6_tso_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m, const struct sockaddr_in6 *dst, struct rtentry *rt) { struct ip6_tso_output_args args; args.ifp = ifp; args.origifp = origifp; args.dst = dst; args.rt = rt; return tcp6_segment(m, ip6_tso_output_callback, &args); } /* * tcp6_segment: handle M_CSUM_TSOv6 by software. * * => always consume m. * => call output_func with output_arg for each segments. */ int tcp6_segment(struct mbuf *m, int (*output_func)(void *, struct mbuf *), void *output_arg) { int mss; int iphlen; int thlen; int hlen; int len; struct ip6_hdr *iph; struct tcphdr *th; uint32_t tcpseq; struct mbuf *hdr = NULL; struct mbuf *t; int error = 0; KASSERT((m->m_flags & M_PKTHDR) != 0); KASSERT((m->m_pkthdr.csum_flags & M_CSUM_TSOv6) != 0); m->m_pkthdr.csum_flags = 0; len = m->m_pkthdr.len; KASSERT(len >= sizeof(*iph) + sizeof(*th)); if (m->m_len < sizeof(*iph)) { m = m_pullup(m, sizeof(*iph)); if (m == NULL) { error = ENOMEM; goto quit; } } iph = mtod(m, struct ip6_hdr *); iphlen = sizeof(*iph); KASSERT((iph->ip6_vfc & IPV6_VERSION_MASK) == IPV6_VERSION); KASSERT(iph->ip6_nxt == IPPROTO_TCP); hlen = iphlen + sizeof(*th); if (m->m_len < hlen) { m = m_pullup(m, hlen); if (m == NULL) { error = ENOMEM; goto quit; } } th = (void *)(mtod(m, char *) + iphlen); tcpseq = ntohl(th->th_seq); thlen = th->th_off * 4; hlen = iphlen + thlen; mss = m->m_pkthdr.segsz; KASSERT(mss != 0); KASSERT(len > hlen); t = m_split(m, hlen, M_NOWAIT); if (t == NULL) { error = ENOMEM; goto quit; } hdr = m; m = t; len -= hlen; KASSERT(len % mss == 0); while (len > 0) { struct mbuf *n; n = m_dup(hdr, 0, hlen, M_NOWAIT); if (n == NULL) { error = ENOMEM; goto quit; } KASSERT(n->m_len == hlen); /* XXX */ t = m_split(m, mss, M_NOWAIT); if (t == NULL) { m_freem(n); error = ENOMEM; goto quit; } m_cat(n, m); m = t; KASSERT(n->m_len >= hlen); /* XXX */ n->m_pkthdr.len = hlen + mss; iph = mtod(n, struct ip6_hdr *); KASSERT((iph->ip6_vfc & IPV6_VERSION_MASK) == IPV6_VERSION); iph->ip6_plen = htons(thlen + mss); th = (void *)(mtod(n, char *) + iphlen); th->th_seq = htonl(tcpseq); th->th_sum = 0; th->th_sum = in6_cksum(n, IPPROTO_TCP, iphlen, thlen + mss); error = (*output_func)(output_arg, n); if (error) { goto quit; } tcpseq += mss; len -= mss; } quit: if (hdr != NULL) { m_freem(hdr); } if (m != NULL) { m_freem(m); } return error; } void ip6_undefer_csum(struct mbuf *m, size_t hdrlen, int csum_flags) { const size_t ip6_plen_offset = hdrlen + offsetof(struct ip6_hdr, ip6_plen); size_t l4hdroff; size_t l4offset; uint16_t plen; uint16_t csum; KASSERT(m->m_flags & M_PKTHDR); KASSERT((m->m_pkthdr.csum_flags & csum_flags) == csum_flags); KASSERT(csum_flags == M_CSUM_UDPv6 || csum_flags == M_CSUM_TCPv6); if (__predict_true(hdrlen + sizeof(struct ip6_hdr) <= m->m_len)) { plen = *(uint16_t *)(mtod(m, char *) + ip6_plen_offset); } else { m_copydata(m, ip6_plen_offset, sizeof(plen), &plen); } plen = ntohs(plen); l4hdroff = M_CSUM_DATA_IPv6_HL(m->m_pkthdr.csum_data); l4offset = hdrlen + l4hdroff; csum = in6_cksum(m, 0, l4offset, plen - l4hdroff); if (csum == 0 && (csum_flags & M_CSUM_UDPv6) != 0) csum = 0xffff; l4offset += M_CSUM_DATA_IPv6_OFFSET(m->m_pkthdr.csum_data); if (__predict_true((l4offset + sizeof(uint16_t)) <= m->m_len)) { *(uint16_t *)(mtod(m, char *) + l4offset) = csum; } else { m_copyback(m, l4offset, sizeof(csum), (void *) &csum); } m->m_pkthdr.csum_flags ^= csum_flags; }
#pragma once #include <opencv2/opencv.hpp> #include <memory> #include <iostream> #include <iomanip> #include <functional> #define ABSTRUCT_CLONEABLE(T) \ protected:\ virtual T* _cloneinner()const=0;\ public:\ std::shared_ptr<T> clone()const{ \ return std::shared_ptr<T>(_cloneinner()); \ } #define CLONEABLE(T) \ protected:\ virtual T* _cloneinner()const{ \ return new T(*this); \ }\ public:\ std::shared_ptr<T>clone()const{ \ return std::shared_ptr<T>(_cloneinner()); \ } namespace cv_wrapper{ struct ClassifierParam { std::string name; }; class Classifier; typedef std::shared_ptr<Classifier> SClassifier; class Classifier { protected: bool trained_flag; cv::Mat norm_coef; cv::Mat norm_bias; Classifier(){} std::string name; Classifier(const std::string& name) :name(name) { }; Classifier(const Classifier& obj){ trained_flag = false; if (!obj.norm_coef.empty()) norm_coef = obj.norm_coef.clone(); if (!obj.norm_bias.empty()) norm_bias = obj.norm_bias.clone(); } public: bool isTrained(){return trained_flag;} virtual ~Classifier(){}; static SClassifier create(){ throw std::runtime_error("no create function!"); } void reset_scale(); void train_scale(cv::InputArray data,float minVal=-1.0,float maxVal=1.0); void normalize(cv::InputArray src, cv::OutputArray dst); virtual void train(cv::InputArray labeled,cv::InputArray label,cv::InputArray sampleIdx=cv::Mat(),cv::InputArray weight=cv::Mat())=0; virtual float predict(const cv::Mat& data)=0; virtual std::map<float,float> predict_probability(const cv::Mat& data)=0; static std::vector<int> getIdxVector(int sample_size,const cv::Mat& idxmat); std::string getName()const{ return name; } ABSTRUCT_CLONEABLE(Classifier); }; }
#import <ABI40_0_0UMCore/ABI40_0_0UMExportedModule.h> #import <ABI40_0_0UMCore/ABI40_0_0UMModuleRegistryConsumer.h> @interface ABI40_0_0EXInterstitialAdManager : ABI40_0_0UMExportedModule <ABI40_0_0UMModuleRegistryConsumer> @end
/**ARGS: symbols --explain --locate "-DFOO=(1+1)" -DBAR=3 */ /**SYSCODE: = 2 */ #define SYM (FOO And (FOO SYM BAR) And BAR) #if SYM KEEP ME #endif
/* * ASTImport.h * * This file is part of the "XieXie 2.0 Project" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #ifndef __XX_AST_IMPORT_H__ #define __XX_AST_IMPORT_H__ /* --- Common AST types --- */ #include "Program.h" #include "CodeBlock.h" #include "VarName.h" #include "VarDecl.h" #include "Param.h" #include "Arg.h" #include "ProcSignature.h" #include "AttribPrefix.h" #include "Attrib.h" #include "ArrayAccess.h" #include "ProcCall.h" #include "SwitchCase.h" /* --- Statements --- */ #include "ReturnStmnt.h" #include "CtrlTransferStmnt.h" #include "ExprStmnt.h" #include "IfStmnt.h" #include "SwitchStmnt.h" #include "ForStmnt.h" #include "ForEachStmnt.h" #include "ForRangeStmnt.h" #include "RepeatStmnt.h" #include "WhileStmnt.h" #include "DoWhileStmnt.h" #include "ClassDeclStmnt.h" #include "VarDeclStmnt.h" #include "ProcDeclStmnt.h" #include "FriendDeclStmnt.h" #include "CopyAssignStmnt.h" #include "ModifyAssignStmnt.h" #include "PostOperatorStmnt.h" /* --- Expressions --- */ #include "TernaryExpr.h" #include "BinaryExpr.h" #include "UnaryExpr.h" #include "LiteralExpr.h" #include "CastExpr.h" #include "ProcCallExpr.h" #include "PostfixValueExpr.h" #include "InstanceOfExpr.h" #include "AllocExpr.h" #include "VarAccessExpr.h" #include "InitListExpr.h" #include "RangeExpr.h" /* --- Type denoters --- */ #include "BuiltinTypeDenoter.h" #include "ArrayTypeDenoter.h" #include "PointerTypeDenoter.h" #endif // ================================================================================
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import "ABI38_0_0RCTTurboModule.h" @protocol ABI38_0_0RCTTurboModuleManagerDelegate <NSObject> // TODO: Move to xplat codegen. - (std::shared_ptr<ABI38_0_0facebook::ABI38_0_0React::TurboModule>)getTurboModule:(const std::string &)name instance:(id<ABI38_0_0RCTTurboModule>)instance jsInvoker: (std::shared_ptr<ABI38_0_0facebook::ABI38_0_0React::CallInvoker>)jsInvoker; @optional /** * Given a module name, return its actual class. If not provided, basic ObjC class lookup is performed. */ - (Class)getModuleClassFromName:(const char *)name; /** * Given a module class, provide an instance for it. If not provided, default initializer is used. */ - (id<ABI38_0_0RCTTurboModule>)getModuleInstanceFromClass:(Class)moduleClass; /** * Create an instance of a TurboModule without relying on any ObjC++ module instance. */ - (std::shared_ptr<ABI38_0_0facebook::ABI38_0_0React::TurboModule>)getTurboModule:(const std::string &)name jsInvoker: (std::shared_ptr<ABI38_0_0facebook::ABI38_0_0React::CallInvoker>)jsInvoker; @end @interface ABI38_0_0RCTTurboModuleManager : NSObject <ABI38_0_0RCTTurboModuleLookupDelegate> - (instancetype)initWithBridge:(ABI38_0_0RCTBridge *)bridge delegate:(id<ABI38_0_0RCTTurboModuleManagerDelegate>)delegate; - (void)installJSBindingWithRuntime:(ABI38_0_0facebook::jsi::Runtime *)runtime; - (std::shared_ptr<ABI38_0_0facebook::ABI38_0_0React::TurboModule>)getModule:(const std::string &)name; - (void)invalidate; @end
/* * Copyright © 2011 Intel Corporation * * 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 (including the next * paragraph) 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. */ #include "brw_context.h" #include "brw_state.h" #include "brw_defines.h" #include "brw_util.h" #include "program/prog_parameter.h" #include "program/prog_statevars.h" #include "intel_batchbuffer.h" static void upload_vs_state(struct brw_context *brw) { struct intel_context *intel = &brw->intel; BEGIN_BATCH(2); OUT_BATCH(_3DSTATE_BINDING_TABLE_POINTERS_VS << 16 | (2 - 2)); OUT_BATCH(brw->vs.bind_bo_offset); ADVANCE_BATCH(); if (brw->vs.push_const_size == 0) { /* Disable the push constant buffers. */ BEGIN_BATCH(7); OUT_BATCH(_3DSTATE_CONSTANT_VS << 16 | (7 - 2)); OUT_BATCH(0); OUT_BATCH(0); OUT_BATCH(0); OUT_BATCH(0); OUT_BATCH(0); OUT_BATCH(0); ADVANCE_BATCH(); } else { BEGIN_BATCH(7); OUT_BATCH(_3DSTATE_CONSTANT_VS << 16 | (7 - 2)); OUT_BATCH(brw->vs.push_const_size); OUT_BATCH(0); /* Pointer to the VS constant buffer. Covered by the set of * state flags from gen6_prepare_wm_contants */ OUT_BATCH(brw->vs.push_const_offset); OUT_BATCH(0); OUT_BATCH(0); OUT_BATCH(0); ADVANCE_BATCH(); } BEGIN_BATCH(6); OUT_BATCH(_3DSTATE_VS << 16 | (6 - 2)); OUT_BATCH(brw->vs.prog_offset); OUT_BATCH((0 << GEN6_VS_SAMPLER_COUNT_SHIFT) | GEN6_VS_FLOATING_POINT_MODE_ALT | (brw->vs.nr_surfaces << GEN6_VS_BINDING_TABLE_ENTRY_COUNT_SHIFT)); OUT_BATCH(0); /* scratch space base offset */ OUT_BATCH((1 << GEN6_VS_DISPATCH_START_GRF_SHIFT) | (brw->vs.prog_data->urb_read_length << GEN6_VS_URB_READ_LENGTH_SHIFT) | (0 << GEN6_VS_URB_ENTRY_READ_OFFSET_SHIFT)); OUT_BATCH(((brw->vs_max_threads - 1) << GEN6_VS_MAX_THREADS_SHIFT) | GEN6_VS_STATISTICS_ENABLE | GEN6_VS_ENABLE); ADVANCE_BATCH(); } const struct brw_tracked_state gen7_vs_state = { .dirty = { .mesa = _NEW_TRANSFORM | _NEW_PROGRAM_CONSTANTS, .brw = (BRW_NEW_CURBE_OFFSETS | BRW_NEW_NR_VS_SURFACES | BRW_NEW_URB_FENCE | BRW_NEW_CONTEXT | BRW_NEW_VERTEX_PROGRAM | BRW_NEW_VS_BINDING_TABLE | BRW_NEW_BATCH), .cache = CACHE_NEW_VS_PROG }, .emit = upload_vs_state, };
// 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. #ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SERVER_INITIATED_SPDY_STREAM_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SERVER_INITIATED_SPDY_STREAM_H_ #include "quic/core/http/quic_spdy_stream.h" namespace quic { // QuicServerInitiatedSpdyStream is a subclass of QuicSpdyStream meant to handle // WebTransport traffic on server-initiated bidirectional streams. Receiving or // sending any other traffic on this stream will result in a CONNECTION_CLOSE. class QUIC_EXPORT_PRIVATE QuicServerInitiatedSpdyStream : public QuicSpdyStream { public: using QuicSpdyStream::QuicSpdyStream; void OnBodyAvailable() override; size_t WriteHeaders( spdy::SpdyHeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener) override; void OnInitialHeadersComplete(bool fin, size_t frame_len, const QuicHeaderList& header_list) override; }; } // namespace quic #endif // QUICHE_QUIC_CORE_HTTP_QUIC_SERVER_INITIATED_SPDY_STREAM_H_
// Copyright (c) 2015 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_UI_EXCLUSIVE_ACCESS_EXCLUSIVE_ACCESS_MANAGER_H_ #define CHROME_BROWSER_UI_EXCLUSIVE_ACCESS_EXCLUSIVE_ACCESS_MANAGER_H_ #include "base/macros.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.h" #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" #include "chrome/browser/ui/exclusive_access/keyboard_lock_controller.h" #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h" class ExclusiveAccessContext; class FullscreenController; class GURL; class KeyboardLockController; class MouseLockController; namespace content { struct NativeWebKeyboardEvent; class WebContents; } // This class combines the different exclusive access modes (like fullscreen and // mouse lock) which are each handled by respective controller. It also updates // the exit bubble to reflect the combined state. class ExclusiveAccessManager { public: explicit ExclusiveAccessManager( ExclusiveAccessContext* exclusive_access_context); ExclusiveAccessManager(const ExclusiveAccessManager&) = delete; ExclusiveAccessManager& operator=(const ExclusiveAccessManager&) = delete; ~ExclusiveAccessManager(); FullscreenController* fullscreen_controller() { return &fullscreen_controller_; } KeyboardLockController* keyboard_lock_controller() { return &keyboard_lock_controller_; } MouseLockController* mouse_lock_controller() { return &mouse_lock_controller_; } ExclusiveAccessContext* context() const { return exclusive_access_context_; } ExclusiveAccessBubbleType GetExclusiveAccessExitBubbleType() const; void UpdateExclusiveAccessExitBubbleContent(ExclusiveAccessBubbleHideCallback, bool force_update = false); GURL GetExclusiveAccessBubbleURL() const; // Callbacks //////////////////////////////////////////////////////////////// // Called by Browser::TabDeactivated. void OnTabDeactivated(content::WebContents* web_contents); // Called by Browser::ActiveTabChanged. void OnTabDetachedFromView(content::WebContents* web_contents); // Called by Browser::TabClosingAt. void OnTabClosing(content::WebContents* web_contents); // Called by Browser::PreHandleKeyboardEvent. bool HandleUserKeyEvent(const content::NativeWebKeyboardEvent& event); // Called by Browser::ContentsMouseEvent. void OnUserInput(); // Called by platform ExclusiveAccessExitBubble. void ExitExclusiveAccess(); void RecordBubbleReshownUMA(ExclusiveAccessBubbleType type); private: ExclusiveAccessContext* const exclusive_access_context_; FullscreenController fullscreen_controller_; KeyboardLockController keyboard_lock_controller_; MouseLockController mouse_lock_controller_; }; #endif // CHROME_BROWSER_UI_EXCLUSIVE_ACCESS_EXCLUSIVE_ACCESS_MANAGER_H_
/*! \file cros_message_queue.h * \brief This header file declares the cRosMessageQueue type and associated management functions * * cRosMessageQueue implements a queue of TCPROS-protocol messages. This queue behaves as a * FIFO (First In First Out). * This queue only stores the fields of the messages ('fields' fields of the struct), not the message definition (msgDef field). * \author Richard R. Carrillo. Aging in Vision and Action lab, Institut de la Vision, Sorbonne University, Paris, France. * \date 31 Oct 2017 */ #ifndef _CROS_MESSAGE_QUEUE_H_ #define _CROS_MESSAGE_QUEUE_H_ #include "cros_message.h" #define MAX_QUEUE_LEN 10 //! Maximum number of messages that can be hold in the queue struct cRosMessageQueue { cRosMessage msgs[MAX_QUEUE_LEN]; //! Content of the queue unsigned int length; //! Number of messages currently in the queue unsigned int first_msg_ind; //! Index of the oldest message in the queue (the one that was inserted first) }; typedef struct cRosMessageQueue cRosMessageQueue; /*! \brief Initializes a queue. * * This function must be called before using a queue for the first time. * \param q Pointer to the queue. */ void cRosMessageQueueInit(cRosMessageQueue *q); /*! \brief Empty queue. * * This function removes all the messages in a queue. * \param q Pointer to the queue. */ void cRosMessageQueueClear(cRosMessageQueue *q); /*! \brief Deletes the content of a queue and free all its allocated memory. * * This function frees the memory allocated for its content so cRosMessageQueueInit() must be called before * using the queue again. * \param q Pointer to the queue. */ void cRosMessageQueueRelease(cRosMessageQueue *q); /*! \brief Calculates the free space still available in the queue. * * \return Number of messages that can still be added to the queue without causing an overflow. */ unsigned int cRosMessageQueueVacancies(cRosMessageQueue *q); /*! \brief Calculates the number of messages stored in the queue. * * \return Number of messages that can be removed from the queue. */ unsigned int cRosMessageQueueUsage(cRosMessageQueue *q); /*! \brief Add a new message at the end of the queue. * * This function adds a new element (message) at the end of the queue. The fields of the message pointed by m will be copied * in internal memory of the queue, so the message pointed by m can be freed after being added. * \param q Pointer to the queue. * \param m Pointer to the message to be added. * \return 0 on success, otherwise an error code: -1 = error allocating memory, -2 = No free space to add a new element. */ int cRosMessageQueueAdd(cRosMessageQueue *q, cRosMessage *m); /*! \brief Extract the first message of the queue. * * This function removes a element (message) at the start of the queue. The fields of the message at the start of the queue will be copied * to the message pointed by m, so the message pointed by m should be freed independently after being used. * \param q Pointer to the queue. * \param m Pointer to the message where the fields of the removed message are copied. * \return 0 on success, otherwise an error code: -1 = error allocating memory, -2 = No messages in the queue. If an error occurs, the * message is not removed from the queue. */ int cRosMessageQueueExtract(cRosMessageQueue *q, cRosMessage *m); /*! \brief Get a copy of the first message from the queue. * * This function obtains the element (message) at the start of the queue. The fields of the message at the start of the queue will be copied * to the message pointed by m, so the message pointed by m should be freed independently after being used. * The queue is not modified. * \param q Pointer to the queue. * \param m Pointer to the message where the fields of the removed message are copied. * \return 0 on success, otherwise an error code: -1 = error allocating memory, -2 = No messages in the queue. */ int cRosMessageQueueGet(cRosMessageQueue *q, cRosMessage *m); /*! \brief Delete the first message from the queue. * * This function removes a element (message) at the start of the queue. * \param q Pointer to the queue. * \return 0 on success, otherwise an error code: -2 = No messages in the queue. */ int cRosMessageQueueRemove(cRosMessageQueue *q); /*! \brief Get a reference of the first message from the queue. * * This function obtains a pointer to the element (message) at the start of the queue (oldest element). The fields of the message at the * start of the queue will not be copied, so if the message queue is modified after obtaining this pointer, the pointer become invalid. * The queue is not modified. * \param q Pointer to the queue. * \return Pointer to the first message. If the first message could not be obtained, NULL is returned. */ cRosMessage *cRosMessageQueuePeekFirst(cRosMessageQueue *q); /*! \brief Get a reference of the last message from the queue. * * This function obtains a pointer to the element (message) at the end of the queue (newest element). The fields of this message * of the queue will not be copied, so if the message queue is modified after obtaining this pointer, the pointer become invalid. * The queue is not modified by this function. * \param q Pointer to the queue. * \return Pointer to the last message. If the last message could not be obtained, NULL is returned. */ cRosMessage *cRosMessageQueuePeekLast(cRosMessageQueue *q); #endif // _CROS_MESSAGE_QUEUE_H_
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef TERA_SDK_SCHEMA_IMPL_H_ #define TERA_SDK_SCHEMA_IMPL_H_ #include <string> #include "proto/table_meta.pb.h" #include "tera.h" namespace tera { /// 列族描述 class CFDescImpl : public ColumnFamilyDescriptor { public: /// 列族名字仅允许使用字母、数字和下划线构造, 长度不超过256 CFDescImpl(const std::string& cf_name, int32_t id, const std::string& lg_name); /// id int32_t Id() const; const std::string& Name() const; const std::string& LocalityGroup() const; /// 历史版本保留时间, 不设置时为0, 表示无限大永久保存 void SetTimeToLive(int32_t ttl); int32_t TimeToLive() const; /// 在TTL内,最多存储的版本数 void SetMaxVersions(int32_t max_versions); int32_t MaxVersions() const; /// 最少存储的版本数,即使超出TTL,也至少保留min_versions个版本 void SetMinVersions(int32_t min_versions); int32_t MinVersions() const; /// 存储限额, MBytes void SetDiskQuota(int64_t quota); int64_t DiskQuota() const; /// ACL void SetAcl(ACL acl); ACL Acl() const; void SetType(const std::string& type); const std::string& Type() const; private: int32_t _id; std::string _name; std::string _lg_name; int32_t _max_versions; int32_t _min_versions; int32_t _ttl; int64_t _acl; int32_t _owner; int32_t _disk_quota; std::string _type; }; /// 局部性群组描述 class LGDescImpl : public LocalityGroupDescriptor { public: /// 局部性群组名字仅允许使用字母、数字和下划线构造,长度不超过256 LGDescImpl(const std::string& lg_name, int32_t id); /// Id read only int32_t Id() const; /// Name read only const std::string& Name() const; /// Compress type void SetCompress(CompressType type); CompressType Compress() const; /// Block size void SetBlockSize(int block_size); int BlockSize() const; /// Store type void SetStore(StoreType type); StoreType Store() const; /// Bloomfilter void SetUseBloomfilter(bool use_bloomfilter); bool UseBloomfilter() const; /// Memtable On Leveldb (disable/enable) bool UseMemtableOnLeveldb() const; void SetUseMemtableOnLeveldb(bool use_mem_ldb); /// Memtable-LDB WriteBuffer Size int32_t MemtableLdbWriteBufferSize() const; void SetMemtableLdbWriteBufferSize(int32_t buffer_size); /// Memtable-LDB Block Size int32_t MemtableLdbBlockSize() const; void SetMemtableLdbBlockSize(int32_t block_size); /// sst file size, in Bytes int32_t SstSize() const; void SetSstSize(int32_t sst_size); private: int32_t _id; std::string _name; CompressType _compress_type; StoreType _store_type; int _block_size; bool _use_bloomfilter; bool _use_memtable_on_leveldb; int32_t _memtable_ldb_write_buffer_size; int32_t _memtable_ldb_block_size; int32_t _sst_size; // in bytes }; /// 表描述符. class TableDescImpl { public: /// 表格名字仅允许使用字母、数字和下划线构造,长度不超过256 TableDescImpl(const std::string& tb_name); ~TableDescImpl(); void SetTableName(const std::string& name); std::string TableName() const; /// 增加一个localitygroup LocalityGroupDescriptor* AddLocalityGroup(const std::string& lg_name); /// 获取默认localitygroup,仅用于kv表 LocalityGroupDescriptor* DefaultLocalityGroup(); /// 删除一个localitygroup bool RemoveLocalityGroup(const std::string& lg_name); /// 获取localitygroup const LocalityGroupDescriptor* LocalityGroup(int32_t id) const; const LocalityGroupDescriptor* LocalityGroup(const std::string& lg_name) const; /// 获取localitygroup数量 int32_t LocalityGroupNum() const; /// 增加一个columnfamily ColumnFamilyDescriptor* AddColumnFamily(const std::string& cf_name, const std::string& lg_name); ColumnFamilyDescriptor* DefaultColumnFamily(); /// 删除一个columnfamily void RemoveColumnFamily(const std::string& cf_name); /// 获取所有的colmnfamily const ColumnFamilyDescriptor* ColumnFamily(int32_t id) const; const ColumnFamilyDescriptor* ColumnFamily(const std::string& cf_name) const; int32_t ColumnFamilyNum() const; /// Raw Key Mode void SetRawKey(RawKeyType type); RawKeyType RawKey() const; void SetSplitSize(int64_t size); int64_t SplitSize() const; void SetMergeSize(int64_t size); int64_t MergeSize() const; void DisableWal(); bool IsWalDisabled() const; void EnableTxn(); bool IsTxnEnabled() const; /// 插入snapshot int32_t AddSnapshot(uint64_t snapshot); /// 获取snapshot uint64_t Snapshot(int32_t id) const; /// Snapshot数量 int32_t SnapshotNum() const; void SetAdminGroup(const std::string& name); std::string AdminGroup() const; void SetAdmin(const std::string& name); std::string Admin() const; void SetAlias(const std::string& alias); std::string Alias() const; private: typedef std::map<std::string, LGDescImpl*> LGMap; typedef std::map<std::string, CFDescImpl*> CFMap; std::string _name; LGMap _lg_map; std::vector<LGDescImpl*> _lgs; CFMap _cf_map; std::vector<CFDescImpl*> _cfs; int32_t _next_lg_id; int32_t _next_cf_id; std::vector<uint64_t> _snapshots; static const std::string DEFAULT_LG_NAME; static const std::string DEFAULT_CF_NAME; RawKeyType _raw_key_type; int64_t _split_size; int64_t _merge_size; bool _disable_wal; bool _enable_txn; std::string _admin_group; std::string _admin; std::string _alias; }; } // namespace tera #endif // TERA_SDK_SCHEMA_IMPL_H_
/* * Copyright (c) 2009-2010, Bjoern Knafla * http://www.bjoernknafla.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Bjoern Knafla * Parallelization + AI + Gamedev Consulting nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * * Backend specific definition of amp mutex to allow placing a mutex on the * stack though platform specific headers will be included. * * @attention Don't copy a variable of type amp_raw_mutex_s - copying a pointer * to this type is ok though. * * TODO: @todo Add Apple OS X 10.6 libdispatch backends for amp_raw_ mutex. */ #ifndef AMP_amp_raw_mutex_H #define AMP_amp_raw_mutex_H #include <amp/amp_mutex.h> #if defined(AMP_USE_PTHREADS) # include <pthread.h> #elif defined(AMP_USE_WINTHREADS) # define WIN32_LEAN_AND_MEAN /* Only include streamlined windows header. */ # if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0403) /* To support CRITICAL_SECTION */ # error Windows version not supported. # endif # include <windows.h> #else # error Unsupported platform. #endif #if defined(__cplusplus) extern "C" { #endif /** * Simple non-recursive mutex to synchronization inside the owning process. * No inter-process syncing supported. * * Treat definition and size as opaque as these can change without a * warning in future versions of amp. * * @attention Don't copy or move an amp_raw_mutex instance or behavior is * undefined - use pointers to an amp_raw_mutex instead. */ struct amp_raw_mutex_s { #if defined(AMP_USE_PTHREADS) /* Don't copy or move - therefore don't copy or move amp_mutex_s. */ pthread_mutex_t mutex; #elif defined(AMP_USE_WINTHREADS) /* Don't copy or move - therefore don't copy or move amp_mutex_s. */ CRITICAL_SECTION critical_section; /* Helper to prevent recursive locking on Windows. This is always * included instead of only in debug mode because the interface and the * way the source is compiled can differ which might lead to hard to * track down errors. */ BOOL is_locked; #else # error Unsupported platform. #endif }; /** * Like amp_mutex_create but does not allocate memory for the amp mutex * other than indirectly via the platform API to create a platform mutex. */ int amp_raw_mutex_init(amp_mutex_t mutex); /** * Like amp_mutex_destroy but does not free memory for the amp mutex * other than indirectly via the platform API to destroy a platform mutex. */ int amp_raw_mutex_finalize(amp_mutex_t mutex); #if defined(__cplusplus) } /* extern "C" */ #endif #endif /* AMP_amp_raw_mutex_H */
/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* ryu sensor hub configuration */ #include "common.h" #include "console.h" #include "driver/accelgyro_lsm6ds0.h" #include "gpio.h" #include "hooks.h" #include "i2c.h" #include "motion_sense.h" #include "power.h" #include "registers.h" #include "task.h" #include "util.h" #include "gpio_list.h" /* Initialize board. */ static void board_init(void) { } DECLARE_HOOK(HOOK_INIT, board_init, HOOK_PRIO_DEFAULT); /* power signal list. Must match order of enum power_signal. */ const struct power_signal_info power_signal_list[] = { {GPIO_AP_IN_SUSPEND, 1, "SUSPEND_ASSERTED"}, }; BUILD_ASSERT(ARRAY_SIZE(power_signal_list) == POWER_SIGNAL_COUNT); /* I2C ports */ const struct i2c_port_t i2c_ports[] = { {"master", I2C_PORT_MASTER, 100, GPIO_MASTER_I2C_SCL, GPIO_MASTER_I2C_SDA}, {"slave", I2C_PORT_SLAVE, 100, GPIO_SLAVE_I2C_SCL, GPIO_SLAVE_I2C_SDA}, }; const unsigned int i2c_ports_used = ARRAY_SIZE(i2c_ports); /* Sensor mutex */ static struct mutex g_mutex; struct motion_sensor_t motion_sensors[] = { /* * Note: lsm6ds0: supports accelerometer and gyro sensor * Requriement: accelerometer sensor must init before gyro sensor * DO NOT change the order of the following table. */ {SENSOR_ACTIVE_S0_S3, "Accel", MOTIONSENSE_CHIP_LSM6DS0, MOTIONSENSE_TYPE_ACCEL, MOTIONSENSE_LOC_LID, &lsm6ds0_drv, &g_mutex, NULL, LSM6DS0_ADDR1, NULL, 119000, 2}, {SENSOR_ACTIVE_S0_S3, "Gyro", MOTIONSENSE_CHIP_LSM6DS0, MOTIONSENSE_TYPE_GYRO, MOTIONSENSE_LOC_LID, &lsm6ds0_drv, &g_mutex, NULL, LSM6DS0_ADDR1, NULL, 119000, 2000}, }; const unsigned int motion_sensor_count = ARRAY_SIZE(motion_sensors); void board_config_pre_init(void) { /* * enable SYSCFG clock: * otherwise the SYSCFG peripheral is not clocked during the pre-init * and the register write as no effect. */ STM32_RCC_APB2ENR |= 1 << 0; /* * Remap USART DMA to match the USART driver * the DMA mapping is : * Chan 4 : USART1_TX * Chan 5 : USART1_RX */ STM32_SYSCFG_CFGR1 |= (1 << 9) | (1 << 10);/* Remap USART1 RX/TX DMA */ }
#ifndef __TRIM__ #define __TRIM__ char * trim(char *str); #endif /*__TRIM__*/
// Copyright 2014 The Chromium Authors. All rights reserved. // Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_RUNTIME_BROWSER_TIZEN_RENDER_VIEW_CONTEXT_MENU_IMPL_H_ #define XWALK_RUNTIME_BROWSER_TIZEN_RENDER_VIEW_CONTEXT_MENU_IMPL_H_ #include "components/renderer_context_menu/render_view_context_menu_base.h" #include "content/public/browser/render_widget_host_view.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" namespace aura { class Window; } namespace views { class Widget; } namespace gfx { class Point; } namespace xwalk { class RenderViewContextMenuImpl : public RenderViewContextMenuBase { public: RenderViewContextMenuImpl(content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params); virtual ~RenderViewContextMenuImpl(); void RunMenuAt(views::Widget* parent, const gfx::Point& point, ui::MenuSourceType type); void Show() override; private: // RenderViewContextMenuBase: void InitMenu() override; void RecordShownItem(int id) override; void RecordUsedItem(int id) override; void NotifyMenuShown() override; void NotifyURLOpened(const GURL& url, content::WebContents* new_contents) override; void HandleAuthorizeAllPlugins() override; // ui::SimpleMenuModel: bool GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) override; bool IsCommandIdChecked(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; void ExecuteCommand(int command_id, int event_flags) override; aura::Window* GetActiveNativeView(); views::Widget* GetTopLevelWidget(); DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuImpl); }; } // namespace xwalk #endif // XWALK_RUNTIME_BROWSER_TIZEN_RENDER_VIEW_CONTEXT_MENU_IMPL_H_
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_environment_18.c Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml Template File: source-sinks-18.tmpl.c */ /* * @description * CWE: 761 Free Pointer not at Start of Buffer * BadSource: environment Read input from an environment variable * Sinks: * GoodSink: free() memory correctly at the start of the buffer * BadSink : free() memory not at the start of the buffer * Flow Variant: 18 Control flow: goto statements * * */ #include "std_testcase.h" #include <wchar.h> #define ENV_VARIABLE L"ADD" #ifdef _WIN32 #define GETENV _wgetenv #else #define GETENV getenv #endif #define SEARCH_CHAR L'S' #ifndef OMITBAD void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_environment_18_bad() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; { /* Append input from an environment variable to data */ size_t dataLen = wcslen(data); wchar_t * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ wcsncat(data+dataLen, environment, 100-dataLen-1); } } goto sink; sink: /* FLAW: We are incrementing the pointer in the loop - this will cause us to free the * memory block not at the start of the buffer */ for (; *data != L'\0'; data++) { if (*data == SEARCH_CHAR) { printLine("We have a match!"); break; } } free(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G() - use badsource and goodsink by reversing the blocks on the goto statement */ static void goodB2G() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; { /* Append input from an environment variable to data */ size_t dataLen = wcslen(data); wchar_t * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ wcsncat(data+dataLen, environment, 100-dataLen-1); } } goto sink; sink: { size_t i; /* FIX: Use a loop variable to traverse through the string pointed to by data */ for (i=0; i < wcslen(data); i++) { if (data[i] == SEARCH_CHAR) { printLine("We have a match!"); break; } } free(data); } } void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_environment_18_good() { goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_environment_18_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_environment_18_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
// Copyright 2015 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd // +build !darwin #include <avahi-client/publish.h> #include <avahi-common/error.h> #include <avahi-common/strlst.h> #include <avahi-common/thread-watch.h> #include <stdlib.h> // free const char *startAvahiClient(AvahiThreadedPoll **threaded_poll, AvahiClient **client); const char *addAvahiGroup(AvahiThreadedPoll *threaded_poll, AvahiClient *client, AvahiEntryGroup **group, const char *serviceName, unsigned short port, AvahiStringList *txt); const char *updateAvahiGroup(AvahiThreadedPoll *threaded_poll, AvahiEntryGroup *group, const char *serviceName, AvahiStringList *txt); const char *removeAvahiGroup(AvahiThreadedPoll *threaded_poll, AvahiEntryGroup *group); void stopAvahiClient(AvahiThreadedPoll *threaded_poll, AvahiClient *client);
// Copyright 2015 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 BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_H_ #define BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_H_ #include <functional> #include "base/base_export.h" #include "starboard/types.h" namespace base { namespace trace_event { // When heap profiling is enabled, tracing keeps track of the allocation // context for each allocation intercepted. It is generated by the // |AllocationContextTracker| which keeps stacks of context in TLS. // The tracker is initialized lazily. // The backtrace in the allocation context is a snapshot of the stack. For now, // this is the pseudo stack where frames are created by trace event macros. In // the future, we might add the option to use the native call stack. In that // case, |Backtrace| and |AllocationContextTracker::GetContextSnapshot| might // have different implementations that can be selected by a compile time flag. // The number of stack frames stored in the backtrace is a trade off between // memory used for tracing and accuracy. Measurements done on a prototype // revealed that: // // - In 60 percent of the cases, pseudo stack depth <= 7. // - In 87 percent of the cases, pseudo stack depth <= 9. // - In 95 percent of the cases, pseudo stack depth <= 11. // // See the design doc (https://goo.gl/4s7v7b) for more details. // Represents (pseudo) stack frame. Used in Backtrace class below. // // Conceptually stack frame is identified by its value, and type is used // mostly to properly format the value. Value is expected to be a valid // pointer from process' address space. struct BASE_EXPORT StackFrame { enum class Type { TRACE_EVENT_NAME, // const char* string THREAD_NAME, // const char* thread name PROGRAM_COUNTER, // as returned by stack tracing (e.g. by StackTrace) }; static StackFrame FromTraceEventName(const char* name) { return {Type::TRACE_EVENT_NAME, name}; } static StackFrame FromThreadName(const char* name) { return {Type::THREAD_NAME, name}; } static StackFrame FromProgramCounter(const void* pc) { return {Type::PROGRAM_COUNTER, pc}; } Type type; const void* value; }; bool BASE_EXPORT operator < (const StackFrame& lhs, const StackFrame& rhs); bool BASE_EXPORT operator == (const StackFrame& lhs, const StackFrame& rhs); bool BASE_EXPORT operator != (const StackFrame& lhs, const StackFrame& rhs); struct BASE_EXPORT Backtrace { Backtrace(); // If the stack is higher than what can be stored here, the top frames // (the ones further from main()) are stored. Depth of 12 is enough for most // pseudo traces (see above), but not for native traces, where we need more. enum { kMaxFrameCount = 48 }; StackFrame frames[kMaxFrameCount]; size_t frame_count = 0; }; bool BASE_EXPORT operator==(const Backtrace& lhs, const Backtrace& rhs); bool BASE_EXPORT operator!=(const Backtrace& lhs, const Backtrace& rhs); // The |AllocationContext| is context metadata that is kept for every allocation // when heap profiling is enabled. To simplify memory management for book- // keeping, this struct has a fixed size. struct BASE_EXPORT AllocationContext { AllocationContext(); AllocationContext(const Backtrace& backtrace, const char* type_name); Backtrace backtrace; // Type name of the type stored in the allocated memory. A null pointer // indicates "unknown type". Grouping is done by comparing pointers, not by // deep string comparison. In a component build, where a type name can have a // string literal in several dynamic libraries, this may distort grouping. const char* type_name; }; bool BASE_EXPORT operator==(const AllocationContext& lhs, const AllocationContext& rhs); bool BASE_EXPORT operator!=(const AllocationContext& lhs, const AllocationContext& rhs); // Struct to store the size and count of the allocations. struct AllocationMetrics { size_t size; size_t count; }; } // namespace trace_event } // namespace base namespace std { template <> struct BASE_EXPORT hash<base::trace_event::StackFrame> { size_t operator()(const base::trace_event::StackFrame& frame) const; }; template <> struct BASE_EXPORT hash<base::trace_event::Backtrace> { size_t operator()(const base::trace_event::Backtrace& backtrace) const; }; template <> struct BASE_EXPORT hash<base::trace_event::AllocationContext> { size_t operator()(const base::trace_event::AllocationContext& context) const; }; } // namespace std #endif // BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_H_
// Copyright (c) 2012, HTW Berlin / Project HardMut // (http://www.hardmut-projekt.de) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the HTW Berlin / INKA Research Group nor the names // of its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Singleton.h // orbitio // // Created by Markus Konrad on 09.04.11. // Copyright 2011 INKA Forschungsgruppe. All rights reserved. // #import <Foundation/Foundation.h> // Declares a standard singleton interface @protocol Singleton <NSObject> // "shared" method. Each singleton gives access to its object with this method. + (id)shared; @end
/* * Copyright 2012 The LibYuv Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef INCLUDE_LIBYUV_VERSION_H_ // NOLINT #define INCLUDE_LIBYUV_VERSION_H_ #define LIBYUV_VERSION 1416 #endif // INCLUDE_LIBYUV_VERSION_H_ NOLINT
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include "fboss/agent/hw/bcm/BcmPlatformPort.h" #include "fboss/agent/gen-cpp/switch_config_types.h" namespace facebook { namespace fboss { class WedgePort : public BcmPlatformPort { protected: explicit WedgePort(PortID id); public: PortID getPortID() const override { return id_; } void setBcmPort(BcmPort* port) override; BcmPort* getBcmPort() const override { return bcmPort_; } cfg::PortSpeed maxLaneSpeed() const override { return cfg::PortSpeed::XG; } void preDisable(bool temporary) override; void postDisable(bool temporary) override; void preEnable() override; void postEnable() override; bool isMediaPresent() override; void statusIndication(bool enabled, bool link, bool ingress, bool egress, bool discards, bool errors) override; void linkStatusChanged(bool up, bool adminUp) override; private: // Forbidden copy constructor and assignment operator WedgePort(WedgePort const &) = delete; WedgePort& operator=(WedgePort const &) = delete; protected: PortID id_{0}; BcmPort* bcmPort_{nullptr}; }; }} // facebook::fboss
int foo1(void) { return 1; } extern int foo2(void); int foo3(void) { return 3; } extern int foo4(void); int foo5(void) { return 5; } extern int foo6(void); int main(int argc, char* argv[]) { switch(argc) { case 1: return foo1(); case 2: return foo2(); case 3: return foo3(); case 4: return foo4(); case 5: return foo5(); case 6: return foo6(); default: return -1; } }
// 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. #ifndef CHROME_BROWSER_MANAGED_MODE_CHROMEOS_MANAGER_PASSWORD_SERVICE_FACTORY_H_ #define CHROME_BROWSER_MANAGED_MODE_CHROMEOS_MANAGER_PASSWORD_SERVICE_FACTORY_H_ #include "base/memory/singleton.h" #include "chrome/browser/managed_mode/managed_users.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" class ManagerPasswordService; class Profile; class ManagerPasswordServiceFactory : public BrowserContextKeyedServiceFactory { public: static ManagerPasswordService* GetForProfile(Profile* profile); static ManagerPasswordServiceFactory* GetInstance(); private: friend struct DefaultSingletonTraits<ManagerPasswordServiceFactory>; ManagerPasswordServiceFactory(); virtual ~ManagerPasswordServiceFactory(); // BrowserContextKeyedServiceFactory: virtual KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const OVERRIDE; virtual content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const OVERRIDE; }; #endif // CHROME_BROWSER_MANAGED_MODE_CHROMEOS_MANAGER_PASSWORD_SERVICE_FACTORY_H_
/* $OpenBSD: disktab.h,v 1.2 1997/09/21 10:45:31 niklas Exp $ */ /* $NetBSD: disktab.h,v 1.3 1994/10/26 00:55:51 cgd Exp $ */ /* * Copyright (c) 1983 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)disktab.h 5.6 (Berkeley) 4/20/91 */ #ifndef _DISKTAB_H_ #define _DISKTAB_H_ /* * Disk description table, see disktab(5) */ #define DISKTAB "/etc/disktab" struct disktab { char *d_name; /* drive name */ char *d_type; /* drive type */ int d_secsize; /* sector size in bytes */ int d_ntracks; /* # tracks/cylinder */ int d_nsectors; /* # sectors/track */ int d_ncylinders; /* # cylinders */ int d_rpm; /* revolutions/minute */ int d_badsectforw; /* supports DEC bad144 std */ int d_sectoffset; /* use sect rather than cyl offsets */ struct partition { int p_size; /* #sectors in partition */ short p_bsize; /* block size in bytes */ short p_fsize; /* frag size in bytes */ } d_partitions[8]; }; #endif /* !_DISKTAB_H_ */
#pragma once #ifndef TCG_PTR_WRAPPER #define TCG_PTR_WRAPPER // STD includes #include <iterator> namespace tcg { /*! \brief The ptr_wrapper class implements the basic functions necessary to wrap a generic pointer object. The use case for this class is to allow pointer inheritance. */ template <typename T> class ptr { public: typedef T *ptr_type; typedef typename std::iterator_traits<ptr_type>::iterator_category iterator_category; typedef typename std::iterator_traits<ptr_type>::value_type value_type; typedef typename std::iterator_traits<ptr_type>::difference_type difference_type; typedef typename std::iterator_traits<ptr_type>::pointer pointer; typedef typename std::iterator_traits<ptr_type>::reference reference; public: explicit ptr(ptr_type p = ptr_type()) : m_ptr(p) {} operator bool() const { return m_ptr; } // There should be no need to use // the Safe Bool idiom bool operator==(const ptr &other) const { return (m_ptr == other.m_ptr); } bool operator!=(const ptr &other) const { return (m_ptr != other.m_ptr); } bool operator<(const ptr &other) const { return (m_ptr < other.m_ptr); } bool operator>(const ptr &other) const { return (m_ptr > other.m_ptr); } bool operator<=(const ptr &other) const { return (m_ptr <= other.m_ptr); } bool operator>=(const ptr &other) const { return (m_ptr >= other.m_ptr); } ptr &operator++() { ++m_ptr; return *this; } ptr operator++(int) { return ptr(m_ptr++, *this); } ptr &operator--() { --m_ptr; return *this; } ptr operator--(int) { return ptr(m_ptr--, *this); } ptr operator+(difference_type d) const { return ptr(m_ptr + d, *this); } ptr &operator+=(difference_type d) { m_ptr += d; return *this; } ptr operator-(difference_type d) const { return ptr(m_ptr - d, *this); } ptr &operator-=(difference_type d) { m_ptr -= d; return *this; } difference_type operator-(const ptr &other) const { return m_ptr - other.m_ptr; } pointer operator->() const { return m_ptr; } reference operator*() const { return *m_ptr; } reference operator[](difference_type d) const { return m_ptr[d]; } protected: ptr_type m_ptr; }; //======================================================= template <typename T> ptr<T> make_ptr(T *p) { return ptr<T>(p); } } // namespace tcg #endif // TCG_PTR_WRAPPER
/* * Copyright (c) 2016, SRCH2 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the SRCH2 nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SRCH2 BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * SharedToken.h * * Created on: 2013-5-17 */ #ifndef __CORE_ANALYZER_TOKENSTREAMCONTAINER_H__ #define __CORE_ANALYZER_TOKENSTREAMCONTAINER_H__ #include <vector> #include "util/encoding.h" #include "CharSet.h" #include <instantsearch/Analyzer.h> namespace srch2 { namespace instantsearch { class TokenStreamContainer { public: TokenStreamContainer():offset(0), currentTokenPosition(0), currentTokenOffset(0), type(ANALYZED_ORIGINAL_TOKEN){} void fillInCharacters(const std::vector<CharType> &charVector, bool isPrefix=false){ currentToken.clear(); completeCharVector = charVector; currentTokenOffset = 0; currentTokenPosition = 0; offset = 0; type = ANALYZED_ORIGINAL_TOKEN; this->isPrefix = isPrefix; } /* * For example: process "We went to school" * completeCharVector = "We went to school" * When we process to the first character 'W', currentToken="W", * offset=0, Token position = 1, currentTokenOffset = 1 * When we move to the second character 'e', currentToken="We", * offset=1, Token position = 1, currentTokenOffset = 1 * ... * When we move to 'n' at 6th place, currentToken= 'wen' * offset=5, Token position = 2, currentTokenOffset = 4 */ std::vector<CharType> currentToken; //current token std::vector<CharType> completeCharVector; //complete char vector of a string int offset; //the offset of current position to process unsigned currentTokenPosition; unsigned currentTokenOffset; // offset of current token from the beginning of the buffer. AnalyzedTokenType type; unsigned currentTokenLen; bool isPrefix; }; }} #endif /* __CORE_ANALYZER__TOKENSTREAMCONTAINER_H__ */
// 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 IOS_CHROME_BROWSER_DOWNLOAD_DOWNLOAD_MANAGER_TAB_HELPER_H_ #define IOS_CHROME_BROWSER_DOWNLOAD_DOWNLOAD_MANAGER_TAB_HELPER_H_ #include <memory> #import <Foundation/Foundation.h> #include "base/macros.h" #include "ios/web/public/download/download_task_observer.h" #include "ios/web/public/web_state_observer.h" #import "ios/web/public/web_state_user_data.h" @protocol DownloadManagerTabHelperDelegate; namespace web { class DownloadTask; class WebState; } // namespace web // TabHelper which manages a single file download. class DownloadManagerTabHelper : public web::WebStateUserData<DownloadManagerTabHelper>, public web::WebStateObserver, public web::DownloadTaskObserver { public: ~DownloadManagerTabHelper() override; // Creates TabHelper. |delegate| is not retained by TabHelper. |web_state| // must not be null. static void CreateForWebState(web::WebState* web_state, id<DownloadManagerTabHelperDelegate> delegate); // Asynchronously downloads a file using the given |task|. virtual void Download(std::unique_ptr<web::DownloadTask> task); // Returns |true| after Download() was called, |false| after the task was // cancelled. bool has_download_task() const { return task_.get(); } protected: // Allow subclassing from DownloadManagerTabHelper for testing purposes. DownloadManagerTabHelper(web::WebState* web_state, id<DownloadManagerTabHelperDelegate> delegate); private: friend class web::WebStateUserData<DownloadManagerTabHelper>; // web::WebStateObserver overrides: void WasShown(web::WebState* web_state) override; void WasHidden(web::WebState* web_state) override; void WebStateDestroyed(web::WebState* web_state) override; // web::DownloadTaskObserver overrides: void OnDownloadUpdated(web::DownloadTask* task) override; // Returns key for using with NetworkActivityIndicatorManager. NSString* GetNetworkActivityKey() const; // Assigns |task| to |task_|; replaces the current download if exists; // instructs the delegate that download has started. void DidCreateDownload(std::unique_ptr<web::DownloadTask> task); web::WebState* web_state_ = nullptr; __weak id<DownloadManagerTabHelperDelegate> delegate_ = nil; std::unique_ptr<web::DownloadTask> task_; WEB_STATE_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(DownloadManagerTabHelper); }; #endif // IOS_CHROME_BROWSER_DOWNLOAD_DOWNLOAD_MANAGER_TAB_HELPER_H_
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" extern NSString* const FlutterEngineWillDealloc; @class FlutterBinaryMessengerRelay; namespace flutter { class ThreadHost; } // Category to add test-only visibility. @interface FlutterEngine (Test) <FlutterBinaryMessenger> - (void)setBinaryMessenger:(FlutterBinaryMessengerRelay*)binaryMessenger; - (flutter::IOSRenderingAPI)platformViewsRenderingAPI; - (void)waitForFirstFrame:(NSTimeInterval)timeout callback:(void (^)(BOOL didTimeout))callback; - (FlutterEngine*)spawnWithEntrypoint:(/*nullable*/ NSString*)entrypoint libraryURI:(/*nullable*/ NSString*)libraryURI initialRoute:(/*nullable*/ NSString*)initialRoute entrypointArgs:(/*nullable*/ NSArray<NSString*>*)entrypointArgs; - (const flutter::ThreadHost&)threadHost; @end
/* * Copyright (c) 2011 Gerard Green * All rights reserved * * Please see the file 'LICENSE' for further information */ #include <stdlib.h> /* This variable is in rand.c */ extern unsigned int _RandSeed; void srand(unsigned seed) { _RandSeed = seed; }
/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// #ifndef _BSPSYSARRAYEMITTER_H_ #define _BSPSYSARRAYEMITTER_H_ //--BEGIN FILE HEAD CUSTOM CODE--// //--END CUSTOM CODE--// #include "NiPSysVolumeEmitter.h" namespace Niflib { class BSPSysArrayEmitter; typedef Ref<BSPSysArrayEmitter> BSPSysArrayEmitterRef; /*! * Particle emitter that uses a node, its children and subchildren to emit from. * Emission will be evenly spread along points from nodes leading to their direct * parents/children only. */ class BSPSysArrayEmitter : public NiPSysVolumeEmitter { public: /*! Constructor */ NIFLIB_API BSPSysArrayEmitter(); /*! Destructor */ NIFLIB_API virtual ~BSPSysArrayEmitter(); /*! * A constant value which uniquly identifies objects of this type. */ NIFLIB_API static const Type TYPE; /*! * A factory function used during file reading to create an instance of this type of object. * \return A pointer to a newly allocated instance of this type of object. */ NIFLIB_API static NiObject * Create(); /*! * Summarizes the information contained in this object in English. * \param[in] verbose Determines whether or not detailed information about large areas of data will be printed out. * \return A string containing a summary of the information within the object in English. This is the function that Niflyze calls to generate its analysis, so the output is the same. */ NIFLIB_API virtual string asString(bool verbose = false) const; /*! * Used to determine the type of a particular instance of this object. * \return The type constant for the actual type of the object. */ NIFLIB_API virtual const Type & GetType() const; //--This object has no eligable attributes. No example implementation generated--// //--BEGIN MISC CUSTOM CODE--// //--END CUSTOM CODE--// public: /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual void Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info); /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual void Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const; /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual void FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info); /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual list<NiObjectRef> GetRefs() const; /*! NIFLIB_HIDDEN function. For internal use only. */ NIFLIB_HIDDEN virtual list<NiObject *> GetPtrs() const; }; //--BEGIN FILE FOOT CUSTOM CODE--// //--END CUSTOM CODE--// } //End Niflib namespace #endif
/* $NetBSD: asm.h,v 1.8 1999/03/05 10:55:55 pk Exp $ */ /* * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This software was developed by the Computer Systems Engineering group * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and * contributed to Berkeley. * * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Lawrence Berkeley Laboratory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)asm.h 8.1 (Berkeley) 6/11/93 */ /* * GCC __asm constructs for doing assembly stuff. */ /* * ``Routines'' to load and store from/to alternate address space. * The location can be a variable, the asi value (address space indicator) * must be a constant. * * N.B.: You can put as many special functions here as you like, since * they cost no kernel space or time if they are not used. * * These were static inline functions, but gcc screws up the constraints * on the address space identifiers (the "n"umeric value part) because * it inlines too late, so we have to use the funny valued-macro syntax. */ /* load byte from alternate address space */ #define lduba(loc, asi) ({ \ register int _lduba_v; \ __asm __volatile("lduba [%1]%2,%0" : "=r" (_lduba_v) : \ "r" ((int)(loc)), "n" (asi)); \ _lduba_v; \ }) /* load half-word from alternate address space */ #define lduha(loc, asi) ({ \ register int _lduha_v; \ __asm __volatile("lduha [%1]%2,%0" : "=r" (_lduha_v) : \ "r" ((int)(loc)), "n" (asi)); \ _lduha_v; \ }) /* load int from alternate address space */ #define lda(loc, asi) ({ \ register int _lda_v; \ __asm __volatile("lda [%1]%2,%0" : "=r" (_lda_v) : \ "r" ((int)(loc)), "n" (asi)); \ _lda_v; \ }) /* store byte to alternate address space */ #define stba(loc, asi, value) ({ \ __asm __volatile("stba %0,[%1]%2" : : \ "r" ((int)(value)), "r" ((int)(loc)), "n" (asi)); \ }) /* store half-word to alternate address space */ #define stha(loc, asi, value) ({ \ __asm __volatile("stha %0,[%1]%2" : : \ "r" ((int)(value)), "r" ((int)(loc)), "n" (asi)); \ }) /* store int to alternate address space */ #define sta(loc, asi, value) ({ \ __asm __volatile("sta %0,[%1]%2" : : \ "r" ((int)(value)), "r" ((int)(loc)), "n" (asi)); \ }) /* load 64-bit int from alternate address space */ #define ldda(loc, asi) ({ \ register long long _lda_v; \ __asm __volatile("ldda [%1]%2,%0" : "=r" (_lda_v) : \ "r" ((int)(loc)), "n" (asi)); \ _lda_v; \ }) /* store 64-bit int to alternate address space */ #define stda(loc, asi, value) ({ \ __asm __volatile("stda %0,[%1]%2" : : \ "r" ((long long)(value)), "r" ((int)(loc)), "n" (asi)); \ }) /* atomic swap of a word between a register and memory */ #define swap(loc, val) ({ \ __asm __volatile("swap [%2],%0" : "=&r" (val) : "0" (val), "r" (loc)); \ }) /* atomic load/store of a byte in memory */ #define ldstub(loc) ({ \ int _v; \ __asm __volatile("ldstub [%1],%0" : "=r" (_v) : "r" (loc) : "memory"); \ _v; \ }) /* read ancillary state register */ #define rdasr(asr) _rdasr(asr) #define _rdasr(asr) ({ \ register int _rdasr_v; \ __asm __volatile("rd %%asr" #asr ",%0" : "=r" (_rdasr_v)); \ _rdasr_v; \ }) /* write ancillary state register */ #define wrasr(value, asr) _wrasr(value, asr) #define _wrasr(value, asr) ({ \ __asm __volatile("wr %0,%%asr" #asr : : "r" ((int)(value))); \ })
// // SDLTouchManagerDelegate.h // SmartDeviceLink-iOS // // Created by Muller, Alexander (A.) on 6/14/16. // Copyright © 2016 smartdevicelink. All rights reserved. // @import UIKit; @class SDLTouchManager; NS_ASSUME_NONNULL_BEGIN @protocol SDLTouchManagerDelegate <NSObject> @optional /** * @abstract * Single tap was received. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Location of the single tap in the head unit's coordinate system. */ - (void)touchManager:(SDLTouchManager *)manager didReceiveSingleTapAtPoint:(CGPoint)point; /** * @abstract * Double tap was received. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Location of the double tap in the head unit's coordinate system. This is the * average of the first and second tap. */ - (void)touchManager:(SDLTouchManager *)manager didReceiveDoubleTapAtPoint:(CGPoint)point; /** * @abstract * Panning did start. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Location of the panning start point in the head unit's coordinate system. */ - (void)touchManager:(SDLTouchManager *)manager panningDidStartAtPoint:(CGPoint)point; /** * @abstract * Panning did move. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param fromPoint * Location of the panning's previous point in the head unit's coordinate system. * @param toPoint * Location of the panning's new point in the head unit's coordinate system. */ - (void)touchManager:(SDLTouchManager *)manager didReceivePanningFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint; /** * @abstract * Panning did end. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Location of the panning's end point in the head unit's coordinate system. */ - (void)touchManager:(SDLTouchManager *)manager panningDidEndAtPoint:(CGPoint)point; /** * @abstract * Pinch did start. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Center point of the pinch in the head unit's coordinate system. */ - (void)touchManager:(SDLTouchManager *)manager pinchDidStartAtCenterPoint:(CGPoint)point; /** * @abstract * Pinch did move. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Center point of the pinch in the head unit's coordinate system. * @param scale * Scale relative to the distance between touch points. */ - (void)touchManager:(SDLTouchManager *)manager didReceivePinchAtCenterPoint:(CGPoint)point withScale:(CGFloat)scale; /** * @abstract * Pinch did end. * @param manager * Current initalized SDLTouchManager issuing the callback. * @param point * Center point of the pinch in the head unit's coordinate system. */ - (void)touchManager:(SDLTouchManager *)manager pinchDidEndAtCenterPoint:(CGPoint)point; @end NS_ASSUME_NONNULL_END
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_connect_socket_system_12.c Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml Template File: sources-sink-12.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Fixed string * Sink: system * BadSink : Execute command in data using system() * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse()) * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define FULL_COMMAND L"dir " #else #include <unistd.h> #define FULL_COMMAND L"ls " #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #ifdef _WIN32 #define SYSTEM _wsystem #else /* NOT _WIN32 */ #define SYSTEM system #endif #ifndef OMITBAD void CWE78_OS_Command_Injection__wchar_t_connect_socket_system_12_bad() { wchar_t * data; wchar_t data_buf[100] = FULL_COMMAND; data = data_buf; if(globalReturnsTrueOrFalse()) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } else { /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); } /* POTENTIAL FLAW: Execute command in data possibly leading to command injection */ if (SYSTEM(data) != 0) { printLine("command execution failed!"); exit(1); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ static void goodG2B() { wchar_t * data; wchar_t data_buf[100] = FULL_COMMAND; data = data_buf; if(globalReturnsTrueOrFalse()) { /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); } else { /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); } /* POTENTIAL FLAW: Execute command in data possibly leading to command injection */ if (SYSTEM(data) != 0) { printLine("command execution failed!"); exit(1); } } void CWE78_OS_Command_Injection__wchar_t_connect_socket_system_12_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__wchar_t_connect_socket_system_12_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__wchar_t_connect_socket_system_12_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#ifndef LOG_H_ #define LOG_H_ #include <fstream> namespace tinyco { enum LOGLEVEL { LL_DEBUG = 0, LL_INFO, LL_WARNING, LL_ERROR, }; class Log { public: virtual int Initialize(const void *arg) = 0; virtual void SetLogLevel(int level) { loglevel_ = level; } virtual void Debug(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...) = 0; virtual void Info(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...) = 0; virtual void Warning(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...) = 0; virtual void Error(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...) = 0; protected: virtual void CommonLog(uint64_t uin, uint32_t line, const char *func, const char *fmt, va_list *args); virtual uint32_t AppendLogItemHeader(uint64_t uin, uint32_t line, const char *func); virtual void WriteLog() {} protected: int loglevel_; std::string content_; const static uint32_t kLogItemSize = 2048; }; class LocalLog : public Log { public: static Log *Instance(); virtual int Initialize(const void *arg); virtual void Debug(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...); virtual void Info(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...); virtual void Warning(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...); virtual void Error(uint64_t uin, uint32_t line, const char *func, const char *fmt, ...); private: virtual void WriteLog(); private: std::string filepath_; std::string current_file_; std::ofstream file_; }; #if 0 #define LOG(fmt, arg...) \ printf("[%s][%s][%u]: " fmt "\n", __FILE__, __FUNCTION__, __LINE__, ##arg) #define LOG_ERROR(fmt, arg...) \ printf("[%s][%s][%u]: " fmt "\n", __FILE__, __FUNCTION__, __LINE__, ##arg) #define LOG_WARNING(fmt, arg...) \ printf("[%s][%s][%u]: " fmt "\n", __FILE__, __FUNCTION__, __LINE__, ##arg) #define LOG_NOTICE(fmt, arg...) \ printf("[%s][%s][%u]: " fmt "\n", __FILE__, __FUNCTION__, __LINE__, ##arg) #define LOG_INFO(fmt, arg...) \ printf("[%s][%s][%u]: " fmt "\n", __FILE__, __FUNCTION__, __LINE__, ##arg) #define LOG_DEBUG(fmt, arg...) \ printf("[%s][%s][%u]: " fmt "\n", __FILE__, __FUNCTION__, __LINE__, ##arg) #endif #if 1 #define LOG(fmt, arg...) \ LocalLog::Instance()->Debug(LL_DEBUG, __LINE__, __FUNCTION__, fmt, ##arg) #define LOG_ERROR(fmt, arg...) \ LocalLog::Instance()->Error(LL_ERROR, __LINE__, __FUNCTION__, fmt, ##arg) #define LOG_WARNING(fmt, arg...) \ LocalLog::Instance()->Warning(LL_WARNING, __LINE__, __FUNCTION__, fmt, ##arg) #define LOG_INFO(fmt, arg...) \ LocalLog::Instance()->Info(LL_INFO, __LINE__, __FUNCTION__, fmt, ##arg) #define LOG_DEBUG(fmt, arg...) \ LocalLog::Instance()->Debug(LL_DEBUG, __LINE__, __FUNCTION__, fmt, ##arg) #endif } #endif
/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef VP9_ENCODER_VP9_TREEWRITER_H_ #define VP9_ENCODER_VP9_TREEWRITER_H_ /* Trees map alphabets into huffman-like codes suitable for an arithmetic bit coder. Timothy S Murphy 11 October 2004 */ #include "vp9/common/vp9_treecoder.h" #include "vp9/encoder/vp9_boolhuff.h" /* for now */ typedef BOOL_CODER vp9_writer; #define vp9_write encode_bool #define vp9_write_literal vp9_encode_value #define vp9_write_bit(W, V) vp9_write(W, V, vp9_prob_half) /* Approximate length of an encoded bool in 256ths of a bit at given prob */ #define vp9_cost_zero(x) (vp9_prob_cost[x]) #define vp9_cost_one(x) vp9_cost_zero(vp9_complement(x)) #define vp9_cost_bit(x, b) vp9_cost_zero((b) ? vp9_complement(x) : (x)) /* VP8BC version is scaled by 2^20 rather than 2^8; see bool_coder.h */ /* Both of these return bits, not scaled bits. */ static __inline unsigned int cost_branch(const unsigned int ct[2], vp9_prob p) { /* Imitate existing calculation */ return ((ct[0] * vp9_cost_zero(p)) + (ct[1] * vp9_cost_one(p))) >> 8; } static __inline unsigned int cost_branch256(const unsigned int ct[2], vp9_prob p) { /* Imitate existing calculation */ return ((ct[0] * vp9_cost_zero(p)) + (ct[1] * vp9_cost_one(p))); } /* Small functions to write explicit values and tokens, as well as estimate their lengths. */ static __inline void treed_write(vp9_writer *const w, vp9_tree t, const vp9_prob *const p, int v, /* number of bits in v, assumed nonzero */ int n) { vp9_tree_index i = 0; do { const int b = (v >> --n) & 1; vp9_write(w, b, p[i >> 1]); i = t[i + b]; } while (n); } static __inline void write_token(vp9_writer *const w, vp9_tree t, const vp9_prob *const p, vp9_token *const x) { treed_write(w, t, p, x->value, x->Len); } static __inline int treed_cost(vp9_tree t, const vp9_prob *const p, int v, /* number of bits in v, assumed nonzero */ int n) { int c = 0; vp9_tree_index i = 0; do { const int b = (v >> --n) & 1; c += vp9_cost_bit(p[i >> 1], b); i = t[i + b]; } while (n); return c; } static __inline int cost_token(vp9_tree t, const vp9_prob *const p, vp9_token *const x) { return treed_cost(t, p, x->value, x->Len); } /* Fill array of costs for all possible token values. */ void vp9_cost_tokens(int *Costs, const vp9_prob *, vp9_tree); void vp9_cost_tokens_skip(int *c, const vp9_prob *p, vp9_tree t); #endif // VP9_ENCODER_VP9_TREEWRITER_H_
// 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 COMPONENTS_NTP_TILES_CUSTOM_LINKS_MANAGER_IMPL_H_ #define COMPONENTS_NTP_TILES_CUSTOM_LINKS_MANAGER_IMPL_H_ #include <utility> #include <vector> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/scoped_observer.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_service_observer.h" #include "components/ntp_tiles/custom_links_manager.h" #include "components/ntp_tiles/custom_links_store.h" #include "components/ntp_tiles/ntp_tile.h" #include "components/prefs/pref_change_registrar.h" class PrefService; namespace user_prefs { class PrefRegistrySyncable; } // namespace user_prefs namespace ntp_tiles { // Non-test implementation of the CustomLinksManager interface. class CustomLinksManagerImpl : public CustomLinksManager, public history::HistoryServiceObserver { public: // Restores the previous state of |current_links_| from prefs. CustomLinksManagerImpl(PrefService* prefs, // Can be nullptr in unittests. history::HistoryService* history_service); ~CustomLinksManagerImpl() override; // CustomLinksManager implementation. bool Initialize(const NTPTilesVector& tiles) override; void Uninitialize() override; bool IsInitialized() const override; const std::vector<Link>& GetLinks() const override; bool AddLink(const GURL& url, const base::string16& title) override; bool UpdateLink(const GURL& url, const GURL& new_url, const base::string16& new_title) override; bool ReorderLink(const GURL& url, size_t new_pos) override; bool DeleteLink(const GURL& url) override; bool UndoAction() override; std::unique_ptr<base::CallbackList<void()>::Subscription> RegisterCallbackForOnChanged(base::RepeatingClosure callback) override; // Register preferences used by this class. static void RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* user_prefs); private: void ClearLinks(); // Stores the current list to the profile's preferences. Does not notify // |OnPreferenceChanged|. void StoreLinks(); // Returns an iterator into |custom_links_|. std::vector<Link>::iterator FindLinkWithUrl(const GURL& url); // history::HistoryServiceObserver implementation. // Deletes any Most Visited links whose URL is in |deletion_info|. Clears // |previous_links_|. Does not delete entries expired by HistoryService. void OnURLsDeleted(history::HistoryService* history_service, const history::DeletionInfo& deletion_info) override; void HistoryServiceBeingDeleted( history::HistoryService* history_service) override; // Called when the current list of links and/or initialization state in // PrefService is modified. Saves the new set of links in |current_links_| // and notifies |callback_list_|. void OnPreferenceChanged(); PrefService* const prefs_; CustomLinksStore store_; std::vector<Link> current_links_; // The state of the current list of links before the last action was // performed. base::Optional<std::vector<Link>> previous_links_; // List of callbacks to be invoked when custom links are updated by outside // sources. base::CallbackList<void()> callback_list_; // Observer for the HistoryService. ScopedObserver<history::HistoryService, history::HistoryServiceObserver> history_service_observer_; // Observer for Chrome sync changes to |prefs::kCustomLinksList| and // |prefs::kCustomLinksInitialized|. PrefChangeRegistrar pref_change_registrar_; // Used to ignore notifications from |pref_change_registrar_| that we trigger // ourselves when updating the preferences. bool updating_preferences_ = false; base::WeakPtrFactory<CustomLinksManagerImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(CustomLinksManagerImpl); }; } // namespace ntp_tiles #endif // COMPONENTS_NTP_TILES_CUSTOM_LINKS_MANAGER_IMPL_H_
// 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. #ifndef CHROMEOS_SERVICES_LIBASSISTANT_AUDIO_AUDIO_DEVICE_OWNER_H_ #define CHROMEOS_SERVICES_LIBASSISTANT_AUDIO_AUDIO_DEVICE_OWNER_H_ #include <memory> #include <string> #include <vector> #include "base/sequence_checker.h" #include "base/synchronization/lock.h" #include "chromeos/services/libassistant/public/mojom/audio_output_delegate.mojom-forward.h" #include "libassistant/shared/public/platform_audio_output.h" #include "media/base/audio_block_fifo.h" #include "media/base/audio_parameters.h" #include "media/base/audio_renderer_sink.h" #include "media/mojo/mojom/audio_stream_factory.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/audio/public/cpp/output_device.h" #include "services/media_session/public/mojom/media_session.mojom.h" namespace chromeos { namespace libassistant { class AudioDeviceOwner : public media::AudioRendererSink::RenderCallback, media_session::mojom::MediaSessionObserver { public: explicit AudioDeviceOwner(const std::string& device_id); AudioDeviceOwner(const AudioDeviceOwner&) = delete; AudioDeviceOwner& operator=(const AudioDeviceOwner&) = delete; ~AudioDeviceOwner() override; void Start( chromeos::libassistant::mojom::AudioOutputDelegate* audio_output_delegate, assistant_client::AudioOutput::Delegate* delegate, mojo::PendingRemote<media::mojom::AudioStreamFactory> stream_factory, const assistant_client::OutputStreamFormat& format); void Stop(); // media_session::mojom::MediaSessionObserver overrides: void MediaSessionInfoChanged( media_session::mojom::MediaSessionInfoPtr info) override; void MediaSessionMetadataChanged( const absl::optional<::media_session::MediaMetadata>& metadata) override { } void MediaSessionActionsChanged( const std::vector<media_session::mojom::MediaSessionAction>& action) override {} void MediaSessionImagesChanged( const base::flat_map<media_session::mojom::MediaSessionImageType, std::vector<::media_session::MediaImage>>& images) override {} void MediaSessionPositionChanged( const absl::optional<::media_session::MediaPosition>& position) override { } // media::AudioRenderSink::RenderCallback overrides: int Render(base::TimeDelta delay, base::TimeTicks delay_timestamp, int prior_frames_skipped, media::AudioBus* dest) override; void OnRenderError() override; void SetDelegate(assistant_client::AudioOutput::Delegate* delegate); private: void StartDevice( mojo::PendingRemote<media::mojom::AudioStreamFactory> stream_factory, mojom::AudioOutputDelegate* audio_output_delegate); // Requests assistant to fill buffer with more data. void ScheduleFillLocked(const base::TimeTicks& time); // Callback for assistant to notify that it completes the filling. void BufferFillDone(int num_bytes); base::Lock lock_; std::unique_ptr<media::AudioBlockFifo> audio_fifo_ GUARDED_BY(lock_); // Whether assistant is filling the buffer -- delegate_->FillBuffer is called // and BufferFillDone() is not called yet. bool is_filling_ GUARDED_BY(lock_) = false; media::AudioParameters audio_param_ GUARDED_BY(lock_); std::vector<uint8_t> audio_data_ GUARDED_BY(lock_); // Stores audio frames generated by assistant. assistant_client::OutputStreamFormat format_ GUARDED_BY(lock_); assistant_client::AudioOutput::Delegate* delegate_ GUARDED_BY(lock_); // Audio output device id used for output. std::string device_id_ GUARDED_BY_CONTEXT(sequence_checker_); std::unique_ptr<audio::OutputDevice> output_device_ GUARDED_BY_CONTEXT(sequence_checker_); mojo::Receiver<media_session::mojom::MediaSessionObserver> session_receiver_{ this}; // The callbacks from |RenderCallback| are called on a different sequence, // so this sequence checker prevents the other methods from being called on // the render sequence. SEQUENCE_CHECKER(sequence_checker_); }; } // namespace libassistant } // namespace chromeos #endif // CHROMEOS_SERVICES_LIBASSISTANT_AUDIO_AUDIO_DEVICE_OWNER_H_
/* * File: periodic_table.h * Author: scadars * * Created on September 17, 2013, 11:09 PM */ #ifndef PERIODIC_TABLE_H #define PERIODIC_TABLE_H #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <vector> class isotope { public: isotope(const boost::property_tree::ptree::value_type& ptbranch, std::string eltSymbol_v); std::string get_name() ; int get_isotopeNb() { return number ; } ; double get_nucSpin() { return nucSpin ;} ; double get_magGyrRatio() { return magGyrRatio ; } ; double get_natAbundance() { return natAbundance ; } ; double get_Q() { return Q_barn ; } ; virtual ~isotope(); private: protected: int number ; std::string eltSymbol ; double nucSpin; double magGyrRatio; double natAbundance; double Q_barn; }; class element { public: element(const boost::property_tree::ptree::value_type& ptbranch); int get_atomNumber() {return atomicNumber ; }; std::string get_symbol() {return symbol ; }; std::string get_name() {return name ; }; isotope get_isotope(int isotope_number) ; isotope get_isotope(std::string isotope_name) ; std::vector <std::string> get_isotopeList(); virtual ~element(); private: protected: int atomicNumber; std::string name; std::string symbol; std::vector <isotope> isotopes; }; class periodic_table { public: periodic_table(); periodic_table(const periodic_table& orig); virtual ~periodic_table(); element get_element(int atom_number) ; element get_element(std::string atom_symbol) ; private: protected: std::vector <element> elements; }; #endif /* PERIODIC_TABLE_H */
/**************************************************************************** ** SCALASCA http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2013 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** See the file COPYRIGHT in the package base directory for details ** ****************************************************************************/ #ifndef PEARL_PROCESS_H #define PEARL_PROCESS_H #include <vector> #include "NamedObject.h" /*-------------------------------------------------------------------------*/ /** * @file Process.h * @ingroup PEARL_base * @brief Declaration of the class Process. * * This header file provides the declaration of the class Process. */ /*-------------------------------------------------------------------------*/ namespace pearl { //--- Forward declarations -------------------------------------------------- class Node; class Thread; /*-------------------------------------------------------------------------*/ /** * @class Process * @ingroup PEARL_base * @brief Stores information related to a process of the target * application. * * Instances of the class Process provide information about a single * process of the target application. Each process is bound to exactly * one Node of a Machine and consists of at least one Thread. * * The numerical identifiers of the individual processes are globally * defined and continuously enumerated, i.e., the ID is element of * [0,@#processes-1]. In the context of MPI applications, the identifier * of a process is equal to its rank number in MPI_COMM_WORLD. * * @note The Thread objects added to a process are only referenced and not * owned by the corresponding Process object. Therefore, they will * not be deleted if the Process object is released. */ /*-------------------------------------------------------------------------*/ class Process : public NamedObject { public: /// @name Constructors & destructor /// @{ Process(ident_t id, const std::string& name); /// @} /// @name Get & set process information /// @{ uint32_t num_threads() const; Thread* get_thread(uint32_t index) const; void add_thread(Thread* thread); Node* get_node() const; /// @} private: /// Container type for the threads running within this process typedef std::vector<Thread*> thread_container; /// %Node this process belongs to Node* m_node; /// Threads running in this process thread_container m_threads; /* Private methods */ void set_node(Node* node); /* Declare friends */ friend class Node; }; } /* namespace pearl */ #endif /* !PEARL_PROCESS_H */
/* * $NetBSD: ls.c,v 1.3 1997/06/13 13:48:47 drochner Exp $ */ /*- * Copyright (c) 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 1996 * Matthias Drochner. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/boot/common/ls.c 119483 2003-08-25 23:30:41Z obrien $"); #include <sys/param.h> #include <ufs/ufs/dinode.h> #include <ufs/ufs/dir.h> #include <stand.h> #include <string.h> #include "bootstrap.h" static char typestr[] = "?fc?d?b? ?l?s?w"; static int ls_getdir(char **pathp); COMMAND_SET(ls, "ls", "list files", command_ls); static int command_ls(int argc, char *argv[]) { int fd; struct stat sb; struct dirent *d; char *buf, *path; char lbuf[128]; /* one line */ int result, ch; int verbose; result = CMD_OK; fd = -1; verbose = 0; optind = 1; optreset = 1; while ((ch = getopt(argc, argv, "l")) != -1) { switch(ch) { case 'l': verbose = 1; break; case '?': default: /* getopt has already reported an error */ return(CMD_OK); } } argv += (optind - 1); argc -= (optind - 1); if (argc < 2) { path = ""; } else { path = argv[1]; } fd = ls_getdir(&path); if (fd == -1) { result = CMD_ERROR; goto out; } pager_open(); pager_output(path); pager_output("\n"); while ((d = readdirfd(fd)) != NULL) { if (strcmp(d->d_name, ".") && strcmp(d->d_name, "..")) { if (verbose) { /* stat the file, if possible */ sb.st_size = 0; buf = malloc(strlen(path) + strlen(d->d_name) + 2); sprintf(buf, "%s/%s", path, d->d_name); /* ignore return, could be symlink, etc. */ if (stat(buf, &sb)) sb.st_size = 0; free(buf); sprintf(lbuf, " %c %8d %s\n", typestr[d->d_type], (int)sb.st_size, d->d_name); } else { sprintf(lbuf, " %c %s\n", typestr[d->d_type], d->d_name); } if (pager_output(lbuf)) goto out; } } out: pager_close(); if (fd != -1) close(fd); if (path != NULL) free(path); return(result); } /* * Given (path) containing a vaguely reasonable path specification, return an fd * on the directory, and an allocated copy of the path to the directory. */ static int ls_getdir(char **pathp) { struct stat sb; int fd; const char *cp; char *path, *tail; tail = NULL; fd = -1; /* one extra byte for a possible trailing slash required */ path = malloc(strlen(*pathp) + 2); strcpy(path, *pathp); /* Make sure the path is respectable to begin with */ if (archsw.arch_getdev(NULL, path, &cp)) { sprintf(command_errbuf, "bad path '%s'", path); goto out; } /* If there's no path on the device, assume '/' */ if (*cp == 0) strcat(path, "/"); fd = open(path, O_RDONLY); if (fd < 0) { sprintf(command_errbuf, "open '%s' failed: %s", path, strerror(errno)); goto out; } if (fstat(fd, &sb) < 0) { sprintf(command_errbuf, "stat failed: %s", strerror(errno)); goto out; } if (!S_ISDIR(sb.st_mode)) { sprintf(command_errbuf, "%s: %s", path, strerror(ENOTDIR)); goto out; } *pathp = path; return(fd); out: free(path); *pathp = NULL; if (fd != -1) close(fd); return(-1); }
// // CGICalendar.h // // Created by Satoshi Konno on 11/01/28. // Copyright 2011 Satoshi Konno. All rights reserved. // #import <Foundation/Foundation.h> #import "CGICalendarObject.h" #import "NSDate+CGICalendar.h" #import "CGICalendarComponent.h" #import "CGICalendarProperty.h" #define CG_ICALENDAR_HEADER_CONTENTLINE @"BEGIN:VCALENDAR" #define CG_ICALENDAR_FOOTER_CONTENTLINE @"END:VCALENDAR" @interface CGICalendar : NSObject { } @property(strong) NSMutableArray *objects; + (NSString *)UUID; - (id)init; - (id)initWithString:(NSString *)string; - (id)initWithPath:(NSString *)path; - (BOOL)parseWithString:(NSString *)string error:(NSError **)error; - (BOOL)parseWithPath:(NSString *)path error:(NSError **)error; - (void)addObject:(CGICalendarObject *)object; - (CGICalendarObject *)objectAtIndex:(NSUInteger)index; - (NSString *)description; + (NSString *)unescape:(NSString *)aValue; - (BOOL)writeToFile:(NSString *)path; @end
// 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 NET_ANDROID_NETWORK_CHANGE_NOTIFIER_ANDROID_H_ #define NET_ANDROID_NETWORK_CHANGE_NOTIFIER_ANDROID_H_ #include <memory> #include "base/android/jni_android.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "net/android/network_change_notifier_delegate_android.h" #include "net/base/net_export.h" #include "net/base/network_change_notifier.h" namespace net { class NetworkChangeNotifierAndroidTest; class NetworkChangeNotifierFactoryAndroid; // NetworkChangeNotifierAndroid observes network events from the Android // notification system and forwards them to observers. // // The implementation is complicated by the differing lifetime and thread // affinity requirements of Android notifications and of NetworkChangeNotifier. // // High-level overview: // NetworkChangeNotifier.java - Receives notifications from Android system, and // notifies native code via JNI (on the main application thread). // NetworkChangeNotifierDelegateAndroid ('Delegate') - Listens for notifications // sent via JNI on the main application thread, and forwards them to observers // on their threads. Owned by Factory, lives exclusively on main application // thread. // NetworkChangeNotifierFactoryAndroid ('Factory') - Creates the Delegate on the // main thread to receive JNI events, and vends Notifiers. Lives exclusively // on main application thread, and outlives all other classes. // NetworkChangeNotifierAndroid ('Notifier') - Receives event notifications from // the Delegate. Processes and forwards these events to the // NetworkChangeNotifier observers on their threads. May live on any thread // and be called by any thread. // // For more details, see the implementation file. class NET_EXPORT_PRIVATE NetworkChangeNotifierAndroid : public NetworkChangeNotifier, public NetworkChangeNotifierDelegateAndroid::Observer { public: ~NetworkChangeNotifierAndroid() override; // NetworkChangeNotifier: ConnectionType GetCurrentConnectionType() const override; // Requires ACCESS_WIFI_STATE permission in order to provide precise WiFi link // speed. void GetCurrentMaxBandwidthAndConnectionType( double* max_bandwidth_mbps, ConnectionType* connection_type) const override; bool AreNetworkHandlesCurrentlySupported() const override; void GetCurrentConnectedNetworks(NetworkList* network_list) const override; ConnectionType GetCurrentNetworkConnectionType( NetworkHandle network) const override; NetworkChangeNotifier::ConnectionSubtype GetCurrentConnectionSubtype() const override; NetworkHandle GetCurrentDefaultNetwork() const override; // NetworkChangeNotifierDelegateAndroid::Observer: void OnConnectionTypeChanged() override; void OnMaxBandwidthChanged(double max_bandwidth_mbps, ConnectionType type) override; void OnNetworkConnected(NetworkHandle network) override; void OnNetworkSoonToDisconnect(NetworkHandle network) override; void OnNetworkDisconnected(NetworkHandle network) override; void OnNetworkMadeDefault(NetworkHandle network) override; // Promote GetMaxBandwidthMbpsForConnectionSubtype to public for the Android // delegate class. using NetworkChangeNotifier::GetMaxBandwidthMbpsForConnectionSubtype; protected: void OnFinalizingMetricsLogRecord() override; private: friend class NetworkChangeNotifierAndroidTest; friend class NetworkChangeNotifierFactoryAndroid; class DnsConfigServiceThread; // Enable NetworkHandles support for tests. void ForceNetworkHandlesSupportedForTesting(); explicit NetworkChangeNotifierAndroid( NetworkChangeNotifierDelegateAndroid* delegate); static NetworkChangeCalculatorParams NetworkChangeCalculatorParamsAndroid(); NetworkChangeNotifierDelegateAndroid* const delegate_; std::unique_ptr<DnsConfigServiceThread> dns_config_service_thread_; bool force_network_handles_supported_for_testing_; DISALLOW_COPY_AND_ASSIGN(NetworkChangeNotifierAndroid); }; } // namespace net #endif // NET_ANDROID_NETWORK_CHANGE_NOTIFIER_ANDROID_H_
/** * @file MathML.h * @brief Utilities for reading and writing MathML to/from text strings. * @author Ben Bornstein * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2013-2014 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution and * also available online as http://sbml.org/software/libsbml/license.html * ---------------------------------------------------------------------- -->*/ #ifndef MathML_h #define MathML_h #include <sbml/common/extern.h> #include <sbml/common/sbmlfwd.h> #ifdef __cplusplus #include <limits> #include <iomanip> #include <string> #include <sstream> #include <cstdlib> LIBSBML_CPP_NAMESPACE_BEGIN /** @cond doxygenLibsbmlInternal */ class ASTNode; class XMLInputStream; class XMLOutputStream; /** * Reads the MathML from the given XMLInputStream, constructs a corresponding * abstract syntax tree and returns a pointer to the root of the tree. */ LIBSBML_EXTERN ASTNode* readMathML (XMLInputStream& stream, std::string reqd_prefix=""); /** * Writes the given ASTNode (and its children) to the XMLOutputStream as * MathML. */ LIBSBML_EXTERN void writeMathML (const ASTNode* node, XMLOutputStream& stream, SBMLNamespaces *sbmlns=NULL); /** @endcond */ LIBSBML_CPP_NAMESPACE_END #endif /* __cplusplus */ LIBSBML_CPP_NAMESPACE_BEGIN BEGIN_C_DECLS /** * Reads the MathML from the given XML string, constructs a corresponding * abstract syntax tree, and returns a pointer to the root of the tree. * * @param xml a string containing a full MathML expression * * @return the root of an AST corresponding to the given mathematical * expression, otherwise @c NULL is returned if the given string is @c NULL * or invalid. * * @if conly * @memberof ASTNode_t * @endif */ LIBSBML_EXTERN ASTNode_t * readMathMLFromString (const char *xml); /** * Writes the given ASTNode (and its children) to a string as MathML, and * returns the string. * * @param node the root of an AST to write out to the stream. * * @return a string containing the written-out MathML representation * of the given AST. * * @note The string is owned by the caller and should be freed (with * free()) when no longer needed. @c NULL is returned if the given * argument is @c NULL. * * @if conly * @memberof ASTNode_t * @endif */ LIBSBML_EXTERN char * writeMathMLToString (const ASTNode_t* node); END_C_DECLS LIBSBML_CPP_NAMESPACE_END #endif /** MathML_h **/
#pragma once #include <string> #include <vector> #include <stdexcept> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <luabind/lua_include.hpp> #include <math/matrix.h> #include "forward.h" namespace graphic { class Joint { public: struct transform { transform(std::string const &s, math::matrix<4,4> const &m): sid(s), matrix(m) { } std::string sid; math::matrix<4,4> matrix; }; typedef std::vector<JointWeakPtr> childs_type; size_t index; std::string id, name; JointWeakPtr parent; childs_type childs; std::vector<transform> transforms; mutable math::matrix<4,4> matrix; boost::weak_ptr<Mesh> mesh_ptr; Joint(size_t i): index(i) { } math::matrix<4,4> &get_transform_by_sid(std::string const &sid){ for (std::vector<transform>::iterator it = transforms.begin(); it != transforms.end(); it++) if (it->sid == sid) return it->matrix; throw std::logic_error("transform sid = " + sid + " not found"); } void build_frame_transforms() { matrix.identity(); for (std::vector<transform>::reverse_iterator it = transforms.rbegin(); it != transforms.rend(); it++) { matrix *= it->matrix; } if (JointPtr p = parent.lock()) matrix *= p->matrix; for (childs_type::iterator it = childs.begin(); it != childs.end(); it++) { if (JointPtr child = it->lock()) child->build_frame_transforms(); } } static void bind(lua_State *L); }; }
/* $NetBSD: clmpccvar.h,v 1.2 1999/02/20 00:27:30 scw Exp $ */ /*- * Copyright (c) 1999 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Steve C. Woodford. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __clmpccvar_h #define __clmpccvar_h /* Buffer size for character buffer */ #define CLMPCC_RING_SIZE 512 /* How many channels per chip */ #define CLMPCC_NUM_CHANS 4 /* Reasons for calling the MD code's iack hook function */ #define CLMPCC_IACK_MODEM 0 #define CLMPCC_IACK_RX 1 #define CLMPCC_IACK_TX 2 struct clmpcc_softc; /* * Each channel is represented by one of the following structures */ struct clmpcc_chan { struct tty *ch_tty; /* This channel's tty structure */ struct clmpcc_softc *ch_sc; /* Pointer to chip's softc structure */ u_char ch_car; /* Channel number (CD2400_REG_CAR) */ u_char ch_openflags; /* Persistant TIOC flags */ u_short ch_flags; /* Various channel-specific flags */ #define CLMPCC_FLG_IS_CONSOLE 0x0001 /* Channel is system console */ #define CLMPCC_FLG_CARRIER_CHNG 0x0002 #define CLMPCC_FLG_START_BREAK 0x0004 #define CLMPCC_FLG_END_BREAK 0x0008 #define CLMPCC_FLG_START 0x0010 #define CLMPCC_FLG_STOP 0x0020 #define CLMPCC_FLG_FIFO_CLEAR 0x0040 #define CLMPCC_FLG_UPDATE_PARMS 0x0080 #define CLMPCC_FLG_NEED_INIT 0x0100 u_char ch_control; /* New port parameters wait here until written by the Tx ISR */ u_char ch_tcor; u_char ch_tbpr; u_char ch_rcor; u_char ch_rbpr; u_char ch_cor1; u_char ch_cor2; u_char ch_cor3; u_char ch_cor4; /* Current Rx Fifo threshold */ u_char ch_cor5; u_int8_t *ch_ibuf; /* Start of input ring buffer */ u_int8_t *ch_ibuf_end; /* End of input ring buffer */ u_int8_t *ch_ibuf_rd; /* Input buffer tail (reader) */ u_int8_t *ch_ibuf_wr; /* Input buffer head (writer) */ }; struct clmpcc_softc { struct device sc_dev; /* * The bus/MD-specific attachment code must initialise the * following four fields before calling 'clmpcc_attach_subr()'. */ bus_space_tag_t sc_iot; /* Tag for parent bus */ bus_space_handle_t sc_ioh; /* Handle for chip's regs */ void *sc_data; /* MD-specific data */ int sc_clk; /* Clock-rate, in Hz */ u_char sc_vector_base; /* Vector base reg, or 0 for auto */ u_char sc_rpilr; /* Receive Priority Interupt Level */ u_char sc_tpilr; /* Transmit Priority Interupt Level */ u_char sc_mpilr; /* Modem Priority Interupt Level */ int sc_swaprtsdtr; /* Non-zero if RTS and DTR swapped */ u_int sc_byteswap; /* One of the following ... */ #define CLMPCC_BYTESWAP_LOW 0x00 /* *byteswap pin is low */ #define CLMPCC_BYTESWAP_HIGH 0x03 /* *byteswap pin is high */ /* Called to request a soft interrupt callback to clmpcc_softintr */ void (*sc_softhook) __P((struct clmpcc_softc *)); /* Called when an interrupt has to be acknowledged in polled mode. */ void (*sc_iackhook) __P((struct clmpcc_softc *, int)); /* * No user-serviceable parts below */ int sc_soft_running; struct clmpcc_chan sc_chans[CLMPCC_NUM_CHANS]; }; extern void clmpcc_attach __P((struct clmpcc_softc *)); extern int clmpcc_cnattach __P((struct clmpcc_softc *, int, int)); extern int clmpcc_rxintr __P((void *)); extern int clmpcc_txintr __P((void *)); extern int clmpcc_mdintr __P((void *)); extern int clmpcc_softintr __P((void *)); #endif /* __clmpccvar_h */
#if !defined(DISABLE_SOUND) enum { BEEPEVENT_MAXBIT = 8, BEEPEVENT_MAX = (1 << BEEPEVENT_MAXBIT) }; typedef struct { SINT32 clock; int enable; } BPEVENT; typedef struct { UINT16 cnt; UINT16 hz; int buz; int __puchi; UINT8 mode; UINT8 padding[3]; int low; int enable; int lastenable; SINT32 clock; UINT events; BPEVENT event[BEEPEVENT_MAX]; } _BEEP, *BEEP; typedef struct { UINT rate; UINT vol; UINT __puchibase; UINT samplebase; } BEEPCFG; #ifdef __cplusplus extern "C" { #endif extern _BEEP g_beep; void beep_initialize(UINT rate); void beep_deinitialize(void); void beep_setvol(UINT vol); void beep_changeclock(void); void beep_reset(void); void beep_hzset(UINT16 cnt); void beep_modeset(void); void beep_eventinit(void); void beep_eventreset(void); void beep_lheventset(int beep_low); void beep_oneventset(void); void SOUNDCALL beep_getpcm(BEEP bp, SINT32 *pcm, UINT count); #ifdef __cplusplus } #endif #else #define beep_setvol(v) #define beep_changeclock() #define beep_hzset(c) #define beep_modeset() #define beep_eventreset() #define beep_lheventset(b) #define beep_oneventset() #endif
// 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. #ifndef COMPONENTS_PREFS_WRITEABLE_PREF_STORE_H_ #define COMPONENTS_PREFS_WRITEABLE_PREF_STORE_H_ #include <stdint.h> #include <memory> #include <set> #include <string> #include <vector> #include "base/macros.h" #include "components/prefs/pref_store.h" namespace base { class Value; } // A pref store that can be written to as well as read from. class COMPONENTS_PREFS_EXPORT WriteablePrefStore : public PrefStore { public: // PrefWriteFlags can be used to change the way a pref will be written to // storage. enum PrefWriteFlags : uint32_t { // No flags are specified. DEFAULT_PREF_WRITE_FLAGS = 0, // This marks the pref as "lossy". There is no strict time guarantee on when // a lossy pref will be persisted to permanent storage when it is modified. LOSSY_PREF_WRITE_FLAG = 1 << 1 }; WriteablePrefStore() {} // Sets a |value| for |key| in the store. |value| must be non-NULL. |flags| is // a bitmask of PrefWriteFlags. virtual void SetValue(const std::string& key, std::unique_ptr<base::Value> value, uint32_t flags) = 0; // Removes the value for |key|. virtual void RemoveValue(const std::string& key, uint32_t flags) = 0; // Equivalent to PrefStore::GetValue but returns a mutable value. virtual bool GetMutableValue(const std::string& key, base::Value** result) = 0; // Triggers a value changed notification. This function or // ReportSubValuesChanged needs to be called if one retrieves a list or // dictionary with GetMutableValue and change its value. SetValue takes care // of notifications itself. Note that ReportValueChanged will trigger // notifications even if nothing has changed. |flags| is a bitmask of // PrefWriteFlags. virtual void ReportValueChanged(const std::string& key, uint32_t flags) = 0; // Triggers a value changed notification for |path_components| in the |key| // pref. This function or ReportValueChanged needs to be called if one // retrieves a list or dictionary with GetMutableValue and change its value. // SetValue takes care of notifications itself. Note that // ReportSubValuesChanged will trigger notifications even if nothing has // changed. |flags| is a bitmask of PrefWriteFlags. virtual void ReportSubValuesChanged( const std::string& key, std::set<std::vector<std::string>> path_components, uint32_t flags); // Same as SetValue, but doesn't generate notifications. This is used by // PrefService::GetMutableUserPref() in order to put empty entries // into the user pref store. Using SetValue is not an option since existing // tests rely on the number of notifications generated. |flags| is a bitmask // of PrefWriteFlags. virtual void SetValueSilently(const std::string& key, std::unique_ptr<base::Value> value, uint32_t flags) = 0; // Clears all the preferences which names start with |prefix| and doesn't // generate update notifications. virtual void RemoveValuesByPrefixSilently(const std::string& prefix) = 0; protected: ~WriteablePrefStore() override {} private: DISALLOW_COPY_AND_ASSIGN(WriteablePrefStore); }; #endif // COMPONENTS_PREFS_WRITEABLE_PREF_STORE_H_
// 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 CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PAGE_ACTION_IMAGE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PAGE_ACTION_IMAGE_VIEW_H_ #include <map> #include <string> #include "base/memory/scoped_ptr.h" #include "chrome/browser/extensions/image_loading_tracker.h" #include "chrome/browser/ui/views/extensions/extension_popup.h" #include "chrome/common/extensions/extension_action.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/image_view.h" #include "ui/views/widget/widget_observer.h" class Browser; class LocationBarView; namespace content { class WebContents; } namespace views { class MenuRunner; } // PageActionImageView is used by the LocationBarView to display the icon for a // given PageAction and notify the extension when the icon is clicked. class PageActionImageView : public views::ImageView, public ImageLoadingTracker::Observer, public views::WidgetObserver, public views::ContextMenuController, public content::NotificationObserver, public ExtensionAction::IconAnimation::Observer { public: PageActionImageView(LocationBarView* owner, ExtensionAction* page_action, Browser* browser); virtual ~PageActionImageView(); ExtensionAction* page_action() { return page_action_; } int current_tab_id() { return current_tab_id_; } void set_preview_enabled(bool preview_enabled) { preview_enabled_ = preview_enabled; } // Overridden from views::View: virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE; virtual bool OnMousePressed(const views::MouseEvent& event) OVERRIDE; virtual void OnMouseReleased(const views::MouseEvent& event) OVERRIDE; virtual bool OnKeyPressed(const views::KeyEvent& event) OVERRIDE; // Overridden from ImageLoadingTracker: virtual void OnImageLoaded(const gfx::Image& image, const std::string& extension_id, int index) OVERRIDE; // Overridden from views::WidgetObserver: virtual void OnWidgetClosing(views::Widget* widget) OVERRIDE; // Overridden from views::ContextMenuController. virtual void ShowContextMenuForView(View* source, const gfx::Point& point) OVERRIDE; // Overridden from content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Overridden from ui::AcceleratorTarget: virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE; virtual bool CanHandleAccelerators() const OVERRIDE; // Called to notify the PageAction that it should determine whether to be // visible or hidden. |contents| is the WebContents that is active, |url| is // the current page URL. void UpdateVisibility(content::WebContents* contents, const GURL& url); // Either notify listeners or show a popup depending on the page action. void ExecuteAction(int button); private: // Overridden from ExtensionAction::IconAnimation::Observer: virtual void OnIconChanged( const ExtensionAction::IconAnimation& animation) OVERRIDE; // Shows the popup, with the given URL. void ShowPopupWithURL(const GURL& popup_url); // Hides the active popup, if there is one. void HidePopup(); // The location bar view that owns us. LocationBarView* owner_; // The PageAction that this view represents. The PageAction is not owned by // us, it resides in the extension of this particular profile. ExtensionAction* page_action_; // The corresponding browser. Browser* browser_; // The object that is waiting for the image loading to complete // asynchronously. ImageLoadingTracker tracker_; // The tab id we are currently showing the icon for. int current_tab_id_; // The URL we are currently showing the icon for. GURL current_url_; // The string to show for a tooltip; std::string tooltip_; // This is used for post-install visual feedback. The page_action icon is // briefly shown even if it hasn't been enabled by its extension. bool preview_enabled_; // The current popup and the button it came from. NULL if no popup. ExtensionPopup* popup_; content::NotificationRegistrar registrar_; // The extension command accelerator this page action is listening for (to // show the popup). scoped_ptr<ui::Accelerator> page_action_keybinding_; // The extension command accelerator this script badge is listening for (to // show the popup). scoped_ptr<ui::Accelerator> script_badge_keybinding_; scoped_ptr<views::MenuRunner> menu_runner_; // Fade-in animation for the icon with observer scoped to this. ExtensionAction::IconAnimation::ScopedObserver scoped_icon_animation_observer_; DISALLOW_IMPLICIT_CONSTRUCTORS(PageActionImageView); }; #endif // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PAGE_ACTION_IMAGE_VIEW_H_
// Copyright 2015 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_ANDROID_AFFILIATION_FACET_MANAGER_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_H_ #include <set> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/site_affiliation/affiliation_service.h" namespace base { class Clock; class TaskRunner; } // namespace base namespace password_manager { class FacetManagerHost; // Encapsulates the state and logic required for handling affiliation requests // concerning a single facet. The AffiliationBackend owns one instance for each // facet that requires attention, and it itself implements the FacetManagerHost // interface to provide shared functionality needed by all FacetManagers. class FacetManager { public: using StrategyOnCacheMiss = AffiliationService::StrategyOnCacheMiss; // Both the |backend| and |clock| must outlive this object. FacetManager(const FacetURI& facet_uri, FacetManagerHost* backend, base::Clock* clock); FacetManager(const FacetManager&) = delete; FacetManager& operator=(const FacetManager&) = delete; ~FacetManager(); // Facet-specific implementations for methods in AffiliationService of // the same name. See documentation in android_affiliation_service.h for // details: void GetAffiliationsAndBranding( StrategyOnCacheMiss cache_miss_strategy, AffiliationService::ResultCallback callback, const scoped_refptr<base::TaskRunner>& callback_task_runner); void Prefetch(const base::Time& keep_fresh_until); void CancelPrefetch(const base::Time& keep_fresh_until); // Called when |affiliation| information regarding this facet has just been // fetched from the Affiliation API. void OnFetchSucceeded(const AffiliatedFacetsWithUpdateTime& affiliation); // Called by the backend when the time specified in RequestNotificationAtTime // has come to pass, so that |this| can perform delayed administrative tasks. void NotifyAtRequestedTime(); // Returns whether this instance has becomes redundant, that is, it has no // more meaningful state than a newly created instance would have. bool CanBeDiscarded() const; // Returns whether or not cached data for this facet can be discarded without // harm when trimming the database. bool CanCachedDataBeDiscarded() const; // Returns whether or not affiliation information relating to this facet needs // to be fetched right now. bool DoesRequireFetch() const; // The members below are made public for the sake of tests. // Returns whether or not cached data for this facet is fresh (not stale). bool IsCachedDataFresh() const; // Returns whether or not cached data for this facet is near-stale or stale. bool IsCachedDataNearStale() const; // The duration after which cached affiliation data is considered near-stale. static const int kCacheSoftExpiryInHours; // The duration after which cached affiliation data is considered stale. static const int kCacheHardExpiryInHours; private: struct RequestInfo; // Returns the time when the cached data for this facet will become stale. // The data is considered stale with the returned time value inclusive. base::Time GetCacheHardExpiryTime() const; // Returns the time when cached data for this facet becomes near-stale. // The data is considered near-stale with the returned time value inclusive. base::Time GetCacheSoftExpiryTime() const; // Returns the maximum of |keep_fresh_thresholds_|, or the NULL time if the // set is empty. base::Time GetMaximumKeepFreshUntilThreshold() const; // Returns the next time affiliation data for this facet needs to be fetched // due to active prefetch requests, or base::Time::Max() if not at all. base::Time GetNextRequiredFetchTimeDueToPrefetch() const; // Posts the callback of the request described by |request_info| with success. static void ServeRequestWithSuccess(RequestInfo request_info, const AffiliatedFacets& affiliation); // Posts the callback of the request described by |request_info| with failure. static void ServeRequestWithFailure(RequestInfo request_info); FacetURI facet_uri_; FacetManagerHost* backend_; base::Clock* clock_; // The last time affiliation information was fetched for this facet, i.e. the // freshness of the data in the cache. If there is no corresponding data in // the database, this will contain the NULL time. Otherwise, the update time // in the database should match this value; it is stored to reduce disk I/O. base::Time last_update_time_; // Contains information about the GetAffiliationsAndBranding() requests that // are waiting for the result of looking up this facet. std::vector<RequestInfo> pending_requests_; // Keeps track of |keep_fresh_until| thresholds corresponding to Prefetch() // requests for this facet. Affiliation information for this facet must be // kept fresh by periodic refetches until at least the maximum time in this // set (exclusive). // // This is not a single timestamp but rather a multiset so that cancellation // of individual prefetches can be supported even if there are two requests // with the same |keep_fresh_until| threshold. std::multiset<base::Time> keep_fresh_until_thresholds_; }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_H_
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_VECTOR_H_ #define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_VECTOR_H_ #include "base/logging.h" #include "build/build_config.h" #include "third_party/blink/public/platform/web_common.h" #include <vector> namespace blink { // A simple vector class that wraps a std::vector. // // Sample usage: // // void Foo(WebVector<int>& result) { // WebVector<int> data(10); // for (size_t i = 0; i < data.size(); ++i) // data[i] = ... // result.Swap(data); // } // // In-place element construction: // // WebVector<WebString> Foo() { // WebVector<WebString> data; // data.reserve(10); // WebUChar* buffer = ....; // data.emplace_back(buffer, buffer_size); // return data; // } // // It is also possible to assign from any container that implements begin() // and end(). // // void Foo(const std::vector<WTF::String>& input) { // WebVector<WebString> strings = input; // ... // } template <typename T> class WebVector { public: using value_type = typename std::vector<T>::value_type; using iterator = typename std::vector<T>::iterator; using const_iterator = typename std::vector<T>::const_iterator; ~WebVector() = default; // Create an empty vector. // // The vector can be populated using reserve() and emplace_back(). WebVector() = default; #if defined(ARCH_CPU_64_BITS) // Create a vector with |size| default-constructed elements. We define // a constructor with size_t otherwise we'd have a duplicate define. explicit WebVector(size_t size) : data_(size) {} #endif // Create a vector with |size| default-constructed elements. explicit WebVector(uint32_t size) : data_(size) {} template <typename U> WebVector(const U* values, size_t size) : data_(values, values + size) {} WebVector(const WebVector<T>& other) : data_(other.data_) {} template <typename C> WebVector(const C& other) : data_(other.begin(), other.end()) {} WebVector(WebVector<T>&& other) noexcept { Swap(other); } WebVector(std::vector<T>&& other) noexcept : data_(std::move(other)) {} std::vector<T> ReleaseVector() noexcept { return std::move(data_); } WebVector& operator=(const WebVector& other) { if (this != &other) Assign(other); return *this; } WebVector& operator=(WebVector&& other) noexcept { if (this != &other) Swap(other); return *this; } template <typename C> WebVector<T>& operator=(const C& other) { if (this != reinterpret_cast<const WebVector<T>*>(&other)) Assign(other); return *this; } WebVector<T>& operator=(std::vector<T>&& other) noexcept { data_ = std::move(other); return *this; } template <typename C> void Assign(const C& other) { data_.assign(other.begin(), other.end()); } template <typename U> void Assign(const U* values, size_t size) { data_.assign(values, values + size); } size_t size() const { return data_.size(); } void resize(size_t new_size) { DCHECK_LE(new_size, data_.capacity()); data_.resize(new_size); } bool empty() const { return data_.empty(); } size_t capacity() const { return data_.capacity(); } void reserve(size_t new_capacity) { data_.reserve(new_capacity); } T& operator[](size_t i) { DCHECK_LT(i, data_.size()); return data_[i]; } const T& operator[](size_t i) const { DCHECK_LT(i, data_.size()); return data_[i]; } T* Data() { return data_.data(); } const T* Data() const { return data_.data(); } iterator begin() { return data_.begin(); } iterator end() { return data_.end(); } const_iterator begin() const { return data_.begin(); } const_iterator end() const { return data_.end(); } template <typename... Args> void emplace_back(Args&&... args) { data_.emplace_back(std::forward<Args>(args)...); } void Swap(WebVector<T>& other) { data_.swap(other.data_); } void Clear() { data_.clear(); } T& front() { return data_.front(); } const T& front() const { return data_.front(); } T& back() { return data_.back(); } const T& back() const { return data_.back(); } void EraseAt(size_t index) { data_.erase(begin() + index); } void Insert(size_t index, const T& value) { data_.insert(begin() + index, value); } private: std::vector<T> data_; }; } // namespace blink #endif
/*- * Copyright (c) 1997 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/types.h> #include <sys/param.h> #include <sys/linker.h> #include <sys/sysctl.h> #include <sys/stat.h> #include <err.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #define PATHCTL "kern.module_path" static int path_check(const char *, int); static void usage(void); /* * Check to see if the requested module is specified as a filename with no * path. If so and if a file by the same name exists in the module path, * warn the user that the module in the path will be used in preference. */ static int path_check(const char *kldname, int quiet) { int mib[5], found; size_t miblen, pathlen; char kldpath[MAXPATHLEN]; char *path, *tmppath, *element; struct stat sb; dev_t dev; ino_t ino; if (strchr(kldname, '/') != NULL) { return (0); } if (strstr(kldname, ".ko") == NULL) { return (0); } if (stat(kldname, &sb) != 0) { return (0); } found = 0; dev = sb.st_dev; ino = sb.st_ino; miblen = sizeof(mib) / sizeof(mib[0]); if (sysctlnametomib(PATHCTL, mib, &miblen) != 0) { err(1, "sysctlnametomib(%s)", PATHCTL); } if (sysctl(mib, miblen, NULL, &pathlen, NULL, 0) == -1) { err(1, "getting path: sysctl(%s) - size only", PATHCTL); } path = malloc(pathlen + 1); if (path == NULL) { err(1, "allocating %lu bytes for the path", (unsigned long)pathlen + 1); } if (sysctl(mib, miblen, path, &pathlen, NULL, 0) == -1) { err(1, "getting path: sysctl(%s)", PATHCTL); } tmppath = path; while ((element = strsep(&tmppath, ";")) != NULL) { strlcpy(kldpath, element, MAXPATHLEN); if (kldpath[strlen(kldpath) - 1] != '/') { strlcat(kldpath, "/", MAXPATHLEN); } strlcat(kldpath, kldname, MAXPATHLEN); if (stat(kldpath, &sb) == -1) { continue; } found = 1; if (sb.st_dev != dev || sb.st_ino != ino) { if (!quiet) { warnx("%s will be loaded from %s, not the " "current directory", kldname, element); } break; } else if (sb.st_dev == dev && sb.st_ino == ino) { break; } } free(path); if (!found) { if (!quiet) { warnx("%s is not in the module path", kldname); } return (-1); } return (0); } static void usage(void) { fprintf(stderr, "usage: kldload [-nqv] file ...\n"); exit(1); } int main(int argc, char** argv) { int c; int errors; int fileid; int verbose; int quiet; int check_loaded; errors = 0; verbose = 0; quiet = 0; check_loaded = 0; while ((c = getopt(argc, argv, "nqv")) != -1) { switch (c) { case 'q': quiet = 1; verbose = 0; break; case 'v': verbose = 1; quiet = 0; break; case 'n': check_loaded = 1; break; default: usage(); } } argc -= optind; argv += optind; if (argc == 0) usage(); while (argc-- != 0) { if (path_check(argv[0], quiet) == 0) { fileid = kldload(argv[0]); if (fileid < 0) { if (check_loaded != 0 && errno == EEXIST) { if (verbose) printf("%s is already " "loaded\n", argv[0]); } else { switch (errno) { case EEXIST: warnx("can't load %s: module " "already loaded or " "in kernel", argv[0]); break; case ENOEXEC: warnx("an error occurred while " "loading the module. " "Please check dmesg(8) for " "more details."); break; default: warn("can't load %s", argv[0]); break; } errors++; } } else { if (verbose) printf("Loaded %s, id=%d\n", argv[0], fileid); } } else { errors++; } argv++; } return (errors ? 1 : 0); }
/***************************************************************************** Copyright (c) 2011, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** * Contents: Native high-level C interface to LAPACK function dsbgvd * Author: Intel Corporation * Generated November, 2011 *****************************************************************************/ #include "lapacke.h" #include "lapacke_utils.h" lapack_int LAPACKE_dsbgvd( int matrix_order, char jobz, char uplo, lapack_int n, lapack_int ka, lapack_int kb, double* ab, lapack_int ldab, double* bb, lapack_int ldbb, double* w, double* z, lapack_int ldz ) { lapack_int info = 0; lapack_int liwork = -1; lapack_int lwork = -1; lapack_int* iwork = NULL; double* work = NULL; lapack_int iwork_query; double work_query; if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_dsbgvd", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK /* Optionally check input matrices for NaNs */ if( LAPACKE_dsb_nancheck( matrix_order, uplo, n, ka, ab, ldab ) ) { return -7; } if( LAPACKE_dsb_nancheck( matrix_order, uplo, n, kb, bb, ldbb ) ) { return -9; } #endif /* Query optimal working array(s) size */ info = LAPACKE_dsbgvd_work( matrix_order, jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, &work_query, lwork, &iwork_query, liwork ); if( info != 0 ) { goto exit_level_0; } liwork = (lapack_int)iwork_query; lwork = (lapack_int)work_query; /* Allocate memory for work arrays */ iwork = (lapack_int*)LAPACKE_malloc( sizeof(lapack_int) * liwork ); if( iwork == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } work = (double*)LAPACKE_malloc( sizeof(double) * lwork ); if( work == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_1; } /* Call middle-level interface */ info = LAPACKE_dsbgvd_work( matrix_order, jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork ); /* Release memory and exit */ LAPACKE_free( work ); exit_level_1: LAPACKE_free( iwork ); exit_level_0: if( info == LAPACK_WORK_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_dsbgvd", info ); } return info; }
// Copyright 2016-present 650 Industries. All rights reserved. #import <ABI39_0_0UMPermissionsInterface/ABI39_0_0UMPermissionsInterface.h> @interface ABI39_0_0EXCalendarPermissionRequester : NSObject<ABI39_0_0UMPermissionsRequester> @end
#ifndef _CoreUtils_CoreUtils_h_ #define _CoreUtils_CoreUtils_h_ #include <Core/Core.h> using namespace Upp; #include "Statistics.h" #include "Color.h" #include "Types.h" #include "Node.h" #include "SearchAlgos.h" #include "ActionPlanner.h" #include "Optimizer.h" #include "QueryTable.h" void StreamCopy(Stream& dest, Stream& src); template <class Stream> void CopyStreamCont(Array<Stream>& dest, Array<Stream>& src) { dest.Clear(); for(int i = 0; i < src.GetCount(); i++) { StreamCopy(dest.Add(), src[i]); } } #ifdef CPU_LITTLE_ENDIAN inline int StrPut(TcpSocket& out, void* data, int count) { void* mem = MemoryAlloc(count); byte* buf = (byte*)data; byte* tmp = (byte*)mem; buf += count-1; for(int i = 0; i < count; i++) { *tmp = *buf; buf--; tmp++; } int res = out.Put(mem, count); MemoryFree(mem); return res; } inline int StrGet(TcpSocket& in, void* data, int count) { void* mem = MemoryAlloc(count); byte* buf = (byte*)data; byte* tmp = (byte*)mem; int res = in.Get(mem, count); buf += res-1; for(int i = 0; i < res; i++) { *buf = *tmp; buf--; tmp++; } MemoryFree(mem); return res; } inline int StrPut(Stream& out, void* data, int count) { void* mem = MemoryAlloc(count); byte* buf = (byte*)data; byte* tmp = (byte*)mem; buf += count-1; for(int i = 0; i < count; i++) { *tmp = *buf; buf--; tmp++; } out.Put(mem, count); MemoryFree(mem); return 0; } inline int StrGet(Stream& in, void* data, int count) { void* mem = MemoryAlloc(count); byte* buf = (byte*)data; byte* tmp = (byte*)mem; in.Get(mem, count); buf += count-1; for(int i = 0; i < count; i++) { *buf = *tmp; buf--; tmp++; } MemoryFree(mem); return 0; } inline int LEPut(Stream& out, void* data, int count) {out.Put(data, count); return 0;} inline int LEGet(Stream& in, void* data, int count) {in.Get(data, count); return 0;} #else inline int StrPut(TcpSocket& out, void* data, int count) {return out.Put(data, count);} inline int StrGet(TcpSocket& in, void* data, int count) {return in.Get(data, count);} inline int StrPut(Stream& out, void* data, int count) {return out.Put(data, count);} inline int LEGet(Stream& in, void* data, int count) {return in.Get(data, count);} inline int LEPut(Stream& out, void* data, int count) { void* mem = MemoryAlloc(count); byte* buf = (byte*)data; byte* tmp = (byte*)mem; buf += count-1; for(int i = 0; i < count; i++) { *tmp = *buf; buf--; tmp++; } out.Put(mem, count); MemoryFree(mem); return 0; } inline int StrGet(Stream& in, void* data, int count) { void* mem = MemoryAlloc(count); byte* buf = (byte*)data; byte* tmp = (byte*)mem; in.Get(mem, count); buf += count-1; for(int i = 0; i < count; i++) { *buf = *tmp; buf--; tmp++; } MemoryFree(mem); return 0; } #endif inline dword Timestamp(const Time& t) { return (dword)(t.Get() - Time(1970,1,1).Get()); } inline dword TimestampNow() { return (dword)(GetSysTime().Get() - Time(1970,1,1).Get()); } inline Time TimeFromTimestamp(int64 seconds) { return Time(1970, 1, 1) + seconds; } inline String TimeDiffString(int64 seconds) { String out; if (seconds > -60 && seconds < 60) return "Now"; if (seconds < 0) {out += "-"; seconds *= -1;} else if (seconds > 0) out += "+"; int64 years, months, days, hours, minutes; #define DIV(x, y) x = seconds / (y); seconds = seconds % (y); DIV(years, 365*24*60*60); DIV(months, 30*24*60*60); DIV(days, 24*60*60); DIV(hours, 60*60); DIV(minutes, 60); #undef DIV #undef PRINT #define PRINT(x) if (x) out += " " + IntStr64(x) + " " #x; PRINT(years); PRINT(months); PRINT(days); PRINT(hours); PRINT(minutes); #undef PRINT return out; } #if defined flagMSC10 || defined flagMSC11 // For upp version 9251 and older struct AtomicInt { volatile Atomic value; AtomicInt() : value(0) {} AtomicInt(int i) : value(i) {} AtomicInt(const AtomicInt& ai) : value(ai.value) {} operator int() {return AtomicRead(value);} int operator = (int i) {AtomicWrite(value, i); return i;} int operator++(int) {return AtomicXAdd(value, +1);} int operator--(int) {return AtomicXAdd(value, -1);} }; #else #include <atomic> struct AtomicInt { std::atomic<int> value; AtomicInt() {value = 0;} AtomicInt(int i) {value = i;} AtomicInt(const AtomicInt& ai) {value = (int)ai.value;} operator int() {return value;} int operator = (int i) {value = i; return i;} int operator++(int) {return value++;} int operator--(int) {return value--;} }; #endif struct FakeAtomicInt : Moveable<FakeAtomicInt> { SpinLock lock; int value; FakeAtomicInt() : value(0) {} FakeAtomicInt(int i) : value(i) {} FakeAtomicInt(const AtomicInt& ai) : value(ai.value) {} operator int() {return value;} int operator = (int i) { lock.Enter(); value = i; lock.Leave(); return i; } int operator++(int) { lock.Enter(); int i = value++; lock.Leave(); return i; } int operator--(int) { lock.Enter(); int i = value--; lock.Leave(); return i; } int Get() const {return value;} }; inline String AppendPosixFilename(const String& a, const String& b) { if (a.Right(1) == "/") return a + b; else return a + "/" + b; } #endif
/*************************************************************************************************** * Copyright (c) 2017-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/ #pragma once #include "cutlass/cutlass.h" #include "cutlass/complex.h" namespace cutlass { namespace transform { namespace thread { namespace UnaryTransform { struct Identity; ///< None (i.e., identity) struct Conjugate; ///< Complex conjugate } /// Element-wise unary operator that transforms one element of a fragment at a time template< typename FragmentIn, ///< Input Fragment typename FragmentOut,///< Output Fragment typename Transform> ///< Unary transform operator class UnaryOp { public: CUTLASS_DEVICE static FragmentOut execute(FragmentIn &in) { static_assert(FragmentIn::kElements == FragmentOut::kElements, "Number of elements must match."); static_assert(std::is_same<Transform, UnaryTransform::Identity>::value || std::is_same<Transform, UnaryTransform::Conjugate>::value, "Unary Operator not supported."); FragmentOut out; if( std::is_same<Transform, UnaryTransform::Identity>::value ) { CUTLASS_PRAGMA_UNROLL for(int i=0; i < FragmentIn::kElements; ++i){ out[i] = static_cast<typename FragmentOut::Element>(in[i]); } } else if( std::is_same<Transform, UnaryTransform::Conjugate>::value ) { for(int i=0; i < FragmentIn::kElements; ++i){ out[i] = conj(static_cast<typename FragmentOut::Element>(in[i])); } } return out; } }; template<typename FragmentIn, typename Transform> class UnaryOp<FragmentIn, FragmentIn, Transform> { public: CUTLASS_DEVICE static FragmentIn execute(FragmentIn &in) { static_assert(std::is_same<Transform, UnaryTransform::Identity>::value || std::is_same<Transform, UnaryTransform::Conjugate>::value, "Unary Operator not supported."); if( std::is_same<Transform, UnaryTransform::Identity>::value ) { return in; } else if( std::is_same<Transform, UnaryTransform::Conjugate>::value ) { for(int i=0; i < FragmentIn::kElements; ++i){ in[i] = conj(in[i]); } } return in; } }; } } }
// 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 CHROMEOS_DBUS_IMAGE_LOADER_CLIENT_H_ #define CHROMEOS_DBUS_IMAGE_LOADER_CLIENT_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/component_export.h" #include "base/files/file_path.h" #include "base/macros.h" #include "chromeos/dbus/dbus_client.h" #include "chromeos/dbus/dbus_method_call_status.h" namespace chromeos { // ImageLoaderClient is used to communicate with the ImageLoader service, which // registers and loads component updates on Chrome OS. class COMPONENT_EXPORT(CHROMEOS_DBUS) ImageLoaderClient : public DBusClient { public: ~ImageLoaderClient() override; // Registers a component by copying from |component_folder_abs_path| into its // internal storage, if and only if, the component passes verification. virtual void RegisterComponent(const std::string& name, const std::string& version, const std::string& component_folder_abs_path, DBusMethodCallback<bool> callback) = 0; // Mounts a component given the |name| and return the mount point (if call is // successful). virtual void LoadComponent(const std::string& name, DBusMethodCallback<std::string> callback) = 0; // Mounts a component given the |name| and install path |path|, then returns // the mount point (if call is successful). virtual void LoadComponentAtPath( const std::string& name, const base::FilePath& path, DBusMethodCallback<base::FilePath> callback) = 0; // Requests the currently registered version of the given component |name|. virtual void RequestComponentVersion( const std::string& name, DBusMethodCallback<std::string> callback) = 0; // Removes a component and returns true (if call is successful). virtual void RemoveComponent(const std::string& name, DBusMethodCallback<bool> callback) = 0; // Unmounts all mount points given component |name|. virtual void UnmountComponent(const std::string& name, DBusMethodCallback<bool> callback) = 0; // Factory function, creates a new instance and returns ownership. // For normal usage, access the singleton via DBusThreadManager::Get(). static std::unique_ptr<ImageLoaderClient> Create(); protected: // Create() should be used instead. ImageLoaderClient(); private: DISALLOW_COPY_AND_ASSIGN(ImageLoaderClient); }; } // namespace chromeos #endif // CHROMEOS_DBUS_IMAGE_LOADER_CLIENT_H_
/* * AppContext.h * * Created on: Apr 9, 2012 * Author: rgreen */ #ifndef APPCONTEXT_H_ #define APPCONTEXT_H_ #include <batterytech/Context.h> using namespace BatteryTech; class HelloWorldApp; class AppContext : public Context { public: AppContext(GraphicsConfiguration *gConfig); virtual ~AppContext(); HelloWorldApp *app; }; #endif /* GAMECONTEXT_H_ */
// 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 TOOLS_GN_PARSE_NODE_VALUE_ADAPTER_H_ #define TOOLS_GN_PARSE_NODE_VALUE_ADAPTER_H_ #include "base/macros.h" #include "gn/value.h" class ParseNode; // Provides a means to convert a parse node to a value without causing a copy // in the common case of an "Identifier" node. Normally to get a value from a // parse node you have to call Execute(), and when an identifier is executed // it just returns the current value of itself as a copy. But some variables // are very large (lists of many strings for example). // // The reason you might not want to do this is that in the case of an // identifier where the copy is optimized away, the origin will still be the // original value. The result can be confusing because it will reference the // original value rather than the place where the value was dereferenced, e.g. // for a function call. The InitForType() function will verify type information // and will fix up the origin so it's not confusing. class ParseNodeValueAdapter { public: ParseNodeValueAdapter(); ~ParseNodeValueAdapter(); const Value& get() { if (ref_) return *ref_; return temporary_; } // Initializes the adapter for the result of the given expression. Returns // truen on success. bool Init(Scope* scope, const ParseNode* node, Err* err); // Like Init() but additionally verifies that the type of the result matches. bool InitForType(Scope* scope, const ParseNode* node, Value::Type type, Err* err); private: // Holds either a reference to an existing item, or a temporary as a copy. // If ref is non-null, it's valid, otherwise the temporary is used. const Value* ref_; Value temporary_; DISALLOW_COPY_AND_ASSIGN(ParseNodeValueAdapter); }; #endif // TOOLS_GN_PARSE_NODE_VALUE_ADAPTER_H_
// 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. #ifndef COMPONENTS_EMBEDDER_SUPPORT_USER_AGENT_UTILS_H_ #define COMPONENTS_EMBEDDER_SUPPORT_USER_AGENT_UTILS_H_ #include <string> #include "build/build_config.h" #include "components/prefs/pref_service.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" namespace blink { struct UserAgentMetadata; } namespace content { class WebContents; } namespace embedder_support { // Returns the product used in building the user-agent. std::string GetProduct(); // Returns the user agent string for Chrome. If the ReduceUserAgent // feature is enabled, this will return |GetReducedUserAgent| std::string GetUserAgent(); // Returns the reduced user agent string for Chrome. std::string GetReducedUserAgent(); // Returns UserAgentMetadata per the default policy. // This override is currently used in fuchsia, where the enterprise policy // is not relevant. blink::UserAgentMetadata GetUserAgentMetadata(); // Return UserAgentMetadata, potentially overridden by policy. // Note that this override is likely to be removed once an enterprise // escape hatch is no longer needed. See https://crbug.com/1261908. blink::UserAgentMetadata GetUserAgentMetadata(PrefService* local_state); blink::UserAgentBrandList GenerateBrandVersionList( int seed, absl::optional<std::string> brand, std::string major_version, absl::optional<std::string> maybe_greasey_brand, absl::optional<std::string> maybe_greasey_version, bool enable_updated_grease_by_policy); blink::UserAgentBrandVersion GetGreasedUserAgentBrandVersion( std::vector<int> permuted_order, int seed, absl::optional<std::string> maybe_greasey_brand, absl::optional<std::string> maybe_greasey_version, bool enable_updated_grease_by_policy); #if defined(OS_ANDROID) // This sets a user agent string to simulate a desktop user agent on mobile. // If |override_in_new_tabs| is true, and the first navigation in the tab is // renderer initiated, then is-overriding-user-agent is set to true for the // NavigationEntry. void SetDesktopUserAgentOverride(content::WebContents* web_contents, const blink::UserAgentMetadata& metadata, bool override_in_new_tabs); #endif #if defined(OS_WIN) int GetHighestKnownUniversalApiContractVersionForTesting(); #endif // defined(OS_WIN) } // namespace embedder_support #endif // COMPONENTS_EMBEDDER_SUPPORT_USER_AGENT_UTILS_H_
// 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. #ifndef WebLocalFrame_h #define WebLocalFrame_h #include "WebFrame.h" #include "public/platform/WebThread.h" namespace blink { enum class WebAppBannerPromptReply; enum class WebSandboxFlags; class WebAutofillClient; class WebContentSettingsClient; class WebFrameClient; class WebScriptExecutionCallback; struct WebPrintPresetOptions; // Interface for interacting with in process frames. This contains methods that // require interacting with a frame's document. // FIXME: Move lots of methods from WebFrame in here. class WebLocalFrame : public WebFrame { public: // Creates a WebFrame. Delete this WebFrame by calling WebFrame::close(). // It is valid to pass a null client pointer. BLINK_EXPORT static WebLocalFrame* create(WebFrameClient*); // Returns the WebFrame associated with the current V8 context. This // function can return 0 if the context is associated with a Document that // is not currently being displayed in a Frame. BLINK_EXPORT static WebLocalFrame* frameForCurrentContext(); // Returns the frame corresponding to the given context. This can return 0 // if the context is detached from the frame, or if the context doesn't // correspond to a frame (e.g., workers). BLINK_EXPORT static WebLocalFrame* frameForContext(v8::Local<v8::Context>); // Returns the frame inside a given frame or iframe element. Returns 0 if // the given element is not a frame, iframe or if the frame is empty. BLINK_EXPORT static WebLocalFrame* fromFrameOwnerElement(const WebElement&); // Initialization --------------------------------------------------------- // Used when we might swap from a remote frame to a local frame. // Creates a provisional, semi-attached frame that will be fully // swapped into the frame tree if it commits. // FIXME(alexmos): Remove when Chromium side is updated to pass name and sandbox flags. virtual void initializeToReplaceRemoteFrame(WebRemoteFrame*) = 0; virtual void initializeToReplaceRemoteFrame(WebRemoteFrame*, const WebString& name, WebSandboxFlags) = 0; virtual void setAutofillClient(WebAutofillClient*) = 0; virtual WebAutofillClient* autofillClient() = 0; // Navigation Ping -------------------------------------------------------- virtual void sendPings(const WebNode& linkNode, const WebURL& destinationURL) = 0; // Navigation State ------------------------------------------------------- // Returns true if the current frame's load event has not completed. virtual bool isLoading() const = 0; // Returns true if any resource load is currently in progress. Exposed // primarily for use in layout tests. You probably want isLoading() // instead. virtual bool isResourceLoadInProgress() const = 0; // Navigation Transitions ------------------------------------------------- virtual void addStyleSheetByURL(const WebString& url) = 0; virtual void navigateToSandboxedMarkup(const WebData& markup) = 0; // Orientation Changes ---------------------------------------------------- // Notify the frame that the screen orientation has changed. virtual void sendOrientationChangeEvent() = 0; // Printing ------------------------------------------------------------ // Returns true on success and sets the out parameter to the print preset options for the document. virtual bool getPrintPresetOptionsForPlugin(const WebNode&, WebPrintPresetOptions*) = 0; // Scripting -------------------------------------------------------------- // Executes script in the context of the current page and returns the value // that the script evaluated to with callback. Script execution can be // suspend. virtual void requestExecuteScriptAndReturnValue(const WebScriptSource&, bool userGesture, WebScriptExecutionCallback*) = 0; // worldID must be > 0 (as 0 represents the main world). // worldID must be < EmbedderWorldIdLimit, high number used internally. virtual void requestExecuteScriptInIsolatedWorld( int worldID, const WebScriptSource* sourceIn, unsigned numSources, int extensionGroup, bool userGesture, WebScriptExecutionCallback*) = 0; // Run the task when the context of the current page is not suspended // otherwise run it on context resumed. // Method takes ownership of the passed task. virtual void requestRunTask(WebThread::Task*) const = 0; // Associates an isolated world with human-readable name which is useful for // extension debugging. virtual void setIsolatedWorldHumanReadableName(int worldID, const WebString&) = 0; // Selection -------------------------------------------------------------- // Moves the selection extent point. This function does not allow the // selection to collapse. If the new extent is set to the same position as // the current base, this function will do nothing. virtual void moveRangeSelectionExtent(const WebPoint&, TextGranularity = CharacterGranularity) = 0; // Content Settings ------------------------------------------------------- virtual void setContentSettingsClient(WebContentSettingsClient*) = 0; // App banner ------------------------------------------------------------- // Request to show an application install banner for the given |platform|. // The implementation can request the embedder to cancel the call by setting // |cancel| to true. virtual void willShowInstallBannerPrompt(const WebString& platform, WebAppBannerPromptReply*) = 0; }; } // namespace blink #endif // WebLocalFrame_h
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53a.c Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml Template File: source-sinks-53a.tmpl.c */ /* * @description * CWE: 761 Free Pointer not at Start of Buffer * BadSource: fixed_string Initialize data to be a fixed string * Sinks: * GoodSink: free() memory correctly at the start of the buffer * BadSink : free() memory not at the start of the buffer * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> #define BAD_SOURCE_FIXED_STRING L"Fixed String" /* MAINTENANCE NOTE: This string must contain the SEARCH_CHAR */ #define SEARCH_CHAR L'S' #ifndef OMITBAD /* bad function declaration */ void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53b_badSink(wchar_t * data); void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53_bad() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* POTENTIAL FLAW: Initialize data to be a fixed string that contains the search character in the sinks */ wcscpy(data, BAD_SOURCE_FIXED_STRING); CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53b_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53b_goodB2GSink(wchar_t * data); /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* POTENTIAL FLAW: Initialize data to be a fixed string that contains the search character in the sinks */ wcscpy(data, BAD_SOURCE_FIXED_STRING); CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53b_goodB2GSink(data); } void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53_good() { goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_53_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* * ClientConnectionState.h * * Created on: Nov 2, 2012 * Author: Mitchell Wills */ #ifndef CLIENTCONNECTIONSTATE_H_ #define CLIENTCONNECTIONSTATE_H_ class ClientConnectionState; class ClientConnectionState_Error; class ClientConnectionState_ProtocolUnsuppotedByServer; #include <exception> #include "networktables2/connection/NetworkTableConnection.h" /** * Represents a state that the client is in * * @author Mitchell * */ class ClientConnectionState { public: /** * indicates that the client is disconnected from the server */ static ClientConnectionState DISCONNECTED_FROM_SERVER; /** * indicates that the client is connected to the server but has not yet begun communication */ static ClientConnectionState CONNECTED_TO_SERVER; /** * represents that the client has sent the hello to the server and is waiting for a response */ static ClientConnectionState SENT_HELLO_TO_SERVER; /** * represents that the client is now in sync with the server */ static ClientConnectionState IN_SYNC_WITH_SERVER; private: const char* name; protected: ClientConnectionState(const char* name); public: virtual const char* toString(); }; /** * Represents that a client received a message from the server indicating that the client's protocol revision is not supported by the server * @author Mitchell * */ class ClientConnectionState_ProtocolUnsuppotedByServer : public ClientConnectionState{ private: const ProtocolVersion serverVersion; public: /** * Create a new protocol unsupported state * @param serverVersion */ ClientConnectionState_ProtocolUnsuppotedByServer(ProtocolVersion serverVersion); /** * @return the protocol version that the server reported it supports */ ProtocolVersion getServerVersion(); const char* toString(); }; /** * Represents that the client is in an error state * * @author Mitchell * */ class ClientConnectionState_Error : public ClientConnectionState{ private: std::exception& e; char msg[100]; public: /** * Create a new error state * @param e */ ClientConnectionState_Error(std::exception& e); virtual ~ClientConnectionState_Error(); /** * @return the exception that caused the client to enter an error state */ std::exception& getException(); virtual const char* toString(); }; #endif /* CLIENTCONNECTIONSTATE_H_ */
#pragma once #include "camera.h" #include <Eigen/Dense> namespace radialpose { void refinement_dist(const Eigen::Matrix<double, 2, Eigen::Dynamic> &x, const Eigen::Matrix<double, 3, Eigen::Dynamic> &X, radialpose::Camera &p, int Np, int Nd); void refinement_undist(const Eigen::Matrix<double, 2, Eigen::Dynamic> &x, const Eigen::Matrix<double, 3, Eigen::Dynamic> &X, radialpose::Camera &p, int Np, int Nd); }
// 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. #ifndef IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_ALERT_FACTORY_H_ #define IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_ALERT_FACTORY_H_ #import <UIKit/UIKit.h> @class AlertCoordinator; class Browser; @class ContentSuggestionsItem; @class ContentSuggestionsMostVisitedItem; @protocol ContentSuggestionsGestureCommands; // Factory for AlertCoordinators for ContentSuggestions. @interface ContentSuggestionsAlertFactory : NSObject // Returns an AlertCoordinator for a suggestions |item| with the indexPath // |indexPath|. The alert will be presented on the |viewController| at the // |touchLocation|, in the coordinates of the |viewController|'s collectionView. // The |commandHandler| will receive callbacks when the user chooses one of the // options displayed by the alert. + (AlertCoordinator*) alertCoordinatorForSuggestionItem:(ContentSuggestionsItem*)item onViewController: (UICollectionViewController*)viewController atPoint:(CGPoint)touchLocation atIndexPath:(NSIndexPath*)indexPath readLaterAction:(BOOL)readLaterAction commandHandler: (id<ContentSuggestionsGestureCommands>)commandHandler browser:(Browser*)browser; // Same as above but for a MostVisited item. + (AlertCoordinator*) alertCoordinatorForMostVisitedItem:(ContentSuggestionsMostVisitedItem*)item onViewController: (UICollectionViewController*)viewController withBrowser:(Browser*)browser atPoint:(CGPoint)touchLocation atIndexPath:(NSIndexPath*)indexPath commandHandler:(id<ContentSuggestionsGestureCommands>) commandHandler; @end #endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_ALERT_FACTORY_H_
#import "ABI42_0_0RNSScreen.h" @interface ABI42_0_0RNSScreenWindowTraits : NSObject + (void)updateWindowTraits; + (void)assertViewControllerBasedStatusBarAppearenceSet; + (void)updateStatusBarAppearance; + (void)enforceDesiredDeviceOrientation; #if !TARGET_OS_TV + (UIStatusBarStyle)statusBarStyleForRNSStatusBarStyle:(ABI42_0_0RNSStatusBarStyle)statusBarStyle; + (UIInterfaceOrientation)defaultOrientationForOrientationMask:(UIInterfaceOrientationMask)orientationMask; + (UIInterfaceOrientation)interfaceOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation; + (UIInterfaceOrientationMask)maskFromOrientation:(UIInterfaceOrientation)orientation; #endif @end
// Copyright 2015 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_FAVICON_CONTENT_CONTENT_FAVICON_DRIVER_H_ #define COMPONENTS_FAVICON_CONTENT_CONTENT_FAVICON_DRIVER_H_ #include "components/favicon/core/favicon_driver_impl.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "url/gurl.h" namespace content { struct FaviconStatus; struct FaviconURL; class WebContents; } namespace favicon { // ContentFaviconDriver is an implementation of FaviconDriver that listens to // WebContents events to start download of favicons and to get informed when the // favicon download has completed. class ContentFaviconDriver : public content::WebContentsObserver, public content::WebContentsUserData<ContentFaviconDriver>, public FaviconDriverImpl { public: static void CreateForWebContents(content::WebContents* web_contents, FaviconService* favicon_service, history::HistoryService* history_service, bookmarks::BookmarkModel* bookmark_model); // Returns the current tab's favicon URLs. If this is empty, // DidUpdateFaviconURL has not yet been called for the current navigation. const std::vector<content::FaviconURL>& favicon_urls() const { return favicon_urls_; } // Saves the favicon for the last committed navigation entry to the thumbnail // database. void SaveFavicon(); // FaviconDriver implementation. gfx::Image GetFavicon() const override; bool FaviconIsValid() const override; int StartDownload(const GURL& url, int max_bitmap_size) override; bool IsOffTheRecord() override; GURL GetActiveURL() override; void SetActiveFaviconValidity(bool valid) override; GURL GetActiveFaviconURL() override; void SetActiveFaviconURL(const GURL& url) override; void SetActiveFaviconImage(const gfx::Image& image) override; protected: ContentFaviconDriver(content::WebContents* web_contents, FaviconService* favicon_service, history::HistoryService* history_service, bookmarks::BookmarkModel* bookmark_model); ~ContentFaviconDriver() override; private: friend class content::WebContentsUserData<ContentFaviconDriver>; // FaviconDriver implementation. void NotifyFaviconUpdated(bool icon_url_changed) override; // content::WebContentsObserver implementation. void DidUpdateFaviconURL( const std::vector<content::FaviconURL>& candidates) override; void DidStartNavigationToPendingEntry( const GURL& url, content::NavigationController::ReloadType reload_type) override; void DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) override; // Returns the active navigation entry's favicon. content::FaviconStatus& GetFaviconStatus(); GURL bypass_cache_page_url_; std::vector<content::FaviconURL> favicon_urls_; DISALLOW_COPY_AND_ASSIGN(ContentFaviconDriver); }; } // namespace favicon #endif // COMPONENTS_FAVICON_CONTENT_CONTENT_FAVICON_DRIVER_H_
// 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. #ifndef ASH_CAPTURE_MODE_CAPTURE_MODE_MENU_GROUP_H_ #define ASH_CAPTURE_MODE_CAPTURE_MODE_MENU_GROUP_H_ #include <string> #include <vector> #include "ash/ash_export.h" #include "ash/capture_mode/capture_mode_session_focus_cycler.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/button/button.h" namespace gfx { struct VectorIcon; } // namespace gfx namespace ash { class CaptureModeMenuHeader; class CaptureModeMenuItem; class CaptureModeOption; // Defines a view that groups together related capture mode settings in an // independent section in the settings menu. Each group has a header icon and a // header label. class ASH_EXPORT CaptureModeMenuGroup : public views::View { public: METADATA_HEADER(CaptureModeMenuGroup); class Delegate { public: // Called when user selects an option. virtual void OnOptionSelected(int option_id) const = 0; // Called to determine if an option with the given `option_id` is selected. virtual bool IsOptionChecked(int option_id) const = 0; // Called to determine if an option with the given `option_id` is enabled. virtual bool IsOptionEnabled(int option_id) const = 0; protected: virtual ~Delegate() = default; }; CaptureModeMenuGroup(Delegate* delegate, const gfx::VectorIcon& header_icon, std::u16string header_label); CaptureModeMenuGroup(const CaptureModeMenuGroup&) = delete; CaptureModeMenuGroup& operator=(const CaptureModeMenuGroup&) = delete; ~CaptureModeMenuGroup() override; // Adds an option which has text and a checked image icon to the the menu // group. When the option is selected, its checked icon is visible. Otherwise // its checked icon is invisible. One and only one option's checked icon is // visible all the time. void AddOption(std::u16string option_label, int option_id); // If an option with the given |option_id| exists, it will be updated with the // given |option_label|. Otherwise, a new option will be added. void AddOrUpdateExistingOption(std::u16string option_label, int option_id); // Refreshes which options are currently selected and showing checked icons // next to their labels. This calls back into the |Delegate| to check each // option's selection state. void RefreshOptionsSelections(); // Removes an option with the given |option_id| if it exists. Does nothing // otherwise. void RemoveOptionIfAny(int option_id); // Adds a menu item which has text to the menu group. Each menu item can have // its own customized behavior. For example, file save menu group's menu item // will open a folder window for user to select a new folder to save the // captured filed on click/press. void AddMenuItem(views::Button::PressedCallback callback, std::u16string item_label); // Returns true if the option with the given |option_id| is checked, if such // option exists. bool IsOptionChecked(int option_id) const; // Appends the enabled items from `options_` and `menu_items_` to the given // `highlightable_items`. void AppendHighlightableItems( std::vector<CaptureModeSessionFocusCycler::HighlightableView*>& highlightable_items); // For tests only. views::View* GetOptionForTesting(int option_id); views::View* GetSelectFolderMenuItemForTesting(); std::u16string GetOptionLabelForTesting(int option_id) const; private: friend class CaptureModeAdvancedSettingsTestApi; // Returns the option whose ID is |option_id|, and nullptr if no such option // exists. CaptureModeOption* GetOptionById(int option_id) const; // This is the callback function on option click. It will select the // clicked/pressed button, and unselect any previously selected button. void HandleOptionClick(int option_id); // CaptureModeAdvancedSettingsView is the |delegate_| here. It's owned by // its views hierarchy. const Delegate* const delegate_; // The menu header of `this`. It's owned by the views hierarchy. CaptureModeMenuHeader* menu_header_; // Options added via calls "AddOption()". Options are owned by theirs views // hierarchy. std::vector<CaptureModeOption*> options_; // It's a container view for |options_|. It's owned by its views hierarchy. // We need it for grouping up options. For example, when user selects a custom // folder, we need to add it to the end of the options instead of adding it // after the menu item. views::View* options_container_; // Menu items added by calling AddMenuItem(). std::vector<CaptureModeMenuItem*> menu_items_; }; } // namespace ash #endif // ASH_CAPTURE_MODE_CAPTURE_MODE_MENU_GROUP_H_
// Copyright 2015 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. // Singly or multiply-included shared traits file depending on circumstances. // This allows the use of printing IPC serialization macros in more than one IPC // message file. #ifndef COMPONENTS_PRINTING_COMMON_PRINTING_PARAM_TRAITS_MACROS_H_ #define COMPONENTS_PRINTING_COMMON_PRINTING_PARAM_TRAITS_MACROS_H_ #include "ipc/ipc_message_macros.h" #include "printing/mojom/print.mojom.h" #include "printing/print_job_constants.h" // TODO(dgn) move all those macros back to // components/printing/common/print_messages.h when they can be handled by a // single generator. (main tracking bug: crbug.com/450822) IPC_ENUM_TRAITS_MAX_VALUE(printing::MarginType, printing::MARGIN_TYPE_LAST) IPC_ENUM_TRAITS_MIN_MAX_VALUE(printing::mojom::DuplexMode, printing::mojom::DuplexMode::kUnknownDuplexMode, printing::mojom::DuplexMode::kShortEdge) #endif // COMPONENTS_PRINTING_COMMON_PRINTING_PARAM_TRAITS_MACROS_H_
#pragma once #include "INetworkLayer.h" namespace UAFML { class ConvolutionLayer : public INetworkLayer { public: ConvolutionLayer(const af::dim4 &size) : INetworkLayer(size) {} virtual ~ConvolutionLayer(); virtual bool ForwardPropagate(af::array &values, const af::array &weights); virtual af::array BackPropagate(af::array &error, const af::array &weights); virtual double CalculateCost(const af::array &output, const af::array &truth); virtual af::array CalculateError(af::array &values, const af::array &truth, const af::array &weights); protected: af::array _input; }; }
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef InspectorLayerTreeAgent_h #define InspectorLayerTreeAgent_h #include "core/CoreExport.h" #include "core/inspector/InspectorBaseAgent.h" #include "platform/Timer.h" #include "platform/inspector_protocol/TypeBuilder.h" #include "wtf/Noncopyable.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" #include "wtf/text/WTFString.h" namespace blink { class GraphicsContext; class GraphicsLayer; class InspectedFrames; class LayoutObject; class LayoutRect; class PictureSnapshot; class PaintLayer; class PaintLayerCompositor; class CORE_EXPORT InspectorLayerTreeAgent final : public InspectorBaseAgent<InspectorLayerTreeAgent, protocol::Frontend::LayerTree>, public protocol::Dispatcher::LayerTreeCommandHandler { WTF_MAKE_NONCOPYABLE(InspectorLayerTreeAgent); public: static PassOwnPtrWillBeRawPtr<InspectorLayerTreeAgent> create(InspectedFrames* inspectedFrames) { return adoptPtrWillBeNoop(new InspectorLayerTreeAgent(inspectedFrames)); } ~InspectorLayerTreeAgent() override; DECLARE_VIRTUAL_TRACE(); void restore() override; // Called from InspectorController void willAddPageOverlay(const GraphicsLayer*); void didRemovePageOverlay(const GraphicsLayer*); // Called from InspectorInstrumentation void layerTreeDidChange(); void didPaint(LayoutObject*, const GraphicsLayer*, GraphicsContext&, const LayoutRect&); // Called from the front-end. void enable(ErrorString*) override; void disable(ErrorString*) override; void compositingReasons(ErrorString*, const String& layerId, OwnPtr<protocol::Array<String>>* compositingReasons) override; void makeSnapshot(ErrorString*, const String& layerId, String* snapshotId) override; void loadSnapshot(ErrorString*, PassOwnPtr<protocol::Array<protocol::LayerTree::PictureTile>> tiles, String* snapshotId) override; void releaseSnapshot(ErrorString*, const String& snapshotId) override; void profileSnapshot(ErrorString*, const String& snapshotId, const Maybe<int>& minRepeatCount, const Maybe<double>& minDuration, const Maybe<protocol::DOM::Rect>& clipRect, OwnPtr<protocol::Array<protocol::Array<double>>>* timings) override; void replaySnapshot(ErrorString*, const String& snapshotId, const Maybe<int>& fromStep, const Maybe<int>& toStep, const Maybe<double>& scale, String* dataURL) override; void snapshotCommandLog(ErrorString*, const String& snapshotId, OwnPtr<protocol::Array<protocol::DictionaryValue>>* commandLog) override; // Called by other agents. PassOwnPtr<protocol::Array<protocol::LayerTree::Layer>> buildLayerTree(); private: static unsigned s_lastSnapshotId; explicit InspectorLayerTreeAgent(InspectedFrames*); GraphicsLayer* rootGraphicsLayer(); PaintLayerCompositor* paintLayerCompositor(); GraphicsLayer* layerById(ErrorString*, const String& layerId); const PictureSnapshot* snapshotById(ErrorString*, const String& snapshotId); typedef HashMap<int, int> LayerIdToNodeIdMap; void buildLayerIdToNodeIdMap(PaintLayer*, LayerIdToNodeIdMap&); void gatherGraphicsLayers(GraphicsLayer*, HashMap<int, int>& layerIdToNodeIdMap, OwnPtr<protocol::Array<protocol::LayerTree::Layer>>&, bool hasWheelEventHandlers, int scrollingRootLayerId); int idForNode(Node*); RawPtrWillBeMember<InspectedFrames> m_inspectedFrames; Vector<int, 2> m_pageOverlayLayerIds; typedef HashMap<String, RefPtr<PictureSnapshot>> SnapshotById; SnapshotById m_snapshotById; }; } // namespace blink #endif // !defined(InspectorLayerTreeAgent_h)
// 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 COMPONENTS_DOWNLOAD_INTERNAL_BACKGROUND_SERVICE_NOOP_STORE_H_ #define COMPONENTS_DOWNLOAD_INTERNAL_BACKGROUND_SERVICE_NOOP_STORE_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/download/internal/background_service/store.h" namespace download { struct Entry; // A Store implementation that doesn't do anything but honors the interface // requirements. Used in incognito mode without any database IO. class NoopStore : public Store { public: NoopStore(); NoopStore(const NoopStore&) = delete; NoopStore& operator=(const NoopStore&) = delete; ~NoopStore() override; // Store implementation. bool IsInitialized() override; void Initialize(InitCallback callback) override; void HardRecover(StoreCallback callback) override; void Update(const Entry& entry, StoreCallback callback) override; void Remove(const std::string& guid, StoreCallback callback) override; private: void OnInitFinished(InitCallback callback); // Whether or not this Store is 'initialized.' Just gets set to |true| once // Initialize() is called. bool initialized_; base::WeakPtrFactory<NoopStore> weak_ptr_factory_{this}; }; } // namespace download #endif // COMPONENTS_DOWNLOAD_INTERNAL_BACKGROUND_SERVICE_NOOP_STORE_H_
#include "cmdqueue.h" #include "config.h" #include "state.h" static CommandStruct queue[CQ_LENGTH]; //if both indexes are the same, the queue is assumed to be empty. //Must never be completely full static int readIdx; //next index to be read static int writeIdx; //next index to be written static uint32_t lastTransactionId; void* anothermemmove (void* s1, const void* s2, size_t n) { size_t i; if (s1 < s2) { for (i=0; i<n; i++) { ((uint8_t*)s1)[i] = ((const uint8_t*)s2)[i]; } } else { i = n; while (i > 0) { i--; ((uint8_t*)s1)[i] = ((const uint8_t*)s2)[i]; } } return s1; } void CQ_Init() { readIdx = 0; writeIdx = 0; lastTransactionId = 0; } bool CQ_GetCommand() { disableInterrupts(); bool ok = (readIdx != writeIdx); if (ok) { anothermemmove(&currentCommand, &(queue[readIdx]), sizeof(CommandStruct)); currentCommandTicks = 0; readIdx = (readIdx+1) % CQ_LENGTH; } enableInterrupts(); return ok; } bool CQ_AddCommand(CommandStruct* cmd) { bool ok = true; disableInterrupts(); if (cmd->command > IMMEDIATE_SEPARATOR) { //Queued command int filled = writeIdx - readIdx; if (filled < 0) filled += CQ_LENGTH; int avail = CQ_LENGTH - filled - 1; if (avail > 0) { anothermemmove(&(queue[writeIdx]), cmd, sizeof(CommandStruct)); writeIdx = (writeIdx+1) % CQ_LENGTH; } else ok = false; } else { //immediate command anothermemmove(&currentCommand, cmd, sizeof(CommandStruct)); currentCommandTicks = 0; readIdx = 0; writeIdx = 0; } lastTransactionId = cmd->transactionId; enableInterrupts(); return ok; } bool CQ_ReadAvail() { disableInterrupts(); bool avail = (readIdx != writeIdx); enableInterrupts(); return avail; } int CQ_EmptySlots(uint32_t* outLastTransactionId) { disableInterrupts(); int filled = writeIdx - readIdx; if (filled < 0) filled += CQ_LENGTH; int avail = CQ_LENGTH - filled - 1; if (outLastTransactionId) *outLastTransactionId = lastTransactionId; enableInterrupts(); return avail; } void CQ_Clear() { disableInterrupts(); readIdx = 0; writeIdx = 0; enableInterrupts(); }
/****************************************************************************** * BRICS_3D - 3D Perception and Modeling Library * Copyright (c) 2011, GPS GmbH * * Author: Pinaki Sunil Banerjee * * * This software is published under a dual-license: GNU Lesser General Public * License LGPL 2.1 and Modified BSD license. The dual-license implies that * users of this code may choose which terms they prefer. * * This program 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 Lesser General Public License LGPL and the BSD license for * more details. * ******************************************************************************/ #ifndef BRICS_3D_OBJECTMODELCYLINDER_H_ #define BRICS_3D_OBJECTMODELCYLINDER_H_ #include "brics_3d/algorithm/segmentation/objectModels/IObjectModelUsingNormals.h" namespace brics_3d { /** * @note The implementation is reusing the object model implementation in ROS:PCl * @ingroup segmentation */ class ObjectModelCylinder : public IObjectModelUsingNormals { public: ObjectModelCylinder(){}; virtual ~ObjectModelCylinder(){}; void getSamples (int &iterations, std::vector<int> &samples); bool computeModelCoefficients (const std::vector<int> &samples, Eigen::VectorXd &model_coefficients); void optimizeModelCoefficients (const std::vector<int> &inliers, const Eigen::VectorXd &model_coefficients, Eigen::VectorXd &optimized_coefficients); void getDistancesToModel (const Eigen::VectorXd &model_coefficients, std::vector<double> &distances); void selectWithinDistance (const Eigen::VectorXd &model_coefficients, double threshold, std::vector<int> &inliers); void getInlierDistance (std::vector<int> &inliers, const Eigen::VectorXd &model_coefficients, std::vector<double> &distances); void projectPoints (const std::vector<int> &inliers, const Eigen::VectorXd &model_coefficients, PointCloud3D* projectedPointCloud); bool doSamplesVerifyModel (const std::set<int> &indices, const Eigen::VectorXd &model_coefficients, double threshold); void computeRandomModel (int &iterations, Eigen::VectorXd &model_coefficients, bool &isDegenerate, bool &modelFound); inline int getNumberOfSamplesRequired(){return 3;}; protected: /** @brief Get the distance from a point to a line (represented by a point and a direction) * @param pt a point * @param model_coefficients the line coefficients (a point on the line, line direction) */ double pointToLineDistance (const Eigen::Vector4d &pt, const Eigen::VectorXd &model_coefficients); /** @brief Get the distance from a point to a line (represented by a point and a direction) * @param pt a point * @param line_pt a point on the line (make sure that line_pt[3] = 0 as there are no internal checks!) * @param line_dir the line direction */ double pointToLineDistance (const Eigen::Vector4d &pt, const Eigen::Vector4d &line_pt, const Eigen::Vector4d &line_dir); /** @brief Project a point onto a line given by a point and a direction vector * @param pt the input point to project * @param line_pt the point on the line (make sure that line_pt[3] = 0 as there are no internal checks!) * @param line_dir the direction of the line (make sure that line_dir[3] = 0 as there are no internal checks!) * @param pt_proj the resultant projected point */ inline void projectPointToLine (const Eigen::Vector4d &pt, const Eigen::Vector4d &line_pt, const Eigen::Vector4d &line_dir, Eigen::Vector4d &pt_proj) { double k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir); // Calculate the projection of the point on the line pt_proj = line_pt + k * line_dir; } /** @brief Project a point onto a cylinder given by its model coefficients (point_on_axis, axis_direction, * cylinder_radius_R) * @param pt the input point to project * @param model_coefficients the coefficients of the cylinder (point_on_axis, axis_direction, cylinder_radius_R) * @param pt_proj the resultant projected point */ inline void projectPointToCylinder(const Eigen::Vector4d &pt, const Eigen::VectorXd &model_coefficients, Eigen::Vector4d &pt_proj) { Eigen::Vector4d line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4d line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); double k = (pt.dot (line_dir) - line_pt.dot (line_dir)) * line_dir.dot (line_dir); pt_proj = line_pt + k * line_dir; Eigen::Vector4d dir = pt - pt_proj; dir.normalize (); // Calculate the projection of the point onto the cylinder pt_proj += dir * model_coefficients[6]; } }; } #endif /* BRICS_3D_OBJECTMODELCYLINDER_H_ */
// // SCItemSet.h // Suitcase // // Copyright (c) 2014, Sebastian Staudt // #import <Foundation/Foundation.h> @interface SCItemSet : NSObject @property (nonatomic, strong) NSArray *items; @property (nonatomic, strong) NSString *name; + (instancetype)itemSetWithId:(NSString *)identifier andName:(NSString *)itemSetName andItems:(NSArray *)itemSetItems; @end