max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
390
<filename>tests/test_agents/test_deep/test_vpg.py<gh_stars>100-1000 import shutil from genrl.agents import VPG from genrl.environments import VectorEnv from genrl.trainers import OnPolicyTrainer class TestVPG: def test_vpg_discrete(self): env = VectorEnv("CartPole-v0") algo = VPG("mlp", env) trainer = OnPolicyTrainer( algo, env, log_mode=["csv"], logdir="./logs", epochs=1 ) trainer.train() shutil.rmtree("./logs") def test_vpg_continuous(self): env = VectorEnv("CartPole-v0") algo = VPG("mlp", env) trainer = OnPolicyTrainer( algo, env, log_mode=["csv"], logdir="./logs", epochs=1 ) trainer.train() shutil.rmtree("./logs") def test_vpg_cnn(self): env = VectorEnv("Pong-v0", env_type="atari") algo = VPG("cnn", env, rollout_size=128) trainer = OnPolicyTrainer( algo, env, log_mode=["csv"], logdir="./logs", epochs=1 ) trainer.train() shutil.rmtree("./logs")
524
6,335
<gh_stars>1000+ package permissions.dispatcher.processor.base; import org.hamcrest.core.SubstringMatcher; final class StringEquals extends SubstringMatcher { StringEquals(String substring) { super(substring); } @Override protected boolean evalSubstringOf(String string) { // Strip Exception prefix from the string to only include the actual message string = string.substring(string.indexOf(':') + 2); return substring != null && substring.equals(string); } @Override protected String relationship() { return "equals"; } }
209
1,531
package com.sleekbyte.tailor.functional; import com.sleekbyte.tailor.common.Messages; import com.sleekbyte.tailor.common.Rules; import com.sleekbyte.tailor.common.Severity; import com.sleekbyte.tailor.output.Printer; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; /** * Functional tests for closing brace by itself on a line. */ @RunWith(MockitoJUnitRunner.class) public class ClosingBraceLineTest extends RuleTest { @Override protected String[] getCommandArgs() { return new String[]{ "--only=brace-style" }; } @Override protected void addAllExpectedMsgs() { addExpectedBraceMsg(13, 54, Severity.WARNING, Messages.SWITCH_STATEMENT); addExpectedBraceMsg(17, 12, Severity.WARNING, Messages.CLASS); addExpectedEmptyConstructBodyMsg(24, 19, Severity.WARNING); addExpectedBraceMsg(27, 12, Severity.WARNING, Messages.STRUCT); addExpectedEmptyConstructBodyMsg(30, 5, Severity.WARNING); addExpectedEmptyConstructBodyMsg(32, 18, Severity.WARNING); addExpectedEmptyConstructBodyMsg(51, 23, Severity.WARNING); addExpectedEmptyConstructBodyMsg(54, 22, Severity.WARNING); addExpectedEmptyConstructBodyMsg(57, 5, Severity.WARNING); addExpectedEmptyConstructBodyMsg(63, 28, Severity.WARNING); addExpectedEmptyConstructBodyMsg(68, 28, Severity.WARNING); addExpectedEmptyConstructBodyMsg(71, 18, Severity.WARNING); addExpectedBraceMsg(85, 16, Severity.WARNING, Messages.FUNCTION); addExpectedEmptyConstructBodyMsg(89, 28, Severity.WARNING); addExpectedBraceMsg(91, 31, Severity.WARNING, Messages.CLASS); addExpectedBraceMsg(96, 4, Severity.WARNING, Messages.CLASS); addExpectedBraceMsg(100, 14, Severity.WARNING, Messages.CLASS); addExpectedBraceMsg(103, 6, Severity.WARNING, Messages.CLASS); addExpectedBraceMsg(108, 25, Severity.WARNING, Messages.SETTER); addExpectedBraceMsg(111, 23, Severity.WARNING, Messages.GETTER); addExpectedBraceMsg(130, 23, Severity.WARNING, Messages.GETTER); addExpectedBraceMsg(139, 25, Severity.WARNING, Messages.GETTER); addExpectedBraceMsg(168, 60, Severity.WARNING, Messages.SETTER); addExpectedBraceMsg(176, 28, Severity.WARNING, Messages.INITIALIZER_BODY); addExpectedBraceMsg(192, 38, Severity.WARNING, Messages.IF_STATEMENT); addExpectedBraceMsg(195, 35, Severity.WARNING, Messages.IF_STATEMENT); addExpectedBraceMsg(201, 44, Severity.WARNING, Messages.ELSE_CLAUSE); int start = 209; addExpectedBraceMsg(start, 30, Severity.WARNING, Messages.FOR_IN_LOOP); addExpectedBraceMsg(start + 3, 47, Severity.WARNING, Messages.WHILE_STATEMENT); addExpectedBraceMsg(start + 5, 38, Severity.WARNING, Messages.REPEAT_WHILE_STATEMENT); addExpectedBraceMsg(start + 8, 18, Severity.WARNING, Messages.REPEAT_WHILE_STATEMENT); start = 221; addExpectedBraceMsg(start, 15, Severity.WARNING, Messages.FUNCTION); addExpectedBraceMsg(start + 2, 40, Severity.WARNING, Messages.FUNCTION); addExpectedBraceMsg(start + 15, 34, Severity.WARNING, Messages.CLOSURE); addExpectedBraceMsg(start + 23, 12, Severity.WARNING, Messages.CLOSURE); start = 257; addExpectedBraceMsg(start, 19, Severity.WARNING, Messages.ENUM); addExpectedBraceMsg(start + 8, 19, Severity.WARNING, Messages.ENUM); addExpectedBraceMsg(start + 15, 25, Severity.WARNING, Messages.ENUM); addExpectedEmptyConstructBodyMsg(start + 19, 15, Severity.WARNING); addExpectedBraceMsg(start + 25, 16, Severity.WARNING, Messages.CLOSURE); addExpectedBraceMsg(start + 35, 35, Severity.WARNING, Messages.SUBSCRIPT); addExpectedBraceMsg(start + 43, 10, Severity.WARNING, Messages.SUBSCRIPT); start = 326; addExpectedBraceMsg(start, 11, Severity.WARNING, Messages.GETTER_SETTER_BLOCK); addExpectedBraceMsg(start, 11, Severity.WARNING, Messages.SUBSCRIPT); addExpectedBraceMsg(start + 6, 68, Severity.WARNING, Messages.WILL_SET_CLAUSE); addExpectedBraceMsg(start + 10, 15, Severity.WARNING, Messages.DID_SET_CLAUSE); addExpectedBraceMsg(start + 19, 15, Severity.WARNING, Messages.DID_SET_CLAUSE); addExpectedBraceMsg(start + 26, 68, Severity.WARNING, Messages.WILL_SET_CLAUSE); addExpectedBraceMsg(start + 34, 11, Severity.WARNING, Messages.WILLSET_DIDSET_BLOCK); } private void addExpectedBraceMsg(int line, int column, Severity severity, String msg) { expectedMessages.add( Printer.genOutputStringForTest(Rules.BRACE_STYLE, inputFile.getName(), line, column, severity, msg + Messages.CLOSE_BRACE_STYLE)); } private void addExpectedEmptyConstructBodyMsg(int line, int column, Severity severity) { expectedMessages.add( Printer.genOutputStringForTest(Rules.BRACE_STYLE, inputFile.getName(), line, column, severity, Messages.EMPTY_BODY)); } }
2,015
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package ifc.loader; import lib.MultiMethodTest; import lib.StatusException; import util.RegistryTools; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.loader.CannotActivateFactoryException; import com.sun.star.loader.XImplementationLoader; import com.sun.star.registry.CannotRegisterImplementationException; import com.sun.star.registry.XRegistryKey; import com.sun.star.registry.XSimpleRegistry; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Testing <code>com.sun.star.loader.XImplementationLoader</code> * interface methods : * <ul> * <li><code> activate()</code></li> * <li><code> writeRegistryInfo()</code></li> * </ul> <p> * * The following object relations required : * <ul> * <li> <code>'ImplementationLoader'</code> : service which is * responsible for loading implementations. </li> * <li> <code>'ImplementationUrl'</code> : implementation file location. </li> * <li> <code>'ImplementationName'</code> : Name of the implementation.</li> * </ul> <p> * Object has to be recreated after this test. <p> * Test is <b> Not </b> multithread compilant. */ public class _XImplementationLoader extends MultiMethodTest { public XImplementationLoader oObj = null; private String implLoader = null ; private String implUrl = null ; private String implName = null ; /** * Retrieves object relations. * @throws StatusException If one of relations not found. */ public void before() { implLoader = (String) tEnv.getObjRelation("ImplementationLoader") ; implUrl = (String) tEnv.getObjRelation("ImplementationUrl") ; implName = (String) tEnv.getObjRelation("ImplementationName") ; if (implLoader == null || implUrl == null || implName == null) throw new StatusException("One of object relations not found", new NullPointerException()) ; } /** * First registry file created, and the root key retrieved. * Then method <code>writeRegistryInfo</code> called and it must * write some info into the registry root key. After all registry * is destroyed.<p> * Has OK status if some info was written into registry. */ public void _writeRegistryInfo() { XRegistryKey key ; XSimpleRegistry xReg = null ; String tmpDir = util.utils.getOfficeTempDir((XMultiServiceFactory)tParam.getMSF()); try { xReg = RegistryTools.createRegistryService ((XMultiServiceFactory)tParam.getMSF()) ; xReg.open(tmpDir + "XImpLoader_tmp.rdb", false, true) ; key = xReg.getRootKey() ; } catch (com.sun.star.uno.Exception e) { log.println("Can not create registry for writing") ; e.printStackTrace(log) ; tRes.tested("writeRegistryInfo()", false) ; return ; } boolean rc ; try { rc = oObj.writeRegistryInfo(key, implLoader, implUrl) ; } catch (CannotRegisterImplementationException e) { throw new StatusException("Can not register implementation", e) ; } if (rc == false) log.println("Method returned false value") ; String[] keys ; try { keys = key.getKeyNames() ; } catch (com.sun.star.uno.Exception e) { log.println("Error retrieving key names from registry") ; tRes.tested("writeRegistryInfo()", false) ; return ; } // destroying registry file try { xReg.close() ; xReg.destroy() ; } catch (com.sun.star.registry.InvalidRegistryException e) { log.println("Can't destroy registry file.") ; } tRes.tested("writeRegistryInfo()", rc && keys.length > 0) ; } /** * Tries to activate the implementation. <p> * * Has OK status if not <code>null</code> value returned by method, * if its implementation name is the same as expected. */ public void _activate() { boolean ok = true ; XInterface factory = null ; try { factory = (XInterface) oObj.activate (implName, implLoader, implUrl, null) ; } catch (CannotActivateFactoryException e) { throw new StatusException("Can not activate factory", e) ; } XServiceInfo xServInf = (XServiceInfo) UnoRuntime.queryInterface (XServiceInfo.class, factory) ; if (xServInf == null) { if (factory == null) { log.println("activate() returns null - FAILED."); } else { log.println("Activated impementation doesn't support "+ "XServiceInfo - FAILED."); } ok = false ; } else { String gImpName = xServInf.getImplementationName() ; log.println("Implementation name returned :" + gImpName); if (!gImpName.equals(implName)) { log.println("!!! But other name was expected :" + implName); ok = false ; } } tRes.tested("activate()", ok) ; } /** * Forces object recreation. */ public void after() { this.disposeEnvironment() ; } }
2,377
1,679
<filename>src/boards/mcu/stm32/EEPROM_Emul/Core/eeprom_emul_types.h /** ****************************************************************************** * @file EEPROM_Emul/Core/eeprom_emul_types.h * @author MCD Application Team * @brief This file contains all the functions prototypes for the EEPROM * emulation firmware library. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution 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 STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __EEPROM_EMUL_TYPES_H #define __EEPROM_EMUL_TYPES_H /** @addtogroup EEPROM_Emulation * @{ */ /* Exported constants --------------------------------------------------------*/ /** @defgroup EEPROM_Exported_Constants EEPROM Exported Constants * @{ */ /** @defgroup Exported_Other_Constants Exported Other Constants * @{ */ /** * @brief EE Status enum definition. */ /* Define of the return value */ typedef enum { /* External return codes : ok */ EE_OK = 0U, /* External return codes : errors */ EE_ERASE_ERROR, EE_WRITE_ERROR, EE_ERROR_NOACTIVE_PAGE, EE_ERROR_NOERASE_PAGE, EE_ERROR_NOERASING_PAGE, EE_ERROR_NOACTIVE_NORECEIVE_NOVALID_PAGE, EE_NO_DATA, EE_INVALID_VIRTUALADDRESS, EE_INVALID_PAGE, EE_INVALID_PAGE_SEQUENCE, EE_INVALID_ELEMENT, EE_TRANSFER_ERROR, EE_DELETE_ERROR, EE_INVALID_BANK_CFG, /* Internal return code */ EE_NO_PAGE_FOUND, EE_PAGE_NOTERASED, EE_PAGE_ERASED, EE_PAGE_FULL, /* External return code : action required */ EE_CLEANUP_REQUIRED = 0x100U, } EE_Status; /* Type of page erasing: EE_FORCED_ERASE --> pages to erase are erased unconditionnally EE_CONDITONAL_ERASE --> pages to erase are erased only if not fully erased */ typedef enum { EE_FORCED_ERASE, EE_CONDITIONAL_ERASE } EE_Erase_type; /* Masks of EE_Status return codes */ #define EE_STATUSMASK_ERROR (uint16_t)0x00FFU /*!< Mask on EE_Status return code, selecting error codes */ #define EE_STATUSMASK_CLEANUP (uint16_t)0x0100U /*!< Mask on EE_Status return code, selecting cleanup request codes */ /** * @} */ /** * @} */ /** * @} */ #endif /* __EEPROM_EMUL_TYPES_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
1,604
648
{"category":[{"coding":[{"code":"chemical","display":"Chemical","system":"http://hl7.org.fhir/substance-category"}]}],"code":{"coding":[{"code":"88480006","display":"Potassium","system":"http://snomed.info/sct"}]},"id":"f203","identifier":[{"system":"http://acme.org/indentifiers/substances","value":"1234"}],"resourceType":"Substance","text":{"div":"<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f203</p><p><b>identifier</b>: 1234</p><p><b>category</b>: Chemical <span>(Details : {http://hl7.org.fhir/substance-category code 'chemical' = '??', given as 'Chemical'})</span></p><p><b>code</b>: Potassium <span>(Details : {SNOMED CT code '88480006' = '88480006', given as 'Potassium'})</span></p></div>","status":"generated"}}
258
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/chromeos/constants/constants_util.h" #include "base/no_destructor.h" namespace chromeos { namespace settings { namespace constants { namespace { template <typename T> std::vector<T> All() { int32_t min_value = static_cast<int32_t>(T::kMinValue); int32_t max_value = static_cast<int32_t>(T::kMaxValue); std::vector<T> all; for (int32_t i = min_value; i <= max_value; ++i) { T current = static_cast<T>(i); // Not every value between the min and max values is valid: // (1) We use a numbering scheme which purposely skips some values for the // Subpage and Setting enums. // (2) Some values are deprecated and removed. if (mojom::IsKnownEnumValue(current)) all.push_back(current); } return all; } } // namespace const std::vector<mojom::Section>& AllSections() { static const base::NoDestructor<std::vector<mojom::Section>> all_sections( All<mojom::Section>()); return *all_sections; } const std::vector<mojom::Subpage>& AllSubpages() { static const base::NoDestructor<std::vector<mojom::Subpage>> all_subpages( All<mojom::Subpage>()); return *all_subpages; } const std::vector<mojom::Setting>& AllSettings() { static const base::NoDestructor<std::vector<mojom::Setting>> all_settings( All<mojom::Setting>()); return *all_settings; } } // namespace constants } // namespace settings } // namespace chromeos
572
652
<gh_stars>100-1000 // Copyright (c) 2019, SafeBreach // 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 copyright holder 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. // AUTHORS: <NAME>, <NAME> // SEE: https://github.com/SafeBreach-Labs/Pinjectra #pragma once // Standard Include's #include <iostream> #include <map> #include <string.h> #include <windows.h> // Local Include's #include "PinjectraPacket.h" #include "DynamicPayloads.h" // Data Types typedef struct { HANDLE process; HANDLE thread; LPVOID addr; LPVOID entry_point; SIZE_T tot_write; SIZE_T tot_alloc; } RUNTIME_MEM_ENTRY; typedef struct { HANDLE process; HANDLE thread; DWORD pid; DWORD tid; } TARGET_PROCESS; //////////////////// // Writer Classes // //////////////////// class SimpleMemoryWriter { public: virtual RUNTIME_MEM_ENTRY* write(DWORD pid, DWORD tid) = 0; }; class AdvanceMemoryWriter { public: virtual RUNTIME_MEM_ENTRY* writeto(HANDLE process_handle, SIZE_T additional_mem_space) = 0; }; class ComplexMemoryWriter { public: virtual PINJECTRA_PACKET* eval_and_write(TARGET_PROCESS* target, TStrDWORD64Map &params) = 0; }; // Base Class class MutableAdvanceMemoryWriter : public AdvanceMemoryWriter { public: void* GetBuffer(void) const { return(m_buf); }; void SetBuffer(void *buf) { m_buf = buf; }; size_t GetBufferSize(void) const { return(m_nbyte); }; void SetBufferSize(size_t nbyte) { m_nbyte = nbyte; }; protected: void* m_buf; size_t m_nbyte; }; ///////////////////// // Adapter Classes // ///////////////////// class ComplexToMutableAdvanceMemoryWriter : public ComplexMemoryWriter { public: // Constructor & Destructor ComplexToMutableAdvanceMemoryWriter(DynamicPayload* payload, MutableAdvanceMemoryWriter* writer) : m_payload(payload), m_writer(writer) { } ~ComplexToMutableAdvanceMemoryWriter(); // Methods PINJECTRA_PACKET* eval_and_write(TARGET_PROCESS* target, TStrDWORD64Map& params); protected: // Members DynamicPayload* m_payload; MutableAdvanceMemoryWriter* m_writer; };
1,234
372
<reponame>mjhopkins/google-api-java-client-services /* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.streetviewpublish.v1.model; /** * Level information containing level number and its corresponding name. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Street View Publish API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Level extends com.google.api.client.json.GenericJson { /** * Required. A name assigned to this Level, restricted to 3 characters. Consider how the elevator * buttons would be labeled for this level if there was an elevator. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Floor number, used for ordering. 0 indicates the ground level, 1 indicates the first level * above ground level, -1 indicates the first level under ground level. Non-integer values are OK. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double number; /** * Required. A name assigned to this Level, restricted to 3 characters. Consider how the elevator * buttons would be labeled for this level if there was an elevator. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Required. A name assigned to this Level, restricted to 3 characters. Consider how the elevator * buttons would be labeled for this level if there was an elevator. * @param name name or {@code null} for none */ public Level setName(java.lang.String name) { this.name = name; return this; } /** * Floor number, used for ordering. 0 indicates the ground level, 1 indicates the first level * above ground level, -1 indicates the first level under ground level. Non-integer values are OK. * @return value or {@code null} for none */ public java.lang.Double getNumber() { return number; } /** * Floor number, used for ordering. 0 indicates the ground level, 1 indicates the first level * above ground level, -1 indicates the first level under ground level. Non-integer values are OK. * @param number number or {@code null} for none */ public Level setNumber(java.lang.Double number) { this.number = number; return this; } @Override public Level set(String fieldName, Object value) { return (Level) super.set(fieldName, value); } @Override public Level clone() { return (Level) super.clone(); } }
1,011
4,894
/* Copyright (c) 2008-2020, <NAME> * 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 Esoteric Software 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. */ package com.esotericsoftware.kryo.util; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.ReferenceResolver; import java.util.ArrayList; /** Uses an {@link ArrayList} to track objects that have already been written. This is more efficient than * {@link MapReferenceResolver} for graphs with few objects, providing an approximate 15% increase in deserialization speed. This * should not be used for graphs with many objects because it uses a linear look up to find objects that have already been * written. * @author <NAME> */ public class ListReferenceResolver implements ReferenceResolver { protected Kryo kryo; protected final ArrayList seenObjects = new ArrayList(); public void setKryo (Kryo kryo) { this.kryo = kryo; } public int addWrittenObject (Object object) { int id = seenObjects.size(); seenObjects.add(object); return id; } public int getWrittenId (Object object) { for (int i = 0, n = seenObjects.size(); i < n; i++) if (seenObjects.get(i) == object) return i; return -1; } public int nextReadId (Class type) { int id = seenObjects.size(); seenObjects.add(null); return id; } public void setReadObject (int id, Object object) { seenObjects.set(id, object); } public Object getReadObject (Class type, int id) { return seenObjects.get(id); } public void reset () { seenObjects.clear(); } /** Returns false for all primitive wrappers and enums. */ public boolean useReferences (Class type) { return !Util.isWrapperClass(type) && !Util.isEnum(type); } }
992
2,253
/************************************************************************************ * * * Copyright (c) 2014 - 2018 <NAME> <<EMAIL>> * * * * This file is part of RTTR (Run Time Type Reflection) * * License: MIT License * * * * 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. * * * *************************************************************************************/ #include "unit_tests/test_classes.h" #include <rttr/type> using namespace rttr; using namespace std; #include <iostream> #include <memory> #include <functional> #include <catch/catch.hpp> //////////////////////////////////////////////////////////////////////////////////////// namespace { struct custom_type { custom_type(){} int value = 23; int my_func() { return value; } int my_const_func() const { return value; } }; typedef int(custom_type::*mem_obj_ptr_t); typedef int(custom_type::*mem_func_ptr_t)(void); typedef int(custom_type::*mem_const_func_ptr_t)(void)const; int my_free_func() { return 42; } typedef int(*func_ptr_t)(void); } // end namespace anonymous TEST_CASE("Test raw_adressof", "[raw_adressof]") { SECTION("Test pointer type") { int value = 23; int* result = detail::raw_addressof(value); CHECK(result == &value); int* int_ptr = &value; int* result_2 = detail::raw_addressof(int_ptr); CHECK(result_2 == &value); int** int_ptr_ptr = &int_ptr; int* result_3 = detail::raw_addressof(int_ptr_ptr); CHECK(result_3 == &value); int*** int_ptr_ptr_ptr = &int_ptr_ptr; int* result_4 = detail::raw_addressof(int_ptr_ptr_ptr); CHECK(result_4 == &value); } SECTION("Test const pointer type") { const int value = 23; const int* int_ptr = &value; const int* result = detail::raw_addressof(value); CHECK(result == &value); const int** int_ptr_ptr = &int_ptr; const int* result_2 = detail::raw_addressof(int_ptr_ptr); CHECK(result_2 == &value); const int*** int_ptr_ptr_ptr = &int_ptr_ptr; const int* result_3 = detail::raw_addressof(int_ptr_ptr_ptr); CHECK(result_3 == &value); } SECTION("Test custom type") { custom_type obj; custom_type* obj_ptr = &obj; custom_type* result = detail::raw_addressof(obj); CHECK(result == &obj); custom_type** obj_ptr_ptr = &obj_ptr; custom_type* result_2 = detail::raw_addressof(obj_ptr_ptr); CHECK(result_2 == &obj); custom_type*** obj_ptr_ptr_ptr = &obj_ptr_ptr; custom_type* result_3 = detail::raw_addressof(obj_ptr_ptr_ptr); CHECK(result_3 == &obj); } SECTION("Test function type") { func_ptr_t func_ptr = &my_free_func; func_ptr_t* result = detail::raw_addressof(func_ptr); CHECK(*result == &my_free_func); func_ptr_t* func_ptr_ptr = &func_ptr; func_ptr_t* result_2 = detail::raw_addressof(func_ptr_ptr); CHECK(*result_2 == &my_free_func); func_ptr_t** func_ptr_ptr_ptr = &func_ptr_ptr; func_ptr_t* result_3 = detail::raw_addressof(func_ptr_ptr_ptr); CHECK(*result_3 == &my_free_func); } SECTION("Test const function type") { const func_ptr_t func_ptr = &my_free_func; const func_ptr_t* result = detail::raw_addressof(func_ptr); CHECK(*result == &my_free_func); const func_ptr_t* func_ptr_ptr = &func_ptr; const func_ptr_t* result_2 = detail::raw_addressof(func_ptr_ptr); CHECK(*result_2 == &my_free_func); const func_ptr_t** func_ptr_ptr_ptr = &func_ptr_ptr; const func_ptr_t* result_3 = detail::raw_addressof(func_ptr_ptr_ptr); CHECK(*result_3 == &my_free_func); } SECTION("Test member object type") { custom_type obj; mem_obj_ptr_t mem_obj_ptr = &custom_type::value; mem_obj_ptr_t* result = detail::raw_addressof(mem_obj_ptr); CHECK(&(obj.**result) == &obj.value); mem_obj_ptr_t* mem_obj_ptr_ptr = &mem_obj_ptr; mem_obj_ptr_t* result_2 = detail::raw_addressof(mem_obj_ptr_ptr); CHECK(&(obj.**result_2) == &obj.value); mem_obj_ptr_t** mem_obj_ptr_ptr_ptr = &mem_obj_ptr_ptr; mem_obj_ptr_t* result_3 = detail::raw_addressof(mem_obj_ptr_ptr_ptr); CHECK(&(obj.**result_3) == &obj.value); } SECTION("Test const member object type") { const custom_type obj; const mem_obj_ptr_t mem_obj_ptr = &custom_type::value; const mem_obj_ptr_t* result = detail::raw_addressof(mem_obj_ptr); CHECK(&(obj.**result) == &obj.value); const mem_obj_ptr_t* mem_obj_ptr_ptr = &mem_obj_ptr; const mem_obj_ptr_t* result_2 = detail::raw_addressof(mem_obj_ptr_ptr); CHECK(&(obj.**result_2) == &obj.value); const mem_obj_ptr_t** mem_obj_ptr_ptr_ptr = &mem_obj_ptr_ptr; const mem_obj_ptr_t* result_3 = detail::raw_addressof(mem_obj_ptr_ptr_ptr); CHECK(&(obj.**result_3) == &obj.value); } SECTION("Test member function type") { custom_type obj; mem_func_ptr_t mem_func_ptr = &custom_type::my_func; mem_func_ptr_t* result = detail::raw_addressof(mem_func_ptr); CHECK(*result == mem_func_ptr); mem_func_ptr_t* mem_func_ptr_ptr = &mem_func_ptr; mem_func_ptr_t* result_2 = detail::raw_addressof(mem_func_ptr_ptr); CHECK(*result_2 == mem_func_ptr); mem_func_ptr_t* mem_func_ptr_ptr_ptr = &mem_func_ptr; mem_func_ptr_t* result_3 = detail::raw_addressof(mem_func_ptr_ptr_ptr); CHECK(*result_3 == mem_func_ptr); } SECTION("Test const member function type") { const custom_type obj; const mem_func_ptr_t mem_func_ptr = &custom_type::my_func; const mem_func_ptr_t* result = detail::raw_addressof(mem_func_ptr); CHECK(*result == mem_func_ptr); const mem_func_ptr_t* mem_func_ptr_ptr = &mem_func_ptr; const mem_func_ptr_t* result_2 = detail::raw_addressof(mem_func_ptr_ptr); CHECK(*result_2 == mem_func_ptr); const mem_func_ptr_t* mem_func_ptr_ptr_ptr = &mem_func_ptr; const mem_func_ptr_t* result_3 = detail::raw_addressof(mem_func_ptr_ptr_ptr); CHECK(*result_3 == mem_func_ptr); } SECTION("Test member function const type") { custom_type obj; mem_const_func_ptr_t mem_func_ptr = &custom_type::my_const_func; mem_const_func_ptr_t* result = detail::raw_addressof(mem_func_ptr); CHECK(*result == mem_func_ptr); mem_const_func_ptr_t* mem_func_ptr_ptr = &mem_func_ptr; mem_const_func_ptr_t* result_2 = detail::raw_addressof(mem_func_ptr_ptr); CHECK(*result_2 == mem_func_ptr); mem_const_func_ptr_t* mem_func_ptr_ptr_ptr = &mem_func_ptr; mem_const_func_ptr_t* result_3 = detail::raw_addressof(mem_func_ptr_ptr_ptr); CHECK(*result_3 == mem_func_ptr); } SECTION("Test const member function const type") { const custom_type obj; const mem_const_func_ptr_t mem_func_ptr = &custom_type::my_const_func; const mem_const_func_ptr_t* result = detail::raw_addressof(mem_func_ptr); CHECK(*result == mem_func_ptr); const mem_const_func_ptr_t* mem_func_ptr_ptr = &mem_func_ptr; const mem_const_func_ptr_t* result_2 = detail::raw_addressof(mem_func_ptr_ptr); CHECK(*result_2 == mem_func_ptr); const mem_const_func_ptr_t* mem_func_ptr_ptr_ptr = &mem_func_ptr; const mem_const_func_ptr_t* result_3 = detail::raw_addressof(mem_func_ptr_ptr_ptr); CHECK(*result_3 == mem_func_ptr); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("Test get_wrapper_adressof", "[wrapped_raw_addressof]") { SECTION("Test std::shared_ptr") { std::shared_ptr<int> obj = std::make_shared<int>(23); int* int_ptr = detail::wrapped_raw_addressof(obj); CHECK(int_ptr == obj.get()); std::shared_ptr<const int> obj_c = std::make_shared<const int>(23); const int* int_ptr_c = detail::wrapped_raw_addressof(obj_c); CHECK(int_ptr_c == obj_c.get()); } SECTION("Test std::reference_wrapper") { int value = 23; std::reference_wrapper<int> obj = std::ref(value); int* result = detail::wrapped_raw_addressof(obj); CHECK(result == &obj.get()); const int value_c = 42; std::reference_wrapper<const int> obj_c = std::cref(value_c); const int* result_2 = detail::wrapped_raw_addressof(obj_c); CHECK(result_2 == &obj_c.get()); const func_ptr_t func_ptr = &my_free_func; std::reference_wrapper<const func_ptr_t> obj_func = std::cref(func_ptr); const func_ptr_t* result_3 = detail::wrapped_raw_addressof(obj_func); CHECK(*result_3 == &my_free_func); } } ///////////////////////////////////////////////////////////////////////////////////////// template<typename T1, typename T2> bool raw_type_check() { static_assert(std::is_same<typename detail::raw_type<T1>::type, T2>::value, "Types are not the same!"); return true; } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("Test raw_type type traits", "[raw_type<T>]") { SECTION("Test pointer type") { raw_type_check<int, int >(); raw_type_check<int*, int >(); raw_type_check<int**, int >(); raw_type_check<const int, int >(); raw_type_check<const int*, int >(); raw_type_check<const int**, int >(); raw_type_check<volatile int, int >(); raw_type_check<volatile int*, int >(); raw_type_check<volatile int**, int >(); raw_type_check<const volatile int, int >(); raw_type_check<const volatile int*, int >(); raw_type_check<const volatile int**, int >(); } SECTION("Test pointer type to cv type") { raw_type_check<const int* const, int >(); raw_type_check<const int** const, int >(); raw_type_check<volatile int* const, int >(); raw_type_check<volatile int** const, int >(); raw_type_check<const volatile int* const, int >(); raw_type_check<const volatile int** const, int >(); // raw_type_check<const int* volatile, int >(); raw_type_check<const int** volatile, int >(); raw_type_check<volatile int* volatile, int >(); raw_type_check<volatile int** volatile, int >(); raw_type_check<const volatile int* volatile, int >(); raw_type_check<const volatile int** volatile, int >(); // raw_type_check<const int* const volatile, int >(); raw_type_check<const int** const volatile, int >(); raw_type_check<volatile int* const volatile, int >(); raw_type_check<volatile int** const volatile, int >(); raw_type_check<const volatile int* const volatile, int >(); raw_type_check<const volatile int** const volatile, int >(); } SECTION("Test reference types") { raw_type_check<int&, int >(); raw_type_check<int&&, int >(); raw_type_check<const int&, int >(); raw_type_check<const int&&, int >(); raw_type_check<volatile int&, int >(); raw_type_check<volatile int&&, int >(); raw_type_check<const volatile int&, int >(); raw_type_check<const volatile int&&, int >(); } SECTION("Test reference to pointer types") { raw_type_check<int*&, int >(); raw_type_check<std::vector<int> const &, std::vector<int> >(); } SECTION("Test array types") { raw_type_check<int[10], int[10]>(); raw_type_check<int(*)[10], int[10]>(); raw_type_check<int(**)[10], int[10] >(); raw_type_check<const int[10], int[10] >(); raw_type_check<const int(*)[10], int[10] >(); raw_type_check<const int(**)[10], int[10] >(); raw_type_check<volatile int[10], int[10] >(); raw_type_check<volatile int(*)[10], int[10] >(); raw_type_check<volatile int(**)[10], int[10] >(); raw_type_check<const volatile int[10], int[10] >(); raw_type_check<const volatile int(*)[10], int[10] >(); raw_type_check<const volatile int(**)[10], int[10] >(); } SECTION("Test array pointer cv types") { raw_type_check<int(*const)[10], int[10]>(); raw_type_check<int(*volatile)[10], int[10]>(); raw_type_check<int(*const volatile)[10], int[10]>(); raw_type_check<int(**const)[10], int[10]>(); raw_type_check<int(**volatile)[10], int[10]>(); raw_type_check<int(**const volatile)[10], int[10]>(); } SECTION("Test multi dimensional array types") { raw_type_check<int[10][25], int[10][25]>(); raw_type_check<int(*)[10][25], int[10][25]>(); raw_type_check<int(**)[10][25], int[10][25] >(); raw_type_check<const int[10][25], int[10][25] >(); raw_type_check<const int(*)[10][25], int[10][25] >(); raw_type_check<const int(**)[10][25], int[10][25] >(); raw_type_check<volatile int[10][25], int[10][25] >(); raw_type_check<volatile int(*)[10][25], int[10][25] >(); raw_type_check<volatile int(**)[10][25], int[10][25] >(); raw_type_check<const volatile int[10][25], int[10][25] >(); raw_type_check<const volatile int(*)[10][25], int[10][25] >(); raw_type_check<const volatile int(**)[10][25], int[10][25] >(); } SECTION("Test multi dimensional array pointer cv types") { raw_type_check<int(*const)[10][25], int[10][25]>(); raw_type_check<int(*volatile)[10][25], int[10][25]>(); raw_type_check<int(*const volatile)[10][25], int[10][25]>(); raw_type_check<int(**const)[10][25], int[10][25]>(); raw_type_check<int(**volatile)[10][25], int[10][25]>(); raw_type_check<int(**const volatile)[10][25], int[10][25]>(); } SECTION("Test free function types") { raw_type_check<func_ptr_t, func_ptr_t>(); raw_type_check<const func_ptr_t, func_ptr_t>(); raw_type_check<const volatile func_ptr_t, func_ptr_t>(); raw_type_check<func_ptr_t*, func_ptr_t>(); raw_type_check<const func_ptr_t*, func_ptr_t>(); raw_type_check<const volatile func_ptr_t*, func_ptr_t>(); } SECTION("Test member object type") { raw_type_check<mem_obj_ptr_t, mem_obj_ptr_t>(); raw_type_check<const mem_obj_ptr_t, mem_obj_ptr_t>(); raw_type_check<const volatile mem_obj_ptr_t, mem_obj_ptr_t>(); raw_type_check<mem_obj_ptr_t*, mem_obj_ptr_t>(); raw_type_check<const mem_obj_ptr_t*, mem_obj_ptr_t>(); raw_type_check<const volatile mem_obj_ptr_t*, mem_obj_ptr_t>(); } SECTION("Test member function type") { raw_type_check<mem_func_ptr_t, mem_func_ptr_t>(); raw_type_check<const mem_func_ptr_t, mem_func_ptr_t>(); raw_type_check<const volatile mem_func_ptr_t, mem_func_ptr_t>(); raw_type_check<mem_func_ptr_t*, mem_func_ptr_t>(); raw_type_check<const mem_func_ptr_t*, mem_func_ptr_t>(); raw_type_check<const volatile mem_func_ptr_t*, mem_func_ptr_t>(); raw_type_check<mem_const_func_ptr_t, mem_const_func_ptr_t>(); raw_type_check<const mem_const_func_ptr_t, mem_const_func_ptr_t>(); raw_type_check<const volatile mem_const_func_ptr_t, mem_const_func_ptr_t>(); raw_type_check<mem_const_func_ptr_t*, mem_const_func_ptr_t>(); raw_type_check<const mem_const_func_ptr_t*, mem_const_func_ptr_t>(); raw_type_check<const volatile mem_const_func_ptr_t*, mem_const_func_ptr_t>(); } } ///////////////////////////////////////////////////////////////////////////////////////// template<typename T1, typename T2> bool raw_array_type_check() { static_assert(std::is_same<typename detail::raw_array_type<T1>::type, T2>::value, "Types are not the same!"); return true; } //////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("Test raw_array_type type traits", "[raw_array_type<T>]") { SECTION("Test array types") { raw_array_type_check<int[100], int>(); raw_array_type_check<const int[100], int>(); raw_array_type_check<const volatile int[100], int>(); raw_array_type_check<const volatile int*[100], int>(); raw_array_type_check<const volatile int* const[100], int>(); raw_array_type_check<const volatile int* const volatile[100], int>(); } SECTION("Test multi dimensional array types") { raw_array_type_check<int[100][25], int>(); raw_array_type_check<const int[100][25], int>(); raw_array_type_check<const volatile int[100][25], int>(); raw_array_type_check<const volatile int*[100][25], int>(); raw_array_type_check<const volatile int* const[100][25], int>(); raw_array_type_check<const volatile int* const volatile[100][25], int>(); } } /////////////////////////////////////////////////////////////////////////////////////////
9,764
791
#pragma once #include "../../rendering/mesh.h" #include <core/reflection/reflection.h> #include <core/serialization/serialization.h> REFLECT_EXTERN(mesh::info); namespace bgfx { SAVE_EXTERN(VertexDecl); LOAD_EXTERN(VertexDecl); } SAVE_EXTERN(mesh::triangle); LOAD_EXTERN(mesh::triangle); SAVE_EXTERN(skin_bind_data::vertex_influence); LOAD_EXTERN(skin_bind_data::vertex_influence); SAVE_EXTERN(skin_bind_data::bone_influence); LOAD_EXTERN(skin_bind_data::bone_influence); SAVE_EXTERN(skin_bind_data); LOAD_EXTERN(skin_bind_data); SAVE_EXTERN(mesh::armature_node); LOAD_EXTERN(mesh::armature_node); SAVE_EXTERN(mesh::load_data); LOAD_EXTERN(mesh::load_data);
278
516
<reponame>scatterfish/unnamed-sdvx-clone<filename>Tests.Shared/src/TestString.cpp #include <Shared/Shared.hpp> #include <Shared/String.hpp> #include <Tests/Tests.hpp> std::vector<std::pair<const char*, const wchar_t*>> testCases({ {"", L""}, {"Hello, world!", L"Hello, world!"}, // Borute in Katakana {"\xe3\x83\x9c\xe3\x83\xab\xe3\x83\x86", L"\x30DC\x30EB\x30C6"}, // Sound Voltex in Hangul {"\xec\x82\xac\xec\x9a\xb4\xeb\x93\x9c \xeb\xb3\xbc\xed\x85\x8d\xec\x8a\xa4", L"\xC0AC\xC6B4\xB4DC\x0020\xBCFC\xD14D\xC2A4"}, // Some SDVX song names {"\xce\xa3mbry\xc3\x98", L"\x03A3\x006D\x0062\x0072\x0079\x00D8"}, {"Lachryma\xe3\x80\x8aRe:Queen'M\xe3\x80\x8b", L"Lachryma\x300ARe:Queen'M\x300B"}, {"HE4VEN \xef\xbd\x9e\xe5\xa4\xa9\xe5\x9b\xbd\xe3\x81\xb8\xe3\x82\x88\xe3\x81\x86\xe3\x81\x93\xe3\x81\x9d\xef\xbd\x9e", L"HE4VEN \xFF5E\x5929\x56FD\x3078\x3088\x3046\x3053\x305D\xFF5E"}, // Some emojis {"\xF0\x9F\x91\x8C\xF0\x9F\x94\xA5", L"\xD83D\xDC4C\xD83D\xDD25"}, }); Test("String.ConvertToWString") { for (auto& test : testCases) { TestEnsure(Utility::ConvertToWString(test.first) == test.second); } } Test("String.ConvertToUTF8") { for (auto& test : testCases) { TestEnsure(Utility::ConvertToUTF8(test.second) == test.first); } } Test("String.ConvertToRoundtrip") { for (auto& test : testCases) { TestEnsure(Utility::ConvertToUTF8(Utility::ConvertToWString(test.first)) == test.first); TestEnsure(Utility::ConvertToWString(Utility::ConvertToUTF8(test.second)) == test.second); } }
811
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.security.fluent.models.AscLocationInner; /** An instance of this class provides access to all the operations defined in LocationsClient. */ public interface LocationsClient { /** * The location of the responsible ASC of the specific subscription (home region). For each subscription there is * only one responsible location. The location in the response should be used to read or write other resources in * ASC according to their ID. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of locations where ASC saves your data. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AscLocationInner> list(); /** * The location of the responsible ASC of the specific subscription (home region). For each subscription there is * only one responsible location. The location in the response should be used to read or write other resources in * ASC according to their ID. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of locations where ASC saves your data. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AscLocationInner> list(Context context); /** * Details of a specific location. * * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get * locations. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the ASC location of the subscription is in the "name" field. */ @ServiceMethod(returns = ReturnType.SINGLE) AscLocationInner get(String ascLocation); /** * Details of a specific location. * * @param ascLocation The location where ASC stores the data of the subscription. can be retrieved from Get * locations. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the ASC location of the subscription is in the "name" field. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<AscLocationInner> getWithResponse(String ascLocation, Context context); }
1,023
892
<filename>advisories/unreviewed/2022/05/GHSA-4rp2-whvp-25jm/GHSA-4rp2-whvp-25jm.json { "schema_version": "1.2.0", "id": "GHSA-4rp2-whvp-25jm", "modified": "2022-05-13T01:10:20Z", "published": "2022-05-13T01:10:20Z", "aliases": [ "CVE-2018-19981" ], "details": "Amazon AWS SDK <=2.8.5 for Android uses Android SharedPreferences to store plain text AWS STS Temporary Credentials retrieved by AWS Cognito Identity Service. An attacker can use these credentials to create authenticated and/or authorized requests. Note that the attacker must have \"root\" privilege access to the Android filesystem in order to exploit this vulnerability (i.e. the device has been compromised, such as disabling or bypassing Android's fundamental security mechanisms).", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-19981" }, { "type": "WEB", "url": "https://aws-amplify.github.io/aws-sdk-android/docs/reference/com/amazonaws/auth/CognitoCachingCredentialsProvider.html" }, { "type": "WEB", "url": "https://raw.githubusercontent.com/lorenzodifuccia/cloudflare/master/Images/vulns/aws/aws_sdk_sp_01.png" }, { "type": "WEB", "url": "https://raw.githubusercontent.com/lorenzodifuccia/cloudflare/master/Images/vulns/aws/aws_sdk_sp_02.png" }, { "type": "WEB", "url": "https://raw.githubusercontent.com/lorenzodifuccia/cloudflare/master/Images/vulns/aws/aws_sdk_sp_03.png" } ], "database_specific": { "cwe_ids": [ "CWE-312" ], "severity": "HIGH", "github_reviewed": false } }
768
1,627
<filename>src/main/java/net/querz/mcaselector/filter/LastUpdateFilter.java package net.querz.mcaselector.filter; import net.querz.mcaselector.io.mca.ChunkData; import net.querz.mcaselector.text.TextHelper; public class LastUpdateFilter extends LongFilter { public LastUpdateFilter() { this(Operator.AND, Comparator.EQUAL, 0); } private LastUpdateFilter(Operator operator, Comparator comparator, long value) { super(FilterType.LAST_UPDATE, operator, comparator, value); } @Override protected Long getNumber(ChunkData data) { if (data.getRegion() == null) { return 0L; } return data.getRegion().getData().getCompoundTag("Level").getLong("LastUpdate"); } @Override public void setFilterValue(String raw) { super.setFilterValue(raw); if (!isValid()) { try { // LastUpdate is in ticks, not seconds setFilterNumber(TextHelper.parseDuration(raw) * 20); setValid(true); setRawValue(raw); } catch (IllegalArgumentException ex) { setFilterNumber(0L); setValid(false); } } } @Override public String toString() { return "LastUpdate " + getComparator().getQueryString() + " \"" + getRawValue() + "\""; } @Override public String getFormatText() { return "duration"; } @Override public LastUpdateFilter clone() { return new LastUpdateFilter(getOperator(), getComparator(), value); } }
486
332
// Autogenerated from vk-api-schema. Please don't edit it manually. package com.vk.api.sdk.objects.utils; import com.google.gson.annotations.SerializedName; import com.vk.api.sdk.queries.EnumParam; /** * Object type */ public enum DomainResolvedType implements EnumParam { @SerializedName("user") USER("user"), @SerializedName("group") GROUP("group"), @SerializedName("application") APPLICATION("application"), @SerializedName("page") PAGE("page"), @SerializedName("vk_app") VK_APP("vk_app"), @SerializedName("community_application") COMMUNITY_APPLICATION("community_application"); private final String value; DomainResolvedType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return value.toLowerCase(); } }
333
471
# Generated by Django 2.2.24 on 2021-07-29 21:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('enterprise', '0002_enterprisepermissions_account_unique'), ] operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.AlterField( model_name='enterprisepermissions', name='account', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='accounting.BillingAccount'), ), ], ), ]
357
2,338
<reponame>medismailben/llvm-project<gh_stars>1000+ // Check that without suppressions, we catch the issue. // RUN: %clangxx_asan -O0 %s -o %t -framework Foundation // RUN: not %run %t 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // Check that suppressing a function name works within a no-fork sandbox // RUN: echo "interceptor_via_fun:CFStringCreateWithBytes" > %t.supp // RUN: %env_asan_opts=suppressions='"%t.supp"' \ // RUN: sandbox-exec -p '(version 1)(allow default)(deny process-fork)' \ // RUN: %run %t 2>&1 | FileCheck --check-prefix=CHECK-IGNORE %s // sandbox-exec isn't available on iOS // UNSUPPORTED: ios #include <CoreFoundation/CoreFoundation.h> int main() { char *a = (char *)malloc(6); strcpy(a, "hello"); CFStringRef str = CFStringCreateWithBytes(kCFAllocatorDefault, (unsigned char *)a, 10, kCFStringEncodingUTF8, FALSE); // BOOM fprintf(stderr, "Ignored.\n"); free(a); CFRelease(str); } // CHECK-CRASH: AddressSanitizer: heap-buffer-overflow // CHECK-CRASH-NOT: Ignored. // CHECK-IGNORE-NOT: AddressSanitizer: heap-buffer-overflow // CHECK-IGNORE: Ignored.
442
14,425
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.s3a; import org.apache.hadoop.fs.contract.ContractTestUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; /** * Unit tests for {@link S3ADataBlocks}. */ public class TestDataBlocks extends Assert { @Rule public Timeout testTimeout = new Timeout(30 * 1000); @Before public void nameThread() { Thread.currentThread().setName("JUnit"); } /** * Test the {@link S3ADataBlocks.ByteBufferBlockFactory}. * That code implements an input stream over a ByteBuffer, and has to * return the buffer to the pool after the read complete. * * This test verifies the basic contract of the process. */ @Test public void testByteBufferIO() throws Throwable { try (S3ADataBlocks.ByteBufferBlockFactory factory = new S3ADataBlocks.ByteBufferBlockFactory(null)) { int limit = 128; S3ADataBlocks.ByteBufferBlockFactory.ByteBufferBlock block = factory.create(1, limit, null); assertOutstandingBuffers(factory, 1); byte[] buffer = ContractTestUtils.toAsciiByteArray("test data"); int bufferLen = buffer.length; block.write(buffer, 0, bufferLen); assertEquals(bufferLen, block.dataSize()); assertEquals("capacity in " + block, limit - bufferLen, block.remainingCapacity()); assertTrue("hasCapacity(64) in " + block, block.hasCapacity(64)); assertTrue("No capacity in " + block, block.hasCapacity(limit - bufferLen)); // now start the write S3ADataBlocks.BlockUploadData blockUploadData = block.startUpload(); S3ADataBlocks.ByteBufferBlockFactory.ByteBufferBlock.ByteBufferInputStream stream = (S3ADataBlocks.ByteBufferBlockFactory.ByteBufferBlock.ByteBufferInputStream) blockUploadData.getUploadStream(); assertTrue("Mark not supported in " + stream, stream.markSupported()); assertTrue("!hasRemaining() in " + stream, stream.hasRemaining()); int expected = bufferLen; assertEquals("wrong available() in " + stream, expected, stream.available()); assertEquals('t', stream.read()); stream.mark(limit); expected--; assertEquals("wrong available() in " + stream, expected, stream.available()); // read into a byte array with an offset int offset = 5; byte[] in = new byte[limit]; assertEquals(2, stream.read(in, offset, 2)); assertEquals('e', in[offset]); assertEquals('s', in[offset + 1]); expected -= 2; assertEquals("wrong available() in " + stream, expected, stream.available()); // read to end byte[] remainder = new byte[limit]; int c; int index = 0; while ((c = stream.read()) >= 0) { remainder[index++] = (byte) c; } assertEquals(expected, index); assertEquals('a', remainder[--index]); assertEquals("wrong available() in " + stream, 0, stream.available()); assertTrue("hasRemaining() in " + stream, !stream.hasRemaining()); // go the mark point stream.reset(); assertEquals('e', stream.read()); // when the stream is closed, the data should be returned stream.close(); assertOutstandingBuffers(factory, 1); block.close(); assertOutstandingBuffers(factory, 0); stream.close(); assertOutstandingBuffers(factory, 0); } } /** * Assert the number of buffers active for a block factory. * @param factory factory * @param expectedCount expected count. */ private static void assertOutstandingBuffers( S3ADataBlocks.ByteBufferBlockFactory factory, int expectedCount) { assertEquals("outstanding buffers in " + factory, expectedCount, factory.getOutstandingBufferCount()); } }
1,625
2,151
/* ** This file contains the TestDb bt wrapper. */ #include "lsmtest_tdb.h" #include "lsmtest.h" #include <unistd.h> #include "bt.h" #include <pthread.h> typedef struct BtDb BtDb; typedef struct BtFile BtFile; /* Background checkpointer interface (see implementations below). */ typedef struct bt_ckpter bt_ckpter; static int bgc_attach(BtDb *pDb, const char*); static int bgc_detach(BtDb *pDb); /* ** Each database or log file opened by a database handle is wrapped by ** an object of the following type. */ struct BtFile { BtDb *pBt; /* Database handle that opened this file */ bt_env *pVfs; /* Underlying VFS */ bt_file *pFile; /* File handle belonging to underlying VFS */ int nSectorSize; /* Size of sectors in bytes */ int nSector; /* Allocated size of nSector array */ u8 **apSector; /* Original sector data */ }; /* ** nCrashSync: ** If this value is non-zero, then a "crash-test" is running. If ** nCrashSync==1, then the crash is simulated during the very next ** call to the xSync() VFS method (on either the db or log file). ** If nCrashSync==2, the following call to xSync(), and so on. ** ** bCrash: ** After a crash is simulated, this variable is set. Any subsequent ** attempts to write to a file or modify the file system in any way ** fail once this is set. All the caller can do is close the connection. ** ** bFastInsert: ** If this variable is set to true, then a BT_CONTROL_FAST_INSERT_OP ** control is issued before each callto BtReplace() or BtCsrOpen(). */ struct BtDb { TestDb base; /* Base class */ bt_db *pBt; /* bt database handle */ sqlite4_env *pEnv; /* SQLite environment (for malloc/free) */ bt_env *pVfs; /* Underlying VFS */ int bFastInsert; /* True to use fast-insert */ /* Space for bt_fetch() results */ u8 *aBuffer; /* Space to store results */ int nBuffer; /* Allocated size of aBuffer[] in bytes */ int nRef; /* Background checkpointer used by mt connections */ bt_ckpter *pCkpter; /* Stuff used for crash test simulation */ BtFile *apFile[2]; /* Database and log files used by pBt */ bt_env env; /* Private VFS for this object */ int nCrashSync; /* Number of syncs until crash (see above) */ int bCrash; /* True once a crash has been simulated */ }; static int btVfsFullpath( sqlite4_env *pEnv, bt_env *pVfs, const char *z, char **pzOut ){ BtDb *pBt = (BtDb*)pVfs->pVfsCtx; if( pBt->bCrash ) return SQLITE4_IOERR; return pBt->pVfs->xFullpath(pEnv, pBt->pVfs, z, pzOut); } static int btVfsOpen( sqlite4_env *pEnv, bt_env *pVfs, const char *zFile, int flags, bt_file **ppFile ){ BtFile *p; BtDb *pBt = (BtDb*)pVfs->pVfsCtx; int rc; if( pBt->bCrash ) return SQLITE4_IOERR; p = (BtFile*)testMalloc(sizeof(BtFile)); if( !p ) return SQLITE4_NOMEM; if( flags & BT_OPEN_DATABASE ){ pBt->apFile[0] = p; }else if( flags & BT_OPEN_LOG ){ pBt->apFile[1] = p; } if( (flags & BT_OPEN_SHARED)==0 ){ p->pBt = pBt; } p->pVfs = pBt->pVfs; rc = pBt->pVfs->xOpen(pEnv, pVfs, zFile, flags, &p->pFile); if( rc!=SQLITE4_OK ){ testFree(p); p = 0; }else{ pBt->nRef++; } *ppFile = (bt_file*)p; return rc; } static int btVfsSize(bt_file *pFile, sqlite4_int64 *piRes){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xSize(p->pFile, piRes); } static int btVfsRead(bt_file *pFile, sqlite4_int64 iOff, void *pBuf, int nBuf){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xRead(p->pFile, iOff, pBuf, nBuf); } static int btFlushSectors(BtFile *p, int iFile){ sqlite4_int64 iSz; int rc; int i; u8 *aTmp = 0; rc = p->pBt->pVfs->xSize(p->pFile, &iSz); for(i=0; rc==SQLITE4_OK && i<p->nSector; i++){ if( p->pBt->bCrash && p->apSector[i] ){ /* The system is simulating a crash. There are three choices for ** this sector: ** ** 1) Leave it as it is (simulating a successful write), ** 2) Restore the original data (simulating a lost write), ** 3) Populate the disk sector with garbage data. */ sqlite4_int64 iSOff = p->nSectorSize*i; int nWrite = MIN(p->nSectorSize, iSz - iSOff); if( nWrite ){ u8 *aWrite = 0; int iOpt = (testPrngValue(i) % 3) + 1; if( iOpt==1 ){ aWrite = p->apSector[i]; }else if( iOpt==3 ){ if( aTmp==0 ) aTmp = testMalloc(p->nSectorSize); aWrite = aTmp; testPrngArray(i*13, (u32*)aWrite, nWrite/sizeof(u32)); } #if 0 fprintf(stderr, "handle sector %d of %s with %s\n", i, iFile==0 ? "db" : "log", iOpt==1 ? "rollback" : iOpt==2 ? "write" : "omit" ); fflush(stderr); #endif if( aWrite ){ rc = p->pBt->pVfs->xWrite(p->pFile, iSOff, aWrite, nWrite); } } } testFree(p->apSector[i]); p->apSector[i] = 0; } testFree(aTmp); return rc; } static int btSaveSectors(BtFile *p, sqlite4_int64 iOff, int nBuf){ int rc; sqlite4_int64 iSz; /* Size of file on disk */ int iFirst; /* First sector affected */ int iSector; /* Current sector */ int iLast; /* Last sector affected */ if( p->nSectorSize==0 ){ p->nSectorSize = p->pBt->pVfs->xSectorSize(p->pFile); if( p->nSectorSize<512 ) p->nSectorSize = 512; } iLast = (iOff+nBuf-1) / p->nSectorSize; iFirst = iOff / p->nSectorSize; rc = p->pBt->pVfs->xSize(p->pFile, &iSz); for(iSector=iFirst; rc==SQLITE4_OK && iSector<=iLast; iSector++){ int nRead; sqlite4_int64 iSOff = iSector * p->nSectorSize; u8 *aBuf = testMalloc(p->nSectorSize); nRead = MIN(p->nSectorSize, (iSz - iSOff)); if( nRead>0 ){ rc = p->pBt->pVfs->xRead(p->pFile, iSOff, aBuf, nRead); } while( rc==SQLITE4_OK && iSector>=p->nSector ){ int nNew = p->nSector + 32; u8 **apNew = (u8**)testMalloc(nNew * sizeof(u8*)); memcpy(apNew, p->apSector, p->nSector*sizeof(u8*)); testFree(p->apSector); p->apSector = apNew; p->nSector = nNew; } p->apSector[iSector] = aBuf; } return rc; } static int btVfsWrite(bt_file *pFile, sqlite4_int64 iOff, void *pBuf, int nBuf){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; if( p->pBt && p->pBt->nCrashSync ){ btSaveSectors(p, iOff, nBuf); } return p->pVfs->xWrite(p->pFile, iOff, pBuf, nBuf); } static int btVfsTruncate(bt_file *pFile, sqlite4_int64 iOff){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xTruncate(p->pFile, iOff); } static int btVfsSync(bt_file *pFile){ int rc = SQLITE4_OK; BtFile *p = (BtFile*)pFile; BtDb *pBt = p->pBt; if( pBt ){ if( pBt->bCrash ) return SQLITE4_IOERR; if( pBt->nCrashSync ){ pBt->nCrashSync--; pBt->bCrash = (pBt->nCrashSync==0); if( pBt->bCrash ){ btFlushSectors(pBt->apFile[0], 0); btFlushSectors(pBt->apFile[1], 1); rc = SQLITE4_IOERR; }else{ btFlushSectors(p, 0); } } } if( rc==SQLITE4_OK ){ rc = p->pVfs->xSync(p->pFile); } return rc; } static int btVfsSectorSize(bt_file *pFile){ BtFile *p = (BtFile*)pFile; return p->pVfs->xSectorSize(p->pFile); } static void btDeref(BtDb *p){ p->nRef--; assert( p->nRef>=0 ); if( p->nRef<=0 ) testFree(p); } static int btVfsClose(bt_file *pFile){ BtFile *p = (BtFile*)pFile; BtDb *pBt = p->pBt; int rc; if( pBt ){ btFlushSectors(p, 0); if( p==pBt->apFile[0] ) pBt->apFile[0] = 0; if( p==pBt->apFile[1] ) pBt->apFile[1] = 0; } testFree(p->apSector); rc = p->pVfs->xClose(p->pFile); #if 0 btDeref(p->pBt); #endif testFree(p); return rc; } static int btVfsUnlink(sqlite4_env *pEnv, bt_env *pVfs, const char *zFile){ BtDb *pBt = (BtDb*)pVfs->pVfsCtx; if( pBt->bCrash ) return SQLITE4_IOERR; return pBt->pVfs->xUnlink(pEnv, pBt->pVfs, zFile); } static int btVfsLock(bt_file *pFile, int iLock, int eType){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xLock(p->pFile, iLock, eType); } static int btVfsTestLock(bt_file *pFile, int iLock, int nLock, int eType){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xTestLock(p->pFile, iLock, nLock, eType); } static int btVfsShmMap(bt_file *pFile, int iChunk, int sz, void **ppOut){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xShmMap(p->pFile, iChunk, sz, ppOut); } static void btVfsShmBarrier(bt_file *pFile){ BtFile *p = (BtFile*)pFile; return p->pVfs->xShmBarrier(p->pFile); } static int btVfsShmUnmap(bt_file *pFile, int bDelete){ BtFile *p = (BtFile*)pFile; if( p->pBt && p->pBt->bCrash ) return SQLITE4_IOERR; return p->pVfs->xShmUnmap(p->pFile, bDelete); } static int bt_close(TestDb *pTestDb){ BtDb *p = (BtDb*)pTestDb; int rc = sqlite4BtClose(p->pBt); free(p->aBuffer); if( p->apFile[0] ) p->apFile[0]->pBt = 0; if( p->apFile[1] ) p->apFile[1]->pBt = 0; bgc_detach(p); testFree(p); return rc; } static int btMinTransaction(BtDb *p, int iMin, int *piLevel){ int iLevel; int rc = SQLITE4_OK; iLevel = sqlite4BtTransactionLevel(p->pBt); if( iLevel<iMin ){ rc = sqlite4BtBegin(p->pBt, iMin); *piLevel = iLevel; }else{ *piLevel = -1; } return rc; } static int btRestoreTransaction(BtDb *p, int iLevel, int rcin){ int rc = rcin; if( iLevel>=0 ){ if( rc==SQLITE4_OK ){ rc = sqlite4BtCommit(p->pBt, iLevel); }else{ sqlite4BtRollback(p->pBt, iLevel); } assert( iLevel==sqlite4BtTransactionLevel(p->pBt) ); } return rc; } static int bt_write(TestDb *pTestDb, void *pK, int nK, void *pV, int nV){ BtDb *p = (BtDb*)pTestDb; int iLevel; int rc; rc = btMinTransaction(p, 2, &iLevel); if( rc==SQLITE4_OK ){ if( p->bFastInsert ) sqlite4BtControl(p->pBt, BT_CONTROL_FAST_INSERT_OP, 0); rc = sqlite4BtReplace(p->pBt, pK, nK, pV, nV); rc = btRestoreTransaction(p, iLevel, rc); } return rc; } static int bt_delete(TestDb *pTestDb, void *pK, int nK){ return bt_write(pTestDb, pK, nK, 0, -1); } static int bt_delete_range( TestDb *pTestDb, void *pKey1, int nKey1, void *pKey2, int nKey2 ){ BtDb *p = (BtDb*)pTestDb; bt_cursor *pCsr = 0; int rc = SQLITE4_OK; int iLevel; rc = btMinTransaction(p, 2, &iLevel); if( rc==SQLITE4_OK ){ if( p->bFastInsert ) sqlite4BtControl(p->pBt, BT_CONTROL_FAST_INSERT_OP, 0); rc = sqlite4BtCsrOpen(p->pBt, 0, &pCsr); } while( rc==SQLITE4_OK ){ const void *pK; int n; int nCmp; int res; rc = sqlite4BtCsrSeek(pCsr, pKey1, nKey1, BT_SEEK_GE); if( rc==SQLITE4_INEXACT ) rc = SQLITE4_OK; if( rc!=SQLITE4_OK ) break; rc = sqlite4BtCsrKey(pCsr, &pK, &n); if( rc!=SQLITE4_OK ) break; nCmp = MIN(n, nKey1); res = memcmp(pKey1, pK, nCmp); assert( res<0 || (res==0 && nKey1<=n) ); if( res==0 && nKey1==n ){ rc = sqlite4BtCsrNext(pCsr); if( rc!=SQLITE4_OK ) break; rc = sqlite4BtCsrKey(pCsr, &pK, &n); if( rc!=SQLITE4_OK ) break; } nCmp = MIN(n, nKey2); res = memcmp(pKey2, pK, nCmp); if( res<0 || (res==0 && nKey2<=n) ) break; rc = sqlite4BtDelete(pCsr); } if( rc==SQLITE4_NOTFOUND ) rc = SQLITE4_OK; sqlite4BtCsrClose(pCsr); rc = btRestoreTransaction(p, iLevel, rc); return rc; } static int bt_fetch( TestDb *pTestDb, void *pK, int nK, void **ppVal, int *pnVal ){ BtDb *p = (BtDb*)pTestDb; bt_cursor *pCsr = 0; int iLevel; int rc = SQLITE4_OK; iLevel = sqlite4BtTransactionLevel(p->pBt); if( iLevel==0 ){ rc = sqlite4BtBegin(p->pBt, 1); if( rc!=SQLITE4_OK ) return rc; } if( p->bFastInsert ) sqlite4BtControl(p->pBt, BT_CONTROL_FAST_INSERT_OP, 0); rc = sqlite4BtCsrOpen(p->pBt, 0, &pCsr); if( rc==SQLITE4_OK ){ rc = sqlite4BtCsrSeek(pCsr, pK, nK, BT_SEEK_EQ); if( rc==SQLITE4_OK ){ const void *pV = 0; int nV = 0; rc = sqlite4BtCsrData(pCsr, 0, -1, &pV, &nV); if( rc==SQLITE4_OK ){ if( nV>p->nBuffer ){ free(p->aBuffer); p->aBuffer = (u8*)malloc(nV*2); p->nBuffer = nV*2; } memcpy(p->aBuffer, pV, nV); *pnVal = nV; *ppVal = (void*)(p->aBuffer); } }else if( rc==SQLITE4_INEXACT || rc==SQLITE4_NOTFOUND ){ *ppVal = 0; *pnVal = -1; rc = SQLITE4_OK; } sqlite4BtCsrClose(pCsr); } if( iLevel==0 ) sqlite4BtCommit(p->pBt, 0); return rc; } static int bt_scan( TestDb *pTestDb, void *pCtx, int bReverse, void *pFirst, int nFirst, void *pLast, int nLast, void (*xCallback)(void *, void *, int , void *, int) ){ BtDb *p = (BtDb*)pTestDb; bt_cursor *pCsr = 0; int rc; int iLevel; rc = btMinTransaction(p, 1, &iLevel); if( rc==SQLITE4_OK ){ if( p->bFastInsert ) sqlite4BtControl(p->pBt, BT_CONTROL_FAST_INSERT_OP, 0); rc = sqlite4BtCsrOpen(p->pBt, 0, &pCsr); } if( rc==SQLITE4_OK ){ if( bReverse ){ if( pLast ){ rc = sqlite4BtCsrSeek(pCsr, pLast, nLast, BT_SEEK_LE); }else{ rc = sqlite4BtCsrLast(pCsr); } }else{ rc = sqlite4BtCsrSeek(pCsr, pFirst, nFirst, BT_SEEK_GE); } if( rc==SQLITE4_INEXACT ) rc = SQLITE4_OK; while( rc==SQLITE4_OK ){ const void *pK = 0; int nK = 0; const void *pV = 0; int nV = 0; rc = sqlite4BtCsrKey(pCsr, &pK, &nK); if( rc==SQLITE4_OK ){ rc = sqlite4BtCsrData(pCsr, 0, -1, &pV, &nV); } if( rc!=SQLITE4_OK ) break; if( bReverse ){ if( pFirst ){ int res; int nCmp = MIN(nK, nFirst); res = memcmp(pFirst, pK, nCmp); if( res>0 || (res==0 && nK<nFirst) ) break; } }else{ if( pLast ){ int res; int nCmp = MIN(nK, nLast); res = memcmp(pLast, pK, nCmp); if( res<0 || (res==0 && nK>nLast) ) break; } } xCallback(pCtx, (void*)pK, nK, (void*)pV, nV); if( bReverse ){ rc = sqlite4BtCsrPrev(pCsr); }else{ rc = sqlite4BtCsrNext(pCsr); } } if( rc==SQLITE4_NOTFOUND ) rc = SQLITE4_OK; sqlite4BtCsrClose(pCsr); } rc = btRestoreTransaction(p, iLevel, rc); return rc; } static int bt_begin(TestDb *pTestDb, int iLvl){ BtDb *p = (BtDb*)pTestDb; int rc = sqlite4BtBegin(p->pBt, iLvl); return rc; } static int bt_commit(TestDb *pTestDb, int iLvl){ BtDb *p = (BtDb*)pTestDb; int rc = sqlite4BtCommit(p->pBt, iLvl); return rc; } static int bt_rollback(TestDb *pTestDb, int iLvl){ BtDb *p = (BtDb*)pTestDb; int rc = sqlite4BtRollback(p->pBt, iLvl); return rc; } static int testParseOption( const char **pzIn, /* IN/OUT: pointer to next option */ const char **pzOpt, /* OUT: nul-terminated option name */ const char **pzArg, /* OUT: nul-terminated option argument */ char *pSpace /* Temporary space for output params */ ){ const char *p = *pzIn; const char *pStart; int n; char *pOut = pSpace; while( *p==' ' ) p++; pStart = p; while( *p && *p!='=' ) p++; if( *p==0 ) return 1; n = (p - pStart); memcpy(pOut, pStart, n); *pzOpt = pOut; pOut += n; *pOut++ = '\0'; p++; pStart = p; while( *p && *p!=' ' ) p++; n = (p - pStart); memcpy(pOut, pStart, n); *pzArg = pOut; pOut += n; *pOut++ = '\0'; *pzIn = p; return 0; } static int testParseInt(const char *z, int *piVal){ int i = 0; const char *p = z; while( *p>='0' && *p<='9' ){ i = i*10 + (*p - '0'); p++; } if( *p=='K' || *p=='k' ){ i = i * 1024; p++; }else if( *p=='M' || *p=='m' ){ i = i * 1024 * 1024; p++; } if( *p ) return SQLITE4_ERROR; *piVal = i; return SQLITE4_OK; } static int testBtConfigure(BtDb *pDb, const char *zCfg, int *pbMt){ int rc = SQLITE4_OK; if( zCfg ){ struct CfgParam { const char *zParam; int eParam; } aParam[] = { { "safety", BT_CONTROL_SAFETY }, { "autockpt", BT_CONTROL_AUTOCKPT }, { "multiproc", BT_CONTROL_MULTIPROC }, { "blksz", BT_CONTROL_BLKSZ }, { "pagesz", BT_CONTROL_PAGESZ }, { "mt", -1 }, { "fastinsert", -2 }, { 0, 0 } }; const char *z = zCfg; int n = strlen(z); char *aSpace; const char *zOpt; const char *zArg; aSpace = (char*)testMalloc(n+2); while( rc==SQLITE4_OK && 0==testParseOption(&z, &zOpt, &zArg, aSpace) ){ int i; int iVal; rc = testArgSelect(aParam, "param", zOpt, &i); if( rc!=SQLITE4_OK ) break; rc = testParseInt(zArg, &iVal); if( rc!=SQLITE4_OK ) break; switch( aParam[i].eParam ){ case -1: *pbMt = iVal; break; case -2: pDb->bFastInsert = 1; break; default: rc = sqlite4BtControl(pDb->pBt, aParam[i].eParam, (void*)&iVal); break; } } testFree(aSpace); } return rc; } int test_bt_open( const char *zSpec, const char *zFilename, int bClear, TestDb **ppDb ){ static const DatabaseMethods SqlMethods = { bt_close, bt_write, bt_delete, bt_delete_range, bt_fetch, bt_scan, bt_begin, bt_commit, bt_rollback }; BtDb *p = 0; bt_db *pBt = 0; int rc; sqlite4_env *pEnv = sqlite4_env_default(); if( bClear && zFilename && zFilename[0] ){ char *zLog = sqlite3_mprintf("%s-wal", zFilename); unlink(zFilename); unlink(zLog); sqlite3_free(zLog); } rc = sqlite4BtNew(pEnv, 0, &pBt); if( rc==SQLITE4_OK ){ int mt = 0; /* True for multi-threaded connection */ p = (BtDb*)testMalloc(sizeof(BtDb)); p->base.pMethods = &SqlMethods; p->pBt = pBt; p->pEnv = pEnv; p->nRef = 1; p->env.pVfsCtx = (void*)p; p->env.xFullpath = btVfsFullpath; p->env.xOpen = btVfsOpen; p->env.xSize = btVfsSize; p->env.xRead = btVfsRead; p->env.xWrite = btVfsWrite; p->env.xTruncate = btVfsTruncate; p->env.xSync = btVfsSync; p->env.xSectorSize = btVfsSectorSize; p->env.xClose = btVfsClose; p->env.xUnlink = btVfsUnlink; p->env.xLock = btVfsLock; p->env.xTestLock = btVfsTestLock; p->env.xShmMap = btVfsShmMap; p->env.xShmBarrier = btVfsShmBarrier; p->env.xShmUnmap = btVfsShmUnmap; sqlite4BtControl(pBt, BT_CONTROL_GETVFS, (void*)&p->pVfs); sqlite4BtControl(pBt, BT_CONTROL_SETVFS, (void*)&p->env); rc = testBtConfigure(p, zSpec, &mt); if( rc==SQLITE4_OK ){ rc = sqlite4BtOpen(pBt, zFilename); } if( rc==SQLITE4_OK && mt ){ int nAuto = 0; rc = bgc_attach(p, zSpec); sqlite4BtControl(pBt, BT_CONTROL_AUTOCKPT, (void*)&nAuto); } } if( rc!=SQLITE4_OK && p ){ bt_close(&p->base); } *ppDb = &p->base; return rc; } int test_fbt_open( const char *zSpec, const char *zFilename, int bClear, TestDb **ppDb ){ return test_bt_open("fast=1", zFilename, bClear, ppDb); } int test_fbts_open( const char *zSpec, const char *zFilename, int bClear, TestDb **ppDb ){ return test_bt_open("fast=1 blksz=32K pagesz=512", zFilename, bClear, ppDb); } void tdb_bt_prepare_sync_crash(TestDb *pTestDb, int iSync){ BtDb *p = (BtDb*)pTestDb; assert( pTestDb->pMethods->xClose==bt_close ); assert( p->bCrash==0 ); p->nCrashSync = iSync; } bt_db *tdb_bt(TestDb *pDb){ if( pDb->pMethods->xClose==bt_close ){ return ((BtDb *)pDb)->pBt; } return 0; } /************************************************************************* ** Beginning of code for background checkpointer. */ struct bt_ckpter { sqlite4_buffer file; /* File name */ sqlite4_buffer spec; /* Options */ int nLogsize; /* Minimum log size to checkpoint */ int nRef; /* Number of clients */ int bDoWork; /* Set by client threads */ pthread_t ckpter_thread; /* Checkpointer thread */ pthread_cond_t ckpter_cond; /* Condition var the ckpter waits on */ pthread_mutex_t ckpter_mutex; /* Mutex used with ckpter_cond */ bt_ckpter *pNext; /* Next object in list at gBgc.pCkpter */ }; static struct GlobalBackgroundCheckpointer { bt_ckpter *pCkpter; /* Linked list of checkpointers */ } gBgc; static void *bgc_main(void *pArg){ BtDb *pDb = 0; int rc; int mt; bt_ckpter *pCkpter = (bt_ckpter*)pArg; rc = test_bt_open("", (char*)pCkpter->file.p, 0, (TestDb**)&pDb); assert( rc==SQLITE4_OK ); rc = testBtConfigure(pDb, (char*)pCkpter->spec.p, &mt); while( pCkpter->nRef>0 ){ bt_db *db = pDb->pBt; int nLog = 0; sqlite4BtBegin(db, 1); sqlite4BtCommit(db, 0); sqlite4BtControl(db, BT_CONTROL_LOGSIZE, (void*)&nLog); if( nLog>=pCkpter->nLogsize ){ int rc; bt_checkpoint ckpt; memset(&ckpt, 0, sizeof(bt_checkpoint)); ckpt.nFrameBuffer = nLog/2; rc = sqlite4BtControl(db, BT_CONTROL_CHECKPOINT, (void*)&ckpt); assert( rc==SQLITE4_OK ); sqlite4BtControl(db, BT_CONTROL_LOGSIZE, (void*)&nLog); } /* The thread will wake up when it is signaled either because another ** thread has created some work for this one or because the connection ** is being closed. */ pthread_mutex_lock(&pCkpter->ckpter_mutex); if( pCkpter->bDoWork==0 ){ pthread_cond_wait(&pCkpter->ckpter_cond, &pCkpter->ckpter_mutex); } pCkpter->bDoWork = 0; pthread_mutex_unlock(&pCkpter->ckpter_mutex); } if( pDb ) bt_close((TestDb*)pDb); return 0; } static void bgc_logsize_cb(void *pCtx, int nLogsize){ bt_ckpter *p = (bt_ckpter*)pCtx; if( nLogsize>=p->nLogsize ){ pthread_mutex_lock(&p->ckpter_mutex); p->bDoWork = 1; pthread_cond_signal(&p->ckpter_cond); pthread_mutex_unlock(&p->ckpter_mutex); } } static int bgc_attach(BtDb *pDb, const char *zSpec){ int rc; int n; bt_info info; bt_ckpter *pCkpter; /* Figure out the full path to the database opened by handle pDb. */ info.eType = BT_INFO_FILENAME; info.pgno = 0; sqlite4_buffer_init(&info.output, 0); rc = sqlite4BtControl(pDb->pBt, BT_CONTROL_INFO, (void*)&info); if( rc!=SQLITE4_OK ) return rc; sqlite4_mutex_enter(sqlite4_mutex_alloc(pDb->pEnv, SQLITE4_MUTEX_STATIC_KV)); /* Search for an existing bt_ckpter object. */ n = info.output.n; for(pCkpter=gBgc.pCkpter; pCkpter; pCkpter=pCkpter->pNext){ if( n==pCkpter->file.n && 0==memcmp(info.output.p, pCkpter->file.p, n) ){ break; } } /* Failed to find a suitable checkpointer. Create a new one. */ if( pCkpter==0 ){ bt_logsizecb cb; pCkpter = testMalloc(sizeof(bt_ckpter)); memcpy(&pCkpter->file, &info.output, sizeof(sqlite4_buffer)); info.output.p = 0; pCkpter->pNext = gBgc.pCkpter; pCkpter->nLogsize = 1000; gBgc.pCkpter = pCkpter; pCkpter->nRef = 1; sqlite4_buffer_init(&pCkpter->spec, 0); rc = sqlite4_buffer_set(&pCkpter->spec, zSpec, strlen(zSpec)+1); assert( rc==SQLITE4_OK ); /* Kick off the checkpointer thread. */ if( rc==0 ) rc = pthread_cond_init(&pCkpter->ckpter_cond, 0); if( rc==0 ) rc = pthread_mutex_init(&pCkpter->ckpter_mutex, 0); if( rc==0 ){ rc = pthread_create(&pCkpter->ckpter_thread, 0, bgc_main, (void*)pCkpter); } assert( rc==0 ); /* todo: Fix this */ /* Set up the logsize callback for the client thread */ cb.pCtx = (void*)pCkpter; cb.xLogsize = bgc_logsize_cb; sqlite4BtControl(pDb->pBt, BT_CONTROL_LOGSIZECB, (void*)&cb); }else{ pCkpter->nRef++; } /* Assuming a checkpointer was encountered or effected, attach the ** connection to it. */ if( pCkpter ){ pDb->pCkpter = pCkpter; } sqlite4_mutex_leave(sqlite4_mutex_alloc(pDb->pEnv, SQLITE4_MUTEX_STATIC_KV)); sqlite4_buffer_clear(&info.output); return rc; } static int bgc_detach(BtDb *pDb){ int rc = SQLITE4_OK; bt_ckpter *pCkpter = pDb->pCkpter; if( pCkpter ){ int bShutdown = 0; /* True if this is the last reference */ sqlite4_mutex_enter(sqlite4_mutex_alloc(pDb->pEnv,SQLITE4_MUTEX_STATIC_KV)); pCkpter->nRef--; if( pCkpter->nRef==0 ){ bt_ckpter **pp; *pp = pCkpter->pNext; for(pp=&gBgc.pCkpter; *pp!=pCkpter; pp=&((*pp)->pNext)); bShutdown = 1; } sqlite4_mutex_leave(sqlite4_mutex_alloc(pDb->pEnv,SQLITE4_MUTEX_STATIC_KV)); if( bShutdown ){ void *pDummy; /* Signal the checkpointer thread. */ pthread_mutex_lock(&pCkpter->ckpter_mutex); pCkpter->bDoWork = 1; pthread_cond_signal(&pCkpter->ckpter_cond); pthread_mutex_unlock(&pCkpter->ckpter_mutex); /* Join the checkpointer thread. */ pthread_join(pCkpter->ckpter_thread, &pDummy); pthread_cond_destroy(&pCkpter->ckpter_cond); pthread_mutex_destroy(&pCkpter->ckpter_mutex); sqlite4_buffer_clear(&pCkpter->file); sqlite4_buffer_clear(&pCkpter->spec); testFree(pCkpter); } pDb->pCkpter = 0; } return rc; } /* ** End of background checkpointer. *************************************************************************/
12,961
1,666
package org.grobid.core.analyzers; import org.grobid.core.layout.LayoutToken; import org.grobid.core.lang.Language; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; /** * Abstract analyzer for tokenizing/filtering text. * */ public interface Analyzer { List<String> tokenize(String text); List<String> tokenize(String text, Language lang); List<String> retokenize(List<String> chunks); List<LayoutToken> tokenizeWithLayoutToken(String text); String getName(); }
161
1,691
package com.kodedu.service; import javafx.event.ActionEvent; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; /** * Created by usta on 25.12.2014. */ public interface ThreadService { public ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit timeUnit); public ScheduledFuture<?> scheduleWithDelay(Runnable runnable, long initialDelay, long delay, TimeUnit timeUnit); // Runs Task in background thread pool public <T> Future<?> runTaskLater(Runnable runnable); // Runs task in JavaFX Thread public void runActionLater(Consumer<ActionEvent> consumer); // Runs task in JavaFX Thread public void runActionLater(final Runnable runnable); public void runActionLater(Runnable runnable, boolean force); public void start(Runnable runnable); public Executor executor(); public static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { // logger.error("Error in Thread#sleep", e); } } public Buff buff(String id); public <T> T supply(Supplier<T> supplier); public <T> void runActionLater(Consumer<T> consumer, T t); public ScheduledFuture<?> scheduleWithDelay(Runnable runnable, int timeBetweenFramesMS, TimeUnit milliseconds); }
497
14,668
// 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 CHROME_BROWSER_SIGNIN_HEADER_MODIFICATION_DELEGATE_IMPL_H_ #define CHROME_BROWSER_SIGNIN_HEADER_MODIFICATION_DELEGATE_IMPL_H_ #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "build/buildflag.h" #include "chrome/browser/signin/header_modification_delegate.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "content/public/browser/browser_thread.h" #include "extensions/buildflags/buildflags.h" class Profile; namespace signin { // This class wraps the FixAccountConsistencyRequestHeader and // ProcessAccountConsistencyResponseHeaders in the HeaderModificationDelegate // interface. class HeaderModificationDelegateImpl : public HeaderModificationDelegate { public: #if defined(OS_ANDROID) explicit HeaderModificationDelegateImpl(Profile* profile, bool incognito_enabled); #else explicit HeaderModificationDelegateImpl(Profile* profile); #endif HeaderModificationDelegateImpl(const HeaderModificationDelegateImpl&) = delete; HeaderModificationDelegateImpl& operator=( const HeaderModificationDelegateImpl&) = delete; ~HeaderModificationDelegateImpl() override; // HeaderModificationDelegate bool ShouldInterceptNavigation(content::WebContents* contents) override; void ProcessRequest(ChromeRequestAdapter* request_adapter, const GURL& redirect_url) override; void ProcessResponse(ResponseAdapter* response_adapter, const GURL& redirect_url) override; #if BUILDFLAG(ENABLE_EXTENSIONS) // Returns true if the request comes from a web view and should be ignored // (i.e. not intercepted). // Returns false if the request does not come from a web view. // Requests coming from most guest web views are ignored. In particular the // requests coming from the InlineLoginUI are not intercepted (see // http://crbug.com/428396). Requests coming from the chrome identity // extension consent flow are not ignored. static bool ShouldIgnoreGuestWebViewRequest(content::WebContents* contents); #endif private: raw_ptr<Profile> profile_; scoped_refptr<content_settings::CookieSettings> cookie_settings_; #if defined(OS_ANDROID) bool incognito_enabled_; #endif }; } // namespace signin #endif // CHROME_BROWSER_SIGNIN_HEADER_MODIFICATION_DELEGATE_IMPL_H_
812
647
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package io.atomix.copycat.client.util; import io.atomix.catalyst.concurrent.Listener; import io.atomix.catalyst.transport.Address; import io.atomix.catalyst.transport.Client; import io.atomix.catalyst.transport.Connection; import io.atomix.catalyst.transport.TransportException; import io.atomix.catalyst.util.Assert; import io.atomix.copycat.error.CopycatError; import io.atomix.copycat.protocol.ConnectRequest; import io.atomix.copycat.protocol.ConnectResponse; import io.atomix.copycat.protocol.Request; import io.atomix.copycat.protocol.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.ConnectException; import java.nio.channels.ClosedChannelException; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; /** * Client connection that recursively connects to servers in the cluster and attempts to submit requests. * * @author <a href="http://github.com/kuujo><NAME></a> */ public class ClientConnection implements Connection { private static final Logger LOGGER = LoggerFactory.getLogger(ClientConnection.class); private final String id; private final Client client; private final AddressSelector selector; private CompletableFuture<Connection> connectFuture; private final Map<Class<?>, Function> handlers = new ConcurrentHashMap<>(); private Connection connection; private boolean open = true; public ClientConnection(String id, Client client, AddressSelector selector) { this.id = Assert.notNull(id, "id"); this.client = Assert.notNull(client, "client"); this.selector = Assert.notNull(selector, "selector"); } /** * Returns the current selector leader. * * @return The current selector leader. */ public Address leader() { return selector.leader(); } /** * Returns the current set of servers. * * @return The current set of servers. */ public Collection<Address> servers() { return selector.servers(); } /** * Resets the client connection. * * @return The client connection. */ public ClientConnection reset() { selector.reset(); return this; } /** * Resets the client connection. * * @param leader The current cluster leader. * @param servers The current servers. * @return The client connection. */ public ClientConnection reset(Address leader, Collection<Address> servers) { selector.reset(leader, servers); return this; } @Override public CompletableFuture<Void> send(Object request) { CompletableFuture<Void> future = new CompletableFuture<>(); sendRequest((Request) request, (r, c) -> c.send(r), future); return future; } @Override public <T, U> CompletableFuture<U> sendAndReceive(T request) { CompletableFuture<U> future = new CompletableFuture<>(); sendRequest((Request) request, (r, c) -> c.sendAndReceive(r), future); return future; } /** * Sends the given request attempt to the cluster. */ private <T extends Request, U> void sendRequest(T request, BiFunction<Request, Connection, CompletableFuture<U>> sender, CompletableFuture<U> future) { if (open) { connect().whenComplete((c, e) -> sendRequest(request, sender, c, e, future)); } } /** * Sends the given request attempt to the cluster via the given connection if connected. */ private <T extends Request, U> void sendRequest(T request, BiFunction<Request, Connection, CompletableFuture<U>> sender, Connection connection, Throwable error, CompletableFuture<U> future) { if (open) { if (error == null) { if (connection != null) { LOGGER.trace("{} - Sending {}", id, request); sender.apply(request, connection).whenComplete((r, e) -> { if (e != null || r != null) { handleResponse(request, sender, connection, (Response) r, e, future); } else { future.complete(null); } }); } else { future.completeExceptionally(new ConnectException("Failed to connect to the cluster")); } } else { LOGGER.trace("{} - Resending {}: {}", id, request, error); resendRequest(error, request, sender, connection, future); } } } /** * Resends a request due to a request failure, resetting the connection if necessary. */ @SuppressWarnings("unchecked") private <T extends Request> void resendRequest(Throwable cause, T request, BiFunction sender, Connection connection, CompletableFuture future) { // If the connection has not changed, reset it and connect to the next server. if (this.connection == connection) { LOGGER.trace("{} - Resetting connection. Reason: {}", id, cause); this.connection = null; connection.close(); } // Create a new connection and resend the request. This will force retries to piggyback on any existing // connect attempts. connect().whenComplete((c, e) -> sendRequest(request, sender, c, e, future)); } /** * Handles a response from the cluster. */ @SuppressWarnings("unchecked") private <T extends Request> void handleResponse(T request, BiFunction sender, Connection connection, Response response, Throwable error, CompletableFuture future) { if (open) { if (error == null) { if (response.status() == Response.Status.OK || response.error() == CopycatError.Type.COMMAND_ERROR || response.error() == CopycatError.Type.QUERY_ERROR || response.error() == CopycatError.Type.APPLICATION_ERROR || response.error() == CopycatError.Type.UNKNOWN_SESSION_ERROR || response.error() == CopycatError.Type.INTERNAL_ERROR) { LOGGER.trace("{} - Received {}", id, response); future.complete(response); } else { resendRequest(response.error().createException(), request, sender, connection, future); } } else if (error instanceof ConnectException || error instanceof TimeoutException || error instanceof TransportException || error instanceof ClosedChannelException) { resendRequest(error, request, sender, connection, future); } else { LOGGER.debug("{} - {} failed! Reason: {}", id, request, error); future.completeExceptionally(error); } } } /** * Connects to the cluster. */ private CompletableFuture<Connection> connect() { // If the address selector has been reset then reset the connection. if (selector.state() == AddressSelector.State.RESET && connection != null) { if (connectFuture != null) { return connectFuture; } CompletableFuture<Connection> future = new OrderedCompletableFuture<>(); future.whenComplete((r, e) -> this.connectFuture = null); this.connectFuture = future; Connection oldConnection = this.connection; this.connection = null; oldConnection.close(); connect(future); return future; } // If a connection was already established then use that connection. if (connection != null) { return CompletableFuture.completedFuture(connection); } // If a connection is currently being established then piggyback on the connect future. if (connectFuture != null) { return connectFuture; } // Create a new connect future and connect to the first server in the cluster. CompletableFuture<Connection> future = new OrderedCompletableFuture<>(); future.whenComplete((r, e) -> this.connectFuture = null); this.connectFuture = future; reset().connect(future); return future; } /** * Attempts to connect to the cluster. */ private void connect(CompletableFuture<Connection> future) { if (!selector.hasNext()) { LOGGER.debug("{} - Failed to connect to the cluster", id); future.complete(null); } else { Address address = selector.next(); LOGGER.debug("{} - Connecting to {}", id, address); client.connect(address).whenComplete((c, e) -> handleConnection(address, c, e, future)); } } /** * Handles a connection to a server. */ private void handleConnection(Address address, Connection connection, Throwable error, CompletableFuture<Connection> future) { if (open) { if (error == null) { setupConnection(address, connection, future); } else { LOGGER.debug("{} - Failed to connect! Reason: {}", id, error); connect(future); } } } /** * Sets up the given connection. */ @SuppressWarnings("unchecked") private void setupConnection(Address address, Connection connection, CompletableFuture<Connection> future) { LOGGER.debug("{} - Setting up connection to {}", id, address); this.connection = connection; connection.onClose(c -> { if (c.equals(this.connection)) { LOGGER.debug("{} - Connection closed", id); this.connection = null; } }); connection.onException(c -> { if (c.equals(this.connection)) { LOGGER.debug("{} - Connection lost", id); this.connection = null; } }); for (Map.Entry<Class<?>, Function> entry : handlers.entrySet()) { connection.handler(entry.getKey(), entry.getValue()); } // When we first connect to a new server, first send a ConnectRequest to the server to establish // the connection with the server-side state machine. ConnectRequest request = ConnectRequest.builder() .withClientId(id) .build(); LOGGER.trace("{} - Sending {}", id, request); connection.<ConnectRequest, ConnectResponse>sendAndReceive(request).whenComplete((r, e) -> handleConnectResponse(r, e, future)); } /** * Handles a connect response. */ private void handleConnectResponse(ConnectResponse response, Throwable error, CompletableFuture<Connection> future) { if (open) { if (error == null) { LOGGER.trace("{} - Received {}", id, response); // If the connection was successfully created, immediately send a keep-alive request // to the server to ensure we maintain our session and get an updated list of server addresses. if (response.status() == Response.Status.OK) { selector.reset(response.leader(), response.members()); future.complete(connection); } else { connect(future); } } else { LOGGER.debug("{} - Failed to connect! Reason: {}", id, error); connect(future); } } } @Override public <T, U> Connection handler(Class<T> type, Consumer<T> handler) { return handler(type, r -> { handler.accept(r); return null; }); } @Override public <T, U> Connection handler(Class<T> type, Function<T, CompletableFuture<U>> handler) { Assert.notNull(type, "type"); Assert.notNull(handler, "handler"); handlers.put(type, handler); if (connection != null) connection.handler(type, handler); return this; } @Override public Listener<Throwable> onException(Consumer<Throwable> listener) { throw new UnsupportedOperationException(); } @Override public Listener<Connection> onClose(Consumer<Connection> listener) { throw new UnsupportedOperationException(); } @Override public CompletableFuture<Void> close() { open = false; return CompletableFuture.completedFuture(null); } }
4,085
14,668
<filename>vendor/chromium/mojo/public/cpp/bindings/unique_associated_receiver_set.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 MOJO_PUBLIC_CPP_BINDINGS_UNIQUE_ASSOCIATED_RECEIVER_SET_H_ #define MOJO_PUBLIC_CPP_BINDINGS_UNIQUE_ASSOCIATED_RECEIVER_SET_H_ #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_receiver_set.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/unique_ptr_impl_ref_traits.h" namespace mojo { // This class manages a set of associated receiving endpoints where each // endpoint is bound to a unique implementation of the interface owned by this // object. That is to say, for every bound AssociatedReceiver<T> in the set, // there is a dedicated unique_ptr<T> owned by the set and receiving messages. // // Each owned implementation of T has its lifetime automatically managed by the // UniqueAssociatedReceiverSet, destroying an instance whenever its receiver is // disconnected because the remote endpoint intentionally hung up, crashed, or // sent malformed message. template <typename Interface, typename ContextType = void, typename Deleter = std::default_delete<Interface>> using UniqueAssociatedReceiverSet = ReceiverSetBase< AssociatedReceiver<Interface, UniquePtrImplRefTraits<Interface, Deleter>>, ContextType>; } // namespace mojo #endif // MOJO_PUBLIC_CPP_BINDINGS_UNIQUE_ASSOCIATED_RECEIVER_SET_H_
499
14,668
<reponame>chromium/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/aura/test/ui_controls_ozone.h" #include "base/ignore_result.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/events/event_utils.h" namespace aura { namespace test { // static unsigned UIControlsOzone::button_down_mask_ = 0; UIControlsOzone::UIControlsOzone(WindowTreeHost* host) : host_(host) {} UIControlsOzone::~UIControlsOzone() = default; bool UIControlsOzone::SendKeyPress(gfx::NativeWindow window, ui::KeyboardCode key, bool control, bool shift, bool alt, bool command) { return SendKeyPressNotifyWhenDone(window, key, control, shift, alt, command, base::OnceClosure()); } bool UIControlsOzone::SendKeyPressNotifyWhenDone(gfx::NativeWindow window, ui::KeyboardCode key, bool control, bool shift, bool alt, bool command, base::OnceClosure closure) { WindowTreeHost* optional_host = nullptr; // Send the key event to the window's host, which may not match |host_|. // This logic should probably exist for the non-aura path as well. // TODO(https://crbug.com/1116649) Support non-aura path. #if defined(USE_AURA) if (window != nullptr && window->GetHost() != nullptr && window->GetHost() != host_) optional_host = window->GetHost(); #endif int flags = button_down_mask_; int64_t display_id = display::Screen::GetScreen()->GetDisplayNearestWindow(window).id(); if (control) { flags |= ui::EF_CONTROL_DOWN; PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_CONTROL, flags, display_id, base::OnceClosure(), optional_host); } if (shift) { flags |= ui::EF_SHIFT_DOWN; PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SHIFT, flags, display_id, base::OnceClosure(), optional_host); } if (alt) { flags |= ui::EF_ALT_DOWN; PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_MENU, flags, display_id, base::OnceClosure(), optional_host); } if (command) { flags |= ui::EF_COMMAND_DOWN; PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_LWIN, flags, display_id, base::OnceClosure(), optional_host); } PostKeyEvent(ui::ET_KEY_PRESSED, key, flags, display_id, base::OnceClosure(), optional_host); const bool has_modifier = control || shift || alt || command; // Pass the real closure to the last generated KeyEvent. PostKeyEvent(ui::ET_KEY_RELEASED, key, flags, display_id, has_modifier ? base::OnceClosure() : std::move(closure), optional_host); if (alt) { flags &= ~ui::EF_ALT_DOWN; PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_MENU, flags, display_id, (shift || control || command) ? base::OnceClosure() : std::move(closure), optional_host); } if (shift) { flags &= ~ui::EF_SHIFT_DOWN; PostKeyEvent( ui::ET_KEY_RELEASED, ui::VKEY_SHIFT, flags, display_id, (control || command) ? base::OnceClosure() : std::move(closure), optional_host); } if (control) { flags &= ~ui::EF_CONTROL_DOWN; PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_CONTROL, flags, display_id, command ? base::OnceClosure() : std::move(closure), optional_host); } if (command) { flags &= ~ui::EF_COMMAND_DOWN; PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_LWIN, flags, display_id, std::move(closure), optional_host); } return true; } bool UIControlsOzone::SendMouseMove(int screen_x, int screen_y) { return SendMouseMoveNotifyWhenDone(screen_x, screen_y, base::OnceClosure()); } bool UIControlsOzone::SendMouseMoveNotifyWhenDone(int screen_x, int screen_y, base::OnceClosure closure) { gfx::PointF host_location(screen_x, screen_y); int64_t display_id = display::kInvalidDisplayId; if (!ScreenDIPToHostPixels(&host_location, &display_id)) return false; ui::EventType event_type; if (button_down_mask_) event_type = ui::ET_MOUSE_DRAGGED; else event_type = ui::ET_MOUSE_MOVED; PostMouseEvent(event_type, host_location, button_down_mask_, 0, display_id, std::move(closure)); return true; } bool UIControlsOzone::SendMouseEvents(ui_controls::MouseButton type, int button_state, int accelerator_state) { return SendMouseEventsNotifyWhenDone(type, button_state, base::OnceClosure(), accelerator_state); } bool UIControlsOzone::SendMouseEventsNotifyWhenDone( ui_controls::MouseButton type, int button_state, base::OnceClosure closure, int accelerator_state) { gfx::PointF host_location(Env::GetInstance()->last_mouse_location()); int64_t display_id = display::kInvalidDisplayId; if (!ScreenDIPToHostPixels(&host_location, &display_id)) return false; int changed_button_flag = 0; switch (type) { case ui_controls::LEFT: changed_button_flag = ui::EF_LEFT_MOUSE_BUTTON; break; case ui_controls::MIDDLE: changed_button_flag = ui::EF_MIDDLE_MOUSE_BUTTON; break; case ui_controls::RIGHT: changed_button_flag = ui::EF_RIGHT_MOUSE_BUTTON; break; default: NOTREACHED(); break; } // Process the accelerator key state. int flag = changed_button_flag; if (accelerator_state & ui_controls::kShift) flag |= ui::EF_SHIFT_DOWN; if (accelerator_state & ui_controls::kControl) flag |= ui::EF_CONTROL_DOWN; if (accelerator_state & ui_controls::kAlt) flag |= ui::EF_ALT_DOWN; if (accelerator_state & ui_controls::kCommand) flag |= ui::EF_COMMAND_DOWN; if (button_state & ui_controls::DOWN) { button_down_mask_ |= flag; // Pass the real closure to the last generated MouseEvent. PostMouseEvent(ui::ET_MOUSE_PRESSED, host_location, button_down_mask_ | flag, changed_button_flag, display_id, (button_state & ui_controls::UP) ? base::OnceClosure() : std::move(closure)); } if (button_state & ui_controls::UP) { button_down_mask_ &= ~flag; PostMouseEvent(ui::ET_MOUSE_RELEASED, host_location, button_down_mask_ | flag, changed_button_flag, display_id, std::move(closure)); } return true; } bool UIControlsOzone::SendMouseClick(ui_controls::MouseButton type) { return SendMouseEvents(type, ui_controls::UP | ui_controls::DOWN, ui_controls::kNoAccelerator); } #if BUILDFLAG(IS_CHROMEOS_ASH) bool UIControlsOzone::SendTouchEvents(int action, int id, int x, int y) { return SendTouchEventsNotifyWhenDone(action, id, x, y, base::OnceClosure()); } bool UIControlsOzone::SendTouchEventsNotifyWhenDone(int action, int id, int x, int y, base::OnceClosure task) { DCHECK_NE(0, action); gfx::PointF host_location(x, y); int64_t display_id = display::kInvalidDisplayId; if (!ScreenDIPToHostPixels(&host_location, &display_id)) return false; bool has_move = action & ui_controls::MOVE; bool has_release = action & ui_controls::RELEASE; if (action & ui_controls::PRESS) { PostTouchEvent( ui::ET_TOUCH_PRESSED, host_location, id, display_id, (has_move || has_release) ? base::OnceClosure() : std::move(task)); } if (has_move) { PostTouchEvent(ui::ET_TOUCH_MOVED, host_location, id, display_id, has_release ? base::OnceClosure() : std::move(task)); } if (has_release) { PostTouchEvent(ui::ET_TOUCH_RELEASED, host_location, id, display_id, std::move(task)); } return true; } #endif void UIControlsOzone::SendEventToSink(ui::Event* event, int64_t display_id, base::OnceClosure closure, WindowTreeHost* optional_host) { // Post the task before processing the event. This is necessary in case // processing the event results in a nested message loop. if (closure) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(closure)); } WindowTreeHost* host = optional_host ? optional_host : host_; ui::EventSourceTestApi event_source_test(host->GetEventSource()); ignore_result(event_source_test.SendEventToSink(event)); } void UIControlsOzone::PostKeyEvent(ui::EventType type, ui::KeyboardCode key_code, int flags, int64_t display_id, base::OnceClosure closure, WindowTreeHost* optional_host) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&UIControlsOzone::PostKeyEventTask, base::Unretained(this), type, key_code, flags, display_id, std::move(closure), optional_host)); } void UIControlsOzone::PostKeyEventTask(ui::EventType type, ui::KeyboardCode key_code, int flags, int64_t display_id, base::OnceClosure closure, WindowTreeHost* optional_host) { // Do not rewrite injected events. See crbug.com/136465. flags |= ui::EF_FINAL; ui::KeyEvent key_event(type, key_code, flags); if (type == ui::ET_KEY_PRESSED) { // Set a property as if this is a key event not consumed by IME. // Ozone/X11+GTK IME works so already. Ozone/wayland IME relies on this // flag to work properly. key_event.SetProperties({{ ui::kPropertyKeyboardImeFlag, std::vector<uint8_t>{ui::kPropertyKeyboardImeIgnoredFlag}, }}); } SendEventToSink(&key_event, display_id, std::move(closure), optional_host); } void UIControlsOzone::PostMouseEvent(ui::EventType type, const gfx::PointF& host_location, int flags, int changed_button_flags, int64_t display_id, base::OnceClosure closure) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&UIControlsOzone::PostMouseEventTask, base::Unretained(this), type, host_location, flags, changed_button_flags, display_id, std::move(closure))); } void UIControlsOzone::PostMouseEventTask(ui::EventType type, const gfx::PointF& host_location, int flags, int changed_button_flags, int64_t display_id, base::OnceClosure closure) { ui::MouseEvent mouse_event(type, host_location, host_location, ui::EventTimeForNow(), flags, changed_button_flags); // This hack is necessary to set the repeat count for clicks. ui::MouseEvent mouse_event2(&mouse_event); SendEventToSink(&mouse_event2, display_id, std::move(closure)); } void UIControlsOzone::PostTouchEvent(ui::EventType type, const gfx::PointF& host_location, int id, int64_t display_id, base::OnceClosure closure) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&UIControlsOzone::PostTouchEventTask, base::Unretained(this), type, host_location, id, display_id, std::move(closure))); } void UIControlsOzone::PostTouchEventTask(ui::EventType type, const gfx::PointF& host_location, int id, int64_t display_id, base::OnceClosure closure) { ui::PointerDetails details(ui::EventPointerType::kTouch, id, 1.0f, 1.0f, 0.0f); ui::TouchEvent touch_event(type, host_location, host_location, ui::EventTimeForNow(), details); SendEventToSink(&touch_event, display_id, std::move(closure)); } bool UIControlsOzone::ScreenDIPToHostPixels(gfx::PointF* location, int64_t* display_id) { // The location needs to be in display's coordinate. display::Display display = display::Screen::GetScreen()->GetDisplayNearestPoint( gfx::ToFlooredPoint(*location)); if (!display.is_valid()) { LOG(ERROR) << "Failed to find the display for " << location->ToString(); return false; } *display_id = display.id(); *location -= display.bounds().OffsetFromOrigin(); location->Scale(display.device_scale_factor()); return true; } ui_controls::UIControlsAura* CreateUIControlsAura(WindowTreeHost* host) { return new UIControlsOzone(host); } } // namespace test } // namespace aura
7,102
368
/* Plugin-SDK (Grand Theft Auto Vice City) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CPad.h" PLUGIN_SOURCE_FILE PLUGIN_VARIABLE CKeyboardState &CPad::NewKeyState = *reinterpret_cast<CKeyboardState *>(GLOBAL_ADDRESS_BY_VERSION(0x7D15A8, 0x7D15B0, 0x7D05B0)); PLUGIN_VARIABLE CMouseControllerState &CPad::PCTempMouseControllerState = *reinterpret_cast<CMouseControllerState *>(GLOBAL_ADDRESS_BY_VERSION(0x7DD860, 0x7DD868, 0x7DC868)); PLUGIN_VARIABLE CKeyboardState &CPad::OldKeyState = *reinterpret_cast<CKeyboardState *>(GLOBAL_ADDRESS_BY_VERSION(0x7DDB88, 0x7DDB90, 0x7DCB90)); PLUGIN_VARIABLE CKeyboardState &CPad::TempKeyState = *reinterpret_cast<CKeyboardState *>(GLOBAL_ADDRESS_BY_VERSION(0x864A00, 0x864A08, 0x863A08)); PLUGIN_VARIABLE CMouseControllerState &CPad::OldMouseControllerState = *reinterpret_cast<CMouseControllerState *>(GLOBAL_ADDRESS_BY_VERSION(0x936908, 0x936910, 0x935910)); PLUGIN_VARIABLE CMouseControllerState &CPad::NewMouseControllerState = *reinterpret_cast<CMouseControllerState *>(GLOBAL_ADDRESS_BY_VERSION(0x94D788, 0x94D790, 0x94C790)); PLUGIN_VARIABLE char(&CPad::KeyBoardCheatString)[30] = *reinterpret_cast<char(*)[30]>(GLOBAL_ADDRESS_BY_VERSION(0xA10942, 0xA1094A, 0xA0F94A)); PLUGIN_VARIABLE bool &CPad::m_bMapPadOneToPadTwo = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA10AE4, 0xA10AEC, 0xA0FAEC)); PLUGIN_VARIABLE bool &CPad::bDisplayNoControllerMessage = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA10AEC, 0xA10AF4, 0xA0FAF4)); PLUGIN_VARIABLE bool &CPad::bInvertLook4Pad = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA10AF7, 0xA10AFF, 0xA0FAFF)); PLUGIN_VARIABLE bool &CPad::bHasPlayerCheated = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA10B2E, 0xA10B36, 0xA0FB37)); PLUGIN_VARIABLE bool &CPad::bObsoleteControllerMessage = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA10B83, 0xA10B8C, 0xA0FB8D)); PLUGIN_VARIABLE CPad(&Pads)[2] = *reinterpret_cast<CPad(*)[2]>(GLOBAL_ADDRESS_BY_VERSION(0x7DBCB0, 0x7DBCB8, 0x7DACB8)); int ctor_addr(CPad) = ADDRESS_BY_VERSION(0x4AF0F0, 0x4AF110, 0x4AEFC0); int ctor_gaddr(CPad) = GLOBAL_ADDRESS_BY_VERSION(0x4AF0F0, 0x4AF110, 0x4AEFC0); int dtor_addr(CPad) = ADDRESS_BY_VERSION(0x4AF0E0, 0x4AF100, 0x4AEFB0); int dtor_gaddr(CPad) = GLOBAL_ADDRESS_BY_VERSION(0x4AF0E0, 0x4AF100, 0x4AEFB0); int addrof(CPad::AddToPCCheatString) = ADDRESS_BY_VERSION(0x4ABD20, 0x4ABD40, 0x4ABBF0); int gaddrof(CPad::AddToPCCheatString) = GLOBAL_ADDRESS_BY_VERSION(0x4ABD20, 0x4ABD40, 0x4ABBF0); void CPad::AddToPCCheatString(char character) { plugin::CallMethodDynGlobal<CPad *, char>(gaddrof(CPad::AddToPCCheatString), this, character); } int addrof(CPad::CarGunJustDown) = ADDRESS_BY_VERSION(0x4AA9F0, 0x4AAA10, 0x4AA8C0); int gaddrof(CPad::CarGunJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA9F0, 0x4AAA10, 0x4AA8C0); bool CPad::CarGunJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CarGunJustDown), this); } int addrof(CPad::ChangeStationJustDown) = ADDRESS_BY_VERSION(0x4AA590, 0x4AA5B0, 0x4AA460); int gaddrof(CPad::ChangeStationJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA590, 0x4AA5B0, 0x4AA460); bool CPad::ChangeStationJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::ChangeStationJustDown), this); } int addrof(CPad::Clear) = ADDRESS_BY_VERSION(0x4ADBE0, 0x4ADC00, 0x4ADAB0); int gaddrof(CPad::Clear) = GLOBAL_ADDRESS_BY_VERSION(0x4ADBE0, 0x4ADC00, 0x4ADAB0); void CPad::Clear(char bDisablePlayerControls) { plugin::CallMethodDynGlobal<CPad *, char>(gaddrof(CPad::Clear), this, bDisablePlayerControls); } int addrof(CPad::CollectPickupJustDown) = ADDRESS_BY_VERSION(0x4A9F80, 0x4A9FA0, 0x4A9E50); int gaddrof(CPad::CollectPickupJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4A9F80, 0x4A9FA0, 0x4A9E50); bool CPad::CollectPickupJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CollectPickupJustDown), this); } int addrof(CPad::CycleCameraModeDownJustDown) = ADDRESS_BY_VERSION(0x4AA6C0, 0x4AA6E0, 0x4AA590); int gaddrof(CPad::CycleCameraModeDownJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA6C0, 0x4AA6E0, 0x4AA590); bool CPad::CycleCameraModeDownJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CycleCameraModeDownJustDown), this); } int addrof(CPad::CycleCameraModeJustDown) = ADDRESS_BY_VERSION(0x4AA630, 0x4AA650, 0x4AA500); int gaddrof(CPad::CycleCameraModeJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA630, 0x4AA650, 0x4AA500); bool CPad::CycleCameraModeJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CycleCameraModeJustDown), this); } int addrof(CPad::CycleCameraModeUpJustDown) = ADDRESS_BY_VERSION(0x4AA700, 0x4AA720, 0x4AA5D0); int gaddrof(CPad::CycleCameraModeUpJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA700, 0x4AA720, 0x4AA5D0); bool CPad::CycleCameraModeUpJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CycleCameraModeUpJustDown), this); } int addrof(CPad::CycleWeaponLeftJustDown) = ADDRESS_BY_VERSION(0x4AA560, 0x4AA580, 0x4AA430); int gaddrof(CPad::CycleWeaponLeftJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA560, 0x4AA580, 0x4AA430); bool CPad::CycleWeaponLeftJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CycleWeaponLeftJustDown), this); } int addrof(CPad::CycleWeaponRightJustDown) = ADDRESS_BY_VERSION(0x4AA530, 0x4AA550, 0x4AA400); int gaddrof(CPad::CycleWeaponRightJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA530, 0x4AA550, 0x4AA400); bool CPad::CycleWeaponRightJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::CycleWeaponRightJustDown), this); } int addrof(CPad::DuckJustDown) = ADDRESS_BY_VERSION(0x4AA430, 0x4AA450, 0x4AA300); int gaddrof(CPad::DuckJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA430, 0x4AA450, 0x4AA300); bool CPad::DuckJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::DuckJustDown), this); } int addrof(CPad::ExitVehicleJustDown) = ADDRESS_BY_VERSION(0x4AA870, 0x4AA890, 0x4AA740); int gaddrof(CPad::ExitVehicleJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA870, 0x4AA890, 0x4AA740); bool CPad::ExitVehicleJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::ExitVehicleJustDown), this); } int addrof(CPad::ForceCameraBehindPlayer) = ADDRESS_BY_VERSION(0x4A9F00, 0x4A9F20, 0x4A9DD0); int gaddrof(CPad::ForceCameraBehindPlayer) = GLOBAL_ADDRESS_BY_VERSION(0x4A9F00, 0x4A9F20, 0x4A9DD0); bool CPad::ForceCameraBehindPlayer() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::ForceCameraBehindPlayer), this); } int addrof(CPad::GetAccelerate) = ADDRESS_BY_VERSION(0x4AA760, 0x4AA780, 0x4AA630); int gaddrof(CPad::GetAccelerate) = GLOBAL_ADDRESS_BY_VERSION(0x4AA760, 0x4AA780, 0x4AA630); short CPad::GetAccelerate() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetAccelerate), this); } int addrof(CPad::GetAnalogueLeftRight) = ADDRESS_BY_VERSION(0x4AADC0, 0x4AADE0, 0x4AAC90); int gaddrof(CPad::GetAnalogueLeftRight) = GLOBAL_ADDRESS_BY_VERSION(0x4AADC0, 0x4AADE0, 0x4AAC90); short CPad::GetAnalogueLeftRight() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetAnalogueLeftRight), this); } int addrof(CPad::GetAnaloguePadDown) = ADDRESS_BY_VERSION(0x4AA260, 0x4AA280, 0x4AA130); int gaddrof(CPad::GetAnaloguePadDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA260, 0x4AA280, 0x4AA130); bool CPad::GetAnaloguePadDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetAnaloguePadDown), this); } int addrof(CPad::GetAnaloguePadLeft) = ADDRESS_BY_VERSION(0x4AA200, 0x4AA220, 0x4AA0D0); int gaddrof(CPad::GetAnaloguePadLeft) = GLOBAL_ADDRESS_BY_VERSION(0x4AA200, 0x4AA220, 0x4AA0D0); bool CPad::GetAnaloguePadLeft() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetAnaloguePadLeft), this); } int addrof(CPad::GetAnaloguePadLeftJustUp) = ADDRESS_BY_VERSION(0x4AA0D0, 0x4AA0F0, 0x4A9FA0); int gaddrof(CPad::GetAnaloguePadLeftJustUp) = GLOBAL_ADDRESS_BY_VERSION(0x4AA0D0, 0x4AA0F0, 0x4A9FA0); bool CPad::GetAnaloguePadLeftJustUp() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetAnaloguePadLeftJustUp), this); } int addrof(CPad::GetAnaloguePadRight) = ADDRESS_BY_VERSION(0x4AA1A0, 0x4AA1C0, 0x4AA070); int gaddrof(CPad::GetAnaloguePadRight) = GLOBAL_ADDRESS_BY_VERSION(0x4AA1A0, 0x4AA1C0, 0x4AA070); bool CPad::GetAnaloguePadRight() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetAnaloguePadRight), this); } int addrof(CPad::GetAnaloguePadRightJustUp) = ADDRESS_BY_VERSION(0x4AA000, 0x4AA020, 0x4A9ED0); int gaddrof(CPad::GetAnaloguePadRightJustUp) = GLOBAL_ADDRESS_BY_VERSION(0x4AA000, 0x4AA020, 0x4A9ED0); bool CPad::GetAnaloguePadRightJustUp() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetAnaloguePadRightJustUp), this); } int addrof(CPad::GetAnaloguePadUp) = ADDRESS_BY_VERSION(0x4AA2B0, 0x4AA2D0, 0x4AA180); int gaddrof(CPad::GetAnaloguePadUp) = GLOBAL_ADDRESS_BY_VERSION(0x4AA2B0, 0x4AA2D0, 0x4AA180); bool CPad::GetAnaloguePadUp() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetAnaloguePadUp), this); } int addrof(CPad::GetAnalogueUpDown) = ADDRESS_BY_VERSION(0x4AACC0, 0x4AACE0, 0x4AAB90); int gaddrof(CPad::GetAnalogueUpDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AACC0, 0x4AACE0, 0x4AAB90); short CPad::GetAnalogueUpDown() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetAnalogueUpDown), this); } int addrof(CPad::GetBrake) = ADDRESS_BY_VERSION(0x4AA960, 0x4AA980, 0x4AA830); int gaddrof(CPad::GetBrake) = GLOBAL_ADDRESS_BY_VERSION(0x4AA960, 0x4AA980, 0x4AA830); short CPad::GetBrake() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetBrake), this); } int addrof(CPad::GetCarGunFired) = ADDRESS_BY_VERSION(0x4AAA60, 0x4AAA80, 0x4AA930); int gaddrof(CPad::GetCarGunFired) = GLOBAL_ADDRESS_BY_VERSION(0x4AAA60, 0x4AAA80, 0x4AA930); bool CPad::GetCarGunFired() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetCarGunFired), this); } int addrof(CPad::GetCarGunLeftRight) = ADDRESS_BY_VERSION(0x4AAEB0, 0x4AAED0, 0x4AAD80); int gaddrof(CPad::GetCarGunLeftRight) = GLOBAL_ADDRESS_BY_VERSION(0x4AAEB0, 0x4AAED0, 0x4AAD80); short CPad::GetCarGunLeftRight() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetCarGunLeftRight), this); } int addrof(CPad::GetCarGunUpDown) = ADDRESS_BY_VERSION(0x4AAF00, 0x4AAF20, 0x4AADD0); int gaddrof(CPad::GetCarGunUpDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AAF00, 0x4AAF20, 0x4AADD0); short CPad::GetCarGunUpDown() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetCarGunUpDown), this); } int addrof(CPad::GetExitVehicle) = ADDRESS_BY_VERSION(0x4AA8F0, 0x4AA910, 0x4AA7C0); int gaddrof(CPad::GetExitVehicle) = GLOBAL_ADDRESS_BY_VERSION(0x4AA8F0, 0x4AA910, 0x4AA7C0); bool CPad::GetExitVehicle() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetExitVehicle), this); } int addrof(CPad::GetHandBrake) = ADDRESS_BY_VERSION(0x4AA9B0, 0x4AA9D0, 0x4AA880); int gaddrof(CPad::GetHandBrake) = GLOBAL_ADDRESS_BY_VERSION(0x4AA9B0, 0x4AA9D0, 0x4AA880); short CPad::GetHandBrake() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetHandBrake), this); } int addrof(CPad::GetHorn) = ADDRESS_BY_VERSION(0x4AAB60, 0x4AAB80, 0x4AAA30); int gaddrof(CPad::GetHorn) = GLOBAL_ADDRESS_BY_VERSION(0x4AAB60, 0x4AAB80, 0x4AAA30); bool CPad::GetHorn() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetHorn), this); } int addrof(CPad::GetLookBehindForCar) = ADDRESS_BY_VERSION(0x4AAC30, 0x4AAC50, 0x4AAB00); int gaddrof(CPad::GetLookBehindForCar) = GLOBAL_ADDRESS_BY_VERSION(0x4AAC30, 0x4AAC50, 0x4AAB00); bool CPad::GetLookBehindForCar() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetLookBehindForCar), this); } int addrof(CPad::GetLookBehindForPed) = ADDRESS_BY_VERSION(0x4AAC00, 0x4AAC20, 0x4AAAD0); int gaddrof(CPad::GetLookBehindForPed) = GLOBAL_ADDRESS_BY_VERSION(0x4AAC00, 0x4AAC20, 0x4AAAD0); bool CPad::GetLookBehindForPed() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetLookBehindForPed), this); } int addrof(CPad::GetLookLeft) = ADDRESS_BY_VERSION(0x4AAC90, 0x4AACB0, 0x4AAB60); int gaddrof(CPad::GetLookLeft) = GLOBAL_ADDRESS_BY_VERSION(0x4AAC90, 0x4AACB0, 0x4AAB60); bool CPad::GetLookLeft() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetLookLeft), this); } int addrof(CPad::GetLookRight) = ADDRESS_BY_VERSION(0x4AAC60, 0x4AAC80, 0x4AAB30); int gaddrof(CPad::GetLookRight) = GLOBAL_ADDRESS_BY_VERSION(0x4AAC60, 0x4AAC80, 0x4AAB30); bool CPad::GetLookRight() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetLookRight), this); } int addrof(CPad::GetPedWalkLeftRight) = ADDRESS_BY_VERSION(0x4AAE30, 0x4AAE50, 0x4AAD00); int gaddrof(CPad::GetPedWalkLeftRight) = GLOBAL_ADDRESS_BY_VERSION(0x4AAE30, 0x4AAE50, 0x4AAD00); short CPad::GetPedWalkLeftRight() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetPedWalkLeftRight), this); } int addrof(CPad::GetPedWalkUpDown) = ADDRESS_BY_VERSION(0x4AAD40, 0x4AAD60, 0x4AAC10); int gaddrof(CPad::GetPedWalkUpDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AAD40, 0x4AAD60, 0x4AAC10); short CPad::GetPedWalkUpDown() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetPedWalkUpDown), this); } int addrof(CPad::GetSprint) = ADDRESS_BY_VERSION(0x4AA390, 0x4AA3B0, 0x4AA260); int gaddrof(CPad::GetSprint) = GLOBAL_ADDRESS_BY_VERSION(0x4AA390, 0x4AA3B0, 0x4AA260); bool CPad::GetSprint() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetSprint), this); } int addrof(CPad::GetSteeringLeftRight) = ADDRESS_BY_VERSION(0x4AAFD0, 0x4AAFF0, 0x4AAEA0); int gaddrof(CPad::GetSteeringLeftRight) = GLOBAL_ADDRESS_BY_VERSION(0x4AAFD0, 0x4AAFF0, 0x4AAEA0); short CPad::GetSteeringLeftRight() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetSteeringLeftRight), this); } int addrof(CPad::GetSteeringUpDown) = ADDRESS_BY_VERSION(0x4AAF50, 0x4AAF70, 0x4AAE20); int gaddrof(CPad::GetSteeringUpDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AAF50, 0x4AAF70, 0x4AAE20); short CPad::GetSteeringUpDown() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetSteeringUpDown), this); } int addrof(CPad::GetTarget) = ADDRESS_BY_VERSION(0x4AA4D0, 0x4AA4F0, 0x4AA3A0); int gaddrof(CPad::GetTarget) = GLOBAL_ADDRESS_BY_VERSION(0x4AA4D0, 0x4AA4F0, 0x4AA3A0); bool CPad::GetTarget() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::GetTarget), this); } int addrof(CPad::GetWeapon) = ADDRESS_BY_VERSION(0x4AA830, 0x4AA850, 0x4AA700); int gaddrof(CPad::GetWeapon) = GLOBAL_ADDRESS_BY_VERSION(0x4AA830, 0x4AA850, 0x4AA700); short CPad::GetWeapon() { return plugin::CallMethodAndReturnDynGlobal<short, CPad *>(gaddrof(CPad::GetWeapon), this); } int addrof(CPad::HornJustDown) = ADDRESS_BY_VERSION(0x4AAAC0, 0x4AAAE0, 0x4AA990); int gaddrof(CPad::HornJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AAAC0, 0x4AAAE0, 0x4AA990); bool CPad::HornJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::HornJustDown), this); } int addrof(CPad::InputHowLongAgo) = ADDRESS_BY_VERSION(0x4ADBD0, 0x4ADBF0, 0x4ADAA0); int gaddrof(CPad::InputHowLongAgo) = GLOBAL_ADDRESS_BY_VERSION(0x4ADBD0, 0x4ADBF0, 0x4ADAA0); int CPad::InputHowLongAgo() { return plugin::CallMethodAndReturnDynGlobal<int, CPad *>(gaddrof(CPad::InputHowLongAgo), this); } int addrof(CPad::JumpJustDown) = ADDRESS_BY_VERSION(0x4AA400, 0x4AA420, 0x4AA2D0); int gaddrof(CPad::JumpJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA400, 0x4AA420, 0x4AA2D0); bool CPad::JumpJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::JumpJustDown), this); } int addrof(CPad::LookAroundLeftRight) = ADDRESS_BY_VERSION(0x4A9A80, 0x4A9AA0, 0x4A9950); int gaddrof(CPad::LookAroundLeftRight) = GLOBAL_ADDRESS_BY_VERSION(0x4A9A80, 0x4A9AA0, 0x4A9950); int CPad::LookAroundLeftRight() { return plugin::CallMethodAndReturnDynGlobal<int, CPad *>(gaddrof(CPad::LookAroundLeftRight), this); } int addrof(CPad::LookAroundUpDown) = ADDRESS_BY_VERSION(0x4A98F0, 0x4A9910, 0x4A97C0); int gaddrof(CPad::LookAroundUpDown) = GLOBAL_ADDRESS_BY_VERSION(0x4A98F0, 0x4A9910, 0x4A97C0); int CPad::LookAroundUpDown() { return plugin::CallMethodAndReturnDynGlobal<int, CPad *>(gaddrof(CPad::LookAroundUpDown), this); } int addrof(CPad::ReconcileTwoControllersInput) = ADDRESS_BY_VERSION(0x4AD350, 0x4AD370, 0x4AD220); int gaddrof(CPad::ReconcileTwoControllersInput) = GLOBAL_ADDRESS_BY_VERSION(0x4AD350, 0x4AD370, 0x4AD220); CControllerState CPad::ReconcileTwoControllersInput(CControllerState const &controller1, CControllerState const &controller2) { CControllerState ret_result; plugin::CallMethodDynGlobal<CPad *, CControllerState *, CControllerState const &, CControllerState const &>(gaddrof(CPad::ReconcileTwoControllersInput), this, &ret_result, controller1, controller2); return ret_result; } int addrof(CPad::ResetAverageWeapon) = ADDRESS_BY_VERSION(0x4A98A0, 0x4A98C0, 0x4A9770); int gaddrof(CPad::ResetAverageWeapon) = GLOBAL_ADDRESS_BY_VERSION(0x4A98A0, 0x4A98C0, 0x4A9770); void CPad::ResetAverageWeapon() { plugin::CallMethodDynGlobal<CPad *>(gaddrof(CPad::ResetAverageWeapon), this); } int addrof(CPad::SetDrunkInputDelay) = ADDRESS_BY_VERSION(0x4AD340, 0x4AD360, 0x4AD210); int gaddrof(CPad::SetDrunkInputDelay) = GLOBAL_ADDRESS_BY_VERSION(0x4AD340, 0x4AD360, 0x4AD210); void CPad::SetDrunkInputDelay(int bEnable) { plugin::CallMethodDynGlobal<CPad *, int>(gaddrof(CPad::SetDrunkInputDelay), this, bEnable); } int addrof(CPad::ShiftTargetLeftJustDown) = ADDRESS_BY_VERSION(0x4AA360, 0x4AA380, 0x4AA230); int gaddrof(CPad::ShiftTargetLeftJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA360, 0x4AA380, 0x4AA230); bool CPad::ShiftTargetLeftJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::ShiftTargetLeftJustDown), this); } int addrof(CPad::ShiftTargetRightJustDown) = ADDRESS_BY_VERSION(0x4AA300, 0x4AA320, 0x4AA1D0); int gaddrof(CPad::ShiftTargetRightJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA300, 0x4AA320, 0x4AA1D0); bool CPad::ShiftTargetRightJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::ShiftTargetRightJustDown), this); } int addrof(CPad::SniperModeLookLeftRight) = ADDRESS_BY_VERSION(0x4A9D40, 0x4A9D60, 0x4A9C10); int gaddrof(CPad::SniperModeLookLeftRight) = GLOBAL_ADDRESS_BY_VERSION(0x4A9D40, 0x4A9D60, 0x4A9C10); int CPad::SniperModeLookLeftRight() { return plugin::CallMethodAndReturnDynGlobal<int, CPad *>(gaddrof(CPad::SniperModeLookLeftRight), this); } int addrof(CPad::SniperModeLookUpDown) = ADDRESS_BY_VERSION(0x4A9C40, 0x4A9C60, 0x4A9B10); int gaddrof(CPad::SniperModeLookUpDown) = GLOBAL_ADDRESS_BY_VERSION(0x4A9C40, 0x4A9C60, 0x4A9B10); int CPad::SniperModeLookUpDown() { return plugin::CallMethodAndReturnDynGlobal<int, CPad *>(gaddrof(CPad::SniperModeLookUpDown), this); } int addrof(CPad::SniperZoomIn) = ADDRESS_BY_VERSION(0x4A9E90, 0x4A9EB0, 0x4A9D60); int gaddrof(CPad::SniperZoomIn) = GLOBAL_ADDRESS_BY_VERSION(0x4A9E90, 0x4A9EB0, 0x4A9D60); bool CPad::SniperZoomIn() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::SniperZoomIn), this); } int addrof(CPad::SniperZoomOut) = ADDRESS_BY_VERSION(0x4A9E20, 0x4A9E40, 0x4A9CF0); int gaddrof(CPad::SniperZoomOut) = GLOBAL_ADDRESS_BY_VERSION(0x4A9E20, 0x4A9E40, 0x4A9CF0); bool CPad::SniperZoomOut() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::SniperZoomOut), this); } int addrof(CPad::StartShake) = ADDRESS_BY_VERSION(0x4AD2E0, 0x4AD300, 0x4AD1B0); int gaddrof(CPad::StartShake) = GLOBAL_ADDRESS_BY_VERSION(0x4AD2E0, 0x4AD300, 0x4AD1B0); void CPad::StartShake(short duration, unsigned char frequency) { plugin::CallMethodDynGlobal<CPad *, short, unsigned char>(gaddrof(CPad::StartShake), this, duration, frequency); } int addrof(CPad::StopShaking) = ADDRESS_BY_VERSION(0x4AB070, 0x4AB090, 0x4AAF40); int gaddrof(CPad::StopShaking) = GLOBAL_ADDRESS_BY_VERSION(0x4AB070, 0x4AB090, 0x4AAF40); void CPad::StopShaking(int a1) { plugin::CallMethodDynGlobal<CPad *, int>(gaddrof(CPad::StopShaking), this, a1); } int addrof(CPad::TargetJustDown) = ADDRESS_BY_VERSION(0x4AA460, 0x4AA480, 0x4AA330); int gaddrof(CPad::TargetJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA460, 0x4AA480, 0x4AA330); bool CPad::TargetJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::TargetJustDown), this); } int addrof(CPad::Update) = ADDRESS_BY_VERSION(0x4AB0C0, 0x4AB0E0, 0x4AAF90); int gaddrof(CPad::Update) = GLOBAL_ADDRESS_BY_VERSION(0x4AB0C0, 0x4AB0E0, 0x4AAF90); void CPad::Update(int a2) { plugin::CallMethodDynGlobal<CPad *, int>(gaddrof(CPad::Update), this, a2); } int addrof(CPad::WeaponJustDown) = ADDRESS_BY_VERSION(0x4AA7B0, 0x4AA7D0, 0x4AA680); int gaddrof(CPad::WeaponJustDown) = GLOBAL_ADDRESS_BY_VERSION(0x4AA7B0, 0x4AA7D0, 0x4AA680); bool CPad::WeaponJustDown() { return plugin::CallMethodAndReturnDynGlobal<bool, CPad *>(gaddrof(CPad::WeaponJustDown), this); } int addrof(CPad::ClearMouseHistory) = ADDRESS_BY_VERSION(0x4ADB30, 0x4ADB50, 0x4ADA00); int gaddrof(CPad::ClearMouseHistory) = GLOBAL_ADDRESS_BY_VERSION(0x4ADB30, 0x4ADB50, 0x4ADA00); void CPad::ClearMouseHistory() { plugin::CallDynGlobal(gaddrof(CPad::ClearMouseHistory)); } int addrof(CPad::DoCheats) = ADDRESS_BY_VERSION(0x4AB090, 0x4AB0B0, 0x4AAF60); int gaddrof(CPad::DoCheats) = GLOBAL_ADDRESS_BY_VERSION(0x4AB090, 0x4AB0B0, 0x4AAF60); void CPad::DoCheats() { plugin::CallDynGlobal(gaddrof(CPad::DoCheats)); } int addrof(CPad::EditCodesForControls) = ADDRESS_BY_VERSION(0x4A90B0, 0x4A90D0, 0x4A8F80); int gaddrof(CPad::EditCodesForControls) = GLOBAL_ADDRESS_BY_VERSION(0x4A90B0, 0x4A90D0, 0x4A8F80); void CPad::EditCodesForControls(int *outKeyCode, int a2) { plugin::CallDynGlobal<int *, int>(gaddrof(CPad::EditCodesForControls), outKeyCode, a2); } int addrof(CPad::FixPadsAfterSave) = ADDRESS_BY_VERSION(0x4AB0A0, 0x4AB0C0, 0x4AAF70); int gaddrof(CPad::FixPadsAfterSave) = GLOBAL_ADDRESS_BY_VERSION(0x4AB0A0, 0x4AB0C0, 0x4AAF70); void CPad::FixPadsAfterSave() { plugin::CallDynGlobal(gaddrof(CPad::FixPadsAfterSave)); } int addrof(CPad::GetPad) = ADDRESS_BY_VERSION(0x4AB060, 0x4AB080, 0x4AAF30); int gaddrof(CPad::GetPad) = GLOBAL_ADDRESS_BY_VERSION(0x4AB060, 0x4AB080, 0x4AAF30); CPad *CPad::GetPad(int padNumber) { return plugin::CallAndReturnDynGlobal<CPad *, int>(gaddrof(CPad::GetPad), padNumber); } int addrof(CPad::PrintErrorMessage) = ADDRESS_BY_VERSION(0x4A9660, 0x4A9680, 0x4A9530); int gaddrof(CPad::PrintErrorMessage) = GLOBAL_ADDRESS_BY_VERSION(0x4A9660, 0x4A9680, 0x4A9530); void CPad::PrintErrorMessage() { plugin::CallDynGlobal(gaddrof(CPad::PrintErrorMessage)); } int addrof(CPad::ResetCheats) = ADDRESS_BY_VERSION(0x4A9590, 0x4A95B0, 0x4A9460); int gaddrof(CPad::ResetCheats) = GLOBAL_ADDRESS_BY_VERSION(0x4A9590, 0x4A95B0, 0x4A9460); void CPad::ResetCheats() { plugin::CallDynGlobal(gaddrof(CPad::ResetCheats)); } int addrof(CPad::StopPadsShaking) = ADDRESS_BY_VERSION(0x4AB080, 0x4AB0A0, 0x4AAF50); int gaddrof(CPad::StopPadsShaking) = GLOBAL_ADDRESS_BY_VERSION(0x4AB080, 0x4AB0A0, 0x4AAF50); void CPad::StopPadsShaking() { plugin::CallDynGlobal(gaddrof(CPad::StopPadsShaking)); } int addrof(CPad::UpdateMouse) = ADDRESS_BY_VERSION(0x4AD820, 0x4AD840, 0x4AD6F0); int gaddrof(CPad::UpdateMouse) = GLOBAL_ADDRESS_BY_VERSION(0x4AD820, 0x4AD840, 0x4AD6F0); void CPad::UpdateMouse() { plugin::CallDynGlobal(gaddrof(CPad::UpdateMouse)); } int addrof(CPad::UpdatePads) = ADDRESS_BY_VERSION(0x4AB6C0, 0x4AB6E0, 0x4AB590); int gaddrof(CPad::UpdatePads) = GLOBAL_ADDRESS_BY_VERSION(0x4AB6C0, 0x4AB6E0, 0x4AB590); void CPad::UpdatePads() { plugin::CallDynGlobal(gaddrof(CPad::UpdatePads)); }
11,137
5,607
<filename>http-server-netty/src/main/java/io/micronaut/http/server/netty/HttpToHttpsRedirectHandler.java<gh_stars>1000+ /* * Copyright 2017-2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.http.server.netty; import io.micronaut.core.annotation.Internal; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.MutableHttpResponse; import io.micronaut.http.netty.NettyHttpResponseBuilder; import io.micronaut.http.server.util.HttpHostResolver; import io.micronaut.http.ssl.ServerSslConfiguration; import io.micronaut.http.uri.UriBuilder; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.ssl.SslHandler; /** * Handler to automatically redirect HTTP to HTTPS request when using dual protocol. * * @author <NAME> * @since 2.5.0 */ @ChannelHandler.Sharable @Internal final class HttpToHttpsRedirectHandler extends ChannelDuplexHandler { private final ServerSslConfiguration sslConfiguration; private final HttpHostResolver hostResolver; /** * Construct HttpToHttpsRedirectHandler for the given arguments. * * @param sslConfiguration The {@link ServerSslConfiguration} * @param hostResolver The {@link HttpHostResolver} */ public HttpToHttpsRedirectHandler(ServerSslConfiguration sslConfiguration, HttpHostResolver hostResolver) { this.hostResolver = hostResolver; this.sslConfiguration = sslConfiguration; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest && ctx.pipeline().get(SslHandler.class) == null) { HttpRequest<?> request = (HttpRequest<?>) msg; UriBuilder uriBuilder = UriBuilder.of(hostResolver.resolve(request)); uriBuilder.scheme("https"); int port = sslConfiguration.getPort(); if (port == 443) { uriBuilder.port(-1); } else { uriBuilder.port(port); } uriBuilder.path(request.getPath()); MutableHttpResponse<?> response = HttpResponse .permanentRedirect(uriBuilder.build()) .header(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); io.netty.handler.codec.http.HttpResponse nettyResponse = NettyHttpResponseBuilder.toHttpResponse(response); ctx.writeAndFlush(nettyResponse); } else { ctx.fireChannelRead(msg); } } }
1,210
4,606
<reponame>makotonium/dagster import warnings from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast from dagster import check from dagster.core.definitions.events import AssetKey from dagster.core.definitions.op_def import OpDefinition from dagster.core.definitions.solid import SolidDefinition from dagster.core.errors import DagsterInvariantViolationError from dagster.core.execution.plan.utils import build_resources_for_manager if TYPE_CHECKING: from dagster.core.execution.context.system import StepExecutionContext from dagster.core.types.dagster_type import DagsterType from dagster.core.definitions import PipelineDefinition from dagster.core.log_manager import DagsterLogManager from dagster.core.system_config.objects import ResolvedRunConfig from dagster.core.definitions.resource import Resources from dagster.core.execution.plan.plan import ExecutionPlan from dagster.core.execution.plan.outputs import StepOutputHandle RUN_ID_PLACEHOLDER = "__EPHEMERAL_RUN_ID" class OutputContext: """ The context object that is available to the `handle_output` method of an :py:class:`IOManager`. Attributes: step_key (Optional[str]): The step_key for the compute step that produced the output. name (Optional[str]): The name of the output that produced the output. pipeline_name (Optional[str]): The name of the pipeline definition. run_id (Optional[str]): The id of the run that produced the output. metadata (Optional[Dict[str, Any]]): A dict of the metadata that is assigned to the OutputDefinition that produced the output. mapping_key (Optional[str]): The key that identifies a unique mapped output. None for regular outputs. config (Optional[Any]): The configuration for the output. solid_def (Optional[SolidDefinition]): The definition of the solid that produced the output. dagster_type (Optional[DagsterType]): The type of this output. log (Optional[DagsterLogManager]): The log manager to use for this output. version (Optional[str]): (Experimental) The version of the output. resource_config (Optional[Dict[str, Any]]): The config associated with the resource that initializes the RootInputManager. resources (Optional[Resources]): The resources required by the output manager, specified by the `required_resource_keys` parameter. op_def (Optional[OpDefinition]): The definition of the op that produced the output. """ def __init__( self, step_key: Optional[str] = None, name: Optional[str] = None, pipeline_name: Optional[str] = None, run_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, mapping_key: Optional[str] = None, config: Optional[Any] = None, solid_def: Optional["SolidDefinition"] = None, dagster_type: Optional["DagsterType"] = None, log_manager: Optional["DagsterLogManager"] = None, version: Optional[str] = None, resource_config: Optional[Dict[str, Any]] = None, resources: Optional[Union["Resources", Dict[str, Any]]] = None, step_context: Optional["StepExecutionContext"] = None, op_def: Optional["OpDefinition"] = None, ): from dagster.core.definitions.resource import Resources, IContainsGenerator from dagster.core.execution.build_resources import build_resources self._step_key = step_key self._name = name self._pipeline_name = pipeline_name self._run_id = run_id self._metadata = metadata self._mapping_key = mapping_key self._config = config check.invariant( solid_def is None or op_def is None, "Can't provide both a solid_def and an op_def arg" ) self._solid_def = solid_def or op_def self._dagster_type = dagster_type self._log = log_manager self._version = version self._resource_config = resource_config self._step_context = step_context if isinstance(resources, Resources): self._resources_cm = None self._resources = resources else: self._resources_cm = build_resources( check.opt_dict_param(resources, "resources", key_type=str) ) self._resources = self._resources_cm.__enter__() # pylint: disable=no-member self._resources_contain_cm = isinstance(self._resources, IContainsGenerator) self._cm_scope_entered = False def __enter__(self): if self._resources_cm: self._cm_scope_entered = True return self def __exit__(self, *exc): if self._resources_cm: self._resources_cm.__exit__(*exc) # pylint: disable=no-member def __del__(self): if self._resources_cm and self._resources_contain_cm and not self._cm_scope_entered: self._resources_cm.__exit__(None, None, None) # pylint: disable=no-member @property def step_key(self) -> str: if self._step_key is None: raise DagsterInvariantViolationError( "Attempting to access step_key, " "but it was not provided when constructing the OutputContext" ) return self._step_key @property def name(self) -> str: if self._name is None: raise DagsterInvariantViolationError( "Attempting to access name, " "but it was not provided when constructing the OutputContext" ) return self._name @property def pipeline_name(self) -> str: if self._pipeline_name is None: raise DagsterInvariantViolationError( "Attempting to access pipeline_name, " "but it was not provided when constructing the OutputContext" ) return self._pipeline_name @property def run_id(self) -> str: if self._run_id is None: raise DagsterInvariantViolationError( "Attempting to access run_id, " "but it was not provided when constructing the OutputContext" ) return self._run_id @property def metadata(self) -> Optional[Dict[str, Any]]: return self._metadata @property def mapping_key(self) -> Optional[str]: return self._mapping_key @property def config(self) -> Any: return self._config @property def solid_def(self) -> "SolidDefinition": if self._solid_def is None: raise DagsterInvariantViolationError( "Attempting to access solid_def, " "but it was not provided when constructing the OutputContext" ) return self._solid_def @property def op_def(self) -> "OpDefinition": if self._solid_def is None: raise DagsterInvariantViolationError( "Attempting to access op_def, " "but it was not provided when constructing the OutputContext" ) return cast(OpDefinition, self._solid_def) @property def dagster_type(self) -> "DagsterType": if self._dagster_type is None: raise DagsterInvariantViolationError( "Attempting to access dagster_type, " "but it was not provided when constructing the OutputContext" ) return self._dagster_type @property def log(self) -> "DagsterLogManager": if self._log is None: raise DagsterInvariantViolationError( "Attempting to access log, " "but it was not provided when constructing the OutputContext" ) return self._log @property def version(self) -> Optional[str]: return self._version @property def resource_config(self) -> Optional[Dict[str, Any]]: return self._resource_config @property def resources(self) -> Any: if self._resources is None: raise DagsterInvariantViolationError( "Attempting to access resources, " "but it was not provided when constructing the OutputContext" ) if self._resources_cm and self._resources_contain_cm and not self._cm_scope_entered: raise DagsterInvariantViolationError( "At least one provided resource is a generator, but attempting to access " "resources outside of context manager scope. You can use the following syntax to " "open a context manager: `with build_output_context(...) as context:`" ) return self._resources @property def asset_key(self) -> Optional[AssetKey]: matching_output_defs = [ output_def for output_def in cast(SolidDefinition, self._solid_def).output_defs if output_def.name == self.name ] check.invariant(len(matching_output_defs) == 1) return matching_output_defs[0].get_asset_key(self) @property def step_context(self) -> "StepExecutionContext": if self._step_context is None: raise DagsterInvariantViolationError( "Attempting to access step_context, " "but it was not provided when constructing the OutputContext" ) return self._step_context def get_run_scoped_output_identifier(self) -> List[str]: """Utility method to get a collection of identifiers that as a whole represent a unique step output. The unique identifier collection consists of - ``run_id``: the id of the run which generates the output. Note: This method also handles the re-execution memoization logic. If the step that generates the output is skipped in the re-execution, the ``run_id`` will be the id of its parent run. - ``step_key``: the key for a compute step. - ``name``: the name of the output. (default: 'result'). Returns: List[str, ...]: A list of identifiers, i.e. run id, step key, and output name """ warnings.warn( "`OutputContext.get_run_scoped_output_identifier` is deprecated. Use " "`OutputContext.get_output_identifier` instead." ) # if run_id is None and this is a re-execution, it means we failed to find its source run id check.invariant( self.run_id is not None, "Unable to find the run scoped output identifier: run_id is None on OutputContext.", ) check.invariant( self.step_key is not None, "Unable to find the run scoped output identifier: step_key is None on OutputContext.", ) check.invariant( self.name is not None, "Unable to find the run scoped output identifier: name is None on OutputContext.", ) run_id = cast(str, self.run_id) step_key = cast(str, self.step_key) name = cast(str, self.name) if self.mapping_key: return [run_id, step_key, name, self.mapping_key] return [run_id, step_key, name] def get_output_identifier(self) -> List[str]: """Utility method to get a collection of identifiers that as a whole represent a unique step output. If not using memoization, the unique identifier collection consists of - ``run_id``: the id of the run which generates the output. Note: This method also handles the re-execution memoization logic. If the step that generates the output is skipped in the re-execution, the ``run_id`` will be the id of its parent run. - ``step_key``: the key for a compute step. - ``name``: the name of the output. (default: 'result'). If using memoization, the ``version`` corresponding to the step output is used in place of the ``run_id``. Returns: List[str, ...]: A list of identifiers, i.e. (run_id or version), step_key, and output_name """ version = self.version step_key = self.step_key name = self.name if version is not None: check.invariant( self.mapping_key is None, f"Mapping key and version both provided for output '{name}' of step '{step_key}'. " "Dynamic mapping is not supported when using versioning.", ) identifier = ["versioned_outputs", version, step_key, name] else: run_id = self.run_id identifier = [run_id, step_key, name] if self.mapping_key: identifier.append(self.mapping_key) return identifier def get_output_context( execution_plan: "ExecutionPlan", pipeline_def: "PipelineDefinition", resolved_run_config: "ResolvedRunConfig", step_output_handle: "StepOutputHandle", run_id: Optional[str], log_manager: Optional["DagsterLogManager"], step_context: Optional["StepExecutionContext"], resources: Optional["Resources"], version: Optional[str], ) -> "OutputContext": """ Args: run_id (str): The run ID of the run that produced the output, not necessarily the run that the context will be used in. """ step = execution_plan.get_step_by_key(step_output_handle.step_key) # get config solid_config = resolved_run_config.solids[step.solid_handle.to_string()] outputs_config = solid_config.outputs if outputs_config: output_config = outputs_config.get_output_manager_config(step_output_handle.output_name) else: output_config = None step_output = execution_plan.get_step_output(step_output_handle) output_def = pipeline_def.get_solid(step_output.solid_handle).output_def_named(step_output.name) io_manager_key = output_def.io_manager_key resource_config = resolved_run_config.resources[io_manager_key].config if step_context: check.invariant( not resources, "Expected either resources or step context to be set, but " "received both. If step context is provided, resources for IO manager will be " "retrieved off of that.", ) resources = build_resources_for_manager(io_manager_key, step_context) return OutputContext( step_key=step_output_handle.step_key, name=step_output_handle.output_name, pipeline_name=pipeline_def.name, run_id=run_id, metadata=output_def.metadata, mapping_key=step_output_handle.mapping_key, config=output_config, solid_def=pipeline_def.get_solid(step.solid_handle).definition, dagster_type=output_def.dagster_type, log_manager=log_manager, version=version, step_context=step_context, resource_config=resource_config, resources=resources, ) def step_output_version( pipeline_def: "PipelineDefinition", execution_plan: "ExecutionPlan", resolved_run_config: "ResolvedRunConfig", step_output_handle: "StepOutputHandle", ) -> Optional[str]: from dagster.core.execution.resolve_versions import resolve_step_output_versions step_output_versions = resolve_step_output_versions( pipeline_def, execution_plan, resolved_run_config ) return ( step_output_versions[step_output_handle] if step_output_handle in step_output_versions else None ) def build_output_context( step_key: Optional[str] = None, name: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, run_id: Optional[str] = None, mapping_key: Optional[str] = None, config: Optional[Any] = None, dagster_type: Optional["DagsterType"] = None, version: Optional[str] = None, resource_config: Optional[Dict[str, Any]] = None, resources: Optional[Dict[str, Any]] = None, solid_def: Optional[SolidDefinition] = None, op_def: Optional[OpDefinition] = None, ) -> "OutputContext": """Builds output context from provided parameters. ``build_output_context`` can be used as either a function, or a context manager. If resources that are also context managers are provided, then ``build_output_context`` must be used as a context manager. Args: step_key (Optional[str]): The step_key for the compute step that produced the output. name (Optional[str]): The name of the output that produced the output. metadata (Optional[Dict[str, Any]]): A dict of the metadata that is assigned to the OutputDefinition that produced the output. mapping_key (Optional[str]): The key that identifies a unique mapped output. None for regular outputs. config (Optional[Any]): The configuration for the output. dagster_type (Optional[DagsterType]): The type of this output. version (Optional[str]): (Experimental) The version of the output. resource_config (Optional[Dict[str, Any]]): The resource config to make available from the input context. This usually corresponds to the config provided to the resource that loads the output manager. resources (Optional[Resources]): The resources to make available from the context. For a given key, you can provide either an actual instance of an object, or a resource definition. solid_def (Optional[SolidDefinition]): The definition of the solid that produced the output. op_def (Optional[OpDefinition]): The definition of the solid that produced the output. Examples: .. code-block:: python build_output_context() with build_output_context(resources={"foo": context_manager_resource}) as context: do_something """ from dagster.core.types.dagster_type import DagsterType from dagster.core.execution.context_creation_pipeline import initialize_console_manager step_key = check.opt_str_param(step_key, "step_key") name = check.opt_str_param(name, "name") metadata = check.opt_dict_param(metadata, "metadata", key_type=str) run_id = check.opt_str_param(run_id, "run_id", default=RUN_ID_PLACEHOLDER) mapping_key = check.opt_str_param(mapping_key, "mapping_key") dagster_type = check.opt_inst_param(dagster_type, "dagster_type", DagsterType) version = check.opt_str_param(version, "version") resource_config = check.opt_dict_param(resource_config, "resource_config", key_type=str) resources = check.opt_dict_param(resources, "resources", key_type=str) solid_def = check.opt_inst_param(solid_def, "solid_def", SolidDefinition) op_def = check.opt_inst_param(op_def, "op_def", OpDefinition) return OutputContext( step_key=step_key, name=name, pipeline_name=None, run_id=run_id, metadata=metadata, mapping_key=mapping_key, config=config, solid_def=solid_def, dagster_type=dagster_type, log_manager=initialize_console_manager(None), version=version, resource_config=resource_config, resources=resources, step_context=None, op_def=op_def, )
7,664
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Echourgnac","circ":"1ère circonscription","dpt":"Dordogne","inscrits":317,"abs":151,"votants":166,"blancs":9,"nuls":8,"exp":149,"res":[{"nuance":"REM","nom":"<NAME>","voix":79},{"nuance":"FI","nom":"<NAME>","voix":70}]}
110
14,668
// Copyright (c) 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. #include "net/tools/transport_security_state_generator/preloaded_state_generator.h" #include <string> #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "net/tools/huffman_trie/huffman/huffman_builder.h" #include "net/tools/transport_security_state_generator/cert_util.h" #include "net/tools/transport_security_state_generator/spki_hash.h" namespace net { namespace transport_security_state { namespace { static const char kNewLine[] = "\n"; static const char kIndent[] = " "; std::string FormatSPKIName(const std::string& name) { return "kSPKIHash_" + name; } std::string FormatAcceptedKeyName(const std::string& name) { return "k" + name + "AcceptableCerts"; } std::string FormatRejectedKeyName(const std::string& name) { return "k" + name + "RejectedCerts"; } std::string FormatReportURIName(const std::string& name) { return "k" + name + "ReportURI"; } // Replaces the first occurrence of "[[" + name + "]]" in |*tpl| with // |value|. bool ReplaceTag(const std::string& name, const std::string& value, std::string* tpl) { std::string tag = "[[" + name + "]]"; size_t start_pos = tpl->find(tag); if (start_pos == std::string::npos) { return false; } tpl->replace(start_pos, tag.length(), value); return true; } // Formats the bytes in |bytes| as an C++ array initializer and returns the // resulting string. std::string FormatVectorAsArray(const std::vector<uint8_t>& bytes) { std::string output = "{"; output.append(kNewLine); output.append(kIndent); output.append(kIndent); size_t bytes_on_current_line = 0; for (size_t i = 0; i < bytes.size(); ++i) { base::StringAppendF(&output, "0x%02x,", bytes[i]); bytes_on_current_line++; if (bytes_on_current_line >= 12 && i + 1 < bytes.size()) { output.append(kNewLine); output.append(kIndent); output.append(kIndent); bytes_on_current_line = 0; } else if (i + 1 < bytes.size()) { output.append(" "); } } output.append(kNewLine); output.append("}"); return output; } std::string WritePinsetList(const std::string& name, const std::vector<std::string>& pins) { std::string output = "static const char* const " + name + "[] = {"; output.append(kNewLine); for (const auto& pin_name : pins) { output.append(kIndent); output.append(kIndent); output.append(FormatSPKIName(pin_name)); output.append(","); output.append(kNewLine); } output.append(kIndent); output.append(kIndent); output.append("nullptr,"); output.append(kNewLine); output.append("};"); return output; } huffman_trie::HuffmanRepresentationTable ApproximateHuffman( const TransportSecurityStateEntries& entries) { huffman_trie::HuffmanBuilder huffman_builder; for (const auto& entry : entries) { for (const auto& c : entry->hostname) { huffman_builder.RecordUsage(c); } huffman_builder.RecordUsage(huffman_trie::kTerminalValue); huffman_builder.RecordUsage(huffman_trie::kEndOfTableValue); } return huffman_builder.ToTable(); } } // namespace PreloadedStateGenerator::PreloadedStateGenerator() = default; PreloadedStateGenerator::~PreloadedStateGenerator() = default; std::string PreloadedStateGenerator::Generate( const std::string& preload_template, const TransportSecurityStateEntries& entries, const Pinsets& pinsets) { std::string output = preload_template; ProcessSPKIHashes(pinsets, &output); NameIDMap expect_ct_report_uri_map; ProcessExpectCTURIs(entries, &expect_ct_report_uri_map, &output); NameIDMap pinsets_map; ProcessPinsets(pinsets, &pinsets_map, &output); std::vector<std::unique_ptr<TransportSecurityStateTrieEntry>> trie_entries; std::vector<huffman_trie::TrieEntry*> raw_trie_entries; for (const auto& entry : entries) { std::unique_ptr<TransportSecurityStateTrieEntry> trie_entry( new TransportSecurityStateTrieEntry(expect_ct_report_uri_map, pinsets_map, entry.get())); raw_trie_entries.push_back(trie_entry.get()); trie_entries.push_back(std::move(trie_entry)); } // The trie generation process is ran twice, the first time using an // approximate Huffman table. During this first run, the correct character // frequencies are collected which are then used to calculate the most space // efficient Huffman table for the given inputs. This table is used for the // second run. huffman_trie::HuffmanRepresentationTable table = ApproximateHuffman(entries); huffman_trie::HuffmanBuilder huffman_builder; huffman_trie::TrieWriter writer(table, &huffman_builder); uint32_t root_position; if (!writer.WriteEntries(raw_trie_entries, &root_position)) { return std::string(); } huffman_trie::HuffmanRepresentationTable optimal_table = huffman_builder.ToTable(); huffman_trie::TrieWriter new_writer(optimal_table, nullptr); if (!new_writer.WriteEntries(raw_trie_entries, &root_position)) { return std::string(); } uint32_t new_length = new_writer.position(); std::vector<uint8_t> huffman_tree = huffman_builder.ToVector(); new_writer.Flush(); ReplaceTag("HUFFMAN_TREE", FormatVectorAsArray(huffman_tree), &output); ReplaceTag("HSTS_TRIE", FormatVectorAsArray(new_writer.bytes()), &output); ReplaceTag("HSTS_TRIE_BITS", base::NumberToString(new_length), &output); ReplaceTag("HSTS_TRIE_ROOT", base::NumberToString(root_position), &output); return output; } void PreloadedStateGenerator::ProcessSPKIHashes(const Pinsets& pinset, std::string* tpl) { std::string output; const SPKIHashMap& hashes = pinset.spki_hashes(); for (const auto& current : hashes) { const std::string& name = current.first; const SPKIHash& hash = current.second; output.append("static const char " + FormatSPKIName(name) + "[] ="); output.append(kNewLine); for (size_t i = 0; i < hash.size() / 16; ++i) { output.append(kIndent); output.append(kIndent); output.append("\""); for (size_t j = i * 16; j < ((i + 1) * 16); ++j) { base::StringAppendF(&output, "\\x%02x", hash.data()[j]); } output.append("\""); if (i + 1 == hash.size() / 16) { output.append(";"); } output.append(kNewLine); } output.append(kNewLine); } base::TrimString(output, kNewLine, &output); ReplaceTag("SPKI_HASHES", output, tpl); } void PreloadedStateGenerator::ProcessExpectCTURIs( const TransportSecurityStateEntries& entries, NameIDMap* expect_ct_report_uri_map, std::string* tpl) { std::string output = "{"; output.append(kNewLine); for (const auto& entry : entries) { const std::string& url = entry->expect_ct_report_uri; if (entry->expect_ct && url.size() && expect_ct_report_uri_map->find(url) == expect_ct_report_uri_map->cend()) { output.append(kIndent); output.append(kIndent); output.append("\"" + entry->expect_ct_report_uri + "\","); output.append(kNewLine); expect_ct_report_uri_map->insert( NameIDPair(entry->expect_ct_report_uri, static_cast<uint32_t>(expect_ct_report_uri_map->size()))); } } output.append(kIndent); output.append(kIndent); output.append("nullptr,"); output.append(kNewLine); output.append("}"); ReplaceTag("EXPECT_CT_REPORT_URIS", output, tpl); } void PreloadedStateGenerator::ProcessPinsets(const Pinsets& pinset, NameIDMap* pinset_map, std::string* tpl) { std::string certs_output; std::string pinsets_output = "{"; pinsets_output.append(kNewLine); const PinsetMap& pinsets = pinset.pinsets(); for (const auto& current : pinsets) { const std::unique_ptr<Pinset>& pinset_ptr = current.second; std::string uppercased_name = pinset_ptr->name(); uppercased_name[0] = base::ToUpperASCII(uppercased_name[0]); const std::string& accepted_pins_names = FormatAcceptedKeyName(uppercased_name); certs_output.append( WritePinsetList(accepted_pins_names, pinset_ptr->static_spki_hashes())); certs_output.append(kNewLine); std::string rejected_pins_names = "kNoRejectedPublicKeys"; if (pinset_ptr->bad_static_spki_hashes().size()) { rejected_pins_names = FormatRejectedKeyName(uppercased_name); certs_output.append(WritePinsetList( rejected_pins_names, pinset_ptr->bad_static_spki_hashes())); certs_output.append(kNewLine); } std::string report_uri = "kNoReportURI"; if (pinset_ptr->report_uri().size()) { report_uri = FormatReportURIName(uppercased_name); certs_output.append("static const char " + report_uri + "[] = "); certs_output.append("\""); certs_output.append(pinset_ptr->report_uri()); certs_output.append("\";"); certs_output.append(kNewLine); } certs_output.append(kNewLine); pinsets_output.append(kIndent); pinsets_output.append(kIndent); pinsets_output.append("{" + accepted_pins_names + ", " + rejected_pins_names + ", " + report_uri + "},"); pinsets_output.append(kNewLine); pinset_map->insert(NameIDPair(pinset_ptr->name(), static_cast<uint32_t>(pinset_map->size()))); } pinsets_output.append("}"); base::TrimString(certs_output, kNewLine, &certs_output); ReplaceTag("ACCEPTABLE_CERTS", certs_output, tpl); ReplaceTag("PINSETS", pinsets_output, tpl); } } // namespace transport_security_state } // namespace net
3,933
3,428
<reponame>ghalimi/stdlib {"id":"00713","group":"easy-ham-2","checksum":{"type":"MD5","value":"49b7b319d69b2dc2bc27a5dd206750a0"},"text":"From <EMAIL> Wed Jul 24 14:15:41 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 4EB19440CD\n\tfor <jm@localhost>; Wed, 24 Jul 2002 09:15:39 -0400 (EDT)\nReceived: from dogma.slashnull.org [212.17.35.15]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 24 Jul 2002 14:15:39 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g6ODG3414691 for <<EMAIL>>;\n Wed, 24 Jul 2002 14:16:03 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 024D929414A; Wed, 24 Jul 2002 06:00:10 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from imo-m08.mx.aol.com (imo-m08.mx.aol.com [64.12.136.163]) by\n xent.com (Postfix) with ESMTP id 64B4829410C for <<EMAIL>>;\n Wed, 24 Jul 2002 05:59:18 -0700 (PDT)\nReceived: from <EMAIL> by imo-m08.mx.aol.com (mail_out_v32.21.)\n id 2.186.b3487c0 (4419) for <<EMAIL>>; Wed, 24 Jul 2002 09:08:11\n -0400 (EDT)\nFrom: [email protected]\nMessage-Id: <<EMAIL>>\nSubject: Re: SimPastry\nTo: [email protected]\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"US-ASCII\"\nContent-Transfer-Encoding: 7bit\nX-Mailer: AOL 5.0 for Mac sub 40\nSender: fork-<EMAIL>\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>.<EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of Rohit Khare <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Wed, 24 Jul 2002 09:08:11 EDT\n\n\nIn a message dated 7/23/2002 8:45:18 PM, <EMAIL> writes:\n\n>Pastry is a generic, scalable and efficient substrate for peer-to-peer\n>applications. Pastry nodes form a decentralized, self-organizing and\n>fault-tolerant overlay network within the Internet. \n\nIs it made with lard, butter, or vegetable shortenings? \nhttp://xent.com/mailman/listinfo/fork\n\n\n"}
1,026
879
<filename>HibernateSpringBootImmutableEntity/src/main/java/com/bookstore/service/BookstoreService.java package com.bookstore.service; import com.bookstore.entity.Author; import com.bookstore.repository.AuthorRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } public void newAuthor() { Author author = new Author(); author.setId(1L); author.setName("<NAME>"); author.setGenre("History"); author.setAge(34); authorRepository.save(author); } public void fetchAuthor() { Author author = authorRepository.findById(1L).orElseThrow(); System.out.println(author); } @Transactional public void updateAuthor() { Author author = authorRepository.findById(1L).orElseThrow(); author.setAge(45); } public void deleteAuthor() { authorRepository.deleteById(1L); } }
425
675
""" Collecting all main APIs for optimisation here. -- <EMAIL> """
23
667
<gh_stars>100-1000 #include <libavcodec/avcodec.h> int main(void) { return AV_CODEC_ID_NONE; }
49
795
<reponame>ddymko/headlamp<gh_stars>100-1000 { "Loading binding details": "A carregar detalhes de «binding»", "Ref. API Group": "Grupo Ref. API" }
61
640
/*************************************************************** * StatusDB.h * Header for Rex addin program. ***************************************************************/ #ifndef STATUSDB_H #define STATUSDB_H enum { STATUS_RECID = 1, STATUS_STATUS }; enum { IDX_STATUS_RECID = 1 }; #define REX_NEW 1 #define REX_MODIFIED 2 #define REX_DELETED 3 #endif
139
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "RendElement.h" #include "CloudImposterRenderElement.h" #include "I3DEngine.h" namespace CloudsGem { int CloudImposterRenderElement::s_MemUpdated = 0; int CloudImposterRenderElement::s_MemPostponed = 0; int CloudImposterRenderElement::s_PrevMemUpdated = 0; int CloudImposterRenderElement::s_PrevMemPostponed = 0; IDynTexture* CloudImposterRenderElement::s_pScreenTexture = nullptr; // Helper method to Enumerates and index edges of a box to find minimal enclosing rectangle static void GetEdgeNo(const uint32 edgeNumber, uint32& vertexA, uint32& vertexB) { switch (edgeNumber) { case 0: vertexA = 0; vertexB = 1; break; case 1: vertexA = 2; vertexB = 3; break; case 2: vertexA = 4; vertexB = 5; break; case 3: vertexA = 6; vertexB = 7; break; case 4: vertexA = 0; vertexB = 2; break; case 5: vertexA = 4; vertexB = 6; break; case 6: vertexA = 5; vertexB = 7; break; case 7: vertexA = 1; vertexB = 3; break; case 8: vertexA = 0; vertexB = 4; break; case 9: vertexA = 2; vertexB = 6; break; case 10: vertexA = 3; vertexB = 7; break; case 11: vertexA = 1; vertexB = 5; break; default: assert(0); } } CloudImposterRenderElement::CloudImposterRenderElement() { m_gemRE = gEnv->pRenderer->EF_CreateRE(eDATA_Gem); m_gemRE->mfSetFlags(FCEF_TRANSFORM); m_gemRE->mfSetDelegate(this); } CloudImposterRenderElement::~CloudImposterRenderElement() { ReleaseResources(); } bool CloudImposterRenderElement::IsImposterValid( const CameraViewParameters& cam, float fRadiusX, float fRadiusY, float fCamRadiusX, float fCamRadiusY, const int iRequiredLogResX, const int iRequiredLogResY, const uint32 dwBestEdge) { #if !defined(DEDICATED_SERVER) if (dwBestEdge != m_nLastBestEdge) { return false; } // Update transparency IRenderer* renderer = gEnv->pRenderer; SRenderPipeline* renderPipeline = renderer->GetRenderPipeline(); float fTransparency = renderPipeline->m_pCurObject->m_II.m_AmbColor.a; IRenderShaderResources* shaderResources = renderPipeline->m_pShaderResources; if (shaderResources) { fTransparency *= shaderResources->GetStrengthValue(EFTT_OPACITY); } if (m_fCurTransparency != fTransparency) { m_fCurTransparency = fTransparency; return false; } // screen impostors should always be updated if (m_bScreenImposter) { m_vFarPoint.Set(0.0f, 0.0f, 0.0f); m_vNearPoint.Set(0.0f, 0.0f, 0.0f); return false; } // Split indicated non valid imposter if (m_bSplit) { return false; } // Get distance to camera Vec3 vEye = m_vPos - cam.vOrigin; float fDistance = vEye.GetLength(); if (fDistance < std::numeric_limits<float>::epsilon()) { return false; } vEye /= fDistance; // Old camera distance Vec3 vOldEye = m_vFarPoint - m_LastViewParameters.vOrigin; float fOldEyeDist = vOldEye.GetLength(); if (fOldEyeDist < std::numeric_limits<float>::epsilon()) { return false; // to avoid float exceptions } vOldEye /= fOldEyeDist; // Change in camera angle float fCosAlpha = vEye * vOldEye; // dot product of normalized vectors = cosine if (fCosAlpha < m_fErrorToleranceCosAngle) { return false; } // Change in sun direction Vec3 curSunDir(gEnv->p3DEngine->GetSunDir().GetNormalized()); if (m_vLastSunDir.Dot(curSunDir) < 0.995) { return false; } // equal pow-of-2 size comparison for consistent look if (iRequiredLogResX != m_nLogResolutionX || iRequiredLogResY != m_nLogResolutionY) { return false; } if (renderer->GetFrameReset() != m_nFrameReset) { return false; } #endif return true; } void CloudImposterRenderElement::ReleaseResources() { SAFE_DELETE(m_pTexture); SAFE_DELETE(s_pScreenTexture); SAFE_DELETE(m_pFrontTexture); SAFE_DELETE(m_pTextureDepth); } int IntersectRayAABB(Vec3 p, Vec3 d, SMinMaxBox a, Vec3& q) { float tmin = 0; float tmax = FLT_MAX; int i; const Vec3& min = a.GetMin(); const Vec3& max = a.GetMax(); for (i = 0; i < 3; i++) { if (fabs(d[i]) < 0.001f) { if (p[i] < min[i] || p[i] > max[i]) { return 0; } } else { float ood = 1.0f / d[i]; float t1 = (min[i] - p[i]) * ood; float t2 = (max[i] - p[i]) * ood; if (t1 > t2) { Exchange(t1, t2); } if (t1 > tmin) { tmin = t1; } if (t2 > tmax) { tmax = t2; } } } q = p + d * tmin; return 1; } bool CloudImposterRenderElement::PrepareForUpdate() { #if !defined(DEDICATED_SERVER) IRenderer* renderer = gEnv->pRenderer; if (renderer->GetRecursionLevel() > 0) { return false; } // Compute eye direction, distance from camera to cloud position, normalized distance CameraViewParameters cam = renderer->GetViewParameters(); Vec3 vCenter = GetPosition(); Vec3 vEye = vCenter - cam.vOrigin; float fDistance = vEye.GetLength(); vEye /= fDistance; // Get viewport dimensions int32 D3DVP[4]; renderer->GetViewport(&D3DVP[0], &D3DVP[1], &D3DVP[2], &D3DVP[3]); // Unproject world space bounding volume Vec3 vUnProjPos[9]; int i = 0; for (i = 0; i < 8; i++) { vUnProjPos[i].x = (i & 1) ? m_WorldSpaceBV.GetMax().x : m_WorldSpaceBV.GetMin().x; vUnProjPos[i].y = (i & 2) ? m_WorldSpaceBV.GetMax().y : m_WorldSpaceBV.GetMin().y; vUnProjPos[i].z = (i & 4) ? m_WorldSpaceBV.GetMax().z : m_WorldSpaceBV.GetMin().z; } vUnProjPos[8] = vCenter; CameraViewParameters tempCam; tempCam.fNear = cam.fNear; tempCam.fFar = cam.fFar; Matrix44A viewMat, projMat; mathMatrixPerspectiveOffCenter(&projMat, -1, 1, 1, -1, tempCam.fNear, tempCam.fFar); float fOldEdgeArea = -FLT_MAX; Vec3 vProjPos[9]; uint32 dwBestEdge = 0xffffffff; // favor the last edge we found float fBestArea = FLT_MAX; float fMinX, fMaxX, fMinY, fMaxY; // try to find minimal enclosing rectangle assuming the best projection frustum must be aligned to a AABB edge for (uint32 dwEdge = 0; dwEdge < 13; ++dwEdge) // 12 edges and iteration no 13 processes the best again { uint32 dwEdgeA, dwEdgeB; if (dwEdge == 12 && fBestArea > fOldEdgeArea * 0.98f) // not a lot better than old axis then keep old axis (to avoid jittering) { dwBestEdge = m_nLastBestEdge; } if (dwEdge == 12) { GetEdgeNo(dwBestEdge, dwEdgeA, dwEdgeB); // the best again } else { GetEdgeNo(dwEdge, dwEdgeA, dwEdgeB); // edge no dwEdge } // Convert edge indices to positions from the bounding volume and compute basis Vec3 vEdge[2] = { vUnProjPos[dwEdgeA], vUnProjPos[dwEdgeB] }; Vec3 vRight = vEdge[0] - vEdge[1]; Vec3 vUp = (vEdge[0] - cam.vOrigin) ^ vRight; // Compute model view matrix tempCam.LookAt(cam.vOrigin, vCenter, vUp); tempCam.GetModelviewMatrix(viewMat.GetData()); // Project the unprojected points into the new space Matrix44A identityMatrix = renderer->GetIdentityMatrix(); mathVec3ProjectArray((Vec3*)&vProjPos[0].x, sizeof(Vec3), (Vec3*)&vUnProjPos[0].x, sizeof(Vec3), D3DVP, &projMat, &viewMat, &identityMatrix, 9, 0); // Calculate 2D extents of projected points fMinX = fMinY = FLT_MAX; fMaxX = fMaxY = -FLT_MAX; for (i = 0; i < 8; i++) { if (fMinX > vProjPos[i].x) { fMinX = vProjPos[i].x; } if (fMaxX < vProjPos[i].x) { fMaxX = vProjPos[i].x; } if (fMinY > vProjPos[i].y) { fMinY = vProjPos[i].y; } if (fMaxY < vProjPos[i].y) { fMaxY = vProjPos[i].y; } } // Compute area from extents float fArea = (fMaxX - fMinX) * (fMaxY - fMinY); if (dwEdge == m_nLastBestEdge) { fOldEdgeArea = fArea; } // Update the best edge and best area if smaller than best area if (fArea < fBestArea) { dwBestEdge = dwEdge; fBestArea = fArea; } } // high precision - no jitter float fCamZ = (tempCam.vOrigin - vCenter).Dot(tempCam.ViewDir()); float f = -fCamZ / tempCam.fNear; vUnProjPos[0] = tempCam.CamToWorld(Vec3((fMinX / D3DVP[2] * 2.0f - 1.0f) * f, (fMinY / D3DVP[3] * 2.0f - 1.0f) * f, fCamZ)); vUnProjPos[1] = tempCam.CamToWorld(Vec3((fMaxX / D3DVP[2] * 2.0f - 1.0f) * f, (fMinY / D3DVP[3] * 2.0f - 1.0f) * f, fCamZ)); vUnProjPos[2] = tempCam.CamToWorld(Vec3((fMaxX / D3DVP[2] * 2.0f - 1.0f) * f, (fMaxY / D3DVP[3] * 2.0f - 1.0f) * f, fCamZ)); vUnProjPos[3] = tempCam.CamToWorld(Vec3((fMinX / D3DVP[2] * 2.0f - 1.0f) * f, (fMaxY / D3DVP[3] * 2.0f - 1.0f) * f, fCamZ)); m_vPos = vCenter; Vec3 vProjCenter = (vUnProjPos[0] + vUnProjPos[1] + vUnProjPos[2] + vUnProjPos[3]) / 4.0f; Vec3 vDif = vProjCenter - vCenter; float fDerivX = vDif * tempCam.vX; float fDerivY = vDif * tempCam.vY; float fRadius = m_WorldSpaceBV.GetRadius(); Vec3 vRight = vUnProjPos[0] - vUnProjPos[1]; Vec3 vUp = vUnProjPos[0] - vUnProjPos[2]; float fRadiusX = vRight.len() / 2.0f + fabsf(fDerivX); float fRadiusY = vUp.len() / 2.0f + fabsf(fDerivY); Vec3 vNearest; int nCollide = IntersectRayAABB(cam.vOrigin, vEye, m_WorldSpaceBV, vNearest); Vec4 v4Nearest = Vec4(vNearest, 1); Vec4 v4Far = Vec4(vNearest + vEye * fRadius * 2.0f, 1.0f); Vec4 v4ZRange = Vec4(0.0f, 0.0f, 0.0f, 0.0f); Vec4 v4Column2 = renderer->GetViewProjectionMatrix().GetColumn4(2); Vec4 v4Column3 = renderer->GetViewProjectionMatrix().GetColumn4(3); bool bScreen = false; float fZ = v4Nearest.Dot(v4Column2); float fW = v4Nearest.Dot(v4Column3); float fNewNear = m_fNear; float fNewFar = m_fFar; if (fabs(fW) < 0.001f) // to avoid division by 0 (near the object Screen is used and the value doesn't matter anyway) { fNewNear = 0.0f; bScreen = true; } else { fNewNear = 0.999f * fZ / fW; } fZ = v4Far.Dot(v4Column2); fW = v4Far.Dot(v4Column3); if (fabs(fW) < 0.001f) // to avoid division by 0 (near the object Screen is used and the value doesn't matter anyway) { fNewFar = 1.0f; bScreen = true; } else { fNewFar = fZ / fW; } float fCamRadiusX = sqrtf(cam.fWR * cam.fWR + cam.fNear * cam.fNear); float fCamRadiusY = sqrtf(cam.fWT * cam.fWT + cam.fNear * cam.fNear); float fWidth = cam.fWR - cam.fWL; float fHeight = cam.fWT - cam.fWB; if (!bScreen) { bScreen = (fRadiusX * cam.fNear / fDistance >= fWidth || fRadiusY * cam.fNear / fDistance >= fHeight || (fDistance - fRadiusX <= fCamRadiusX) || (fDistance - fRadiusY <= fCamRadiusY)); } IDynTexture* pDT = bScreen ? s_pScreenTexture : m_pTexture; SDynTexture2* pDT2 = (SDynTexture2*)pDT; float fRequiredResX = 1024.0f; float fRequiredResY = 512.0f; float imposterRatio = renderer->GetFloatConfigurationValue("r_ImposterRatio", 1.0f); float fTexScale = imposterRatio > 0.1f ? 1.0f / imposterRatio : 1.0f / 0.1f; if (!bScreen) // outside cloud { assert(D3DVP[0] == 0 && D3DVP[1] == 0); // otherwise the following lines don't make sense float fRadPixelX = (fMaxX - fMinX) * 2.0f; // for some reason *2 is needed, most likely /near (*4) is the correct float fRadPixelY = (fMaxY - fMinY) * 2.0f; fRequiredResX = min(fRequiredResX, max(16.0f, fRadPixelX)); fRequiredResY = min(fRequiredResY, max(16.0f, fRadPixelY)); } int nRequiredLogXRes = LogBaseTwo((int)(fRequiredResX * fTexScale)); int nRequiredLogYRes = LogBaseTwo((int)(fRequiredResY * fTexScale)); bool isAlwaysUpdated = renderer->GetBooleanConfigurationValue("r_CloudsUpdateAlways", true); if (IsImposterValid(cam, fRadiusX, fRadiusY, fCamRadiusX, fCamRadiusY, nRequiredLogXRes, nRequiredLogYRes, dwBestEdge)) { if (!pDT2 || !pDT2->_IsValid()) { return true; } if (!isAlwaysUpdated) { return false; } } if (pDT2) { pDT2->ResetUpdateMask(); } bool bPostpone = false; int nCurFrame = renderer->GetFrameID(false); if (renderer->GetActiveGPUCount() == 1) { if (!isAlwaysUpdated && !bScreen && !m_bScreenImposter && pDT && pDT->GetTexture() && m_fRadiusX && m_fRadiusY) { int updatesPerFrame = renderer->GetIntegerConfigurationValue("r_ImpostersUpdatePerFrame", 6000); if (s_MemUpdated > updatesPerFrame) { bPostpone = true; } if (s_PrevMemPostponed) { int nDeltaFrames = s_PrevMemPostponed / updatesPerFrame; if (nCurFrame - m_FrameUpdate > nDeltaFrames) { bPostpone = false; } } if (bPostpone) { s_MemPostponed += (1 << nRequiredLogXRes) * (1 << nRequiredLogYRes) * 4 / 1024; return false; } } } m_FrameUpdate = nCurFrame; m_fNear = fNewNear; m_fFar = fNewFar; m_LastViewParameters = cam; m_vLastSunDir = gEnv->p3DEngine->GetSunDir().GetNormalized(); m_nLogResolutionX = nRequiredLogXRes; m_nLogResolutionY = nRequiredLogYRes; if (!bScreen) { m_LastViewParameters = tempCam; // otherwise the following lines don't make sense assert(D3DVP[0] == 0 && D3DVP[1] == 0); m_LastViewParameters.fWL = (fMinX / D3DVP[2] * 2 - 1); m_LastViewParameters.fWR = (fMaxX / D3DVP[2] * 2 - 1); m_LastViewParameters.fWT = (fMaxY / D3DVP[3] * 2 - 1); m_LastViewParameters.fWB = (fMinY / D3DVP[3] * 2 - 1); m_fRadiusX = 0.5f * (m_LastViewParameters.fWR - m_LastViewParameters.fWL) * fDistance / m_LastViewParameters.fNear; m_fRadiusY = 0.5f * (m_LastViewParameters.fWT - m_LastViewParameters.fWB) * fDistance / m_LastViewParameters.fNear; m_vQuadCorners[0] = vUnProjPos[0] - m_vPos; m_vQuadCorners[1] = vUnProjPos[1] - m_vPos; m_vQuadCorners[2] = vUnProjPos[2] - m_vPos; m_vQuadCorners[3] = vUnProjPos[3] - m_vPos; m_nLastBestEdge = dwBestEdge; m_bScreenImposter = false; // store points used in later error estimation m_vNearPoint = -m_LastViewParameters.vZ * m_LastViewParameters.fNear + m_LastViewParameters.vOrigin; m_vFarPoint = -m_LastViewParameters.vZ * m_LastViewParameters.fFar + m_LastViewParameters.vOrigin; } else { m_bScreenImposter = true; } #endif return true; } bool CloudImposterRenderElement::UpdateImposter() { #if !defined(DEDICATED_SERVER) IRenderer* renderer = gEnv->pRenderer; SRenderPipeline* renderPipeline = renderer->GetRenderPipeline(); if (!PrepareForUpdate()) { return true; } // Save viewport for later restore int oldViewport[4]; renderer->GetViewport(&oldViewport[0], &oldViewport[1], &oldViewport[2], &oldViewport[3]); // Find actual resolution int iResX = 1 << m_nLogResolutionX; int iResY = 1 << m_nLogResolutionY; renderer->FX_SetState(GS_DEPTHWRITE); IDynTexture** pDT; if (!m_bSplit) { pDT = !m_bScreenImposter ? &m_pTexture : &s_pScreenTexture; if (!*pDT) { *pDT = renderer->CreateDynTexture2(iResX, iResY, FT_STATE_CLAMP, "Imposter", eTP_Clouds); } if (*pDT) { (*pDT)->Update(iResX, iResY); CTexture* pT = (CTexture*)(*pDT)->GetTexture(); int nSize = pT->GetDataSize(); s_MemUpdated += nSize / 1024; renderPipeline->m_PS[renderPipeline->m_nProcessThreadID].m_ImpostersSizeUpdate += nSize; SDepthTexture* pDepth = renderer->FX_GetDepthSurface(iResX, iResY, false); (*pDT)->ClearRT(); (*pDT)->SetRT(0, true, pDepth); renderer->FX_ClearTarget(pDepth); float fYFov, fXFov, fAspect, fNearest, fFar; m_LastViewParameters.GetPerspectiveParams(&fYFov, &fXFov, &fAspect, &fNearest, &fFar); CCamera EngCam; CCamera OldCam = renderer->GetCamera(); int nW = iResX; int nH = iResY; fYFov = DEG2RAD(fYFov); fXFov = DEG2RAD(fXFov); if (m_bScreenImposter) { nW = renderer->GetWidth(); nH = renderer->GetHeight(); fXFov = EngCam.GetFov(); } Matrix34 matr; matr = Matrix34::CreateFromVectors(m_LastViewParameters.vX, -m_LastViewParameters.vZ, m_LastViewParameters.vY, m_LastViewParameters.vOrigin); EngCam.SetMatrix(matr); EngCam.SetFrustum(nW, nH, fXFov, fNearest, fFar); Matrix44A transposed = renderer->GetViewProjectionMatrix().GetTransposed(); renderer->SetTranspOrigCameraProjMatrix(transposed); renderer->SetViewParameters(m_LastViewParameters); int nFL = renderPipeline->m_PersFlags2; renderPipeline->m_TI[renderPipeline->m_nProcessThreadID].m_PersFlags |= RBPF_IMPOSTERGEN; renderPipeline->m_PersFlags2 |= RBPF2_NOALPHABLEND | RBPF2_NOALPHATEST; renderPipeline->m_StateAnd &= ~(GS_BLEND_MASK | GS_ALPHATEST_MASK); assert(!"GetI3DEngine()->RenderImposterContent() does not exist"); renderPipeline->m_PersFlags2 = nFL; (*pDT)->RestoreRT(0, true); renderer->SetCamera(OldCam); } } renderer->RT_SetViewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); #endif return true; } bool CloudImposterRenderElement::Display(bool /* bDisplayFrontOfSplit */) { return true; } }
10,612
338
<reponame>XmobiTea-Family/ezyfox-server<filename>ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/socket/EzySimpleSocketStream.java<gh_stars>100-1000 package com.tvd12.ezyfoxserver.socket; import com.tvd12.ezyfoxserver.entity.EzySession; import lombok.Getter; @Getter public class EzySimpleSocketStream implements EzySocketStream { private byte[] bytes; private long timestamp; private EzySession session; public EzySimpleSocketStream(EzySession session, byte[] bytes) { this.bytes = bytes; this.session = session; this.timestamp = System.currentTimeMillis(); } @Override public void release() { this.bytes = null; this.session = null; } }
292
852
<reponame>malbouis/cmssw #ifndef CondFormats_CSCObjects_CSCL1TPLookupTableME11ILT_h #define CondFormats_CSCObjects_CSCL1TPLookupTableME11ILT_h #include "CondFormats/Serialization/interface/Serializable.h" #include <vector> class CSCL1TPLookupTableME11ILT { public: CSCL1TPLookupTableME11ILT(); ~CSCL1TPLookupTableME11ILT() {} typedef std::vector<unsigned> t_lut; // setters void set_GEM_pad_CSC_hs_ME1b_even(t_lut lut); void set_GEM_pad_CSC_hs_ME1a_even(t_lut lut); void set_GEM_pad_CSC_hs_ME1b_odd(t_lut lut); void set_GEM_pad_CSC_hs_ME1a_odd(t_lut lut); void set_GEM_pad_CSC_es_ME1b_even(t_lut lut); void set_GEM_pad_CSC_es_ME1a_even(t_lut lut); void set_GEM_pad_CSC_es_ME1b_odd(t_lut lut); void set_GEM_pad_CSC_es_ME1a_odd(t_lut lut); void set_GEM_roll_L1_CSC_min_wg_ME11_even(t_lut lut); void set_GEM_roll_L1_CSC_max_wg_ME11_even(t_lut lut); void set_GEM_roll_L1_CSC_min_wg_ME11_odd(t_lut lut); void set_GEM_roll_L1_CSC_max_wg_ME11_odd(t_lut lut); void set_GEM_roll_L2_CSC_min_wg_ME11_even(t_lut lut); void set_GEM_roll_L2_CSC_max_wg_ME11_even(t_lut lut); void set_GEM_roll_L2_CSC_min_wg_ME11_odd(t_lut lut); void set_GEM_roll_L2_CSC_max_wg_ME11_odd(t_lut lut); // GEM-CSC trigger: slope correction void set_CSC_slope_cosi_2to1_L1_ME11_even(t_lut lut); void set_CSC_slope_cosi_2to1_L1_ME11_odd(t_lut lut); void set_CSC_slope_cosi_3to1_L1_ME11_even(t_lut lut); void set_CSC_slope_cosi_3to1_L1_ME11_odd(t_lut lut); void set_CSC_slope_cosi_corr_L1_ME11_even(t_lut lut); void set_CSC_slope_cosi_corr_L2_ME11_even(t_lut lut); void set_CSC_slope_cosi_corr_L1_ME11_odd(t_lut lut); void set_CSC_slope_cosi_corr_L2_ME11_odd(t_lut lut); void set_CSC_slope_corr_L1_ME11_even(t_lut lut); void set_CSC_slope_corr_L2_ME11_even(t_lut lut); void set_CSC_slope_corr_L1_ME11_odd(t_lut lut); void set_CSC_slope_corr_L2_ME11_odd(t_lut lut); void set_es_diff_slope_L1_ME1a_even(t_lut lut); void set_es_diff_slope_L2_ME1a_even(t_lut lut); void set_es_diff_slope_L1_ME1a_odd(t_lut lut); void set_es_diff_slope_L2_ME1a_odd(t_lut lut); void set_es_diff_slope_L1_ME1b_even(t_lut lut); void set_es_diff_slope_L2_ME1b_even(t_lut lut); void set_es_diff_slope_L1_ME1b_odd(t_lut lut); void set_es_diff_slope_L2_ME1b_odd(t_lut lut); // getters unsigned GEM_pad_CSC_hs_ME1b_even(unsigned pad) const; unsigned GEM_pad_CSC_hs_ME1a_even(unsigned pad) const; unsigned GEM_pad_CSC_hs_ME1b_odd(unsigned pad) const; unsigned GEM_pad_CSC_hs_ME1a_odd(unsigned pad) const; unsigned GEM_pad_CSC_es_ME1b_even(unsigned pad) const; unsigned GEM_pad_CSC_es_ME1a_even(unsigned pad) const; unsigned GEM_pad_CSC_es_ME1b_odd(unsigned pad) const; unsigned GEM_pad_CSC_es_ME1a_odd(unsigned pad) const; unsigned GEM_roll_L1_CSC_min_wg_ME11_even(unsigned roll) const; unsigned GEM_roll_L1_CSC_max_wg_ME11_even(unsigned roll) const; unsigned GEM_roll_L1_CSC_min_wg_ME11_odd(unsigned roll) const; unsigned GEM_roll_L1_CSC_max_wg_ME11_odd(unsigned roll) const; unsigned GEM_roll_L2_CSC_min_wg_ME11_even(unsigned roll) const; unsigned GEM_roll_L2_CSC_max_wg_ME11_even(unsigned roll) const; unsigned GEM_roll_L2_CSC_min_wg_ME11_odd(unsigned roll) const; unsigned GEM_roll_L2_CSC_max_wg_ME11_odd(unsigned roll) const; // GEM-CSC trigger: slope correction unsigned CSC_slope_cosi_2to1_L1_ME11_even(unsigned channel) const; unsigned CSC_slope_cosi_2to1_L1_ME11_odd(unsigned channel) const; unsigned CSC_slope_cosi_3to1_L1_ME11_even(unsigned channel) const; unsigned CSC_slope_cosi_3to1_L1_ME11_odd(unsigned channel) const; unsigned CSC_slope_cosi_corr_L1_ME11_even(unsigned channel) const; unsigned CSC_slope_cosi_corr_L2_ME11_even(unsigned channel) const; unsigned CSC_slope_cosi_corr_L1_ME11_odd(unsigned channel) const; unsigned CSC_slope_cosi_corr_L2_ME11_odd(unsigned channel) const; unsigned CSC_slope_corr_L1_ME11_even(unsigned channel) const; unsigned CSC_slope_corr_L2_ME11_even(unsigned channel) const; unsigned CSC_slope_corr_L1_ME11_odd(unsigned channel) const; unsigned CSC_slope_corr_L2_ME11_odd(unsigned channel) const; // GEM-CSC trigger: 1/8-strip difference to slope unsigned es_diff_slope_L1_ME1a_even(unsigned es_diff) const; unsigned es_diff_slope_L2_ME1a_even(unsigned es_diff) const; unsigned es_diff_slope_L1_ME1a_odd(unsigned es_diff) const; unsigned es_diff_slope_L2_ME1a_odd(unsigned es_diff) const; unsigned es_diff_slope_L1_ME1b_even(unsigned es_diff) const; unsigned es_diff_slope_L2_ME1b_even(unsigned es_diff) const; unsigned es_diff_slope_L1_ME1b_odd(unsigned es_diff) const; unsigned es_diff_slope_L2_ME1b_odd(unsigned es_diff) const; private: t_lut GEM_pad_CSC_hs_ME1b_even_; t_lut GEM_pad_CSC_hs_ME1a_even_; t_lut GEM_pad_CSC_hs_ME1b_odd_; t_lut GEM_pad_CSC_hs_ME1a_odd_; t_lut GEM_pad_CSC_es_ME1b_even_; t_lut GEM_pad_CSC_es_ME1a_even_; t_lut GEM_pad_CSC_es_ME1b_odd_; t_lut GEM_pad_CSC_es_ME1a_odd_; t_lut GEM_roll_L1_CSC_min_wg_ME11_even_; t_lut GEM_roll_L1_CSC_max_wg_ME11_even_; t_lut GEM_roll_L1_CSC_min_wg_ME11_odd_; t_lut GEM_roll_L1_CSC_max_wg_ME11_odd_; t_lut GEM_roll_L2_CSC_min_wg_ME11_even_; t_lut GEM_roll_L2_CSC_max_wg_ME11_even_; t_lut GEM_roll_L2_CSC_min_wg_ME11_odd_; t_lut GEM_roll_L2_CSC_max_wg_ME11_odd_; t_lut CSC_slope_cosi_2to1_L1_ME11_even_; t_lut CSC_slope_cosi_2to1_L1_ME11_odd_; t_lut CSC_slope_cosi_3to1_L1_ME11_even_; t_lut CSC_slope_cosi_3to1_L1_ME11_odd_; t_lut CSC_slope_cosi_corr_L1_ME11_even_; t_lut CSC_slope_cosi_corr_L2_ME11_even_; t_lut CSC_slope_cosi_corr_L1_ME11_odd_; t_lut CSC_slope_cosi_corr_L2_ME11_odd_; t_lut CSC_slope_corr_L1_ME11_even_; t_lut CSC_slope_corr_L2_ME11_even_; t_lut CSC_slope_corr_L1_ME11_odd_; t_lut CSC_slope_corr_L2_ME11_odd_; t_lut es_diff_slope_L1_ME1a_even_; t_lut es_diff_slope_L2_ME1a_even_; t_lut es_diff_slope_L1_ME1a_odd_; t_lut es_diff_slope_L2_ME1a_odd_; t_lut es_diff_slope_L1_ME1b_even_; t_lut es_diff_slope_L2_ME1b_even_; t_lut es_diff_slope_L1_ME1b_odd_; t_lut es_diff_slope_L2_ME1b_odd_; COND_SERIALIZABLE; }; #endif
3,187
3,702
<reponame>skahler-yuga/yugabyte-db<gh_stars>1000+ // Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/util/net/inetaddress.h" #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include "yb/gutil/strings/split.h" #include "yb/util/net/net_util.h" using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::tcp; namespace yb { InetAddress::InetAddress() { } InetAddress::InetAddress(const boost::asio::ip::address& address) : boost_addr_(address) { } InetAddress::InetAddress(const InetAddress& other) { boost_addr_ = other.boost_addr_; } std::string InetAddress::ToString() const { std::string strval; CHECK_OK(ToString(&strval)); return strval; } CHECKED_STATUS InetAddress::ToString(std::string *strval) const { boost::system::error_code ec; *strval = boost_addr_.to_string(ec); if (ec.value()) { return STATUS(IllegalState, "InetAddress object cannot be converted to string: $0", ec.message()); } return Status::OK(); } CHECKED_STATUS InetAddress::ToBytes(std::string* bytes) const { try { if (boost_addr_.is_v4()) { auto v4bytes = boost_addr_.to_v4().to_bytes(); bytes->assign(reinterpret_cast<char *>(v4bytes.data()), v4bytes.size()); } else if (boost_addr_.is_v6()) { auto v6bytes = boost_addr_.to_v6().to_bytes(); bytes->assign(reinterpret_cast<char *>(v6bytes.data()), v6bytes.size()); } else { return STATUS(Uninitialized, "InetAddress doesn't hold a valid IPv4 or IPv6 address"); } } catch (std::exception& e) { return STATUS(Corruption, "Couldn't serialize InetAddress to raw bytes!"); } return Status::OK(); } CHECKED_STATUS InetAddress::FromSlice(const Slice& slice, size_t size_hint) { size_t expected_size = (size_hint == 0) ? slice.size() : size_hint; if (expected_size > slice.size()) { return STATUS_SUBSTITUTE(InvalidArgument, "Size of slice: $0 is smaller than provided " "size_hint: $1", slice.size(), expected_size); } if (expected_size == kInetAddressV4Size) { address_v4::bytes_type v4bytes; DCHECK_EQ(expected_size, v4bytes.size()); memcpy(v4bytes.data(), slice.data(), v4bytes.size()); address_v4 v4address(v4bytes); boost_addr_ = v4address; } else if (expected_size == kInetAddressV6Size) { address_v6::bytes_type v6bytes; DCHECK_EQ(expected_size, v6bytes.size()); memcpy(v6bytes.data(), slice.data(), v6bytes.size()); address_v6 v6address(v6bytes); boost_addr_ = v6address; } else { return STATUS_SUBSTITUTE(InvalidArgument, "Size of slice is invalid: $0", expected_size); } return Status::OK(); } CHECKED_STATUS InetAddress::FromBytes(const std::string& bytes) { Slice slice (bytes.data(), bytes.size()); return FromSlice(slice); } bool IsIPv6NonLinkLocal(const IpAddress& address) { if (!address.is_v6() || address.is_unspecified()) { return false; } boost::asio::ip::address_v6 v6_address = address.to_v6(); return !v6_address.is_link_local(); } bool IsIPv6External(const IpAddress& address) { return address.is_v6() && !address.is_unspecified() && !address.is_loopback() && IsIPv6NonLinkLocal(address); } typedef std::function<bool(const IpAddress&)> FilterType; const std::map<string, FilterType>* GetFilters() { static const auto ipv4_filter = [](const IpAddress& a) { return a.is_v4(); }; static const auto ipv6_filter = [](const IpAddress& a) { return a.is_v6(); }; static const auto ipv4_external_filter = [](const IpAddress& a) { return !a.is_unspecified() && a.is_v4() && !a.is_loopback(); }; static const auto ipv6_external_filter = [](const IpAddress& a) { return IsIPv6External(a); }; static const auto ipv6_non_link_local_filter = [](const IpAddress& a) { return IsIPv6NonLinkLocal(a); }; static const auto all_filter = [](const IpAddress& a) { return true; }; static const std::map<string, FilterType> kFilters( { { "ipv4_all", ipv4_filter }, // any IPv4 address including 0.0.0.0 and loopback { "ipv6_all", ipv6_filter }, // any IPv6 address including ::, loopback etc { "ipv4_external", ipv4_external_filter }, // Non-loopback IPv4 { "ipv6_external", ipv6_external_filter }, // Non-loopback non-link-local IPv6 { "ipv6_non_link_local", ipv6_non_link_local_filter }, // Non-link-local, loopback is ok { "all", all_filter } }); return &kFilters; } // Filter_spec has to be some subset of the following filters // ipv4_all,ipv4_external,ipv6_all,ipv6_external,ipv6_non_link_local // For ex: "ipv4_external,ipv4_all,ipv6_external,ipv6_non_link_local" // This would result in a vector that has // [ IPV4 external addresses, Remaining IPv4 addresses, IPv6 external addresses, // Non-external IPv6 non_link_local addresses ] // with [ link_local IPv6 addresses ] removed from the original list void FilterAddresses(const string& filter_spec, vector<IpAddress>* addresses) { if (filter_spec.empty()) { return; } const std::map<string, FilterType>* kFilters = GetFilters(); DCHECK(kFilters); vector<string> filter_names = strings::Split(filter_spec, ","); vector<const FilterType*> filters; filters.reserve(filter_names.size()); for (const auto &filter_name : filter_names) { VLOG(4) << "filtering by " << filter_name; auto filter_it = kFilters->find(filter_name); if (filter_it != kFilters->end()) { filters.push_back(&filter_it->second); } else { LOG(ERROR) << "Unknown filter spec " << filter_name << " in filter spec " << filter_spec; } } vector<vector<IpAddress> > matches(filters.size()); for (const auto& address : *addresses) { for (size_t i = 0; i < filters.size(); ++i) { DCHECK(filters[i]); if ((*filters[i])(address)) { VLOG(3) << address.to_string() << " matches filter " << filter_names[i]; matches[i].push_back(address); break; } else { VLOG(4) << address.to_string() << " does not match filter " << filter_names[i]; } } } vector<IpAddress> results; for (const auto& match : matches) { results.insert(results.end(), match.begin(), match.end()); } addresses->swap(results); } } // namespace yb
2,641
1,962
package com.bolingcavalry.druidonesource.mapper; import com.bolingcavalry.druidonesource.entity.LogExtend; import com.bolingcavalry.druidonesource.entity.User; import org.springframework.stereotype.Repository; import java.util.List; /** * @Description: (这里用一句话描述这个类的作用) * @author: willzhao E-mail: <EMAIL> * @date: 2020/8/4 8:32 */ @Repository public interface UserMapper { User sel(int id); int insertWithFields(User user); int insertBatch(List<User> users); int clearAll(); List<User> findByName(String name); int update(User user); int delete(int id); int totalCount(); LogExtend selExtend(int id); }
272
838
<filename>test/lib/stmt.h /** * Setup a test prepared statement. */ #ifndef TEST_STMT_H #define TEST_STMT_H #include <sqlite3.h> #define FIXTURE_STMT sqlite3_stmt *stmt #define STMT_PREPARE(CONN, STMT, SQL) \ { \ int rc; \ rc = sqlite3_prepare_v2(CONN, SQL, -1, &STMT, NULL); \ munit_assert_int(rc, ==, 0); \ } #define STMT_FINALIZE(STMT) sqlite3_finalize(STMT) #define STMT_EXEC(CONN, SQL) \ { \ int rc; \ char *msg; \ rc = sqlite3_exec(CONN, SQL, NULL, NULL, &msg); \ munit_assert_int(rc, ==, SQLITE_OK); \ } #endif /* TEST_STMT_H */
610
4,036
// Generated automatically from android.util.ArrayMap for testing purposes package android.util; import java.util.Collection; import java.util.Map; import java.util.Set; public class ArrayMap<K, V> implements Map<K, V> { public ArrayMap(){} public ArrayMap(ArrayMap<K, V> p0){} public ArrayMap(int p0){} public Collection<V> values(){ return null; } public K keyAt(int p0){ return null; } public Set<K> keySet(){ return null; } public Set<Map.Entry<K, V>> entrySet(){ return null; } public String toString(){ return null; } public V get(Object p0){ return null; } public V put(K p0, V p1){ return null; } public V remove(Object p0){ return null; } public V removeAt(int p0){ return null; } public V setValueAt(int p0, V p1){ return null; } public V valueAt(int p0){ return null; } public boolean containsAll(Collection<? extends Object> p0){ return false; } public boolean containsKey(Object p0){ return false; } public boolean containsValue(Object p0){ return false; } public boolean equals(Object p0){ return false; } public boolean isEmpty(){ return false; } public boolean removeAll(Collection<? extends Object> p0){ return false; } public boolean retainAll(Collection<? extends Object> p0){ return false; } public int hashCode(){ return 0; } public int indexOfKey(Object p0){ return 0; } public int indexOfValue(Object p0){ return 0; } public int size(){ return 0; } public void clear(){} public void ensureCapacity(int p0){} public void putAll(ArrayMap<? extends K, ? extends V> p0){} public void putAll(Map<? extends K, ? extends V> p0){} }
557
14,668
<reponame>zealoussnow/chromium // Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/policy/core/common/policy_load_status.h" #include "base/bind.h" #include "base/metrics/histogram.h" #include "components/policy/core/common/policy_types.h" namespace policy { namespace { const char kHistogramName[] = "Enterprise.PolicyLoadStatus"; } // namespace PolicyLoadStatusSampler::PolicyLoadStatusSampler() { Add(POLICY_LOAD_STATUS_STARTED); } PolicyLoadStatusSampler::~PolicyLoadStatusSampler() {} void PolicyLoadStatusSampler::Add(PolicyLoadStatus status) { status_bits_[status] = true; } PolicyLoadStatusUmaReporter::PolicyLoadStatusUmaReporter() {} PolicyLoadStatusUmaReporter::~PolicyLoadStatusUmaReporter() { base::HistogramBase* histogram(base::LinearHistogram::FactoryGet( kHistogramName, 1, POLICY_LOAD_STATUS_SIZE, POLICY_LOAD_STATUS_SIZE + 1, base::Histogram::kUmaTargetedHistogramFlag)); for (int i = 0; i < POLICY_LOAD_STATUS_SIZE; ++i) { if (GetStatusSet()[i]) histogram->Add(i); } } } // namespace policy
420
476
<filename>hetu-sql-migration-tool/src/main/java/io/hetu/core/sql/migration/tool/SqlConverterFactory.java /* * Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hetu.core.sql.migration.tool; import io.hetu.core.sql.migration.SqlMigrationException; import static java.lang.String.format; public class SqlConverterFactory { private SqlConverterFactory() {} public static SqlSyntaxConverter getSqlConverter(SessionProperties session) throws SqlMigrationException { switch (session.getSourceType()) { case HIVE: return HiveSqlConverter.getHiveSqlConverter(session.getParsingOptions()); case IMPALA: return ImpalaSqlConverter.getImpalaSqlConverter(session.getParsingOptions()); default: throw new SqlMigrationException(format("Migration tool doesn't support type: %s", session.getSourceType())); } } }
523
352
#pragma once #include <stdint.h> #include "minheap.h" struct rank_hit { doc_id_t docID; float score; uint32_t n_occurs; position_t *occurs; /* occur positions */ }; typedef struct priority_Q { struct heap heap; uint32_t n_elements; } ranked_results_t /* a conceptually more descriptive name */; void priority_Q_init(struct priority_Q*, uint32_t); bool priority_Q_full(struct priority_Q*); float priority_Q_min_score(struct priority_Q*); bool priority_Q_add_or_replace(struct priority_Q*, struct rank_hit*); void priority_Q_sort(struct priority_Q*); void priority_Q_print(struct priority_Q*); void priority_Q_free(struct priority_Q*); /* a conceptually more descriptive name */ #define free_ranked_results(_Q) \ priority_Q_free(_Q) /* ranking window */ struct rank_window { ranked_results_t *results; uint32_t from, to; }; struct rank_window rank_window_calc(ranked_results_t*, uint32_t, uint32_t, uint32_t*); typedef void (*rank_window_it_callbk)(struct rank_hit*, uint32_t, void*); uint32_t rank_window_foreach(struct rank_window*, rank_window_it_callbk, void*);
424
435
{ "copyright_text": "Standard YouTube License", "description": "PyData DC 2016\n\nThis tutorial is an introduction to how to matplotlib's event handling system to build an tool for interactively exploring multi-scale time series data.\n\nThe primary example will be how to 'drill down' through summary data sets to view the underlying data using hourly weather data from NOAA.", "duration": 3657, "language": "eng", "recorded": "2016-10-07", "related_urls": [ "http://pydata.org/dc2016/schedule/presentation/79/" ], "speakers": [ "<NAME>" ], "tags": [ "matplotlib" ], "thumbnail_url": "https://i.ytimg.com/vi/oEIf6ugC8Gg/maxresdefault.jpg", "title": "Interactive multi scale time series exploration with matplotlib", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=oEIf6ugC8Gg" } ] }
309
38,047
#include "test/jemalloc_test.h" #include "jemalloc/internal/ticker.h" static nstime_monotonic_t *nstime_monotonic_orig; static nstime_update_t *nstime_update_orig; static unsigned nupdates_mock; static nstime_t time_mock; static bool monotonic_mock; static bool check_background_thread_enabled(void) { bool enabled; size_t sz = sizeof(bool); int ret = mallctl("background_thread", (void *)&enabled, &sz, NULL,0); if (ret == ENOENT) { return false; } assert_d_eq(ret, 0, "Unexpected mallctl error"); return enabled; } static bool nstime_monotonic_mock(void) { return monotonic_mock; } static bool nstime_update_mock(nstime_t *time) { nupdates_mock++; if (monotonic_mock) { nstime_copy(time, &time_mock); } return !monotonic_mock; } static unsigned do_arena_create(ssize_t dirty_decay_ms, ssize_t muzzy_decay_ms) { unsigned arena_ind; size_t sz = sizeof(unsigned); assert_d_eq(mallctl("arenas.create", (void *)&arena_ind, &sz, NULL, 0), 0, "Unexpected mallctl() failure"); size_t mib[3]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib("arena.0.dirty_decay_ms", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[1] = (size_t)arena_ind; assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, (void *)&dirty_decay_ms, sizeof(dirty_decay_ms)), 0, "Unexpected mallctlbymib() failure"); assert_d_eq(mallctlnametomib("arena.0.muzzy_decay_ms", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[1] = (size_t)arena_ind; assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, (void *)&muzzy_decay_ms, sizeof(muzzy_decay_ms)), 0, "Unexpected mallctlbymib() failure"); return arena_ind; } static void do_arena_destroy(unsigned arena_ind) { size_t mib[3]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib("arena.0.destroy", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[1] = (size_t)arena_ind; assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, NULL, 0), 0, "Unexpected mallctlbymib() failure"); } void do_epoch(void) { uint64_t epoch = 1; assert_d_eq(mallctl("epoch", NULL, NULL, (void *)&epoch, sizeof(epoch)), 0, "Unexpected mallctl() failure"); } void do_purge(unsigned arena_ind) { size_t mib[3]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib("arena.0.purge", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[1] = (size_t)arena_ind; assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, NULL, 0), 0, "Unexpected mallctlbymib() failure"); } void do_decay(unsigned arena_ind) { size_t mib[3]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib("arena.0.decay", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[1] = (size_t)arena_ind; assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, NULL, 0), 0, "Unexpected mallctlbymib() failure"); } static uint64_t get_arena_npurge_impl(const char *mibname, unsigned arena_ind) { size_t mib[4]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib(mibname, mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[2] = (size_t)arena_ind; uint64_t npurge = 0; size_t sz = sizeof(npurge); assert_d_eq(mallctlbymib(mib, miblen, (void *)&npurge, &sz, NULL, 0), config_stats ? 0 : ENOENT, "Unexpected mallctlbymib() failure"); return npurge; } static uint64_t get_arena_dirty_npurge(unsigned arena_ind) { do_epoch(); return get_arena_npurge_impl("stats.arenas.0.dirty_npurge", arena_ind); } static uint64_t get_arena_dirty_purged(unsigned arena_ind) { do_epoch(); return get_arena_npurge_impl("stats.arenas.0.dirty_purged", arena_ind); } static uint64_t get_arena_muzzy_npurge(unsigned arena_ind) { do_epoch(); return get_arena_npurge_impl("stats.arenas.0.muzzy_npurge", arena_ind); } static uint64_t get_arena_npurge(unsigned arena_ind) { do_epoch(); return get_arena_npurge_impl("stats.arenas.0.dirty_npurge", arena_ind) + get_arena_npurge_impl("stats.arenas.0.muzzy_npurge", arena_ind); } static size_t get_arena_pdirty(unsigned arena_ind) { do_epoch(); size_t mib[4]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib("stats.arenas.0.pdirty", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[2] = (size_t)arena_ind; size_t pdirty; size_t sz = sizeof(pdirty); assert_d_eq(mallctlbymib(mib, miblen, (void *)&pdirty, &sz, NULL, 0), 0, "Unexpected mallctlbymib() failure"); return pdirty; } static size_t get_arena_pmuzzy(unsigned arena_ind) { do_epoch(); size_t mib[4]; size_t miblen = sizeof(mib)/sizeof(size_t); assert_d_eq(mallctlnametomib("stats.arenas.0.pmuzzy", mib, &miblen), 0, "Unexpected mallctlnametomib() failure"); mib[2] = (size_t)arena_ind; size_t pmuzzy; size_t sz = sizeof(pmuzzy); assert_d_eq(mallctlbymib(mib, miblen, (void *)&pmuzzy, &sz, NULL, 0), 0, "Unexpected mallctlbymib() failure"); return pmuzzy; } static void * do_mallocx(size_t size, int flags) { void *p = mallocx(size, flags); assert_ptr_not_null(p, "Unexpected mallocx() failure"); return p; } static void generate_dirty(unsigned arena_ind, size_t size) { int flags = MALLOCX_ARENA(arena_ind) | MALLOCX_TCACHE_NONE; void *p = do_mallocx(size, flags); dallocx(p, flags); } TEST_BEGIN(test_decay_ticks) { test_skip_if(check_background_thread_enabled()); ticker_t *decay_ticker; unsigned tick0, tick1, arena_ind; size_t sz, large0; void *p; sz = sizeof(size_t); assert_d_eq(mallctl("arenas.lextent.0.size", (void *)&large0, &sz, NULL, 0), 0, "Unexpected mallctl failure"); /* Set up a manually managed arena for test. */ arena_ind = do_arena_create(0, 0); /* Migrate to the new arena, and get the ticker. */ unsigned old_arena_ind; size_t sz_arena_ind = sizeof(old_arena_ind); assert_d_eq(mallctl("thread.arena", (void *)&old_arena_ind, &sz_arena_ind, (void *)&arena_ind, sizeof(arena_ind)), 0, "Unexpected mallctl() failure"); decay_ticker = decay_ticker_get(tsd_fetch(), arena_ind); assert_ptr_not_null(decay_ticker, "Unexpected failure getting decay ticker"); /* * Test the standard APIs using a large size class, since we can't * control tcache interactions for small size classes (except by * completely disabling tcache for the entire test program). */ /* malloc(). */ tick0 = ticker_read(decay_ticker); p = malloc(large0); assert_ptr_not_null(p, "Unexpected malloc() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during malloc()"); /* free(). */ tick0 = ticker_read(decay_ticker); free(p); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during free()"); /* calloc(). */ tick0 = ticker_read(decay_ticker); p = calloc(1, large0); assert_ptr_not_null(p, "Unexpected calloc() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during calloc()"); free(p); /* posix_memalign(). */ tick0 = ticker_read(decay_ticker); assert_d_eq(posix_memalign(&p, sizeof(size_t), large0), 0, "Unexpected posix_memalign() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during posix_memalign()"); free(p); /* aligned_alloc(). */ tick0 = ticker_read(decay_ticker); p = aligned_alloc(sizeof(size_t), large0); assert_ptr_not_null(p, "Unexpected aligned_alloc() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during aligned_alloc()"); free(p); /* realloc(). */ /* Allocate. */ tick0 = ticker_read(decay_ticker); p = realloc(NULL, large0); assert_ptr_not_null(p, "Unexpected realloc() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during realloc()"); /* Reallocate. */ tick0 = ticker_read(decay_ticker); p = realloc(p, large0); assert_ptr_not_null(p, "Unexpected realloc() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during realloc()"); /* Deallocate. */ tick0 = ticker_read(decay_ticker); realloc(p, 0); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during realloc()"); /* * Test the *allocx() APIs using large and small size classes, with * tcache explicitly disabled. */ { unsigned i; size_t allocx_sizes[2]; allocx_sizes[0] = large0; allocx_sizes[1] = 1; for (i = 0; i < sizeof(allocx_sizes) / sizeof(size_t); i++) { sz = allocx_sizes[i]; /* mallocx(). */ tick0 = ticker_read(decay_ticker); p = mallocx(sz, MALLOCX_TCACHE_NONE); assert_ptr_not_null(p, "Unexpected mallocx() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during mallocx() (sz=%zu)", sz); /* rallocx(). */ tick0 = ticker_read(decay_ticker); p = rallocx(p, sz, MALLOCX_TCACHE_NONE); assert_ptr_not_null(p, "Unexpected rallocx() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during rallocx() (sz=%zu)", sz); /* xallocx(). */ tick0 = ticker_read(decay_ticker); xallocx(p, sz, 0, MALLOCX_TCACHE_NONE); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during xallocx() (sz=%zu)", sz); /* dallocx(). */ tick0 = ticker_read(decay_ticker); dallocx(p, MALLOCX_TCACHE_NONE); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during dallocx() (sz=%zu)", sz); /* sdallocx(). */ p = mallocx(sz, MALLOCX_TCACHE_NONE); assert_ptr_not_null(p, "Unexpected mallocx() failure"); tick0 = ticker_read(decay_ticker); sdallocx(p, sz, MALLOCX_TCACHE_NONE); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during sdallocx() " "(sz=%zu)", sz); } } /* * Test tcache fill/flush interactions for large and small size classes, * using an explicit tcache. */ unsigned tcache_ind, i; size_t tcache_sizes[2]; tcache_sizes[0] = large0; tcache_sizes[1] = 1; size_t tcache_max, sz_tcache_max; sz_tcache_max = sizeof(tcache_max); assert_d_eq(mallctl("arenas.tcache_max", (void *)&tcache_max, &sz_tcache_max, NULL, 0), 0, "Unexpected mallctl() failure"); sz = sizeof(unsigned); assert_d_eq(mallctl("tcache.create", (void *)&tcache_ind, &sz, NULL, 0), 0, "Unexpected mallctl failure"); for (i = 0; i < sizeof(tcache_sizes) / sizeof(size_t); i++) { sz = tcache_sizes[i]; /* tcache fill. */ tick0 = ticker_read(decay_ticker); p = mallocx(sz, MALLOCX_TCACHE(tcache_ind)); assert_ptr_not_null(p, "Unexpected mallocx() failure"); tick1 = ticker_read(decay_ticker); assert_u32_ne(tick1, tick0, "Expected ticker to tick during tcache fill " "(sz=%zu)", sz); /* tcache flush. */ dallocx(p, MALLOCX_TCACHE(tcache_ind)); tick0 = ticker_read(decay_ticker); assert_d_eq(mallctl("tcache.flush", NULL, NULL, (void *)&tcache_ind, sizeof(unsigned)), 0, "Unexpected mallctl failure"); tick1 = ticker_read(decay_ticker); /* Will only tick if it's in tcache. */ if (sz <= tcache_max) { assert_u32_ne(tick1, tick0, "Expected ticker to tick during tcache " "flush (sz=%zu)", sz); } else { assert_u32_eq(tick1, tick0, "Unexpected ticker tick during tcache " "flush (sz=%zu)", sz); } } } TEST_END static void decay_ticker_helper(unsigned arena_ind, int flags, bool dirty, ssize_t dt, uint64_t dirty_npurge0, uint64_t muzzy_npurge0, bool terminate_asap) { #define NINTERVALS 101 nstime_t time, update_interval, decay_ms, deadline; nstime_init(&time, 0); nstime_update(&time); nstime_init2(&decay_ms, dt, 0); nstime_copy(&deadline, &time); nstime_add(&deadline, &decay_ms); nstime_init2(&update_interval, dt, 0); nstime_idivide(&update_interval, NINTERVALS); /* * Keep q's slab from being deallocated during the looping below. If a * cached slab were to repeatedly come and go during looping, it could * prevent the decay backlog ever becoming empty. */ void *p = do_mallocx(1, flags); uint64_t dirty_npurge1, muzzy_npurge1; do { for (unsigned i = 0; i < DECAY_NTICKS_PER_UPDATE / 2; i++) { void *q = do_mallocx(1, flags); dallocx(q, flags); } dirty_npurge1 = get_arena_dirty_npurge(arena_ind); muzzy_npurge1 = get_arena_muzzy_npurge(arena_ind); nstime_add(&time_mock, &update_interval); nstime_update(&time); } while (nstime_compare(&time, &deadline) <= 0 && ((dirty_npurge1 == dirty_npurge0 && muzzy_npurge1 == muzzy_npurge0) || !terminate_asap)); dallocx(p, flags); if (config_stats) { assert_u64_gt(dirty_npurge1 + muzzy_npurge1, dirty_npurge0 + muzzy_npurge0, "Expected purging to occur"); } #undef NINTERVALS } TEST_BEGIN(test_decay_ticker) { test_skip_if(check_background_thread_enabled()); #define NPS 2048 ssize_t ddt = opt_dirty_decay_ms; ssize_t mdt = opt_muzzy_decay_ms; unsigned arena_ind = do_arena_create(ddt, mdt); int flags = (MALLOCX_ARENA(arena_ind) | MALLOCX_TCACHE_NONE); void *ps[NPS]; size_t large; /* * Allocate a bunch of large objects, pause the clock, deallocate every * other object (to fragment virtual memory), restore the clock, then * [md]allocx() in a tight loop while advancing time rapidly to verify * the ticker triggers purging. */ size_t tcache_max; size_t sz = sizeof(size_t); assert_d_eq(mallctl("arenas.tcache_max", (void *)&tcache_max, &sz, NULL, 0), 0, "Unexpected mallctl failure"); large = nallocx(tcache_max + 1, flags); do_purge(arena_ind); uint64_t dirty_npurge0 = get_arena_dirty_npurge(arena_ind); uint64_t muzzy_npurge0 = get_arena_muzzy_npurge(arena_ind); for (unsigned i = 0; i < NPS; i++) { ps[i] = do_mallocx(large, flags); } nupdates_mock = 0; nstime_init(&time_mock, 0); nstime_update(&time_mock); monotonic_mock = true; nstime_monotonic_orig = nstime_monotonic; nstime_update_orig = nstime_update; nstime_monotonic = nstime_monotonic_mock; nstime_update = nstime_update_mock; for (unsigned i = 0; i < NPS; i += 2) { dallocx(ps[i], flags); unsigned nupdates0 = nupdates_mock; do_decay(arena_ind); assert_u_gt(nupdates_mock, nupdates0, "Expected nstime_update() to be called"); } decay_ticker_helper(arena_ind, flags, true, ddt, dirty_npurge0, muzzy_npurge0, true); decay_ticker_helper(arena_ind, flags, false, ddt+mdt, dirty_npurge0, muzzy_npurge0, false); do_arena_destroy(arena_ind); nstime_monotonic = nstime_monotonic_orig; nstime_update = nstime_update_orig; #undef NPS } TEST_END TEST_BEGIN(test_decay_nonmonotonic) { test_skip_if(check_background_thread_enabled()); #define NPS (SMOOTHSTEP_NSTEPS + 1) int flags = (MALLOCX_ARENA(0) | MALLOCX_TCACHE_NONE); void *ps[NPS]; uint64_t npurge0 = 0; uint64_t npurge1 = 0; size_t sz, large0; unsigned i, nupdates0; sz = sizeof(size_t); assert_d_eq(mallctl("arenas.lextent.0.size", (void *)&large0, &sz, NULL, 0), 0, "Unexpected mallctl failure"); assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0, "Unexpected mallctl failure"); do_epoch(); sz = sizeof(uint64_t); npurge0 = get_arena_npurge(0); nupdates_mock = 0; nstime_init(&time_mock, 0); nstime_update(&time_mock); monotonic_mock = false; nstime_monotonic_orig = nstime_monotonic; nstime_update_orig = nstime_update; nstime_monotonic = nstime_monotonic_mock; nstime_update = nstime_update_mock; for (i = 0; i < NPS; i++) { ps[i] = mallocx(large0, flags); assert_ptr_not_null(ps[i], "Unexpected mallocx() failure"); } for (i = 0; i < NPS; i++) { dallocx(ps[i], flags); nupdates0 = nupdates_mock; assert_d_eq(mallctl("arena.0.decay", NULL, NULL, NULL, 0), 0, "Unexpected arena.0.decay failure"); assert_u_gt(nupdates_mock, nupdates0, "Expected nstime_update() to be called"); } do_epoch(); sz = sizeof(uint64_t); npurge1 = get_arena_npurge(0); if (config_stats) { assert_u64_eq(npurge0, npurge1, "Unexpected purging occurred"); } nstime_monotonic = nstime_monotonic_orig; nstime_update = nstime_update_orig; #undef NPS } TEST_END TEST_BEGIN(test_decay_now) { test_skip_if(check_background_thread_enabled()); unsigned arena_ind = do_arena_create(0, 0); assert_zu_eq(get_arena_pdirty(arena_ind), 0, "Unexpected dirty pages"); assert_zu_eq(get_arena_pmuzzy(arena_ind), 0, "Unexpected muzzy pages"); size_t sizes[] = {16, PAGE<<2, HUGEPAGE<<2}; /* Verify that dirty/muzzy pages never linger after deallocation. */ for (unsigned i = 0; i < sizeof(sizes)/sizeof(size_t); i++) { size_t size = sizes[i]; generate_dirty(arena_ind, size); assert_zu_eq(get_arena_pdirty(arena_ind), 0, "Unexpected dirty pages"); assert_zu_eq(get_arena_pmuzzy(arena_ind), 0, "Unexpected muzzy pages"); } do_arena_destroy(arena_ind); } TEST_END TEST_BEGIN(test_decay_never) { test_skip_if(check_background_thread_enabled() || !config_stats); unsigned arena_ind = do_arena_create(-1, -1); int flags = MALLOCX_ARENA(arena_ind) | MALLOCX_TCACHE_NONE; assert_zu_eq(get_arena_pdirty(arena_ind), 0, "Unexpected dirty pages"); assert_zu_eq(get_arena_pmuzzy(arena_ind), 0, "Unexpected muzzy pages"); size_t sizes[] = {16, PAGE<<2, HUGEPAGE<<2}; void *ptrs[sizeof(sizes)/sizeof(size_t)]; for (unsigned i = 0; i < sizeof(sizes)/sizeof(size_t); i++) { ptrs[i] = do_mallocx(sizes[i], flags); } /* Verify that each deallocation generates additional dirty pages. */ size_t pdirty_prev = get_arena_pdirty(arena_ind); size_t pmuzzy_prev = get_arena_pmuzzy(arena_ind); assert_zu_eq(pdirty_prev, 0, "Unexpected dirty pages"); assert_zu_eq(pmuzzy_prev, 0, "Unexpected muzzy pages"); for (unsigned i = 0; i < sizeof(sizes)/sizeof(size_t); i++) { dallocx(ptrs[i], flags); size_t pdirty = get_arena_pdirty(arena_ind); size_t pmuzzy = get_arena_pmuzzy(arena_ind); assert_zu_gt(pdirty + (size_t)get_arena_dirty_purged(arena_ind), pdirty_prev, "Expected dirty pages to increase."); assert_zu_eq(pmuzzy, 0, "Unexpected muzzy pages"); pdirty_prev = pdirty; } do_arena_destroy(arena_ind); } TEST_END int main(void) { return test( test_decay_ticks, test_decay_ticker, test_decay_nonmonotonic, test_decay_now, test_decay_never); }
8,231
611
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #ifndef INCLUDED_OCIO_MTLTEXTURE_H #define INCLUDED_OCIO_MTLTEXTURE_H #include <vector> #include <OpenGL/gl.h> #import <AppKit/AppKit.h> #import <Metal/Metal.h> #import <CoreVideo/CVPixelBuffer.h> #import <CoreVideo/CVOpenGLTextureCache.h> #import <CoreVideo/CVMetalTextureCache.h> #include <OpenColorIO/OpenColorIO.h> namespace OCIO_NAMESPACE { typedef struct { int cvPixelFormat; MTLPixelFormat mtlFormat; GLuint glInternalFormat; GLuint glFormat; GLuint glType; } GLMetalTextureFormatInfo; class MtlTexture { public: MtlTexture() = delete; MtlTexture(const MtlTexture&) = delete; MtlTexture & operator=(const MtlTexture&) = delete; int getWidth() const { return m_width; } int getHeight() const { return m_height; } uint64_t getGLHandle() const { if(!m_openGLContext) { throw Exception("There is no valid OpenGL Context for this texture"); } return m_texID; } ~MtlTexture(); MtlTexture(id<MTLDevice> device, uint32_t width, uint32_t height, const float* image); MtlTexture(id<MTLDevice> device, NSOpenGLContext* glContext, uint32_t width, uint32_t height, const float* image); void update(const float* image); id<MTLTexture> getMetalTextureHandle() const { return m_metalTexture; } std::vector<float> readTexture() const; private: void createGLTexture(); void createMetalTexture(); id<MTLDevice> m_device; NSOpenGLContext* m_openGLContext; int m_width; int m_height; unsigned int m_texID; id<MTLTexture> m_metalTexture; const GLMetalTextureFormatInfo* m_formatInfo; CVPixelBufferRef m_CVPixelBuffer; CVMetalTextureRef m_CVMTLTexture; CVOpenGLTextureCacheRef m_CVGLTextureCache; CVOpenGLTextureRef m_CVGLTexture; CGLPixelFormatObj m_CGLPixelFormat; // Metal CVMetalTextureCacheRef m_CVMTLTextureCache; }; } // namespace OCIO_NAMESPACE #endif // INCLUDED_OCIO_MTLTEXTURE_H
1,143
678
<filename>iOSOpenDev/frameworks/StoreServices.framework/Headers/SSNetworkConstraints.h /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/StoreServices.framework/StoreServices */ #import <StoreServices/SSXPCCoding.h> #import <StoreServices/StoreServices-Structs.h> #import <StoreServices/SSCoding.h> #import <StoreServices/NSCopying.h> #import <StoreServices/XXUnknownSuperclass.h> @interface SSNetworkConstraints : XXUnknownSuperclass <SSCoding, SSXPCCoding, NSCopying> { @private dispatch_queue_s *_dispatchQueue; // 4 = 0x4 long long _sizeLimit2G; // 8 = 0x8 long long _sizeLimit3G; // 16 = 0x10 long long _sizeLimitWiFi; // 24 = 0x18 } @property(readonly, assign, getter=isAnyNetworkTypeEnabled) BOOL anyNetworkTypeEnabled; // G=0x21151; + (id)_newModernNetworkConstraintsWithArray:(id)array; // 0x223ed + (id)_newLegacyNetworkConstraintsWithDictionary:(id)dictionary; // 0x22325 + (void)_addNetworkConstraintsToDictionary:(id)dictionary forNetworkType:(int)networkType legacyDictionary:(id)dictionary3; // 0x22085 + (id)newNetworkConstraintsByDownloadKindFromURLBag:(id)urlbag; // 0x21d5d - (void)_setSizeLimit:(long long)limit forNetworkType:(int)networkType; // 0x22715 - (void)setSizeLimitsWithStoreConstraintDictionary:(id)storeConstraintDictionary; // 0x21e2d - (void *)copyXPCEncoding; // 0x21c6d - (id)copyPropertyListEncoding; // 0x21ad1 - (id)initWithXPCEncoding:(void *)xpcencoding; // 0x21a41 - (id)initWithPropertyListEncoding:(id)propertyListEncoding; // 0x21915 - (id)copyWithZone:(NSZone *)zone; // 0x217dd - (BOOL)isEqual:(id)equal; // 0x21729 - (id)description; // 0x214e1 - (long long)sizeLimitForNetworkType:(int)networkType; // 0x213bd - (void)setSizeLimit:(long long)limit forNetworkType:(int)networkType; // 0x21311 - (void)setAllNetworkTypesDisabled; // 0x2125d // declared property getter: - (BOOL)isAnyNetworkTypeEnabled; // 0x21151 - (void)dealloc; // 0x21111 - (id)init; // 0x210c1 @end
738
631
<filename>Source/OpenNI/XnXml.cpp /***************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "XnXml.h" #include <XnOpenNI.h> #include <XnLog.h> //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnStatus xnXmlLoadDocument(TiXmlDocument& doc, const XnChar* strFileName) { XnStatus nRetVal = XN_STATUS_OK; XnBool bExists = FALSE; nRetVal = xnOSDoesFileExist(strFileName, &bExists); XN_IS_STATUS_OK(nRetVal); if (!bExists) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FILE_NOT_FOUND, XN_MASK_OPEN_NI, "Failed loading '%s': File does not exist!", strFileName); } if (!doc.LoadFile(strFileName)) { XN_LOG_ERROR_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Failed loading '%s': %s [row %d, column %d]", strFileName, doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol()); } return (XN_STATUS_OK); } XnStatus xnXmlGetChildElement(const TiXmlElement* pElem, const XnChar* strName, const TiXmlElement** ppChild) { *ppChild = pElem->FirstChildElement(strName); if (*ppChild == NULL) { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - no '%s' child (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); } XnStatus xnXmlReadStringAttribute(const TiXmlElement* pElem, const XnChar* strName, const XnChar** pstrValue) { *pstrValue = pElem->Attribute(strName); if (*pstrValue == NULL) { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - no '%s' attribute (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); } XnStatus xnXmlReadBoolAttribute(const TiXmlElement* pElem, const XnChar* strName, XnBool* pbValue) { XnStatus nRetVal = XN_STATUS_OK; const XnChar* strValue; nRetVal = xnXmlReadStringAttribute(pElem, strName, &strValue); XN_IS_STATUS_OK(nRetVal); if (strcmp(strValue, "true") == 0) { *pbValue = TRUE; } else if (strcmp(strValue, "false") == 0) { *pbValue = FALSE; } else { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - '%s' attribute value should be 'true' or 'false' (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); } XnStatus xnXmlReadIntAttribute(const TiXmlElement* pElem, const XnChar* strName, XnInt* pnValue) { XnStatus nRetVal = XN_STATUS_OK; const XnChar* strValue; nRetVal = xnXmlReadStringAttribute(pElem, strName, &strValue); XN_IS_STATUS_OK(nRetVal); if (sscanf(strValue, "%d", pnValue) == 0) { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - '%s' attribute value should be a number (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); } XnStatus xnXmlReadUInt32Attribute(const TiXmlElement* pElem, const XnChar* strName, XnUInt32* pnValue) { XnStatus nRetVal = XN_STATUS_OK; const XnChar* strValue; nRetVal = xnXmlReadStringAttribute(pElem, strName, &strValue); XN_IS_STATUS_OK(nRetVal); if (sscanf(strValue, "%u", pnValue) == 0) { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - '%s' attribute value should be a positive number (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); } XnStatus xnXmlReadUInt16Attribute(const TiXmlElement* pElem, const XnChar* strName, XnUInt16* pnValue) { XnStatus nRetVal = XN_STATUS_OK; XnUInt32 nValue; nRetVal = xnXmlReadUInt32Attribute(pElem, strName, &nValue); XN_IS_STATUS_OK(nRetVal); if (nValue > XN_MAX_UINT16) { XN_LOG_WARNING_RETURN(XN_STATUS_BAD_PARAM, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - '%s' attribute value should be unsigned 16-bit number (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } *pnValue = (XnUInt16)nValue; return (XN_STATUS_OK); } XnStatus xnXmlReadUInt8Attribute(const TiXmlElement* pElem, const XnChar* strName, XnUInt8* pnValue) { XnStatus nRetVal = XN_STATUS_OK; XnUInt32 nValue; nRetVal = xnXmlReadUInt32Attribute(pElem, strName, &nValue); XN_IS_STATUS_OK(nRetVal); if (nValue > XN_MAX_UINT8) { XN_LOG_WARNING_RETURN(XN_STATUS_BAD_PARAM, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - '%s' attribute value should be unsigned 8-bit number (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } *pnValue = (XnUInt8)nValue; return (XN_STATUS_OK); } XnStatus xnXmlReadRealAttribute(const TiXmlElement* pElem, const XnChar* strName, XnDouble* pdValue) { XnStatus nRetVal = XN_STATUS_OK; const XnChar* strValue; nRetVal = xnXmlReadStringAttribute(pElem, strName, &strValue); XN_IS_STATUS_OK(nRetVal); if (sscanf(strValue, "%lf", pdValue) == 0) { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - '%s' attribute value should be a floating point (line %u, col %u)!", pElem->Value(), strName, pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); } XnStatus xnXmlReadTextAsInt(const TiXmlElement* pElem, XnInt* pnValue) { if (sscanf(pElem->GetText(), "%d", pnValue) == 0) { XN_LOG_WARNING_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Invalid '%s' xml entry - text should be a number (line %u, col %u)!", pElem->Value(), pElem->Row(), pElem->Column()); } return (XN_STATUS_OK); }
3,668
394
<reponame>solhuebner/ESP32-BLE-Gamepad #ifndef ESP32_BLE_GAMEPAD_H #define ESP32_BLE_GAMEPAD_H #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include "nimconfig.h" #if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL) #include "BleConnectionStatus.h" #include "NimBLEHIDDevice.h" #include "NimBLECharacteristic.h" #define CONTROLLER_TYPE_JOYSTICK 0x04 #define CONTROLLER_TYPE_GAMEPAD 0x05 #define CONTROLLER_TYPE_MULTI_AXIS 0x08 #define BUTTON_1 0x1 #define BUTTON_2 0x2 #define BUTTON_3 0x3 #define BUTTON_4 0x4 #define BUTTON_5 0x5 #define BUTTON_6 0x6 #define BUTTON_7 0x7 #define BUTTON_8 0x8 #define BUTTON_9 0x9 #define BUTTON_10 0xa #define BUTTON_11 0xb #define BUTTON_12 0xc #define BUTTON_13 0xd #define BUTTON_14 0xe #define BUTTON_15 0xf #define BUTTON_16 0x10 #define BUTTON_17 0x11 #define BUTTON_18 0x12 #define BUTTON_19 0x13 #define BUTTON_20 0x14 #define BUTTON_21 0x15 #define BUTTON_22 0x16 #define BUTTON_23 0x17 #define BUTTON_24 0x18 #define BUTTON_25 0x19 #define BUTTON_26 0x1a #define BUTTON_27 0x1b #define BUTTON_28 0x1c #define BUTTON_29 0x1d #define BUTTON_30 0x1e #define BUTTON_31 0x1f #define BUTTON_32 0x20 #define BUTTON_33 0x21 #define BUTTON_34 0x22 #define BUTTON_35 0x23 #define BUTTON_36 0x24 #define BUTTON_37 0x25 #define BUTTON_38 0x26 #define BUTTON_39 0x27 #define BUTTON_40 0x28 #define BUTTON_41 0x29 #define BUTTON_42 0x2a #define BUTTON_43 0x2b #define BUTTON_44 0x2c #define BUTTON_45 0x2d #define BUTTON_46 0x2e #define BUTTON_47 0x2f #define BUTTON_48 0x30 #define BUTTON_49 0x31 #define BUTTON_50 0x32 #define BUTTON_51 0x33 #define BUTTON_52 0x34 #define BUTTON_53 0x35 #define BUTTON_54 0x36 #define BUTTON_55 0x37 #define BUTTON_56 0x38 #define BUTTON_57 0x39 #define BUTTON_58 0x3a #define BUTTON_59 0x3b #define BUTTON_60 0x3c #define BUTTON_61 0x3d #define BUTTON_62 0x3e #define BUTTON_63 0x3f #define BUTTON_64 0x40 #define BUTTON_65 0x41 #define BUTTON_66 0x42 #define BUTTON_67 0x43 #define BUTTON_68 0x44 #define BUTTON_69 0x45 #define BUTTON_70 0x46 #define BUTTON_71 0x47 #define BUTTON_72 0x48 #define BUTTON_73 0x49 #define BUTTON_74 0x4a #define BUTTON_75 0x4b #define BUTTON_76 0x4c #define BUTTON_77 0x4d #define BUTTON_78 0x4e #define BUTTON_79 0x4f #define BUTTON_80 0x50 #define BUTTON_81 0x51 #define BUTTON_82 0x52 #define BUTTON_83 0x53 #define BUTTON_84 0x54 #define BUTTON_85 0x55 #define BUTTON_86 0x56 #define BUTTON_87 0x57 #define BUTTON_88 0x58 #define BUTTON_89 0x59 #define BUTTON_90 0x5a #define BUTTON_91 0x5b #define BUTTON_92 0x5c #define BUTTON_93 0x5d #define BUTTON_94 0x5e #define BUTTON_95 0x5f #define BUTTON_96 0x60 #define BUTTON_97 0x61 #define BUTTON_98 0x62 #define BUTTON_99 0x63 #define BUTTON_100 0x64 #define BUTTON_101 0x65 #define BUTTON_102 0x66 #define BUTTON_103 0x67 #define BUTTON_104 0x68 #define BUTTON_105 0x69 #define BUTTON_106 0x6a #define BUTTON_107 0x6b #define BUTTON_108 0x6c #define BUTTON_109 0x6d #define BUTTON_110 0x6e #define BUTTON_111 0x6f #define BUTTON_112 0x70 #define BUTTON_113 0x71 #define BUTTON_114 0x72 #define BUTTON_115 0x73 #define BUTTON_116 0x74 #define BUTTON_117 0x75 #define BUTTON_118 0x76 #define BUTTON_119 0x77 #define BUTTON_120 0x78 #define BUTTON_121 0x79 #define BUTTON_122 0x7a #define BUTTON_123 0x7b #define BUTTON_124 0x7c #define BUTTON_125 0x7d #define BUTTON_126 0x7e #define BUTTON_127 0x7f #define BUTTON_128 0x80 #define DPAD_CENTERED 0 #define DPAD_UP 1 #define DPAD_UP_RIGHT 2 #define DPAD_RIGHT 3 #define DPAD_DOWN_RIGHT 4 #define DPAD_DOWN 5 #define DPAD_DOWN_LEFT 6 #define DPAD_LEFT 7 #define DPAD_UP_LEFT 8 #define HAT_CENTERED 0 #define HAT_UP 1 #define HAT_UP_RIGHT 2 #define HAT_RIGHT 3 #define HAT_DOWN_RIGHT 4 #define HAT_DOWN 5 #define HAT_DOWN_LEFT 6 #define HAT_LEFT 7 #define HAT_UP_LEFT 8 class BleGamepad { private: uint8_t _controllerType; uint8_t _buttons[16]; //8 bytes x 16 --> 128 bytes int16_t _x; int16_t _y; int16_t _z; int16_t _rZ; int16_t _rX; int16_t _rY; int16_t _slider1; int16_t _slider2; int16_t _rudder; int16_t _throttle; int16_t _accelerator; int16_t _brake; int16_t _steering; int16_t _hat1; int16_t _hat2; int16_t _hat3; int16_t _hat4; bool _autoReport; uint16_t _buttonCount; uint8_t _hatSwitchCount; bool _includeXAxis; bool _includeYAxis; bool _includeZAxis; bool _includeRxAxis; bool _includeRyAxis; bool _includeRzAxis; bool _includeSlider1; bool _includeSlider2; bool _includeRudder; bool _includeThrottle; bool _includeAccelerator; bool _includeBrake; bool _includeSteering; BleConnectionStatus* connectionStatus; NimBLEHIDDevice* hid; NimBLECharacteristic* inputGamepad; void rawAction(uint8_t msg[], char msgSize); static void taskServer(void* pvParameter); public: BleGamepad(std::string deviceName = "ESP32 BLE Gamepad", std::string deviceManufacturer = "Espressif", uint8_t batteryLevel = 100); void begin(uint16_t buttonCount = 16, uint8_t hatSwitchCount = 1, bool includeXAxis = true, bool includeYAxis = true, bool includeZAxis = true, bool includeRzAxis = true, bool includeRxAxis = true, bool includeRyAxis = true, bool includeSlider1 = true, bool includeSlider2 = true, bool includeRudder = false, bool includeThrottle = false, bool includeAccelerator = false, bool includeBrake = false, bool includeSteering = false); void end(void); void setControllerType(uint8_t controllerType = CONTROLLER_TYPE_GAMEPAD); void setAxes(int16_t x = 0, int16_t y = 0, int16_t z = 0, int16_t rZ = 0, int16_t rX = 0, int16_t rY = 0, int16_t slider1 = 0, int16_t slider2 = 0, signed char hat1 = 0, signed char hat2 = 0, signed char hat3 = 0, signed char hat4 = 0); void press(uint8_t b = BUTTON_1); // press BUTTON_1 by default void release(uint8_t b = BUTTON_1); // release BUTTON_1 by default void setLeftThumb(int16_t x = 0, int16_t y = 0); void setRightThumb(int16_t z = 0, int16_t rZ = 0); void setLeftTrigger(int16_t rX = 0); void setRightTrigger(int16_t rY = 0); void setTriggers(int16_t rX = 0, int16_t rY = 0); void setHats(signed char hat1 = 0, signed char hat2 = 0, signed char hat3 = 0, signed char hat4 = 0); void setHat(signed char hat = 0); void setHat1(signed char hat1 = 0); void setHat2(signed char hat2 = 0); void setHat3(signed char hat3 = 0); void setHat4(signed char hat4 = 0); void setX(int16_t x = 0); void setY(int16_t y = 0); void setZ(int16_t z = 0); void setRZ(int16_t rZ = 0); void setRX(int16_t rX = 0); void setRY(int16_t rY = 0); void setSliders(int16_t slider1 = 0, int16_t slider2 = 0); void setSlider(int16_t slider = 0); void setSlider1(int16_t slider1 = 0); void setSlider2(int16_t slider2 = 0); void setRudder(int16_t rudder = 0); void setThrottle(int16_t throttle = 0); void setAccelerator(int16_t accelerator = 0); void setBrake(int16_t brake = 0); void setSteering(int16_t steering = 0); void setSimulationControls(int16_t rudder = 0, int16_t throttle = 0, int16_t accelerator = 0, int16_t brake = 0, int16_t steering = 0); void setAutoReport(bool autoReport = true); void sendReport(); bool isPressed(uint8_t b = BUTTON_1); // check BUTTON_1 by default bool isConnected(void); void resetButtons(); void setBatteryLevel(uint8_t level); uint8_t batteryLevel; std::string deviceManufacturer; std::string deviceName; protected: virtual void onStarted(NimBLEServer *pServer) { }; }; #endif // CONFIG_BT_NIMBLE_ROLE_PERIPHERAL #endif // CONFIG_BT_ENABLED #endif // ESP32_BLE_GAMEPAD_H
3,586
469
<filename>uats/src/main/java/org/mini2Dx/uats/TilingDrawableUAT.java<gh_stars>100-1000 package org.mini2Dx.uats; import org.mini2Dx.core.Graphics; import org.mini2Dx.core.Mdx; import org.mini2Dx.core.files.FileHandleResolver; import org.mini2Dx.core.game.GameContainer; import org.mini2Dx.core.graphics.TilingDrawable; import org.mini2Dx.core.screen.BasicGameScreen; import org.mini2Dx.core.screen.GameScreen; import org.mini2Dx.core.screen.ScreenManager; import org.mini2Dx.core.screen.transition.FadeInTransition; import org.mini2Dx.core.screen.transition.FadeOutTransition; import org.mini2Dx.uats.util.ScreenIds; import org.mini2Dx.uats.util.UATSelectionScreen; public class TilingDrawableUAT extends BasicGameScreen { private static final String TILING_DRAWABLE = "tank"; private final FileHandleResolver fileHandleResolver; private TilingDrawable tilingDrawable; private int side = 100; private int sign = 1; public TilingDrawableUAT(FileHandleResolver fileHandleResolver) { this.fileHandleResolver = fileHandleResolver; } @Override public void initialise(GameContainer gc) { tilingDrawable = Mdx.graphics.newTilingDrawable(Mdx.graphics.newTextureRegion(Mdx.graphics.newTexture(fileHandleResolver.resolve(TILING_DRAWABLE + ".png")))); } @Override public void update(GameContainer gc, ScreenManager<? extends GameScreen> screenManager, float delta) { if (Mdx.input.justTouched()) { screenManager.enterGameScreen(UATSelectionScreen.SCREEN_ID, new FadeOutTransition(), new FadeInTransition()); } side += sign; if (side == 100 || side == 250){ sign = -sign; } } @Override public void render(GameContainer gc, Graphics g) { tilingDrawable.draw(g, 50, 50, side, side); g.drawRect(50, 50, side, side); } @Override public int getId() { return ScreenIds.getScreenId(TilingDrawableUAT.class); } }
794
1,311
<filename>Jolt/Physics/Collision/Shape/ScaleHelpers.h // SPDX-FileCopyrightText: 2021 <NAME> // SPDX-License-Identifier: MIT #pragma once #include <Physics/PhysicsSettings.h> namespace JPH { /// Helper functions to get properties of a scaling vector namespace ScaleHelpers { /// The tolerance used to check if components of the scale vector are the same static constexpr float cScaleToleranceSq = 1.0e-8f; /// Test if a scale is identity inline bool IsNotScaled(Vec3Arg inScale) { return inScale.IsClose(Vec3::sReplicate(1.0f), cScaleToleranceSq); } /// Test if a scale is uniform inline bool IsUniformScale(Vec3Arg inScale) { return inScale.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>().IsClose(inScale, cScaleToleranceSq); } /// Scale the convex radius of an object inline float ScaleConvexRadius(float inConvexRadius, Vec3Arg inScale) { return min(inConvexRadius * inScale.Abs().ReduceMin(), cDefaultConvexRadius); } /// Test if a scale flips an object inside out (which requires flipping all normals and polygon windings) inline bool IsInsideOut(Vec3Arg inScale) { return (CountBits(Vec3::sLess(inScale, Vec3::sZero()).GetTrues() & 0x7) & 1) != 0; } /// Get the average scale if inScale, used to make the scale uniform when a shape doesn't support non-uniform scale inline Vec3 MakeUniformScale(Vec3Arg inScale) { return Vec3::sReplicate((inScale.GetX() + inScale.GetY() + inScale.GetZ()) / 3.0f); } /// Checks in scale can be rotated to child shape /// @param inRotation Rotation of child shape /// @param inScale Scale in local space of parent shape /// @return True if the scale is valid (no shearing introduced) inline bool CanScaleBeRotated(QuatArg inRotation, Vec3Arg inScale) { // inScale is a scale in local space of the shape, so the transform for the shape (ignoring translation) is: T = Mat44::sScale(inScale) * mRotation. // when we pass the scale to the child it needs to be local to the child, so we want T = mRotation * Mat44::sScale(ChildScale). // Solving for ChildScale: ChildScale = mRotation^-1 * Mat44::sScale(inScale) * mRotation = mRotation^T * Mat44::sScale(inScale) * mRotation // If any of the off diagonal elements are non-zero, it means the scale / rotation is not compatible. Mat44 r = Mat44::sRotation(inRotation); Mat44 child_scale = r.Multiply3x3LeftTransposed(r.PostScaled(inScale)); // Get the columns, but zero the diagonal Vec4 zero = Vec4::sZero(); Vec4 c0 = Vec4::sSelect(child_scale.GetColumn4(0), zero, UVec4(0xffffffff, 0, 0, 0)).Abs(); Vec4 c1 = Vec4::sSelect(child_scale.GetColumn4(1), zero, UVec4(0, 0xffffffff, 0, 0)).Abs(); Vec4 c2 = Vec4::sSelect(child_scale.GetColumn4(2), zero, UVec4(0, 0, 0xffffffff, 0)).Abs(); // Check if all elements are less than epsilon Vec4 epsilon = Vec4::sReplicate(1.0e-6f); return UVec4::sAnd(UVec4::sAnd(Vec4::sLess(c0, epsilon), Vec4::sLess(c1, epsilon)), Vec4::sLess(c2, epsilon)).TestAllTrue(); } /// Adjust scale for rotated child shape /// @param inRotation Rotation of child shape /// @param inScale Scale in local space of parent shape /// @return Rotated scale inline Vec3 RotateScale(QuatArg inRotation, Vec3Arg inScale) { // Get the diagonal of mRotation^T * Mat44::sScale(inScale) * mRotation (see comment at CanScaleBeRotated) Mat44 r = Mat44::sRotation(inRotation); return r.Multiply3x3LeftTransposed(r.PostScaled(inScale)).GetDiagonal3(); } } } // JPH
1,265
852
<filename>RecoEcal/EgammaCoreTools/interface/SCDynamicDPhiParametersHelper.h #ifndef RecoEcal_EgammaCoreTools_SCDynamicDPhiParametersHelper_h #define RecoEcal_EgammaCoreTools_SCDynamicDPhiParametersHelper_h #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/EcalObjects/interface/EcalSCDynamicDPhiParameters.h" namespace reco { class SCDynamicDPhiParametersHelper { public: SCDynamicDPhiParametersHelper(EcalSCDynamicDPhiParameters &params, const edm::ParameterSet &iConfig); ~SCDynamicDPhiParametersHelper() = default; void addDynamicDPhiParameters(const EcalSCDynamicDPhiParameters::DynamicDPhiParameters &dynDPhiParams); void sortDynamicDPhiParametersCollection(); private: EcalSCDynamicDPhiParameters &parameters_; }; } // namespace reco #endif
274
631
<gh_stars>100-1000 /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.metron.profiler.spark.function; import org.apache.metron.stellar.dsl.Context; import org.apache.metron.stellar.dsl.StellarFunctions; import java.io.Serializable; import java.util.Map; public class TaskUtils implements Serializable { /** * Create the execution context for running Stellar. */ public static Context getContext(Map<String, String> globals) { Context context = new Context.Builder() .with(Context.Capabilities.GLOBAL_CONFIG, () -> globals) .with(Context.Capabilities.STELLAR_CONFIG, () -> globals) .build(); StellarFunctions.initialize(context); return context; } }
457
11,356
// Boost.Geometry (aka GGL, Generic Geometry Library) // This file is manually converted from PROJ4 // Copyright (c) 2008-2012 <NAME>, Amsterdam, the Netherlands. // This file was modified by Oracle on 2017, 2018. // Modifications copyright (c) 2017-2018, Oracle and/or its affiliates. // Contributed and/or modified by <NAME>, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is converted from PROJ4, http://trac.osgeo.org/proj // PROJ4 is originally written by <NAME> (then of the USGS) // PROJ4 is maintained by <NAME> // PROJ4 is converted to Geometry Library by <NAME> (Geodan, Amsterdam) // Original copyright notice: // 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. #ifndef BOOST_GEOMETRY_PROJECTIONS_PJ_PARAM_HPP #define BOOST_GEOMETRY_PROJECTIONS_PJ_PARAM_HPP #include <string> #include <vector> #include <boost/geometry/srs/projections/exception.hpp> #include <boost/geometry/srs/projections/impl/dms_parser.hpp> #include <boost/geometry/srs/projections/impl/projects.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits/is_integral.hpp> namespace boost { namespace geometry { namespace projections { namespace detail { /* create pvalue list entry */ template <typename T> inline pvalue<T> pj_mkparam(std::string const& name, std::string const& value) { pvalue<T> newitem; newitem.param = name; newitem.s = value; //newitem.used = false; return newitem; } /* create pvalue list entry */ template <typename T> inline pvalue<T> pj_mkparam(std::string const& str) { std::string name = str; std::string value; boost::trim_left_if(name, boost::is_any_of("+")); std::string::size_type loc = name.find("="); if (loc != std::string::npos) { value = name.substr(loc + 1); name.erase(loc); } return pj_mkparam<T>(name, value); } /* input exists */ template <typename T> inline typename std::vector<pvalue<T> >::const_iterator pj_param_find(std::vector<pvalue<T> > const& pl, std::string const& name) { typedef typename std::vector<pvalue<T> >::const_iterator iterator; for (iterator it = pl.begin(); it != pl.end(); it++) { if (it->param == name) { //it->used = true; return it; } // TODO: needed for pipeline /*else if (it->param == "step") { return pl.end(); }*/ } return pl.end(); } /* input exists */ template <typename T> inline bool pj_param_exists(std::vector<pvalue<T> > const& pl, std::string const& name) { return pj_param_find(pl, name) != pl.end(); } /* integer input */ template <typename T> inline bool pj_param_i(std::vector<pvalue<T> > const& pl, std::string const& name, int & par) { typename std::vector<pvalue<T> >::const_iterator it = pj_param_find(pl, name); if (it != pl.end()) { par = geometry::str_cast<int>(it->s); return true; } return false; } /* floating point input */ template <typename T> inline bool pj_param_f(std::vector<pvalue<T> > const& pl, std::string const& name, T & par) { typename std::vector<pvalue<T> >::const_iterator it = pj_param_find(pl, name); if (it != pl.end()) { par = geometry::str_cast<T>(it->s); return true; } return false; } /* radians input */ template <typename T> inline bool pj_param_r(std::vector<pvalue<T> > const& pl, std::string const& name, T & par) { typename std::vector<pvalue<T> >::const_iterator it = pj_param_find(pl, name); if (it != pl.end()) { dms_parser<T, true> parser; par = parser.apply(it->s.c_str()).angle(); return true; } return false; } /* string input */ template <typename T> inline bool pj_param_s(std::vector<pvalue<T> > const& pl, std::string const& name, std::string & par) { typename std::vector<pvalue<T> >::const_iterator it = pj_param_find(pl, name); if (it != pl.end()) { par = it->s; return true; } return false; } /* bool input */ template <typename T> inline bool pj_get_param_b(std::vector<pvalue<T> > const& pl, std::string const& name) { typename std::vector<pvalue<T> >::const_iterator it = pj_param_find(pl, name); if (it != pl.end()) { switch (it->s[0]) { case '\0': case 'T': case 't': return true; case 'F': case 'f': return false; default: BOOST_THROW_EXCEPTION( projection_exception(error_invalid_boolean_param) ); return false; } } return false; } // NOTE: In the original code, in pl_ell_set.c there is a function pj_get_param // which behavior is similar to pj_param but it doesn't set `user` member to TRUE // while pj_param does in the original code. In Boost.Geometry this member is not used. template <typename T> inline int pj_get_param_i(std::vector<pvalue<T> > const& pl, std::string const& name) { int res = 0; pj_param_i(pl, name, res); return res; } template <typename T> inline T pj_get_param_f(std::vector<pvalue<T> > const& pl, std::string const& name) { T res = 0; pj_param_f(pl, name, res); return res; } template <typename T> inline T pj_get_param_r(std::vector<pvalue<T> > const& pl, std::string const& name) { T res = 0; pj_param_r(pl, name, res); return res; } template <typename T> inline std::string pj_get_param_s(std::vector<pvalue<T> > const& pl, std::string const& name) { std::string res; pj_param_s(pl, name, res); return res; } } // namespace detail }}} // namespace boost::geometry::projections #endif
2,616
2,288
<reponame>michaelfolkson/lnhw<filename>clightning/ccan/ccan/tal/benchmark/speed.c /* Taken from samba/lib/talloc/testsuite.c: Unix SMB/CIFS implementation. local testing of talloc routines. Copyright (C) <NAME> 2004 ** NOTE! The following LGPL license applies to the talloc ** library. This does NOT imply that all of Samba is released ** under the LGPL 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; either version 3 of the License, or (at your option) any later version. This library 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 for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #include <ccan/talloc/talloc.h> #include <ccan/tal/tal.h> #include <ccan/tal/str/str.h> #include <ccan/time/time.h> #include <ccan/err/err.h> #include <string.h> #define LOOPS 1024 int main(int argc, char *argv[]) { void *ctx; unsigned count; int i, j; struct timeabs tv; void *p1, *p2[100], *p3[100]; bool run_talloc = true, run_tal = true, run_malloc = true; if (argv[1]) { if (strcmp(argv[1], "--talloc") == 0) run_tal = run_malloc = false; else if (strcmp(argv[1], "--tal") == 0) run_talloc = run_malloc = false; else if (strcmp(argv[1], "--malloc") == 0) run_talloc = run_tal = false; else errx(1, "Bad flag %s", argv[1]); } if (!run_talloc) goto after_talloc; ctx = talloc_new(NULL); tv = time_now(); count = 0; do { for (i=0;i<LOOPS;i++) { p1 = talloc_size(ctx, LOOPS % 128); for (j = 0; j < 100; j++) { p2[j] = talloc_strdup(p1, "foo bar"); p3[j] = talloc_size(p1, 300); } talloc_free(p1); } count += (1 + 200) * LOOPS; } while (time_between(time_now(), tv).ts.tv_sec < 5); fprintf(stderr, "talloc: %.0f ops/sec\n", count/5.0); talloc_free(ctx); after_talloc: if (!run_tal) goto after_tal; ctx = tal(NULL, char); tv = time_now(); count = 0; do { for (i=0;i<LOOPS;i++) { p1 = tal_arr(ctx, char, LOOPS % 128); for (j = 0; j < 100; j++) { p2[j] = tal_strdup(p1, "foo bar"); p3[j] = tal_arr(p1, char, 300); } tal_free(p1); } count += (1 + 200) * LOOPS; } while (time_between(time_now(), tv).ts.tv_sec < 5); fprintf(stderr, "tal: %.0f ops/sec\n", count/5.0); tal_free(ctx); after_tal: if (!run_malloc) goto after_malloc; tv = time_now(); count = 0; do { for (i=0;i<LOOPS;i++) { p1 = malloc(LOOPS % 128); for (j = 0; j < 100; j++) { p2[j] = strdup("foo bar"); p3[j] = malloc(300); } for (j = 0; j < 100; j++) { free(p2[j]); free(p3[j]); } free(p1); } count += (1 + 200) * LOOPS; } while (time_between(time_now(), tv).ts.tv_sec < 5); fprintf(stderr, "malloc: %.0f ops/sec\n", count/5.0); after_malloc: printf("success: speed\n"); return 0; }
1,392
378
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomee.catalina.cluster; import org.apache.catalina.ha.CatalinaCluster; import org.apache.catalina.ha.ClusterMessage; import org.apache.openejb.assembler.classic.AppInfo; import org.apache.openejb.assembler.classic.event.AssemblerAfterApplicationCreated; import org.apache.openejb.assembler.classic.event.AssemblerBeforeApplicationDestroyed; import org.apache.openejb.loader.SystemInstance; import org.apache.openejb.observer.Observes; import org.apache.openejb.observer.event.AfterEvent; import java.io.File; import java.util.Set; public class ClusterObserver { private static final boolean ClUSTER_DEPLOYMENT = "true".equals(SystemInstance.get().getProperty("tomee.cluster.deployment", "false")); private final Set<CatalinaCluster> clusters; public ClusterObserver(final Set<CatalinaCluster> clusters) { this.clusters = clusters; } public void deploy(@Observes final AfterEvent<AssemblerAfterApplicationCreated> app) { if (!ClUSTER_DEPLOYMENT) { return; } final AppInfo appInfo = app.getEvent().getApp(); send(new DeployMessage(appInfo.path), appInfo); } public void undeploy(@Observes final AssemblerBeforeApplicationDestroyed app) { if (!ClUSTER_DEPLOYMENT) { return; } final AppInfo appInfo = app.getApp(); send(new UndeployMessage(appInfo.path), appInfo); } private void send(final ClusterMessage message, final AppInfo app) { for (final CatalinaCluster cluster : clusters) { final String path = app.path; if (new File(path).exists() && !app.autoDeploy) { cluster.send(message); } } } }
862
418
#include <vector> #include "caffe/my_layers/skelvector_loss_layer.hpp" #include "caffe/util/math_functions.hpp" using namespace std; namespace caffe { template <typename Dtype> void SkelVectorLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; diff_.ReshapeLike(*bottom[0]); bone_1.ReshapeLike(*bottom[0]); bone_2.ReshapeLike(*bottom[0]); } template<typename Dtype> void SkelVectorLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype> ::LayerSetUp(bottom,top); CHECK(this->layer_param_.has_skel_vector_param()); this->dim = this->layer_param_.skel_vector_param().dim(); } template <typename Dtype> void SkelVectorLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int count = bottom[0]->count(); const int num = bottom[0] -> num(); const int num_skel = bottom[0] -> channels() / this->dim; // for 3d pose // int parent_node[] = {0, 0,1,2, 0,4,5, 0,7,8,9, 8,11,12, 8,14,15 }; int parent_node[] = {0, 0,1,2, 0,4,5, 0,7,8, 8,10,11, 8,13,14}; const Dtype *blob_data1 = bottom[0] -> cpu_data(); const Dtype *blob_data2 = bottom[1] -> cpu_data(); Dtype *bone_data1 = bone_1.mutable_cpu_data(); Dtype *bone_data2 = bone_2.mutable_cpu_data(); for(int n = 0; n < num; ++n) { // except the root node for(int c = 0; c < num_skel; ++c){ for (int d = 0; d < this->dim; ++d) { bone_data1[bottom[0]->offset(n,this->dim*c+d)] = blob_data1[bottom[0]->offset(n,this->dim*parent_node[c]+d)] - blob_data1[bottom[0]->offset(n,this->dim*c+d)]; bone_data2[bottom[1]->offset(n,this->dim*c+d)] = blob_data2[bottom[1]->offset(n,this->dim*parent_node[c]+d)] - blob_data2[bottom[1]->offset(n,this->dim*c+d)]; } // bone_data1[bottom[0]->offset(n,3*c)] = blob_data1[bottom[0]->offset(n,3*parent_node[c])] - blob_data1[bottom[0]->offset(n,3*c)]; // bone_data1[bottom[0]->offset(n,3*c+1)] = blob_data1[bottom[0]->offset(n,3*parent_node[c]+1)] - blob_data1[bottom[0]->offset(n,3*c)+1]; // bone_data1[bottom[0]->offset(n,3*c+2)] = blob_data1[bottom[0]->offset(n,3*parent_node[c])+2] - blob_data1[bottom[0]->offset(n,3*c)+2]; // bone_data2[bottom[1]->offset(n,3*c)] = blob_data2[bottom[1]->offset(n,3*parent_node[c])] - blob_data2[bottom[1]->offset(n,3*c)]; // bone_data2[bottom[1]->offset(n,3*c+1)] = blob_data2[bottom[1]->offset(n,3*parent_node[c]+1)] - blob_data2[bottom[1]->offset(n,3*c)+1]; // bone_data2[bottom[1]->offset(n,3*c+2)] = blob_data2[bottom[1]->offset(n,3*parent_node[c])+2] - blob_data2[bottom[1]->offset(n,3*c)+2]; } } caffe_sub( count, bone_1.cpu_data(), bone_2.cpu_data(), diff_.mutable_cpu_data()); Dtype dot = caffe_cpu_dot(count, diff_.cpu_data(), diff_.cpu_data()); Dtype loss = dot / bottom[0]->num() / Dtype(2); top[0]->mutable_cpu_data()[0] = loss; } template <typename Dtype> void SkelVectorLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { for (int i = 0; i < 2; ++i) { if (propagate_down[i]) { const Dtype sign = (i == 0) ? -1 : 1; const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num(); caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } } } #ifdef CPU_ONLY STUB_GPU(SkelVectorLossLayer); #endif INSTANTIATE_CLASS(SkelVectorLossLayer); REGISTER_LAYER_CLASS(SkelVectorLoss); } // namespace caffe
1,852
485
/************************************************************ cvslice.h - $Author: lsxi $ Copyright (C) 2005-2006 <NAME> ************************************************************/ #ifndef RUBY_OPENCV_CVSLICE_H #define RUBY_OPENCV_CVSLICE_H #include "opencv.h" #define __NAMESPACE_BEGIN_CVSLICE namespace cCvSlice { #define __NAMESPACE_END_CVSLICE } __NAMESPACE_BEGIN_OPENCV __NAMESPACE_BEGIN_CVSLICE VALUE rb_class(); void init_ruby_class(); VALUE rb_allocate(VALUE klass); VALUE rb_initialize(VALUE self, VALUE start, VALUE end); VALUE rb_start_index_aref(VALUE self); VALUE rb_end_index_aref(VALUE self); VALUE rb_start_index_aset(VALUE self, VALUE index); VALUE rb_end_index_aset(VALUE self, VALUE index); __NAMESPACE_END_CVSLICE inline CvSlice* CVSLICE(VALUE object) { CvSlice *ptr; Data_Get_Struct(object, CvSlice, ptr); return ptr; } inline CvSlice VALUE_TO_CVSLICE(VALUE object) { if (rb_obj_is_kind_of(object, cCvSlice::rb_class())) { CvSlice* ptr = CVSLICE(object); return *ptr; } else if (rb_obj_is_kind_of(object, rb_cRange)) { return cvSlice(NUM2INT(rb_funcall(object, rb_intern("begin"), 0)), rb_funcall(object, rb_intern("exclude_end?"), 0) ? NUM2INT(rb_funcall(object, rb_intern("end"), 0)) : NUM2INT(rb_funcall(object, rb_intern("end"), 0)) - 1); } else { raise_compatible_typeerror(object, cCvSlice::rb_class()); } throw "Should never reach here"; } __NAMESPACE_END_OPENCV #endif // RUBY_OPENCV_CVSLICE_H
623
922
//tag::include[] package org.hibernate.validator.referenceguide.chapter12.getterselectionstrategy; //end::include[] import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotEmpty; //tag::include[] public class User { private String firstName; private String lastName; private String email; // [...] //end::include[] public User(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } //tag::include[] @NotEmpty public String firstName() { return firstName; } @NotEmpty public String lastName() { return lastName; } @Email public String email() { return email; } } //end::include[]
243
1,031
<reponame>kyletanyag/LL-Smartcard import template_partial_specialization_typedef.*; public class template_partial_specialization_typedef_runme { static { try { System.loadLibrary("template_partial_specialization_typedef"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); System.exit(1); } } public static void main(String argv[]) { // One parameter tests new A().a(); new B().b(); new C().c(); new D().d(); new E().e(); new F().f(); new G().g(); new H().h(); new J().j(); new K().k(); new M().m(); new N().n(); new BB().b(); new BBB().b(); new BBBB().b(); new BBBBB().b(); new B1().b(); new B2().b(); new B3().b(); new B4().b(); // Two parameter tests new A_().a(); new B_().b(); new C_().c(); new D_().d(); new E_().e(); new F_().f(); new G_().g(); new C1_().c(); new C2_().c(); new C3_().c(); new C4_().c(); new B1_().b(); new E1_().e(); new E2_().e(); } }
522
384
from django.contrib.contenttypes.models import ContentType import graphene_django_optimizer as gql_optimizer class ContentTypeType(gql_optimizer.OptimizedDjangoObjectType): """ Graphene-Django object type for ContentType records. Needed because ContentType is a built-in model, not one that we own and can auto-generate types for. """ class Meta: model = ContentType
130
5,156
<reponame>jalapenopuzzle/rr from util import * send_gdb('b constructor') expect_gdb('Make breakpoint pending on future shared library load?') send_gdb('y') expect_gdb('Breakpoint 1') send_gdb('c') expect_gdb('Breakpoint 1') ok()
91
1,872
<reponame>mingwayzhang/tvm """NNVM compiler toolchain. User only need to use :any:`build` and :any:`build_config` to do the compilation, and :any:`save_param_dict` to save the parameters into bytes. The other APIs are for more advanced interaction with the compiler toolchain. """ from __future__ import absolute_import import tvm from . import build_module from . build_module import build, optimize, build_config from . compile_engine import engine, graph_key from . param_dict import save_param_dict, load_param_dict from .. import symbol as _symbol from .. import graph as _graph from .. import top as _top tvm.register_extension(_symbol.Symbol, _symbol.Symbol) tvm.register_extension(_graph.Graph, _graph.Graph)
218
619
/* * Author: <NAME> <<EMAIL>> * Copyright (c) 2016 Intel Corporation * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #pragma once #include <stdint.h> #include "upm.h" #include "mraa/gpio.h" #include "mraa/spi.h" #ifdef __cplusplus extern "C" { #endif /** * @file apa102.h * @library apa102 * @brief C API for controlling APA102/DotStar RGB LED Strips * * @include apa102.c */ /** * Device context */ typedef struct _apa102_context { mraa_spi_context spi; // optional chip select mraa_gpio_context cs; uint8_t* buffer; int leds; int framelength; } *apa102_context; /** * Instantiates a new APA102 LED Strip * * @param ledcount Number of LEDs on the strip * @param bus SPI bus to use * @param cs Pin to use for chip select. -1 if not used. * @return an initialized apa102 context on success, NULL on error. */ apa102_context apa102_init(int ledcount, int bus, int cs); /** * APA102 close function * * @param dev The apa102_context to close */ void apa102_close(apa102_context dev); /** * Sets the color and brightness for one LED in the buffer * * @param dev The apa102_context to use * @param index Index of the LED (0 based) * @param brightness Brightness value (0-31) * @param r Red component (0-255) * @param g Green component (0-255) * @param b Blue component (0-255) * @return upm_result_t UPM success/error code */ upm_result_t apa102_set_led(apa102_context dev, uint16_t index, uint8_t brightness, uint8_t r, uint8_t g, uint8_t b); /** * Sets the brightness for one LED in the buffer * * @param dev The apa102_context to use * @param index Index of the LED (0 based) * @param brightness Brightness value (0-31) * @return upm_result_t UPM success/error code */ upm_result_t apa102_set_led_brightness(apa102_context dev, uint16_t index, uint8_t brightness); /** * Sets the color and brightness for multiple LEDs in the buffer * * @param dev The apa102_context to use * @param s_index The start Index of the LED range (0 based) * @param e_index The end Index of the LED range (0 based) * @param brightness Brightness value (0-31) * @param r Red component (0-255) * @param g Green component (0-255) * @param b Blue component (0-255) * @return upm_result_t UPM success/error code */ upm_result_t apa102_set_leds(apa102_context dev, uint16_t s_index, uint16_t e_index, uint8_t brightness, uint8_t r, uint8_t g, uint8_t b); /** * Sets the brightness for multiple LEDs in the buffer * * @param dev The apa102_context to use * @param s_index The start Index of the LED range (0 based) * @param e_index The end Index of the LED range (0 based) * @param brightness Brightness value (0-31) * @return upm_result_t UPM success/error code */ upm_result_t apa102_set_leds_brightness(apa102_context dev, uint16_t s_index, uint16_t e_index, uint8_t brightness); /** * Writes the buffer to the SPI bus thus updating the LED Strip * * @param dev The apa102_context to use * @return upm_result_t UPM success/error code */ upm_result_t apa102_refresh(apa102_context dev); #ifdef __cplusplus } #endif
1,335
1,305
/* * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.corba.se.spi.legacy.connection; import java.util.Collection; import com.sun.corba.se.spi.legacy.connection.LegacyServerSocketEndPointInfo; import com.sun.corba.se.spi.transport.SocketOrChannelAcceptor; /** * @author <NAME> */ public interface LegacyServerSocketManager { public int legacyGetTransientServerPort(String type); public int legacyGetPersistentServerPort(String socketType); public int legacyGetTransientOrPersistentServerPort(String socketType); public LegacyServerSocketEndPointInfo legacyGetEndpoint(String name); public boolean legacyIsLocalServerPort(int port); } // End of file.
285
2,338
//===- IPO/OpenMPOpt.h - Collection of OpenMP optimizations -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_TRANSFORMS_IPO_OPENMPOPT_H #define LLVM_TRANSFORMS_IPO_OPENMPOPT_H #include "llvm/Analysis/CGSCCPassManager.h" #include "llvm/Analysis/LazyCallGraph.h" #include "llvm/IR/PassManager.h" namespace llvm { namespace omp { /// Summary of a kernel (=entry point for target offloading). using Kernel = Function *; /// Set of kernels in the module using KernelSet = SmallPtrSet<Kernel, 4>; /// Helper to determine if \p M contains OpenMP. bool containsOpenMP(Module &M); /// Helper to determine if \p M is a OpenMP target offloading device module. bool isOpenMPDevice(Module &M); /// Get OpenMP device kernels in \p M. KernelSet getDeviceKernels(Module &M); } // namespace omp /// OpenMP optimizations pass. class OpenMPOptPass : public PassInfoMixin<OpenMPOptPass> { public: PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM); }; class OpenMPOptCGSCCPass : public PassInfoMixin<OpenMPOptCGSCCPass> { public: PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR); }; } // end namespace llvm #endif // LLVM_TRANSFORMS_IPO_OPENMPOPT_H
523
348
<filename>docs/data/leg-t2/059/05910508.json {"nom":"Roncq","circ":"10ème circonscription","dpt":"Nord","inscrits":10891,"abs":6291,"votants":4600,"blancs":210,"nuls":123,"exp":4267,"res":[{"nuance":"LR","nom":"<NAME>","voix":2553},{"nuance":"REM","nom":"<NAME>","voix":1714}]}
115
310
<reponame>dreeves/usesthis { "name": "Enlightenment", "description": "A window manager for X.", "url": "https://www.enlightenment.org/" }
54
2,443
<gh_stars>1000+ // Copyright (c) 2015-2019 The HomeKit ADK Contributors // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors. #include <errno.h> #include <stdio.h> #include <string.h> #include <time.h> #ifdef _WIN32 #include <Windows.h> #else #include <sys/time.h> #endif #include "HAP.h" #include "HAPPlatformLog+Init.h" #ifdef __linux__ #if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200112L #error "This file needs the XSI-compliant version of 'strerror_r'. Set _POSIX_C_SOURCE >= 200112L." #endif #if defined(_GNU_SOURCE) && _GNU_SOURCE #error "This file needs the XSI-compliant version of 'strerror_r'. Do not set _GNU_SOURCE." #endif #endif static const HAPLogObject logObject = { .subsystem = kHAPPlatform_LogSubsystem, .category = "Log" }; void HAPPlatformLogPOSIXError( HAPLogType type, const char* _Nonnull message, int errorNumber, const char* _Nonnull function, const char* _Nonnull file, int line) { HAPPrecondition(message); HAPPrecondition(function); HAPPrecondition(file); HAPError err; // Get error message. char errorString[256]; int e = strerror_r(errorNumber, errorString, sizeof errorString); if (e == EINVAL) { err = HAPStringWithFormat(errorString, sizeof errorString, "Unknown error %d", errorNumber); HAPAssert(!err); } else if (e) { HAPAssert(e == ERANGE); HAPLog(&logObject, "strerror_r error: ERANGE."); return; } // Perform logging. HAPLogWithType(&logObject, type, "%s:%d:%s - %s @ %s:%d", message, errorNumber, errorString, function, file, line); } HAP_RESULT_USE_CHECK HAPPlatformLogEnabledTypes HAPPlatformLogGetEnabledTypes(const HAPLogObject* _Nonnull log HAP_UNUSED) { switch (HAP_LOG_LEVEL) { case 0: { return kHAPPlatformLogEnabledTypes_None; } case 1: { return kHAPPlatformLogEnabledTypes_Default; } case 2: { return kHAPPlatformLogEnabledTypes_Info; } case 3: { return kHAPPlatformLogEnabledTypes_Debug; } default: { HAPFatalError(); } } } void HAPPlatformLogCapture( const HAPLogObject* _Nonnull log, HAPLogType type, const char* _Nonnull message, const void* _Nullable bufferBytes, size_t numBufferBytes) HAP_DIAGNOSE_ERROR(!bufferBytes && numBufferBytes, "empty buffer cannot have a length") { HAPPrecondition(log); HAPPrecondition(message); HAPPrecondition(!numBufferBytes || bufferBytes); static volatile bool captureLock = 0; while (__atomic_test_and_set(&captureLock, __ATOMIC_SEQ_CST)) ; // Format log message. bool logHandled = false; // Perform regular logging. if (!logHandled) { // Color. switch (type) { case kHAPLogType_Debug: { fprintf(stderr, "\x1B[0m"); } break; case kHAPLogType_Info: { fprintf(stderr, "\x1B[32m"); } break; case kHAPLogType_Default: { fprintf(stderr, "\x1B[35m"); } break; case kHAPLogType_Error: { fprintf(stderr, "\x1B[31m"); } break; case kHAPLogType_Fault: { fprintf(stderr, "\x1B[1m\x1B[31m"); } break; } // Time. #ifdef _WIN32 SYSTEMTIME now; GetSystemTime(&now); (void) fprintf( stderr, "%04d-%02d-%02d'T'%02d:%02d:%02d'Z'", now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond); #else struct timeval now; int err = gettimeofday(&now, NULL); if (!err) { struct tm g; struct tm* gmt = gmtime_r(&now.tv_sec, &g); if (gmt) { (void) fprintf( stderr, "%04d-%02d-%02d'T'%02d:%02d:%02d'Z'", 1900 + gmt->tm_year, 1 + gmt->tm_mon, gmt->tm_mday, gmt->tm_hour, gmt->tm_min, gmt->tm_sec); } } #endif (void) fprintf(stderr, "\t"); // Type. switch (type) { case kHAPLogType_Debug: { (void) fprintf(stderr, "Debug"); } break; case kHAPLogType_Info: { (void) fprintf(stderr, "Info"); } break; case kHAPLogType_Default: { (void) fprintf(stderr, "Default"); } break; case kHAPLogType_Error: { (void) fprintf(stderr, "Error"); } break; case kHAPLogType_Fault: { (void) fprintf(stderr, "Fault"); } break; } (void) fprintf(stderr, "\t"); // Subsystem / Category. if (log->subsystem) { (void) fprintf(stderr, "[%s", log->subsystem); if (log->category) { (void) fprintf(stderr, ":%s", log->category); } (void) fprintf(stderr, "] "); } // Message. (void) fprintf(stderr, "%s", message); (void) fprintf(stderr, "\n"); // Buffer. if (bufferBytes) { size_t i, n; const uint8_t* b = bufferBytes; size_t length = numBufferBytes; if (length == 0) { (void) fprintf(stderr, "\n"); } else { i = 0; do { (void) fprintf(stderr, " %04zx ", i); for (n = 0; n != 8 * 4; n++) { if (n % 4 == 0) { (void) fprintf(stderr, " "); } if ((n <= length) && (i < length - n)) { (void) fprintf(stderr, "%02x", b[i + n] & 0xff); } else { (void) fprintf(stderr, " "); } }; (void) fprintf(stderr, " "); for (n = 0; n != 8 * 4; n++) { if (i != length) { if ((32 <= b[i]) && (b[i] < 127)) { (void) fprintf(stderr, "%c", b[i]); } else { (void) fprintf(stderr, "."); } i++; } } (void) fprintf(stderr, "\n"); } while (i != length); } } // Reset color. fprintf(stderr, "\x1B[0m"); } // Finish log. (void) fflush(stderr); __atomic_clear(&captureLock, __ATOMIC_SEQ_CST); }
4,026
777
// 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. #include "ui/events/win/system_event_state_lookup.h" #include <windows.h> namespace ui { namespace win { bool IsShiftPressed() { return (::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000; } bool IsCtrlPressed() { return (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000; } bool IsAltPressed() { return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000; } bool IsAltGrPressed() { return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000 && (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000; } bool IsWindowsKeyPressed() { return (::GetKeyState(VK_LWIN) & 0x8000) == 0x8000 || (::GetKeyState(VK_RWIN) & 0x8000) == 0x8000; } bool IsCapsLockOn() { return (::GetKeyState(VK_CAPITAL) & 0x0001) == 0x0001; } bool IsNumLockOn() { return (::GetKeyState(VK_NUMLOCK) & 0x0001) == 0x0001; } bool IsScrollLockOn() { return (::GetKeyState(VK_SCROLL) & 0x0001) == 0x0001; } } // namespace win } // namespace ui
446
1,091
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.protocol.restconf; import org.onosproject.net.DeviceId; import org.onosproject.protocol.http.HttpSBController; /** * Abstraction of a RESTCONF controller. Serves as a one stop shop for obtaining * RESTCONF southbound devices and (un)register listeners. */ public interface RestConfSBController extends HttpSBController { /** * This method is to be called by whoever is interested to receive * Notifications from a specific device. It does a REST GET request * with specified parameters to the device, and calls the provided * callBackListener upon receiving notifications to notify the requester * about notifications. * * @param device device to make the request to * @param request url of the request * @param mediaType format to retrieve the content in * @param callBackListener method to call when notifications arrives */ void enableNotifications(DeviceId device, String request, String mediaType, RestconfNotificationEventListener callBackListener); /** * Registers a listener for notification events that occur to restconf * devices. * * @param deviceId identifier of the device to which the listener is attached * @param listener the listener to notify */ void addNotificationListener(DeviceId deviceId, RestconfNotificationEventListener listener); /** * Unregisters the listener for the device. * * @param deviceId identifier of the device for which the listener * is to be removed * @param listener listener to be removed */ void removeNotificationListener(DeviceId deviceId, RestconfNotificationEventListener listener); /** * Returns true if a listener has been installed to listen to RESTCONF * notifications sent from a particular device. * * @param deviceId identifier of the device from which the notifications * are generated * @return true if listener is installed; false otherwise */ boolean isNotificationEnabled(DeviceId deviceId); }
912
505
package de.rieckpil.blog; import com.fasterxml.jackson.databind.JsonNode; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; @RestClientTest(ResourceClient.class) @AutoConfigureWebClient(registerRestTemplate = true) class ResourceClientTest { @Autowired private ResourceClient resourceClient; @Autowired private MockRestServiceServer mockRestServiceServer; @BeforeEach // @Before for JUnit 4 void setUp() { this.mockRestServiceServer.reset(); } @AfterEach // @After for JUnit 4 void tearDown() { this.mockRestServiceServer.verify(); } @Test void successfullyReturnData() { String json = """ { "data": "duke" } """; this.mockRestServiceServer .expect(requestTo("/api/unkown/1")) .andRespond(withSuccess(json, MediaType.APPLICATION_JSON)); JsonNode result = resourceClient.getSingleResource(1L); assertNotNull(result); } }
546
316
<reponame>MrMarvin/cloudkeeper import yaml from resotolib.baseplugin import BaseActionPlugin from resotolib.logging import log from resotolib.core.query import CoreGraph from resotolib.graph import Graph from resoto_plugin_aws.resources import ( AWSVPC, AWSVPCPeeringConnection, AWSEC2NetworkAcl, AWSEC2NetworkInterface, AWSELB, AWSALB, AWSALBTargetGroup, AWSEC2Subnet, AWSEC2SecurityGroup, AWSEC2InternetGateway, AWSEC2NATGateway, AWSEC2RouteTable, AWSVPCEndpoint, AWSEC2Instance, AWSEC2ElasticIP, ) from resotolib.args import ArgumentParser from typing import Dict class CleanupAWSVPCsPlugin(BaseActionPlugin): action = "post_cleanup_plan" def __init__(self): super().__init__() self.config = {} if ArgumentParser.args.cleanup_aws_vpcs_config: self.config = CleanupAWSVPCsConfig( config_file=ArgumentParser.args.cleanup_aws_vpcs_config ) self.config.read() # initial read to ensure config format is valid def bootstrap(self) -> bool: return ArgumentParser.args.cleanup_aws_vpcs def do_action(self, data: Dict) -> None: cg = CoreGraph() query = "is(aws_vpc) and desired.clean == true and metadata.cleaned == false <-[0:]->" graph = cg.graph(query) self.vpc_cleanup(graph) cg.patch_nodes(graph) def vpc_cleanup(self, graph: Graph): log.info("AWS VPC cleanup called") for node in graph.nodes: if node.protected or not node.clean or not isinstance(node, AWSVPC): continue cloud = node.cloud(graph) account = node.account(graph) region = node.region(graph) log_prefix = ( f"Found AWS VPC {node.dname} in cloud {cloud.name} account {account.dname} " f"region {region.name} marked for cleanup." ) if len(self.config) > 0: if ( cloud.id not in self.config or account.id not in self.config[cloud.id] ): log.debug( ( f"{log_prefix} Account not found in config - ignoring dependent resources." ) ) continue vpc_instances = [ i for i in node.descendants(graph) if isinstance(i, AWSEC2Instance) and i.instance_status not in ("shutting-down", "terminated") and not i.clean ] if len(vpc_instances) > 0: log_msg = "VPC contains active EC2 instances - not cleaning VPC." log.debug(f"{log_prefix} {log_msg}") node.log(log_msg) node.clean = False continue log.debug(f"{log_prefix} Marking dependent resources for cleanup as well.") for descendant in node.descendants(graph): log.debug(f"Found descendant {descendant.rtdname} of VPC {node.dname}") if isinstance( descendant, ( AWSVPCPeeringConnection, AWSEC2NetworkAcl, AWSEC2NetworkInterface, AWSELB, AWSALB, AWSALBTargetGroup, AWSEC2Subnet, AWSEC2SecurityGroup, AWSEC2InternetGateway, AWSEC2NATGateway, AWSEC2RouteTable, AWSVPCEndpoint, AWSEC2ElasticIP, ), ): descendant.log( ( f"Marking for cleanup because resource is a descendant of VPC {node.dname} " f"which is set to be cleaned" ) ) node.log( f"Marking {descendant.rtdname} for cleanup because resource is a descendant" ) descendant.clean = True else: if descendant.clean: log.debug( ( f"Descendant {descendant.rtdname} of VPC {node.dname} is not targeted but " f"already marked for cleaning" ) ) else: log.error( ( f"Descendant {descendant.rtdname} of VPC {node.dname} is not targeted and " f"not marked for cleaning - VPC cleanup will likely fail" ) ) node.log( ( f"Descendant {descendant.rtdname} is not targeted and not marked for cleaning " f"- cleanup will likely fail" ) ) @staticmethod def add_args(arg_parser: ArgumentParser) -> None: arg_parser.add_argument( "--cleanup-aws-vpcs", help="Cleanup AWS VPCs (default: False)", dest="cleanup_aws_vpcs", action="store_true", default=False, ) arg_parser.add_argument( "--cleanup-aws-vpcs-config", help="Path to Cleanup AWS VPCs Plugin Config", default=None, dest="cleanup_aws_vpcs_config", ) class CleanupAWSVPCsConfig(dict): def __init__(self, *args, config_file: str = None, **kwargs) -> None: super().__init__(*args, **kwargs) self.config_file = config_file def read(self) -> bool: if not self.config_file: raise ValueError( "Attribute config_file is not set on CleanupAWSVPCsConfig() instance" ) with open(self.config_file) as config_file: config = yaml.load(config_file, Loader=yaml.FullLoader) if self.validate(config): self.update(config) return True return False @staticmethod def validate(config) -> bool: if not isinstance(config, dict): raise ValueError("Config is no dict") for cloud_id, account_ids in config.items(): if not isinstance(cloud_id, str): raise ValueError(f"Cloud ID {cloud_id} is no string") if not isinstance(account_ids, list): raise ValueError(f"Account IDs {account_ids} is no list") for account_id in account_ids: if not isinstance(account_id, str): raise ValueError(f"Account ID {account_id} is no string") return True
3,857
414
<reponame>Job-Yang/JYLocalized // // JYCellModel.h // JYLocalizedExample // // Created by 杨权 on 2017/9/27. // Copyright © 2017年 Job-Yang. All rights reserved. // #import <Foundation/Foundation.h> @interface JYCellModel : NSObject /** * 是否选中 */ @property (assign, nonatomic) BOOL enabled; /** * key */ @property (copy, nonatomic) NSString *key; /** * 标题 */ @property (copy, nonatomic) NSString *title; /** * 子标题 */ @property (copy, nonatomic) NSString *subTitle; /** * 图标名 */ @property (copy, nonatomic) NSString *iconName; /** * 方法名 */ @property (copy, nonatomic) NSString *selName; @end
264
584
import os import time import torch import gym from all.agents import Agent def watch(agent, env, fps=60): action = None returns = 0 # have to call this before initial reset for pybullet envs env.render(mode="human") env.reset() while True: action = agent.act(env.state) returns += env.state.reward time.sleep(1 / fps) if env.state.done: print('returns:', returns) env.reset() returns = 0 else: env.step(action) env.render() def load_and_watch(filename, env, fps=60): agent = torch.load(filename).test_agent() watch(agent, env, fps=fps)
294
14,668
// 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. package org.chromium.chrome.browser.compositor.bottombar.contextualsearch; import android.view.View; import org.chromium.chrome.R; import org.chromium.components.browser_ui.bottomsheet.BottomSheetContent; class ContextualSearchSheetContent implements BottomSheetContent { private final View mView; private final float mFullHeightFraction; /** * Construct the coordinator. * @param view The view for the bottom sheet. * @param fullHeightFraction The fraction for the height the content when fully expanded. */ public ContextualSearchSheetContent(View view, float fullHeightFraction) { mView = view; mFullHeightFraction = fullHeightFraction; } // region BottomSheetContent implementation // --------------------------------------------------------------------------------------------- @Override public View getContentView() { return mView; } @Override public View getToolbarView() { return null; } @Override public int getVerticalScrollOffset() { return 0; } @Override public void destroy() {} @Override public int getPriority() { return ContentPriority.HIGH; } @Override public boolean swipeToDismissEnabled() { return true; } @Override public float getFullHeightRatio() { return mFullHeightFraction; } // TODO(sinansahin): These are the temporary strings borrowed from the Preview Tab to avoid a // Resources$NotFoundException. We can replace them once the real strings are ready. @Override public int getSheetContentDescriptionStringId() { return R.string.ephemeral_tab_sheet_description; } @Override public int getSheetHalfHeightAccessibilityStringId() { return R.string.ephemeral_tab_sheet_opened_half; } @Override public int getSheetFullHeightAccessibilityStringId() { return R.string.ephemeral_tab_sheet_opened_full; } @Override public int getSheetClosedAccessibilityStringId() { return R.string.ephemeral_tab_sheet_closed; } // --------------------------------------------------------------------------------------------- // endregion }
787
1,155
package org.zalando.intellij.swagger.documentation; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.zalando.intellij.swagger.SwaggerLightCodeInsightFixtureTestCase; public abstract class DocumentationTest extends SwaggerLightCodeInsightFixtureTestCase { private final String filesPath; public DocumentationTest(final String filesPath) { this.filesPath = filesPath; } protected void testQuickDocumentation(final String fileName, final String expectedDocumentation) { final PsiFile psiFile = myFixture.configureByFile(filesPath + fileName); final PsiElement originalElement = psiFile.findElementAt(myFixture.getEditor().getCaretModel().getOffset()).getParent(); final PsiElement targetElement = originalElement.getReferences()[0].resolve(); final DocumentationProvider documentationProvider = DocumentationManager.getProviderFromElement(targetElement); final String quickNavigateInfo = documentationProvider.getQuickNavigateInfo(targetElement, originalElement); assertEquals(expectedDocumentation, quickNavigateInfo); } }
365
554
package github.tornaco.xposedmoduletest.xposed.submodules.debug; import android.content.Context; import android.util.Log; import com.android.internal.app.AlertController; import com.android.internal.policy.PhoneWindow; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Set; import de.robv.android.xposed.IXposedHookZygoteInit; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import github.tornaco.xposedmoduletest.xposed.submodules.AndroidSubModule; import github.tornaco.xposedmoduletest.xposed.util.XposedLog; /** * Created by guohao4 on 2017/10/31. * Email: <EMAIL> */ public class WindowSubModule extends AndroidSubModule { @Override public void initZygote(IXposedHookZygoteInit.StartupParam startupParam) { super.initZygote(startupParam); hookSetContentView(); hookAlertController(); } private void hookSetContentView() { XposedLog.verbose("PhoneWindow hookSetContentView..."); try { Class clz = XposedHelpers.findClass("com.android.internal.policy.PhoneWindow", null); @SuppressWarnings("unchecked") Method setContentViewInt = clz.getDeclaredMethod("setContentView", int.class); XC_MethodHook.Unhook unhook = XposedBridge.hookMethod(setContentViewInt, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); Log.d(XposedLog.TAG, String.format("PhoneWindow setContentView: %s %s", param.thisObject, Arrays.toString(param.args))); PhoneWindow phoneWindow = (PhoneWindow) param.thisObject; Context context = phoneWindow.getContext(); int id = (int) param.args[0]; if (id != 0) { String entry = context.getResources().getResourceEntryName(id); String name = context.getResources().getResourceName(id); String pkg = context.getResources().getResourcePackageName(id); String type = context.getResources().getResourceTypeName(id); Log.d(XposedLog.TAG, String.format("PhoneWindow, setContentView: %s-%s-%s-%s", pkg, type, entry, name)); } } }); XposedLog.verbose("PhoneWindow hookSetContentView OK:" + unhook); setStatus(unhookToStatus(unhook)); } catch (Exception e) { XposedLog.verbose("PhoneWindow Fail hookSetContentView:" + e); setStatus(SubModuleStatus.ERROR); setErrorMessage(Log.getStackTraceString(e)); } } private void hookAlertController() { XposedLog.verbose("AlertController hookAlertController..."); try { Class stackClass = XposedHelpers.findClass("com.android.internal.app.AlertController", null); Set unHooks = XposedBridge.hookAllConstructors(stackClass, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); AlertController ac = (AlertController) param.thisObject; int mAlertDialogLayout = XposedHelpers.getIntField(ac, "mAlertDialogLayout"); int mSingleChoiceItemLayout = XposedHelpers.getIntField(ac, "mSingleChoiceItemLayout"); int mListLayout = XposedHelpers.getIntField(ac, "mListLayout"); Context context = (Context) XposedHelpers.getObjectField(ac, "mContext"); printId("mAlertDialogLayout", mAlertDialogLayout, context); printId("mSingleChoiceItemLayout", mSingleChoiceItemLayout, context); printId("mListLayout", mListLayout, context); } }); XposedLog.verbose("AlertController hookAlertController OK:" + unHooks); setStatus(unhooksToStatus(unHooks)); } catch (Exception e) { XposedLog.verbose("AlertController Fail hook hookAlertController" + Log.getStackTraceString(e)); setStatus(SubModuleStatus.ERROR); setErrorMessage(Log.getStackTraceString(e)); } } private static void printId(String idName, int id, Context context) { Log.d(XposedLog.TAG, String.format("AlertController printId: %s-%s", idName, id)); if (id != 0) { String entry = context.getResources().getResourceEntryName(id); String name = context.getResources().getResourceName(id); String pkg = context.getResources().getResourcePackageName(id); String type = context.getResources().getResourceTypeName(id); Log.d(XposedLog.TAG, String.format("AlertController, print id for:%s ---- %s-%s-%s-%s", idName, pkg, type, entry, name)); } } }
2,460
2,874
<filename>feature/tool/compare2d.c #include <math.h> #include <stdio.h> #include <stdlib.h> #ifndef DATA_TYPE #define DATA_TYPE double #endif typedef DATA_TYPE data_t; int main(int argc, const char **argv) { FILE *ref_file = 0; FILE *dis_file = 0; int w, h; double ref_accum = 0; double dis_accum = 0; double mse_accum = 0; double xsq_accum = 0; double abs_err = 0; double rel_err = 0; int abs_err_i = 0; int abs_err_j = 0; int rel_err_i = 0; int rel_err_j = 0; int i, j; int ret = 1; if (argc < 5) { goto fail; } ref_file = fopen(argv[1], "rb"); dis_file = fopen(argv[2], "rb"); w = atoi(argv[3]); h = atoi(argv[4]); if (!ref_file || !dis_file || w <= 0 || h <= 0) { goto fail; } for (i = 0; i < h; ++i) { data_t x, y; double abs_err_inner; double rel_err_inner; double ref_inner = 0; double dis_inner = 0; double mse_inner = 0; double xsq_inner = 0; for (j = 0; j < w; ++j) { if (fread(&x, sizeof(data_t), 1, ref_file) != 1) { goto fail; } if (fread(&y, sizeof(data_t), 1, dis_file) != 1) { goto fail; } abs_err_inner = fabs(x - y); rel_err_inner = abs_err_inner / (x == 0 ? nextafter(x, INFINITY) : x); ref_inner += x; dis_inner += y; mse_inner += (x - y) * (x - y); xsq_inner += x * x; if (abs_err_inner > abs_err) { abs_err = abs_err_inner; abs_err_i = i; abs_err_j = j; } if (rel_err_inner > rel_err) { rel_err = rel_err_inner; rel_err_i = i; rel_err_j = j; } } ref_accum += ref_inner; dis_accum += dis_inner; mse_accum += mse_inner; xsq_accum += xsq_inner; } ref_accum /= (double)w * h; dis_accum /= (double)w * h; printf("ref mean: %f\n", ref_accum); printf("dis mean: %f\n", dis_accum); printf("snr: %f\n", 10 * log10(xsq_accum / mse_accum)); printf("max abs err: %e @ (%d, %d)\n", abs_err, abs_err_i, abs_err_j); printf("max rel err: %e @ (%d, %d)\n", rel_err, rel_err_i, rel_err_j); fail: if (ref_file) fclose(ref_file); if (dis_file) fclose(dis_file); return ret; }
1,044
4,262
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.infinispan; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.ScheduledExecutorService; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.support.ResourceHelper; import org.apache.camel.util.ObjectHelper; public class InfinispanUtil { protected InfinispanUtil() { } public static boolean isInHeaderEmpty(Exchange exchange, String header) { return isHeaderEmpty(exchange.getMessage(), header); } public static boolean isHeaderEmpty(Message message, String header) { return ObjectHelper.isEmpty(message.getHeader(header)); } public static Properties loadProperties(CamelContext camelContext, String uri) throws Exception { try (InputStream is = openInputStream(camelContext, uri)) { Properties properties = new Properties(); properties.load(is); return properties; } catch (IOException e) { } throw new FileNotFoundException("Cannot find resource: " + uri); } public static InputStream openInputStream(CamelContext camelContext, String uri) throws Exception { if (camelContext != null) { uri = camelContext.resolvePropertyPlaceholders(uri); return ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri); } return Thread.currentThread().getContextClassLoader().getResourceAsStream(uri); } public static ScheduledExecutorService newSingleThreadScheduledExecutor(CamelContext camelContext, Object source) { return camelContext.getExecutorServiceManager().newSingleThreadScheduledExecutor( source, source.getClass().getSimpleName()); } public static ScheduledExecutorService newSingleThreadScheduledExecutor( CamelContextAware camelContextAware, Object source) { return newSingleThreadScheduledExecutor(camelContextAware.getCamelContext(), source); } public static ScheduledExecutorService newSingleThreadScheduledExecutor( CamelContext camelContext, Object source, String id) { return camelContext.getExecutorServiceManager().newSingleThreadScheduledExecutor( source, source.getClass().getSimpleName() + "-" + id); } public static ScheduledExecutorService newSingleThreadScheduledExecutor( CamelContextAware camelContextAware, Object source, String id) { return newSingleThreadScheduledExecutor(camelContextAware.getCamelContext(), source, id); } }
1,164
2,139
<reponame>buzzdeee/ffi /* * Copyright (c) 2017 <NAME>. All rights reserved. * * For licensing, see LICENSE.SPECS */ #include <stdint.h> int test_untagged_bitmask(int val) { return val; } int test_untagged_typedef_bitmask(int val) { return val; } uint8_t test_untagged_nonint_bitmask(uint8_t val) { return val; } uint16_t test_tagged_nonint_bitmask1(uint16_t val) { return val; } uint32_t test_tagged_nonint_bitmask2(uint32_t val) { return val; } uint64_t test_tagged_nonint_bitmask3(uint64_t val) { return val; } typedef enum {c1 = (1<<0), c2 = (1<<1), c3 = (1<<2), c4 = (1<<3)} bitmask_type1; int test_tagged_typedef_bitmask1(int val) { return val; } typedef enum {c5 = (1<<2), c6 = (1<<3), c7 = (1<<4), c8 = (1<<5)} bitmask_type2; int test_tagged_typedef_bitmask2(int val) { return val; } typedef enum {c9 = (1<<2), c10 = (1<<3), c11 = (1<<5), c12 = (1<<6)} bitmask_type3; int test_tagged_typedef_bitmask3(int val) { return val; } typedef enum {c13 = (1<<2), c14 = (1<<4), c15 = (1<<6), c16 = (1<<8)} bitmask_type4; int test_tagged_typedef_bitmask4(int val) { return val; }
533
2,151
<reponame>zipated/src // Copyright 2018 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/net/http_transport.h" #include <fcntl.h> #include <netdb.h> #include <poll.h> #include <sys/socket.h> #include "base/logging.h" #include "base/macros.h" #include "base/numerics/safe_conversions.h" #include "base/posix/eintr_wrapper.h" #include "base/scoped_generic.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "util/file/file_io.h" #include "util/net/http_body.h" #include "util/net/url.h" #include "util/stdlib/string_number_conversion.h" #include "util/string/split_string.h" namespace crashpad { namespace { constexpr const char kCRLFTerminator[] = "\r\n"; class HTTPTransportSocket final : public HTTPTransport { public: HTTPTransportSocket() = default; ~HTTPTransportSocket() override = default; bool ExecuteSynchronously(std::string* response_body) override; private: DISALLOW_COPY_AND_ASSIGN(HTTPTransportSocket); }; struct ScopedAddrinfoTraits { static addrinfo* InvalidValue() { return nullptr; } static void Free(addrinfo* ai) { freeaddrinfo(ai); } }; using ScopedAddrinfo = base::ScopedGeneric<addrinfo*, ScopedAddrinfoTraits>; bool WaitUntilSocketIsReady(int sock) { pollfd pollfds; pollfds.fd = sock; pollfds.events = POLLIN | POLLPRI | POLLOUT; constexpr int kTimeoutMS = 1000; int ret = HANDLE_EINTR(poll(&pollfds, 1, kTimeoutMS)); if (ret < 0) { PLOG(ERROR) << "poll"; return false; } else if (ret == 1) { if (pollfds.revents & POLLERR) { int err; socklen_t err_len = sizeof(err); if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_len) != 0) { PLOG(ERROR) << "getsockopt"; } else { errno = err; PLOG(ERROR) << "POLLERR"; } return false; } if (pollfds.revents & POLLHUP) { return false; } return (pollfds.revents & POLLIN) != 0 || (pollfds.revents & POLLOUT) != 0; } // Timeout. return false; } class ScopedSetNonblocking { public: explicit ScopedSetNonblocking(int sock) : sock_(sock) { int flags = fcntl(sock, F_GETFL, 0); if (flags < 0) { PLOG(ERROR) << "fcntl"; sock_ = -1; return; } if (fcntl(sock_, F_SETFL, flags | O_NONBLOCK) < 0) { PLOG(ERROR) << "fcntl"; sock_ = -1; } } ~ScopedSetNonblocking() { if (sock_ >= 0) { int flags = fcntl(sock_, F_GETFL, 0); if (flags < 0) { PLOG(ERROR) << "fcntl"; return; } if (fcntl(sock_, F_SETFL, flags & (~O_NONBLOCK)) < 0) { PLOG(ERROR) << "fcntl"; } } } private: int sock_; DISALLOW_COPY_AND_ASSIGN(ScopedSetNonblocking); }; base::ScopedFD CreateSocket(const std::string& hostname, const std::string& port) { addrinfo hints = {}; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = 0; hints.ai_flags = 0; addrinfo* addrinfo_raw; if (getaddrinfo(hostname.c_str(), port.c_str(), &hints, &addrinfo_raw) < 0) { PLOG(ERROR) << "getaddrinfo"; return base::ScopedFD(); } ScopedAddrinfo addrinfo(addrinfo_raw); for (const auto* ap = addrinfo.get(); ap; ap = ap->ai_next) { base::ScopedFD result( socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol)); if (!result.is_valid()) { continue; } { // Set socket to non-blocking to avoid hanging for a long time if the // network is down. ScopedSetNonblocking nonblocking(result.get()); if (HANDLE_EINTR(connect(result.get(), ap->ai_addr, ap->ai_addrlen)) < 0) { if (errno != EINPROGRESS) { PLOG(ERROR) << "connect"; } else if (WaitUntilSocketIsReady(result.get())) { return result; } return base::ScopedFD(); } return result; } } return base::ScopedFD(); } bool WriteRequest(int sock, const std::string& method, const std::string& resource, const HTTPHeaders& headers, HTTPBodyStream* body_stream) { std::string request_line = base::StringPrintf( "%s %s HTTP/1.0\r\n", method.c_str(), resource.c_str()); if (!LoggingWriteFile(sock, request_line.data(), request_line.size())) return false; // Write headers, and determine if Content-Length has been specified. bool chunked = true; size_t content_length = 0; for (const auto& header : headers) { std::string header_str = base::StringPrintf( "%s: %s\r\n", header.first.c_str(), header.second.c_str()); if (header.first == kContentLength) { chunked = !base::StringToSizeT(header.second, &content_length); DCHECK(!chunked); } if (!LoggingWriteFile(sock, header_str.data(), header_str.size())) return false; } // If no Content-Length, then encode as chunked, so add that header too. if (chunked) { static constexpr const char kTransferEncodingChunked[] = "Transfer-Encoding: chunked\r\n"; if (!LoggingWriteFile( sock, kTransferEncodingChunked, strlen(kTransferEncodingChunked))) { return false; } } if (!LoggingWriteFile(sock, kCRLFTerminator, strlen(kCRLFTerminator))) { return false; } FileOperationResult data_bytes; do { constexpr size_t kCRLFSize = arraysize(kCRLFTerminator) - 1; struct __attribute__((packed)) { char size[8]; char crlf[2]; uint8_t data[32 * 1024 + kCRLFSize]; } buf; static_assert( sizeof(buf) == sizeof(buf.size) + sizeof(buf.crlf) + sizeof(buf.data), "buf should not have padding"); // Read a block of data. data_bytes = body_stream->GetBytesBuffer(buf.data, sizeof(buf.data) - kCRLFSize); if (data_bytes == -1) { return false; } DCHECK_GE(data_bytes, 0); DCHECK_LE(static_cast<size_t>(data_bytes), sizeof(buf.data) - kCRLFSize); void* write_start; size_t write_size; if (chunked) { // Chunked encoding uses the entirety of buf. buf.size is presented in // hexadecimal without any leading "0x". The terminating CR and LF will be // placed immediately following the used portion of buf.data, even if // buf.data is not full. // Not snprintf because non-null terminated is desired. int rv = sprintf( buf.size, "%08x", base::checked_cast<unsigned int>(data_bytes)); DCHECK_GE(rv, 0); DCHECK_EQ(static_cast<size_t>(rv), sizeof(buf.size)); DCHECK_NE(buf.size[sizeof(buf.size) - 1], '\0'); memcpy(&buf.crlf[0], kCRLFTerminator, kCRLFSize); memcpy(&buf.data[data_bytes], kCRLFTerminator, kCRLFSize); // Skip leading zeroes in the chunk size. size_t size_len; for (size_len = sizeof(buf.size); size_len > 1; --size_len) { if (buf.size[sizeof(buf.size) - size_len] != '0') { break; } } write_start = buf.crlf - size_len; write_size = size_len + sizeof(buf.crlf) + data_bytes + kCRLFSize; } else { // When not using chunked encoding, only use buf.data. write_start = buf.data; write_size = data_bytes; } // write_size will be 0 at EOF in non-chunked mode. Skip the write in that // case. In contrast, at EOF in chunked mode, a zero-length chunk must be // sent to signal EOF. This will happen when processing the EOF indicated by // a 0 return from body_stream()->GetBytesBuffer() above. if (write_size != 0) { if (!LoggingWriteFile(sock, write_start, write_size)) return false; } } while (data_bytes > 0); return true; } bool ReadLine(int sock, std::string* line) { line->clear(); for (;;) { char byte; if (!LoggingReadFileExactly(sock, &byte, 1)) { return false; } line->append(&byte, 1); if (byte == '\n') return true; } } bool StartsWith(const std::string& str, const char* with, size_t len) { return str.compare(0, len, with) == 0; } bool ReadResponseLine(int sock) { std::string response_line; if (!ReadLine(sock, &response_line)) { LOG(ERROR) << "ReadLine"; return false; } static constexpr const char kHttp10[] = "HTTP/1.0 200 "; static constexpr const char kHttp11[] = "HTTP/1.1 200 "; return StartsWith(response_line, kHttp10, strlen(kHttp10)) || StartsWith(response_line, kHttp11, strlen(kHttp11)); } bool ReadResponseHeaders(int sock, HTTPHeaders* headers) { for (;;) { std::string line; if (!ReadLine(sock, &line)) { return false; } if (line == kCRLFTerminator) { return true; } std::string left, right; if (!SplitStringFirst(line, ':', &left, &right)) { LOG(ERROR) << "SplitStringFirst"; return false; } DCHECK_EQ(right[right.size() - 1], '\n'); DCHECK_EQ(right[right.size() - 2], '\r'); DCHECK_EQ(right[0], ' '); DCHECK_NE(right[1], ' '); right = right.substr(1, right.size() - 3); (*headers)[left] = right; } } bool ReadContentChunked(int sock, std::string* body) { // TODO(scottmg): https://crashpad.chromium.org/bug/196. LOG(ERROR) << "TODO(scottmg): chunked response read"; return false; } bool ReadResponse(int sock, std::string* response_body) { response_body->clear(); if (!ReadResponseLine(sock)) { return false; } HTTPHeaders response_headers; if (!ReadResponseHeaders(sock, &response_headers)) { return false; } auto it = response_headers.find("Content-Length"); size_t len = 0; if (it != response_headers.end()) { if (!base::StringToSizeT(it->second, &len)) { LOG(ERROR) << "invalid Content-Length"; return false; } } if (len) { response_body->resize(len, 0); return ReadFileExactly(sock, &(*response_body)[0], len); } it = response_headers.find("Transfer-Encoding"); bool chunked = false; if (it != response_headers.end() && it->second == "chunked") { chunked = true; } return chunked ? ReadContentChunked(sock, response_body) : LoggingReadToEOF(sock, response_body); } bool HTTPTransportSocket::ExecuteSynchronously(std::string* response_body) { std::string scheme, hostname, port, resource; if (!CrackURL(url(), &scheme, &hostname, &port, &resource)) { return false; } base::ScopedFD sock(CreateSocket(hostname, port)); if (!sock.is_valid()) { return false; } if (!WriteRequest(sock.get(), method(), resource, headers(), body_stream())) { return false; } if (!ReadResponse(sock.get(), response_body)) { return false; } return true; } } // namespace // static std::unique_ptr<HTTPTransport> HTTPTransport::Create() { return std::unique_ptr<HTTPTransportSocket>(new HTTPTransportSocket); } } // namespace crashpad
4,650
3,274
<reponame>tyang513/QLExpress<gh_stars>1000+ package com.ql.util.express.instruction.op; import java.lang.reflect.Array; import com.ql.util.express.ArraySwap; import com.ql.util.express.ExpressUtil; import com.ql.util.express.InstructionSetContext; import com.ql.util.express.OperateData; import com.ql.util.express.instruction.OperateDataCacheManager; public class OperatorAnonymousNewArray extends OperatorBase { public OperatorAnonymousNewArray(String aName) { this.name = aName; } public OperatorAnonymousNewArray(String aAliasName, String aName, String aErrorInfo) { this.name = aName; this.aliasName = aAliasName; this.errorInfo = aErrorInfo; } public OperateData executeInner(InstructionSetContext context, ArraySwap list) throws Exception { Class<?> type = this.findArrayClassType(context,list); type = ExpressUtil.getSimpleDataType(type); int[] dims = new int[1]; dims[0]= list.length; Object data = Array.newInstance(type,dims); for(int i=0;i<list.length;i++){ Array.set(data, i, list.get(i).getObject(context)); } return OperateDataCacheManager.fetchOperateData(data,data.getClass()); } private Class<?>findArrayClassType(InstructionSetContext context, ArraySwap list) throws Exception { Class<?> type = null; for(int i=0;i<list.length;i++){ Class<?> type1 = list.get(i).getType(context); if(type1==null){ //doNothing }else if(type==null){ //第一次赋值 type = type1; }else if(type1==type || type.isAssignableFrom(type1)){//type1是type的子类 //doNothing }else if(type1.isAssignableFrom(type)){ //寻找更基础的类 type = type1 ; }else{ type = Object.class; } } if(type==null) type = Object.class;//参数全部为null的情况 return type; } }
696
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iPodUI.framework/iPodUI */ @class IUCoverFlowViewController; @protocol IUCoverFlowOwner <NSObject> @property(readonly, assign, nonatomic) BOOL isShowingCoverFlow; @property(retain, nonatomic) IUCoverFlowViewController *coverFlowViewController; // declared property getter: - (BOOL)isShowingCoverFlow; // declared property setter: - (void)setCoverFlowViewController:(id)controller; // declared property getter: - (id)coverFlowViewController; @end
170
587
/* * Copyright 2017-2021 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.gchq.gaffer.cache.impl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import uk.gov.gchq.gaffer.exception.SerialisationException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertEquals; public class HashMapCacheTest { private HashMapCache<String, Integer> cache = new HashMapCache<>(); @AfterEach public void after() { cache.clear(); } @Test public void shouldAddKeyValuePairToCache() { cache.put("key", 1); assertThat(cache.size()).isOne(); } @Test public void shouldGetEntryFromCacheUsingKey() { cache.put("key", 2); assertEquals(new Integer(2), cache.get("key")); } @Test public void shouldDeleteCachedEntriesByKeyName() { cache.put("key", 3); cache.remove("key"); assertThat(cache.size()).isZero(); } @Test public void putShouldOverriteEntriesWithDuplicateKeyName() { cache.put("key", 4); cache.put("key", 5); assertThat(cache.size()).isOne(); assertEquals(new Integer(5), cache.get("key")); } @Test public void shouldClearAllEntries() { cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); cache.clear(); assertThat(cache.size()).isZero(); } @Test public void shouldGetAllKeys() { cache.put("test1", 1); cache.put("test2", 2); cache.put("test3", 3); assertThat(cache.size()).isEqualTo(3); assertThat(cache.getAllKeys()).contains("test1", "test2", "test3"); } @Test public void shouldGetAllValues() { cache.put("test1", 1); cache.put("test2", 2); cache.put("test3", 3); cache.put("duplicate", 3); assertThat(cache.size()).isEqualTo(4); assertThat(cache.getAllValues()) .hasSize(4) .contains(1, 2, 3, 3); } @DisplayName("Should cause JavaSerialisableException when serialisation flag is true") @Test public void shouldThrowRuntimeExceptionCausedByNonJavaSerialisableException() { final HashMapCache<String, Object> map = new HashMapCache<>(true); final String s = "hello"; map.put("test1", s); class TempClass { } TempClass tempClass = new TempClass(); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> map.put("test1", tempClass)) .withCauseInstanceOf(SerialisationException.class); } @DisplayName("Should not cause JavaSerialisableException when serialisation flag is false") @Test public void shouldNotThrowAnyExceptions() { final HashMapCache<String, Object> map = new HashMapCache<>(false); map.put("test1", "hello"); class TempClass { } final TempClass tempClass = new TempClass(); map.put("test1", tempClass); } }
1,478
310
<gh_stars>100-1000 package org.seasar.doma.jdbc.query; import java.sql.Connection; import java.sql.SQLException; public interface CreateQuery<RESULT> extends Query { RESULT create(Connection connection) throws SQLException; }
76
1,247
<filename>goodsKill-spring-boot-provider/goodsKill-service/src/main/java/org/seckill/service/mp/SuccessKilledService.java package org.seckill.service.mp; import com.baomidou.mybatisplus.extension.service.IService; import org.seckill.entity.SuccessKilled; /** * @author heng */ public interface SuccessKilledService extends IService<SuccessKilled> { }
123
348
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000 {"nom":"Seix","circ":"1ère circonscription","dpt":"Ariège","inscrits":674,"abs":298,"votants":376,"blancs":26,"nuls":13,"exp":337,"res":[{"nuance":"FI","nom":"<NAME>","voix":181},{"nuance":"REM","nom":"<NAME>","voix":156}]}
114
745
#ifndef CK_AMD_BUFFER_ADDRESSING_HPP #define CK_AMD_BUFFER_ADDRESSING_HPP #include "data_type.hpp" namespace ck { template <typename T> union BufferResource { // 128 bit SGPRs to supply buffer resource in buffer instructions // https://rocm-documentation.readthedocs.io/en/latest/GCN_ISA_Manuals/testdocbook.html#vector-memory-buffer-instructions int32x4_t content; StaticallyIndexedArray<T*, 2> address; StaticallyIndexedArray<int32_t, 4> range; StaticallyIndexedArray<int32_t, 4> config; }; template <typename T> __device__ int32x4_t make_wave_buffer_resource(T* p_wave, index_t element_space_size) { BufferResource<T> wave_buffer_resource; // wavewise base address (64 bit) wave_buffer_resource.address(Number<0>{}) = const_cast<remove_cv_t<T>*>(p_wave); // wavewise range (32 bit) wave_buffer_resource.range(Number<2>{}) = element_space_size * sizeof(T); // wavewise setting (32 bit) wave_buffer_resource.config(Number<3>{}) = CK_BUFFER_RESOURCE_3RD_DWORD; return wave_buffer_resource.content; } // load __device__ int8_t llvm_amdgcn_raw_buffer_load_i8(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.i8"); __device__ int8x2_t llvm_amdgcn_raw_buffer_load_i8x2(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v2i8"); __device__ int8x4_t llvm_amdgcn_raw_buffer_load_i8x4(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v4i8"); __device__ int16_t llvm_amdgcn_raw_buffer_load_i16(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.i32"); __device__ int32_t llvm_amdgcn_raw_buffer_load_i32(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.i32"); __device__ int32x2_t llvm_amdgcn_raw_buffer_load_i32x2(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v2i32"); __device__ int32x4_t llvm_amdgcn_raw_buffer_load_i32x4(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v4i32"); // half __device__ half_t llvm_amdgcn_raw_buffer_load_fp16(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.f16"); __device__ half2_t llvm_amdgcn_raw_buffer_load_fp16x2(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v2f16"); __device__ half4_t llvm_amdgcn_raw_buffer_load_fp16x4(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v4f16"); // float __device__ float llvm_amdgcn_raw_buffer_load_fp32(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.f32"); __device__ float2_t llvm_amdgcn_raw_buffer_load_fp32x2(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v2f32"); __device__ float4_t llvm_amdgcn_raw_buffer_load_fp32x4(int32x4_t srsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.load.v4f32"); // store __device__ void llvm_amdgcn_raw_buffer_store_i8(int8_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.i8"); __device__ void llvm_amdgcn_raw_buffer_store_i8x2(int8x2_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v2i8"); __device__ void llvm_amdgcn_raw_buffer_store_i8x4(int8x4_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v4i8"); __device__ void llvm_amdgcn_raw_buffer_store_i16(int16_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.i16"); __device__ void llvm_amdgcn_raw_buffer_store_i32(int32_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.i32"); __device__ void llvm_amdgcn_raw_buffer_store_i32x2(int32x2_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v2i32"); __device__ void llvm_amdgcn_raw_buffer_store_i32x4(int32x4_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v4i32"); // half __device__ void llvm_amdgcn_raw_buffer_store_fp16(half_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.f16"); __device__ void llvm_amdgcn_raw_buffer_store_fp16x2(half2_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v2f16"); __device__ void llvm_amdgcn_raw_buffer_store_fp16x4(half4_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v4f16"); // float __device__ void llvm_amdgcn_raw_buffer_store_fp32(float vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.f32"); __device__ void llvm_amdgcn_raw_buffer_store_fp32x2(float2_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v2f32"); __device__ void llvm_amdgcn_raw_buffer_store_fp32x4(float4_t vdata, int32x4_t rsrc, index_t voffset, index_t soffset, index_t glc_slc) __asm("llvm.amdgcn.raw.buffer.store.v4f32"); template <typename T, index_t N> __device__ typename vector_type<T, N>::type amd_buffer_load_impl(int32x4_t src_wave_buffer_resource, index_t src_thread_addr_offset, index_t src_wave_addr_offset) { static_assert( (is_same<T, double>::value && (N == 1 || N == 2 || N == 4)) || (is_same<T, float>::value && (N == 1 || N == 2 || N == 4 || N == 8)) || (is_same<T, half_t>::value && (N == 1 || N == 2 || N == 4 || N == 8)) || (is_same<T, int32_t>::value && (N == 1 || N == 2 || N == 4 || N == 8)) || (is_same<T, int8_t>::value && (N == 1 || N == 2 || N == 4 || N == 8 || N == 16)), "wrong! not implemented"); if constexpr(is_same<T, double>::value) { // use fp32 load to mimic fp64 load if constexpr(N == 1) { const float2_t tmp = llvm_amdgcn_raw_buffer_load_fp32x2( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<double>(tmp); } else if constexpr(N == 2) { const float4_t tmp = llvm_amdgcn_raw_buffer_load_fp32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<double2_t>(tmp); } else if constexpr(N == 4) { const float4_t f32_0 = llvm_amdgcn_raw_buffer_load_fp32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); const float4_t f32_1 = llvm_amdgcn_raw_buffer_load_fp32x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 4 * sizeof(float), 0); vector_type<double, 4> tmp; tmp.AsType<double2_t>()(Number<0>{}) = as_type<double2_t>(f32_0); tmp.AsType<double2_t>()(Number<1>{}) = as_type<double2_t>(f32_1); return tmp.AsType<double4_t>()(Number<0>{}); } } else if constexpr(is_same<T, float>::value) { if constexpr(N == 1) { return llvm_amdgcn_raw_buffer_load_fp32( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 2) { return llvm_amdgcn_raw_buffer_load_fp32x2( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 4) { return llvm_amdgcn_raw_buffer_load_fp32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 8) { vector_type<float, 8> tmp; tmp.AsType<float4_t>()(Number<0>{}) = llvm_amdgcn_raw_buffer_load_fp32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); tmp.AsType<float4_t>()(Number<1>{}) = llvm_amdgcn_raw_buffer_load_fp32x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 4 * sizeof(float), 0); return tmp.AsType<float8_t>()(Number<0>{}); } } else if constexpr(is_same<T, half_t>::value) { if constexpr(N == 1) { return llvm_amdgcn_raw_buffer_load_fp16( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 2) { return llvm_amdgcn_raw_buffer_load_fp16x2( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 4) { return llvm_amdgcn_raw_buffer_load_fp16x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 8) { // use fp32 load to mimic fp16 load float4_t tmp = llvm_amdgcn_raw_buffer_load_fp32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<half8_t>(tmp); } } else if constexpr(is_same<T, int32_t>::value) { if constexpr(N == 1) { return llvm_amdgcn_raw_buffer_load_i32( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 2) { return llvm_amdgcn_raw_buffer_load_i32x2( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 4) { return llvm_amdgcn_raw_buffer_load_i32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 8) { vector_type<int32_t, 8> tmp; tmp.AsType<int32x4_t>()(Number<0>{}) = llvm_amdgcn_raw_buffer_load_i32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); tmp.AsType<int32x4_t>()(Number<1>{}) = llvm_amdgcn_raw_buffer_load_i32x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 4 * sizeof(int32_t), 0); return tmp.AsType<int32x8_t>()(Number<0>{}); } } else if constexpr(is_same<T, int8_t>::value) { if constexpr(N == 1) { return llvm_amdgcn_raw_buffer_load_i8( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); } else if constexpr(N == 2) { #if !CK_WORKAROUND_SWDEV_XXXXXX_INT8_BUFFER_LOAD_STORE_ISSUE return llvm_amdgcn_raw_buffer_load_i8x2( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); #else int16_t tmp = llvm_amdgcn_raw_buffer_load_i16( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<int8x2_t>(tmp); #endif } else if constexpr(N == 4) { #if !CK_WORKAROUND_SWDEV_XXXXXX_INT8_BUFFER_LOAD_STORE_ISSUE return llvm_amdgcn_raw_buffer_load_i8x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); #else int32_t tmp = llvm_amdgcn_raw_buffer_load_i32( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<int8x4_t>(tmp); #endif } else if constexpr(N == 8) { #if !CK_WORKAROUND_SWDEV_XXXXXX_INT8_BUFFER_LOAD_STORE_ISSUE vector_type<int8_t, 8> tmp; tmp.AsType<int8x4_t>()(Number<0>{}) = llvm_amdgcn_raw_buffer_load_i8x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); tmp.AsType<int8x4_t>()(Number<1>{}) = llvm_amdgcn_raw_buffer_load_i8x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 4 * sizeof(int8_t), 0); return tmp.AsType<int8x8_t>()(Number<0>{}); #else int32x2_t tmp = llvm_amdgcn_raw_buffer_load_i32x2( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<int8x8_t>(tmp); #endif } else if constexpr(N == 16) { #if !CK_WORKAROUND_SWDEV_XXXXXX_INT8_BUFFER_LOAD_STORE_ISSUE vector_type<int8_t, 16> tmp; tmp.AsType<int8x4_t>()(Number<0>{}) = llvm_amdgcn_raw_buffer_load_i8x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); tmp.AsType<int8x4_t>()(Number<1>{}) = llvm_amdgcn_raw_buffer_load_i8x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 4 * sizeof(int8_t), 0); tmp.AsType<int8x4_t>()(Number<2>{}) = llvm_amdgcn_raw_buffer_load_i8x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 8 * sizeof(int8_t), 0); tmp.AsType<int8x4_t>()(Number<3>{}) = llvm_amdgcn_raw_buffer_load_i8x4(src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset + 12 * sizeof(int8_t), 0); return tmp.AsType<int8x16_t>()(Number<0>{}); #else int32x4_t tmp = llvm_amdgcn_raw_buffer_load_i32x4( src_wave_buffer_resource, src_thread_addr_offset, src_wave_addr_offset, 0); return as_type<int8x16_t>(tmp); #endif } } } template <typename T, index_t N> __device__ void amd_buffer_store_impl(const typename vector_type<T, N>::type src_thread_data, int32x4_t dst_wave_buffer_resource, index_t dst_thread_addr_offset, index_t dst_wave_addr_offset) { static_assert( (is_same<T, double>::value && (N == 1 || N == 2)) || (is_same<T, float>::value && (N == 1 || N == 2 || N == 4)) || (is_same<T, half_t>::value && (N == 1 || N == 2 || N == 4 || N == 8)) || (is_same<T, int32_t>::value && (N == 1 || N == 2 || N == 4)) || (is_same<T, int8_t>::value && (N == 1 || N == 2 || N == 4 || N == 8 || N == 16)), "wrong! not implemented"); if constexpr(is_same<T, double>::value) { // use fp32 store to mimic fp64 store if constexpr(N == 1) { llvm_amdgcn_raw_buffer_store_fp32x2(as_type<float2_t>(src_thread_data), dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 2) { llvm_amdgcn_raw_buffer_store_fp32x4(as_type<float4_t>(src_thread_data), dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } } else if constexpr(is_same<T, float>::value) { if constexpr(N == 1) { llvm_amdgcn_raw_buffer_store_fp32(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 2) { llvm_amdgcn_raw_buffer_store_fp32x2(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 4) { llvm_amdgcn_raw_buffer_store_fp32x4(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } } else if constexpr(is_same<T, half_t>::value) { if constexpr(N == 1) { llvm_amdgcn_raw_buffer_store_fp16(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 2) { llvm_amdgcn_raw_buffer_store_fp16x2(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 4) { llvm_amdgcn_raw_buffer_store_fp16x4(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 8) { vector_type<half_t, 8> tmp{src_thread_data}; llvm_amdgcn_raw_buffer_store_fp16x4(tmp.AsType<half4_t>()[Number<0>{}], dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); llvm_amdgcn_raw_buffer_store_fp16x4(tmp.AsType<half4_t>()[Number<1>{}], dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset + 4 * sizeof(half_t), 0); } } else if constexpr(is_same<T, int32_t>::value) { if constexpr(N == 1) { llvm_amdgcn_raw_buffer_store_i32(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 2) { llvm_amdgcn_raw_buffer_store_i32x2(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 4) { llvm_amdgcn_raw_buffer_store_i32x4(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } } else if constexpr(is_same<T, int8_t>::value) { if constexpr(N == 1) { llvm_amdgcn_raw_buffer_store_i8(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 2) { #if !CK_WORKAROUND_SWDEV_XXXXXX_INT8_BUFFER_LOAD_STORE_ISSUE llvm_amdgcn_raw_buffer_store_i8x2(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); #else llvm_amdgcn_raw_buffer_store_i16(as_type<int16_t>(src_thread_data), dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); #endif } else if constexpr(N == 4) { #if !CK_WORKAROUND_SWDEV_XXXXXX_INT8_BUFFER_LOAD_STORE_ISSUE llvm_amdgcn_raw_buffer_store_i8x4(src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); #else llvm_amdgcn_raw_buffer_store_i32(as_type<int32_t>(src_thread_data), dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); #endif } else if constexpr(N == 8) { llvm_amdgcn_raw_buffer_store_i32x2(as_type<int32x2_t>(src_thread_data), dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } else if constexpr(N == 16) { llvm_amdgcn_raw_buffer_store_i32x4(as_type<int32x4_t>(src_thread_data), dst_wave_buffer_resource, dst_thread_addr_offset, dst_wave_addr_offset, 0); } } } // buffer_load requires: // 1) p_src_wave must be in global memory space // 2) p_src_wave must be a wavewise pointer. // It is user's responsibility to make sure that is true. template <typename T, index_t N> __device__ typename vector_type_maker<T, N>::type::type amd_buffer_load_invalid_element_return_return_zero(const T* p_src_wave, index_t src_thread_element_offset, bool src_thread_element_valid, index_t src_element_space_size) { const int32x4_t src_wave_buffer_resource = make_wave_buffer_resource(p_src_wave, src_element_space_size); index_t src_thread_addr_offset = src_thread_element_offset * sizeof(T); using vector_t = typename vector_type_maker<T, N>::type::type; using scalar_t = typename scalar_type<vector_t>::type; constexpr index_t vector_size = scalar_type<vector_t>::vector_size; #if CK_EXPERIMENTAL_USE_BUFFER_LOAD_OOB_CHECK_OFFSET_TRICK uint32_t src_addr_shift = src_thread_element_valid ? 0 : 0x7fffffff; return amd_buffer_load_impl<scalar_t, vector_size>( src_wave_buffer_resource, src_addr_shift + src_thread_addr_offset, 0); #else vector_t tmp = amd_buffer_load_impl<scalar_t, vector_size>( src_wave_buffer_resource, src_thread_addr_offset, 0); return src_thread_element_valid ? tmp : vector_t(0); #endif } // buffer_load requires: // 1) p_src_wave must be in global memory space // 2) p_src_wave must be a wavewise pointer. // It is user's responsibility to make sure that is true. template <typename T, index_t N> __device__ typename vector_type_maker<T, N>::type::type amd_buffer_load_invalid_element_return_customized_value(const T* p_src_wave, index_t src_thread_element_offset, bool src_thread_element_valid, index_t src_element_space_size, T customized_value) { const int32x4_t src_wave_buffer_resource = make_wave_buffer_resource(p_src_wave, src_element_space_size); index_t src_thread_addr_offset = src_thread_element_offset * sizeof(T); using vector_t = typename vector_type_maker<T, N>::type::type; using scalar_t = typename scalar_type<vector_t>::type; constexpr index_t vector_size = scalar_type<vector_t>::vector_size; vector_t tmp = amd_buffer_load_impl<scalar_t, vector_size>( src_wave_buffer_resource, src_thread_addr_offset, 0); return src_thread_element_valid ? tmp : vector_t(customized_value); } // buffer_store requires: // 1) p_dst_wave must be global memory // 2) p_dst_wave to be a wavewise pointer. // It is user's responsibility to make sure that is true. template <typename T, index_t N> __device__ void amd_buffer_store(const typename vector_type_maker<T, N>::type::type src_thread_data, T* p_dst_wave, const index_t dst_thread_element_offset, const bool dst_thread_element_valid, const index_t dst_element_space_size) { const int32x4_t dst_wave_buffer_resource = make_wave_buffer_resource(p_dst_wave, dst_element_space_size); index_t dst_thread_addr_offset = dst_thread_element_offset * sizeof(T); using vector_t = typename vector_type_maker<T, N>::type::type; using scalar_t = typename scalar_type<vector_t>::type; constexpr index_t vector_size = scalar_type<vector_t>::vector_size; #if CK_EXPERIMENTAL_USE_BUFFER_STORE_OOB_CHECK_OFFSET_TRICK uint32_t dst_addr_shift = dst_thread_element_valid ? 0 : 0x7fffffff; amd_buffer_store_impl<scalar_t, vector_size>( src_thread_data, dst_wave_buffer_resource, dst_addr_shift + dst_thread_addr_offset, 0); #else if(dst_thread_element_valid) { amd_buffer_store_impl<scalar_t, vector_size>( src_thread_data, dst_wave_buffer_resource, dst_thread_addr_offset, 0); } #endif } } // namespace ck #endif
19,578
9,402
<reponame>pyracanda/runtime // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ============================================================ // // ApplicationContext.cpp // // // Implements the ApplicationContext class // // ============================================================ #include "applicationcontext.hpp" #include "stringarraylist.h" #include "loadcontext.hpp" #include "failurecache.hpp" #include "assemblyidentitycache.hpp" #include "utils.hpp" #include "ex.h" #include "clr/fs/path.h" using namespace clr::fs; namespace BINDER_SPACE { ApplicationContext::ApplicationContext() { m_pExecutionContext = NULL; m_pFailureCache = NULL; m_contextCS = NULL; m_pTrustedPlatformAssemblyMap = nullptr; } ApplicationContext::~ApplicationContext() { SAFE_DELETE(m_pExecutionContext); SAFE_DELETE(m_pFailureCache); if (m_contextCS != NULL) { ClrDeleteCriticalSection(m_contextCS); } if (m_pTrustedPlatformAssemblyMap != nullptr) { delete m_pTrustedPlatformAssemblyMap; } } HRESULT ApplicationContext::Init() { HRESULT hr = S_OK; NewHolder<ExecutionContext> pExecutionContext; FailureCache *pFailureCache = NULL; // Allocate context objects SAFE_NEW(pExecutionContext, ExecutionContext); SAFE_NEW(pFailureCache, FailureCache); m_contextCS = ClrCreateCriticalSection( CrstFusionAppCtx, CRST_REENTRANCY); if (!m_contextCS) { SAFE_DELETE(pFailureCache); hr = E_OUTOFMEMORY; } else { m_pExecutionContext = pExecutionContext.Extract(); m_pFailureCache = pFailureCache; } Exit: return hr; } HRESULT ApplicationContext::SetupBindingPaths(SString &sTrustedPlatformAssemblies, SString &sPlatformResourceRoots, SString &sAppPaths, BOOL fAcquireLock) { HRESULT hr = S_OK; CRITSEC_Holder contextLock(fAcquireLock ? GetCriticalSectionCookie() : NULL); if (m_pTrustedPlatformAssemblyMap != nullptr) { GO_WITH_HRESULT(S_OK); } // // Parse TrustedPlatformAssemblies // m_pTrustedPlatformAssemblyMap = new SimpleNameToFileNameMap(); sTrustedPlatformAssemblies.Normalize(); for (SString::Iterator i = sTrustedPlatformAssemblies.Begin(); i != sTrustedPlatformAssemblies.End(); ) { SString fileName; SString simpleName; bool isNativeImage = false; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextTPAPath(sTrustedPlatformAssemblies, i, /*dllOnly*/ false, fileName, simpleName, isNativeImage)); if (pathResult == S_FALSE) { break; } const SimpleNameToFileNameMapEntry *pExistingEntry = m_pTrustedPlatformAssemblyMap->LookupPtr(simpleName.GetUnicode()); if (pExistingEntry != nullptr) { // // We want to store only the first entry matching a simple name we encounter. // The exception is if we first store an IL reference and later in the string // we encounter a native image. Since we don't touch IL in the presence of // native images, we replace the IL entry with the NI. // if ((pExistingEntry->m_wszILFileName != nullptr && !isNativeImage) || (pExistingEntry->m_wszNIFileName != nullptr && isNativeImage)) { continue; } } LPWSTR wszSimpleName = nullptr; if (pExistingEntry == nullptr) { wszSimpleName = new WCHAR[simpleName.GetCount() + 1]; if (wszSimpleName == nullptr) { GO_WITH_HRESULT(E_OUTOFMEMORY); } wcscpy_s(wszSimpleName, simpleName.GetCount() + 1, simpleName.GetUnicode()); } else { wszSimpleName = pExistingEntry->m_wszSimpleName; } LPWSTR wszFileName = new WCHAR[fileName.GetCount() + 1]; if (wszFileName == nullptr) { GO_WITH_HRESULT(E_OUTOFMEMORY); } wcscpy_s(wszFileName, fileName.GetCount() + 1, fileName.GetUnicode()); SimpleNameToFileNameMapEntry mapEntry; mapEntry.m_wszSimpleName = wszSimpleName; if (isNativeImage) { mapEntry.m_wszNIFileName = wszFileName; mapEntry.m_wszILFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszILFileName; } else { mapEntry.m_wszILFileName = wszFileName; mapEntry.m_wszNIFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszNIFileName; } m_pTrustedPlatformAssemblyMap->AddOrReplace(mapEntry); } // // Parse PlatformResourceRoots // sPlatformResourceRoots.Normalize(); for (SString::Iterator i = sPlatformResourceRoots.Begin(); i != sPlatformResourceRoots.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sPlatformResourceRoots, i, pathName)); if (pathResult == S_FALSE) { break; } if (Path::IsRelative(pathName)) { GO_WITH_HRESULT(E_INVALIDARG); } m_platformResourceRoots.Append(pathName); } // // Parse AppPaths // sAppPaths.Normalize(); for (SString::Iterator i = sAppPaths.Begin(); i != sAppPaths.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sAppPaths, i, pathName)); if (pathResult == S_FALSE) { break; } if (Path::IsRelative(pathName)) { GO_WITH_HRESULT(E_INVALIDARG); } m_appPaths.Append(pathName); } Exit: return hr; } HRESULT ApplicationContext::GetAssemblyIdentity(LPCSTR szTextualIdentity, AssemblyIdentityUTF8 **ppAssemblyIdentity) { HRESULT hr = S_OK; _ASSERTE(szTextualIdentity != NULL); _ASSERTE(ppAssemblyIdentity != NULL); CRITSEC_Holder contextLock(GetCriticalSectionCookie()); AssemblyIdentityUTF8 *pAssemblyIdentity = m_assemblyIdentityCache.Lookup(szTextualIdentity); if (pAssemblyIdentity == NULL) { NewHolder<AssemblyIdentityUTF8> pNewAssemblyIdentity; SString sTextualIdentity; SAFE_NEW(pNewAssemblyIdentity, AssemblyIdentityUTF8); sTextualIdentity.SetUTF8(szTextualIdentity); IF_FAIL_GO(TextualIdentityParser::Parse(sTextualIdentity, pNewAssemblyIdentity)); IF_FAIL_GO(m_assemblyIdentityCache.Add(szTextualIdentity, pNewAssemblyIdentity)); pNewAssemblyIdentity->PopulateUTF8Fields(); pAssemblyIdentity = pNewAssemblyIdentity.Extract(); } *ppAssemblyIdentity = pAssemblyIdentity; Exit: return hr; } bool ApplicationContext::IsTpaListProvided() { return m_pTrustedPlatformAssemblyMap != nullptr; } };
4,054
1,738
<filename>dev/Code/Sandbox/Plugins/DeploymentTool/Tests/DeploymentToolTestsJsonPreProcessor.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "DeploymentTool_precompiled.h" #ifdef AZ_TESTS_ENABLED #include <AzTest/AzTest.h> #include "../JsonPreProcessor.h" #include <AzCore/Memory/SystemAllocator.h> #include <AzFramework/StringFunc/StringFunc.h> namespace DeployTool { class DeploymentToolTestsJsonPreProcessor : public ::testing::Test { public: AZ_TEST_CLASS_ALLOCATOR(DeploymentToolTestsJsonPreProcessor); void SetUp() override { AZ::AllocatorInstance<AZ::SystemAllocator>::Create(); } void TearDown() override { AZ::AllocatorInstance<AZ::SystemAllocator>::Destroy(); } }; TEST_F(DeploymentToolTestsJsonPreProcessor, DeploymentToolTestsJsonPreProcessor_CommentMarkerInString) { AZStd::string testInput = "{\n" "\"foo\": \"b#ar\" # hello\n" "}\n"; AZStd::string testOutput = "{\n" "\"foo\": \"b#ar\" \n" "}\n"; JsonPreProcessor jsonPreProcessor(testInput.c_str()); ASSERT_TRUE(AzFramework::StringFunc::Equal(testOutput.c_str(), jsonPreProcessor.GetResult().c_str())); } TEST_F(DeploymentToolTestsJsonPreProcessor, DeploymentToolTestsJsonPreProcessor_AdvancedComments) { AZStd::string testInput = "\"astronauts\": [\n" " \"<NAME>\", # <NAME> was the first person to walk on the Moon.\n" " \"<NAME>\", # Buzz Aldrin was the second person to walk on the Moon.\n" " \"<NAME>\" # <NAME> was the first American woman in space.\n" "]\n"; AZStd::string testOutput = "\"astronauts\": [\n" " \"<NAME>\", \n" " \"<NAME>\", \n" " \"<NAME>\" \n" "]\n"; JsonPreProcessor jsonPreProcessor(testInput.c_str()); ASSERT_TRUE(AzFramework::StringFunc::Equal(testOutput.c_str(), jsonPreProcessor.GetResult().c_str())); } TEST_F(DeploymentToolTestsJsonPreProcessor, DeploymentToolTestsJsonPreProcessor_Empty) { AZStd::string testInput = ""; AZStd::string testOutput = ""; JsonPreProcessor jsonPreProcessor(testInput.c_str()); ASSERT_TRUE(AzFramework::StringFunc::Equal(testOutput.c_str(), jsonPreProcessor.GetResult().c_str())); } TEST_F(DeploymentToolTestsJsonPreProcessor, DeploymentToolTestsJsonPreProcessor_CommentAllOneLine) { AZStd::string testInput = "{} # empty one no line feed"; AZStd::string testOutput = "{} "; JsonPreProcessor jsonPreProcessor(testInput.c_str()); ASSERT_TRUE(AzFramework::StringFunc::Equal(testOutput.c_str(), jsonPreProcessor.GetResult().c_str())); } TEST_F(DeploymentToolTestsJsonPreProcessor, DeploymentToolTestsJsonPreProcessor_EscapedQuoteWithCommentMarker) { AZStd::string testInput = "{\"\\\"#foo\":\"bar\"}"; AZStd::string testOutput = "{\"\\\"#foo\":\"bar\"}"; JsonPreProcessor jsonPreProcessor(testInput.c_str()); ASSERT_TRUE(AzFramework::StringFunc::Equal(testOutput.c_str(), jsonPreProcessor.GetResult().c_str())); } } // namespace DeployTool #endif // AZ_TESTS_ENABLED
1,627
1,609
<gh_stars>1000+ # # Copyright (C) 2016 <NAME> # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # generates reference data for the PMI descriptors from rdkit import Chem from rdkit.Chem import AllChem import numpy as np def GetMoments(mol, includeWeights): conf = mol.GetConformer() if includeWeights: masses = np.array([x.GetMass() for x in mol.GetAtoms()]) else: masses = [1.0] * mol.GetNumAtoms() ps = conf.GetPositions() mps = [x*y for x,y in zip(ps,masses)] centroid = np.sum(mps,axis=0)/sum(masses) cps = ps - centroid xx = xy = xz = yy = yz = zz = 0.0 for m,p in zip(masses,cps): xx += m*(p[1]*p[1] + p[2]*p[2]) yy += m*(p[0]*p[0] + p[2]*p[2]) zz += m*(p[1]*p[1] + p[0]*p[0]) xy -= m*p[0]*p[1] xz -= m*p[0]*p[2] yz -= m*p[1]*p[2] covm = np.array([[xx,xy,xz],[xy,yy,yz],[xz,yz,zz]]) res = np.linalg.eigvals(covm) return sorted(res) if __name__ == '__main__': suppl = Chem.SDMolSupplier('./PBF_egfr.sdf', removeHs=False) output = open('./PMI_egfr.out', 'w+') for m in suppl: i1, i2, i3 = GetMoments(m, True) mi1, mi2, mi3 = GetMoments(m, False) print("%s %.4f %.4f %.4f %.4f %.4f %.4f" % (m.GetProp("_Name"), i1, i2, i3, mi1, mi2, mi3), file=output)
677
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "macavf_player.hxx" #include "macavf_framegrabber.hxx" #include "macavf_window.hxx" #include <cmath> // for log10() using namespace ::com::sun::star; #include <hash_map> typedef std::hash_map<NSObject*,avmedia::macavf::MacAVObserverHandler*> HandlersForObject; @implementation MacAVObserverObject { HandlersForObject maHandlersForObject; } - (void)observeValueForKeyPath:(NSString*)pKeyPath ofObject:(id)pObject change:(NSDictionary*)pChangeDict context:(void*)pContext { NSString* pDictStr = [NSString stringWithFormat:@"%@", pChangeDict]; OSL_TRACE( "MacAVObserver::onKeyChange k=\"%s\" c=%s", [pKeyPath UTF8String], [pDictStr UTF8String]); avmedia::macavf::MacAVObserverHandler* pHandler = (avmedia::macavf::MacAVObserverHandler*)pContext; pHandler->handleObservation( pKeyPath ); } - (void)onNotification:(NSNotification*)pNotification { NSString* pNoteName = (NSString*)[pNotification name]; OSL_TRACE( "MacAVObserver::onNotification key=\"%s\"", [pNoteName UTF8String]); HandlersForObject::iterator it = maHandlersForObject.find( [pNotification object]); if( it != maHandlersForObject.end() ) (*it).second->handleObservation( pNoteName ); } - (void)setHandlerForObject:(NSObject*)pObject handler:(avmedia::macavf::MacAVObserverHandler*)pHandler { maHandlersForObject[ pObject] = pHandler; } - (void)removeHandlerForObject:(NSObject*)pObject { maHandlersForObject.erase( pObject); } @end namespace avmedia { namespace macavf { MacAVObserverObject* MacAVObserverHandler::mpMacAVObserverObject = NULL; MacAVObserverObject* MacAVObserverHandler::getObserver() const { if( !mpMacAVObserverObject) { mpMacAVObserverObject = [MacAVObserverObject alloc]; [mpMacAVObserverObject retain]; } return mpMacAVObserverObject; } // ---------------- // - Player - // ---------------- Player::Player( const uno::Reference< lang::XMultiServiceFactory >& rxMgr ) : mxMgr( rxMgr ) , mpPlayer( NULL ) , mfUnmutedVolume( 0 ) , mfStopTime( DBL_MAX ) , mbMuted( false ) , mbLooping( false ) {} // ------------------------------------------------------------------------------ Player::~Player() { if( !mpPlayer ) return; // remove the observers [mpPlayer removeObserver:getObserver() forKeyPath:@"currentItem.status"]; AVPlayerItem* pOldPlayerItem = [mpPlayer currentItem]; [[NSNotificationCenter defaultCenter] removeObserver:getObserver() name:AVPlayerItemDidPlayToEndTimeNotification object:pOldPlayerItem]; [getObserver() removeHandlerForObject:pOldPlayerItem]; // release the AVPlayer CFRelease( mpPlayer ); } // ------------------------------------------------------------------------------ bool Player::handleObservation( NSString* pKeyPath ) { OSL_TRACE( "AVPlayer::handleObservation key=\"%s\"", [pKeyPath UTF8String]); if( [pKeyPath isEqualToString:AVPlayerItemDidPlayToEndTimeNotification]) { OSL_TRACE( "AVPlayer replay=%d", mbLooping); if( mbLooping ) setMediaTime( 0.0); } return true; } // ------------------------------------------------------------------------------ bool Player::create( const ::rtl::OUString& rURL ) { // get the media asset NSString* aNSStr = [NSString stringWithCharacters:rURL.getStr() length:rURL.getLength()]; NSURL* aNSURL = [NSURL URLWithString: [aNSStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; // get the matching AVPlayerItem AVPlayerItem* pPlayerItem = [AVPlayerItem playerItemWithURL:aNSURL]; // create or update the AVPlayer with the new AVPlayerItem if( !mpPlayer ) { mpPlayer = [AVPlayer playerWithPlayerItem:pPlayerItem]; CFRetain( mpPlayer ); [mpPlayer setActionAtItemEnd:AVPlayerActionAtItemEndNone]; } else { // remove the obsoleted observers AVPlayerItem* pOldPlayerItem = [mpPlayer currentItem]; [mpPlayer removeObserver:getObserver() forKeyPath:@"currentItem.status"]; [getObserver() removeHandlerForObject:pOldPlayerItem]; [[NSNotificationCenter defaultCenter] removeObserver:getObserver() name:AVPlayerItemDidPlayToEndTimeNotification object:pOldPlayerItem]; // replace the playeritem [mpPlayer replaceCurrentItemWithPlayerItem:pPlayerItem]; } // observe the status of the current player item [mpPlayer addObserver:getObserver() forKeyPath:@"currentItem.status" options:0 context:this]; // observe playback-end needed for playback looping [[NSNotificationCenter defaultCenter] addObserver:getObserver() selector:@selector(onNotification:) name:AVPlayerItemDidPlayToEndTimeNotification object:pPlayerItem]; [getObserver() setHandlerForObject:pPlayerItem handler:this]; return true; } // ------------------------------------------------------------------------------ void SAL_CALL Player::start() throw (uno::RuntimeException) { if( !mpPlayer ) return; #if 0 const AVPlayerStatus eStatus = [mpPlayer status]; OSL_TRACE ("Player::start status=%d", (int)eStatus); if( eStatus == AVPlayerStatusReadyToPlay) #endif [mpPlayer play]; // else // TODO: delay until it becomes ready } // ------------------------------------------------------------------------------ void SAL_CALL Player::stop() throw (uno::RuntimeException) { if( !mpPlayer ) return; const bool bPlaying = isPlaying(); OSL_TRACE ("Player::stop() playing=%d", bPlaying); if( bPlaying ) [mpPlayer pause]; } // ------------------------------------------------------------------------------ sal_Bool SAL_CALL Player::isPlaying() throw (uno::RuntimeException) { if( !mpPlayer ) return false; const float fRate = [mpPlayer rate]; return (fRate != 0.0); } // ------------------------------------------------------------------------------ double SAL_CALL Player::getDuration() throw (uno::RuntimeException) { // slideshow checks for non-zero duration, so cheat here double duration = 0.01; if( mpPlayer ) { AVPlayerItem* pItem = [mpPlayer currentItem]; if( [pItem status] == AVPlayerItemStatusReadyToPlay ) duration = CMTimeGetSeconds( [pItem duration] ); else // fall back to AVAsset's best guess duration = CMTimeGetSeconds( [[pItem asset] duration] ); } return duration; } // ------------------------------------------------------------------------------ void SAL_CALL Player::setMediaTime( double fTime ) throw (uno::RuntimeException) { OSL_TRACE ("Player::setMediaTime( %.3fsec)", fTime); if( mpPlayer ) [mpPlayer seekToTime: CMTimeMakeWithSeconds(fTime,1000) ]; } // ------------------------------------------------------------------------------ double SAL_CALL Player::getMediaTime() throw (uno::RuntimeException) { if( !mpPlayer ) return 0.0; const double position = CMTimeGetSeconds( [mpPlayer currentTime] ); OSL_TRACE( "Player::getMediaTime() = %.3fsec", position); if( position >= mfStopTime ) if( isPlaying() ) stop(); return position; } // ------------------------------------------------------------------------------ void SAL_CALL Player::setStopTime( double fTime ) throw (uno::RuntimeException) { OSL_TRACE ("Player::setStopTime( %.3fsec)", fTime); mfStopTime = fTime; } // ------------------------------------------------------------------------------ double SAL_CALL Player::getStopTime() throw (uno::RuntimeException) { return mfStopTime; } // ------------------------------------------------------------------------------ void SAL_CALL Player::setRate( double fRate ) throw (uno::RuntimeException) { OSL_TRACE ("Player::setRate( %.3f)", fRate); if( !mpPlayer ) return; // playback rate: 0 = stop, 1 = normal speed, 2 = double speed, -1 = normal speed backwards [mpPlayer setRate: fRate]; } // ------------------------------------------------------------------------------ double SAL_CALL Player::getRate() throw (uno::RuntimeException) { // macavf: 0 = stop, 1 = normal speed, 2 = double speed, -1 = normal speed backwards const double fRate = mpPlayer ? (double)[mpPlayer rate] : 1.0; OSL_TRACE ("Player::getRate() = %.3f", fRate); return fRate; } // ------------------------------------------------------------------------------ void SAL_CALL Player::setPlaybackLoop( sal_Bool bSet ) throw (uno::RuntimeException) { OSL_TRACE ("Player::setPlaybackLoop( %d)", bSet ); mbLooping = bSet; } // ------------------------------------------------------------------------------ sal_Bool SAL_CALL Player::isPlaybackLoop() throw (uno::RuntimeException) { const bool bRet = mbLooping; OSL_TRACE ("Player::isPlaybackLoop() = %d", bRet ); return bRet; } // ------------------------------------------------------------------------------ void SAL_CALL Player::setMute( sal_Bool bSet ) throw (uno::RuntimeException) { OSL_TRACE( "Player::setMute(%d), was-muted: %d unmuted-volume: %.3f", bSet, mbMuted, mfUnmutedVolume ); if( !mpPlayer ) return; mbMuted = (bSet == TRUE); [mpPlayer setMuted:mbMuted]; } // ------------------------------------------------------------------------------ sal_Bool SAL_CALL Player::isMute() throw (uno::RuntimeException) { OSL_TRACE ("Player::isMuted() = %d", mbMuted); return mbMuted; } // ------------------------------------------------------------------------------ void SAL_CALL Player::setVolumeDB( sal_Int16 nVolumeDB ) throw (uno::RuntimeException) { // -40dB <-> AVPlayer volume 0.0 // 0dB <-> AVPlayer volume 1.0 mfUnmutedVolume = (nVolumeDB <= -40) ? 0.0 : pow( 10.0, nVolumeDB / 20.0 ); OSL_TRACE( "Player::setVolume(%ddB), muted=%d, unmuted-volume: %.3f", nVolumeDB, mbMuted, mfUnmutedVolume ); // change volume if( !mbMuted && mpPlayer ) [mpPlayer setVolume:mfUnmutedVolume]; } // ------------------------------------------------------------------------------ sal_Int16 SAL_CALL Player::getVolumeDB() throw (uno::RuntimeException) { if( !mpPlayer ) return 0; // get the actual volume const float fVolume = [mpPlayer volume]; // convert into Dezibel value // -40dB <-> AVPlayer volume 0.0 // 0dB <-> AVPlayer volume 1.0 const int nVolumeDB = (fVolume <= 0) ? -40 : lrint( 20.0*log10(fVolume)); return (sal_Int16)nVolumeDB; } // ------------------------------------------------------------------------------ awt::Size SAL_CALL Player::getPreferredPlayerWindowSize() throw (uno::RuntimeException) { awt::Size aSize( 0, 0 ); // default size AVAsset* pMovie = [[mpPlayer currentItem] asset]; NSArray* pVideoTracks = [pMovie tracksWithMediaType:AVMediaTypeVideo]; AVAssetTrack* pFirstVideoTrack = (AVAssetTrack*)[pVideoTracks firstObject]; if( pFirstVideoTrack ) { const CGSize aPrefSize = [pFirstVideoTrack naturalSize]; aSize = awt::Size( aPrefSize.width, aPrefSize.height ); } return aSize; } // ------------------------------------------------------------------------------ uno::Reference< ::media::XPlayerWindow > SAL_CALL Player::createPlayerWindow( const uno::Sequence< uno::Any >& aArguments ) throw (uno::RuntimeException) { // get the preferred window size const awt::Size aSize( getPreferredPlayerWindowSize() ); OSL_TRACE( "Player::createPlayerWindow %dx%d argsLength: %d", aSize.Width, aSize.Height, aArguments.getLength() ); // get the parent view sal_IntPtr nNSViewPtr = NULL; aArguments[0] >>= nNSViewPtr; NSView* pParentView = reinterpret_cast<NSView*>(nNSViewPtr); // check the window parameters uno::Reference< ::media::XPlayerWindow > xRet; if( (aSize.Width <= 0) || (aSize.Height <= 0) || (pParentView == NULL) ) return xRet; // create the window ::avmedia::macavf::Window* pWindow = new ::avmedia::macavf::Window( mxMgr, *this, pParentView ); xRet = pWindow; return xRet; } // ------------------------------------------------------------------------------ uno::Reference< media::XFrameGrabber > SAL_CALL Player::createFrameGrabber() throw (uno::RuntimeException) { uno::Reference< media::XFrameGrabber > xRet; OSL_TRACE ("Player::createFrameGrabber"); FrameGrabber* pGrabber = new FrameGrabber( mxMgr ); AVAsset* pMovie = [[mpPlayer currentItem] asset]; if( pGrabber->create( pMovie ) ) xRet = pGrabber; return xRet; } // ------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL Player::getImplementationName( ) throw (uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( AVMEDIA_MACAVF_PLAYER_IMPLEMENTATIONNAME ) ); } // ------------------------------------------------------------------------------ sal_Bool SAL_CALL Player::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( AVMEDIA_MACAVF_PLAYER_SERVICENAME ) ); } // ------------------------------------------------------------------------------ uno::Sequence< ::rtl::OUString > SAL_CALL Player::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( AVMEDIA_MACAVF_PLAYER_SERVICENAME ) ); return aRet; } } // namespace macavf } // namespace avmedia
4,891
448
<filename>FileDownloaderDemo2/src/main/java/org/wlf/filedownloader_demo2/custom_model/CustomVideoInfo.java package org.wlf.filedownloader_demo2.custom_model; import android.util.Log; import org.wlf.filedownloader.DownloadFileInfo; import org.wlf.filedownloader.FileDownloader; import org.wlf.filedownloader.listener.OnDownloadFileChangeListener; /** * the custom model about the network resource(this example is an video play info) * * @author wlf(Andy) * @datetime 2015-12-05 10:15 GMT+8 * @email <EMAIL> */ public class CustomVideoInfo implements OnDownloadFileChangeListener { private Integer mId;//the id of the video private String mUrl;//the url of the video private String mStartTime;//the start time of the video,yyyy-MM-dd HH:mm:ss private String mEndTime;//the end time of the video,yyyy-MM-dd HH:mm:ss private DownloadFileInfo mDownloadFileInfo; public CustomVideoInfo(Integer id, String url, String startTime, String endTime) { mId = id; mUrl = url; mStartTime = startTime; mEndTime = endTime; init(); } /** * init resources */ private void init() { // register DownloadFileChangeListener FileDownloader.registerDownloadFileChangeListener(this); // init DownloadFileInfo if has been downloaded mDownloadFileInfo = FileDownloader.getDownloadFile(mUrl); } /** * release resources */ public void release() { // unregister FileDownloader.unregisterDownloadFileChangeListener(this); } // getters public Integer getId() { return mId; } public String getUrl() { return mUrl; } public String getStartTime() { return mStartTime; } public String getEndTime() { return mEndTime; } public DownloadFileInfo getDownloadFileInfo() { return mDownloadFileInfo; } @Override public void onDownloadFileCreated(DownloadFileInfo downloadFileInfo) { if (downloadFileInfo != null && downloadFileInfo.getUrl() != null && downloadFileInfo.getUrl().equals(mUrl)) { this.mDownloadFileInfo = downloadFileInfo; Log.e("wlf", "onDownloadFileCreated,downloadFileInfo:" + downloadFileInfo); } } @Override public void onDownloadFileUpdated(DownloadFileInfo downloadFileInfo, Type type) { if (downloadFileInfo != null && downloadFileInfo.getUrl() != null && downloadFileInfo.getUrl().equals(mUrl)) { this.mDownloadFileInfo = downloadFileInfo; Log.e("wlf", "onDownloadFileUpdated,downloadFileInfo:" + downloadFileInfo); } } @Override public void onDownloadFileDeleted(DownloadFileInfo downloadFileInfo) { if (downloadFileInfo != null && downloadFileInfo.getUrl() != null && downloadFileInfo.getUrl().equals(mUrl)) { this.mDownloadFileInfo = null; Log.e("wlf", "onDownloadFileDeleted,downloadFileInfo:" + downloadFileInfo); } } }
1,128
14,425
<reponame>bzhaoopenstack/hadoop /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation; import java.util.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.server.api.ContainerLogAggregationPolicy; import org.apache.hadoop.yarn.server.api.ContainerLogContext; import org.apache.hadoop.yarn.server.api.ContainerType; /** * The sample policy samples logs of successful worker containers to aggregate. * It always aggregates AM container and failed/killed worker * containers' logs. To make sure small applications have enough logs, it only * applies sampling beyond minimal number of containers. The parameters can be * configured by SAMPLE_RATE and MIN_THRESHOLD. For example if SAMPLE_RATE is * 0.2 and MIN_THRESHOLD is 20, for an application with 100 successful * worker containers, 20 + (100-20) * 0.2 = 36 containers's logs will be * aggregated. */ @Private public class SampleContainerLogAggregationPolicy implements ContainerLogAggregationPolicy { private static final Logger LOG = LoggerFactory.getLogger(SampleContainerLogAggregationPolicy.class); static String SAMPLE_RATE = "SR"; public static final float DEFAULT_SAMPLE_RATE = 0.2f; static String MIN_THRESHOLD = "MIN"; public static final int DEFAULT_SAMPLE_MIN_THRESHOLD = 20; private float sampleRate = DEFAULT_SAMPLE_RATE; private int minThreshold = DEFAULT_SAMPLE_MIN_THRESHOLD; static public String buildParameters(float sampleRate, int minThreshold) { StringBuilder sb = new StringBuilder(); sb.append(SAMPLE_RATE).append(":").append(sampleRate).append(","). append(MIN_THRESHOLD).append(":").append(minThreshold); return sb.toString(); } // Parameters are comma separated properties, for example // "SR:0.5,MIN:50" public void parseParameters(String parameters) { Collection<String> params = StringUtils.getStringCollection(parameters); for(String param : params) { // The first element is the property name. // The second element is the property value. String[] property = StringUtils.getStrings(param, ":"); if (property == null || property.length != 2) { continue; } if (property[0].equals(SAMPLE_RATE)) { try { float sampleRate = Float.parseFloat(property[1]); if (sampleRate >= 0.0 && sampleRate <= 1.0) { this.sampleRate = sampleRate; } else { LOG.warn("The format isn't valid. Sample rate falls back to the " + "default value " + DEFAULT_SAMPLE_RATE); } } catch (NumberFormatException nfe) { LOG.warn("The format isn't valid. Sample rate falls back to the " + "default value " + DEFAULT_SAMPLE_RATE); } } else if (property[0].equals(MIN_THRESHOLD)) { try { int minThreshold = Integer.parseInt(property[1]); if (minThreshold >= 0) { this.minThreshold = minThreshold; } else { LOG.warn("The format isn't valid. Min threshold falls back to " + "the default value " + DEFAULT_SAMPLE_MIN_THRESHOLD); } } catch (NumberFormatException nfe) { LOG.warn("The format isn't valid. Min threshold falls back to the " + "default value " + DEFAULT_SAMPLE_MIN_THRESHOLD); } } } } public boolean shouldDoLogAggregation(ContainerLogContext logContext) { if (logContext.getContainerType() == ContainerType.APPLICATION_MASTER || logContext.getExitCode() != 0) { // If it is AM or failed or killed container, enable log aggregation. return true; } // Only sample log aggregation for large applications. // We assume the container id is continuously allocated from number 1 and // Worker containers start from id 2. So logs of worker containers with ids // in [2, minThreshold + 1] will be aggregated. if ((logContext.getContainerId().getContainerId() & ContainerId.CONTAINER_ID_BITMASK) < minThreshold + 2) { return true; } // Sample log aggregation for the rest of successful worker containers return (sampleRate != 0 && logContext.getContainerId().hashCode() % (1/sampleRate) == 0); } }
1,794