max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
335
<filename>G/Grave_noun.json { "word": "Grave", "definitions": [ "A hole dug in the ground to receive a coffin or dead body, typically marked by a stone or mound.", "Used as an allusive term for death.", "A place where a broken or discarded object lies." ], "parts-of-speech": "Noun" }
124
346
#include "DefaultStrategicAIPolicy.h" #include "GameSettings.h" #include "JsonObject.h" #include <array> #include <string_theory/string> template<typename T> static std::array<T, NUM_DIF_LEVELS> ReadSAIPolicy(const rapidjson::Document& json, const std::string& key) { static_assert(std::is_integral<T>::value); return std::array<T, NUM_DIF_LEVELS> { json[(key + "_easy" ).c_str()].Get<T>(), json[(key + "_medium").c_str()].Get<T>(), json[(key + "_hard" ).c_str()].Get<T>() }; } DefaultStrategicAIPolicy::DefaultStrategicAIPolicy(rapidjson::Document* json) { queens_pool_of_troops = ReadSAIPolicy<unsigned int>(*json, "queens_pool_of_troops"); initial_garrison_percentages = ReadSAIPolicy<unsigned int>(*json, "initial_garrison_percentages"); min_enemy_group_size = ReadSAIPolicy<unsigned int>(*json, "min_enemy_group_size"); enemy_starting_alert_level = ReadSAIPolicy<unsigned int>(*json, "enemy_starting_alert_level"); enemy_starting_alert_decay = ReadSAIPolicy<unsigned int>(*json, "enemy_starting_alert_decay"); time_evaluate_in_minutes = ReadSAIPolicy<unsigned int>(*json, "time_evaluate_in_minutes"); time_evaluate_variance = ReadSAIPolicy<int> (*json, "time_evaluate_variance"); grace_period_in_hours = ReadSAIPolicy<unsigned int>(*json, "grace_period_in_hours"); patrol_grace_period_in_days = ReadSAIPolicy<unsigned int>(*json, "patrol_grace_period_in_days"); num_aware_battles = ReadSAIPolicy<unsigned int>(*json, "num_aware_battles"); JsonObjectReader r(*json); refill_defeated_patrol_groups = r.getOptionalBool("refill_defeated_patrol_groups", false); }
651
7,470
{"index":11,"lineNumber":1,"column":12,"message":"Error: Line 1: let is disallowed as a lexically bound name","description":"let is disallowed as a lexically bound name"}
45
305
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <variant> // GCC 5 pretends it supports C++17, but it doesn't properly support it, and // <variant> fails. // UNSUPPORTED: gcc-5 #include <variant> #include "test_macros.h" #ifndef _LIBCPP_VERSION #error _LIBCPP_VERSION not defined #endif int main(int, char**) { return 0; }
193
8,768
#define DISQUE_VERSION "1.0-rc1"
16
716
/* * 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 * */ /* clang-format off */ /* getdat3f.c - Implements getdat subroutine. */ #if defined(WIN64) || defined(WIN32) #include <windows.h> #include "ent3f.h" void ENT3F(GETDAT, getdat)(unsigned short *iyr, unsigned short *imon, unsigned short *iday) { SYSTEMTIME st; GetLocalTime(&st); /* gets current time */ *iyr = st.wYear; *imon = st.wMonth; *iday = st.wDay; } void ENT3F(GETDAT4, getdat4)(int *iyr, int *imon, int *iday) { SYSTEMTIME st; GetLocalTime(&st); /* gets current time */ *iyr = st.wYear; *imon = st.wMonth; *iday = st.wDay; } void ENT3F(GETDAT8, getdat8)(long long *iyr, long long *imon, long long *iday) { SYSTEMTIME st; GetLocalTime(&st); /* gets current time */ *iyr = st.wYear; *imon = st.wMonth; *iday = st.wDay; } #endif
417
590
<filename>src/arch/arm32/mach-f1c100s/include/f1c100s-dma.h #ifndef __F1C100S_DMA_H__ #define __F1C100S_DMA_H__ #ifdef __cplusplus extern "C" { #endif #define F1C100S_NDMA_CHANNEL0 (0) #define F1C100S_NDMA_CHANNEL1 (1) #define F1C100S_NDMA_CHANNEL2 (2) #define F1C100S_NDMA_CHANNEL3 (3) #define F1C100S_DDMA_CHANNEL0 (4) #define F1C100S_DDMA_CHANNEL1 (5) #define F1C100S_DDMA_CHANNEL2 (6) #define F1C100S_DDMA_CHANNEL3 (7) #define F1C100S_NDMA_PORT_IR (0) #define F1C100S_NDMA_PORT_OWA (1) #define F1C100S_NDMA_PORT_SPI0 (4) #define F1C100S_NDMA_PORT_SPI1 (5) #define F1C100S_NDMA_PORT_UART0 (8) #define F1C100S_NDMA_PORT_UART1 (9) #define F1C100S_NDMA_PORT_UART2 (10) #define F1C100S_NDMA_PORT_AUDIO (12) #define F1C100S_NDMA_PORT_TP (13) #define F1C100S_NDMA_PORT_DAUDIO (14) #define F1C100S_NDMA_PORT_SRAM (16) #define F1C100S_NDMA_PORT_SDRAM (17) #define F1C100S_NDMA_PORT_USB (20) #define F1C100S_NDMA_PORT_USB_EP1 (21) #define F1C100S_NDMA_PORT_USB_EP2 (22) #define F1C100S_NDMA_PORT_USB_EP3 (23) #define F1C100S_DDMA_PORT_SRAM (0) #define F1C100S_DDMA_PORT_SDRAM (1) #define F1C100S_DDMA_PORT_LCD (2) #define F1C100S_DDMA_PORT_USB (4) #define F1C100S_DDMA_PORT_AHB (9) #ifdef __cplusplus } #endif #endif /* __F1C100S_DMA_H__ */
732
648
{ "lists": { "makePrivate": { "notLoggedIn": "Du musst eingeloggt sein, um Listen zu erstellen.", "lastPublicList": "Du kannst die letzte öffentliche Liste nicht auf privat ändern." }, "makePublic": { "notLoggedIn": "Du musst eingeloggt sein.", "accessDenied": "Du hast keine Berechtigung, um diese Liste zu bearbeiten." }, "updateName": { "accessDenied": "Du hast keine Berechtigung, um diese Liste zu bearbeiten." }, "remove": { "accessDenied": "Du hast keine Berechtigung, um diese Liste zu löschen.", "lastPublicList": "Du kannst die letzte öffentliche Liste nicht löschen.", "confirm": "Bist du sicher, dass du diese Liste löschen willst?" }, "show": { "cancel": "Abbrechen", "showMenu": "Menü anzeigen", "selectAction": "Aktion wählen", "makePublic": "Öffentlich machen", "makePrivate": "Privat machen", "delete": "Löschen", "makeListPublic": "Liste öffentlich machen", "makeListPrivate": "Liste privat machen", "deleteList": "Liste löschen", "typeToAdd": "Text einfügen, um eine neue Aufgabe zu erstellen", "noTasks": "Keine Aufgaben", "addAbove": "Um eine neue Aufgabe zu erstellen, benutze das obere Feld", "loading": "Lade Aufgaben…" }, "insert": { "list": "Liste" } }, "todos": { "insert": { "accessDenied": "Du kannst keine Aufgaben zu einer privaten Liste hinzufügen, die nicht dir gehört" }, "setCheckedStatus": { "accessDenied": "Du kannst keine Aufgaben in einer privaten Liste ändern, die nicht dir gehört" }, "updateText": { "accessDenied": "Du kannst keine Aufgaben in einer privaten Liste ändern, die nicht dir gehört" }, "remove": { "accessDenied": "Du kannst keine Aufgaben von einer privaten Liste löschen, die nicht dir gehört" }, "item": { "taskName": "Bezeichnung der Aufgabe" } }, "useraccounts": { "atTitle": { "subtitle": "Nur eingeloggte Benutzer können private Listen erstellen" } }, "layouts": { "appBody": { "logout": "Ausloggen", "login": "Einloggen", "join": "Registrieren", "newList": "Neue Liste", "newListError": "Liste konnte nicht erstellt werden.", "tryingToConnect": "Verbindung wird hergestellt", "connectionIssue": "Verbindungsprobleme" } }, "pages": { "appNotFound": { "pageNotFound": "Seite konnte nicht gefunden werden" } } }
1,174
2,151
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_CAPTURE_VIDEO_ANDROID_VIDEO_CAPTURE_DEVICE_FACTORY_ANDROID_H_ #define MEDIA_CAPTURE_VIDEO_ANDROID_VIDEO_CAPTURE_DEVICE_FACTORY_ANDROID_H_ #include "media/capture/video/video_capture_device_factory.h" #include <jni.h> #include "base/android/scoped_java_ref.h" #include "base/macros.h" #include "media/capture/video/video_capture_device.h" namespace media { // VideoCaptureDeviceFactory on Android. This class implements the static // VideoCapture methods and the factory of VideoCaptureAndroid. class CAPTURE_EXPORT VideoCaptureDeviceFactoryAndroid : public VideoCaptureDeviceFactory { public: static base::android::ScopedJavaLocalRef<jobject> createVideoCaptureAndroid( int id, jlong nativeVideoCaptureDeviceAndroid); VideoCaptureDeviceFactoryAndroid() : test_mode_(false) {} ~VideoCaptureDeviceFactoryAndroid() override {} std::unique_ptr<VideoCaptureDevice> CreateDevice( const VideoCaptureDeviceDescriptor& device_descriptor) override; void GetDeviceDescriptors( VideoCaptureDeviceDescriptors* device_descriptors) override; void GetSupportedFormats(const VideoCaptureDeviceDescriptor& device, VideoCaptureFormats* supported_formats) override; static bool IsLegacyOrDeprecatedDevice(const std::string& device_id); // Configures all subsequent CreateDevice()s in test mode. void ConfigureForTesting() { test_mode_ = true; } private: // Switch to indicate that all created Java capturers will be in test mode. bool test_mode_; DISALLOW_COPY_AND_ASSIGN(VideoCaptureDeviceFactoryAndroid); }; } // namespace media #endif // MEDIA_CAPTURE_VIDEO_ANDROID_VIDEO_CAPTURE_DEVICE_FACTORY_ANDROID_H_
602
3,212
<reponame>YolandaMDavis/nifi<filename>nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-site-to-site/src/main/java/org/apache/nifi/remote/PeerDescriptionModifier.java<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.nifi.remote; import org.apache.nifi.attribute.expression.language.EvaluationContext; import org.apache.nifi.attribute.expression.language.PreparedQuery; import org.apache.nifi.attribute.expression.language.Query; import org.apache.nifi.attribute.expression.language.StandardEvaluationContext; import org.apache.nifi.attribute.expression.language.exception.AttributeExpressionLanguageParsingException; import org.apache.nifi.remote.protocol.SiteToSiteTransportProtocol; import org.apache.nifi.util.NiFiProperties; import org.apache.nifi.util.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.lang.String.format; import static org.apache.commons.lang3.StringUtils.isBlank; public class PeerDescriptionModifier { private static final Logger logger = LoggerFactory.getLogger(PeerDescriptionModifier.class); public enum RequestType { SiteToSiteDetail, Peers } private static class Route { private String name; private SiteToSiteTransportProtocol protocol; private PreparedQuery predicate; private PreparedQuery hostname; private PreparedQuery port; private PreparedQuery secure; private Route validate() { if (hostname == null) { throw new IllegalArgumentException( format("Found an invalid Site-to-Site route definition [%s] 'hostname' is not specified.", name)); } if (port == null) { throw new IllegalArgumentException( format("Found an invalid Site-to-Site route definition [%s] 'port' is not specified.", name)); } return this; } private PeerDescription getTarget(final Map<String, String> variables) { final EvaluationContext evaluationContext = new StandardEvaluationContext(variables); final String targetHostName = hostname.evaluateExpressions(evaluationContext, null); if (isBlank(targetHostName)) { throw new IllegalStateException("Target hostname was not resolved for the route definition " + name); } final String targetPortStr = port.evaluateExpressions(evaluationContext, null); if (isBlank(targetPortStr)) { throw new IllegalStateException("Target port was not resolved for the route definition " + name); } final String targetIsSecure = secure == null ? null : secure.evaluateExpressions(evaluationContext, null); return new PeerDescription(targetHostName, Integer.valueOf(targetPortStr), Boolean.valueOf(targetIsSecure)); } } private Map<SiteToSiteTransportProtocol, List<Route>> routes; private static final String PROPERTY_PREFIX = "nifi.remote.route."; private static final Pattern PROPERTY_REGEX = Pattern.compile("^nifi\\.remote\\.route\\.(raw|http)\\.([^.]+)\\.(when|hostname|port|secure)$"); public PeerDescriptionModifier(final NiFiProperties properties) { final Map<Tuple<String, String>, List<Tuple<String, String>>> routeDefinitions = properties.getPropertyKeys().stream() .filter(propertyKey -> propertyKey.startsWith(PROPERTY_PREFIX)) .map(propertyKey -> { final Matcher matcher = PROPERTY_REGEX.matcher(propertyKey); if (!matcher.matches()) { throw new IllegalArgumentException( format("Found an invalid Site-to-Site route definition property '%s'." + " Routing property keys should be formatted as 'nifi.remote.route.{protocol}.{name}.{routingConfigName}'." + " Where {protocol} is 'raw' or 'http', and {routingConfigName} is 'when', 'hostname', 'port' or 'secure'.", propertyKey)); } return matcher; }) .collect(Collectors.groupingBy(matcher -> new Tuple<>(matcher.group(1), matcher.group(2)), Collectors.mapping(matcher -> new Tuple<>(matcher.group(3), matcher.group(0)), Collectors.toList()))); routes = routeDefinitions.entrySet().stream().map(routeDefinition -> { final Route route = new Route(); // E.g. [raw, example1], [http, example2] final Tuple<String, String> protocolAndRoutingName = routeDefinition.getKey(); route.protocol = SiteToSiteTransportProtocol.valueOf(protocolAndRoutingName.getKey().toUpperCase()); route.name = protocolAndRoutingName.getValue(); routeDefinition.getValue().forEach(routingConfigNameAndPropertyKey -> { final String routingConfigName = routingConfigNameAndPropertyKey.getKey(); final String propertyKey = routingConfigNameAndPropertyKey.getValue(); final String routingConfigValue = properties.getProperty(propertyKey); try { switch (routingConfigName) { case "when": route.predicate = Query.prepare(routingConfigValue); break; case "hostname": route.hostname = Query.prepare(routingConfigValue); break; case "port": route.port = Query.prepare(routingConfigValue); break; case "secure": route.secure = Query.prepare(routingConfigValue); break; } } catch (AttributeExpressionLanguageParsingException e) { throw new IllegalArgumentException(format("Failed to parse NiFi expression language configured" + " for Site-to-Site routing property at '%s' due to '%s'", propertyKey, e.getMessage()), e); } }); return route; }).map(Route::validate).collect(Collectors.groupingBy(r -> r.protocol)); } private void addVariables(Map<String, String> map, String prefix, PeerDescription peer) { map.put(format("%s.hostname", prefix), peer.getHostname()); map.put(format("%s.port", prefix), String.valueOf(peer.getPort())); map.put(format("%s.secure", prefix), String.valueOf(peer.isSecure())); } public boolean isModificationNeeded(final SiteToSiteTransportProtocol protocol) { return routes != null && routes.containsKey(protocol) && !routes.get(protocol).isEmpty(); } /** * Modifies target peer description so that subsequent request can go through the appropriate route * @param source The source peer from which a request was sent, this can be any server host participated to relay the request, * but should be the one which can contribute to derive the correct target peer. * @param target The original target which should receive and process further incoming requests. * @param protocol The S2S protocol being used. * @param requestType The requested API type. * @param variables Containing context variables those can be referred from Expression Language. * @return A peer description. The original target peer can be returned if there is no intermediate peer such as reverse proxies needed. */ public PeerDescription modify(final PeerDescription source, final PeerDescription target, final SiteToSiteTransportProtocol protocol, final RequestType requestType, final Map<String, String> variables) { addVariables(variables, "s2s.source", source); addVariables(variables, "s2s.target", target); variables.put("s2s.protocol", protocol.name()); variables.put("s2s.request", requestType.name()); logger.debug("Modifying PeerDescription, variables={}", variables); return routes.get(protocol).stream().filter(r -> r.predicate == null || Boolean.valueOf(r.predicate.evaluateExpressions(new StandardEvaluationContext(variables), null))) .map(r -> { final PeerDescription t = r.getTarget(variables); logger.debug("Route definition {} matched, {}", r.name, t); return t; }) // If a matched route was found, use it, else use the original target. .findFirst().orElse(target); } }
3,991
1,233
<filename>samples/scoping-samples/simple-stack-example-scoping-java/src/main/java/com/zhuinden/simplestackexamplescoping/features/words/WordListAdapter.java package com.zhuinden.simplestackexamplescoping.features.words; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.zhuinden.simplestackexamplescoping.R; import java.util.Collections; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.ViewHolder> { private List<String> words = Collections.emptyList(); public void updateWords(List<String> words) { this.words = words; notifyDataSetChanged(); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.word_list_item, parent, false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.bind(words.get(position)); } @Override public int getItemCount() { return words.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { private final TextView text; public ViewHolder(@NonNull View itemView) { super(itemView); text = itemView.findViewById(R.id.text); } public void bind(String word) { text.setText(word); } } }
630
2,313
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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 SRC_COMMON_ITENSORPACK_H_ #define SRC_COMMON_ITENSORPACK_H_ #include "arm_compute/core/ITensorPack.h" #include "src/common/IContext.h" struct AclTensorPack_ { arm_compute::detail::Header header{ arm_compute::detail::ObjectType::TensorPack, nullptr }; protected: AclTensorPack_() = default; ~AclTensorPack_() = default; }; namespace arm_compute { // Forward declaration class ITensor; class ITensorV2; /** Tensor packing service * * Class is responsible for creating and managing a collection of tensors. * Tensor packs can be passed to operators to be part of the mutable data of the execution. */ class TensorPack : public AclTensorPack_ { public: /** Constructor * * @param[in] ctx Context to be used */ explicit TensorPack(IContext *ctx); /** Destructor */ ~TensorPack(); /** Add tensor to the pack * * @param[in] tensor Tensor to add * @param[in] slot_id Slot identification in respect to the operator of the tensor to add * * @return Status code */ AclStatus add_tensor(ITensorV2 *tensor, int32_t slot_id); /** Pack size accessor * * @return Number of tensors registered to the pack */ size_t size() const; /** Checks if pack is empty * * @return True if empty else false */ bool empty() const; /** Checks if an object is valid * * @return True if valid else false */ bool is_valid() const; /** Get tensor of a given id from the pac * * @param[in] slot_id Slot identification of tensor to extract * * @return The pointer to the tensor if exist and is non-const else nullptr */ arm_compute::ITensor *get_tensor(int32_t slot_id); /** Get legacy tensor pack * * @return Legacy tensor pack */ arm_compute::ITensorPack &get_tensor_pack(); private: arm_compute::ITensorPack _pack; /**< Pack that currently redirects to the existing TensorPack */ }; /** Extract internal representation of a TensoPack * * @param[in] pack Opaque tensor pack pointer * * @return The internal representation as an TensorPack */ inline TensorPack *get_internal(AclTensorPack pack) { return static_cast<TensorPack *>(pack); } namespace detail { /** Check if an internal TensorPack is valid * * @param[in] pack Internal tensor pack to check * * @return A status code */ inline StatusCode validate_internal_pack(const TensorPack *pack) { if(pack == nullptr || !pack->is_valid()) { ARM_COMPUTE_LOG_ERROR_ACL("[TensorPack]: Invalid tensor pack object"); return StatusCode::InvalidArgument; } return StatusCode::Success; } } // namespace detail } // namespace arm_compute #endif /* SRC_COMMON_ITENSORPACK_H_ */
1,313
190,993
<gh_stars>1000+ /* Copyright 2021 The TensorFlow 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 "tensorflow/lite/kernels/shim/test_util.h" #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/interpreter.h" namespace tflite { namespace { TEST(TfliteTensorDebugString, Basic) { ::tflite::Interpreter interpreter; interpreter.AddTensors(3); interpreter.AllocateTensors(); auto t_int32 = UniqueTfLiteTensor(interpreter.tensor(0)); PopulateTfLiteTensor<int32_t>({1, 2, 3, 4, 5}, {5}, t_int32.get()); EXPECT_EQ("[1, 2, 3, 4, 5]", TfliteTensorDebugString(t_int32.get())); auto t_int64 = UniqueTfLiteTensor(interpreter.tensor(1)); PopulateTfLiteTensor<int32_t>({1, 2, 3, 4}, {2, 2}, t_int64.get()); EXPECT_EQ("[[1, 2], [3, 4]]", TfliteTensorDebugString(t_int64.get())); auto t_str = UniqueTfLiteTensor(interpreter.tensor(2)); PopulateTfLiteTensor<std::string>({"ab", "cde", "f"}, {1, 3}, t_str.get()); EXPECT_EQ("[[ab, cde, f]]", TfliteTensorDebugString(t_str.get())); } TEST(TfliteTensorDebugString, MaxVal) { ::tflite::Interpreter interpreter; interpreter.AddTensors(2); interpreter.AllocateTensors(); auto t_int32 = UniqueTfLiteTensor(interpreter.tensor(0)); PopulateTfLiteTensor<int32_t>({1, 2, 3, 4}, {4}, t_int32.get()); EXPECT_EQ("[1, 2, 3, 4]", TfliteTensorDebugString(t_int32.get(), /*max_values=*/4)); t_int32 = UniqueTfLiteTensor(interpreter.tensor(0)); PopulateTfLiteTensor<int32_t>({1, 2, 3, 4, 5}, {5}, t_int32.get()); EXPECT_EQ("[1, 2, 3, 4, ...]", TfliteTensorDebugString(t_int32.get(), /*max_values=*/4)); } } // namespace } // namespace tflite
875
4,756
/* * Copyright (C) 2020 The Libphonenumber 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 com.google.phonenumbers.migrator; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import com.google.common.collect.ImmutableMap; import com.google.i18n.phonenumbers.metadata.DigitSequence; import com.google.i18n.phonenumbers.metadata.RangeSpecification; import com.google.i18n.phonenumbers.metadata.table.Column; import com.google.i18n.phonenumbers.metadata.table.CsvTable; import com.google.i18n.phonenumbers.metadata.table.RangeKey; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class MigrationUtilsTest { private static final String TEST_DATA_PATH = "./src/test/java/com/google/phonenumbers/migrator/testing/testData/"; private static final Path RECIPES_PATH = Paths.get(TEST_DATA_PATH + "testRecipesFile.csv"); private static final String COUNTRY_CODE = "44"; private static final String VALID_TEST_NUMBER = "123"; @Test public void getCountryMigratableNumbers_expectNoMatches() throws IOException { String invalidTestNumber = "34"; MigrationJob job = MigrationFactory.createCustomRecipeMigration(invalidTestNumber, COUNTRY_CODE, MigrationFactory .importRecipes(Files.newInputStream(RECIPES_PATH))); Stream<MigrationEntry> noMatchesRange = MigrationUtils .getMigratableRangeByCountry(job.getRecipesRangeTable(), job.getCountryCode(), job.getMigrationEntries()); assertThat(noMatchesRange.collect(Collectors.toSet())).isEmpty(); } @Test public void getCountryMigratableNumbers_expectMatches() throws IOException { String numbersPath = TEST_DATA_PATH + "testNumbersFile.txt"; MigrationJob job = MigrationFactory .createCustomRecipeMigration(Paths.get(numbersPath), COUNTRY_CODE, MigrationFactory .importRecipes(Files.newInputStream(RECIPES_PATH))); Stream<MigrationEntry> matchesRange = MigrationUtils .getMigratableRangeByCountry(job.getRecipesRangeTable(), job.getCountryCode(), job.getMigrationEntries()); assertThat(matchesRange.collect(Collectors.toList())) .containsExactlyElementsIn(job.getMigrationEntries().collect(Collectors.toList())); } @Test public void getMigratableNumbers_invalidKey_expectException() throws IOException { RangeSpecification testRangeSpec = RangeSpecification.from(DigitSequence.of(VALID_TEST_NUMBER)); RangeKey invalidKey = RangeKey.create(testRangeSpec, Collections.singleton(3)); MigrationJob job = MigrationFactory.createCustomRecipeMigration(VALID_TEST_NUMBER, COUNTRY_CODE, MigrationFactory .importRecipes(Files.newInputStream(RECIPES_PATH))); try { MigrationUtils .getMigratableRangeByRecipe(job.getRecipesCsvTable(), invalidKey, job.getMigrationEntries()); Assert.fail("Expected RuntimeException and did not receive"); } catch (RuntimeException e) { assertThat(e).isInstanceOf(IllegalArgumentException.class); assertThat(e).hasMessageThat().contains(invalidKey.toString()); } } @Test public void getMigratableNumbers_validKey_expectNoExceptionAndNoMatches() throws IOException { RangeSpecification testRangeSpec = RangeSpecification.from(DigitSequence.of("12")); RangeKey validKey = RangeKey.create(testRangeSpec, Collections.singleton(5)); MigrationJob job = MigrationFactory.createCustomRecipeMigration(VALID_TEST_NUMBER, COUNTRY_CODE, MigrationFactory .importRecipes(Files.newInputStream(RECIPES_PATH))); assertThat(MigrationUtils .getMigratableRangeByRecipe(job.getRecipesCsvTable(), validKey, job.getMigrationEntries()) .collect(Collectors.toSet())) .isEmpty(); } @Test public void findMatchingRecipe_expectNoMatchingRecipe() throws IOException { MigrationJob job = MigrationFactory.createCustomRecipeMigration(VALID_TEST_NUMBER, COUNTRY_CODE, MigrationFactory .importRecipes(Files.newInputStream(RECIPES_PATH))); DigitSequence testNumberToMatch = DigitSequence.of("12"); assertThat(MigrationUtils .findMatchingRecipe(job.getRecipesCsvTable(), job.getCountryCode(), testNumberToMatch)) .isEmpty(); } @Test public void findMatchingRecipe_expectMatchingRecipe() throws IOException { MigrationJob job = MigrationFactory.createCustomRecipeMigration(VALID_TEST_NUMBER, COUNTRY_CODE, MigrationFactory .importRecipes(Files.newInputStream(RECIPES_PATH))); DigitSequence testNumberToMatch = DigitSequence.of("12345"); Optional<ImmutableMap<Column<?>, Object>> foundRecipe = MigrationUtils .findMatchingRecipe(job.getRecipesCsvTable(), job.getCountryCode(), testNumberToMatch); assertThat(foundRecipe).isPresent(); RangeSpecification oldFormat = RangeSpecification .parse((String) foundRecipe.get().get(RecipesTableSchema.OLD_FORMAT)); assertThat(oldFormat.matches(testNumberToMatch)).isTrue(); } }
1,943
5,937
<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma once #ifndef __XPSDEVSIMINTEROPPRINTERHANDLER_HPP__ #define __XPSDEVSIMINTEROPPRINTERHANDLER_HPP__ /*++ Abstract: Managed wrapper for Win32 XPS print APIs. This object wraps a printer handle and does gets, sets and enum operations. Implements IDisposable. The caller must call Dispose when done using the object. --*/ namespace MS { namespace Internal { namespace PrintWin32Thunk { using namespace System::IO; using namespace System::Security; using namespace System::Runtime::InteropServices; private ref class XpsDeviceSimulatingPrintThunkHandler : public PrinterThunkHandlerBase { public: XpsDeviceSimulatingPrintThunkHandler( String^ printerName ); property virtual Boolean IsInvalid { Boolean virtual get() override; } virtual Boolean ReleaseHandle( void ) override; virtual Int32 ThunkStartDocPrinter( DocInfoThree^ docInfo, PrintTicket^ printTicket ) override; virtual Boolean ThunkEndDocPrinter( void ) override; virtual Boolean ThunkAbortPrinter( void ) override; virtual void ThunkOpenSpoolStream( void ) override; virtual void ThunkCommitSpoolData( Int32 bytes ) override; virtual Boolean ThunkCloseSpoolStream( void ) override; virtual Int32 ThunkReportJobProgress( Int32 jobId, JobOperation jobOperation, System::Windows::Xps::Packaging::PackagingAction packagingAction ) override; property virtual int JobIdentifier { int get() override; } property virtual Stream^ SpoolStream { Stream^ get() override; } private: String^ printerName; Stream^ spoolerStream; IXpsPrintJob* xpsPrintJob; int jobIdentifier; }; } } } #endif
1,533
3,200
<filename>mindspore/ccsrc/runtime/device/ascend/ascend_launch_kernel.cc /** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "runtime/device/ascend/ascend_launch_kernel.h" #include "runtime/device/memory_manager.h" #include "runtime/device/ascend/ascend_memory_pool.h" #include "runtime/device/ascend/kernel_build_ascend.h" #include "runtime/device/ascend/kernel_select_ascend.h" namespace mindspore::device::ascend { void AscendLaunchKernel::FreeDeviceMem(void *addr) { AscendMemoryPool::GetInstance().FreeTensorMem(addr); } size_t AscendLaunchKernel::AlignSizeForLaunchKernel(size_t size) { return MemoryManager::GetCommonAlignSize(size); } uint8_t *AscendLaunchKernel::AllocDeviceMem(size_t size) { auto device_memory = AscendMemoryPool::GetInstance().AllocTensorMem(size); MS_EXCEPTION_IF_NULL(device_memory); return static_cast<uint8_t *>(device_memory); } void AscendLaunchKernel::KernelSelect(const std::shared_ptr<session::KernelGraph> &kernel_graph) { MS_EXCEPTION_IF_NULL(kernel_graph); auto node_list = kernel_graph->execution_order(); for (size_t i = 0; i < node_list.size(); ++i) { auto status = device::ascend::SelectKernelInfo(node_list[i]); if (status == ascend::kNoMatched) { MS_LOG(ERROR) << "Cnode name : " << node_list[i]->fullname_with_scope() << " kernel select failed"; } } } void AscendLaunchKernel::KernelBuild(const std::shared_ptr<session::KernelGraph> &kernel_graph) { MS_EXCEPTION_IF_NULL(kernel_graph); auto ret = device::ascend::KernelBuild(kernel_graph->execution_order()); if (!ret) { MS_LOG(ERROR) << "kernel build failed"; } } } // namespace mindspore::device::ascend
721
575
<filename>ash/projector/projector_ui_controller.cc<gh_stars>100-1000 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/projector/projector_ui_controller.h" #include "ash/projector/projector_controller_impl.h" #include "ash/projector/ui/projector_bar_view.h" #include "ash/public/cpp/toast_data.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/toast/toast_manager_impl.h" #include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/widget/widget.h" namespace ash { namespace { constexpr char kMarkedKeyIdeaToastId[] = "projector_marked_key_idea"; constexpr base::TimeDelta kToastDuration = base::TimeDelta::FromMilliseconds(2500); void ShowToast(const std::string& id, int message_id, base::TimeDelta duration) { DCHECK(Shell::Get()); DCHECK(Shell::Get()->toast_manager()); ToastData toast(id, l10n_util::GetStringUTF16(message_id), duration.InMilliseconds(), l10n_util::GetStringUTF16(IDS_ASH_TOAST_DISMISS_BUTTON)); Shell::Get()->toast_manager()->Show(toast); } void AddExcludedWindowToFastInkController(aura::Window* window) { DCHECK(window); Shell::Get()->laser_pointer_controller()->AddExcludedWindow(window); MarkerController::Get()->AddExcludedWindow(window); } void EnableLaserPointer(bool enabled) { auto* laser_pointer_controller = Shell::Get()->laser_pointer_controller(); DCHECK(laser_pointer_controller); Shell::Get()->laser_pointer_controller()->SetEnabled(enabled); } void EnableMarker(bool enabled) { auto* marker_controller = MarkerController::Get(); DCHECK(marker_controller); MarkerController::Get()->SetEnabled(enabled); } } // namespace ProjectorUiController::ProjectorUiController( ProjectorControllerImpl* projector_controller) : projector_controller_(projector_controller) { auto* laser_pointer_controller = Shell::Get()->laser_pointer_controller(); DCHECK(laser_pointer_controller); laser_pointer_controller_observation_.Observe(laser_pointer_controller); auto* marker_controller = MarkerController::Get(); DCHECK(marker_controller); marker_controller_observation_.Observe(marker_controller); projector_session_observation_.Observe( projector_controller->projector_session()); } ProjectorUiController::~ProjectorUiController() = default; void ProjectorUiController::ShowToolbar() { if (!projector_bar_widget_) { // Create the toolbar. projector_bar_widget_ = ProjectorBarView::Create(projector_controller_); projector_bar_view_ = static_cast<ProjectorBarView*>( projector_bar_widget_->GetContentsView()); AddExcludedWindowToFastInkController( projector_bar_widget_->GetNativeWindow()); } projector_bar_widget_->ShowInactive(); model_.SetBarEnabled(true); } void ProjectorUiController::CloseToolbar() { if (!projector_bar_widget_) return; ResetTools(); projector_bar_widget_->Close(); projector_bar_view_ = nullptr; model_.SetBarEnabled(false); } void ProjectorUiController::OnKeyIdeaMarked() { ShowToast(kMarkedKeyIdeaToastId, IDS_ASH_PROJECTOR_KEY_IDEA_MARKED, kToastDuration); } void ProjectorUiController::OnLaserPointerPressed() { auto* laser_pointer_controller = Shell::Get()->laser_pointer_controller(); DCHECK(laser_pointer_controller); EnableLaserPointer(!laser_pointer_controller->is_enabled()); } void ProjectorUiController::OnMarkerPressed() { auto* marker_controller = MarkerController::Get(); DCHECK(marker_controller); EnableMarker(!marker_controller->is_enabled()); } void ProjectorUiController::OnTranscription(const std::string& transcription, bool is_final) {} bool ProjectorUiController::IsToolbarVisible() const { return model_.bar_enabled(); } // TODO(llin): Refactor this logic into ProjectorTool and ProjectorToolManager. void ProjectorUiController::ResetTools() { // Reset laser pointer. EnableLaserPointer(false); // Reset marker. EnableMarker(false); } void ProjectorUiController::OnLaserPointerStateChanged(bool enabled) { // Disable marker if laser pointer is enabled; if (enabled) MarkerController::Get()->SetEnabled(false); if (projector_bar_view_) projector_bar_view_->OnLaserPointerStateChanged(enabled); } void ProjectorUiController::OnMarkerStateChanged(bool enabled) { // Disable laser pointer since marker if enabled; if (enabled) Shell::Get()->laser_pointer_controller()->SetEnabled(false); if (projector_bar_view_) projector_bar_view_->OnMarkerStateChanged(enabled); } void ProjectorUiController::OnProjectorSessionActiveStateChanged(bool active) { if (!active) MarkerController::Get()->Clear(); } } // namespace ash
1,702
7,353
<reponame>sh0tCa11er/lanternEnhancement /** * @file IndexedList.h * @author <NAME> <<EMAIL>> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author 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 AUTHOR 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. * * @section DESCRIPTION * * A data structure similar to a list, but with efficient index-based access. */ #ifndef BADVPN_INDEXEDLIST_H #define BADVPN_INDEXEDLIST_H #include <stddef.h> #include <stdint.h> #include <misc/offset.h> #include <misc/debug.h> #include <structure/CAvl.h> typedef struct IndexedList_s IndexedList; typedef struct IndexedListNode_s IndexedListNode; typedef IndexedListNode *IndexedList__tree_link; #include "IndexedList_tree.h" #include <structure/CAvl_decl.h> struct IndexedList_s { IndexedList__Tree tree; }; struct IndexedListNode_s { IndexedListNode *tree_child[2]; IndexedListNode *tree_parent; int8_t tree_balance; uint64_t tree_count; }; /** * Initializes the indexed list. * * @param o uninitialized list object to initialize */ static void IndexedList_Init (IndexedList *o); /** * Inserts a node into the indexed list. * * @param o indexed list to insert into * @param node uninitialized node to insert * @param index index to insert at (starting with zero). Any existing elements * at or after this index will be shifted forward, i.e. their * indices will be incremented by one. Must be <=count. */ static void IndexedList_InsertAt (IndexedList *o, IndexedListNode *node, uint64_t index); /** * Removes a nove from the indexed list. * * @param o indexed list to remove from * @param node node in the list to remove */ static void IndexedList_Remove (IndexedList *o, IndexedListNode *node); /** * Returns the number of nodes in the indexed list. * * @param o indexed list * @return number of nodes */ static uint64_t IndexedList_Count (IndexedList *o); /** * Returns the index of a node in the indexed list. * * @param o indexed list * @param node node in the list to get index of * @return index of the node */ static uint64_t IndexedList_IndexOf (IndexedList *o, IndexedListNode *node); /** * Returns the node at the specified index in the indexed list. * * @param o indexed list * @param index index of the node to return. Must be < count. * @return node at the specified index */ static IndexedListNode * IndexedList_GetAt (IndexedList *o, uint64_t index); /** * Returns the first node, or NULL if the list is empty. * * @param o indexed list * @return first node, or NULL */ static IndexedListNode * IndexedList_GetFirst (IndexedList *o); /** * Returns the last node, or NULL if the list is empty. * * @param o indexed list * @return last node, or NULL */ static IndexedListNode * IndexedList_GetLast (IndexedList *o); /** * Returns the next node of a given node, or NULL this is the last node. * * @param o indexed list * @param node existing node * @return next node, or NULL */ static IndexedListNode * IndexedList_GetNext (IndexedList *o, IndexedListNode *node); /** * Returns the previous node of a given node, or NULL this is the first node. * * @param o indexed list * @param node existing node * @return previous node, or NULL */ static IndexedListNode * IndexedList_GetPrev (IndexedList *o, IndexedListNode *node); #include "IndexedList_tree.h" #include <structure/CAvl_impl.h> static IndexedListNode * IndexedList__deref (IndexedList__TreeRef ref) { return ref.link; } static void IndexedList_Init (IndexedList *o) { IndexedList__Tree_Init(&o->tree); } static void IndexedList_InsertAt (IndexedList *o, IndexedListNode *node, uint64_t index) { ASSERT(index <= IndexedList__Tree_Count(&o->tree, 0)) ASSERT(IndexedList__Tree_Count(&o->tree, 0) < UINT64_MAX - 1) uint64_t orig_count = IndexedList__Tree_Count(&o->tree, 0); B_USE(orig_count) IndexedList__Tree_InsertAt(&o->tree, 0, IndexedList__TreeDeref(0, node), index); ASSERT(IndexedList__Tree_IndexOf(&o->tree, 0, IndexedList__TreeDeref(0, node)) == index) ASSERT(IndexedList__Tree_Count(&o->tree, 0) == orig_count + 1) } static void IndexedList_Remove (IndexedList *o, IndexedListNode *node) { IndexedList__Tree_Remove(&o->tree, 0, IndexedList__TreeDeref(0, node)); } static uint64_t IndexedList_Count (IndexedList *o) { return IndexedList__Tree_Count(&o->tree, 0); } static uint64_t IndexedList_IndexOf (IndexedList *o, IndexedListNode *node) { return IndexedList__Tree_IndexOf(&o->tree, 0, IndexedList__TreeDeref(0, node)); } static IndexedListNode * IndexedList_GetAt (IndexedList *o, uint64_t index) { ASSERT(index < IndexedList__Tree_Count(&o->tree, 0)) IndexedList__TreeRef ref = IndexedList__Tree_GetAt(&o->tree, 0, index); ASSERT(!IndexedList__TreeIsNullRef(ref)) return ref.ptr; } static IndexedListNode * IndexedList_GetFirst (IndexedList *o) { return IndexedList__deref(IndexedList__Tree_GetFirst(&o->tree, 0)); } static IndexedListNode * IndexedList_GetLast (IndexedList *o) { return IndexedList__deref(IndexedList__Tree_GetLast(&o->tree, 0)); } static IndexedListNode * IndexedList_GetNext (IndexedList *o, IndexedListNode *node) { ASSERT(node) return IndexedList__deref(IndexedList__Tree_GetNext(&o->tree, 0, IndexedList__TreeDeref(0, node))); } static IndexedListNode * IndexedList_GetPrev (IndexedList *o, IndexedListNode *node) { ASSERT(node) return IndexedList__deref(IndexedList__Tree_GetPrev(&o->tree, 0, IndexedList__TreeDeref(0, node))); } #endif
2,366
567
#ifndef BeanLoader_H #define BeanLoader_H namespace hiberlite{ class LoadBean { public: template<class AV> inline void notifyInitWalk(AV& av); template<class AV> inline void notifyDoneWalk(AV& av); template<class AV, class C> inline void act(AV& av, db_atom<C> atom){ int col_indx=locateCol(av.getScope().prefix()); atom.loadValue(stmt.top().first, col_indx); } template<class AV, class E, class S> inline void act(AV& av, collection_nvp<E,S> nvp ); protected: std::stack< std::pair<SQLiteSelect,sqlid_t> > stmt; inline int locateCol(std::string name){ SQLiteSelect& sel=stmt.top().first; unsigned int n=sel.column_count(); for(unsigned int i=0;i<n;i++) if(sel.get_name(i)==name) return i; throw database_error(name+": column not found in SELECT query results"); } }; class BeanLoader : AVisitor<LoadBean> { public: BeanLoader(); template<class C> C* loadBean(bean_key k); protected: LoadBean actor; private: }; } //namespace hiberlite #endif // BeanLoader_H
415
372
<filename>clients/google-api-services-apigee/v1/1.31.0/com/google/api/services/apigee/v1/model/GoogleCloudApigeeV1TlsInfo.java /* * 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.apigee.v1.model; /** * TLS configuration information for VirtualHosts and TargetServers. * * <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 Apigee 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 GoogleCloudApigeeV1TlsInfo extends com.google.api.client.json.GenericJson { /** * The SSL/TLS cipher suites to be used. Must be one of the cipher suite names listed in: * http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ciphers; /** * Optional. Enables two-way TLS. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean clientAuthEnabled; /** * The TLS Common Name of the certificate. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudApigeeV1TlsInfoCommonName commonName; /** * Required. Enables TLS. If false, neither one-way nor two-way TLS will be enabled. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enabled; /** * If true, Edge ignores TLS certificate errors. Valid when configuring TLS for target servers and * target endpoints, and when configuring virtual hosts that use 2-way TLS. When used with a * target endpoint/target server, if the backend system uses SNI and returns a cert with a subject * Distinguished Name (DN) that does not match the hostname, there is no way to ignore the error * and the connection fails. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean ignoreValidationErrors; /** * Required if `client_auth_enabled` is true. The resource ID for the alias containing the private * key and cert. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String keyAlias; /** * Required if `client_auth_enabled` is true. The resource ID of the keystore. References not yet * supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String keyStore; /** * The TLS versioins to be used. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> protocols; /** * The resource ID of the truststore. References not yet supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String trustStore; /** * The SSL/TLS cipher suites to be used. Must be one of the cipher suite names listed in: * http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites * @return value or {@code null} for none */ public java.util.List<java.lang.String> getCiphers() { return ciphers; } /** * The SSL/TLS cipher suites to be used. Must be one of the cipher suite names listed in: * http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites * @param ciphers ciphers or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setCiphers(java.util.List<java.lang.String> ciphers) { this.ciphers = ciphers; return this; } /** * Optional. Enables two-way TLS. * @return value or {@code null} for none */ public java.lang.Boolean getClientAuthEnabled() { return clientAuthEnabled; } /** * Optional. Enables two-way TLS. * @param clientAuthEnabled clientAuthEnabled or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setClientAuthEnabled(java.lang.Boolean clientAuthEnabled) { this.clientAuthEnabled = clientAuthEnabled; return this; } /** * The TLS Common Name of the certificate. * @return value or {@code null} for none */ public GoogleCloudApigeeV1TlsInfoCommonName getCommonName() { return commonName; } /** * The TLS Common Name of the certificate. * @param commonName commonName or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setCommonName(GoogleCloudApigeeV1TlsInfoCommonName commonName) { this.commonName = commonName; return this; } /** * Required. Enables TLS. If false, neither one-way nor two-way TLS will be enabled. * @return value or {@code null} for none */ public java.lang.Boolean getEnabled() { return enabled; } /** * Required. Enables TLS. If false, neither one-way nor two-way TLS will be enabled. * @param enabled enabled or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setEnabled(java.lang.Boolean enabled) { this.enabled = enabled; return this; } /** * If true, Edge ignores TLS certificate errors. Valid when configuring TLS for target servers and * target endpoints, and when configuring virtual hosts that use 2-way TLS. When used with a * target endpoint/target server, if the backend system uses SNI and returns a cert with a subject * Distinguished Name (DN) that does not match the hostname, there is no way to ignore the error * and the connection fails. * @return value or {@code null} for none */ public java.lang.Boolean getIgnoreValidationErrors() { return ignoreValidationErrors; } /** * If true, Edge ignores TLS certificate errors. Valid when configuring TLS for target servers and * target endpoints, and when configuring virtual hosts that use 2-way TLS. When used with a * target endpoint/target server, if the backend system uses SNI and returns a cert with a subject * Distinguished Name (DN) that does not match the hostname, there is no way to ignore the error * and the connection fails. * @param ignoreValidationErrors ignoreValidationErrors or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setIgnoreValidationErrors(java.lang.Boolean ignoreValidationErrors) { this.ignoreValidationErrors = ignoreValidationErrors; return this; } /** * Required if `client_auth_enabled` is true. The resource ID for the alias containing the private * key and cert. * @return value or {@code null} for none */ public java.lang.String getKeyAlias() { return keyAlias; } /** * Required if `client_auth_enabled` is true. The resource ID for the alias containing the private * key and cert. * @param keyAlias keyAlias or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setKeyAlias(java.lang.String keyAlias) { this.keyAlias = keyAlias; return this; } /** * Required if `client_auth_enabled` is true. The resource ID of the keystore. References not yet * supported. * @return value or {@code null} for none */ public java.lang.String getKeyStore() { return keyStore; } /** * Required if `client_auth_enabled` is true. The resource ID of the keystore. References not yet * supported. * @param keyStore keyStore or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setKeyStore(java.lang.String keyStore) { this.keyStore = keyStore; return this; } /** * The TLS versioins to be used. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getProtocols() { return protocols; } /** * The TLS versioins to be used. * @param protocols protocols or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setProtocols(java.util.List<java.lang.String> protocols) { this.protocols = protocols; return this; } /** * The resource ID of the truststore. References not yet supported. * @return value or {@code null} for none */ public java.lang.String getTrustStore() { return trustStore; } /** * The resource ID of the truststore. References not yet supported. * @param trustStore trustStore or {@code null} for none */ public GoogleCloudApigeeV1TlsInfo setTrustStore(java.lang.String trustStore) { this.trustStore = trustStore; return this; } @Override public GoogleCloudApigeeV1TlsInfo set(String fieldName, Object value) { return (GoogleCloudApigeeV1TlsInfo) super.set(fieldName, value); } @Override public GoogleCloudApigeeV1TlsInfo clone() { return (GoogleCloudApigeeV1TlsInfo) super.clone(); } }
3,073
599
<filename>bcs-ui/backend/container_service/clusters/cc_host/utils.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ import logging from typing import Dict, List from backend.components import cc, gse, paas_cc from backend.container_service.clusters.models import CommonStatus from backend.utils.basic import get_with_placeholder logger = logging.getLogger(__name__) def fetch_cc_app_hosts(username, bk_biz_id, bk_module_id=None, bk_set_id=None) -> List[Dict]: """ 拉取 业务 下机器列表(业务/集群/模块全量) TODO 当前场景只需要支持单模块/集群,后续有需要可扩展 :return: CMDB 业务下机器列表 """ bk_module_ids = [bk_module_id] if bk_module_id else None bk_set_ids = [bk_set_id] if bk_set_id else None return cc.HostQueryService(username, bk_biz_id, bk_module_ids, bk_set_ids).fetch_all() def fetch_all_cluster_nodes(access_token: str) -> Dict: """ 获取所有集群中使用的主机信息 :return: {'ip': node_info} """ nodes = paas_cc.get_all_cluster_hosts(access_token, exclude_status_list=[CommonStatus.Removed]) return {n['inner_ip']: n for n in nodes} def fetch_project_cluster_info(access_token: str) -> Dict: """ 获取 项目 & 集群信息 :return: {cluster_id: {'project_name': p_name, 'cluster_name': c_name} """ resources = paas_cc.get_project_cluster_resource(access_token) return { cluster['id']: {'project_name': project['name'], 'cluster_name': cluster['name']} for project in resources if project for cluster in project['cluster_list'] if cluster } def gen_used_info(host: Dict, all_cluster_nodes: Dict, project_cluster_info: Dict) -> Dict: """ 生成主机被使用的项目,集群信息 :param host: 原始主机信息 :param all_cluster_nodes: 全集群节点信息 :param project_cluster_info: 项目 & 集群信息 :return: 主机的使用信息 """ info = {'project_name': '', 'cluster_name': '', 'cluster_id': '', 'is_used': False} for ip in host['bk_host_innerip'].split(','): node_info = all_cluster_nodes.get(ip) if not node_info: continue info['is_used'] = True info['cluster_id'] = node_info.get('cluster_id') name_dict = project_cluster_info.get(info['cluster_id']) or {} info['project_name'] = get_with_placeholder(name_dict, 'project_name') info['cluster_name'] = get_with_placeholder(name_dict, 'cluster_name') break return info def is_valid_machine(*args, **kwargs) -> bool: """ 判断是否为机器类型是否可用 """ # NOTE ce 版本不做判断 return True def attach_project_cluster_info(host_list: List, all_cluster_nodes: Dict, project_cluster_info: Dict) -> List: """ 更新节点使用状态 & 是否类型可用,补充项目,集群等信息 :param host_list: 原始主机列表 :param all_cluster_nodes: 全集群节点信息 :param project_cluster_info: 项目 & 集群信息 :return: 包含使用信息的主机列表 """ new_host_list, used_host_list = [], [] for host in host_list: # 没有 内网 IP 的主机直接忽略 if 'bk_host_innerip' not in host or not host['bk_host_innerip']: continue host.update(gen_used_info(host, all_cluster_nodes, project_cluster_info)) host['is_valid'] = is_valid_machine(host) if host['is_used']: used_host_list.append(host) else: new_host_list.append(host) # 已被使用的 Host 放列表最后 new_host_list.extend(used_host_list) return new_host_list def is_host_selectable(host: Dict) -> bool: """ 判断机器是否可被选择为 Master / Node 已经被使用 / 机器类型不可用 则不能选择 Agent 异常也可以选择(初始化会重装) :param host: 主机配置信息 :return: 是否可选择 """ return not host['is_used'] and host['is_valid'] def update_gse_agent_status(username, host_list: List) -> List: """ 更新 GSE Agent 状态信息 """ gse_params = [] for info in host_list: bk_cloud_id = info.get('bk_cloud_id') or 0 gse_params.extend( [ {'plat_id': bk_cloud_id, 'bk_cloud_id': bk_cloud_id, 'ip': ip} for ip in info.get('bk_host_innerip', '').split(',') ] ) gse_host_status_map = {info['ip']: info for info in gse.get_agent_status(username, gse_params)} # 根据 IP 匹配更新 Agent 信息 cc_host_map = {host['bk_host_innerip']: host for host in host_list} for ips in cc_host_map: # 同主机可能存在多个 IP,任一 IP Agent 正常即可 for ip in ips.split(','): if ip not in gse_host_status_map: continue ip_status = gse_host_status_map[ip] cc_host_map[ips]['agent_alive'] = ip_status.get('bk_agent_alive') break return list(cc_host_map.values()) try: from .utils_ext import * # noqa except ImportError as e: logger.debug("Load extension failed: %s", e)
2,802
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-6g7p-3fmx-8jh6", "modified": "2022-05-01T02:05:39Z", "published": "2022-05-01T02:05:39Z", "aliases": [ "CVE-2005-2169" ], "details": "Directory traversal vulnerability in source.php in Quick & Dirty PHPSource Printer 1.1 and earlier allows remote attackers to read arbitrary files via \".../...//\" sequences in the file parameter, which are reduced to \"../\" when PHPSource Printer uses a regular expression to remove \"../\" sequences.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2005-2169" }, { "type": "WEB", "url": "http://guff.szub.net/2005/07/04/quick-and-dirty-security/" }, { "type": "WEB", "url": "http://secunia.com/advisories/15900" }, { "type": "WEB", "url": "http://securitytracker.com/id?1014376" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
472
381
""" A simple standalone target. The target below specifies None as the argument types list. This is a case treated specially in driver.py . If the list of input types is empty, it is meant to be a list of strings, actually implementing argv of the executable. """ # __________ Entry point __________ class A(object): pass class B(object): pass def f(x): if x == 0: return f(x - 1) b = B() b.x = x return b global_a = A() def entry_point(argv): a1 = A() a2 = A() a3 = A() a4 = A() global_a.next = a1 a1.x = 1 a2.x = 2 a3.x = 3 a4.x = 4 a1.next = a2 a2.next = a3 a3.next = a4 a4.next = None # push stuff global_a.b = f(len(argv)) global_a.b.x = len(argv) # pop stuff return a1.x + a2.x + a3.x + a4.x + global_a.b.x # _____ Define and setup target ___ def target(*args): return entry_point, None
412
5,169
{ "name": "JFMinimalNotifications", "version": "0.0.6", "summary": "An iOS UIView for presenting a minimalistic notification that doesn't block the UI and is highly configurable", "requires_arc": true, "description": "An iOS UIView for presenting a beautiful notification that is highly configurable and works for both iPhone and iPad. \nJFMinimalNotification is only available in ARC and targets iOS 7.0+.", "homepage": "https://github.com/atljeremy/JFMinimalNotifications", "screenshots": "http://imageshack.com/a/img673/9547/7auGJk.png", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://jeremyfox.me", "platforms": { "ios": "7.0" }, "source": { "git": "https://github.com/atljeremy/JFMinimalNotifications.git", "tag": "0.0.6" }, "source_files": "JFMinimalNotification/*.{h,m}", "public_header_files": "JFMinimalNotification/*.h", "frameworks": "CoreGraphics" }
368
1,462
""" Tests for quad.py Notes ----- Many of tests were derived from the file demqua## in the CompEcon toolbox. For all other tests, the MATLAB code is provided here in a section of comments. """ import os import unittest from scipy.io import loadmat import numpy as np from numpy.testing import assert_allclose import pandas as pd from quantecon.quad import ( qnwcheb, qnwequi, qnwlege, qnwnorm, qnwlogn, qnwsimp, qnwtrap, qnwunif, quadrect, qnwbeta, qnwgamma ) from quantecon.tests.util import get_data_dir ### MATLAB code needed to generate data (in addition to a modified demqua03) # % set random number seed so we get the same random nums as in python # rng(42) # % 1-d parameters -- just some random numbers # a = -2.0 # b = 3.0 # n = 11 # % 3-d parameters -- just some random numbers # a_3 = [-1.0 -2.0 1.0] # b_3 = [1.0 12.0 1.5] # n_3 = [7 5 9] # mu_3d = [1.0 2.0 2.5] # sigma2_3d = [1.0 0.1 0.0; 0.1 1.0 0.0; 0.0 0.0 1.2] # % 1-d nodes and weights # [x_cheb_1 w_cheb_1] = qnwcheb(n, a, b) # [x_equiN_1 w_equiN_1] = qnwequi(n, a, b, 'N') # [x_equiW_1 w_equiW_1] = qnwequi(n, a, b, 'W') # [x_equiH_1 w_equiH_1] = qnwequi(n, a, b, 'H') # rng(41); [x_equiR_1 w_equiR_1] = qnwequi(n, a, b, 'R') # [x_lege_1 w_lege_1] = qnwlege(n, a, b) # [x_norm_1 w_norm_1] = qnwnorm(n, a, b) # [x_logn_1 w_logn_1] = qnwlogn(n, a, b) # [x_simp_1 w_simp_1] = qnwsimp(n, a, b) # [x_trap_1 w_trap_1] = qnwtrap(n, a, b) # [x_unif_1 w_unif_1] = qnwunif(n, a, b) # [x_beta_1 w_beta_1] = qnwbeta(n, b, b+1) # [x_gamm_1 w_gamm_1] = qnwgamma(n, b) # % 3-d nodes and weights # [x_cheb_3 w_cheb_3] = qnwcheb(n_3, a_3, b_3) # rng(42); [x_equiN_3 w_equiN_3] = qnwequi(n_3, a_3, b_3, 'N') # [x_equiW_3 w_equiW_3] = qnwequi(n_3, a_3, b_3, 'W') # [x_equiH_3 w_equiH_3] = qnwequi(n_3, a_3, b_3, 'H') # [x_equiR_3 w_equiR_3] = qnwequi(n_3, a_3, b_3, 'R') # [x_lege_3 w_lege_3] = qnwlege(n_3, a_3, b_3) # [x_norm_3 w_norm_3] = qnwnorm(n_3, mu_3d, sigma2_3d) # [x_logn_3 w_logn_3] = qnwlogn(n_3, mu_3d, sigma2_3d) # [x_simp_3 w_simp_3] = qnwsimp(n_3, a_3, b_3) # [x_trap_3 w_trap_3] = qnwtrap(n_3, a_3, b_3) # [x_unif_3 w_unif_3] = qnwunif(n_3, a_3, b_3) # [x_beta_3 w_beta_3] = qnwbeta(n_3, b_3, b_3+1.0) # [x_gamm_3 w_gamm_3] = qnwgamma(n_3, b_3) ### End MATLAB commands data_dir = get_data_dir() data = loadmat(os.path.join(data_dir, "matlab_quad.mat"), squeeze_me=True) # Unpack parameters from MATLAB a = data['a'] b = data['b'] n = data['n'] a_3 = data['a_3'] b_3 = data['b_3'] n_3 = data['n_3'] mu_3d = data['mu_3d'] sigma2_3d = data['sigma2_3d'] class TestQuadrect(unittest.TestCase): @classmethod def setUpClass(cls): ## Create Python Data for quadrect # Create the python data -- similar to notebook code kinds = ["trap", "simp", "lege", "N", "W", "H", "R"] # Define some functions f1 = lambda x: np.exp(-x) f2 = lambda x: 1.0 / (1.0 + 25.0 * x**2.0) f3 = lambda x: np.abs(x) ** 0.5 func_names = ["f1", "f2", "f3"] # Integration parameters n = np.array([5, 11, 21, 51, 101, 401]) # number of nodes np.random.seed(42) # same seed as ML code. a, b = -1, 1 # endpoints # Set up pandas DataFrame to hold results ind = pd.MultiIndex.from_product([func_names, n]) ind.names = ["Function", "Number of Nodes"] cols = pd.Index(kinds, name="Kind") quad_rect_res1d = pd.DataFrame(index=ind, columns=cols, dtype=float) for i, func in enumerate([f1, f2, f3]): func_name = func_names[i] for kind in kinds: for num in n: num_in = num ** 2 if len(kind) == 1 else num quad_rect_res1d.loc[func_name, num][kind] = quadrect(func, num_in, a, b, kind) cls.data1d = quad_rect_res1d # Now 2d data kinds2 = ["lege", "trap", "simp", "N", "W", "H", "R"] f1_2 = lambda x: np.exp(x[:, 0] + x[:, 1]) f2_2 = lambda x: np.exp(-x[:, 0] * np.cos(x[:, 1]**2)) # Set up pandas DataFrame to hold results a = ([0, 0], [-1, -1]) b = ([1, 2], [1, 1]) ind_2 = pd.Index(n**2, name="Num Points") cols2 = pd.Index(kinds2, name="Kind") data2 = pd.DataFrame(index=ind_2, columns=cols2, dtype=float) for num in n: for kind in kinds2[:4]: data2.loc[num**2][kind] = quadrect(f1_2, [num, num], a[0], b[0], kind) for kind in kinds2[4:]: data2.loc[num**2][kind] = quadrect(f1_2, num**2, a[0], b[0], kind) cls.data2d1 = data2 n3 = 10 ** (2 + np.array([1, 2, 3])) ind_3 = pd.Index(n3, name="Num Points") cols3 = pd.Index(kinds2[3:]) data3 = pd.DataFrame(index=ind_3, columns=cols3, dtype=float) for num in n3: for kind in kinds2[3:]: data3.loc[num][kind] = quadrect(f2_2, num, a[1], b[1], kind) cls.data2d2 = data3 ## Organize MATLAB Data ml_data = pd.DataFrame(index=ind, columns=cols, dtype=float) ml_data.iloc[:6, :] = data['int_1d'][:, :, 0] ml_data.iloc[6:12, :] = data['int_1d'][:, :, 1] ml_data.iloc[12:18, :] = data['int_1d'][:, :, 2] ml_data2 = pd.DataFrame(index=ind_2, columns=cols2, dtype=float) ml_data2.iloc[:, :] = data['int_2d1'] ml_data3 = pd.DataFrame(index=ind_3, columns=cols3, dtype=float) ml_data3.iloc[:, :] = data['int_2d2'] cls.ml_data1d = ml_data cls.ml_data2d1 = ml_data2 cls.ml_data2d2 = ml_data3 def test_quadrect_1d_lege(self): assert_allclose(self.data1d['lege'], self.ml_data1d['lege']) def test_quadrect_1d_trap(self): assert_allclose(self.data1d['trap'], self.ml_data1d['trap']) def test_quadrect_1d_simp(self): assert_allclose(self.data1d['simp'], self.ml_data1d['simp']) def test_quadrect_1d_R(self): assert_allclose(self.data1d['R'], self.ml_data1d['R']) def test_quadrect_1d_W(self): assert_allclose(self.data1d['W'], self.ml_data1d['W']) def test_quadrect_1d_N(self): assert_allclose(self.data1d['N'], self.ml_data1d['N']) def test_quadrect_1d_H(self): assert_allclose(self.data1d['H'], self.ml_data1d['H']) def test_quadrect_2d_lege(self): assert_allclose(self.data2d1['lege'], self.ml_data2d1['lege']) def test_quadrect_2d_trap(self): assert_allclose(self.data2d1['trap'], self.ml_data2d1['trap']) def test_quadrect_2d_simp(self): assert_allclose(self.data2d1['simp'], self.ml_data2d1['simp']) # NOTE: The R tests will fail in more than 1 dimension. This is a # function of MATLAB and numpy storing arrays in different # "order". See comment in TestQnwequiR.setUpClass # def test_quadrect_2d_R(self): # assert_allclose(self.data2d1['R'], self.ml_data2d1['R']) def test_quadrect_2d_W(self): assert_allclose(self.data2d1['W'], self.ml_data2d1['W']) def test_quadrect_2d_N(self): assert_allclose(self.data2d1['N'], self.ml_data2d1['N']) def test_quadrect_2d_H(self): assert_allclose(self.data2d1['H'], self.ml_data2d1['H']) def test_quadrect_2d_W2(self): assert_allclose(self.data2d2['W'], self.ml_data2d2['W']) def test_quadrect_2d_N2(self): assert_allclose(self.data2d2['N'], self.ml_data2d2['N']) def test_quadrect_2d_H2(self): assert_allclose(self.data2d2['H'], self.ml_data2d2['H']) class TestQnwcheb(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_cheb_1, cls.w_cheb_1 = qnwcheb(n, a, b) cls.x_cheb_3, cls.w_cheb_3 = qnwcheb(n_3, a_3, b_3) def test_qnwcheb_nodes_1d(self): assert_allclose(self.x_cheb_1, data['x_cheb_1']) def test_qnwcheb_nodes_3d(self): assert_allclose(self.x_cheb_3, data['x_cheb_3']) def test_qnwcheb_weights_1d(self): assert_allclose(self.w_cheb_1, data['w_cheb_1']) def test_qnwcheb_weights_3d(self): assert_allclose(self.w_cheb_3, data['w_cheb_3']) class TestQnwequiN(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_equiN_1, cls.w_equiN_1 = qnwequi(n, a, b, "N") cls.x_equiN_3, cls.w_equiN_3 = qnwequi(n_3, a_3, b_3, "N") def test_qnwequiN_nodes_1d(self): assert_allclose(self.x_equiN_1, data['x_equiN_1']) def test_qnwequiN_nodes_3d(self): assert_allclose(self.x_equiN_3, data['x_equiN_3']) def test_qnwequiN_weights_1d(self): assert_allclose(self.w_equiN_1, data['w_equiN_1']) def test_qnwequiN_weights_3d(self): assert_allclose(self.w_equiN_3, data['w_equiN_3']) class TestQnwequiW(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_equiW_1, cls.w_equiW_1 = qnwequi(n, a, b, "W") cls.x_equiW_3, cls.w_equiW_3 = qnwequi(n_3, a_3, b_3, "W") def test_qnwequiW_nodes_1d(self): assert_allclose(self.x_equiW_1, data['x_equiW_1']) def test_qnwequiW_nodes_3d(self): assert_allclose(self.x_equiW_3, data['x_equiW_3']) def test_qnwequiW_weights_1d(self): assert_allclose(self.w_equiW_1, data['w_equiW_1']) def test_qnwequiW_weights_3d(self): assert_allclose(self.w_equiW_3, data['w_equiW_3']) class TestQnwequiH(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_equiH_1, cls.w_equiH_1 = qnwequi(n, a, b, "H") cls.x_equiH_3, cls.w_equiH_3 = qnwequi(n_3, a_3, b_3, "H") def test_qnwequiH_nodes_1d(self): assert_allclose(self.x_equiH_1, data['x_equiH_1']) def test_qnwequiH_nodes_3d(self): assert_allclose(self.x_equiH_3, data['x_equiH_3']) def test_qnwequiH_weights_1d(self): assert_allclose(self.w_equiH_1, data['w_equiH_1']) def test_qnwequiH_weights_3d(self): assert_allclose(self.w_equiH_3, data['w_equiH_3']) class TestQnwequiR(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_equiR_1, cls.w_equiR_1 = qnwequi(n, a, b, "R", random_state=41) temp, cls.w_equiR_3 = qnwequi(n_3, a_3, b_3, "R", random_state=42) # NOTE: I need to do a little magic here. MATLAB and numpy # are generating the same random numbers, but MATLAB is # column major and numpy is row major, so they are stored # in different places for multi-dimensional arrays. # The ravel, reshape code here moves the numpy nodes into # the same relative position as the MATLAB ones. Also, in # order for this to work I have to undo the shifting of # the nodes, re-organize data, then re-shift. If this # seems like voodoo to you, it kinda is. But, the fact # that the test can pass after this kind of manipulation # is a strong indicator that we are doing it correctly unshifted = (temp - a_3) / (b_3 - a_3) reshaped = np.ravel(unshifted).reshape(315, 3, order='F') reshifted = a_3 + reshaped * (b_3 - a_3) cls.x_equiR_3 = reshifted def test_qnwequiR_nodes_1d(self): assert_allclose(self.x_equiR_1, data['x_equiR_1']) def test_qnwequiR_nodes_3d(self): assert_allclose(self.x_equiR_3, data['x_equiR_3']) def test_qnwequiR_weights_1d(self): assert_allclose(self.w_equiR_1, data['w_equiR_1']) def test_qnwequiR_weights_3d(self): assert_allclose(self.w_equiR_3, data['w_equiR_3']) class TestQnwlege(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_lege_1, cls.w_lege_1 = qnwlege(n, a, b) cls.x_lege_3, cls.w_lege_3 = qnwlege(n_3, a_3, b_3) def test_qnwlege_nodes_1d(self): assert_allclose(self.x_lege_1, data['x_lege_1']) def test_qnwlege_nodes_3d(self): assert_allclose(self.x_lege_3, data['x_lege_3']) def test_qnwlege_weights_1d(self): assert_allclose(self.w_lege_1, data['w_lege_1']) def test_qnwlege_weights_3d(self): assert_allclose(self.w_lege_3, data['w_lege_3']) class TestQnwnorm(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_norm_1, cls.w_norm_1 = qnwnorm(n, a, b) cls.x_norm_3, cls.w_norm_3 = qnwnorm(n_3, mu_3d, sigma2_3d) def test_qnwnorm_nodes_1d(self): assert_allclose(self.x_norm_1, data['x_norm_1']) def test_qnwnorm_nodes_3d(self): assert_allclose(self.x_norm_3, data['x_norm_3']) def test_qnwnorm_weights_1d(self): assert_allclose(self.w_norm_1, data['w_norm_1']) def test_qnwnorm_weights_3d(self): assert_allclose(self.w_norm_3, data['w_norm_3']) class TestQnwlogn(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_logn_1, cls.w_logn_1 = qnwlogn(n, a, b) cls.x_logn_3, cls.w_logn_3 = qnwlogn(n_3, mu_3d, sigma2_3d) def test_qnwlogn_nodes_1d(self): assert_allclose(self.x_logn_1, data['x_logn_1']) def test_qnwlogn_nodes_3d(self): assert_allclose(self.x_logn_3, data['x_logn_3']) def test_qnwlogn_weights_1d(self): assert_allclose(self.w_logn_1, data['w_logn_1']) def test_qnwlogn_weights_3d(self): assert_allclose(self.w_logn_3, data['w_logn_3']) class TestQnwsimp(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_simp_1, cls.w_simp_1 = qnwsimp(n, a, b) cls.x_simp_3, cls.w_simp_3 = qnwsimp(n_3, a_3, b_3) def test_qnwsimp_nodes_1d(self): assert_allclose(self.x_simp_1, data['x_simp_1']) def test_qnwsimp_nodes_3d(self): assert_allclose(self.x_simp_3, data['x_simp_3']) def test_qnwsimp_weights_1d(self): assert_allclose(self.w_simp_1, data['w_simp_1']) def test_qnwsimp_weights_3d(self): assert_allclose(self.w_simp_3, data['w_simp_3']) class TestQnwtrap(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_trap_1, cls.w_trap_1 = qnwtrap(n, a, b) cls.x_trap_3, cls.w_trap_3 = qnwtrap(n_3, a_3, b_3) def test_qnwtrap_nodes_1d(self): assert_allclose(self.x_trap_1, data['x_trap_1']) def test_qnwtrap_nodes_3d(self): assert_allclose(self.x_trap_3, data['x_trap_3']) def test_qnwtrap_weights_1d(self): assert_allclose(self.w_trap_1, data['w_trap_1']) def test_qnwtrap_weights_3d(self): assert_allclose(self.w_trap_3, data['w_trap_3']) class TestQnwunif(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_unif_1, cls.w_unif_1 = qnwunif(n, a, b) cls.x_unif_3, cls.w_unif_3 = qnwunif(n_3, a_3, b_3) def test_qnwunif_nodes_1d(self): assert_allclose(self.x_unif_1, data['x_unif_1']) def test_qnwunif_nodes_3d(self): assert_allclose(self.x_unif_3, data['x_unif_3']) def test_qnwunif_weights_1d(self): assert_allclose(self.w_unif_1, data['w_unif_1']) def test_qnwunif_weights_3d(self): assert_allclose(self.w_unif_3, data['w_unif_3']) class TestQnwbeta(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_beta_1, cls.w_beta_1 = qnwbeta(n, b, b + 1.0) cls.x_beta_3, cls.w_beta_3 = qnwbeta(n_3, b_3, b_3 + 1.0) def test_qnwbeta_nodes_1d(self): assert_allclose(self.x_beta_1, data['x_beta_1']) def test_qnwbeta_nodes_3d(self): assert_allclose(self.x_beta_3, data['x_beta_3']) def test_qnwbeta_weights_1d(self): assert_allclose(self.w_beta_1, data['w_beta_1']) def test_qnwbeta_weights_3d(self): assert_allclose(self.w_beta_3, data['w_beta_3']) class TestQnwgamm(unittest.TestCase): @classmethod def setUpClass(cls): cls.x_gamm_1, cls.w_gamm_1 = qnwgamma(n, b) cls.x_gamm_3, cls.w_gamm_3 = qnwgamma(n_3, b_3) def test_qnwgamm_nodes_1d(self): assert_allclose(self.x_gamm_1, data['x_gamm_1']) def test_qnwgamm_nodes_3d(self): assert_allclose(self.x_gamm_3, data['x_gamm_3']) def test_qnwgamm_weights_1d(self): assert_allclose(self.w_gamm_1, data['w_gamm_1']) def test_qnwgamm_weights_3d(self): assert_allclose(self.w_gamm_3, data['w_gamm_3'])
8,973
903
package php.runtime.invoke.cache; import php.runtime.reflection.ClassEntity; public class ClassCallCache extends CallCache<ClassEntity> { @Override public Item[] newArrayData(int length) { return new Item[length]; } @Override public Item[][] newArrayArrayData(int length) { return new Item[length][]; } }
124
663
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/mphal.h" #include "py/mpthread.h" #include <sys/time.h> #include <windows.h> #include <unistd.h> HANDLE std_in = NULL; HANDLE con_out = NULL; DWORD orig_mode = 0; STATIC void assure_stdin_handle() { if (!std_in) { std_in = GetStdHandle(STD_INPUT_HANDLE); assert(std_in != INVALID_HANDLE_VALUE); } } STATIC void assure_conout_handle() { if (!con_out) { con_out = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); assert(con_out != INVALID_HANDLE_VALUE); } } void mp_hal_stdio_mode_raw(void) { assure_stdin_handle(); GetConsoleMode(std_in, &orig_mode); DWORD mode = orig_mode; mode &= ~ENABLE_ECHO_INPUT; mode &= ~ENABLE_LINE_INPUT; mode &= ~ENABLE_PROCESSED_INPUT; SetConsoleMode(std_in, mode); } void mp_hal_stdio_mode_orig(void) { assure_stdin_handle(); SetConsoleMode(std_in, orig_mode); } // Handler to be installed by SetConsoleCtrlHandler, currently used only to handle Ctrl-C. // This handler has to be installed just once (this has to be done elswhere in init code). // Previous versions of the mp_hal code would install a handler whenever Ctrl-C input is // allowed and remove the handler again when it is not. That is not necessary though (1), // and it might introduce problems (2) because console notifications are delivered to the // application in a separate thread. // (1) mp_hal_set_interrupt_char effectively enables/disables processing of Ctrl-C via the // ENABLE_PROCESSED_INPUT flag so in raw mode console_sighandler won't be called. // (2) if mp_hal_set_interrupt_char would remove the handler while Ctrl-C was issued earlier, // the thread created for handling it might not be running yet so we'd miss the notification. BOOL WINAPI console_sighandler(DWORD evt) { if (evt == CTRL_C_EVENT) { if (MP_STATE_VM(mp_pending_exception) == MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception))) { // this is the second time we are called, so die straight away exit(1); } mp_sched_keyboard_interrupt(); return TRUE; } return FALSE; } void mp_hal_set_interrupt_char(char c) { assure_stdin_handle(); if (c == CHAR_CTRL_C) { DWORD mode; GetConsoleMode(std_in, &mode); mode |= ENABLE_PROCESSED_INPUT; SetConsoleMode(std_in, mode); } else { DWORD mode; GetConsoleMode(std_in, &mode); mode &= ~ENABLE_PROCESSED_INPUT; SetConsoleMode(std_in, mode); } } void mp_hal_move_cursor_back(uint pos) { if (!pos) { return; } assure_conout_handle(); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(con_out, &info); info.dwCursorPosition.X -= (short)pos; // Move up a line if needed. while (info.dwCursorPosition.X < 0) { info.dwCursorPosition.X = info.dwSize.X + info.dwCursorPosition.X; info.dwCursorPosition.Y -= 1; } // Caller requested to move out of the screen. That's not possible so just clip, // it's the caller's responsibility to not let this happen. if (info.dwCursorPosition.Y < 0) { info.dwCursorPosition.X = 0; info.dwCursorPosition.Y = 0; } SetConsoleCursorPosition(con_out, info.dwCursorPosition); } void mp_hal_erase_line_from_cursor(uint n_chars_to_erase) { assure_conout_handle(); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(con_out, &info); DWORD written; FillConsoleOutputCharacter(con_out, ' ', n_chars_to_erase, info.dwCursorPosition, &written); FillConsoleOutputAttribute(con_out, info.wAttributes, n_chars_to_erase, info.dwCursorPosition, &written); } typedef struct item_t { WORD vkey; const char *seq; } item_t; // map virtual key codes to key sequences known by MicroPython's readline implementation STATIC item_t keyCodeMap[] = { {VK_UP, "[A"}, {VK_DOWN, "[B"}, {VK_RIGHT, "[C"}, {VK_LEFT, "[D"}, {VK_HOME, "[H"}, {VK_END, "[F"}, {VK_DELETE, "[3~"}, {0, ""} // sentinel }; // likewise, but with Ctrl key down STATIC item_t ctrlKeyCodeMap[] = { {VK_LEFT, "b"}, {VK_RIGHT, "f"}, {VK_DELETE, "d"}, {VK_BACK, "\x7F"}, {0, ""} // sentinel }; STATIC const char *cur_esc_seq = NULL; STATIC int esc_seq_process_vk(WORD vk, bool ctrl_key_down) { for (item_t *p = (ctrl_key_down ? ctrlKeyCodeMap : keyCodeMap); p->vkey != 0; ++p) { if (p->vkey == vk) { cur_esc_seq = p->seq; return 27; // ESC, start of escape sequence } } return 0; // nothing found } STATIC int esc_seq_chr() { if (cur_esc_seq) { const char c = *cur_esc_seq++; if (c) { return c; } cur_esc_seq = NULL; } return 0; } int mp_hal_stdin_rx_chr(void) { // currently processing escape seq? const int ret = esc_seq_chr(); if (ret) { return ret; } // poll until key which we handle is pressed assure_stdin_handle(); BOOL status; DWORD num_read; INPUT_RECORD rec; for (;;) { MP_THREAD_GIL_EXIT(); status = ReadConsoleInput(std_in, &rec, 1, &num_read); MP_THREAD_GIL_ENTER(); if (!status || !num_read) { return CHAR_CTRL_C; // EOF, ctrl-D } if (rec.EventType != KEY_EVENT || !rec.Event.KeyEvent.bKeyDown) { // only want key down events continue; } const bool ctrl_key_down = (rec.Event.KeyEvent.dwControlKeyState & LEFT_CTRL_PRESSED) || (rec.Event.KeyEvent.dwControlKeyState & RIGHT_CTRL_PRESSED); const int ret = esc_seq_process_vk(rec.Event.KeyEvent.wVirtualKeyCode, ctrl_key_down); if (ret) { return ret; } const char c = rec.Event.KeyEvent.uChar.AsciiChar; if (c) { // plain ascii char, return it return c; } } } void mp_hal_stdout_tx_strn(const char *str, size_t len) { MP_THREAD_GIL_EXIT(); write(STDOUT_FILENO, str, len); MP_THREAD_GIL_ENTER(); } void mp_hal_stdout_tx_strn_cooked(const char *str, size_t len) { mp_hal_stdout_tx_strn(str, len); } void mp_hal_stdout_tx_str(const char *str) { mp_hal_stdout_tx_strn(str, strlen(str)); } mp_uint_t mp_hal_ticks_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } mp_uint_t mp_hal_ticks_us(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000000 + tv.tv_usec; } mp_uint_t mp_hal_ticks_cpu(void) { LARGE_INTEGER value; QueryPerformanceCounter(&value); #ifdef _WIN64 return value.QuadPart; #else return value.LowPart; #endif } uint64_t mp_hal_time_ns(void) { struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * 1000000000ULL + (uint64_t)tv.tv_usec * 1000ULL; }
3,433
1,754
/* * 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 ratpack.core.impose; import ratpack.core.server.ServerConfigBuilder; /** * Forces the port that the server should use to listen for requests. * <p> * This imposition is used by {@link ServerConfigBuilder}. * If present, the imposed value will be used regardless of any previously specified setting on the builder. * * @see ServerConfigBuilder#port(int) * @see Impositions * @since 1.2 */ public final class ForceServerListenPortImposition implements Imposition { private final int port; private ForceServerListenPortImposition(int port) { this.port = port; } /** * Creates an imposition that forces the use of an ephemeral port. * * @return an imposition for an ephemeral port */ public static ForceServerListenPortImposition ephemeral() { return of(0); } /** * Creates an imposition that forces the use of the specified port. * * @param port the port to force * @return an imposition for the specified port */ public static ForceServerListenPortImposition of(int port) { if (port < 0) { throw new IllegalArgumentException("port must be >= 0"); } return new ForceServerListenPortImposition(port); } /** * The port to be forced. * * @return the port to be forced */ public int getPort() { return port; } }
560
348
{"nom":"Montflours","circ":"1ère circonscription","dpt":"Mayenne","inscrits":168,"abs":85,"votants":83,"blancs":8,"nuls":1,"exp":74,"res":[{"nuance":"SOC","nom":"<NAME>","voix":56},{"nuance":"REM","nom":"<NAME>","voix":18}]}
88
5,169
<filename>Specs/8/3/d/InLocoCommon-iOS-SDK/5.0.0/InLocoCommon-iOS-SDK.podspec.json<gh_stars>1000+ { "name": "InLocoCommon-iOS-SDK", "version": "5.0.0", "summary": "In Loco Common iOS SDK", "description": "Analyze, understand, and drive results for your business with real-world data on the flow of visits to establishments and behavior in the physical world.", "homepage": "https://www.inloco.com.br/en/", "license": "LICENSE", "authors": { "<NAME>ia da Informacao S.A.": "<EMAIL>" }, "source": { "git": "https://github.com/In-Loco-Media/inlocomedia-ios-sdk.git", "tag": "5.0.0" }, "documentation_url": "https://docs.inloco.ai/", "platforms": { "ios": "9.0" }, "xcconfig": { "OTHER_LDFLAGS": "-lObjC" }, "frameworks": "Foundation", "vendored_frameworks": [ "InLocoSDK/InLocoSDK.framework", "InLocoSDK/InLocoSDKCore.framework" ], "requires_arc": true }
390
342
{ "agent": { "run_as_user": "root" }, "logs": { "logs_collected": { "files": { "collect_list": [ { "file_path": "/var/log/buildkite-agent", "log_group_name": "/buildkite/buildkite-agent", "log_stream_name": "{instance_id}", "timestamp_format": "%b %d %H:%M:%S" }, { "file_path": "/var/log/cfn-init.log", "log_group_name": "/buildkite/cfn-init", "log_stream_name": "{instance_id}", "timestamp_format": "%Y-%m-%d %H:%M:%S,%f" }, { "file_path": "/var/log/cloud-init.log", "log_group_name": "/buildkite/cloud-init", "log_stream_name": "{instance_id}", "timestamp_format": "%Y-%m-%d %H:%M:%S,%f" }, { "file_path": "/var/log/cloud-init-output.log", "log_group_name": "/buildkite/cloud-init/output", "log_stream_name": "{instance_id}", "timestamp_format": "%Y-%m-%d %H:%M:%S,%f" }, { "file_path": "/var/log/docker", "log_group_name": "/buildkite/docker-daemon", "log_stream_name": "{instance_id}", "timestamp_format": "%Y-%m-%dT%H:%M:%S.%f" }, { "file_path": "/var/log/elastic-stack.log", "log_group_name": "/buildkite/elastic-stack", "log_stream_name": "{instance_id}", "timestamp_format": "%Y-%m-%d %H:%M:%S,%f" }, { "file_path": "/var/log/messages", "log_group_name": "/buildkite/system", "log_stream_name": "{instance_id}", "timestamp_format": "%b %d %H:%M:%S" } ] } } } }
861
809
<reponame>nikitavlaev/embox /** * @file * * @brief * * @date 22.06.2012 * @author <NAME> */ #ifndef MIPS_ASM_IPL_H_ #define MIPS_ASM_IPL_H_ #include <asm/mipsregs.h> typedef unsigned int __ipl_t; static inline void ipl_init(void) { unsigned int c0_reg; /* read status registers for cleaning interrupts mask */ c0_reg = mips_read_c0_status(); // c0_reg &= ~(ST0_IM); /* clear all interrupts mask */ c0_reg |= ST0_IE; /* global enable interrupt */ mips_write_c0_status(c0_reg); /* write back status register */ /* read cause register for cleaning all pending bits */ // c0_reg = mips_read_c0_cause(); // c0_reg &= ~(ST0_IM); /* clear all interrupts pending bits */ // mips_write_c0_cause(c0_reg); /* write back cause register */ } static inline __ipl_t ipl_save(void) { unsigned int c0_reg; /* read mips status register */ c0_reg = mips_read_c0_status(); /* write back status register with cleaned irq mask*/ mips_write_c0_status(c0_reg & ~(ST0_IE)); /* return previous interrupt mask */ return c0_reg; } static inline void ipl_restore(__ipl_t ipl) { unsigned int c0_reg; /* read status registers for cleaning interrupts mask */ c0_reg = mips_read_c0_status(); if (ipl & ST0_IE) { mips_write_c0_status(c0_reg | ST0_IE); } else { mips_write_c0_status(c0_reg & ~ST0_IE); } } #endif /* MIPS_ASM_IPL_H_ */
580
2,236
<filename>solution/implementation/15787/main.py<gh_stars>1000+ # Authored by : yj2221 # Co-authored by : - # Link : http://boj.kr/a636cadadf8d444180ee022a5af9353a import sys def input(): return sys.stdin.readline().rstrip() n, m = map(int,input().split()) trains= [0] * (n+1) commands = [list(map(int, input().split())) for _ in range(m)] for command in commands: if command[0] == 1: _, i, x = command trains[i] |= (1 << (x-1)) elif command[0] == 2: _, i, x = command trains[i] &= ~(1 << (x-1)) elif command[0] == 3: _, i = command trains[i] = trains[i] << 1 trains[i] &= ((1 << 20) - 1) elif command[0] == 4: _, i = command trains[i] = trains[i] >> 1 result = set(trains[1:]) print(len(result))
385
437
<reponame>tayueliuxiang/spring-learning package com.brianway.learning.spring.aop.aspectj; import com.brianway.learning.spring.aop.aspectj.anno.NeedTest; public interface Waiter { @NeedTest void greetTo(String clientName); void serveTo(String clientName); }
112
380
/* * Copyright (c) 2017 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baidu.duer.dcs.framework; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import com.baidu.dcs.okhttp3.Call; import com.baidu.dcs.okhttp3.Response; import com.baidu.duer.dcs.api.IConnectionStatusListener; import com.baidu.duer.dcs.devicemodule.system.message.ThrowExceptionPayload; import com.baidu.duer.dcs.framework.decoder.IDecoder; import com.baidu.duer.dcs.framework.decoder.JLayerDecoderImpl; import com.baidu.duer.dcs.framework.dispatcher.AudioData; import com.baidu.duer.dcs.framework.dispatcher.MultipartParser; import com.baidu.duer.dcs.framework.heartbeat.HeartBeat; import com.baidu.duer.dcs.framework.message.DcsRequestBody; import com.baidu.duer.dcs.framework.message.DcsResponseBody; import com.baidu.duer.dcs.framework.message.DcsStreamRequestBody; import com.baidu.duer.dcs.framework.message.Directive; import com.baidu.duer.dcs.framework.message.Payload; import com.baidu.duer.dcs.http.HttpConfig; import com.baidu.duer.dcs.http.HttpRequestInterface; import com.baidu.duer.dcs.http.OkHttpRequestImpl; import com.baidu.duer.dcs.http.callback.ResponseCallback; import com.baidu.duer.dcs.util.LogUtil; import com.baidu.duer.dcs.util.NetWorkStateReceiver; import com.baidu.duer.dcs.util.NetWorkUtil; import com.baidu.duer.dcs.util.SystemServiceManager; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static com.baidu.duer.dcs.api.IConnectionStatusListener.ConnectionStatus.CONNECTED; /** * 和服务器端保持长连接、发送events和接收directives和维持心跳 * <p> * Created by wuruisheng on 2017/6/1. */ public class DcsClient { public static final String TAG = DcsClient.class.getSimpleName(); public static final long HTTP_DIRECTIVES_TIME = 60 * 60 * 1000; private final DcsResponseDispatcher dcsResponseDispatcher; private final HttpRequestInterface httpRequestImp; private final HeartBeat heartBeat; private IDcsClientListener dcsClientListener; private IDecoder decoder; private final MultipartParser directiveParser; private final MultipartParser eventParser; private final List<IConnectionStatusListener> connectStatusListeners; private volatile boolean isReleased; private NetWorkStateReceiver netWorkStateReceiver; private Context context = SystemServiceManager.getAppContext(); private volatile IConnectionStatusListener.ConnectionStatus connectStatus; private Handler handlerMain = new Handler(Looper.getMainLooper()); private CalculateRetryTime calculateRetryTime; private volatile boolean isNeedConnect; private Runnable startConnectRunnable = new Runnable() { @Override public void run() { // 下一次连接时重制状态 connect(); } }; /** * 建立连接 */ private final IResponseListener connectListener = new SimpleResponseListener() { @Override public void onSucceed(int statusCode) { LogUtil.d(TAG, "getDirectives statusCode: " + statusCode); if (statusCode == 200) { connectStatus = CONNECTED; fireConnectStatus(connectStatus); heartBeat.start(); stopTryConnect(); } else { tryConnect(); } } @Override public void onFailed(String errorMessage) { LogUtil.d(TAG, "getDirectives onFailed," + errorMessage); tryConnect(); } }; private final NetWorkStateReceiver.INetWorkStateListener netWorkStateListener = new NetWorkStateReceiver.INetWorkStateListener() { @Override public void onNetWorkStateChange(int netType) { Log.d(TAG, "onNetWorkStateChange-netType:" + netType); if (netType != NetWorkUtil.NETWORK_NONE) { Log.d(TAG, " onNetWorkStateChange "); tryConnectAtOnce(); } else { connectStatus = IConnectionStatusListener.ConnectionStatus.DISCONNECTED; fireConnectStatus(connectStatus); } } }; public DcsClient(DcsResponseDispatcher dcsResponseDispatcher, IDcsClientListener dcsClientListener) { this.dcsResponseDispatcher = dcsResponseDispatcher; this.dcsClientListener = dcsClientListener; httpRequestImp = new OkHttpRequestImpl(); heartBeat = new HeartBeat(httpRequestImp); decoder = new JLayerDecoderImpl(); MultipartParser.IMultipartParserListener parserListener = new ClientParserListener(); directiveParser = new MultipartParser(decoder, new ClientParserListener() { @Override public void onClose() { super.onClose(); Log.d(TAG, "directiveParser-onClose"); if (connectStatus != IConnectionStatusListener.ConnectionStatus.PENDING) { connectStatus = IConnectionStatusListener.ConnectionStatus.DISCONNECTED; fireConnectStatus(connectStatus); } tryConnectAtOnce(); } @Override public void onResponseBody(DcsResponseBody responseBody) { super.onResponseBody(responseBody); Directive directive = responseBody.getDirective(); if (directive != null) { Payload payload = directive.getPayload(); if (payload != null) { if (payload instanceof ThrowExceptionPayload) { // 服务器下发了ThrowException异常 isNeedConnect = false; } } } } }); eventParser = new MultipartParser(decoder, parserListener); netWorkStateReceiver = new NetWorkStateReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(netWorkStateReceiver, filter); netWorkStateReceiver.setOnNetWorkStateListener(netWorkStateListener); connectStatusListeners = new CopyOnWriteArrayList<>(); connectStatus = IConnectionStatusListener.ConnectionStatus.DISCONNECTED; calculateRetryTime = new CalculateRetryTime(); isNeedConnect = true; } public void release() { Log.d(TAG, "release"); stopTryConnect(); try { if (netWorkStateReceiver != null) { context.unregisterReceiver(netWorkStateReceiver); } } catch (Exception e) { e.printStackTrace(); } finally { isReleased = true; decoder.release(); heartBeat.release(); httpRequestImp.cancelRequest(HttpConfig.HTTP_DIRECTIVES_TAG); httpRequestImp.cancelRequest(HttpConfig.HTTP_EVENT_TAG); } } public void startConnect() { if (!isReleased) { getDirectives(connectListener); } } public boolean isConnected() { return connectStatus == IConnectionStatusListener.ConnectionStatus.CONNECTED; } private void tryConnectAtOnce() { resetRetryTime(); tryConnect(); } private void tryConnect() { if (isNeedConnect) { heartBeat.stop(); connectStatus = IConnectionStatusListener.ConnectionStatus.DISCONNECTED; fireConnectStatus(connectStatus); handlerMain.removeCallbacks(startConnectRunnable); handlerMain.postDelayed(startConnectRunnable, getRetryTime()); } } private void stopTryConnect() { resetRetryTime(); handlerMain.removeCallbacks(startConnectRunnable); } private void connect() { if (TextUtils.isEmpty(HttpConfig.getAccessToken())) { Log.d(TAG, "connect-accessToken is null !"); return; } if (!isReleased && connectStatus == IConnectionStatusListener.ConnectionStatus.DISCONNECTED) { if (NetWorkUtil.isNetworkConnected(context)) { connectStatus = IConnectionStatusListener.ConnectionStatus.PENDING; fireConnectStatus(connectStatus); getDirectives(connectListener); } else { connectStatus = IConnectionStatusListener.ConnectionStatus.DISCONNECTED; fireConnectStatus(connectStatus); } } } /** * 发送带流式请求 * * @param requestBody 消息体 * @param streamRequestBody stream式消息体 * @param listener 回调 */ public void sendRequest(DcsRequestBody requestBody, DcsStreamRequestBody streamRequestBody, final IResponseListener listener) { Log.e("logId", "logId send stream start"); decoder.interruptDecode(); httpRequestImp.cancelRequest(HttpConfig.HTTP_VOICE_TAG); httpRequestImp.doPostEventMultipartAsync(requestBody, streamRequestBody, getResponseCallback(eventParser, new IResponseListener() { @Override public void onSucceed(int statusCode) { if (listener != null) { listener.onSucceed(statusCode); } } @Override public void onFailed(String errorMessage) { if (listener != null) { listener.onFailed(errorMessage); } } })); } /** * 发送普通请求 * * @param requestBody 消息体 * @param listener 回调 */ public void sendRequest(DcsRequestBody requestBody, IResponseListener listener) { httpRequestImp.doPostEventStringAsync(requestBody, getResponseCallback(eventParser, listener)); } private void getDirectives(IResponseListener listener) { httpRequestImp.cancelRequest(HttpConfig.HTTP_DIRECTIVES_TAG); httpRequestImp.doGetDirectivesAsync(getResponseCallback(directiveParser, listener)); } private void fireOnConnected() { if (dcsClientListener != null) { dcsClientListener.onConnected(); } } private void fireOnUnconnected() { if (dcsClientListener != null) { dcsClientListener.onUnconnected(); } } private ResponseCallback getResponseCallback(final MultipartParser multipartParser, final IResponseListener responseListener) { return new ResponseCallback() { @Override public void onError(Call call, Exception e, int id) { LogUtil.d(TAG, "onError,", e); if (call.request().tag().equals(HttpConfig.DIRECTIVES) || call.request().tag().equals(HttpConfig.HTTP_VOICE_TAG)) { fireOnFailed(e.getMessage()); } } @Override public void onResponse(Response response, int id) { super.onResponse(response, id); LogUtil.d(TAG, "onResponse OK ," + response.request().url()); LogUtil.d(TAG, "onResponse code ," + response.code()); if (response.isSuccessful()) { if (responseListener != null) { responseListener.onSucceed(response.code()); } } } @Override public Response parseNetworkResponse(Response response, int id) throws Exception { int statusCode = response.code(); if (statusCode == 200) { Log.d(TAG, "onResponse OK ," + response.request().tag()); multipartParser.parseResponse(response); } return response; } void fireOnFailed(String errorMessage) { if (responseListener != null) { responseListener.onFailed(errorMessage); } } }; } public interface IDcsClientListener { void onConnected(); void onUnconnected(); } /** * 添加连接状态listener * * @param */ public void addConnectStatusListener(IConnectionStatusListener connectionStatusListener) { connectStatusListeners.add(connectionStatusListener); } public void removeConnectStatusListeners(IConnectionStatusListener connectionStatusListener) { connectStatusListeners.remove(connectionStatusListener); } private void fireConnectStatus(final IConnectionStatusListener.ConnectionStatus connectStatus) { handlerMain.post(new Runnable() { @Override public void run() { for (IConnectionStatusListener listener : connectStatusListeners) { listener.onConnectStatus(connectStatus); } } }); } private int getRetryTime() { return calculateRetryTime.getRetryTime(); } public void resetRetryTime() { calculateRetryTime.reset(); } private class ClientParserListener implements MultipartParser.IMultipartParserListener { @Override public void onResponseBody(DcsResponseBody responseBody) { DcsClient.this.dcsResponseDispatcher.onResponseBody(responseBody); } @Override public void onAudioData(AudioData audioData) { DcsClient.this.dcsResponseDispatcher.onAudioData(audioData); } @Override public void onParseFailed(String unParseMessage) { DcsClient.this.dcsResponseDispatcher.onParseFailed(unParseMessage); } @Override public void onHeartBeat() { // heartBeat.receiveHeartbeat(); } @Override public void onClose() { } } }
6,615
3,793
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2021 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFComm/NFPluginModule/NFIBluePrintModule.h" class NFCreateObjectExecutor : public NFIExecutor { private: NFCreateObjectExecutor() {} public: NFCreateObjectExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::CreateObject; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectInputArg::toString(NFExecutorCreateObjectInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectInputArg::toString(NFExecutorCreateObjectInputArg::ClassName); var->SetValueType(NFValueType::String); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectInputArg::toString(NFExecutorCreateObjectInputArg::ConfigID); var->SetValueType(NFValueType::String); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectInputArg::toString(NFExecutorCreateObjectInputArg::SceneID); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectInputArg::toString(NFExecutorCreateObjectInputArg::GroupID); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectInputArg::toString(NFExecutorCreateObjectInputArg::Position); var->SetValueType(NFValueType::Vector3); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectOutputputArg::toString(NFExecutorCreateObjectOutputputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorCreateObjectOutputputArg::toString(NFExecutorCreateObjectOutputputArg::ObjectID); var->SetValueType(NFValueType::Object); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFDestroyObjectExecutor : public NFIExecutor { private: NFDestroyObjectExecutor() {} public: NFDestroyObjectExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::DestroyObject; Init(); }; virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorDestroyObjectInputArg::toString(NFExecutorDestroyObjectInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorDestroyObjectInputArg::toString(NFExecutorDestroyObjectInputArg::ObjectID); var->SetValueType(NFValueType::Float); var->fromType = NFIODataComFromType::INTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorDestroyObjectInputArg::toString(NFExecutorDestroyObjectInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorDestroyObjectOutputputArg::toString(NFExecutorDestroyObjectOutputputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFGameEventExecutor : public NFIExecutor { private: NFGameEventExecutor() {} public: NFGameEventExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::GameEvent; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorGameEventInputArg::toString(NFExecutorGameEventInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorGameEventInputArg::toString(NFExecutorGameEventInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorGameEventInputArg::toString(NFExecutorGameEventInputArg::EventID); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorGameEventInputArg::toString(NFExecutorGameEventInputArg::Dctionary); var->SetValueType(NFValueType::Dictionary); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorGameEventOutputArg::toString(NFExecutorGameEventOutputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFMoveObjectExecutor : public NFIExecutor { private: NFMoveObjectExecutor() {} public: NFMoveObjectExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::MoveObject; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorMoveObjectInputArg::toString(NFExecutorMoveObjectInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorMoveObjectInputArg::toString(NFExecutorMoveObjectInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorMoveObjectInputArg::toString(NFExecutorMoveObjectInputArg::Position); var->SetValueType(NFValueType::Vector3); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorMoveObjectInputArg::toString(NFExecutorMoveObjectInputArg::MoveType); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorMoveObjectOutputArg::toString(NFExecutorMoveObjectOutputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFSendMessageExecutor : public NFIExecutor { private: NFSendMessageExecutor() {} public: NFSendMessageExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::SendMessage; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSendMessageInputArg::toString(NFExecutorSendMessageInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSendMessageInputArg::toString(NFExecutorSendMessageInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::BOTH; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSendMessageInputArg::toString(NFExecutorSendMessageInputArg::MessageID); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::BOTH; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSendMessageInputArg::toString(NFExecutorSendMessageInputArg::Data); var->SetValueType(NFValueType::Dictionary); var->fromType = NFIODataComFromType::BOTH; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorMoveObjectOutputArg::toString(NFExecutorMoveObjectOutputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFEnterSceneExecutor : public NFIExecutor { private: NFEnterSceneExecutor() {} public: NFEnterSceneExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::EnterScene; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorEnterSceneInputArg::toString(NFExecutorEnterSceneInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorEnterSceneInputArg::toString(NFExecutorEnterSceneInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorEnterSceneInputArg::toString(NFExecutorEnterSceneInputArg::SceneID); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorEnterSceneInputArg::toString(NFExecutorEnterSceneInputArg::GroupID); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorEnterSceneInputArg::toString(NFExecutorEnterSceneInputArg::Position); var->SetValueType(NFValueType::Vector3); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorEnterSceneOutputArg::toString(NFExecutorEnterSceneOutputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFSleepExecutor : public NFIExecutor { private: NFSleepExecutor() {} public: NFSleepExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::Sleep; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSleepInputArg::toString(NFExecutorSleepInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSleepInputArg::toString(NFExecutorSleepInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSleepInputArg::toString(NFExecutorSleepInputArg::SleepTime); var->SetValueType(NFValueType::Float); var->fromType = NFIODataComFromType::BOTH; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSleepOutputArg::toString(NFExecutorSleepOutputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorSleepOutputArg::toString(NFExecutorSleepOutputArg::ObjectID); var->SetValueType(NFValueType::Object); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFAddHeartBeatExecutor : public NFIExecutor { private: NFAddHeartBeatExecutor() {} public: NFAddHeartBeatExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::AddHeartBeat; Init(); } virtual void InitInputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorAddHeartBeatInputArg::toString(NFExecutorAddHeartBeatInputArg::PreNode); var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorAddHeartBeatInputArg::toString(NFExecutorAddHeartBeatInputArg::ObjectID); var->SetValueType(NFValueType::Object); var->fromType = NFIODataComFromType::EXTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorAddHeartBeatInputArg::toString(NFExecutorAddHeartBeatInputArg::BeatName); var->SetValueType(NFValueType::String); var->fromType = NFIODataComFromType::INTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorAddHeartBeatInputArg::toString(NFExecutorAddHeartBeatInputArg::BeatTime); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::INTERNAL; inputArgs.push_back(var); } { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorAddHeartBeatInputArg::toString(NFExecutorAddHeartBeatInputArg::BeatCount); var->SetValueType(NFValueType::Int); var->fromType = NFIODataComFromType::INTERNAL; inputArgs.push_back(var); } } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = NFExecutorAddHeartBeatOutputArg::toString(NFExecutorAddHeartBeatOutputArg::NextNode); var->SetValueType(NFValueType::Node); outputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; }; class NFAttackObjectExecutor : public NFIExecutor { private: NFAttackObjectExecutor() {} public: NFAttackObjectExecutor(NFIPluginManager* p, const NFGUID& blockID, const NFGUID& id, const std::string& name) { this->id = id; this->name = name; this->logicBlockId = blockID; this->pPluginManager = p; executerType = NFExecutorType::AttackObject; Init(); } virtual void InitInputArgs() { } virtual void InitOutputArgs() { { NF_SHARE_PTR<NFIOData> var = NF_SHARE_PTR<NFIOData>(NF_NEW NFIOData()); var->id = this->pPluginManager->FindModule<NFIKernelModule>()->CreateGUID(); var->name = "NextNode"; var->SetValueType(NFValueType::Node); inputArgs.push_back(var); } } virtual void UpdateOutputData(const NFGUID& runTimeOwner) override; virtual NF_SHARE_PTR<NFIOData> FindOutputNodeIOData() override; };
8,774
145,614
<reponame>NavpreetDevpuri/Python """ Similarity Search : https://en.wikipedia.org/wiki/Similarity_search Similarity search is a search algorithm for finding the nearest vector from vectors, used in natural language processing. In this algorithm, it calculates distance with euclidean distance and returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector (float) """ from __future__ import annotations import math import numpy as np def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates euclidean distance between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Euclidean distance of input_a and input_b. By using math.sqrt(), result will be float. >>> euclidean(np.array([0]), np.array([1])) 1.0 >>> euclidean(np.array([0, 1]), np.array([1, 1])) 1.0 >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) 1.0 """ return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> list[list[list[float] | float]]: """ :param dataset: Set containing the vectors. Should be ndarray. :param value_array: vector/vectors we want to know the nearest vector from dataset. :return: Result will be a list containing 1. the nearest vector 2. distance from the vector >>> dataset = np.array([[0], [1], [2]]) >>> value_array = np.array([[0]]) >>> similarity_search(dataset, value_array) [[[0], 0.0]] >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] These are the errors that might occur: 1. If dimensions are different. For example, dataset has 2d array and value_array has 1d array: >>> dataset = np.array([[1]]) >>> value_array = np.array([1]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 2. If data's shapes are different. For example, dataset has shape of (3, 2) and value_array has (2, 3). We are expecting same shapes of two arrays, so it is wrong. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's shape... dataset : 2, value_array : 3 3. If data types are different. When trying to compare, we are expecting same types so they should be same. If not, it'll come up with errors. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: Input data have different datatype... dataset : float32, value_array : int32 """ if dataset.ndim != value_array.ndim: raise ValueError( f"Wrong input data's dimensions... dataset : {dataset.ndim}, " f"value_array : {value_array.ndim}" ) try: if dataset.shape[1] != value_array.shape[1]: raise ValueError( f"Wrong input data's shape... dataset : {dataset.shape[1]}, " f"value_array : {value_array.shape[1]}" ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: raise TypeError( f"Input data have different datatype... dataset : {dataset.dtype}, " f"value_array : {value_array.dtype}" ) answer = [] for value in value_array: dist = euclidean(value, dataset[0]) vector = dataset[0].tolist() for dataset_value in dataset[1:]: temp_dist = euclidean(value, dataset_value) if dist > temp_dist: dist = temp_dist vector = dataset_value.tolist() answer.append([vector, dist]) return answer if __name__ == "__main__": import doctest doctest.testmod()
1,961
889
import numpy as np import hyperchamber as hc import inspect import collections from hypergan.trainers.base_trainer import BaseTrainer TINY = 1e-12 cg_state = collections.namedtuple("CGState", ["i", "x", "r", "p", "rdotr", "alpha"]) def update_vars(state1, state2): ops = [] for name in state1._fields: state1_vs = getattr(state1, name) if isinstance(state1_vs, list): ops += [tf.assign(_v1, _v2) for _v1, _v2 in zip(state1_vs, getattr(state2, name))] else: ops += [tf.assign(state1_vs, getattr(state2, name))] return tf.group(*ops) def build_vars(state): args = [] variables = [] for name in state._fields: vs = getattr(state, name) if name == 'alpha': sv = tf.Variable(vs, trainable=False, name=name+"_sv_dontsave") variables += [sv] elif isinstance(vs, list): sv = [tf.Variable(tf.zeros_like(v), trainable=False, name=name+"_sv_dontsave") for v in vs] variables += sv else: sv = tf.Variable(tf.zeros_like(vs), trainable=False, name=name+"_sv_dontsave") variables += [sv] args.append(sv) return cg_state(*args), variables def tf_conjugate_gradient(operator, rhs, tol=1e-4, max_iter=20, alpha=1.0, config={}, loss=None, params=None, name="conjugate_gradient"): r""" modified from tensorflow/contrib/solvers/python/ops/linear_equations.py """ def dot(x, y): x = [tf.reshape(_x, [-1]) for _x in x] y = [tf.reshape(_y, [-1]) for _y in y] x = tf.concat(x, axis=0) y = tf.concat(y, axis=0) return tf.reduce_sum(tf.multiply(x,y)) def cg_step(state): # pylint: disable=missing-docstring #z = [p * h2 for p, h2 in zip(state.p, operator.apply(state.p))] grad = operator.apply(state.p) if config.z == "p+grad": z = [_grad + _p for _grad, _p in zip(grad, state.p)] else: z = grad if config.alpha == "hager_zhang": ValueAndGradient = collections.namedtuple('ValueAndGradient', ['x', 'f', 'df']) def value_and_gradients_function(x): return ValueAndGradient(x=params, f=loss, df=tf.gradients(loss, params)) ls_result = tfp.optimizer.linesearch.hager_zhang(value_and_gradients_function, initial_step_size=1.0) alpha = ls_result.left else: #alpha = dot(z,z) / (dot(state.p, state.p)+1e-32) alpha = state.alpha#tf.Print(state.alpha, [state.alpha], "Alpha:") #x = [_alpha * _p + _x for _alpha, _p, _x in zip(alpha, state.p, state.x)] print("X", state.x) print("P", state.p) print("alpha", alpha) x = [alpha * _p + _x for _p, _x in zip(state.p, state.x)] r_1 = state.r r = grad#z#[alpha * _z + _r for _z, _r in zip(z, state.r)] new_rdotr = dot(r, r) beta_fr = new_rdotr / (rdotr+1e-32) y = [_r - _p for _r, _p in zip(r, state.p)] beta_pk = tf.nn.relu(dot(r, y) / (dot(state.p, state.p)+1e-32)) beta_bycd = dot(r, r) / tf.maximum( dot( state.p, y ), dot( [-_p for _p in state.p], r_1 ) ) p = [_r + beta_bycd * _p for _r, _p in zip(r,state.p)] i = state.i + 1 return cg_state(i, x, r, p, new_rdotr, alpha) with tf.name_scope(name): x = [tf.zeros_like(h) for h in rhs] rdotr = dot(rhs, rhs) #p = [-_p for _p in rhs] p = rhs state = cg_state(i=0, x=x, r=p, p=p, rdotr=rdotr, alpha=alpha) state, variables = build_vars(state) def update_op(state): return update_vars(state, cg_step(state)) def reset_op(state, rhs): return update_vars(state, cg_step(cg_state(i=0, x=x, r=[state.alpha * _g for _g in rhs], p=[state.alpha * _g for _g in rhs], rdotr=rdotr, alpha=state.alpha))) return [reset_op(state, rhs), update_op(state), variables, state] class CGOperator: def __init__(self, hvp, x_loss, y_loss, x_params, y_params, lr): self.hvp = hvp self.x_loss = x_loss self.y_loss = y_loss self.x_params = x_params self.y_params = y_params self.lr = lr def apply(self, p): lr_x = self.lr#tf.sqrt(self.lr) lr_y = self.lr h_1_v = self.hvp(self.x_loss, self.y_params, self.x_params, [lr_x * _p for _p in p]) for _x, _h in zip(self.x_params, h_1_v): if _h is None: print("X none", _x) h_2_v = self.hvp(self.y_loss, self.x_params, self.y_params, [lr_y * _h for _h in h_1_v]) return h_2_v #return [lr_x * _g for _g in h_2_v] class CompetitiveTrainer(BaseTrainer): def hessian_vector_product(self, ys, xs, xs2, vs, grads=None): if len(vs) != len(xs): raise ValueError("xs and v must have the same length.") if grads is None: grads = tf.gradients(ys, xs) assert len(grads) == len(xs) elemwise_products = [ math_ops.multiply(grad_elem, tf.stop_gradient(v_elem)) for grad_elem, v_elem in zip(grads, vs) if grad_elem is not None ] return tf.gradients(elemwise_products, xs2) def _create(self): gan = self.gan config = self.config lr = self.config.learn_rate loss = self.gan.loss d_loss, g_loss = loss.sample config.optimizer["loss"] = loss.sample self.optimizer = self.gan.create_optimizer(config.optimizer) d_grads = tf.gradients(d_loss, gan.d_vars()) g_grads = tf.gradients(g_loss, gan.g_vars()) self.g_loss = g_loss self.d_loss = d_loss self.gan.trainer = self d_params = gan.d_vars() g_params = gan.g_vars() clarified_d_grads = [tf.Variable(tf.zeros_like(v), trainable=False, name=v.name.split(":")[0]+"_sv_dontsave") for v in d_grads] clarified_g_grads = [tf.Variable(tf.zeros_like(v), trainable=False, name=v.name.split(":")[0]+"_sv_dontsave") for v in g_grads] clarified_grads = clarified_d_grads + clarified_g_grads operator_g = CGOperator(hvp=self.hessian_vector_product, x_loss=d_loss, y_loss=g_loss, x_params=d_params, y_params=g_params, lr=lr) reset_g_op, cg_g_op, var_g, state_g = tf_conjugate_gradient( operator_g, clarified_g_grads, max_iter=(self.config.nsteps or 10), config=(self.config.conjugate or hc.Config({})), alpha=(self.config.initial_alpha or 1.0), loss=g_loss, params=g_params) operator_d = CGOperator(hvp=self.hessian_vector_product, x_loss=g_loss, y_loss=d_loss, x_params=g_params, y_params=d_params, lr=lr) reset_d_op, cg_d_op, var_d, state_d = tf_conjugate_gradient( operator_d, clarified_d_grads, max_iter=(self.config.nsteps or 10), config=(self.config.conjugate or hc.Config({})), alpha=(self.config.initial_alpha or 1.0), loss=d_loss, params=d_params) self._variables = var_g + var_d + clarified_g_grads + clarified_d_grads assign_d = [tf.assign(c, x) for c, x in zip(clarified_d_grads, d_grads)] assign_g = [tf.assign(c, y) for c, y in zip(clarified_g_grads, g_grads)] self.reset_clarified_gradients = tf.group(*(assign_d+assign_g)) self.reset_conjugate_tracker = tf.group(reset_g_op, reset_d_op) self.conjugate_gradient_descend_t_1 = tf.group(cg_g_op, cg_d_op) assign_d2 = [tf.assign(c, x) for c, x in zip(clarified_d_grads, state_d.x)] assign_g2 = [tf.assign(c, y) for c, y in zip(clarified_g_grads, state_g.x)] self.conjugate_gradient_descend_t_2 = tf.group(*(assign_d2+assign_g2)) self.gan.add_metric('cg_g', sum([ tf.reduce_sum(tf.abs(_p)) for _p in clarified_g_grads])) if self.config.sga_lambda: dyg = tf.gradients(g_loss, g_params) dxf = tf.gradients(d_loss, d_params) hyp_d = self.hessian_vector_product(d_loss, g_params, d_params, [self.config.sga_lambda * _g for _g in dyg]) hyp_g = self.hessian_vector_product(g_loss, d_params, g_params, [self.config.sga_lambda * _g for _g in dxf]) sga_g_op = [tf.assign_sub(_g, _h) for _g, _h in zip(clarified_g_grads, ([state_g.alpha * _g for _g in hyp_g]))] sga_d_op = [tf.assign_sub(_g, _h) for _g, _h in zip(clarified_d_grads, ([state_d.alpha * _g for _g in hyp_d]))] self.sga_step_t = tf.group(*(sga_d_op + sga_g_op)) self.gan.add_metric('hyp_g', sum([ tf.reduce_mean(_p) for _p in hyp_g])) self.gan.add_metric('hyp_d', sum([ tf.reduce_mean(_p) for _p in hyp_d])) #self.clarification_metric_g = sum(state_g.rdotr) #self.clarification_metric_d = sum(state_d.rdotr) def _metric(r): #return tf.reduce_max(tf.convert_to_tensor([tf.reduce_max(tf.norm(_r)) for _r in r])) return [tf.reduce_max(tf.norm(_r)) for _r in r][0] self.clarification_metric_g = state_g.rdotr self.clarification_metric_d = state_d.rdotr all_vars = d_params + g_params new_grads_and_vars = list(zip(clarified_grads, all_vars)).copy() self.last_mx = 1e12 self.last_my = 1e12 self.alpha = state_g.alpha self.alpha_value= tf.constant(1.0) set_alpha_d = tf.assign(state_d.alpha, self.alpha_value) set_alpha_g = tf.assign(state_g.alpha, self.alpha_value) self.set_alpha = tf.group(set_alpha_d, set_alpha_g) self.optimize_t = self.optimizer.apply_gradients(new_grads_and_vars) def required(self): return "".split() def variables(self): return super().variables() + self._variables def _step(self, feed_dict): gan = self.gan sess = gan.session config = self.config loss = gan.loss metrics = gan.metrics() d_loss, g_loss = loss.sample self.before_step(self.current_step, feed_dict) sess.run(self.reset_clarified_gradients, feed_dict) sess.run(self.reset_conjugate_tracker, feed_dict) i=0 sess.run(self.set_alpha, {self.alpha_value: (self.config.initial_alpha or 1.0)}) alpha = sess.run(self.alpha) if self.config.sga_lambda: sess.run(self.sga_step_t, feed_dict) while True: i+=1 mx, my, _ = sess.run([self.clarification_metric_d, self.clarification_metric_g, self.conjugate_gradient_descend_t_1], feed_dict) if i == 1: initial_clarification_metric_g = my initial_clarification_metric_d = mx dy = my dx = mx my_t1 = my mx_t1 = mx else: dy = my_t1 - my dx = mx_t1 - mx my_t1 = my mx_t1 = mx if self.config.log_level == "info": alpha = sess.run(self.alpha) print("-MD %e MG %e alpha %e" % (mx, my, alpha)) if mx > initial_clarification_metric_d or my > initial_clarification_metric_g or np.isnan(mx) or np.isnan(my) or np.isinf(mx) or np.isinf(my): sess.run(self.set_alpha, {self.alpha_value: alpha / 2.0}) sess.run(self.reset_clarified_gradients, feed_dict) sess.run(self.reset_conjugate_tracker, feed_dict) if self.config.sga_lambda: sess.run(self.sga_step_t, feed_dict) new_alpha = sess.run(self.alpha) if new_alpha < 1e-10: print("Alpha too low, exploding") break print(i, "Explosion detected, reduced alpha from ", alpha, "to", new_alpha) alpha = new_alpha i=0 continue threshold_x = mx / (initial_clarification_metric_d+1e-12) threshold_y = my / (initial_clarification_metric_g+1e-12) threshold = threshold_x + threshold_y if self.config.max_steps and i > self.config.max_steps: if self.config.verbose: print("Max steps ", self.config.max_steps, "threshold", threshold, "max", self.config.threshold, "mx", mx, "my", my) break #print( "p", i, dx / mx, dy / my, self.config.threshold, dy / my > self.config.threshold) if i % 100 == 0 and i != 0: print("Threshold at", i, threshold_x, threshold_y, "last", self.last_mx, self.last_my, "m", mx, my, "d", dx, dy) #self.last_mx = (self.last_mx + 1e-16) * 1.05 #self.last_my = (self.last_my + 1e-16) * 1.05 #if ((dx / (initial_clarification_metric_d+1e-12)) < self.config.threshold and (dy / (initial_clarification_metric_g+1e-12)) < self.config.threshold and my <= self.last_my and mx <= self.last_mx): if mx < self.config.threshold and my < self.config.threshold: #self.last_mx = mx #self.last_my = my sess.run(self.conjugate_gradient_descend_t_2) if self.config.verbose: print("Found in ", i, "threshold", threshold, "mx", mx, "my", my, "alpha", alpha) break metric_values = sess.run([self.optimize_t] + self.output_variables(metrics), feed_dict)[1:] self.after_step(self.current_step, feed_dict) if self.current_step % 10 == 0: print(str(self.output_string(metrics) % tuple([self.current_step] + metric_values)))
6,888
831
<gh_stars>100-1000 from siuba import spread, gather, _ from pandas.testing import assert_frame_equal import pandas as pd import pytest @pytest.fixture def df(): return pd.DataFrame({ 'id': [1, 1, 2], 'm': ['a', 'b', 'b'], 'v': [1,2,3] }) @pytest.fixture def wide_df(): return pd.DataFrame({ 'id': [1,2], 'a': [1, None], 'b': [2., 3.] }) @pytest.mark.parametrize('key, value', [ ("m", "v"), (_.m, _.v), (_["m"], _["v"]), (1, 2), ]) def test_spread_selection(df, wide_df, key, value): res = spread(df, key, value) assert_frame_equal(res, wide_df) def test_spread_fill(df, wide_df): res = spread(df, "m", "v", fill = 99) assert_frame_equal(res, wide_df.fillna(99.)) def test_spread_grouped_df(df, wide_df): gdf = df.groupby('id') res = spread(gdf, "m", "v") gdf_wide = wide_df.groupby('id') assert_frame_equal(res.obj, gdf_wide.obj) assert len(res.grouper.groupings) == 1 assert res.grouper.groupings[0].name == "id" def test_gather(df, wide_df): res = gather(wide_df, "m", "v", "a", "b") # note, unlike df, includes an NA now long = pd.DataFrame({ 'id': [1,2,1,2], 'm': ['a', 'a', 'b', 'b'], 'v': [1, None, 2, 3] }) assert_frame_equal(res, long) def test_gather_drop_na(df, wide_df): res = gather(wide_df, "m", "v", "a", "b", drop_na = True) # note that .dropna doesn't work here, since coerces floats to ints assert_frame_equal(res, df.assign(v = df.v.astype(float))) def test_gather_drop_na_varselect(df, wide_df): res = gather(wide_df, "m", "v", _["a": "b"], drop_na = True) # note that .dropna doesn't work here, since coerces floats to ints assert_frame_equal(res, df.assign(v = df.v.astype(float)))
873
1,323
<reponame>bradmccoydev/keptn { "type": "sh.keptn.event.firststage.echosequence.triggered", "specversion": "1.0", "source": "travis-ci", "contenttype": "application/json", "data": { "project": "linking-stages-project", "stage": "firststage", "service": "linking-stages-service" } }
147
994
<reponame>IT-Enthusiast-Nepal/Windows-Driver-Frameworks<gh_stars>100-1000 /*++ Copyright (c) Microsoft Corporation ModuleName: MxDeviceObjectUm.cpp Abstract: User Mode implementation of Device Object defined in MxDeviceObject.h --*/ #include "fxmin.hpp" #include "fxldrum.h" PVOID MxDriverObject::GetDriverExtensionAddDevice( VOID ) { return m_DriverObject->AddDevice; } VOID MxDriverObject::SetDriverExtensionAddDevice( _In_ MdDriverAddDevice Value ) { m_DriverObject->AddDevice = Value; } MdDriverUnload MxDriverObject::GetDriverUnload( VOID ) { m_DriverObject->DriverUnload; return NULL; } VOID MxDriverObject::SetDriverUnload( _In_ MdDriverUnload Value ) { m_DriverObject->DriverUnload = Value; } VOID MxDriverObject::SetMajorFunction( _In_ UCHAR i, _In_ MdDriverDispatch Value ) { m_DriverObject->MajorFunction[i] = Value; } VOID MxDriverObject::SetDriverObjectFlag( _In_ FxDriverObjectUmFlags Flag ) { m_DriverObject->Flags |= Flag; } BOOLEAN MxDriverObject::IsDriverObjectFlagSet( _In_ FxDriverObjectUmFlags Flag ) { return (!!(m_DriverObject->Flags & Flag)); }
478
354
<reponame>d-m-bailey/openlane-openroad<gh_stars>100-1000 # Copyright 2020 Efabless Corporation # # 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. import json import argparse import os parser = argparse.ArgumentParser( description="top module generation helper to show the optional fields of a given pad") parser.add_argument('--padType', '-t', action='store', required=False, help="The pad type to show the mapping for") parser.add_argument('--showPadTypes', '-s', action='store_true', default=False, help="A flag to list all the available pad types in a given library.") parser.add_argument('--padsLibs', '-p', action='store', required=True, help="The pad libraries json description") parser.add_argument('--padsLibName', '-n', action='store', required=True, help="The name of the pad library to use from the given padsLibs") args = parser.parse_args() padType = args.padType padsLibs = args.padsLibs showPadTypes = args.showPadTypes padsLibName = args.padsLibName if padType is None and showPadTypes == False: print("Please either specify a pad type to show the mapping for, or use the showPadTypes flag to list all possible types in the library") else: #description of the libraries parsed into a dict if not os.path.exists(padsLibs): raise IOError("file not found: " + padsLibs) padsLibsJSONOpener = open(padsLibs, 'r') padsLibs_json = json.load(padsLibsJSONOpener) padsLibsJSONOpener.close() #Finding the used pads library padsLib_json = dict() for padsLib in padsLibs_json: if padsLib["library_name"] == padsLibName: padsLib_json = padsLib break if len(padsLib_json) == 0: raise Exception("Used Pad Lib is not found in the given Pad Libraries JSON") if showPadTypes: for pad in padsLib_json["pads"]: if "mapping" in pad: print(pad["type"]) if padType is not None: for pad in padsLib_json["pads"]: if padType == pad["type"]: print("print mapping for pad", padType) print("key : mapped_to") for mapping in pad["mapping"].keys(): print(mapping, " : ", pad["mapping"][mapping]) break
1,268
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Bignicourt","circ":"1ère circonscription","dpt":"Ardennes","inscrits":63,"abs":32,"votants":31,"blancs":1,"nuls":1,"exp":29,"res":[{"nuance":"LR","nom":"<NAME>","voix":25},{"nuance":"REM","nom":"<NAME>","voix":4}]}
108
32,544
package com.baeldung.features.sealed; public non-sealed class Snake implements JungleAnimal { }
29
9,718
<reponame>yash7raut/IoT-For-Beginners #include <Arduino.h> #include "Seeed_vl53l0x.h" Seeed_vl53l0x VL53L0X; void setup() { Serial.begin(9600); while (!Serial) ; // Wait for Serial to be ready delay(1000); VL53L0X.VL53L0X_common_init(); VL53L0X.VL53L0X_high_accuracy_ranging_init(); } void loop() { VL53L0X_RangingMeasurementData_t RangingMeasurementData; memset(&RangingMeasurementData, 0, sizeof(VL53L0X_RangingMeasurementData_t)); VL53L0X.PerformSingleRangingMeasurement(&RangingMeasurementData); Serial.print("Distance = "); Serial.print(RangingMeasurementData.RangeMilliMeter); Serial.println(" mm"); delay(1000); }
298
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_DBUS_DBUS_THREAD_LINUX_H_ #define CHROME_BROWSER_DBUS_DBUS_THREAD_LINUX_H_ #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "build/build_config.h" // Many APIs in ::dbus are required to be called from the same thread // (https://crbug.com/130984). Therefore, a SingleThreadedTaskRunner is // maintained and accessible through GetDBusTaskRunner(), from which all calls // to dbus on Linux have to be made. #if defined(OS_CHROMEOS) #error On ChromeOS, use DBusThreadManager instead. #endif namespace chrome { scoped_refptr<base::SingleThreadTaskRunner> GetDBusTaskRunner(); } // namespace chrome #endif // CHROME_BROWSER_DBUS_DBUS_THREAD_LINUX_H_
295
454
package cn.originx.scaffold.component; import cn.originx.refine.Ox; import cn.vertxup.jet.domain.tables.pojos.IService; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.tp.atom.modeling.data.DataAtom; import io.vertx.tp.atom.refine.Ao; import io.vertx.tp.jet.refine.Jt; import io.vertx.tp.jet.uca.business.AbstractJob; import io.vertx.tp.modular.dao.AoDao; import io.vertx.up.annotations.Contract; import io.vertx.up.atom.Refer; import io.vertx.up.atom.worker.Mission; import io.vertx.up.commune.Envelop; import io.vertx.up.commune.rule.RuleUnique; import io.vertx.up.eon.ID; import io.vertx.up.uca.job.plugin.JobIncome; import io.vertx.up.unity.Ux; /** * ## 「Income」顶层任务前置器 * * ### 1. 基本介绍 * * 任务执行流程`Income -> Channel -> Outcome`中的`Income`前置对象,在任务通道之前执行。 * * ### 2. 组件功能 * * - 实现了{@link JobIncome}接口。 * - 从{@link AbstractJob}继承。 * - 参数执行`$$__BODY__$$`数据封装,包含单记录和多记录两种数据结构。 * * @author <a href="http://www.origin-x.cn">Lang</a> */ public abstract class AbstractIncome extends AbstractJob implements JobIncome { /** * 「合约」Vertx实例引用 */ @Contract private transient Vertx vertx; /** * 「合约」{@link Mission}任务配置成员,从`I_JOB`中提取任务配置并执行计算。 */ @Contract private transient Mission mission; /** * 返回Vertx实例。 * * @return {@link Vertx}实例 */ protected Vertx vertx() { return this.vertx; } /** * 返回任务配置实例。 * * @return {@link Mission}任务配置。 */ @Override protected Mission mission() { return this.mission; } /** * 「批量」请求转换器。 * * @param array {@link JsonArray} 数组数据。 * @param request {@link Envelop} Zero统一数据请求模型。 * * @return {@link Future}<{@link Envelop}> 复刻后请求 */ protected Future<Envelop> output(final JsonArray array, final Envelop request) { final JsonObject data = new JsonObject(); data.put(ID.PARAM_BODY, array); return Ux.future(Envelop.success(data).from(request)); } /** * 「批量」请求转换器。 * * @param json {@link JsonObject} 记录数据。 * @param request {@link Envelop} Zero统一数据请求模型。 * * @return {@link Future}<{@link Envelop}> 复刻后请求 */ protected Future<Envelop> output(final JsonObject json, final Envelop request) { final JsonObject data = new JsonObject(); data.put(ID.PARAM_BODY, json); return Ux.future(Envelop.success(data).from(request)); } /** * 成员函数,读取静态模型定义对象{@link DataAtom}。 * * 该组件中的{@link DataAtom}模型定义对象是通过`I_SERVICE`直接构造,非合约提取。 * * @return {@link DataAtom}计算过后的模型定义 */ protected DataAtom atom() { final IService service = this.service(); final RuleUnique rule = Jt.toRule(service); return Ox.toAtom(service.getSigma(), service.getIdentifier()).ruleConnect(rule); } /** * 「Async」异步提取当前组件所使用的数据库访问器。 * * @return {@link Future}<{@link AoDao}> */ protected Future<AoDao> dao() { return Ux.future(Ao.toDao(this.database(), this.atom())); } /** * 「Async」参数专用容器,可在`Income -> Channel -> Outcome`中执行参数传递(底层参数传输)。 * * @return {@link Future}引用容器 */ @Override public Future<Refer> underway() { /* * Parameters */ final String identifier = this.atom().identifier(); return super.underway(identifier); } }
2,035
8,477
<gh_stars>1000+ # -*- coding: utf-8 -*- import unittest from prompt_toolkit.document import Document from http_prompt.completer import HttpPromptCompleter from http_prompt.context import Context class TestCompleter(unittest.TestCase): def setUp(self): self.context = Context('http://localhost', spec={ 'paths': { '/users': {}, '/users/{username}': {}, '/users/{username}/events': {}, '/users/{username}/orgs': {}, '/orgs': {}, '/orgs/{org}': {}, '/orgs/{org}/events': {}, '/orgs/{org}/members': {} } }) self.completer = HttpPromptCompleter(self.context) self.completer_event = None def get_completions(self, command): if not isinstance(command, str): command = command.decode() position = len(command) completions = self.completer.get_completions( Document(text=command, cursor_position=position), self.completer_event) return [c.text for c in completions] def test_header_name(self): result = self.get_completions('ctype') self.assertEqual(result[0], 'Content-Type') def test_header_value(self): result = self.get_completions('Content-Type:json') self.assertEqual(result[0], 'application/json') def test_verify_option(self): result = self.get_completions('--vfy') self.assertEqual(result[0], '--verify') def test_preview_then_action(self): result = self.get_completions('httpie po') self.assertEqual(result[0], 'post') def test_rm_body_param(self): self.context.body_params['my_name'] = 'dont_care' result = self.get_completions('rm -b ') self.assertEqual(result[0], 'my_name') def test_rm_body_json_param(self): self.context.body_json_params['number'] = 2 result = self.get_completions('rm -b ') self.assertEqual(result[0], 'number') def test_rm_querystring_param(self): self.context.querystring_params['my_name'] = 'dont_care' result = self.get_completions('rm -q ') self.assertEqual(result[0], 'my_name') def test_rm_header(self): self.context.headers['Accept'] = 'dont_care' result = self.get_completions('rm -h ') self.assertEqual(result[0], 'Accept') def test_rm_option(self): self.context.options['--form'] = None result = self.get_completions('rm -o ') self.assertEqual(result[0], '--form') def test_querystring_with_chinese(self): result = self.get_completions('name==王') self.assertFalse(result) def test_header_with_spanish(self): result = self.get_completions('X-Custom-Header:Jesú') self.assertFalse(result) def test_options_method(self): result = self.get_completions('opt') self.assertEqual(result[0], 'options') def test_ls_no_path(self): result = self.get_completions('ls ') self.assertEqual(result, ['orgs', 'users']) def test_ls_no_path_substring(self): result = self.get_completions('ls o') self.assertEqual(result, ['orgs']) def test_ls_absolute_path(self): result = self.get_completions('ls /users/1/') self.assertEqual(result, ['events', 'orgs']) def test_ls_absolute_path_substring(self): result = self.get_completions('ls /users/1/e') self.assertEqual(result, ['events']) def test_ls_relative_path(self): self.context.url = 'http://localhost/orgs' result = self.get_completions('ls 1/') self.assertEqual(result, ['events', 'members']) def test_cd_no_path(self): result = self.get_completions('cd ') self.assertEqual(result, ['orgs', 'users']) def test_cd_no_path_substring(self): result = self.get_completions('cd o') self.assertEqual(result, ['orgs']) def test_cd_absolute_path(self): result = self.get_completions('cd /users/1/') self.assertEqual(result, ['events', 'orgs']) def test_cd_absolute_path_substring(self): result = self.get_completions('cd /users/1/e') self.assertEqual(result, ['events']) def test_cd_relative_path(self): self.context.url = 'http://localhost/orgs' result = self.get_completions('cd 1/') self.assertEqual(result, ['events', 'members'])
2,028
3,358
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 <NAME> This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <<EMAIL>>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/experimental/commodities/energyswap.hpp> #include <ql/settings.hpp> #include <utility> namespace QuantLib { EnergySwap::EnergySwap(Calendar calendar, Currency payCurrency, Currency receiveCurrency, PricingPeriods pricingPeriods, const CommodityType& commodityType, const ext::shared_ptr<SecondaryCosts>& secondaryCosts) : EnergyCommodity(commodityType, secondaryCosts), calendar_(std::move(calendar)), payCurrency_(std::move(payCurrency)), receiveCurrency_(std::move(receiveCurrency)), pricingPeriods_(std::move(pricingPeriods)) {} const CommodityType& EnergySwap::commodityType() const { QL_REQUIRE(!pricingPeriods_.empty(), "no pricing periods"); return pricingPeriods_[0]->quantity().commodityType(); } Quantity EnergySwap::quantity() const { Real totalQuantityAmount = 0; for (const auto& pricingPeriod : pricingPeriods_) { totalQuantityAmount += pricingPeriod->quantity().amount(); } return Quantity(pricingPeriods_[0]->quantity().commodityType(), pricingPeriods_[0]->quantity().unitOfMeasure(), totalQuantityAmount); } bool EnergySwap::isExpired() const { return pricingPeriods_.empty() || detail::simple_event(pricingPeriods_.back()->paymentDate()) .hasOccurred(); } }
893
7,220
<reponame>dedsec-9/trax # coding=utf-8 # Copyright 2021 The Trax 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. """Trax RL environments library.""" import gin from trax.rl.envs import data_envs def configure_rl_env(*args, **kwargs): kwargs['module'] = 'trax.rl.envs' return gin.external_configurable(*args, **kwargs) copy_stream = configure_rl_env(data_envs.copy_stream) SequenceDataEnv = configure_rl_env(data_envs.SequenceDataEnv)
293
1,731
import ast from configparser import ConfigParser from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple, no_type_check @dataclass class Setup: """ Abstraction of a Python project setup file. """ name: Optional[str] = None version: Optional[str] = None install_requires: List[str] = field(default_factory=list) extras_require: Dict[str, List[str]] = field(default_factory=dict) python_requires: Optional[str] = None def update(self, other: "Setup") -> None: if other.name: self.name = other.name if other.version: self.version = other.version if other.install_requires: self.install_requires = other.install_requires if other.extras_require: self.extras_require = other.extras_require if other.python_requires: self.python_requires = other.python_requires def as_dict(self) -> Dict[str, Any]: return asdict(self) @classmethod def from_directory(cls, dir: Path) -> "Setup": return _SetupReader.read_from_directory(dir) class _SetupReader: """ Class that reads a setup.py file without executing it. """ @classmethod def read_from_directory(cls, directory: Path) -> Setup: result = Setup() for filename, file_reader in [ ("pyproject.toml", cls.read_pyproject_toml), ("setup.cfg", cls.read_setup_cfg), ("setup.py", cls.read_setup_py), ]: filepath = directory / filename if not filepath.exists(): continue new_result = file_reader(filepath) result.update(new_result) return result @staticmethod def read_pyproject_toml(file: Path) -> Setup: from pdm.project.metadata import MutableMetadata try: metadata = MutableMetadata(file) except ValueError: return Setup() return Setup( name=metadata.name, version=metadata.version, install_requires=metadata.dependencies or [], extras_require=metadata.optional_dependencies or {}, python_requires=metadata.requires_python, ) @no_type_check @classmethod def read_setup_py(cls, file: Path) -> Setup: with file.open(encoding="utf-8") as f: content = f.read() body = ast.parse(content).body setup_call, body = cls._find_setup_call(body) if not setup_call: return Setup() return Setup( name=cls._find_single_string(setup_call, body, "name"), version=cls._find_single_string(setup_call, body, "version"), install_requires=cls._find_install_requires(setup_call, body), extras_require=cls._find_extras_require(setup_call, body), python_requires=cls._find_single_string( setup_call, body, "python_requires" ), ) @staticmethod def read_setup_cfg(file: Path) -> Setup: parser = ConfigParser() parser.read(str(file)) name = None version = None if parser.has_option("metadata", "name"): name = parser.get("metadata", "name") if parser.has_option("metadata", "version"): version = parser.get("metadata", "version") install_requires = [] extras_require: Dict[str, List[str]] = {} python_requires = None if parser.has_section("options"): if parser.has_option("options", "install_requires"): for dep in parser.get("options", "install_requires").split("\n"): dep = dep.strip() if not dep: continue install_requires.append(dep) if parser.has_option("options", "python_requires"): python_requires = parser.get("options", "python_requires") if parser.has_section("options.extras_require"): for group in parser.options("options.extras_require"): extras_require[group] = [] deps = parser.get("options.extras_require", group) for dep in deps.split("\n"): dep = dep.strip() if not dep: continue extras_require[group].append(dep) return Setup( name=name, version=version, install_requires=install_requires, extras_require=extras_require, python_requires=python_requires, ) @classmethod def _find_setup_call( cls, elements: List[Any] ) -> Tuple[Optional[ast.Call], Optional[List[Any]]]: funcdefs = [] for i, element in enumerate(elements): if isinstance(element, ast.If) and i == len(elements) - 1: # Checking if the last element is an if statement # and if it is 'if __name__ == "__main__"' which # could contain the call to setup() test = element.test if not isinstance(test, ast.Compare): continue left = test.left if not isinstance(left, ast.Name): continue if left.id != "__name__": continue setup_call, body = cls._find_sub_setup_call([element]) if not setup_call: continue return setup_call, body + elements if not isinstance(element, ast.Expr): if isinstance(element, ast.FunctionDef): funcdefs.append(element) continue value = element.value if not isinstance(value, ast.Call): continue func = value.func if not (isinstance(func, ast.Name) and func.id == "setup") and not ( isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == "setuptools" and func.attr == "setup" ): continue return value, elements # Nothing, we inspect the function definitions return cls._find_sub_setup_call(funcdefs) @no_type_check @classmethod def _find_sub_setup_call( cls, elements: List[Any] ) -> Tuple[Optional[ast.Call], Optional[List[Any]]]: for element in elements: if not isinstance(element, (ast.FunctionDef, ast.If)): continue setup_call = cls._find_setup_call(element.body) if setup_call != (None, None): setup_call, body = setup_call body = elements + body return setup_call, body return None, None @no_type_check @classmethod def _find_install_requires(cls, call: ast.Call, body: Iterable[Any]) -> List[str]: install_requires: List[str] = [] value = cls._find_in_call(call, "install_requires") if value is None: # Trying to find in kwargs kwargs = cls._find_call_kwargs(call) if kwargs is None or not isinstance(kwargs, ast.Name): return install_requires variable = cls._find_variable_in_body(body, kwargs.id) if not isinstance(variable, (ast.Dict, ast.Call)): return install_requires if isinstance(variable, ast.Call): if not isinstance(variable.func, ast.Name): return install_requires if variable.func.id != "dict": return install_requires value = cls._find_in_call(variable, "install_requires") else: value = cls._find_in_dict(variable, "install_requires") if value is None: return install_requires if isinstance(value, ast.List): for el in value.elts: install_requires.append(el.s) elif isinstance(value, ast.Name): variable = cls._find_variable_in_body(body, value.id) if variable is not None and isinstance(variable, ast.List): for el in variable.elts: install_requires.append(el.s) return install_requires @no_type_check @classmethod def _find_extras_require( cls, call: ast.Call, body: Iterable[Any] ) -> Dict[str, List[str]]: extras_require: Dict[str, List[str]] = {} value = cls._find_in_call(call, "extras_require") if value is None: # Trying to find in kwargs kwargs = cls._find_call_kwargs(call) if kwargs is None or not isinstance(kwargs, ast.Name): return extras_require variable = cls._find_variable_in_body(body, kwargs.id) if not isinstance(variable, (ast.Dict, ast.Call)): return extras_require if isinstance(variable, ast.Call): if not isinstance(variable.func, ast.Name): return extras_require if variable.func.id != "dict": return extras_require value = cls._find_in_call(variable, "extras_require") else: value = cls._find_in_dict(variable, "extras_require") if value is None: return extras_require if isinstance(value, ast.Dict): for key, val in zip(value.keys, value.values): if isinstance(val, ast.Name): val = cls._find_variable_in_body(body, val.id) if isinstance(val, ast.List): extras_require[key.s] = [e.s for e in val.elts] elif isinstance(value, ast.Name): variable = cls._find_variable_in_body(body, value.id) if variable is None or not isinstance(variable, ast.Dict): return extras_require for key, val in zip(variable.keys, variable.values): if isinstance(val, ast.Name): val = cls._find_variable_in_body(body, val.id) if isinstance(val, ast.List): extras_require[key.s] = [e.s for e in val.elts] return extras_require @classmethod def _find_single_string( cls, call: ast.Call, body: List[Any], name: str ) -> Optional[str]: value = cls._find_in_call(call, name) if value is None: # Trying to find in kwargs kwargs = cls._find_call_kwargs(call) if kwargs is None or not isinstance(kwargs, ast.Name): return None variable = cls._find_variable_in_body(body, kwargs.id) if not isinstance(variable, (ast.Dict, ast.Call)): return None if isinstance(variable, ast.Call): if not isinstance(variable.func, ast.Name): return None if variable.func.id != "dict": return None value = cls._find_in_call(variable, name) else: value = cls._find_in_dict(variable, name) if value is None: return None if isinstance(value, ast.Str): return value.s elif isinstance(value, ast.Name): variable = cls._find_variable_in_body(body, value.id) if variable is not None and isinstance(variable, ast.Str): return variable.s return None @staticmethod def _find_in_call(call: ast.Call, name: str) -> Optional[Any]: for keyword in call.keywords: if keyword.arg == name: return keyword.value return None @staticmethod def _find_call_kwargs(call: ast.Call) -> Optional[Any]: kwargs = None for keyword in call.keywords: if keyword.arg is None: kwargs = keyword.value return kwargs @staticmethod def _find_variable_in_body(body: Iterable[Any], name: str) -> Optional[Any]: for elem in body: if not isinstance(elem, ast.Assign): continue for target in elem.targets: if not isinstance(target, ast.Name): continue if target.id == name: return elem.value return None @staticmethod def _find_in_dict(dict_: ast.Dict, name: str) -> Optional[Any]: for key, val in zip(dict_.keys, dict_.values): if isinstance(key, ast.Str) and key.s == name: return val return None
6,206
488
#ifndef PAR_PRO_TRANSITION_GRAPH_H #define PAR_PRO_TRANSITION_GRAPH_H #include "sage3basic.h" // CodeThorn includes #include "Flow.h" #include "ParProEState.h" #include "ParProAutomataGenerator.h" // CodeThorn includes // BOOST includes #include "boost/lexical_cast.hpp" #include "boost/regex.hpp" #include "boost/algorithm/string.hpp" #include "boost/algorithm/string/trim.hpp" #include "boost/algorithm/string/regex.hpp" using namespace CodeThorn; namespace CodeThorn { /*! * \author <NAME> * \date 2016. */ class ParProTransition { public: ParProTransition(const ParProEState* s, Edge e, const ParProEState* t) : source(s), edge(e), target(t) {} const ParProEState* source; Edge edge; const ParProEState* target; }; bool operator==(const ParProTransition& t1, const ParProTransition& t2); bool operator!=(const ParProTransition& t1, const ParProTransition& t2); bool operator<(const ParProTransition& t1, const ParProTransition& t2); typedef std::set<ParProTransition> ParProTransitions; // multiple identical edges are not desired in the STG typedef std::unordered_map<const ParProEState*, ParProTransitions> EStateTransitionMap; /*! * \brief State transition graph consisting of ParProEStates. * \author <NAME> * \date 2016. * \details Graph is implemented as a map: Each state is mapped to its set of outgoing transitions. Transitions store pointers to their source and target states. */ class ParProTransitionGraph { public: ParProTransitionGraph() : _preciseStg(true), _completeStg(false) {} void deleteStates(); void add(ParProTransition transition); void setStartState(const ParProEState* state) { _startState = state; } const ParProEState* getStartState() { return _startState; } ParProTransitions succ(const ParProEState* source); EStateTransitionMap* getOutEdgesMap() { return &_outEdges; } size_t size(); size_t numStates(); std::set<std::string> getAllAnnotations(); bool isPrecise() { return _preciseStg; } void setIsPrecise(bool p) { _preciseStg = p; } bool isComplete() { return _completeStg; } void setIsComplete(bool c) { _completeStg = c; } Flow* toFlowEnumerateStates(NumberGenerator& numGen); // generates a string for visiualization with dot/graphviz. std::string toDot(); private: EStateTransitionMap _outEdges; const ParProEState* _startState; bool _preciseStg; bool _completeStg; }; } // end of namespace CodeThorn #endif
903
461
<gh_stars>100-1000 #!/usr/bin/env python3 import ipaddress import json import logging import os import sys import click from habu.lib import dnsx from habu.lib.loadcfg import loadcfg from habu.lib.shodan import shodan_get_result @click.command() @click.argument('ip') @click.option('--cache/--no-cache', 'cache', default=True) @click.option('-v', 'verbose', is_flag=True, default=False, help='Verbose output') @click.option('--format', 'output_format', type=click.Choice(['txt', 'csv','json', 'nmap']), default='txt', help='Output format') def cmd_shodan(ip, cache, verbose, output_format): """Simple shodan API client. Prints the JSON result of a shodan query. Example: \b $ habu.shodan 172.16.17.32 asn AS15169 isp Google hostnames eze04s06-in-f4.1e100.net, gru09s17-in-f36.1e100.net country_code US region_code CA city Mountain View org Google open_ports tcp/443, tcp/80 """ try: ipaddress.ip_address(ip) except ValueError: ip = dnsx.resolve(ip) if ip and isinstance(ip, list): ip = ip[0] logging.info('Resolved to {}'.format(ip)) if not ip: logging.error('Invalid IP address or unresolvable name') return False habucfg = loadcfg() if 'SHODAN_APIKEY' not in habucfg: print('You must provide a shodan apikey. Use the ~/.habu.json file (variable SHODAN_APIKEY), or export the variable HABU_SHODAN_APIKEY') print('Get your API key from https://www.shodan.io/') sys.exit(1) if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') data = shodan_get_result(ip, habucfg['SHODAN_APIKEY'], cache=cache, verbose=verbose) if output_format == 'json': print(json.dumps(data, indent=4)) return True if not data: logging.error('Shodan seems to have no data for this host') return False if output_format == 'nmap': ports_string = ','.join(['{}:{}'.format(port['transport'][0].upper(), port['port']) for port in data['data']]) print(ports_string, end='') return True default_fields = [ 'asn', 'isp', 'hostnames', 'country_code', 'region_code', 'city', 'org', 'os', ] for field in default_fields: value = data.get(field, None) if not value: continue if output_format == 'csv': if not isinstance(value, list): value = [value] for v in sorted(value): print('"{}","shodan.{}","{}"'.format(ip, field, v)) else: if isinstance(value, list): value = ', '.join(sorted(value)) print('{:<25}{}'.format(field, value)) if output_format == 'txt': ports_string = ', '.join(['{}/{}'.format(port['transport'], port['port']) for port in data['data']]) print('{:<25}{}'.format('open_ports', ports_string)) else: for port in data['data']: print('"{}","shodan.open_port","{}/{}"'.format(ip, port['transport'], port['port'])) if __name__ == '__main__': cmd_shodan()
1,545
352
<reponame>octo-online/reactive-aud /* * Copyright 2014 OCTO Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.octo.reactive.audit.javax.xml.ws; import com.octo.reactive.audit.TestTools; import com.octo.reactive.audit.lib.NetworkReactiveAuditException; import org.junit.Test; import javax.xml.ws.Dispatch; public class ProviderTest { private final Dispatch<?> x = (Dispatch) TestTools.createProxy(Dispatch.class); @Test(expected = NetworkReactiveAuditException.class) public void invoke() { TestTools.strict.commit(); x.invoke(null); } }
337
1,338
/* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> */ #include "PopupSlider.h" #include <math.h> #include <stdio.h> #include <Message.h> #include <MDividable.h> #include <MWindow.h> #include "SliderView.h" // constructor PopupSlider::PopupSlider(const char* name, const char* label, BMessage* model, BHandler* target, int32 min, int32 max, int32 value, const char* formatString) : PopupControl(name, fSlider = new SliderView(this, min, max, value, formatString)), MDividable(), fModel(model), fPressModel(NULL), fReleaseModel(NULL), fTarget(target), fLabel(label), fSliderButtonRect(0.0, 0.0, -1.0, -1.0), fEnabled(true), fTracking(false) { SetViewColor(B_TRANSPARENT_32_BIT); } // destructor PopupSlider::~PopupSlider() { delete fModel; if (BWindow* window = fSlider->Window()) { window->Lock(); window->RemoveChild(fSlider); window->Unlock(); } delete fSlider; } // layoutprefs minimax PopupSlider::layoutprefs() { BFont font; GetFont(&font); font_height fh; font.GetHeight(&fh); float labelHeight = 2.0 + ceilf(fh.ascent + fh.descent) + 2.0; float sliderWidth, sliderHeight; SliderView::GetSliderButtonDimensions(Max(), FormatString(), &font, sliderWidth, sliderHeight); float height = labelHeight > sliderHeight + 2.0 ? labelHeight : sliderHeight + 2.0; float minLabelWidth = LabelWidth(); if (rolemodel) labelwidth = rolemodel->LabelWidth(); labelwidth = minLabelWidth > labelwidth ? minLabelWidth : labelwidth; fSliderButtonRect.left = labelwidth; fSliderButtonRect.right = fSliderButtonRect.left + sliderWidth + 2.0; fSliderButtonRect.top = floorf(height / 2.0 - (sliderHeight + 2.0) / 2.0); fSliderButtonRect.bottom = fSliderButtonRect.top + sliderHeight + 2.0; fSliderButtonRect.OffsetTo(Bounds().right - fSliderButtonRect.Width(), fSliderButtonRect.top); mpm.mini.x = labelwidth + fSliderButtonRect.Width() + 1.0; mpm.maxi.x = 10000.0; mpm.mini.y = mpm.maxi.y = height + 1.0; mpm.weight = 1.0; return mpm; } // layout BRect PopupSlider::layout(BRect frame) { MoveTo(frame.LeftTop()); ResizeTo(frame.Width(), frame.Height()); fSliderButtonRect.OffsetTo(Bounds().right - fSliderButtonRect.Width(), fSliderButtonRect.top); return Frame(); } // MessageReceived void PopupSlider::MessageReceived(BMessage* message) { switch (message->what) { default: PopupControl::MessageReceived(message); break; } } // AttachedToWindow void PopupSlider::AttachedToWindow() { fSliderButtonRect.OffsetTo(Bounds().right - fSliderButtonRect.Width(), fSliderButtonRect.top); PopupControl::AttachedToWindow(); } // Draw void PopupSlider::Draw(BRect updateRect) { bool enabled = IsEnabled(); rgb_color background = ui_color(B_PANEL_BACKGROUND_COLOR); rgb_color black; if (enabled) { black = tint_color(background, B_DARKEN_MAX_TINT); } else { black = tint_color(background, B_DISABLED_LABEL_TINT); } // draw label BRect r(Bounds()); r.right = fSliderButtonRect.left - 1.0; font_height fh; GetFontHeight(&fh); BPoint textPoint(0.0, (r.top + r.bottom) / 2.0 + fh.ascent / 2.0); SetLowColor(background); SetHighColor(black); FillRect(r, B_SOLID_LOW); DrawString(fLabel.String(), textPoint); // draw slider button DrawSlider(fSliderButtonRect, enabled); } // MouseDown void PopupSlider::MouseDown(BPoint where) { if (fEnabled && fSliderButtonRect.Contains(where) && !fSlider->LockLooper()) { SetPopupLocation(BPoint(fSliderButtonRect.left + 1.0 - fSlider->ButtonOffset(), -5.0)); where.x -= fSliderButtonRect.left + 1.0; fSlider->SetDragOffset(where.x); // just to be on the safe side (avoid a dead lock) fTracking = true; ShowPopup(&where); // fSlider->SetDragOffset(where.x); } } // PopupShown void PopupSlider::PopupShown() { TriggerValueChanged(fPressModel); fTracking = true; } // PopupHidden void PopupSlider::PopupHidden(bool canceled) { TriggerValueChanged(fReleaseModel); fTracking = false; } // SetValue void PopupSlider::SetValue(int32 value) { if (!fTracking) { /* if (fSlider->LockLooper()) { fSlider->SetValue(value); fSlider->UnlockLooper(); } else*/ if (value != Value()) { fSlider->SetValue(value); if (LockLooperWithTimeout(0) >= B_OK) { Invalidate(); UnlockLooper(); } } } else ValueChanged(value); } // Value int32 PopupSlider::Value() const { int32 value = 0; /* if (fSlider->LockLooper()) { value = fSlider->Value(); fSlider->UnlockLooper(); } else*/ value = fSlider->Value(); return value; } // SetEnabled void PopupSlider::SetEnabled(bool enable) { if (enable != fEnabled) { fEnabled = enable; if (LockLooper()) { Invalidate(); UnlockLooper(); } } } // SetEnabled bool PopupSlider::IsEnabled() const { return fEnabled; } // TriggerValueChanged void PopupSlider::TriggerValueChanged(const BMessage* message) const { if (message && fTarget) { BMessage msg(*message); msg.AddInt64("be:when", system_time()); msg.AddInt32("be:value", Value()); msg.AddPointer("be:source", (void*)this); if (BLooper* looper = fTarget->Looper()) looper->PostMessage(&msg, fTarget); } } // IsTracking bool PopupSlider::IsTracking() const { return fTracking; } // ValueChanged void PopupSlider::ValueChanged(int32 newValue) { TriggerValueChanged(fModel); } // DrawSlider void PopupSlider::DrawSlider(BRect frame, bool enabled) { rgb_color background = ui_color(B_PANEL_BACKGROUND_COLOR); rgb_color lightShadow; rgb_color darkShadow; if (enabled) { lightShadow = tint_color(background, B_DARKEN_2_TINT); darkShadow = tint_color(background, B_DARKEN_4_TINT); } else { lightShadow = tint_color(background, B_DARKEN_1_TINT); darkShadow = tint_color(background, B_DARKEN_2_TINT); } BeginLineArray(4); AddLine(BPoint(frame.left, frame.bottom), BPoint(frame.left, frame.top), lightShadow); AddLine(BPoint(frame.left + 1.0, frame.top), BPoint(frame.right, frame.top), lightShadow); AddLine(BPoint(frame.right, frame.top + 1.0), BPoint(frame.right, frame.bottom), darkShadow); AddLine(BPoint(frame.right - 1.0, frame.bottom), BPoint(frame.left + 1.0, frame.bottom), darkShadow); EndLineArray(); frame.InsetBy(1.0, 1.0); SliderView::DrawSliderButton(this, frame, Value(), FormatString(), enabled); } // Scale float PopupSlider::Scale(float ratio) const { return ratio; } // DeScale float PopupSlider::DeScale(float ratio) const { return ratio; } // SetMessage void PopupSlider::SetMessage(BMessage* message) { delete fModel; fModel = message; } // SetPressedMessage void PopupSlider::SetPressedMessage(BMessage* message) { delete fPressModel; fPressModel = message; } // SetReleasedMessage void PopupSlider::SetReleasedMessage(BMessage* message) { delete fReleaseModel; fReleaseModel = message; } // SetMin void PopupSlider::SetMin(int32 min) { /* if (fSlider->LockLooper()) { fSlider->SetMin(min); fSlider->UnlockLooper(); } else*/ fSlider->SetMin(min); } // Min int32 PopupSlider::Min() const { int32 value = 0; /* if (fSlider->LockLooper()) { value = fSlider->Min(); fSlider->UnlockLooper(); } else*/ value = fSlider->Min(); return value; } // SetMax void PopupSlider::SetMax(int32 max) { /* if (fSlider->LockLooper()) { fSlider->SetMax(max); fSlider->UnlockLooper(); } else*/ fSlider->SetMax(max); } // Max int32 PopupSlider::Max() const { int32 value = 0; /* if (fSlider->LockLooper()) { value = fSlider->Max(); fSlider->UnlockLooper(); } else*/ value = fSlider->Max(); return value; } // SetLabel void PopupSlider::SetLabel(const char* label) { fLabel.SetTo(label); Invalidate(); } // Label const char* PopupSlider::Label() const { return fLabel.String(); } // LabelWidth float PopupSlider::LabelWidth() { return _MinLabelWidth(); } // StringForValue const char* PopupSlider::StringForValue(int32 value) { return NULL; } // MaxValueStringWidth float PopupSlider::MaxValueStringWidth() { return 0.0; } // SetFormatString void PopupSlider::SetFormatString(const char* formatString) { /* if (fSlider->LockLooper()) { fSlider->SetFormatString(formatString); fSlider->UnlockLooper(); } else*/ fSlider->SetFormatString(formatString); } // FormatString const char* PopupSlider::FormatString() const { return fSlider->FormatString(); } // _MinLabelWidth float PopupSlider::_MinLabelWidth() const { return ceilf(StringWidth(fLabel.String())) + 5.0; } /* // StringForValue const char* PercentSlider::StringForValue(int32 value) { BString string; string << (value * 100) / Max() << "%"; return } */
3,499
383
"""The tests for the BlueMaestro ble_parser.""" from ble_monitor.ble_parser import BleParser class TestBlueMaestro: """Tests for the BlueMaestro parser""" def test_BlueMaestro_THD(self): """Test BlueMaestro Tempo Disc THD parser.""" data_string = "043e4702010400aabb611d12e03b11ff330117550e10061eff2f02a6ff0301000908111111111111111100000000330174536166650000000000000000616974536166650000000000a6" data = bytes(bytearray.fromhex(data_string)) # pylint: disable=unused-variable ble_parser = BleParser() sensor_msg, tracker_msg = ble_parser.parse_data(data) assert sensor_msg["firmware"] == "BlueMaestro" assert sensor_msg["type"] == "Tempo Disc THD" assert sensor_msg["mac"] == "E0121D61BBAA" assert sensor_msg["packet"] == 1566 assert sensor_msg["data"] assert sensor_msg["temperature"] == -20.9 assert sensor_msg["humidity"] == 67.8 assert sensor_msg['dewpoint'] == -25.3 assert sensor_msg["battery"] == 85 assert sensor_msg["rssi"] == -90
446
435
<gh_stars>100-1000 { "alias": "video/1319/tornado-in-depth", "category": "EuroPython 2012", "copyright_text": "Standard YouTube License", "description": "Tornado is a non-blocking light-weight web server and framework. There\u2019s\nbeen many introductory talks about it, and it\u2019s time to look deeper into\nit: not just what Tornado does, but how it does it and what can we learn\nfrom it when designing our own concurrent systems. We\u2019ll cover each\ntopic in two parts: first we\u2019ll see how to use a certain feature in our\napplications; then, we\u2019ll dig into Tornado\u2019s source code to see how it\nreally works. How much time we\u2019ll spend in the \u201chow to use\u201d will depend\non the audience\u2019s knowledge of Tornado. Getting Started: quickly get a\nsimple Tornado application up and running. We\u2019ll keep digging into,\nchanging and poking this Application for most of the talk. An\nApplication Listens: what an Application is, how does Tornado start it\nand how does it process its requests. Application and IOLoop: we\u2019ll look\nat how the IOLoop receives the connections from the users and passes\nthem on to the Applications. Scheduled Tasks: we\u2019ll see how to schedule\ntasks and how the IOLoop will run them. Generators: we\u2019ll learn to use\ngenerators to handle the responses of our asynchronous calls, and how\nthey work with the IOLoop. Websockets: how to use them and how they\nwork. IOStream: how do Tornado\u2019s non- blocking sockets work. Database:\nhow to use non-blocking sockets to connect to a MySQL or MongoDB\ndatabase.\n", "duration": null, "id": 1319, "language": "eng", "quality_notes": "", "recorded": "2012-07-04", "slug": "tornado-in-depth", "speakers": [ "O Vilaplana" ], "summary": "[EuroPython 2012] O Vilaplana - 3 JULY 2012 in \"Track Tagliatelle\"\n", "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/4Ztq-Yz1ero/hqdefault.jpg", "title": "Tornado in Depth", "videos": [ { "length": 0, "type": "youtube", "url": "https://www.youtube.com/watch?v=4Ztq-Yz1ero" } ] }
685
3,326
/* Copyright 2017 Google Inc. 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 "syntaxnet/base.h" #include "syntaxnet/parser_state.h" #include "syntaxnet/parser_transitions.h" using tensorflow::strings::StrCat; namespace syntaxnet { namespace { // A transition system that has exactly one action and performs exactly one // action per state, regardless of sentence length. class OnceTransitionSystem : public ParserTransitionSystem { public: // A transition state that allows exactly one transition. class State : public ParserTransitionState { public: // Implements TransitionState. State *Clone() const override { return new State(*this); } void Init(ParserState *state) override {} bool IsTokenCorrect(const ParserState &state, int index) const override { return true; } string ToString(const ParserState &state) const override { return StrCat("done=", done() ? "true" : "false"); } // Records that a transition has been performed. void PerformAction() { done_ = true; } // Returns true if no more transitions are allowed. bool done() const { return done_; } private: bool done_ = false; // true if no more transitions are allowed }; // Implements ParserTransitionSystem. int NumActionTypes() const override { return 1; } int NumActions(int num_labels) const override { return 1; } ParserAction GetDefaultAction(const ParserState &state) const override { DCHECK(!IsFinalState(state)); return 0; } ParserAction GetNextGoldAction(const ParserState &state) const override { return GetDefaultAction(state); } void PerformActionWithoutHistory(ParserAction action, ParserState *state) const override { DCHECK(!IsFinalState(*state)); static_cast<State *>(state->mutable_transition_state())->PerformAction(); } bool IsAllowedAction(ParserAction action, const ParserState &state) const override { return action == 0 && !IsFinalState(state); } bool IsFinalState(const ParserState &state) const override { return static_cast<const State *>(state.transition_state())->done(); } string ActionAsString(ParserAction action, const ParserState &state) const override { return StrCat("action:", action); } ParserTransitionState *NewTransitionState(bool training_mode) const override { return new State(); } bool IsDeterministicState(const ParserState &state) const override { return true; // all states have only one action } }; REGISTER_TRANSITION_SYSTEM("once", OnceTransitionSystem); } // namespace } // namespace syntaxnet
988
815
<reponame>xj361685640/ParaView /*************************************************************************************************** * Copyright 2021 NVIDIA Corporation. All rights reserved. **************************************************************************************************/ /// \file /// \brief API component for various image-related functions. #ifndef MI_NEURAYLIB_IIMAGE_API_H #define MI_NEURAYLIB_IIMAGE_API_H #include <mi/base/interface_declare.h> namespace mi { class IArray; namespace neuraylib { class IBuffer; class ICanvas; class ICanvas_cuda; class IReader; class ITile; /** \if MDL_SDK_API \defgroup mi_neuray_mdl_sdk_misc Miscellaneous Interfaces \ingroup mi_neuray \brief Various utility classes. \elseif IRAY_API \defgroup mi_neuray_mdl_sdk_misc Miscellaneous MDL-related Interfaces \ingroup mi_neuray \brief Various utility classes. \endif */ /** \if IRAY_API \addtogroup mi_neuray_rendering \elseif MDL_SDK_API \addtogroup mi_neuray_mdl_sdk_misc \elseif DICE_API \addtogroup mi_neuray_rtmp \endif @{ */ /// This interface provides various utilities related to canvases and buffers. /// /// Note that #create_buffer_from_canvas() and #create_canvas_from_buffer() encode and decode pixel /// data to/from memory buffers. \if IRAY_API To import images from disk use /// #mi::neuraylib::IImport_api::import_canvas(). To export images to disk use /// #mi::neuraylib::IExport_api::export_canvas(). \endif class IImage_api : public mi::base::Interface_declare<0x4c25a4f0,0x2bac,0x4ce6,0xb0,0xab,0x4d,0x94,0xbf,0xfd,0x97,0xa5> { public: /// \name Factory methods for canvases and tiles //@{ /// Creates a tile with given pixel type, width, and height. /// /// This factory function allows to create instances of the abstract interface /// #mi::neuraylib::ITile based on an internal default implementation. However, you are not /// obligated to use this factory function and the internal default implementation. It is /// absolutely fine to use your own (correct) implementation of the #mi::neuraylib::ITile /// interface. /// /// \param pixel_type The desired pixel type. See \ref mi_neuray_types for a list of supported /// pixel types. /// \param width The desired width. /// \param height The desired height. /// \return The requested tile, or \c NULL in case of invalid pixel type, width, or /// height. virtual ITile* create_tile( const char* pixel_type, Uint32 width, Uint32 height) const = 0; /// Creates a canvas with given pixel type, resolution, and layers. /// /// This factory function allows to create instances of the abstract interface /// #mi::neuraylib::ICanvas based on an internal default implementation. However, you are not /// obligated to use this factory function and the internal default implementation. It is /// absolutely fine to use your own (correct) implementation of the #mi::neuraylib::ICanvas /// interface. /// /// \param pixel_type The desired pixel type. See \ref mi_neuray_types for a list of /// supported pixel types. /// \param width The desired width. /// \param height The desired height. /// \param layers The desired number of layers (depth). Must be 6 for cubemaps. /// \param is_cubemap Flag that indicates whether this canvas represents a cubemap. /// \param gamma The desired gamma value. The special value 0.0 represents the default /// gamma which is 1.0 for HDR pixel types and 2.2 for LDR pixel types. /// \return The requested canvas, or \c NULL in case of invalid pixel type, width, /// height, layers, or cubemap flag. virtual ICanvas* create_canvas( const char* pixel_type, Uint32 width, Uint32 height, Uint32 layers = 1, bool is_cubemap = false, Float32 gamma = 0.0f) const = 0; #ifndef MI_SKIP_WITH_MDL_SDK_DOXYGEN /// Creates a CUDA canvas with given pixel type, width, height, and layers. /// /// \see #create_canvas() /// \see #mi::neuraylib::IGpu_description::get_cuda_device_id() /// /// \param cuda_device_id The CUDA ID of the device on which the canvas will reside. /// Note that this is the CUDA device ID, not the 1-based GPU index /// used in \if IRAY_API #mi::neuraylib::IRendering_configuration. /// \else #mi::neuraylib::IDice_configuration. \endif /// \param pixel_type The desired pixel type. See \ref mi_neuray_types for a list of /// supported pixel types. /// \param width The desired width. /// \param height The desired height. /// \param layers The desired number of layers. /// \param gamma The desired gamma value. The special value 0.0 represents the default /// gamma which is 1.0 for HDR pixel types and 2.2 for LDR pixel types. /// \return The requested canvas, or \c NULL in case of invalid parameters or /// CUDA errors. #endif // MI_SKIP_WITH_MDL_SDK_DOXYGEN virtual ICanvas_cuda* create_canvas_cuda( Sint32 cuda_device_id, const char* pixel_type, Uint32 width, Uint32 height, Uint32 layers = 1, Float32 gamma = 0.0f) const = 0; /// Creates mipmaps from the given canvas. /// /// \note The base level (the canvas that is passed in) is not included in the returned /// canvas array. /// /// \param canvas The canvas to create the mipmaps from. /// \param gamma_override If this parameter is different from zero, it is used instead of the /// canvas gamma during mipmap creation. /// \return An array of type #mi::IPointer containing pointers to /// the mipmaps of type #mi::neuraylib::ICanvas. /// If no mipmaps could be created, NULL is returned. virtual IArray* create_mipmaps( const ICanvas* canvas, Float32 gamma_override = 0.0f) const = 0; //@} /// \name Conversion between canvases and raw memory buffers //@{ /// Reads raw pixel data from a canvas. /// /// Reads a rectangular area of pixels from a canvas (possibly spanning multiple tiles), /// converts the pixel type if needed, and writes the pixel data to buffer in memory. /// Management of the buffer memory is the responsibility of the caller. /// /// \param width The width of the rectangular pixel area. /// \param height The height of the rectangular pixel area. /// \param canvas The canvas to read the pixel data from. /// \param canvas_x The x-coordinate of the lower-left corner of the rectangle. /// \param canvas_y The y-coordinate of the lower-left corner of the rectangle. /// \param canvas_layer The layer of the canvas that holds the rectangular area. /// \param buffer The buffer to write the pixel data to. /// \param buffer_topdown Indicates whether the buffer stores the rows in top-down order. /// \param buffer_pixel_type The pixel type of the buffer. See \ref mi_neuray_types for a /// list of supported pixel types. /// \param buffer_padding The padding between subsequent rows of the buffer in bytes. /// \return /// - 0: Success. /// - -1: Invalid parameters (\c NULL pointer). /// - -2: \p width or \p height is zero. /// - -3: Invalid pixel type of the buffer. /// - -4: The rectangular area [\p canvas_x, \p canvas_x + \p width) /// x [\p canvas_y, \p canvas_y + \p height) exceeds the size /// of the canvas, or \p canvas_layer is invalid. virtual Sint32 read_raw_pixels( Uint32 width, Uint32 height, const ICanvas* canvas, Uint32 canvas_x, Uint32 canvas_y, Uint32 canvas_layer, void* buffer, bool buffer_topdown, const char* buffer_pixel_type, Uint32 buffer_padding = 0) const = 0; /// Writes raw pixel data to a canvas. /// /// Reads a rectangular area of pixels from a buffer in memory, converts the pixel type if /// needed, and writes the pixel data to a canvas (possibly spanning multiple tiles). /// Management of the buffer memory is the responsibility of the caller. /// /// \param width The width of the rectangular pixel area. /// \param height The height of the rectangular pixel area. /// \param canvas The canvas to write the pixel data to. /// \param canvas_x The x-coordinate of the lower-left corner of the rectangle. /// \param canvas_y The y-coordinate of the lower-left corner of the rectangle. /// \param canvas_layer The layer of the canvas that holds the rectangular area. /// \param buffer The buffer to read the pixel data from. /// \param buffer_topdown Indicates whether the buffer stores the rows in top-down order. /// \param buffer_pixel_type The pixel type of the buffer. See \ref mi_neuray_types for a /// list of supported pixel types. /// \param buffer_padding The padding between subsequent rows of the buffer in bytes. /// \return /// - 0: Success. /// - -1: Invalid parameters (\c NULL pointer). /// - -2: \p width or \p height is zero. /// - -3: Invalid pixel type of the buffer. /// - -4: The rectangular area [\p canvas_x, \p canvas_x + \p width) /// x [\p canvas_y, \p canvas_y + \p height) exceeds the size /// of the canvas, or \p canvas_layer is invalid. virtual Sint32 write_raw_pixels( Uint32 width, Uint32 height, ICanvas* canvas, Uint32 canvas_x, Uint32 canvas_y, Uint32 canvas_layer, const void* buffer, bool buffer_topdown, const char* buffer_pixel_type, Uint32 buffer_padding = 0) const = 0; //@} /// \name Conversion between canvases and encoded images //@{ /// Encodes the pixel data of a canvas into a memory buffer. /// /// \param canvas The canvas whose contents are to be used. /// \param image_format The desired image format of the image, e.g., \c "jpg". Note /// that support for a given image format requires an image plugin /// capable of handling that format. /// \param pixel_type The desired pixel type. See \ref mi_neuray_types for a list of /// supported pixel types. Not every image plugin supports every /// pixel type. If the requested pixel type is not supported, the /// argument is ignored and one of the supported formats is chosen /// instead. /// \param quality The compression quality is an integer in the range from 0 to /// 100, where 0 is the lowest quality, and 100 is the highest /// quality. /// \param force_default_gamma If enabled, adjusts the gamma value of the exported pixel data /// according to the pixel type chosen for export (1.0 for HDR /// pixel types, 2.2 for LDR pixel types). /// \return The created buffer, or \c NULL in case of failure. virtual IBuffer* create_buffer_from_canvas( const ICanvas* canvas, const char* image_format, const char* pixel_type, const char* quality, bool force_default_gamma = false) const = 0; /// Decodes the pixel data of a memory buffer into a canvas. /// /// \param buffer The buffer that holds the encoded pixel data. /// \param image_format The image format of the buffer, e.g., \c "jpg". Note that support for /// a given image format requires an image plugin capable of handling that /// format. /// \return The canvas with the decoded pixel data, or \c NULL in case of failure. virtual ICanvas* create_canvas_from_buffer( const IBuffer* buffer, const char* image_format) const = 0; /// Decodes the pixel data from a reader into a canvas. /// /// \param reader The reader that provides the data for the image. The reader needs to /// support absolute access. /// \param image_format The image format of the buffer, e.g., \c "jpg". Note that support for /// a given image format requires an image plugin capable of handling that /// format. /// \return The canvas with the decoded pixel data, or \c NULL in case of failure. virtual ICanvas* create_canvas_from_reader( IReader* reader, const char* image_format) const = 0; /// Indicates whether a particular image format is supported for decoding. /// /// Support for a given image format requires an image plugin capable of handling that format. /// This method allows to check whether such a plugin has been loaded for a particular format. /// /// Decoding is used when the image is converted into a canvas from a \if DICE_API memory /// buffer. \else memory buffer or a file \endif. Note that even if this method returns \c true, /// #create_canvas_from_buffer() \if IRAY_API or /// #mi::neuraylib::IImport_api::import_canvas() \endif can still fail for a particular image if /// that image uses an unsupported feature. /// /// \param image_format The image format in question, e.g., \c "jpg". /// \param reader An optional reader \if IRAY_API used by /// #mi::neuraylib::IImage_plugin::test(). \endif /// \return \c true if the image format is supported, \c false otherwise virtual bool supports_format_for_decoding( const char* image_format, IReader* reader = 0) const = 0; /// Indicates whether a particular image format is supported for encoding. /// /// Support for a given image format requires an image plugin capable of handling that format. /// This method allows to check whether such a plugin has been loaded for a particular format. /// /// Encoding is used when the image is converted from a canvas into a \if DICE_API memory /// buffer. \else memory buffer or a file. \endif. Note that even if this method returns /// \c true, #create_buffer_from_canvas() \if IRAY_API or /// #mi::neuraylib::IExport_api::export_canvas \endif can still fail if the given canvas /// uses an unsupported feature, e.g., multiple layers. /// /// \param image_format The image format in question, e.g., \c "jpg". /// \return \c true if the image format is supported, \c false otherwise virtual bool supports_format_for_encoding( const char* image_format) const = 0; //@} /// \name Utility methods for canvases //@{ /// Converts a canvas to a different pixel type. /// /// \note This method creates a copy if the passed-in canvas already has the desired pixel type. /// (It cannot return the passed-in canvas since this would require a const cast.) If /// performance is critical, you should compare pixel types yourself and skip the method call if /// pixel type conversion is not needed.) /// /// The conversion converts a given pixel as follows: /// /// - Floating-point values are linearly mapped to integers as follows: 0.0f is mapped to 0 and /// 1.0f is mapped to 255 or 65535, respectively. Note that the pixel type \c "Sint8" is /// treated as the corresponding unsigned integer type \c "Uint8" here. Floating-point values /// are clamped to [0.0f, 1.0f] beforehand. The reverse conversion uses the corresponding /// inverse mapping. /// - Single-channel formats are converted to grey-scale RGB formats by duplicating the value /// in each channel. /// - RGB formats are converted to single-channel formats by mixing the RGB channels with /// weights 0.27f for red, 0.67f for green, and 0.06f for blue. /// - If an alpha channel is added, the values are set to 1.0f, 255, or 65535 respectively. /// - The pixel type \c "Float32<4>" is treated in the same way as \c "Color", \c "Float32<3>" /// in the same way as \c "Rgb_fp", and \c "Sint32" in the same way as \c "Rgba". /// - The pixel type \c "Rgbe" is converted via \c "Rgb_fp". Similarly, \c "Rgbea" is converted /// via \c "Color". /// - \c "Float32<2>" is converted to single-channel formats by averaging the two channels. If /// \c "Float32<2>" is converted to three- or four-channel formats, the blue channel is set to /// 0.0f, or 0, respectively. Conversion of single-channel formats to \c "Float32<2>" /// duplicates the channel. Conversion of three- or four-channel formats to \c "Float32<2>" /// drops the third and fourth channel. /// /// \param canvas The canvas to convert (or to copy). /// \param pixel_type The desired pixel type. See \ref mi_neuray_types for a list of supported /// pixel types. If this pixel type is the same as the pixel type of \p /// canvas, then a copy of the canvas is returned. /// \return A canvas with the requested pixel type, or \c NULL in case of errors /// (\p canvas is \c NULL, or \p pixel_type is not valid). virtual ICanvas* convert( const ICanvas* canvas, const char* pixel_type) const = 0; /// Sets the gamma value of a canvas and adjusts the pixel data accordingly. /// /// \note Gamma adjustments are always done in pixel type "Color" or "Rgb_fp". If necessary, /// the pixel data is converted forth and back automatically (which needs temporary /// buffers). /// /// \param canvas The canvas whose pixel data is to be adjusted. /// \param new_gamma The new gamma value. virtual void adjust_gamma( ICanvas* canvas, Float32 new_gamma) const = 0; //@} /// \name Utility methods for pixel type characteristics //@{ /// Returns the number of components per pixel type. /// /// For example, for the pixel type "Color" the method returns 4 because it consists of four /// components R, G, B, and A. Returns 0 in case of invalid pixel types. /// /// \see #get_bytes_per_component() virtual Uint32 get_components_per_pixel( const char* pixel_type) const = 0; /// Returns the number of bytes used per pixel component. /// /// For example, for the pixel type "Color" the method returns 4 because its components are of /// type #mi::Float32 which needs 4 bytes. Returns 0 in case of invalid pixel types. /// /// \see #get_components_per_pixel() virtual Uint32 get_bytes_per_component( const char* pixel_type) const = 0; //@} /// \name Utility methods for RGBA channels //@{ /// Returns the pixel type of an RGBA channel. /// /// Invalid pixel type/selector combinations are: /// - \p pixel_type is not an RGB or RGBA pixel type /// - \p selector is not an RGBA channel selector /// /// \param pixel_type The pixel type of the mipmap/canvas/tile. /// \param selector The RGBA channel selector. /// \return Returns PT_UNDEF for invalid pixel type/selector combinations. /// Otherwise, returns PT_SINT8 or PT_FLOAT32, depending on /// \p pixel_type. virtual const char* get_pixel_type_for_channel( const char* pixel_type, const char* selector) const = 0; /// Extracs an RGBA channel from a canvas. /// /// \param canvas The canvas to extract a channel from. /// \param selector The RGBA channel selector. /// \return The extracted channel, or \c NULL in case of invalid pixel type/ /// channel selector combinations (see #get_pixel_type_for_channel()). virtual ICanvas* extract_channel( const ICanvas* canvas, const char* selector) const = 0; /// Extracs an RGBA channel from a tile. /// /// \param tile The tile to extract a channel from. /// \param selector The RGBA channel selector. /// \return The extracted channel, or \c NULL in case of invalid pixel type/ /// channel selector combinations (see #get_pixel_type_for_channel()). virtual ITile* extract_channel( const ITile* tile, const char* selector) const = 0; //@} }; /*@}*/ // end group mi_neuray_rendering / mi_neuray_rtmp } // namespace neuraylib } // namespace mi #endif // MI_NEURAYLIB_IIMAGE_API_H
8,344
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_WEB_WEB_STATE_UI_FAVICON_UTIL_H_ #define IOS_WEB_WEB_STATE_UI_FAVICON_UTIL_H_ #include "ios/web/public/favicon_url.h" namespace base { class DictionaryValue; } // namespace base namespace web { // Extracts the favicon url out of the |favicon_url_message| and put them into // the |out_parameter|. The |page_origin| is used to get the default favicon.ico // at the root of the page if there is none in the message. The message is // structured as containing a list of favicons containing the href, rel and // sizes attributes of the favicons. Returns whether the extraction was // completely successful or not. bool ExtractFaviconURL(const base::DictionaryValue* favicon_url_message, const GURL& page_origin, std::vector<web::FaviconURL>* out_parameter); } // namespace web #endif // IOS_WEB_WEB_STATE_UI_FAVICON_UTIL_H_
373
2,872
<filename>Ryven/packages/auto_generated/ssl/nodes.py from NENV import * import ssl class NodeBase(Node): pass class Der_Cert_To_Pem_Cert_Node(NodeBase): """ Takes a certificate in binary DER format and returns the PEM version of it as a string.""" title = 'DER_cert_to_PEM_cert' type_ = 'ssl' init_inputs = [ NodeInputBP(label='der_cert_bytes'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.DER_cert_to_PEM_cert(self.input(0))) class Pem_Cert_To_Der_Cert_Node(NodeBase): """ Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence""" title = 'PEM_cert_to_DER_cert' type_ = 'ssl' init_inputs = [ NodeInputBP(label='pem_cert_string'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.PEM_cert_to_DER_cert(self.input(0))) class Rand_Add_Node(NodeBase): """ Mix string into the OpenSSL PRNG state. entropy (a float) is a lower bound on the entropy contained in string. See RFC 4086.""" title = 'RAND_add' type_ = 'ssl' init_inputs = [ NodeInputBP(label='string'), NodeInputBP(label='entropy'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.RAND_add(self.input(0), self.input(1))) class Rand_Bytes_Node(NodeBase): """ Generate n cryptographically strong pseudo-random bytes.""" title = 'RAND_bytes' type_ = 'ssl' init_inputs = [ NodeInputBP(label='n'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.RAND_bytes(self.input(0))) class Rand_Pseudo_Bytes_Node(NodeBase): """ Generate n pseudo-random bytes. Return a pair (bytes, is_cryptographic). is_cryptographic is True if the bytes generated are cryptographically strong.""" title = 'RAND_pseudo_bytes' type_ = 'ssl' init_inputs = [ NodeInputBP(label='n'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.RAND_pseudo_bytes(self.input(0))) class Rand_Status_Node(NodeBase): """ Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not. It is necessary to seed the PRNG with RAND_add() on some platforms before using the ssl() function.""" title = 'RAND_status' type_ = 'ssl' init_inputs = [ ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.RAND_status()) class _Create_Default_Https_Context_Node(NodeBase): """ Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security. """ title = '_create_default_https_context' type_ = 'ssl' init_inputs = [ NodeInputBP(label='purpose', dtype=dtypes.Data(default=_ASN1Object(nid=129, shortname='serverAuth', longname='TLS Web Server Authentication', oid='172.16.31.10.5.172.16.58.3'), size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._create_default_https_context(self.input(0))) class _Create_Stdlib_Context_Node(NodeBase): """ Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility. """ title = '_create_stdlib_context' type_ = 'ssl' init_inputs = [ NodeInputBP(label='protocol', dtype=dtypes.Data(default=2, size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._create_stdlib_context(self.input(0))) class _Create_Unverified_Context_Node(NodeBase): """ Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility. """ title = '_create_unverified_context' type_ = 'ssl' init_inputs = [ NodeInputBP(label='protocol', dtype=dtypes.Data(default=2, size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._create_unverified_context(self.input(0))) class _Dnsname_Match_Node(NodeBase): """ Matching according to RFC 6125, section 6.4.3 - Hostnames are compared lower case. - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE). - Partial wildcards like 'www*.example.org', multiple wildcards, sole wildcard or wildcards in labels other then the left-most label are not supported and a CertificateError is raised. - A wildcard must match at least one character. """ title = '_dnsname_match' type_ = 'ssl' init_inputs = [ NodeInputBP(label='dn'), NodeInputBP(label='hostname'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._dnsname_match(self.input(0), self.input(1))) class _Inet_Paton_Node(NodeBase): """ Try to convert an IP address to packed binary form Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6 support. """ title = '_inet_paton' type_ = 'ssl' init_inputs = [ NodeInputBP(label='ipname'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._inet_paton(self.input(0))) class _Ipaddress_Match_Node(NodeBase): """ Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). """ title = '_ipaddress_match' type_ = 'ssl' init_inputs = [ NodeInputBP(label='cert_ipaddress'), NodeInputBP(label='host_ip'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._ipaddress_match(self.input(0), self.input(1))) class _Nid2Obj_Node(NodeBase): """ Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.""" title = '_nid2obj' type_ = 'ssl' init_inputs = [ NodeInputBP(label='nid'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._nid2obj(self.input(0))) class _Sslcopydoc_Node(NodeBase): """ Copy docstring from SSLObject to SSLSocket""" title = '_sslcopydoc' type_ = 'ssl' init_inputs = [ NodeInputBP(label='func'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._sslcopydoc(self.input(0))) class _Txt2Obj_Node(NodeBase): """ Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default objects are looked up by OID. With name=True short and long name are also matched.""" title = '_txt2obj' type_ = 'ssl' init_inputs = [ NodeInputBP(label='txt'), NodeInputBP(label='name', dtype=dtypes.Data(default=False, size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl._txt2obj(self.input(0), self.input(1))) class Cert_Time_To_Seconds_Node(NodeBase): """ Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec UTC should be specified as GMT (see ASN1_TIME_print()) """ title = 'cert_time_to_seconds' type_ = 'ssl' init_inputs = [ NodeInputBP(label='cert_time'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.cert_time_to_seconds(self.input(0))) class Create_Connection_Node(NodeBase): """ Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. A host of '' or port 0 tells the OS to use the default. """ title = 'create_connection' type_ = 'ssl' init_inputs = [ NodeInputBP(label='address'), NodeInputBP(label='timeout', dtype=dtypes.Data(default=None, size='s')), NodeInputBP(label='source_address', dtype=dtypes.Data(default=None, size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.create_connection(self.input(0), self.input(1), self.input(2))) class Create_Default_Context_Node(NodeBase): """ Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security. """ title = 'create_default_context' type_ = 'ssl' init_inputs = [ NodeInputBP(label='purpose', dtype=dtypes.Data(default=_ASN1Object(nid=129, shortname='serverAuth', longname='TLS Web Server Authentication', oid='172.16.31.10.5.172.16.58.3'), size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.create_default_context(self.input(0))) class Enum_Certificates_Node(NodeBase): """ Retrieve certificates from Windows' cert store. store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too. The function returns a list of (bytes, encoding_type, trust) tuples. The encoding_type flag can be interpreted with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the boolean True.""" title = 'enum_certificates' type_ = 'ssl' init_inputs = [ NodeInputBP(label='store_name'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.enum_certificates(self.input(0))) class Enum_Crls_Node(NodeBase): """ Retrieve CRLs from Windows' cert store. store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too. The function returns a list of (bytes, encoding_type) tuples. The encoding_type flag can be interpreted with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.""" title = 'enum_crls' type_ = 'ssl' init_inputs = [ NodeInputBP(label='store_name'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.enum_crls(self.input(0))) class Get_Default_Verify_Paths_Node(NodeBase): """ Return paths to default cafile and capath. """ title = 'get_default_verify_paths' type_ = 'ssl' init_inputs = [ ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.get_default_verify_paths()) class Get_Protocol_Name_Node(NodeBase): """ """ title = 'get_protocol_name' type_ = 'ssl' init_inputs = [ NodeInputBP(label='protocol_code'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.get_protocol_name(self.input(0))) class Get_Server_Certificate_Node(NodeBase): """ Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" title = 'get_server_certificate' type_ = 'ssl' init_inputs = [ NodeInputBP(label='addr'), NodeInputBP(label='ssl_version', dtype=dtypes.Data(default=2, size='s')), NodeInputBP(label='ca_certs', dtype=dtypes.Data(default=None, size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.get_server_certificate(self.input(0), self.input(1), self.input(2))) class Match_Hostname_Node(NodeBase): """ Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed. The function matches IP addresses rather than dNSNames if hostname is a valid ipaddress string. IPv4 addresses are supported on all platforms. IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 and inet_pton). CertificateError is raised on failure. On success, the function returns nothing. """ title = 'match_hostname' type_ = 'ssl' init_inputs = [ NodeInputBP(label='cert'), NodeInputBP(label='hostname'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.match_hostname(self.input(0), self.input(1))) class Namedtuple_Node(NodeBase): """ Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """ title = 'namedtuple' type_ = 'ssl' init_inputs = [ NodeInputBP(label='typename'), NodeInputBP(label='field_names'), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.namedtuple(self.input(0), self.input(1))) class Wrap_Socket_Node(NodeBase): """ """ title = 'wrap_socket' type_ = 'ssl' init_inputs = [ NodeInputBP(label='sock'), NodeInputBP(label='keyfile', dtype=dtypes.Data(default=None, size='s')), NodeInputBP(label='certfile', dtype=dtypes.Data(default=None, size='s')), NodeInputBP(label='server_side', dtype=dtypes.Data(default=False, size='s')), NodeInputBP(label='cert_reqs', dtype=dtypes.Data(default=0, size='s')), NodeInputBP(label='ssl_version', dtype=dtypes.Data(default=2, size='s')), NodeInputBP(label='ca_certs', dtype=dtypes.Data(default=None, size='s')), NodeInputBP(label='do_handshake_on_connect', dtype=dtypes.Data(default=True, size='s')), NodeInputBP(label='suppress_ragged_eofs', dtype=dtypes.Data(default=True, size='s')), NodeInputBP(label='ciphers', dtype=dtypes.Data(default=None, size='s')), ] init_outputs = [ NodeOutputBP(type_='data'), ] color = '#32DA22' def update_event(self, inp=-1): self.set_output_val(0, ssl.wrap_socket(self.input(0), self.input(1), self.input(2), self.input(3), self.input(4), self.input(5), self.input(6), self.input(7), self.input(8), self.input(9))) export_nodes( Der_Cert_To_Pem_Cert_Node, Pem_Cert_To_Der_Cert_Node, Rand_Add_Node, Rand_Bytes_Node, Rand_Pseudo_Bytes_Node, Rand_Status_Node, _Create_Default_Https_Context_Node, _Create_Stdlib_Context_Node, _Create_Unverified_Context_Node, _Dnsname_Match_Node, _Inet_Paton_Node, _Ipaddress_Match_Node, _Nid2Obj_Node, _Sslcopydoc_Node, _Txt2Obj_Node, Cert_Time_To_Seconds_Node, Create_Connection_Node, Create_Default_Context_Node, Enum_Certificates_Node, Enum_Crls_Node, Get_Default_Verify_Paths_Node, Get_Protocol_Name_Node, Get_Server_Certificate_Node, Match_Hostname_Node, Namedtuple_Node, Wrap_Socket_Node, )
8,012
3,102
// RUN: %clang_cc1 %s -verify // The reinterpret_cast operator shall not cast away constness. struct X {}; struct Y {}; void f(const int * X::* Y::* *p) { // This applies for similar types... (void)reinterpret_cast<int * X::* Y::* *>(p); // expected-error {{casts away qualifiers}} // ... and for cases where the base type is different ... (void)reinterpret_cast<float * X::* Y::* *>(p); // expected-error {{casts away qualifiers}} // ... and for cases where pointers to members point to members of different classes ... (void)reinterpret_cast<int * Y::* X::* *>(p); // expected-error {{casts away qualifiers}} // ... and even for cases where the path is wholly different! // (Though we accept such cases as an extension.) (void)reinterpret_cast<double Y::* X::* * *>(p); // expected-warning {{casts away qualifiers}} // If qualifiers are added, we need a 'const' at every level above. (void)reinterpret_cast<const volatile double Y::* X::* * *>(p); // expected-warning {{casts away qualifiers}} (void)reinterpret_cast<const volatile double Y::*const X::*const **>(p); // expected-warning {{casts away qualifiers}} (void)reinterpret_cast<const volatile double Y::*const X::**const *>(p); // expected-warning {{casts away qualifiers}} (void)reinterpret_cast<const volatile double Y::*X::*const *const *>(p); // expected-warning {{casts away qualifiers}} (void)reinterpret_cast<const volatile double Y::*const X::*const *const *>(p); // ok (void)reinterpret_cast<const double Y::*volatile X::**const *>(p); // expected-warning {{casts away qualifiers}} (void)reinterpret_cast<const double Y::*volatile X::*const *const *>(p); // ok }
500
445
<gh_stars>100-1000 #ifndef _SQ_WEDO_PLUGIN_H_ #define _SQ_WEDO_PLUGIN_H_ int WeDoOpenPort(void); int WeDoClosePort(void); int WeDoRead(char *bufPtr, int bufSize); int WeDoWrite(char *bufPtr, int bufSize); #endif /* _SQ_WEDO_PLUGIN_H_ */
114
1,755
/*========================================================================= Program: ParaView Module: vtkAppendArcLength.cxx Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAppendArcLength.h" #include "vtkCellArray.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" vtkStandardNewMacro(vtkAppendArcLength); //------------------------------------------------------------------------------ vtkAppendArcLength::vtkAppendArcLength() = default; //------------------------------------------------------------------------------ vtkAppendArcLength::~vtkAppendArcLength() = default; //------------------------------------------------------------------------------ int vtkAppendArcLength::RequestData( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkPolyData* input = vtkPolyData::GetData(inputVector[0], 0); vtkPolyData* output = vtkPolyData::GetData(outputVector, 0); if (input->GetNumberOfPoints() == 0) { return 1; } output->ShallowCopy(input); // Now add "arc_length" array. vtkDataArray* arc_length = nullptr; vtkPoints* points = output->GetPoints(); vtkIdType numPoints = points->GetNumberOfPoints(); if (points->GetDataType() == VTK_DOUBLE) { arc_length = vtkDoubleArray::New(); } else { arc_length = vtkFloatArray::New(); } arc_length->SetName("arc_length"); arc_length->SetNumberOfComponents(1); arc_length->SetNumberOfTuples(numPoints); arc_length->FillComponent(0, 0.0); vtkCellArray* lines = output->GetLines(); vtkIdType numCellPoints; const vtkIdType* cellPoints; lines->InitTraversal(); while (lines->GetNextCell(numCellPoints, cellPoints)) { if (numCellPoints == 0) { continue; } double arc_distance = 0.0; double prevPoint[3]; points->GetPoint(cellPoints[0], prevPoint); for (vtkIdType cc = 1; cc < numCellPoints; cc++) { double curPoint[3]; points->GetPoint(cellPoints[cc], curPoint); double distance = sqrt(vtkMath::Distance2BetweenPoints(curPoint, prevPoint)); arc_distance += distance; arc_length->SetTuple1(cellPoints[cc], arc_distance); memcpy(prevPoint, curPoint, 3 * sizeof(double)); } } output->GetPointData()->AddArray(arc_length); arc_length->Delete(); return 1; } //------------------------------------------------------------------------------ void vtkAppendArcLength::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
958
5,703
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.keyframes.deserializers; import android.graphics.Color; import android.graphics.Paint; import android.util.JsonReader; import java.io.IOException; import java.util.Locale; import com.facebook.keyframes.model.KFFeature; /** * Deserializer for {@link KFFeature}. * * Root deserializer starts at {@link KFImageDeserializer}. */ public class KFFeatureDeserializer { static final AbstractListDeserializer<KFFeature> LIST_DESERIALIZER = new AbstractListDeserializer<KFFeature>() { @Override KFFeature readObjectImpl(JsonReader reader) throws IOException { return readObject(reader); } }; public static KFFeature readObject(JsonReader reader) throws IOException { reader.beginObject(); KFFeature.Builder builder = new KFFeature.Builder(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { case KFFeature.NAME_JSON_FIELD: builder.name = reader.nextString(); break; case KFFeature.FILL_COLOR_JSON_FIELD: builder.fillColor = Color.parseColor(reader.nextString()); break; case KFFeature.STROKE_COLOR_JSON_FIELD: builder.strokeColor = Color.parseColor(reader.nextString()); break; case KFFeature.STROKE_WIDTH_JSON_FIELD: builder.strokeWidth = (float) reader.nextDouble(); break; case KFFeature.FROM_FRAME_JSON_FIELD: builder.fromFrame = (float) reader.nextDouble(); break; case KFFeature.TO_FRAME_JSON_FIELD: builder.toFrame = (float) reader.nextDouble(); break; case KFFeature.KEY_FRAMES_JSON_FIELD: builder.keyFrames = KFFeatureFrameDeserializer.LIST_DESERIALIZER.readList(reader); break; case KFFeature.TIMING_CURVES_JSON_FIELD: builder.timingCurves = CommonDeserializerHelper.read3DFloatArray(reader); break; case KFFeature.ANIMATION_GROUP_JSON_FIELD: builder.animationGroup = reader.nextInt(); break; case KFFeature.FEATURE_ANIMATIONS_JSON_FIELD: builder.featureAnimations = KFAnimationDeserializer.LIST_DESERIALIZER.readList(reader); break; case KFFeature.EFFECT_JSON_FIELD: builder.effect = KFFeatureEffectDeserializer.readObject(reader); break; case KFFeature.STROKE_LINE_CAP_JSON_FIELD: builder.strokeLineCap = Paint.Cap.valueOf(reader.nextString().toUpperCase(Locale.US)); break; case KFFeature.BACKED_IMAGE_NAME_JSON_FIELD: builder.backedImageName = reader.nextString(); break; case KFFeature.FEATURE_MASK_JSON_FIELD: builder.featureMask = KFFeatureDeserializer.readObject(reader); break; default: reader.skipValue(); } } reader.endObject(); return builder.build(); } }
1,361
344
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS: [{ "name": "textmate/r.tmbundle", "version": "0.0.0", "license": "TextMate Bundle License", "repositoryURL": "https://github.com/textmate/r.tmbundle", "licenseDetail": [ "Copyright (c) textmate-r.tmbundle project authors", "", "If not otherwise specified (see below), files in this folder fall under the following license: ", "", "Permission to copy, use, modify, sell and distribute this", "software is granted. This software is provided \"as is\" without", "express or implied warranty, and with no claim as to its", "suitability for any purpose." ] }]
218
735
<gh_stars>100-1000 /** * Tencent is pleased to support the open source community by making DCache available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 "UnpackTable.h" int g_iSlaveFlag = 0;//备机可读的轮询标志 namespace DCache { //////////////////////////////////////// UnpackTable::Entry::Entry() : value(0) { } ////////////////////////////////////////////////////// UnpackTable::UnpackTable() : _lrInfo(NULL), _lrInfo1(NULL), _init(false), _iLastLoadTime(0), _pageSize(__pageSize), _allPageCount(__allPageCount), _reloadTime(__reloadTime) { _hash = new NormalHash(); } UnpackTable::UnpackTable(const UnpackTable& r) : _lrInfo(NULL), _lrInfo1(NULL), _init(false), _iLastLoadTime(0), _pageSize(__pageSize), _allPageCount(__allPageCount), _reloadTime(__reloadTime) { _hash = new NormalHash(); string tmpServer = r.getSelfServer(); _pageSize = getPageSize(); _reloadTime = getReloadTime(); init(r.getPackTable(), tmpServer, _pageSize, _reloadTime); } UnpackTable::~UnpackTable() { delete _lrInfo; _lrInfo = NULL; delete _lrInfo1; _lrInfo1 = NULL; delete _hash; _hash = NULL; } ////////////////////////////////////////////////////// int UnpackTable::init(const PackTable& packTable, const string& sServerName, uint32_t pageSize, int64_t reloadTime, const vector<TransferInfo>& transferingInfoList) { LocalRouterInfo* tmpLRInfo = NULL; __UNPACK_TRY__ uint32_t uPageSize = pageSize > 0 ? pageSize : _pageSize; uint32_t uAllPageCount = __max / uPageSize + (__max % uPageSize > 0 ? 1 : 0); int64_t i64ReloadTime = reloadTime > 0 ? reloadTime : _reloadTime; tmpLRInfo = new LocalRouterInfo(uAllPageCount); // 加载服务器组及服务器信息 map<string, GroupInfo>::const_iterator it; for (it = packTable.groupList.begin(); it != packTable.groupList.end(); ++it) { tmpLRInfo->groupMap[it->second.id] = it->second; for (map<string, vector<string> >::const_iterator it2 = it->second.idcList.begin(); it2 != it->second.idcList.end(); ++it2) { for (size_t i = 0; i < it2->second.size(); i++) { tmpLRInfo->serverNameMap[it2->second[i]] = it->second.id; } } } string selfGroupName; // 找出sServerName所在服务器组名 int iRet = 0; if (!sServerName.empty()) { iRet = RET_NOT_FOUND_SERVER; map<string, int>::const_iterator it_s; if ((it_s = tmpLRInfo->serverNameMap.find(sServerName)) != tmpLRInfo->serverNameMap.end()) { iRet = RET_NOT_FOUND_GROUP; map<int, GroupInfo>::const_iterator it_g; if ((it_g = tmpLRInfo->groupMap.find(it_s->second)) != tmpLRInfo->groupMap.end()) { selfGroupName = it_g->second.groupName; iRet = RET_SUCC; } } if (iRet != RET_SUCC) { delete tmpLRInfo; return iRet; } } // 加载路由信息 for (size_t i = 0; i < packTable.recordList.size(); i++) { Entry entry; entry.value = 0; map<string, GroupInfo>::const_iterator it; if ((it = packTable.groupList.find(packTable.recordList[i].groupName)) != packTable.groupList.end()) // 路由记录对应的服务器组存在 { entry.setIndex(it->second.id); tmpLRInfo->routerGroupMap[it->second.id] = 0; } else { delete tmpLRInfo; return RET_NOT_FOUND_GROUP; } // 路由记录对应的服务器组名与本机所在组名相同,则该页为本机服务范围 if (packTable.recordList[i].groupName == selfGroupName) { entry.setSelf(true); } int k = packTable.recordList[i].toPageNo; for (int j = packTable.recordList[i].fromPageNo; j <= k; ++j) { memcpy(&tmpLRInfo->entry[j], &entry, sizeof(entry)); } } if (!transferingInfoList.empty()) { vector<TransferInfo>::const_iterator it = transferingInfoList.begin(); for (; it != transferingInfoList.end(); ++it) { for (int i = it->fromPageNo; i <= it->toPageNo; ++i) { tmpLRInfo->entry[i].setTransfering(true); map<string, GroupInfo>::const_iterator it1; if ((it1 = packTable.groupList.find(it->transGroupName)) != packTable.groupList.end()) // 路由记录对应的迁移目的服务器组存在 { tmpLRInfo->entry[i].setTransIndex(it1->second.id); } else { delete tmpLRInfo; return RET_NOT_FOUND_GROUP; } // 如果本机就是迁移的目的服务器,则也将该页设置为自己的服务范围 if (it->transGroupName == selfGroupName) { tmpLRInfo->entry[i].setSelf(true); } } } } tmpLRInfo->packTable = packTable; // 切换指针 TC_ThreadLock::Lock lock(_lock); int64_t nowus = TC_Common::now2us(); if (nowus - _iLastLoadTime < i64ReloadTime) { usleep(i64ReloadTime - nowus + _iLastLoadTime); } LocalRouterInfo* oldLRInfo = _lrInfo1, *newLRInfo = tmpLRInfo; tmpLRInfo = NULL; _lrInfo1 = _lrInfo; _lrInfo = newLRInfo; delete oldLRInfo; // 记录初始化参数 if (!_init) { _selfServer = sServerName; _init = true; _pageSize = uPageSize; _allPageCount = uAllPageCount; _reloadTime = i64ReloadTime; } // 记录最后一次加载时间 _iLastLoadTime = TC_Common::now2us(); return RET_SUCC; __UNPACK_CATCH__ if (tmpLRInfo != NULL) { delete tmpLRInfo; } return RET_EXCEPTION; } int UnpackTable::reload(const PackTable& packTable, const vector<TransferInfo>& transferingInfoList) { return init(packTable, _selfServer, _pageSize, _reloadTime, transferingInfoList); } int UnpackTable::getMasterByHash(uint32_t hash, ServerInfo& serverInfo) const { __UNPACK_TRY__ int iRet = RET_SUCC; // 取得页号 uint32_t pageNo = hash / _pageSize; assert(pageNo <= _allPageCount); LocalRouterInfo * lrInfTmp = _lrInfo; // 根据页号获取所属服务器组编号 int groupId = lrInfTmp->entry[pageNo].getIndex(); map<int, GroupInfo>::const_iterator it = lrInfTmp->groupMap.find(groupId); if (it != lrInfTmp->groupMap.end()) { if (it->second.accessStatus == 1) return RET_GROUP_READONLY; serverInfo = lrInfTmp->packTable.serverList[it->second.masterServer]; if (serverInfo.serverName.empty()) // 服务器名为空则说明服务器不存在 return RET_NOT_FOUND_SERVER; } else { iRet = RET_NOT_FOUND_GROUP; } return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } int UnpackTable::getAllMasters(vector<ServerInfo>& masterServers) const { __UNPACK_TRY__ int iRet = RET_SUCC; masterServers.clear(); LocalRouterInfo * lrInfTmp = _lrInfo; // 遍历groupMap,获取所有masterServer map<int, GroupInfo>::const_iterator it; for (it = lrInfTmp->groupMap.begin(); it != lrInfTmp->groupMap.end(); it++) { if (!it->second.masterServer.empty()) { masterServers.push_back(lrInfTmp->packTable.serverList[it->second.masterServer]); } else { // 程序如果运行到此else分支,表示该组没有主服务器,这是个严重的错误! iRet = RET_NOT_FOUND_SERVER; // 找不到仍然继续 } } return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } int UnpackTable::getAllIdcServer(const string &sIdc, vector<ServerInfo> &servers) const { __UNPACK_TRY__ int iRet = RET_SUCC; servers.clear(); LocalRouterInfo * lrInfTmp = _lrInfo; // 遍历所有有路由的组 map<int, int>::const_iterator itRouter; for (itRouter = lrInfTmp->routerGroupMap.begin(); itRouter != lrInfTmp->routerGroupMap.end(); itRouter++) { map<int, GroupInfo>::const_iterator it = lrInfTmp->groupMap.find(itRouter->first); if (it == lrInfTmp->groupMap.end()) { TLOGERROR("[UnpackTable::getAllIdcServer] can not find group id:" << itRouter->first << endl); return -1; } map<string, vector<string> >::const_iterator it_idc = it->second.idcList.find(sIdc); if (it_idc != it->second.idcList.end()) { //只读状态,把对主机的读都切到备机 if (it->second.accessStatus == 1) { if (it_idc->second.size() > 1) { servers.push_back(lrInfTmp->packTable.serverList[it_idc->second[1]]); } else servers.push_back(lrInfTmp->packTable.serverList[it_idc->second[0]]); } //镜像不可用状态,把对镜像的读切换到备机 else if (it->second.accessStatus == 2) { ServerInfo serverInfo = lrInfTmp->packTable.serverList[it->second.masterServer]; if (sIdc != serverInfo.idc) { //查询镜像,先要检查镜像服务状态。如果没有镜像备机并且状态不为0,则切到备机 ServerInfo mirrServerInfo = _lrInfo->packTable.serverList[it_idc->second[0]]; if ((it_idc->second.size() == 1) && (mirrServerInfo.status != 0)) { map<string, vector<string> >::const_iterator it_idc_master = it->second.idcList.find(serverInfo.idc); if (it_idc_master->second.size() > 1) servers.push_back(lrInfTmp->packTable.serverList[it_idc_master->second[1]]); else servers.push_back(lrInfTmp->packTable.serverList[it_idc_master->second[0]]); } else servers.push_back(mirrServerInfo); } else servers.push_back(lrInfTmp->packTable.serverList[it_idc->second[0]]); } else { servers.push_back(lrInfTmp->packTable.serverList[it_idc->second[0]]); //? } } else { servers.push_back(lrInfTmp->packTable.serverList[it->second.masterServer]); } } if (servers.size() == 0) { TLOGERROR("[UnpackTable::getAllIdcServer] can not find groups!" << endl); return -1; } return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } int UnpackTable::getGroup(const string& sServerName, GroupInfo& group) const { __UNPACK_TRY__ int iRet = RET_NOT_FOUND_SERVER; LocalRouterInfo * lrInfTmp = _lrInfo; // 根据服务器名找出所在服务器组 map<string, int>::const_iterator it_s; if ((it_s = lrInfTmp->serverNameMap.find(sServerName)) != lrInfTmp->serverNameMap.end()) { iRet = RET_NOT_FOUND_GROUP; map<int, GroupInfo>::const_iterator it_g; if ((it_g = lrInfTmp->groupMap.find(it_s->second)) != lrInfTmp->groupMap.end()) { group = it_g->second; iRet = RET_SUCC; } } return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } int UnpackTable::getTrans(int PageNo, ServerInfo& srcServer, ServerInfo& destServer) { __UNPACK_TRY__ int iRet = RET_SUCC; LocalRouterInfo * lrInfTmp = _lrInfo; if ((uint32_t)PageNo <= _allPageCount) { // 获取当前所属服务器信息 uint32_t id = lrInfTmp->entry[PageNo].getIndex(); map<int, GroupInfo>::const_iterator it_src_group = lrInfTmp->groupMap.find(id); if (it_src_group != lrInfTmp->groupMap.end()) { if (it_src_group->second.masterServer.empty()) iRet = RET_NOT_FOUND_SRC_MASTER; srcServer = lrInfTmp->packTable.serverList[it_src_group->second.masterServer]; } else { iRet = RET_NOT_FOUND_SRC_GROUP; } // 如果正在迁移,则获取迁移目的服务器信息 if (lrInfTmp->entry[PageNo].getTransfering()) { id = lrInfTmp->entry[PageNo].getTransIndex(); map<int, GroupInfo>::const_iterator it_dest_group = lrInfTmp->groupMap.find(id); if (it_dest_group != lrInfTmp->groupMap.end()) { if (it_dest_group->second.masterServer.empty()) iRet = RET_NOT_FOUND_DEST_MASTER; destServer = lrInfTmp->packTable.serverList[it_dest_group->second.masterServer]; } else { iRet = RET_NOT_FOUND_DEST_GROUP; } } else { iRet = RET_NOT_TRANSFERING; } } else { iRet = RET_NOT_FOUND_TRANS; } return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } bool UnpackTable::isTransSrc(int PageNo, const string& sServerName) { ServerInfo srcServer; ServerInfo destServer; getTrans(PageNo, srcServer, destServer); if (srcServer.serverName == sServerName) return true; return false; } int UnpackTable::getBakSource(const string& sServerName, ServerInfo &bakSourceServer) { __UNPACK_TRY__ LocalRouterInfo * lrInfTmp = _lrInfo; int iRet = RET_NOT_FOUND_SERVER; map<string, int>::const_iterator it_s; if ((it_s = lrInfTmp->serverNameMap.find(sServerName)) != lrInfTmp->serverNameMap.end()) { iRet = RET_NOT_FOUND_GROUP; map<int, GroupInfo>::const_iterator it_g; if ((it_g = lrInfTmp->groupMap.find(it_s->second)) != lrInfTmp->groupMap.end()) { map<string, string>::const_iterator it_bs; if ((it_bs = it_g->second.bakList.find(sServerName)) != it_g->second.bakList.end()) { if (it_bs->second != "") { iRet = RET_SUCC; bakSourceServer = lrInfTmp->packTable.serverList[it_bs->second]; } else { iRet = RET_NOT_FOUND_SERVER; } } else { iRet = RET_NOT_FOUND_SERVER; } } } return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } int UnpackTable::getVersion() { return _lrInfo->packTable.info.version; // 返回版本号 } bool UnpackTable::isMySelfByHash(uint32_t hash) const { uint32_t pageNo = hash / _pageSize; assert(pageNo <= _allPageCount); return _lrInfo->entry[pageNo].getSelf(); } bool UnpackTable::isTransferingByHash(uint32_t hash) const { uint32_t pageNo = hash / _pageSize; assert(pageNo <= _allPageCount); return _lrInfo->entry[pageNo].getTransfering(); } void UnpackTable::print(ostream& os) const { __UNPACK_TRY__ _lrInfo->packTable.display(os); __UNPACK_CATCH__ return; } void UnpackTable::clear() { __UNPACK_TRY__ LocalRouterInfo* oldLRInfo = _lrInfo; _lrInfo = new LocalRouterInfo(_allPageCount); delete oldLRInfo; oldLRInfo = _lrInfo1; _lrInfo1 = new LocalRouterInfo(_allPageCount); delete oldLRInfo; _selfServer.clear(); __UNPACK_CATCH__ return; } int UnpackTable::fromFile(const string& fileName, const string& sServerName) { __UNPACK_TRY__ string sContent = TC_File::load2str(fileName); tars::TarsInputStream<tars::BufferReader> _is; _is.setBuffer(sContent.c_str(), sContent.length()); PackTable tmpPackTable; _is.read(tmpPackTable, 0, true); int iRet = init(tmpPackTable, sServerName, _pageSize, _reloadTime); return iRet; __UNPACK_CATCH__ return RET_EXCEPTION; } int UnpackTable::toFile(const string& fileName) const { __UNPACK_TRY__ ofstream outputStream(fileName.c_str()); tars::TarsOutputStream<tars::BufferWriter> _os; _os.write(_lrInfo->packTable, 0); outputStream.write(_os.getBuffer(), _os.getLength()); outputStream.close(); return 0; __UNPACK_CATCH__ return RET_EXCEPTION; } string UnpackTable::toString() const { __UNPACK_TRY__ ostringstream os; _lrInfo->packTable.display(os); return os.str(); __UNPACK_CATCH__ return ""; } size_t UnpackTable::hashKey(uint32_t key) const { return _hash->HashRawInt(key); } size_t UnpackTable::hashKey(uint64_t key) const { return _hash->HashRawLong(key); } size_t UnpackTable::hashKey(string key) const { return _hash->HashRawString(key); } }
10,612
4,756
// Copyright 2020 The MACE 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 "rpc/stub/base_handle.h" namespace rpc { namespace stub { namespace { const remote_handle64 IVALID_HANDLE = -1; } BaseHandle::BaseHandle(FuncOpen *func_open, FuncClose *func_close, const char *uri) : func_open_(func_open), func_close_(func_close), uri_(uri), remote_handle_(IVALID_HANDLE) {} BaseHandle::~BaseHandle() { Close(); } bool BaseHandle::Open() { if (Valid()) { return true; } int ret = func_open_(uri_, &remote_handle_); if (ret != 0 || remote_handle_ == IVALID_HANDLE) { remote_handle_ = IVALID_HANDLE; return false; } else { return true; } } bool BaseHandle::Close() { bool status = true; if (Valid()) { int ret = func_close_(remote_handle_); remote_handle_ = IVALID_HANDLE; if (ret != 0) { status = false; } } return status; } bool BaseHandle::Valid() { return (remote_handle_ != IVALID_HANDLE); } } // namespace stub } // namespace rpc
597
1,231
<reponame>RalfGuder/LaTeX-examples ArrayList<String> l1 = new ArrayList<String>(); ArrayList<Integer> l2 = new ArrayList<Integer>();
49
449
#ifndef GEEF_TAG_H #define GEEF_TAG_H ERL_NIF_TERM geef_tag_list(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]); ERL_NIF_TERM geef_tag_peel(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]); ERL_NIF_TERM geef_tag_name(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]); ERL_NIF_TERM geef_tag_message(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]); ERL_NIF_TERM geef_tag_author(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]); #endif
238
2,389
<reponame>Ankit01Mishra/java package io.kubernetes.client.openapi.models; import com.google.gson.annotations.SerializedName; import io.kubernetes.client.fluent.Fluent; import io.kubernetes.client.fluent.Nested; import java.lang.String; import java.lang.Deprecated; import java.lang.Boolean; /** * Generated */ public interface V1beta2SubjectFluent<A extends io.kubernetes.client.openapi.models.V1beta2SubjectFluent<A>> extends io.kubernetes.client.fluent.Fluent<A>{ /** * This method has been deprecated, please use method buildGroup instead. * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1beta2GroupSubject getGroup(); public io.kubernetes.client.openapi.models.V1beta2GroupSubject buildGroup(); public A withGroup(io.kubernetes.client.openapi.models.V1beta2GroupSubject group); public java.lang.Boolean hasGroup(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.GroupNested<A> withNewGroup(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.GroupNested<A> withNewGroupLike(io.kubernetes.client.openapi.models.V1beta2GroupSubject item); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.GroupNested<A> editGroup(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.GroupNested<A> editOrNewGroup(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.GroupNested<A> editOrNewGroupLike(io.kubernetes.client.openapi.models.V1beta2GroupSubject item); public java.lang.String getKind(); public A withKind(java.lang.String kind); public java.lang.Boolean hasKind(); /** * Method is deprecated. use withKind instead. */ @java.lang.Deprecated public A withNewKind(java.lang.String original); /** * This method has been deprecated, please use method buildServiceAccount instead. * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1beta2ServiceAccountSubject getServiceAccount(); public io.kubernetes.client.openapi.models.V1beta2ServiceAccountSubject buildServiceAccount(); public A withServiceAccount(io.kubernetes.client.openapi.models.V1beta2ServiceAccountSubject serviceAccount); public java.lang.Boolean hasServiceAccount(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.ServiceAccountNested<A> withNewServiceAccount(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.ServiceAccountNested<A> withNewServiceAccountLike(io.kubernetes.client.openapi.models.V1beta2ServiceAccountSubject item); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.ServiceAccountNested<A> editServiceAccount(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.ServiceAccountNested<A> editOrNewServiceAccount(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.ServiceAccountNested<A> editOrNewServiceAccountLike(io.kubernetes.client.openapi.models.V1beta2ServiceAccountSubject item); /** * This method has been deprecated, please use method buildUser instead. * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1beta2UserSubject getUser(); public io.kubernetes.client.openapi.models.V1beta2UserSubject buildUser(); public A withUser(io.kubernetes.client.openapi.models.V1beta2UserSubject user); public java.lang.Boolean hasUser(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.UserNested<A> withNewUser(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.UserNested<A> withNewUserLike(io.kubernetes.client.openapi.models.V1beta2UserSubject item); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.UserNested<A> editUser(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.UserNested<A> editOrNewUser(); public io.kubernetes.client.openapi.models.V1beta2SubjectFluent.UserNested<A> editOrNewUserLike(io.kubernetes.client.openapi.models.V1beta2UserSubject item); public interface GroupNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1beta2GroupSubjectFluent<io.kubernetes.client.openapi.models.V1beta2SubjectFluent.GroupNested<N>>{ public N and(); public N endGroup(); } public interface ServiceAccountNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1beta2ServiceAccountSubjectFluent<io.kubernetes.client.openapi.models.V1beta2SubjectFluent.ServiceAccountNested<N>>{ public N and(); public N endServiceAccount(); } public interface UserNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1beta2UserSubjectFluent<io.kubernetes.client.openapi.models.V1beta2SubjectFluent.UserNested<N>>{ public N and(); public N endUser(); } }
1,687
923
<filename>PyTorch-Lightning/main_tune.py import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader, random_split from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split import pytorch_lightning as pl class NeuralNet(pl.LightningModule): def __init__(self, learning_rate=0.001, batch_size=3): super().__init__() # Boring model self.layer_1 = nn.Linear(30, 16) self.layer_2 = nn.Linear(16, 1) # self.learning_rate = learning_rate self.batch_size = batch_size # Log hyperparameters self.save_hyperparameters() # Built-in API for metrics self.train_accuracy = pl.metrics.Accuracy() self.val_accuracy = pl.metrics.Accuracy() self.test_accuracy = pl.metrics.Accuracy() def forward(self, x): # Simple forward x = self.layer_1(x) x = torch.relu(x) x = self.layer_2(x) x = torch.sigmoid(x) return x.squeeze() def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.learning_rate) def training_step(self, batch, batch_idx): # Gets "x" and "y" tensors for current batch x, y = batch # Feed the model and catch the prediction y_pred = self.forward(x) # Calculates loss for the current batch loss = F.binary_cross_entropy(y_pred, y) # Calculates accuracy for current batch train_acc_batch = self.train_accuracy(y_pred, y) # Save metrics for current batch self.log('train_acc_batch', train_acc_batch) self.log('train_loss_batch', loss) return {'loss' : loss, 'y_pred' : y_pred, 'y_true' : y} def training_epoch_end(self, outputs): accuracy = self.train_accuracy.compute() # Save the metric self.log('Train_acc_epoch', accuracy) def validation_step(self, batch, batch_idx): # Gets "x" and "y" tensors for current batch x, y = batch # Feed the model and catch the prediction (no need to set the model as "evaluation" mode) y_pred = self.forward(x) # Calculate loss for the current batch loss = F.binary_cross_entropy(y_pred, y) # Calculates accuracy for the current batch val_acc_batch = self.val_accuracy(y_pred, y) # Save metrics for current batch self.log('val_acc_batch', val_acc_batch) self.log('val_loss_batch', loss) return {'loss' : loss, 'y_pred' : y_pred, 'target' : y} def validation_epoch_end(self, outputs): accuracy = self.val_accuracy.compute() # Save the metric self.log('Val_acc_epoch', accuracy) def test_step(self, batch, batch_idx): # Gets "x" and "y" tensors for current batch x, y = batch # Feed the model and catch the prediction (no need to set the model as "evaluation" mode) y_pred = self.forward(x) # Calculate loss for the current batch loss = F.binary_cross_entropy(y_pred, y) # Calculates accuracy for the current batch test_acc_batch = self.test_accuracy(y_pred, y) # Save metrics for current batch self.log('test_acc_batch', test_acc_batch) self.log('test_loss_batch', loss) # return {'loss' : loss, 'y_pred' : y_pred, 'target' : y} return test_acc_batch def prepare_data(self): self.x, self.y = load_breast_cancer(return_X_y=True) def setup(self, stage=None): x_train, x_val, y_train, y_val = train_test_split(self.x, self.y, test_size=0.3) x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.3) # Assign train/val datasets for use in dataloaders if stage == 'fit' or stage is None: self.x_train = torch.from_numpy(x_train).type(torch.FloatTensor) self.y_train = torch.from_numpy(y_train).type(torch.FloatTensor) self.x_val = torch.from_numpy(x_val).type(torch.FloatTensor) self.y_val = torch.from_numpy(y_val).type(torch.FloatTensor) # Assign test dataset for use in dataloader(s) if stage == 'test' or stage is None: self.x_test = torch.from_numpy(x_test).type(torch.FloatTensor) self.y_test = torch.from_numpy(y_test).type(torch.FloatTensor) def train_dataloader(self): self.train_dataset = torch.utils.data.TensorDataset(self.x_train, self.y_train) return DataLoader(self.train_dataset, batch_size=self.batch_size) def val_dataloader(self): self.val_dataset = torch.utils.data.TensorDataset(self.x_val, self.y_val) return DataLoader(self.val_dataset, batch_size=self.batch_size) def test_dataloader(self): self.test_dataset = torch.utils.data.TensorDataset(self.x_test, self.y_test) return DataLoader(self.test_dataset, batch_size=self.batch_size) if __name__ == "__main__": # Instantiate model model = NeuralNet() # Initialize trainer trainer = pl.Trainer(max_epochs=100, check_val_every_n_epoch=10, precision=32, weights_summary=None, progress_bar_refresh_rate=1, auto_scale_batch_size='binsearch') # It is implemented the built-in function for finding the # optimal learning rate. Source: https://arxiv.org/pdf/1506.01186.pdf lr_finder = trainer.tuner.lr_find(model, min_lr=0.0005, max_lr=0.005, mode='linear') # Plots the optimal learning rate fig = lr_finder.plot(suggest=True) fig.show() # The suggested optimal learning rate is now taken as the default learning rate model.learning_rate = lr_finder.suggestion() # Once the optimal learning rate is found, let's find the largest optimal batch size trainer.tune(model) # # Once everything is done, let's train the model trainer.fit(model) # # Testing the model trainer.test()
2,848
348
{"nom":"Saillant","circ":"5ème circonscription","dpt":"Puy-de-Dôme","inscrits":301,"abs":134,"votants":167,"blancs":3,"nuls":2,"exp":162,"res":[{"nuance":"COM","nom":"M. <NAME>","voix":121},{"nuance":"REM","nom":"<NAME>","voix":41}]}
96
398
package io.joyrpc.config; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * 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. * #L% */ import io.joyrpc.constants.ExceptionCode; import io.joyrpc.exception.IllegalConfigureException; import io.joyrpc.extension.URLBiOption; import io.joyrpc.extension.URLOption; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * 配置基类 */ public abstract class AbstractConfig { public AbstractConfig() { } public AbstractConfig(AbstractConfig config) { } /** * 添加配置项 * * @param dest 目标 * @param key 键 * @param value 值 */ protected void addElement2Map(final Map<String, String> dest, final String key, final Object value) { if (null != value) { String v = value.toString(); if (v != null && !v.isEmpty()) { dest.put(key, value.toString()); } } } /** * 添加配置项 * * @param dest 目标 * @param option 选项 * @param value 值 */ protected void addElement2Map(final Map<String, String> dest, final URLOption<?> option, final Object value) { addElement2Map(dest, option.getName(), value); } /** * 添加配置项 * * @param dest 目标 * @param option 选项 * @param value 值 */ protected void addElement2Map(final Map<String, String> dest, final URLBiOption<?> option, final Object value) { addElement2Map(dest, option.getName(), value); } /** * 添加配置项 * * @param params 目标 * @return */ protected Map<String, String> addAttribute2Map(Map<String, String> params) { return params; } /** * 创建配置项 * * @return 配置项 */ protected Map<String, String> addAttribute2Map() { Map<String, String> result = new HashMap<>(); addAttribute2Map(result); return result; } /** * 名称 * * @return 名称 */ protected String name() { return ""; } /** * 调用JSR303进行配置项验证 */ public void validate() { Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); if (validator == null) { throw new IllegalConfigureException("javax.validation.Validator is not implement", ExceptionCode.COMMON_VALUE_ILLEGAL); } else { //JSR303验证 Set<ConstraintViolation<Object>> violations = validator.validate(this); if (!violations.isEmpty()) { //有异常 StringBuilder builder = new StringBuilder(100).append(name()); for (ConstraintViolation<Object> violation : violations) { builder.append("\n\t"); builder.append("ConstraintViolation"); builder.append("{message=\"").append(violation.getMessage()); builder.append("\", propertyPath=").append(violation.getPropertyPath()); builder.append('}'); } throw new IllegalConfigureException(builder.toString(), ExceptionCode.COMMON_VALUE_ILLEGAL); } } } }
1,721
352
package com.tmobile.cso.vault.api.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.*; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.tmobile.cso.vault.api.common.AzureServiceAccountConstants; import com.tmobile.cso.vault.api.exception.LogMessage; import com.tmobile.cso.vault.api.model.*; import com.tmobile.cso.vault.api.process.RequestProcessor; import com.tmobile.cso.vault.api.process.Response; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Value; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.util.StringUtils; @Component public class AzureServiceAccountUtils { @Value("${iamPortal.domain}") private String iamPortalDomain; @Value("${iamPortal.auth.endpoint}") private String iamPortalAuthEndpoint; @Value("${azurePortal.secret.endpoint}") private String azurePortalrotateSecretEndpoint; private Logger log = LogManager.getLogger(AzureServiceAccountUtils.class); @Autowired HttpUtils httpUtils; @Autowired IAMServiceAccountUtils iamServiceAccountUtils; @Autowired private RequestProcessor requestProcessor; /** * Convenient method to get policies as list from token lookup. * @param objMapper * @param policyJson * @return * @throws JsonProcessingException * @throws IOException */ public List<String> getTokenPoliciesAsListFromTokenLookupJson(ObjectMapper objMapper, String policyJson) throws IOException{ log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "getTokenPoliciesAsListFromTokenLookupJson") .put(LogMessage.MESSAGE,"Start trying to get policies as list from TokenLookupJson" ) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)) .build())); List<String> currentpolicies = new ArrayList<>(); JsonNode policiesNode = objMapper.readTree(policyJson).get("policies"); if (null != policiesNode ) { if (policiesNode.isContainerNode()) { Iterator<JsonNode> elementsIterator = policiesNode.elements(); while (elementsIterator.hasNext()) { JsonNode element = elementsIterator.next(); currentpolicies.add(element.asText()); } } else { currentpolicies.add(policiesNode.asText()); } } log.debug(JSONUtil.getJSON(ImmutableMap.<String, String> builder() .put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)) .put(LogMessage.ACTION, "getTokenPoliciesAsListFromTokenLookupJson") .put(LogMessage.MESSAGE,"got policies as list from TokenLookupJson" ) .put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)) .build())); return currentpolicies; } /** * To get response from rotate api. * * @return */ public AzureServiceAccountSecret rotateAzureServicePrincipalSecret(AzureServicePrincipalRotateRequest azureServicePrincipalRotateRequest) { String iamApproleToken = iamServiceAccountUtils.getIAMApproleToken(); if (StringUtils.isEmpty(iamApproleToken)) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Invalid Azure Portal approle token"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); return null; } String api = iamPortalDomain + azurePortalrotateSecretEndpoint; if (StringUtils.isEmpty(iamPortalDomain) || StringUtils.isEmpty(azurePortalrotateSecretEndpoint)) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Invalid Azure service principal endpoint"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); return null; } JsonParser jsonParser = new JsonParser(); HttpClient httpClient = httpUtils.getHttpClient(); if (httpClient == null) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Failed to initialize httpClient"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); return null; } HttpPut httpPut = new HttpPut(api); String inputJson = JSONUtil.getJSON(azureServicePrincipalRotateRequest); Gson gson = new Gson(); JsonElement jsonObj= gson.fromJson(inputJson, JsonElement.class); jsonObj.getAsJsonObject().remove("azureSvcAccName"); StringEntity entity; String iamAuthToken = AzureServiceAccountConstants.AZURE_AUTH_TOKEN_PREFIX + " " + Base64.getEncoder().encodeToString(iamApproleToken.getBytes()); try { entity = new StringEntity(jsonObj.toString()); httpPut.setEntity(entity); httpPut.setHeader("Authorization", iamAuthToken); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-type", "application/json"); httpPut.setEntity(entity); } catch (UnsupportedEncodingException e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Failed to build StringEntity"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); return null; } StringBuilder jsonResponse = new StringBuilder(); try { HttpResponse apiResponse = httpClient.execute(httpPut); if (apiResponse.getStatusLine().getStatusCode() != 200) { StringBuilder total = new StringBuilder(); readFailedResponseContent(apiResponse, total); return null; } readResponseContent(jsonResponse, apiResponse, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION); AzureServiceAccountSecret azureServiceAccountSecret = new AzureServiceAccountSecret(); JsonObject responseJson = (JsonObject) jsonParser.parse(jsonResponse.toString()); if (!responseJson.isJsonNull()) { azureServiceAccountSecret = addValuesToAzureServiceAccountSecret(azureServiceAccountSecret,responseJson); } return azureServiceAccountSecret; } catch (IOException e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Failed to parse Azure Service Principal Secret response"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } return null; } /** * Method to read response * @param apiResponse * @param total */ private void readFailedResponseContent(HttpResponse apiResponse, StringBuilder total) { try(BufferedReader r = new BufferedReader(new InputStreamReader(apiResponse.getEntity().getContent()))) { String line = null; while ((line = r.readLine()) != null) { total.append(line); } log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Failed to build StringEntity:"+total.toString()). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); }catch(IOException ex) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, AzureServiceAccountConstants.AZURE_SP_ROTATE_SECRET_ACTION). put(LogMessage.MESSAGE, "Failed to read response"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } } /** * To save Azure Service Principal Secret for a single SecretKeyId. * @param token * @param path * @param servicePrincipalName * @param azureServiceAccountSecret * @return */ public boolean writeAzureSPSecret(String token, String path, String servicePrincipalName, AzureServiceAccountSecret azureServiceAccountSecret) { boolean isSecretUpdated = false; ObjectMapper objMapper = new ObjectMapper(); String secretJson = null; try { secretJson = objMapper.writeValueAsString(azureServiceAccountSecret); } catch (JsonProcessingException e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "writeAzureSPSecret"). put(LogMessage.MESSAGE, "Failed to write Azure Service Principal secret request as string json"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); return isSecretUpdated; } String writeJson = "{\"path\":\""+path+"\",\"data\":"+ secretJson +"}"; Response response = requestProcessor.process("/write", writeJson, token); if(response.getHttpstatus().equals(HttpStatus.NO_CONTENT)){ isSecretUpdated = true; log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "writeAzureSPSecret"). put(LogMessage.MESSAGE, String.format("Successfully saved secrets for Azure Service Principal " + "[%s] for secret key id: [%s]", servicePrincipalName, azureServiceAccountSecret.getSecretKeyId())). put(LogMessage.STATUS, response.getHttpstatus().toString()). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } else { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "writeAzureSPSecret"). put(LogMessage.MESSAGE, "Failed to save Azure Service Principal Secret in T-Vault"). put(LogMessage.STATUS, response.getHttpstatus().toString()). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } return isSecretUpdated; } /** * To update Secret key details in metadata. * @param token * @param servicePrincipalName * @param secretKeyId * @param azureServiceAccountSecret * @return */ public Response updateAzureSPSecretKeyInfoInMetadata(String token, String servicePrincipalName, String secretKeyId, AzureServiceAccountSecret azureServiceAccountSecret){ log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "updateAzureSPSecretKeyInfoInMetadata"). put(LogMessage.MESSAGE, String.format ("Trying to update the metadata with secretKeyId [%s] for Azure Service Principal [%s]", secretKeyId, servicePrincipalName)). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); String path = new StringBuffer(AzureServiceAccountConstants.AZURE_SVCC_ACC_PATH).append(servicePrincipalName).toString(); String typeSecret = "secret"; path = "metadata/"+path; ObjectMapper objMapper = new ObjectMapper(); String pathjson ="{\"path\":\""+path+"\"}"; // Read info for the path Response metadataResponse = requestProcessor.process("/read",pathjson,token); Map<String,Object> _metadataMap = null; if(HttpStatus.OK.equals(metadataResponse.getHttpstatus())){ try { _metadataMap = objMapper.readValue(metadataResponse.getResponse(), new TypeReference<Map<String,Object>>() {}); } catch (IOException e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "updateAzureSPSecretKeyInfoInMetadata"). put(LogMessage.MESSAGE, String.format ("Error creating _metadataMap for type [%s] and path [%s] message [%s]", typeSecret, path, e.getMessage())). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } @SuppressWarnings("unchecked") Map<String,Object> metadataMap = (Map<String,Object>) _metadataMap.get("data"); ObjectMapper objectMapper = new ObjectMapper(); List<AzureSecretsMetadata> currentSecretData = objectMapper.convertValue((List<AzureSecretsMetadata>) metadataMap.get(typeSecret), new TypeReference<List<AzureSecretsMetadata>>() { }); if(null != currentSecretData) { List<AzureSecretsMetadata> newSecretData = new ArrayList<>(); for (int i=0;i<currentSecretData.size();i++) { AzureSecretsMetadata azureSecretsMetadata = currentSecretData.get(i); if (secretKeyId.equals(azureSecretsMetadata.getSecretKeyId())) { azureSecretsMetadata.setSecretKeyId(azureServiceAccountSecret.getSecretKeyId()); } newSecretData.add(azureSecretsMetadata); } metadataMap.put(typeSecret, newSecretData); String metadataJson = ""; try { metadataJson = objMapper.writeValueAsString(metadataMap); } catch (JsonProcessingException e) { log.error(e); log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "updateAzureSPSecretKeyInfoInMetadata"). put(LogMessage.MESSAGE, String.format ("Error in creating metadataJson for type [%s] and path [%s] with message [%s]", typeSecret, path, e.getMessage())). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } String writeJson = "{\"path\":\""+path+"\",\"data\":"+ metadataJson +"}"; metadataResponse = requestProcessor.process("/write",writeJson,token); return metadataResponse; } return metadataResponse; } return null; } /** * Update metadata for the Azure Service Principal on activation. * @param token * @param servicePrincipalName * @return */ public Response updateActivatedStatusInMetadata(String token, String servicePrincipalName){ log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "updateActivatedStatusInMetadata"). put(LogMessage.MESSAGE, String.format ("Trying to update metadata on Azure Service Principal activation for [%s]", servicePrincipalName)). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); String path = new StringBuffer(AzureServiceAccountConstants.AZURE_SVCC_ACC_PATH).append(servicePrincipalName).toString(); Map<String,String> isActivatedParams = new HashMap<>(); isActivatedParams.put("type", "isActivated"); isActivatedParams.put("path",path); isActivatedParams.put("value","true"); String typeIsActivated = isActivatedParams.get("type"); path = "metadata/"+path; ObjectMapper objMapper = new ObjectMapper(); String pathjson ="{\"path\":\""+path+"\"}"; // Read info for the path Response metadataResponse = requestProcessor.process("/read",pathjson,token); Map<String,Object> _metadataMap = null; if(HttpStatus.OK.equals(metadataResponse.getHttpstatus())){ try { _metadataMap = objMapper.readValue(metadataResponse.getResponse(), new TypeReference<Map<String,Object>>() {}); } catch (IOException e) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "updateActivatedStatusInMetadata"). put(LogMessage.MESSAGE, String.format ("Error creating _metadataMap for type [%s] and path [%s] message [%s]", typeIsActivated, path, e.getMessage())). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } @SuppressWarnings("unchecked") Map<String,Object> metadataMap = (Map<String,Object>) _metadataMap.get("data"); @SuppressWarnings("unchecked") boolean isActivated = (boolean) metadataMap.get(typeIsActivated); if(StringUtils.isEmpty(isActivated) || !isActivated) { metadataMap.put(typeIsActivated, true); String metadataJson = ""; try { metadataJson = objMapper.writeValueAsString(metadataMap); } catch (JsonProcessingException e) { log.error(e); log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, "updateActivatedStatusInMetadata"). put(LogMessage.MESSAGE, String.format ("Error in creating metadataJson for type [%s] and path [%s] with message [%s]", typeIsActivated, path, e.getMessage())). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } String writeJson = "{\"path\":\""+path+"\",\"data\":"+ metadataJson +"}"; metadataResponse = requestProcessor.process("/write",writeJson,token); return metadataResponse; } return metadataResponse; } return null; } /** * Method to read the response content * @param jsonResponse * @param apiResponse */ private void readResponseContent(StringBuilder jsonResponse, HttpResponse apiResponse, String actionMsg) { String output = ""; try(BufferedReader br = new BufferedReader(new InputStreamReader((apiResponse.getEntity().getContent())))) { while ((output = br.readLine()) != null) { jsonResponse.append(output); } }catch(Exception ex) { log.error(JSONUtil.getJSON(ImmutableMap.<String, String>builder(). put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER)). put(LogMessage.ACTION, actionMsg). put(LogMessage.MESSAGE, "Failed to read the response"). put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL)). build())); } } private AzureServiceAccountSecret addValuesToAzureServiceAccountSecret(AzureServiceAccountSecret azureServiceAccountSecret, JsonObject responseJson) { if (responseJson.has("servicePrincipalId")) { azureServiceAccountSecret.setServicePrincipalId(responseJson.get("servicePrincipalId").getAsString()); } if (responseJson.has("tenantId")) { azureServiceAccountSecret.setTenantId(responseJson.get("tenantId").getAsString()); } if (responseJson.has("secretKeyId")) { azureServiceAccountSecret.setSecretKeyId(responseJson.get("secretKeyId").getAsString()); } if (responseJson.has("secretText")) { azureServiceAccountSecret.setSecretText(responseJson.get("secretText").getAsString()); } if (responseJson.has("expiryDateEpoch")) { azureServiceAccountSecret.setExpiryDateEpoch(responseJson.get("expiryDateEpoch").getAsLong()); } return azureServiceAccountSecret; } }
9,883
579
<filename>apps/modules/post/process/post_statistical.py #!/usr/bin/env python # -*-coding:utf-8-*- # @Time : 2017/11/1 ~ 2019/9/1 # @Author : <NAME> from bson import ObjectId from celery_once import QueueOnce from apps.app import mdbs, celery @celery.task(base=QueueOnce, once={'graceful': True}) def post_pv(post_id, sid): """ 记录post的访问量 :return: """ r = mdbs["web"].db.access_record.find_one({"post_id": post_id, "sids": sid}) if not r: mdbs["web"].db.access_record.update_one({"post_id": post_id}, {"$inc": {"pv": 1}, "$addToSet": {"sids": sid}}, upsert=True) mdbs["web"].db.post.update_one({"_id": ObjectId(post_id)}, {"$inc": {"pv": 1}}) else: if len(r["sids"]) > 1000: mdbs["web"].db.access_record.update_one({"post_id": post_id}, {"$set": {"sids": []}})
558
562
#include <iostream> #include <inja/inja.hpp> int main() { nlohmann::json data; data["name"] = "world"; std::cout << inja::render("Hello {{ name }}!", data) << "\n"; }
80
3,027
# A single source of truth for constant variables related to the exchange from hummingbot.core.api_throttler.data_types import RateLimit EXCHANGE_NAME = "bitmart" REST_URL = "https://api-cloud.bitmart.com" REST_URL_HK = "https://api-cloud.bitmart.news" WSS_URL = "wss://ws-manager-compress.bitmart.com?protocol=1.1" WSS_URL_HK = "wss://ws-manager-compress.bitmart.news?protocol=1.1" # REST API ENDPOINTS CHECK_NETWORK_PATH_URL = "system/service" GET_TRADING_PAIRS_PATH_URL = "spot/v1/symbols" GET_TRADING_RULES_PATH_URL = "spot/v1/symbols/details" GET_LAST_TRADING_PRICES_PATH_URL = "spot/v1/ticker" GET_ORDER_BOOK_PATH_URL = "spot/v1/symbols/book" CREATE_ORDER_PATH_URL = "spot/v1/submit_order" CANCEL_ORDER_PATH_URL = "spot/v2/cancel_order" GET_ACCOUNT_SUMMARY_PATH_URL = "spot/v1/wallet" GET_ORDER_DETAIL_PATH_URL = "spot/v1/order_detail" GET_TRADE_DETAIL_PATH_URL = "spot/v1/trades" GET_OPEN_ORDERS_PATH_URL = "spot/v1/orders" # WS API ENDPOINTS WS_CONNECT = "WSConnect" WS_SUBSCRIBE = "WSSubscribe" # BitMart has a per method API limit RATE_LIMITS = [ RateLimit(limit_id=CHECK_NETWORK_PATH_URL, limit=10, time_interval=1), RateLimit(limit_id=GET_TRADING_PAIRS_PATH_URL, limit=5, time_interval=1), RateLimit(limit_id=GET_TRADING_RULES_PATH_URL, limit=5, time_interval=1), RateLimit(limit_id=GET_LAST_TRADING_PRICES_PATH_URL, limit=5, time_interval=1), RateLimit(limit_id=GET_ORDER_BOOK_PATH_URL, limit=5, time_interval=1), RateLimit(limit_id=CREATE_ORDER_PATH_URL, limit=50, time_interval=1), RateLimit(limit_id=CANCEL_ORDER_PATH_URL, limit=50, time_interval=1), RateLimit(limit_id=GET_ACCOUNT_SUMMARY_PATH_URL, limit=10, time_interval=1), RateLimit(limit_id=GET_ORDER_DETAIL_PATH_URL, limit=50, time_interval=1), RateLimit(limit_id=GET_TRADE_DETAIL_PATH_URL, limit=10, time_interval=1), RateLimit(limit_id=GET_OPEN_ORDERS_PATH_URL, limit=10, time_interval=1), RateLimit(limit_id=WS_CONNECT, limit=1, time_interval=1), RateLimit(limit_id=WS_SUBSCRIBE, limit=60, time_interval=600), ] ORDER_STATUS = { 1: "FAILED", # Order failure 2: "OPEN", # Placing order 3: "REJECTED", # Order failure, Freeze failure 4: "ACTIVE", # Order success, Pending for fulfilment 5: "ACTIVE", # Partially filled 6: "FILLED", # Fully filled 7: "ACTIVE", # Canceling 8: "CANCELED", # Canceled 9: "ACTIVE", # Outstanding (4 and 5) 10: "COMPLETED" # 6 and 8 }
1,127
32,544
<filename>core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/variableandmethodhiding/variable/VariableHidingDemo.java<gh_stars>1000+ package com.baeldung.variableandmethodhiding.variable; /** * Created by Gebruiker on 5/6/2018. */ public class VariableHidingDemo { public static void main(String[] args) { HideVariable variable = new HideVariable(); variable.printLocalVariable(); variable.printInstanceVariable(); ParentVariable parentVariable = new ParentVariable(); ParentVariable childVariable = new ChildVariable(); parentVariable.printInstanceVariable(); childVariable.printInstanceVariable(); } }
232
2,406
<filename>model-optimizer/unit_tests/extensions/back/SpecialNodesFinalization_test.py # Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest import numpy as np from extensions.back.SpecialNodesFinalization import CreateConstNodesReplacement from mo.utils.ir_engine.compare_graphs import compare_graphs from unit_tests.utils.graph import build_graph_with_attrs class CreateConstNodesReplacementTest(unittest.TestCase): nodes = [ ('data_node', {'kind': 'data', 'shape': None, 'value': None}), ('next_node', {'kind': 'op'}), ] edges = [ ('data_node', 'next_node') ] new_nodes = [ ('const', {'kind': 'op', 'op': 'Const'}), ('const_data', {'kind': 'data'}) ] new_edges = [ ('const', 'data_node'), ('const_data', 'const') ] def test_one_node(self): """We should add Const node and data node.""" shape = np.array([2, 3, 4]) data = np.zeros(shape) graph = build_graph_with_attrs( nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[('data_node', {'shape': shape, 'value': data})] ) graph_ref = build_graph_with_attrs( nodes_with_attrs=self.nodes + self.new_nodes, edges_with_attrs=self.edges + self.new_edges, update_nodes_attributes=[('data_node', {'shape': shape, 'value': data}), ('const_data', {'shape': shape, 'value': data})] ) tested_pattern = CreateConstNodesReplacement() tested_pattern.find_and_replace_pattern(graph) (flag, resp) = compare_graphs(graph, graph_ref, last_node='next_node') self.assertTrue(flag, resp) def test_one_bin_node(self): """Nothing should happen.""" shape = np.array([2, 3, 4]) data = np.zeros(shape) graph = build_graph_with_attrs( nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[('data_node', {'shape': shape, 'value': data})], update_edge_attrs={('data_node', 'next_node', 0): {'bin': 0}}, ) tested_pattern = CreateConstNodesReplacement() tested_pattern.find_and_replace_pattern(graph) (flag, resp) = compare_graphs(graph, graph, last_node='next_node') self.assertTrue(flag, resp) def test_two_nodes_with_bin(self): """Test case for data node with 2 consumers with bin edge attr. Nothing should happened.""" shape = np.array([2, 3, 4]) data = np.zeros(shape) graph = build_graph_with_attrs( nodes_with_attrs=self.nodes + [('next_node_2', {'kind': 'op'})], edges_with_attrs=self.edges + [('data_node', 'next_node_2')], update_nodes_attributes=[('data_node', {'shape': shape, 'value': data})], update_edge_attrs={('data_node', 'next_node', 0): {'bin': 0}, ('data_node', 'next_node_2', 0): {'bin': 0}}, ) tested_pattern = CreateConstNodesReplacement() tested_pattern.find_and_replace_pattern(graph) (flag, resp) = compare_graphs(graph, graph, last_node='next_node') self.assertTrue(flag, resp) def test_two_nodes_one_bin(self): """Test case for two output nodes, one with 'bin' parameter, other without.""" shape = np.array([2, 3, 4]) data = np.zeros(shape) graph = build_graph_with_attrs( nodes_with_attrs=self.nodes + [('next_node_2', {'kind': 'op'})], edges_with_attrs=self.edges + [('data_node', 'next_node_2')], update_nodes_attributes=[('data_node', {'shape': shape, 'value': data})], update_edge_attrs={('data_node', 'next_node', 0): {'bin': 0}}, ) graph_ref = build_graph_with_attrs( nodes_with_attrs=self.nodes + self.new_nodes + [('next_node_2', {'kind': 'op'})], edges_with_attrs=self.edges + self.new_edges + [('data_node', 'next_node_2')], update_nodes_attributes=[('data_node', {'shape': shape, 'value': data}), ('const_data', {'shape': shape, 'value': data})] ) tested_pattern = CreateConstNodesReplacement() tested_pattern.find_and_replace_pattern(graph) (flag, resp) = compare_graphs(graph, graph_ref, last_node='next_node') self.assertTrue(flag, resp)
2,059
660
<filename>app/src/main/java/com/yan/refreshloadlayouttest/testactivity/ScrollingActivity.java package com.yan.refreshloadlayouttest.testactivity; import android.os.Bundle; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.core.content.ContextCompat; import androidx.appcompat.widget.Toolbar; import android.util.Log; import android.view.View; import com.yan.pullrefreshlayout.PRLCommonUtils; import com.yan.pullrefreshlayout.PullRefreshLayout; import com.yan.refreshloadlayouttest.R; import com.yan.refreshloadlayouttest.widget.house.StoreHouseHeader; import static com.yan.pullrefreshlayout.PRLCommonUtils.dipToPx; import java.util.ArrayList; public class ScrollingActivity extends BaseActivity { private static final String TAG = "NestedActivity"; private PullRefreshLayout refreshLayout; private AppBarLayout appBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scrolling); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); appBar = findViewById(R.id.app_bar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); initRecyclerView(); initRefreshLayout(); refreshLayout.postDelayed(new Runnable() { @Override public void run() { refreshLayout.autoRefresh(); } }, 150); } private void initRecyclerView() { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_data); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ArrayList<SimpleItem> datas = new ArrayList<>(); datas.add(new SimpleItem(R.drawable.img1, "夏目友人帐")); datas.add(new SimpleItem(R.drawable.img2, "夏目友人帐")); datas.add(new SimpleItem(R.drawable.img3, "夏目友人帐")); datas.add(new SimpleItem(R.drawable.img4, "夏目友人帐")); datas.add(new SimpleItem(R.drawable.img5, "夏目友人帐")); datas.add(new SimpleItem(R.drawable.img6, "夏目友人帐")); SimpleAdapter adapter = new SimpleAdapter(this, datas); recyclerView.setAdapter(adapter); recyclerView.setItemAnimator(new DefaultItemAnimator()); } private void initRefreshLayout() { this.refreshLayout = findViewById(R.id.refreshLayout); findViewById(R.id.container).setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimaryDark)); StoreHouseHeader header = new StoreHouseHeader(getBaseContext()); header.setPadding(0, dipToPx(getApplicationContext(), 20), 0, dipToPx(getApplicationContext(), 20)); header.initWithString("PullRefreshLayout"); refreshLayout.setHeaderView(header); this.refreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListenerAdapter() { @Override public void onRefresh() { Log.e(TAG, "refreshLayout onRefresh: "); ScrollingActivity.this.refreshLayout.postDelayed(new Runnable() { @Override public void run() { ScrollingActivity.this.refreshLayout.refreshComplete(); } }, 3000); } }); appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { appBarLayout.setTag(verticalOffset); } }); refreshLayout.setOnTargetScrollCheckListener(new PullRefreshLayout.OnTargetScrollCheckListener() { @Override public boolean onScrollUpAbleCheck() { int appbarOffset = ((appBar.getTag() instanceof Integer)) ? (int) appBar.getTag() : 0; return PRLCommonUtils.canChildScrollUp(refreshLayout.getTargetView()) || appbarOffset != 0; } @Override public boolean onScrollDownAbleCheck() { return PRLCommonUtils.canChildScrollDown(refreshLayout.getTargetView()); } }); } }
2,000
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Cheptainville","circ":"3ème circonscription","dpt":"Essonne","inscrits":1368,"abs":706,"votants":662,"blancs":44,"nuls":19,"exp":599,"res":[{"nuance":"REM","nom":"<NAME>","voix":332},{"nuance":"FI","nom":"<NAME>","voix":267}]}
110
1,863
<reponame>gongyiling/PhysX-3.4 // // 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 NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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. // // Copyright (c) 2018 NVIDIA Corporation. All rights reserved. // This file was generated by NvParameterized/scripts/GenParameterized.pl #include "DestructibleActorChunks_0p0.h" #include <string.h> #include <stdlib.h> using namespace NvParameterized; namespace nvidia { namespace parameterized { using namespace DestructibleActorChunks_0p0NS; const char* const DestructibleActorChunks_0p0Factory::vptr = NvParameterized::getVptr<DestructibleActorChunks_0p0, DestructibleActorChunks_0p0::ClassAlignment>(); const uint32_t NumParamDefs = 14; static NvParameterized::DefinitionImpl* ParamDefTable; // now allocated in buildTree [NumParamDefs]; static const size_t ParamLookupChildrenTable[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, }; #define TENUM(type) nvidia::##type #define CHILDREN(index) &ParamLookupChildrenTable[index] static const NvParameterized::ParamLookupNode ParamLookupTable[NumParamDefs] = { { TYPE_STRUCT, false, 0, CHILDREN(0), 1 }, { TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->data), CHILDREN(1), 1 }, // data { TYPE_STRUCT, false, 1 * sizeof(Chunk_Type), CHILDREN(2), 11 }, // data[] { TYPE_U8, false, (size_t)(&((Chunk_Type*)0)->state), NULL, 0 }, // data[].state { TYPE_U8, false, (size_t)(&((Chunk_Type*)0)->flags), NULL, 0 }, // data[].flags { TYPE_U32, false, (size_t)(&((Chunk_Type*)0)->islandID), NULL, 0 }, // data[].islandID { TYPE_F32, false, (size_t)(&((Chunk_Type*)0)->damage), NULL, 0 }, // data[].damage { TYPE_VEC4, false, (size_t)(&((Chunk_Type*)0)->localSphere), NULL, 0 }, // data[].localSphere { TYPE_VEC3, false, (size_t)(&((Chunk_Type*)0)->localOffset), NULL, 0 }, // data[].localOffset { TYPE_I32, false, (size_t)(&((Chunk_Type*)0)->visibleAncestorIndex), NULL, 0 }, // data[].visibleAncestorIndex { TYPE_U32, false, (size_t)(&((Chunk_Type*)0)->shapesCount), NULL, 0 }, // data[].shapesCount { TYPE_TRANSFORM, false, (size_t)(&((Chunk_Type*)0)->globalPose), NULL, 0 }, // data[].globalPose { TYPE_VEC3, false, (size_t)(&((Chunk_Type*)0)->linearVelocity), NULL, 0 }, // data[].linearVelocity { TYPE_VEC3, false, (size_t)(&((Chunk_Type*)0)->angularVelocity), NULL, 0 }, // data[].angularVelocity }; bool DestructibleActorChunks_0p0::mBuiltFlag = false; NvParameterized::MutexType DestructibleActorChunks_0p0::mBuiltFlagMutex; DestructibleActorChunks_0p0::DestructibleActorChunks_0p0(NvParameterized::Traits* traits, void* buf, int32_t* refCount) : NvParameters(traits, buf, refCount) { //mParameterizedTraits->registerFactory(className(), &DestructibleActorChunks_0p0FactoryInst); if (!buf) //Do not init data if it is inplace-deserialized { initDynamicArrays(); initStrings(); initReferences(); initDefaults(); } } DestructibleActorChunks_0p0::~DestructibleActorChunks_0p0() { freeStrings(); freeReferences(); freeDynamicArrays(); } void DestructibleActorChunks_0p0::destroy() { // We cache these fields here to avoid overwrite in destructor bool doDeallocateSelf = mDoDeallocateSelf; NvParameterized::Traits* traits = mParameterizedTraits; int32_t* refCount = mRefCount; void* buf = mBuffer; this->~DestructibleActorChunks_0p0(); NvParameters::destroy(this, traits, doDeallocateSelf, refCount, buf); } const NvParameterized::DefinitionImpl* DestructibleActorChunks_0p0::getParameterDefinitionTree(void) { if (!mBuiltFlag) // Double-checked lock { NvParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex); if (!mBuiltFlag) { buildTree(); } } return(&ParamDefTable[0]); } const NvParameterized::DefinitionImpl* DestructibleActorChunks_0p0::getParameterDefinitionTree(void) const { DestructibleActorChunks_0p0* tmpParam = const_cast<DestructibleActorChunks_0p0*>(this); if (!mBuiltFlag) // Double-checked lock { NvParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex); if (!mBuiltFlag) { tmpParam->buildTree(); } } return(&ParamDefTable[0]); } NvParameterized::ErrorType DestructibleActorChunks_0p0::getParameterHandle(const char* long_name, Handle& handle) const { ErrorType Ret = NvParameters::getParameterHandle(long_name, handle); if (Ret != ERROR_NONE) { return(Ret); } size_t offset; void* ptr; getVarPtr(handle, ptr, offset); if (ptr == NULL) { return(ERROR_INDEX_OUT_OF_RANGE); } return(ERROR_NONE); } NvParameterized::ErrorType DestructibleActorChunks_0p0::getParameterHandle(const char* long_name, Handle& handle) { ErrorType Ret = NvParameters::getParameterHandle(long_name, handle); if (Ret != ERROR_NONE) { return(Ret); } size_t offset; void* ptr; getVarPtr(handle, ptr, offset); if (ptr == NULL) { return(ERROR_INDEX_OUT_OF_RANGE); } return(ERROR_NONE); } void DestructibleActorChunks_0p0::getVarPtr(const Handle& handle, void*& ptr, size_t& offset) const { ptr = getVarPtrHelper(&ParamLookupTable[0], const_cast<DestructibleActorChunks_0p0::ParametersStruct*>(&parameters()), handle, offset); } /* Dynamic Handle Indices */ void DestructibleActorChunks_0p0::freeParameterDefinitionTable(NvParameterized::Traits* traits) { if (!traits) { return; } if (!mBuiltFlag) // Double-checked lock { return; } NvParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex); if (!mBuiltFlag) { return; } for (uint32_t i = 0; i < NumParamDefs; ++i) { ParamDefTable[i].~DefinitionImpl(); } traits->free(ParamDefTable); mBuiltFlag = false; } #define PDEF_PTR(index) (&ParamDefTable[index]) void DestructibleActorChunks_0p0::buildTree(void) { uint32_t allocSize = sizeof(NvParameterized::DefinitionImpl) * NumParamDefs; ParamDefTable = (NvParameterized::DefinitionImpl*)(mParameterizedTraits->alloc(allocSize)); memset(ParamDefTable, 0, allocSize); for (uint32_t i = 0; i < NumParamDefs; ++i) { NV_PARAM_PLACEMENT_NEW(ParamDefTable + i, NvParameterized::DefinitionImpl)(*mParameterizedTraits); } // Initialize DefinitionImpl node: nodeIndex=0, longName="" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[0]; ParamDef->init("", TYPE_STRUCT, "STRUCT", true); } // Initialize DefinitionImpl node: nodeIndex=1, longName="data" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[1]; ParamDef->init("data", TYPE_ARRAY, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS static HintImpl HintTable[1]; static Hint* HintPtrTable[1] = { &HintTable[0], }; HintTable[0].init("INCLUDED", uint64_t(1), true); ParamDefTable[1].setHints((const NvParameterized::Hint**)HintPtrTable, 1); #else static HintImpl HintTable[3]; static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], }; HintTable[0].init("INCLUDED", uint64_t(1), true); HintTable[1].init("longDescription", "The actor's chunk data.", true); HintTable[2].init("shortDescription", "The actor's chunk data", true); ParamDefTable[1].setHints((const NvParameterized::Hint**)HintPtrTable, 3); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ ParamDef->setArraySize(-1); } // Initialize DefinitionImpl node: nodeIndex=2, longName="data[]" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[2]; ParamDef->init("data", TYPE_STRUCT, "Chunk", true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS static HintImpl HintTable[1]; static Hint* HintPtrTable[1] = { &HintTable[0], }; HintTable[0].init("INCLUDED", uint64_t(1), true); ParamDefTable[2].setHints((const NvParameterized::Hint**)HintPtrTable, 1); #else static HintImpl HintTable[3]; static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], }; HintTable[0].init("INCLUDED", uint64_t(1), true); HintTable[1].init("longDescription", "The actor's chunk data.", true); HintTable[2].init("shortDescription", "The actor's chunk data", true); ParamDefTable[2].setHints((const NvParameterized::Hint**)HintPtrTable, 3); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=3, longName="data[].state" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[3]; ParamDef->init("state", TYPE_U8, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Bit flags indicating the state of the chunk.", true); HintTable[1].init("shortDescription", "Bit flags indicating the state of the chunk", true); ParamDefTable[3].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=4, longName="data[].flags" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[4]; ParamDef->init("flags", TYPE_U8, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Overall chunk flags.", true); HintTable[1].init("shortDescription", "Overall chunk flags", true); ParamDefTable[4].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=5, longName="data[].islandID" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[5]; ParamDef->init("islandID", TYPE_U32, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Island ID (if any) to which the chunk is attached.", true); HintTable[1].init("shortDescription", "Island ID (if any) to which the chunk is attached", true); ParamDefTable[5].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=6, longName="data[].damage" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[6]; ParamDef->init("damage", TYPE_F32, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "How damaged the chunk is.", true); HintTable[1].init("shortDescription", "How damaged the chunk is", true); ParamDefTable[6].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=7, longName="data[].localSphere" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[7]; ParamDef->init("localSphere", TYPE_VEC4, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "A local bounding sphere for the chunk.", true); HintTable[1].init("shortDescription", "A local bounding sphere for the chunk", true); ParamDefTable[7].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=8, longName="data[].localOffset" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[8]; ParamDef->init("localOffset", TYPE_VEC3, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "A local bounding sphere for the chunk.", true); HintTable[1].init("shortDescription", "A local bounding sphere for the chunk", true); ParamDefTable[8].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=9, longName="data[].visibleAncestorIndex" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[9]; ParamDef->init("visibleAncestorIndex", TYPE_I32, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Index (in structure) of this chunks' visible ancestor, if any. If none exists, it's InvalidChunkIndex.", true); HintTable[1].init("shortDescription", "Index (in structure) of this chunks' visible ancestor, if any", true); ParamDefTable[9].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=10, longName="data[].shapesCount" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[10]; ParamDef->init("shapesCount", TYPE_U32, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Number of shapes for this chunk.", true); HintTable[1].init("shortDescription", "Number of shapes for this chunk", true); ParamDefTable[10].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=11, longName="data[].globalPose" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[11]; ParamDef->init("globalPose", TYPE_TRANSFORM, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Chunk global transform.", true); HintTable[1].init("shortDescription", "Chunk global transform", true); ParamDefTable[11].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=12, longName="data[].linearVelocity" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[12]; ParamDef->init("linearVelocity", TYPE_VEC3, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Chunk linear velocity.", true); HintTable[1].init("shortDescription", "Chunk linear velocity", true); ParamDefTable[12].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // Initialize DefinitionImpl node: nodeIndex=13, longName="data[].angularVelocity" { NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[13]; ParamDef->init("angularVelocity", TYPE_VEC3, NULL, true); #ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS #else static HintImpl HintTable[2]; static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], }; HintTable[0].init("longDescription", "Chunk angular velocity.", true); HintTable[1].init("shortDescription", "Chunk angular velocity", true); ParamDefTable[13].setHints((const NvParameterized::Hint**)HintPtrTable, 2); #endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */ } // SetChildren for: nodeIndex=0, longName="" { static Definition* Children[1]; Children[0] = PDEF_PTR(1); ParamDefTable[0].setChildren(Children, 1); } // SetChildren for: nodeIndex=1, longName="data" { static Definition* Children[1]; Children[0] = PDEF_PTR(2); ParamDefTable[1].setChildren(Children, 1); } // SetChildren for: nodeIndex=2, longName="data[]" { static Definition* Children[11]; Children[0] = PDEF_PTR(3); Children[1] = PDEF_PTR(4); Children[2] = PDEF_PTR(5); Children[3] = PDEF_PTR(6); Children[4] = PDEF_PTR(7); Children[5] = PDEF_PTR(8); Children[6] = PDEF_PTR(9); Children[7] = PDEF_PTR(10); Children[8] = PDEF_PTR(11); Children[9] = PDEF_PTR(12); Children[10] = PDEF_PTR(13); ParamDefTable[2].setChildren(Children, 11); } mBuiltFlag = true; } void DestructibleActorChunks_0p0::initStrings(void) { } void DestructibleActorChunks_0p0::initDynamicArrays(void) { data.buf = NULL; data.isAllocated = true; data.elementSize = sizeof(Chunk_Type); data.arraySizes[0] = 0; } void DestructibleActorChunks_0p0::initDefaults(void) { freeStrings(); freeReferences(); freeDynamicArrays(); initDynamicArrays(); initStrings(); initReferences(); } void DestructibleActorChunks_0p0::initReferences(void) { } void DestructibleActorChunks_0p0::freeDynamicArrays(void) { if (data.isAllocated && data.buf) { mParameterizedTraits->free(data.buf); } } void DestructibleActorChunks_0p0::freeStrings(void) { } void DestructibleActorChunks_0p0::freeReferences(void) { } } // namespace parameterized } // namespace nvidia
6,777
356
{ "cve": [], "vulnerable": "6.x || 5.x || 4.x", "patched": "^6.2.1 || ^4.5.0", "description": "Ignore negative lengths in calls to `Buffer()` and `Buffer.allocUnsafe()`.", "ref": "https://github.com/nodejs/node/issues/7047#issuecomment-222393982", "overview": "This fixes a possible security concern (reported by <NAME>) where\nuser input is passed unchecked to the Buffer constructor or `allocUnsafe()` as\nit can expose parts of the memory slab used by other Buffers in the application.\nNote that negative lengths are not supported by the Buffer API and user input to\nthe constructor should always be sanitised and type-checked.\n\n" }
203
1,694
<filename>header6.6.1/GetLastestExpressInfoRequest.h // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <MMCommon/WXPBGeneratedMessage.h> @class Address, BaseRequest, NSString; @interface GetLastestExpressInfoRequest : WXPBGeneratedMessage { } + (void)initialize; // Remaining properties @property(retain, nonatomic) Address *address; // @dynamic address; @property(retain, nonatomic) BaseRequest *baseRequest; // @dynamic baseRequest; @property(retain, nonatomic) NSString *lockId; // @dynamic lockId; @property(retain, nonatomic) NSString *productId; // @dynamic productId; @end
244
575
<gh_stars>100-1000 // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/ambient/model/ambient_backend_model.h" #include <memory> #include <string> #include "ash/ambient/model/ambient_backend_model_observer.h" #include "ash/public/cpp/ambient/ambient_prefs.h" #include "ash/public/cpp/ambient/ambient_ui_model.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/scoped_observation.h" #include "testing/gmock/include/gmock/gmock.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_unittest_util.h" #include "ui/views/controls/image_view.h" #define EXPECT_NO_CALLS(args...) EXPECT_CALL(args).Times(0); namespace ash { namespace { class MockAmbientBackendModelObserver : public AmbientBackendModelObserver { public: MockAmbientBackendModelObserver() = default; ~MockAmbientBackendModelObserver() override = default; MOCK_METHOD(void, OnImagesFailed, (), (override)); MOCK_METHOD(void, OnImagesReady, (), (override)); MOCK_METHOD(void, OnImageAdded, (), (override)); }; } // namespace class AmbientBackendModelTest : public AshTestBase { public: AmbientBackendModelTest() = default; AmbientBackendModelTest(const AmbientBackendModelTest&) = delete; AmbientBackendModelTest& operator=(AmbientBackendModelTest&) = delete; ~AmbientBackendModelTest() override = default; void SetUp() override { AshTestBase::SetUp(); ambient_backend_model_ = std::make_unique<AmbientBackendModel>(); } void TearDown() override { ambient_backend_model_.reset(); AshTestBase::TearDown(); } // Adds n test images to the model. void AddNTestImages(int n) { while (n > 0) { PhotoWithDetails test_detailed_image; test_detailed_image.photo = gfx::test::CreateImageSkia(/*width=*/10, /*height=*/10); test_detailed_image.details = std::string("fake-photo-attribution"); ambient_backend_model()->AddNextImage(std::move(test_detailed_image)); n--; } } // Returns whether the image and its details are equivalent to the test // detailed image. bool EqualsToTestImage(const PhotoWithDetails& detailed_image) { gfx::ImageSkia test_image = gfx::test::CreateImageSkia(/*width=*/10, /*height=*/10); return !detailed_image.IsNull() && gfx::test::AreBitmapsEqual(*(detailed_image.photo).bitmap(), *test_image.bitmap()) && (detailed_image.details == std::string("fake-photo-attribution")); } // Returns whether the image is null. bool IsNullImage(const gfx::ImageSkia& image) { return image.isNull(); } base::TimeDelta GetPhotoRefreshInterval() const { return ambient_backend_model()->GetPhotoRefreshInterval(); } void SetPhotoRefreshInterval(const base::TimeDelta& interval) { PrefService* prefs = Shell::Get()->session_controller()->GetPrimaryUserPrefService(); prefs->SetInteger(ambient::prefs::kAmbientModePhotoRefreshIntervalSeconds, interval.InSeconds()); } AmbientBackendModel* ambient_backend_model() const { return ambient_backend_model_.get(); } PhotoWithDetails GetNextImage() { return ambient_backend_model_->GetNextImage(); } PhotoWithDetails GetCurrentImage() { return ambient_backend_model_->GetCurrentImage(); } int failure_count() { return ambient_backend_model_->failures_; } private: std::unique_ptr<AmbientBackendModel> ambient_backend_model_; }; // Test adding the first image. TEST_F(AmbientBackendModelTest, AddFirstImage) { AddNTestImages(1); EXPECT_TRUE(EqualsToTestImage(GetCurrentImage())); EXPECT_TRUE(GetNextImage().IsNull()); } // Test adding the second image. TEST_F(AmbientBackendModelTest, AddSecondImage) { AddNTestImages(1); EXPECT_TRUE(EqualsToTestImage(GetCurrentImage())); EXPECT_TRUE(GetNextImage().IsNull()); AddNTestImages(1); EXPECT_TRUE(EqualsToTestImage(GetNextImage())); } // Test the photo refresh interval is expected. TEST_F(AmbientBackendModelTest, ShouldReturnExpectedPhotoRefreshInterval) { // Should fetch image immediately. EXPECT_EQ(GetPhotoRefreshInterval(), base::TimeDelta()); AddNTestImages(1); // Should fetch image immediately. EXPECT_EQ(GetPhotoRefreshInterval(), base::TimeDelta()); AddNTestImages(1); // Has enough images. Will fetch more image at the |photo_refresh_interval_|, // which is |kPhotoRefreshInterval| by default. EXPECT_EQ(GetPhotoRefreshInterval(), kPhotoRefreshInterval); // Change the photo refresh interval. const base::TimeDelta interval = base::TimeDelta::FromMinutes(1); SetPhotoRefreshInterval(interval); // The refresh interval will be the set value. EXPECT_EQ(GetPhotoRefreshInterval(), interval); } TEST_F(AmbientBackendModelTest, ShouldNotifyObserversIfImagesFailed) { ambient_backend_model()->Clear(); testing::NiceMock<MockAmbientBackendModelObserver> observer; base::ScopedObservation<AmbientBackendModel, AmbientBackendModelObserver> scoped_obs{&observer}; scoped_obs.Observe(ambient_backend_model()); EXPECT_CALL(observer, OnImagesFailed).Times(1); for (int i = 0; i < kMaxConsecutiveReadPhotoFailures; i++) { ambient_backend_model()->AddImageFailure(); } } TEST_F(AmbientBackendModelTest, ShouldResetFailuresOnAddImage) { testing::NiceMock<MockAmbientBackendModelObserver> observer; base::ScopedObservation<AmbientBackendModel, AmbientBackendModelObserver> scoped_obs{&observer}; scoped_obs.Observe(ambient_backend_model()); EXPECT_NO_CALLS(observer, OnImagesFailed); for (int i = 0; i < kMaxConsecutiveReadPhotoFailures - 1; i++) { ambient_backend_model()->AddImageFailure(); } EXPECT_EQ(failure_count(), kMaxConsecutiveReadPhotoFailures - 1); AddNTestImages(1); EXPECT_EQ(failure_count(), 0); } TEST_F(AmbientBackendModelTest, ShouldNotifyObserversOnImagesReady) { testing::NiceMock<MockAmbientBackendModelObserver> observer; base::ScopedObservation<AmbientBackendModel, AmbientBackendModelObserver> scoped_obs{&observer}; scoped_obs.Observe(ambient_backend_model()); EXPECT_CALL(observer, OnImageAdded).Times(1); EXPECT_NO_CALLS(observer, OnImagesReady); AddNTestImages(1); EXPECT_CALL(observer, OnImageAdded).Times(1); EXPECT_CALL(observer, OnImagesReady).Times(1); AddNTestImages(1); } TEST_F(AmbientBackendModelTest, ShouldNotifyObserversOnImageAdded) { testing::NiceMock<MockAmbientBackendModelObserver> observer; base::ScopedObservation<AmbientBackendModel, AmbientBackendModelObserver> scoped_obs{&observer}; scoped_obs.Observe(ambient_backend_model()); EXPECT_CALL(observer, OnImagesReady).Times(1); EXPECT_CALL(observer, OnImageAdded).Times(2); AddNTestImages(2); EXPECT_CALL(observer, OnImageAdded).Times(3); AddNTestImages(3); } } // namespace ash
2,511
1,645
import pprint import argparse import os import json import sys import errno import copy import shutil from subprocess import call import zk_utils gdata = { 'all_clients_node_path': "/all_clients", } def pp(o): p = pprint.PrettyPrinter(indent=4) p.pprint(o) def getOpts(args): parser = argparse.ArgumentParser(prog='seldon-cli rpc', description='Seldon Cli') parser.add_argument('--action', help="the action to use", required=False, choices=['show','set', 'remove']) parser.add_argument('--client-name', help="the name of the client", required=True) parser.add_argument('--proto', help="the proto buffer file with request and optional reply class", required=False) parser.add_argument('--request-class', help="the request class", required=False) parser.add_argument('--reply-class', help="the reply class", required=False) parser.add_argument('args', nargs=argparse.REMAINDER) # catch rest (non-options) as args opts = parser.parse_args(args) return opts def remove_path(path): shutil.rmtree(path) def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def json_to_dict(json_data): return json.loads(json_data) def dict_to_json(d, expand=False): return json.dumps(d, sort_keys=True, indent=4, separators=(',', ': ')) if expand else json.dumps(d, sort_keys=True, separators=(',',':')) def write_data_to_file(data_fpath, data): json = dict_to_json(data, True) mkdir_p(os.path.dirname(data_fpath)) f = open(data_fpath,'w') f.write(json) f.write('\n') f.close() print "Writing data to file[{data_fpath}]".format(**locals()) def is_existing_client(zkroot, client_name): client_names = os.listdir(zkroot + gdata["all_clients_node_path"]) if client_name in client_names: return True else: return False def show_rpc(data): json = dict_to_json(data, True) print json def action_show(command_data, opts): client_name = opts.client_name if client_name == None: print "Need client name to show the rpc settings for" sys.exit(1) zkroot = command_data["zkdetails"]["zkroot"] if not is_existing_client(zkroot, client_name): print "Invalid client[{client_name}]".format(**locals()) sys.exit(1) data_fpath = zkroot + gdata["all_clients_node_path"] + "/" + client_name + "/rpc/_data_" if os.path.isfile(data_fpath): f = open(data_fpath) json = f.read() f.close() data = json_to_dict(json) show_rpc(data) else: print "Unable to show rpc definition for client[{client_name}]".format(**locals()) def create_jar(grpc_home,proto_file,jar_file): cmd = grpc_home+"/create-proto-jar.sh "+proto_file+" "+jar_file print "Creating jar file from proto file. This may take some time..." sys.stdout.flush() return call(cmd, shell=True) def action_set(command_data, opts): if "grpc_util_home" in command_data["conf_data"]: grpc_home = command_data["conf_data"]["grpc_util_home"] else: print "Need the location for grpc_util_home to create proto jar via maven" sys.exit(1) client_name = opts.client_name if client_name == None: print "Need client name to show the rpc settings for" sys.exit(1) proto_file = opts.proto if proto_file == None: print "Need --proto argument" sys.exit(1) request_class = opts.request_class if request_class == None: print "Need request class to setup!" sys.exit(1) jar_file = "/seldon-data/rpc/jar/"+client_name+".jar" if not create_jar(grpc_home,opts.proto,jar_file) == 0: print "Failed to create jar file from proto" sys.exit(1) zkroot = command_data["zkdetails"]["zkroot"] zk_client = command_data["zkdetails"]["zk_client"] if opts.reply_class == None: data = {"jarFilename":jar_file,"requestClassName":opts.request_class} else: data = {"jarFilename":jar_file,"requestClassName":opts.request_class,"replyClassName":opts.reply_class} data_fpath = zkroot + gdata["all_clients_node_path"] + "/" + client_name + "/rpc/_data_" node_path = gdata["all_clients_node_path"] + "/" + client_name + "/rpc" write_data_to_file(data_fpath, data) f = open(data_fpath) data_json = f.read() f.close() zk_client=command_data["zkdetails"]["zk_client"] zk_utils.node_set(zk_client, node_path, data_json) def action_remove(command_data, opts): client_name = opts.client_name if client_name == None: print "Need client name to show the rpc settings for" sys.exit(1) zkroot = command_data["zkdetails"]["zkroot"] zk_client = command_data["zkdetails"]["zk_client"] data_fpath = zkroot + gdata["all_clients_node_path"] + "/" + client_name + "/rpc" node_path = gdata["all_clients_node_path"] + "/" + client_name + "/rpc" zk_utils.node_delete(zk_client,node_path) remove_path(data_fpath) def cmd_rpc(gopts,command_data, command_args): actions = { "default" : action_show, "show" : action_show, "set" : action_set, "remove" : action_remove } opts = getOpts(command_args) action = opts.action if action == None: actions["default"](command_data, opts) else: if actions.has_key(action): actions[action](command_data, opts) else: print "Invalid action[{}]".format(action)
2,371
14,668
<reponame>meyerweb/wpt<gh_stars>1000+ # This file needs to be a sibling of the test files (and not under resources/) # so that base URL resolution is the same between those test files and <script>s # pointing to this file. from wptserve.utils import isomorphic_decode def main(request, response): return ( ((b'Content-Type', b'text/javascript'),), u'import "{}";\n'.format(isomorphic_decode(request.GET.first(b'url'))) )
156
486
<reponame>AnveshAeturi/deep-learning-workshop<filename>notebooks/models/rl-bubble-breaker.py import numpy as np import theano #import theano.tensor as T #theano.config.optimizer='fast_compile' #theano.config.optimizer='None' import lasagne import pickle from game import crush def make_features_variable_size(board): features = [] #shifted_up = np.pad(board, ((0,0),(1,0)), mode='constant')[:,:-1] #print(shifted_up) #print("Board mask") mask = np.greater( board[:, :], 0 ) #print(mask * 1) features.append( mask.reshape((-1,)) ) # This works out whether each cell is the same as the cell 'above it' for shift_up in [1,2,3,]: #print("\n'UP' by %d:" % (shift_up,)) # Actually, no need for np.pad, just choose the views appropriately sameness = np.equal( board[:, :-shift_up], board[:, shift_up:] ) #print(sameness * 1) mask = np.greater( board[:, :-shift_up], 0 ) #print(mask * 1) #print(np.logical_and(sameness, mask) * 1) features.append( np.logical_and(sameness, mask).reshape((-1,)) ) #shifted_left = np.pad(board, ((1,0),(0,0)), mode='constant')[:-2,:] #print(shifted_left) # This works out whether each cell is the same as the cell in to columns 'to the left of it' for shift_left in [1,2,]: #print("\n'LEFT' by %d:" % (shift_left,)) sameness = np.equal( board[:-shift_left, :], board[shift_left:, :] ) #print(sameness * 1) mask = np.greater( board[:-shift_left, :], 0 ) #print(mask * 1) #print(np.logical_and(sameness, mask) * 1) features.append( np.logical_and(sameness, mask).reshape((-1,)) ) #return board.reshape((-1,)) return np.concatenate(features) def make_features_in_layers(board): feature_layers = [] # These are effectively 'colours' for the CNN #print(board) #print("Board mask") mask = np.greater( board[:, :], 0 )*1. feature_layers.append( mask.astype('float32') ) # This works out whether each cell is the same as the cell 'above it' for shift_down in [1,2,3,4,5,]: #print("\n'DOWN' by %d:" % (shift_down,)) sameness = np.zeros_like(board, dtype='float32') sameness[:,:-shift_down] = np.equal( board[:, :-shift_down], board[:, shift_down:] )*1. #print(sameness) feature_layers.append( sameness ) # This works out whether each cell is the same as the cell in to columns 'to the left of it' for shift_right in [1,2,3,]: #print("\n'RIGHT' by %d:" % (shift_right,)) sameness = np.zeros_like(board, dtype='float32') sameness[:-shift_right,:] = np.equal( board[:-shift_right, :], board[shift_right:, :] )*1. #print(sameness) feature_layers.append( sameness ) stacked = np.dstack( feature_layers ) return np.rollaxis( stacked, 2, 0 ) #width, height, n_colours = 10,14,5 width, height, n_colours = 5,8,4 # Create a board for initial sizing only board_temp = crush.new_board(width, height, n_colours) # Same as portrait phone 1 screen~1k, high-score~14k #features_shape = make_features_variable_size(board_temp).shape features_shape = make_features_in_layers(board_temp).shape print( features_shape ) #exit(0) # Now, create a simple ?fully-connected? network (MNIST-like sizing) # See : https://github.com/Lasagne/Lasagne/blob/master/examples/mnist.py # Does it make sense to do dropout? Perhaps learn over a batch a few times to 'average out' a little? def build_cnn(input_var, features_shape): # Create a CNN of two convolution layers and a fully-connected hidden layer in front of the output layer lasagne.random.set_rng( np.random ) # np.random.RandomState.get_state() # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, features_shape[0], features_shape[1], features_shape[2]), input_var=input_var) # No input dropout, as it tends to work less well for convolutional layers. # Strided and padded convolutions are supported as well; see the docstring. network = lasagne.layers.Conv2DLayer( network, num_filters=32, filter_size=(3,3), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform(), ) # Max-pooling layer of factor 2 in both dimensions: #network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) network = lasagne.layers.Conv2DLayer( network, num_filters=16, filter_size=(3,3), nonlinearity=lasagne.nonlinearities.rectify, ) #network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 64 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( #lasagne.layers.dropout(network, p=.5), # In big 'working' run, this dropout was enabled network, num_units=32, nonlinearity=lasagne.nonlinearities.rectify, ) # And, finally, the output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( #lasagne.layers.dropout(network, p=.5), network, num_units=1, nonlinearity=lasagne.nonlinearities.linear, # Actually, expected score cannot be negative, but why exclude learning on one-half of plane? ) return network # If there are no actions possible Q(board)=0 # Otherwise, at random (for a given percentage tending to chose (a) more and more of the time) : # (a) train it to be Q(board) = R(realized,action*) + lambda*Q(realized_board, action*) # action* is chosen to maximise Q(state_after_action, action) # ( small wrinkle is that Q(next_state) may include unknown column(s) if there has been a column clearance move) # (b) chose action* at random (or based on some novelty measure, for instance) # Also, if columns are added, can train Q(realized_board) = Q(state_after_action, action*) # so that projected boards converge to realized boards when there is a (random) extra column added # One question is whether we learn purely on-line, or in batches # and if in batches, how do we store it up? # Most of representation stays constant across turns (intuitively), so the data is quite 'correlated' # OTOH, the overall position changes much quicker than (say) chess, so perhaps it isn't too bad # That being said, it's not changing as quickly as the pole balancing state-space, for instance # Perhaps just set a batchsize, and accumulate game states until it's full, then do backprop pass(es) # In which case, need a 'play game in a loop' function # accumulate stats too # save state every 'n' batches # Alternatively : Play 1 game until the end (yielding training examples as we go) # This returns both stats for the game played and new board positions / rewards to learn from def play_game(game_id, model, per_step_discount_factor=0.95, prob_exploration=0.1): training_data = dict( board=[], target=[]) np.random.seed(game_id) board = crush.new_board(width, height, n_colours) # Same as portrait phone 1 screen~1k, high-score~14k score_total, new_cols_total, moves_total, game_step = 0,0,0,0 while True: moves = crush.potential_moves(board) moves_total += len(moves) if len(moves)==0: # Need to add a training example : This is a zero-score outcome training_data['board'].append( make_features_in_layers(board) ) training_data['target'].append( 0. ) break # Let's find the highest-scoring of those moves: First, get all the features next_step_features = [] next_step_target = [] for (h,v) in moves: # [0:2] b, score, n_cols = crush.after_move(board, h,v, -1) # Added columns are unknown next_step_features.append( make_features_in_layers(b) ) #next_step_target.append( score ) next_step_target.append( n_cols ) # Now evaluate the Q() values of the resulting postion for each possible move in one go all_features = np.array(next_step_features) # , dtype='float32' #print("all_features.shape", all_features.shape) remember_training, i = False, -1 if prob_exploration<0: # This is testing only - just need to pick the best move next_step_q = model_evaluate_features_deterministic( all_features ) else: if np.random.uniform(0.0, 1.0)<prob_exploration: ## Choose a random move, and do it i = np.random.randint( len(moves) ) else: next_step_q = model_evaluate_features( all_features ) remember_training=True if i<0: next_step_aggregate = np.array( next_step_target, dtype='float32') + per_step_discount_factor * next_step_q.flatten() #print( next_step_aggregate ) i = np.argmax( next_step_aggregate ) (h,v) = moves[i] #print("Move : (%2d,%2d)" % (h,v)) #crush.show_board(board, highlight=(h,v)) if remember_training: # Only collect training data if not testing training_data['board'].append( make_features_in_layers(board) ) training_data['target'].append( next_step_aggregate[i] ) # This value includes a Q() that looks at the 'blank cols', rather than the actuals board, score, new_cols = crush.after_move(board, h,v, n_colours) # Now we do the move 'for real' score_total += score new_cols_total += new_cols #print("Move[%2d]=(%2d,%2d) -> Score : %3d, new_cols=%1d" % (i, h,v, score,new_cols)) #crush.show_board(board, highlight=(0,0)) game_step += 1 stats=dict( steps=game_step, av_potential_moves=float(moves_total) / game_step, score=score_total, new_cols=new_cols_total ) return stats, training_data board_input = theano.tensor.tensor4('inputs') board_score = theano.tensor.vector('targets') np.random.seed(0) # This is for the initialisation inside the CNN model=build_cnn(board_input, features_shape) # This is for running the model (training, etc) estimate_q_value = lasagne.layers.get_output(model) # 'running' model_evaluate_features = theano.function([board_input], estimate_q_value) # This is for repeatedly testing the model (deterministic) predict_q_value = lasagne.layers.get_output(model, deterministic=True) model_evaluate_features_deterministic = theano.function([board_input], predict_q_value) # This is used for training model_squared_error = lasagne.objectives.squared_error(estimate_q_value.reshape( (-1,) ), board_score).mean() model_params = lasagne.layers.get_all_params(model, trainable=True) #model_updates = lasagne.updates.nesterov_momentum( model_squared_error, model_params, learning_rate=0.01, momentum=0.9 ) model_updates = lasagne.updates.adam( model_squared_error, model_params ) #model_updates = lasagne.updates.rmsprop( model_squared_error, model_params ) # Seems much slower to converge model_train = theano.function([board_input, board_score], model_squared_error, updates=model_updates) def stats_aggregates(log, prefix, last=None): stats_cols = "steps av_potential_moves new_cols score model_err".split() if last: stats_overall = np.array([ [s[c] for c in stats_cols] for s in log[-last:] ]) else: stats_overall = np.array([ [s[c] for c in stats_cols] for s in log ]) print(prefix+" Min : ", zip(stats_cols, ["%6.1f" % (v,) for v in np.min(stats_overall, axis=0).tolist()]) ) print(prefix+" Max : ", zip(stats_cols, ["%6.1f" % (v,) for v in np.max(stats_overall, axis=0).tolist()]) ) print(prefix+" Mean : ", zip(stats_cols, ["%6.1f" % (v,) for v in np.mean(stats_overall, axis=0).tolist()]) ) def run_test(i): # Run a test set of 10 games (not in training examples stats_test_log=[] for j in range(0,10): stats_test, _ = play_game(1000*1000*1000+j, model, prob_exploration=-1.0) # Negative probability for deterministic... stats_test['model_err'] = -999. stats_test_log.append( stats_test ) stats_aggregates(stats_test_log, "=Test[%5d]" % (i,)) # Initial, untrained network run_test(0) #run_test(0) # Check for consistency : WORKS import datetime t0,i0 = datetime.datetime.now(),0 t_start=t0 #n_games=50*1000 n_games=1*1000 batchsize=512 stats_log=[] training_data=dict( board=[], target=[]) for i in range(0, n_games): stats, training_data_new = play_game(i, model) if False: print("game[%d]" % (i,)) print(" steps = %d" % (stats['steps'],)) print(" average moves = %5.1f" % (stats['av_potential_moves'], ) ) print(" new_cols = %d" % (stats['new_cols'],)) print(" score_total = %d" % (stats['score'],)) training_data['board'] += training_data_new['board'] training_data['target'] += training_data_new['target'] # This keeps the window from growing too big if len(training_data['target'])>batchsize*2: training_data['board'] = training_data['board'][-batchsize:] training_data['target'] = training_data['target'][-batchsize:] for iter in range(0,1): err = model_train( training_data['board'][-batchsize:], training_data['target'][-batchsize:] ) stats['model_err'] = err stats_log.append( stats ) if ((i+1) % 10)==0: t_now = datetime.datetime.now() t_elapsed = (t_now - t0).total_seconds() t_end_projected = t0 + datetime.timedelta( seconds=(n_games-i0) * (t_elapsed/(i-i0)) ) print(" 100 games in %6.1f seconds, Projected end at : %s, stored_data.length=%d" % (100.*t_elapsed/(i-i0), t_end_projected.strftime("%H:%M"), len(training_data['target']), )) t0, i0 = datetime.datetime.now(), i if ((i+1) % 100)==0: stats_aggregates(stats_log, "Train[%5d]" % (i,), last=1000) if ((i+1) % 100)==0: run_test(i) # save state param_values = lasagne.layers.get_all_param_values(model) param_dictionary = dict( param_values=param_values, width=width, height=height, n_colours=n_colours, batchsize=batchsize, i=i, ) with open('../data/game/crush/rl_%dx%dx%d_%s.%06d.pkl' % (width, height, n_colours, t_start.strftime("%Y-%m-%d_%H-%M"), i,), 'wb') as f: pickle.dump(param_dictionary, f) stats_aggregates(stats_log, "FINAL[%5d]" % (n_games,) ) # Aggregate stats for 100 games (played randomly) #('Min : ', [('steps', ' 29.0'), ('av_potential_moves', ' 7.9'), ('new_cols', ' 0.0'), ('score', ' 246.0'), ('model_err', ' 45.9')]) #('Max : ', [('steps', ' 118.0'), ('av_potential_moves', ' 16.0'), ('new_cols', ' 18.0'), ('score', '1152.0'), ('model_err', '7681.9')]) #('Mean : ', [('steps', ' 52.7'), ('av_potential_moves', ' 11.7'), ('new_cols', ' 3.0'), ('score', ' 451.6'), ('model_err', '1235.0')]) # Aggregate stats for 100 games (played with learning : ADAM per game) #('Min : ', [('steps', ' 25.0'), ('av_potential_moves', ' 6.6'), ('new_cols', ' 0.0'), ('score', ' 266.0'), ('model_err', ' 41.0')]) #('Max : ', [('steps', ' 98.0'), ('av_potential_moves', ' 17.9'), ('new_cols', ' 13.0'), ('score', ' 880.0'), ('model_err', '8107.7')]) #('Mean : ', [('steps', ' 53.0'), ('av_potential_moves', ' 11.1'), ('new_cols', ' 3.4'), ('score', ' 451.6'), ('model_err', '1284.6')]) # Aggregate stats for 1000 games (played with learning : ADAM per game) #('Min : ', [('steps', ' 26.0'), ('av_potential_moves', ' 6.1'), ('new_cols', ' 0.0'), ('score', ' 212.0'), ('model_err', ' 7.8')]) #('Max : ', [('steps', ' 139.0'), ('av_potential_moves', ' 19.9'), ('new_cols', ' 21.0'), ('score', '1150.0'), ('model_err', '15163.5')]) #('Mean : ', [('steps', ' 54.1'), ('av_potential_moves', ' 12.2'), ('new_cols', ' 3.4'), ('score', ' 469.0'), ('model_err', ' 221.5')]) # Aggregate stats for 1000 games (played with learning + dropout : ADAM per game) #('Min : ', [('steps', ' 23.0'), ('av_potential_moves', ' 5.7'), ('new_cols', ' 0.0'), ('score', ' 218.0'), ('model_err', ' 36.2')]) #('Max : ', [('steps', ' 180.0'), ('av_potential_moves', ' 19.3'), ('new_cols', ' 27.0'), ('score', '1346.0'), ('model_err', '8232.2')]) #('Mean : ', [('steps', ' 53.6'), ('av_potential_moves', ' 12.1'), ('new_cols', ' 3.3'), ('score', ' 453.5'), ('model_err', ' 274.2')]) ## AMD quad-core ('square') : 49s per 100 games (batchsize=1 game) ## i7 ('simlim') : 29s per 100 games ## gtx760 gpu ('anson') : 12.5s per 100 games # Aggregate stats for 1000 games (played with learning : ADAM per game - simlim) #('Min : ', [('steps', ' 24.0'), ('av_potential_moves', ' 6.1'), ('new_cols', ' 0.0'), ('score', ' 202.0'), ('model_err', ' 5.6')]) #('Max : ', [('steps', ' 161.0'), ('av_potential_moves', ' 18.8'), ('new_cols', ' 23.0'), ('score', '1312.0'), ('model_err', '15164.2')]) #('Mean : ', [('steps', ' 53.6'), ('av_potential_moves', ' 12.3'), ('new_cols', ' 3.4'), ('score', ' 465.4'), ('model_err', ' 222.9')]) ## AMD quad-core ('square') : 140s per 100 games (batchsize=1024 steps ~ 20 games) ## gtx760 gpu ('anson') : 15s per 100 games (batchsize=1024 steps ~ 20 games) ## gtx760 gpu ('anson') : 27s per 100 games (batchsize=1024 steps ~ 20 games, 8 iterations per training) ## Titan X gpu ('simlim') : 27s per 100 games (batchsize=1024 steps ~ 20 games, 8 iterations per training) # Aggregate stats for 1000 games (played with learning : ADAM per game - simlim, batchsize=1024) #('Min : ', [('steps', ' 23.0'), ('av_potential_moves', ' 7.2'), ('new_cols', ' 0.0'), ('score', ' 246.0'), ('model_err', ' 91.7')]) #('Max : ', [('steps', ' 174.0'), ('av_potential_moves', ' 19.4'), ('new_cols', ' 33.0'), ('score', '2046.0'), ('model_err', ' 194.8')]) #('Mean : ', [('steps', ' 53.8'), ('av_potential_moves', ' 12.8'), ('new_cols', ' 4.2'), ('score', ' 554.4'), ('model_err', ' 131.4')]) # Aggregate stats for 1000 games (played with learning : ADAM per game - simlim, batchsize=1024, 8 iterations per game) #('Min : ', [('steps', ' 23.0'), ('av_potential_moves', ' 7.4'), ('new_cols', ' 0.0'), ('score', ' 232.0'), ('model_err', ' 63.8')]) #('Max : ', [('steps', ' 290.0'), ('av_potential_moves', ' 18.6'), ('new_cols', ' 56.0'), ('score', '3286.0'), ('model_err', ' 582.0')]) #('Mean : ', [('steps', ' 69.0'), ('av_potential_moves', ' 12.4'), ('new_cols', ' 8.0'), ('score', ' 853.6'), ('model_err', ' 314.0')]) # simlim 20k games : last 1000: #('Min : ', [('steps', ' 26.0'), ('av_potential_moves', ' 6.8'), ('new_cols', ' 0.0'), ('score', ' 336.0'), ('model_err', ' 15.3')]) #('Max : ', [('steps', ' 339.0'), ('av_potential_moves', ' 18.6'), ('new_cols', ' 65.0'), ('score', '3572.0'), ('model_err', '1789.9')]) #('Mean : ', [('steps', ' 77.7'), ('av_potential_moves', ' 10.8'), ('new_cols', ' 10.2'), ('score', '1070.7'), ('model_err', ' 88.0')]) # simlim 100k games : last 1000: ( interestingly, the scores peak with an average of ~1150 in 20k or so iterations) #('Min : ', [('steps', ' 32.0'), ('av_potential_moves', ' 8.4'), ('new_cols', ' 0.0'), ('score', ' 242.0'), ('model_err', '1391.2')]) #('Max : ', [('steps', ' 390.0'), ('av_potential_moves', ' 20.6'), ('new_cols', ' 69.0'), ('score', '2994.0'), ('model_err', '3802.2')]) #('Mean : ', [('steps', ' 96.6'), ('av_potential_moves', ' 13.7'), ('new_cols', ' 10.7'), ('score', ' 731.2'), ('model_err', '2355.3')]) # simlim 1k games : last 1000: (target = n_cols) #('Min : ', [('steps', ' 29.0'), ('av_potential_moves', ' 7.8'), ('new_cols', ' 0.0'), ('score', ' 210.0'), ('model_err', ' 0.0')]) #('Max : ', [('steps', ' 217.0'), ('av_potential_moves', ' 19.0'), ('new_cols', ' 34.0'), ('score', '2074.0'), ('model_err', ' 0.6')]) #('Mean : ', [('steps', ' 71.5'), ('av_potential_moves', ' 12.8'), ('new_cols', ' 7.4'), ('score', ' 669.1'), ('model_err', ' 0.2')]) # simlim 20k games : last 1000: (target = n_cols, 8xAdam) #('Min : ', [('steps', ' 28.0'), ('av_potential_moves', ' 6.8'), ('new_cols', ' 0.0'), ('score', ' 250.0'), ('model_err', ' 0.3')]) #('Max : ', [('steps', ' 411.0'), ('av_potential_moves', ' 17.5'), ('new_cols', ' 79.0'), ('score', '3662.0'), ('model_err', ' 3.8')]) #('Mean : ', [('steps', ' 81.9'), ('av_potential_moves', ' 11.6'), ('new_cols', ' 8.9'), ('score', ' 689.8'), ('model_err', ' 0.8')]) # simlim 20k games : last 1000: (target = n_cols, 1xAdam) #('Min : ', [('steps', ' 31.0'), ('av_potential_moves', ' 7.8'), ('new_cols', ' 0.0'), ('score', ' 286.0'), ('model_err', ' 0.1')]) #('Max : ', [('steps', ' 588.0'), ('av_potential_moves', ' 19.9'), ('new_cols', ' 118.0'), ('score', '5434.0'), ('model_err', ' 0.4')]) #('Mean : ', [('steps', ' 129.1'), ('av_potential_moves', ' 13.6'), ('new_cols', ' 19.8'), ('score', '1226.8'), ('model_err', ' 0.2')]) # simlim 1k games : grep Test 1k.1xAdam.batch=512.target=cols.test.log | grep Mean #('=Test[ 0] Mean : ', [('steps', ' 52.4'), ('av_potential_moves', ' 11.9'), ('new_cols', ' 2.5'), ('score', ' 389.4'), ('model_err', '-999.0')]) #('=Test[ 99] Mean : ', [('steps', ' 54.5'), ('av_potential_moves', ' 13.4'), ('new_cols', ' 3.4'), ('score', ' 491.2'), ('model_err', '-999.0')]) #('=Test[ 199] Mean : ', [('steps', ' 74.8'), ('av_potential_moves', ' 13.2'), ('new_cols', ' 6.8'), ('score', ' 614.8'), ('model_err', '-999.0')]) #('=Test[ 299] Mean : ', [('steps', ' 68.8'), ('av_potential_moves', ' 13.0'), ('new_cols', ' 6.1'), ('score', ' 584.6'), ('model_err', '-999.0')]) #('=Test[ 399] Mean : ', [('steps', ' 74.1'), ('av_potential_moves', ' 13.5'), ('new_cols', ' 7.6'), ('score', ' 707.2'), ('model_err', '-999.0')]) #('=Test[ 499] Mean : ', [('steps', ' 87.5'), ('av_potential_moves', ' 12.7'), ('new_cols', ' 9.9'), ('score', ' 816.6'), ('model_err', '-999.0')]) #('=Test[ 599] Mean : ', [('steps', ' 79.3'), ('av_potential_moves', ' 12.5'), ('new_cols', ' 9.3'), ('score', ' 827.0'), ('model_err', '-999.0')]) #('=Test[ 699] Mean : ', [('steps', ' 88.5'), ('av_potential_moves', ' 13.3'), ('new_cols', ' 10.4'), ('score', ' 825.0'), ('model_err', '-999.0')]) #('=Test[ 799] Mean : ', [('steps', ' 76.1'), ('av_potential_moves', ' 13.2'), ('new_cols', ' 8.2'), ('score', ' 790.0'), ('model_err', '-999.0')]) #('=Test[ 899] Mean : ', [('steps', ' 105.7'), ('av_potential_moves', ' 11.5'), ('new_cols', ' 13.9'), ('score', '1000.6'), ('model_err', '-999.0')]) #('=Test[ 999] Mean : ', [('steps', ' 78.2'), ('av_potential_moves', ' 12.7'), ('new_cols', ' 8.3'), ('score', ' 718.4'), ('model_err', '-999.0')]) # https://github.com/mdda/deep-learning-workshop/blob/e4437c95c0ca18ae9df11fc06ab74cbcef86cab3/notebooks/7-Reinforcement-Learning.ipynb
9,151
809
/* * LensKit, an open-source toolkit for recommender systems. * Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md) * Copyright 2010-2014 Regents of the University of Minnesota * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.lenskit.data.ratings; import it.unimi.dsi.fastutil.longs.Long2DoubleMap; import it.unimi.dsi.fastutil.longs.LongCollection; import org.grouplens.grapht.annotation.DefaultImplementation; import org.lenskit.util.keys.KeyIndex; import net.jcip.annotations.Immutable; import java.util.Collection; import java.util.List; /** * Snapshot of the ratings data for building a recommender. * * This provides a snapshot of each user's most current rating for each item. It may also represent synthetic ratings * derived from other types of events, depending on the builder that is used for it. * * The ratings obtained from a rating matrix **do not** have timestamps. * * The users, items, and ratings in the rating matrix are associated with 0-based indexes, so that they can be used * in conjunction with vectors or arrays. The rating matrix can be thought of as a sparse matrix in coordinate list * (COO) format, and the index of the rating is its position in the coordinate list. */ @Immutable @DefaultImplementation(PackedRatingMatrix.class) public interface RatingMatrix { /** * Get the set of user IDs in the snapshot. * * @return A set of all known user IDs. */ LongCollection getUserIds(); /** * Get the set of item IDs in the snapshot. * * @return A set of all known item IDs. */ LongCollection getItemIds(); /** * Get the user ID index. * * @return The index mapping between user IDs and user indices. */ KeyIndex userIndex(); /** * Get the item ID index. * * @return The index mapping between user IDs and user indices. */ KeyIndex itemIndex(); /** * Get the collection of ratings in the snapshot. The ratings are returned in an undetermined * order. It is guaranteed that no duplicate ratings appear - each <i>(user,item)</i> pair is * rated at most once. Each preference's index is also in the range [0,len), where len is the * size of this collection. * * <p> Modifying the returned indexed preferences will <b>not</b> modify the underlying * snapshot. * * @return All ratings in the system. */ List<RatingMatrixEntry> getRatings(); /** * Get the ratings for a particular user. It is guaranteed that no duplicate ratings appear - * each <i>(user,item)</i> pair is rated at most once. * * <p>Modifying the returned indexed preferences will <b>not</b> modify the underlying * snapshot. * * @param userId The user's ID. * @return The user's ratings, or an empty collection if the user is unknown. */ Collection<RatingMatrixEntry> getUserRatings(long userId); /** * Get the current preferences of a particular user as a vector. * * @param userId The user's ID. * @return The user's rating vector. */ Long2DoubleMap getUserRatingVector(long userId); }
1,277
347
<reponame>hbraha/ovirt-engine package org.ovirt.engine.core.bll.network.host; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.compat.Guid; public interface VfScheduler { /** * Validates whether the VM interfaces have suitable virtual functions on the specified host. If the host has * suitable VFs, the mappings belonging to given <code>vmId</code> (obtainable from {@link #getVnicToVfMap}) are * updated with mapping between the VM interfaces to the virtual functions. * If not, the problematic VM interface's names are returned. * * @param vmId id of VM * @param hostId id of host * @param allVmNics All {@link VmNetworkInterface} for given <code>vmId</code> * * @return the names of the problematic vm interfaces */ public List<String> validatePassthroughVnics(Guid vmId, Guid hostId, List<VmNetworkInterface> allVmNics); /** * @return the name of a free suitable vf. If there is no one, return null. */ public String findFreeVfForVnic(Guid hostId, Network vnicNetwork, Guid vmId); /** * @return the mapping between the VM interfaces to the virtual functions. Null is returned if there are no data for * given <code>vmId</code> and <code>hostId</code> */ public Map<Guid, String> getVnicToVfMap(Guid vmId, Guid hostId); /** * Cleans all mappings of the specified vm (obtainable using {@link #getVnicToVfMap}). */ public void cleanVmData(Guid vmId); }
580
2,151
<filename>third_party/openscreen/src/platform/linux/network_interface.cc // 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. #include "platform/api/network_interface.h" // clang-format: off #include <sys/socket.h> // clang-format: on #include <linux/ethtool.h> #include <linux/if_arp.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/sockios.h> #include <linux/wireless.h> #include <netinet/ip.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <cstring> #include "absl/strings/string_view.h" #include "osp_base/ip_address.h" #include "osp_base/scoped_pipe.h" #include "platform/api/logging.h" namespace openscreen { namespace platform { namespace { constexpr int kNetlinkRecvmsgBufSize = 8192; // Safely reads the system name for the interface from the (probably) // null-terminated string |kernel_name| and returns a std::string. std::string GetInterfaceName(absl::string_view kernel_name) { OSP_CHECK_LT(kernel_name.length(), IFNAMSIZ); return std::string(kernel_name); } // Returns the type of the interface identified by the name |ifname|, if it can // be determined, otherwise returns InterfaceInfo::Type::kOther. InterfaceInfo::Type GetInterfaceType(const std::string& ifname) { // Determine type after name has been set. ScopedFd s(socket(AF_INET6, SOCK_DGRAM, 0)); if (!s) { s = ScopedFd(socket(AF_INET, SOCK_DGRAM, 0)); if (!s) return InterfaceInfo::Type::kOther; } // Note: This uses Wireless Extensions to test the interface, which is // deprecated. However, it's much easier than using the new nl80211 // interface for this purpose. If Wireless Extensions are ever actually // removed though, this will need to use nl80211. struct iwreq wr; static_assert(sizeof(wr.ifr_name) == IFNAMSIZ, "expected size of interface name fields"); OSP_CHECK_LT(ifname.size(), IFNAMSIZ); strncpy(wr.ifr_name, ifname.c_str(), IFNAMSIZ); if (ioctl(s.get(), SIOCGIWNAME, &wr) != -1) return InterfaceInfo::Type::kWifi; struct ethtool_cmd ecmd; ecmd.cmd = ETHTOOL_GSET; struct ifreq ifr; static_assert(sizeof(ifr.ifr_name) == IFNAMSIZ, "expected size of interface name fields"); OSP_CHECK_LT(ifname.size(), IFNAMSIZ); strncpy(ifr.ifr_name, ifname.c_str(), IFNAMSIZ); ifr.ifr_data = &ecmd; if (ioctl(s.get(), SIOCETHTOOL, &ifr) != -1) return InterfaceInfo::Type::kEthernet; return InterfaceInfo::Type::kOther; } // Reads an interface's name, hardware address, and type from |rta| and places // the results in |info|. |rta| is the first attribute structure returned as // part of an RTM_NEWLINK message. |attrlen| is the total length of the buffer // pointed to by |rta|. void GetInterfaceAttributes(struct rtattr* rta, unsigned int attrlen, InterfaceInfo* info) { for (; RTA_OK(rta, attrlen); rta = RTA_NEXT(rta, attrlen)) { if (rta->rta_type == IFLA_IFNAME) { info->name = GetInterfaceName(reinterpret_cast<const char*>(RTA_DATA(rta))); } else if (rta->rta_type == IFLA_ADDRESS) { OSP_CHECK_EQ(sizeof(info->hardware_address), RTA_PAYLOAD(rta)); std::memcpy(info->hardware_address, RTA_DATA(rta), sizeof(info->hardware_address)); } } info->type = GetInterfaceType(info->name); } InterfaceAddresses* FindOrAddAddressesForIndex( std::vector<InterfaceAddresses>* address_list, const std::vector<InterfaceInfo>& info_list, NetworkInterfaceIndex index) { const auto info_it = std::find_if( info_list.begin(), info_list.end(), [index](const InterfaceInfo& info) { return info.index == index; }); if (info_it == info_list.end()) return nullptr; auto addr_it = std::find_if(address_list->begin(), address_list->end(), [index](const InterfaceAddresses& addresses) { return addresses.info.index == index; }); if (addr_it != address_list->end()) return &(*addr_it); address_list->emplace_back(); InterfaceAddresses& addr = address_list->back(); addr.info = *info_it; return &addr; } // Reads the IPv4 address that comes from an RTM_NEWADDR message and places the // result in |address|. |rta| is the first attribute structure returned by the // message and |attrlen| is the total length of the buffer pointed to by |rta|. // |ifname| is the name of the interface to which we believe the address belongs // based on interface index matching. It is only used for sanity checking in // debug builds. void GetIPv4Address(struct rtattr* rta, unsigned int attrlen, const std::string& ifname, IPAddress* address) { bool have_local = false; IPAddress local; for (; RTA_OK(rta, attrlen); rta = RTA_NEXT(rta, attrlen)) { if (rta->rta_type == IFA_LABEL) { OSP_DCHECK_EQ(ifname, reinterpret_cast<const char*>(RTA_DATA(rta))); } else if (rta->rta_type == IFA_ADDRESS) { OSP_DCHECK_EQ(IPAddress::kV4Size, RTA_PAYLOAD(rta)); *address = IPAddress(IPAddress::Version::kV4, static_cast<uint8_t*>(RTA_DATA(rta))); } else if (rta->rta_type == IFA_LOCAL) { OSP_DCHECK_EQ(IPAddress::kV4Size, RTA_PAYLOAD(rta)); have_local = true; local = IPAddress(IPAddress::Version::kV4, static_cast<uint8_t*>(RTA_DATA(rta))); } } if (have_local) *address = local; } // Reads the IPv6 address that comes from an RTM_NEWADDR message and places the // result in |address|. |rta| is the first attribute structure returned by the // message and |attrlen| is the total length of the buffer pointed to by |rta|. // |ifname| is the name of the interface to which we believe the address belongs // based on interface index matching. It is only used for sanity checking in // debug builds. void GetIPv6Address(struct rtattr* rta, unsigned int attrlen, const std::string& ifname, IPAddress* address) { bool have_local = false; IPAddress local; for (; RTA_OK(rta, attrlen); rta = RTA_NEXT(rta, attrlen)) { if (rta->rta_type == IFA_LABEL) { OSP_DCHECK_EQ(ifname, reinterpret_cast<const char*>(RTA_DATA(rta))); } else if (rta->rta_type == IFA_ADDRESS) { OSP_DCHECK_EQ(IPAddress::kV6Size, RTA_PAYLOAD(rta)); *address = IPAddress(IPAddress::Version::kV6, static_cast<uint8_t*>(RTA_DATA(rta))); } else if (rta->rta_type == IFA_LOCAL) { OSP_DCHECK_EQ(IPAddress::kV6Size, RTA_PAYLOAD(rta)); have_local = true; local = IPAddress(IPAddress::Version::kV6, static_cast<uint8_t*>(RTA_DATA(rta))); } } if (have_local) *address = local; } std::vector<InterfaceInfo> GetLinkInfo() { ScopedFd fd(socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)); if (!fd) { OSP_LOG_WARN << "netlink socket() failed: " << errno << " - " << strerror(errno); return {}; } { // nl_pid = 0 for the kernel. struct sockaddr_nl peer = {}; peer.nl_family = AF_NETLINK; struct { struct nlmsghdr header; struct ifinfomsg msg; } request; request.header.nlmsg_len = sizeof(request); request.header.nlmsg_type = RTM_GETLINK; request.header.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT; request.header.nlmsg_seq = 0; request.header.nlmsg_pid = 0; request.msg.ifi_family = AF_UNSPEC; struct iovec iov = {&request, request.header.nlmsg_len}; struct msghdr msg = {&peer, sizeof(peer), &iov, /* msg_iovlen */ 1, /* msg_control */ nullptr, /* msg_controllen */ 0, /* msg_flags */ 0}; if (sendmsg(fd.get(), &msg, 0) < 0) { OSP_LOG_ERROR << "netlink sendmsg() failed: " << errno << " - " << strerror(errno); return {}; } } std::vector<InterfaceInfo> info_list; { char buf[kNetlinkRecvmsgBufSize]; struct iovec iov = {buf, sizeof(buf)}; struct sockaddr_nl source_address; struct msghdr msg; struct nlmsghdr* netlink_header; msg = {&source_address, sizeof(source_address), &iov, /* msg_iovlen */ 1, /* msg_control */ nullptr, /* msg_controllen */ 0, /* msg_flags */ 0}; bool done = false; while (!done) { size_t len = recvmsg(fd.get(), &msg, 0); for (netlink_header = reinterpret_cast<struct nlmsghdr*>(buf); NLMSG_OK(netlink_header, len); netlink_header = NLMSG_NEXT(netlink_header, len)) { // The end of multipart message. if (netlink_header->nlmsg_type == NLMSG_DONE) { done = true; break; } else if (netlink_header->nlmsg_type == NLMSG_ERROR) { done = true; OSP_LOG_ERROR << "netlink error msg: " << reinterpret_cast<struct nlmsgerr*>( NLMSG_DATA(netlink_header)) ->error; continue; } else if ((netlink_header->nlmsg_flags & NLM_F_MULTI) == 0) { // If this is not a multi-part message, we don't need to wait for an // NLMSG_DONE message; this is the only message. done = true; } // RTM_NEWLINK messages describe existing network links on the host. if (netlink_header->nlmsg_type != RTM_NEWLINK) continue; struct ifinfomsg* interface_info = static_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_header)); // Only process non-loopback interfaces which are active (up). if ((interface_info->ifi_flags & IFF_LOOPBACK) || ((interface_info->ifi_flags & IFF_UP) == 0)) { continue; } info_list.emplace_back(); InterfaceInfo& info = info_list.back(); info.index = interface_info->ifi_index; GetInterfaceAttributes(IFLA_RTA(interface_info), IFLA_PAYLOAD(netlink_header), &info); } } } return info_list; } std::vector<InterfaceAddresses> GetAddressInfo( const std::vector<InterfaceInfo>& info_list) { ScopedFd fd(socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)); if (!fd) { OSP_LOG_ERROR << "netlink socket() failed: " << errno << " - " << strerror(errno); return {}; } { // nl_pid = 0 for the kernel. struct sockaddr_nl peer = {}; peer.nl_family = AF_NETLINK; struct { struct nlmsghdr header; struct ifaddrmsg msg; } request; request.header.nlmsg_len = sizeof(request); request.header.nlmsg_type = RTM_GETADDR; request.header.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT; request.header.nlmsg_seq = 1; request.header.nlmsg_pid = 0; request.msg.ifa_family = AF_UNSPEC; struct iovec iov = {&request, request.header.nlmsg_len}; struct msghdr msg = {&peer, sizeof(peer), &iov, /* msg_iovlen */ 1, /* msg_control */ nullptr, /* msg_controllen */ 0, /* msg_flags */ 0}; if (sendmsg(fd.get(), &msg, 0) < 0) { OSP_LOG_ERROR << "sendmsg failed: " << errno << " - " << strerror(errno); return {}; } } std::vector<InterfaceAddresses> address_list; { char buf[kNetlinkRecvmsgBufSize]; struct iovec iov = {buf, sizeof(buf)}; struct sockaddr_nl source_address; struct msghdr msg; struct nlmsghdr* netlink_header; msg = {&source_address, sizeof(source_address), &iov, /* msg_iovlen */ 1, /* msg_control */ nullptr, /* msg_controllen */ 0, /* msg_flags */ 0}; bool done = false; while (!done) { size_t len = recvmsg(fd.get(), &msg, 0); for (netlink_header = reinterpret_cast<struct nlmsghdr*>(buf); NLMSG_OK(netlink_header, len); netlink_header = NLMSG_NEXT(netlink_header, len)) { if (netlink_header->nlmsg_type == NLMSG_DONE) { done = true; break; } else if (netlink_header->nlmsg_type == NLMSG_ERROR) { done = true; OSP_LOG_ERROR << "netlink error msg: " << reinterpret_cast<struct nlmsgerr*>( NLMSG_DATA(netlink_header)) ->error; continue; } else if ((netlink_header->nlmsg_flags & NLM_F_MULTI) == 0) { // If this is not a multi-part message, we don't need to wait for an // NLMSG_DONE message; this is the only message. done = true; } if (netlink_header->nlmsg_type != RTM_NEWADDR) continue; struct ifaddrmsg* interface_address = static_cast<struct ifaddrmsg*>(NLMSG_DATA(netlink_header)); InterfaceAddresses* addresses = FindOrAddAddressesForIndex( &address_list, info_list, interface_address->ifa_index); if (!addresses) { OSP_DVLOG << "skipping address for interface " << interface_address->ifa_index; continue; } if (interface_address->ifa_family == AF_INET) { addresses->addresses.emplace_back(); IPSubnet& address = addresses->addresses.back(); address.prefix_length = interface_address->ifa_prefixlen; GetIPv4Address(IFA_RTA(interface_address), IFA_PAYLOAD(netlink_header), addresses->info.name, &address.address); } else if (interface_address->ifa_family == AF_INET6) { addresses->addresses.emplace_back(); IPSubnet& address = addresses->addresses.back(); address.prefix_length = interface_address->ifa_prefixlen; GetIPv6Address(IFA_RTA(interface_address), IFA_PAYLOAD(netlink_header), addresses->info.name, &address.address); } else { OSP_LOG_ERROR << "Unknown address family: " << interface_address->ifa_family; } } } } return address_list; } } // namespace std::vector<InterfaceAddresses> GetInterfaceAddresses() { return GetAddressInfo(GetLinkInfo()); } } // namespace platform } // namespace openscreen
6,672
530
<reponame>meghasfdc/jmc<filename>application/org.openjdk.jmc.ui/src/main/java/org/openjdk/jmc/ui/rate/RateLimitedRefresher.java<gh_stars>100-1000 /* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of 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 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 org.openjdk.jmc.ui.rate; /** * A refresh bufferer that limits the rate which with it forwards refresh requests. In addition, * refreshes will typically, subject to the {@link RateCoordinator}, be delivered in the user * interface thread. */ public abstract class RateLimitedRefresher implements Runnable { protected final RateCoordinator rateCoordinator; protected final int minPeriodMillis; private long lastRefreshMillis; private boolean needsRefresh; public RateLimitedRefresher(RateCoordinator rateCoordinator, int minPeriodMillis) { this.rateCoordinator = rateCoordinator; this.minPeriodMillis = minPeriodMillis; } public void setNeedsRefresh() { int delay = -1; synchronized (this) { if (!needsRefresh) { needsRefresh = true; delay = (int) Math.max(0, lastRefreshMillis + minPeriodMillis - System.currentTimeMillis()); } } if (delay >= 0) { rateCoordinator.schedule(this, delay); } } @Override public final void run() { refreshIfNeeded(); } /** * Note: This method should only be called from the SWT display thread. */ public void refreshIfNeeded() { boolean refresh = false; synchronized (this) { if (needsRefresh) { needsRefresh = false; refresh = true; lastRefreshMillis = System.currentTimeMillis(); } } if (refresh) { doRefresh(); } } protected abstract void doRefresh(); }
1,047
1,700
<reponame>brechtvl/embree<gh_stars>1000+ // Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once #include "scenegraph.h" namespace embree { Ref<SceneGraph::Node> loadOBJ(const FileName& fileName, const bool subdivMode = false, const bool combineIntoSingleObject = false); }
174
6,620
/* * Copyright (c) 2017 Intel Corporation * SPDX-License-Identifier: BSD-2-Clause */ #include <vector> #include <assert.h> #include <algorithm> #include <cmath> #include <iostream> #include <stdio.h> #include "gufunc_scheduler.h" // round not available on VS2010. double guround (double number) { return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5); } class RangeActual { public: std::vector<intp> start, end; RangeActual() {} RangeActual(intp s, intp e) { start.push_back(s); end.push_back(e); } RangeActual(const std::vector<intp> &s, const std::vector<intp> &e) { assert(s.size() == e.size()); start = s; end = e; } RangeActual(const std::vector<intp> &lens) { for(uintp i = 0; i < lens.size(); ++i) { start.push_back(0); end.push_back(lens[i] - 1); } } RangeActual(uintp num_dims, intp *lens) { for(uintp i = 0; i < num_dims; ++i) { start.push_back(0); end.push_back(lens[i] - 1); } } RangeActual(uintp num_dims, intp *starts, intp *ends) { for(uintp i = 0; i < num_dims; ++i) { start.push_back(starts[i]); end.push_back(ends[i]); } } uintp ndim() const { return start.size(); } std::vector<intp> iters_per_dim() const { std::vector<intp> ret; for(uintp i = 0; i < start.size(); ++i) { intp ret_val = end[i] - start[i] + 1; if(end[i] < start[i]) ret_val = 0; ret.push_back(ret_val); } return ret; } }; class dimlength { public: uintp dim; intp length; dimlength(uintp d, intp l) : dim(d), length(l) {} }; struct dimlength_by_dim { bool operator()(const dimlength &a, const dimlength &b) const { return a.dim < b.dim; } }; struct dimlength_by_length_reverse { bool operator()(const dimlength &a, const dimlength &b) const { return a.length > b.length; } }; class isf_range { public: uintp dim; intp lower_bound, upper_bound; isf_range(uintp d, intp l, intp u) : dim(d), lower_bound(l), upper_bound(u) {} }; struct isf_range_by_dim { bool operator()(const isf_range &a, const isf_range &b) const { return a.dim < b.dim; } }; /* * m_a is the current start of the partition. * m_b is the current end of the partition. * m_c is the start of the next partition. */ class chunk_info { public: intp m_a, m_b, m_c; chunk_info(intp a, intp b, intp c) : m_a(a), m_b(b), m_c(c) {} }; /* * Split a space starting at rs and ending at re into "divisions" parts. */ chunk_info chunk(intp rs, intp re, intp divisions) { assert(divisions >= 1); intp total = (re - rs) + 1; // If only one division then everything goes into that division. if( divisions == 1) { return chunk_info(rs, re, re + 1); } else { intp len = total / divisions; intp res_end = rs + len - 1; // Return the first division by starting at the beginning (rs) and going to // the remaining length divided by the number of divisions. return chunk_info(rs, res_end, res_end + 1); } } chunk_info equalizing_chunk(intp rs, intp re, intp divisions, float thread_percent) { assert(divisions >= 1); intp total = (re - rs) + 1; if (divisions == 1) { return chunk_info(rs, re, re + 1); } else { intp len = total * thread_percent; intp res_end = rs + len - 1; return chunk_info(rs, res_end, res_end + 1); } } RangeActual isfRangeToActual(const std::vector<isf_range> &build) { std::vector<isf_range> bunsort(build); std::sort(bunsort.begin(), bunsort.end(), isf_range_by_dim()); std::vector<intp> lower_bounds(bunsort.size()), upper_bounds(bunsort.size()); for(uintp i = 0; i < bunsort.size(); ++i) { lower_bounds[i] = bunsort[i].lower_bound; upper_bounds[i] = bunsort[i].upper_bound; } return RangeActual(lower_bounds, upper_bounds); } /* * Does the main work of splitting the iteration space between threads. * In general, we start by allocating a number of threads to handle the largest dimension * then call the routine recursively to allocate threads to the next largest dimension * and so one. */ void divide_work(const RangeActual &full_iteration_space, std::vector<RangeActual> &assignments, std::vector<isf_range> &build, uintp start_thread, uintp end_thread, const std::vector<dimlength> &dims, uintp index) { // Number of threads used for this dimension. uintp num_threads = (end_thread - start_thread) + 1; assert(num_threads >= 1); // If there is only one thread left then it gets all the remaining work. if(num_threads == 1) { assert(build.size() <= dims.size()); // build holds the ongoing constructed range of iterations in each dimension. // If the length of build is the number of dims then we have a complete allocation // so store it in assignments. if(build.size() == dims.size()) { assignments[start_thread] = isfRangeToActual(build); } else { // There are still more dimensions to add. // Create a copy of the incoming build. std::vector<isf_range> new_build(build.begin()+0, build.begin()+index); // Add an entry to new_build for this thread to handle the entire current dimension. new_build.push_back(isf_range(dims[index].dim, full_iteration_space.start[dims[index].dim], full_iteration_space.end[dims[index].dim])); // Recursively process. divide_work(full_iteration_space, assignments, new_build, start_thread, end_thread, dims, index+1); } } else { // There is more than 1 thread for handling this dimension so need to split the dimension between the threads. assert(index < dims.size()); intp total_len = 0; // Compute the total number of iterations in the remaining dimensions to be processed, including the current one. for(uintp i = index; i < dims.size(); ++i) total_len += dims[i].length > 1 ? dims[i].length : 0; uintp divisions_for_this_dim; if(total_len == 0) { divisions_for_this_dim = num_threads; } else { // We allocate the remaining threads proportionally to the ratio of the current dimension length to the total. divisions_for_this_dim = intp(guround(num_threads * ((float)dims[index].length / total_len))); if (divisions_for_this_dim < 1) { divisions_for_this_dim = 1; } } // These are used to divide the iteration space. intp chunkstart = full_iteration_space.start[dims[index].dim]; intp chunkend = full_iteration_space.end[dims[index].dim]; // These are used to divide threads. intp threadstart = start_thread; intp threadend = end_thread; // for each division of the current dimension... for(uintp i = 0; i < divisions_for_this_dim; ++i) { chunk_info chunk_thread = chunk(threadstart, threadend, divisions_for_this_dim - i); // Number of threads used for this division. uintp threads_used_here = (1 + (chunk_thread.m_b - chunk_thread.m_a)); chunk_info chunk_index = equalizing_chunk(chunkstart, chunkend, divisions_for_this_dim - i, threads_used_here / (float)num_threads); // Remember that the next division has threads_used_here fewer threads to allocate. num_threads -= threads_used_here; // m_c contains the next start value so update the iteration space and thread space in preparation for next iteration of this loop. chunkstart = chunk_index.m_c; threadstart = chunk_thread.m_c; // Copy the incoming build to new_build. std::vector<isf_range> new_build(build.begin()+0, build.begin()+index); // Add this dimension to new_build to handle start=m_a to end=m_b. new_build.push_back(isf_range(dims[index].dim, chunk_index.m_a, chunk_index.m_b)); // Recursively process the next dimension. divide_work(full_iteration_space, assignments, new_build, chunk_thread.m_a, chunk_thread.m_b, dims, index+1); } } } /* * Convert from internal format of vector of ranges to a flattened 2D-array usable by Python. */ template<class T> void flatten_schedule(const std::vector<RangeActual> &sched, T *out_sched) { uintp outer = sched.size(); uintp inner = sched[0].start.size(); for(uintp i = 0; i < outer; ++i) { for(uintp j = 0; j < inner; ++j) { out_sched[(i*inner*2) + j] = sched[i].start[j]; } for(uintp j = 0; j < inner; ++j) { out_sched[(i*inner*2) + j + inner] = sched[i].end[j]; } } } /* * Main routine that computes a static schedule. * full_space is the iteration space in each dimension. * num_sched is the number of worker threads. */ std::vector<RangeActual> create_schedule(const RangeActual &full_space, uintp num_sched) { // Compute the number of iterations to be run for each dimension. std::vector<intp> ipd = full_space.iters_per_dim(); // We special-case one dimensional. if(full_space.ndim() == 1) { // Get the number of iterations for the single dimension. intp ra_len = ipd[0]; // If there are fewer iterations for the single dimension than there are threads... if(ra_len < 0 || (uintp)ra_len <= num_sched) { std::vector<RangeActual> ret; for(uintp i = 0; i < num_sched; ++i) { // If the amount of iterations is less than the current thread then give it no work, // signified by start of 1 and end of 0. if(ra_len < 0 || (uintp)ra_len <= i) { ret.push_back(RangeActual((intp)1, (intp)0)); } else { // Give just i'th iteration to thread i. ret.push_back(RangeActual(full_space.start[0] + i, full_space.start[0] + i)); } } return ret; } else { // There are more iterations than threads. std::vector<RangeActual> ret; // cur holds the next unallocated iteration. intp cur = 0; // For each thread... for(uintp i = 0; i < num_sched; ++i) { // Compute the number of items to do in this thread as // the floor of the amount of work left (ra_len-cur) divided // by the number of threads left to which to allocate work. intp ilen = ((ra_len-cur-1) / (num_sched-i)) + 1; // Compute the start iteration number for that thread as the start iteration // plus the modal number of iterations times the thread number. intp start = full_space.start[0] + cur; intp end; // If this isn't the last thread then the end iteration number is one less // than the start iteration number of the next thread. If it is the last // thread then assign all remaining iterations to it. if(i < num_sched-1) { end = full_space.start[0] + (cur + ilen) - 1; } else { end = full_space.end[0]; } // Record the iteration start and end in the schedule. ret.push_back(RangeActual(start, end)); // Update the next unallocated iteration. cur += ilen; } return ret; } } else { // Two or more dimensions are handled generically here. std::vector<dimlength> dims; // Create a vector of objects associating dimensional index to length. for(uintp i = 0; i < ipd.size(); ++i) dims.push_back(dimlength(i, ipd[i])); // Sort the dimensions in the reverse order of their length. std::sort(dims.begin(), dims.end(), dimlength_by_length_reverse()); std::vector<RangeActual> assignments(num_sched, RangeActual((intp)1,(intp)0)); std::vector<isf_range> build; // Compute the division of work across dimensions and threads. divide_work(full_space, assignments, build, 0, num_sched-1, dims, 0); return assignments; } } /* num_dim (D) is the number of dimensions of the iteration space. starts is the range-start of each of those dimensions, inclusive. ends is the range-end of each of those dimensions, inclusive. num_threads is the number (N) of chunks to break the iteration space into sched is pre-allocated memory for the schedule to be stored in and is of size NxD. debug is non-zero if DEBUG_ARRAY_OPT is turned on. */ extern "C" void do_scheduling_signed(uintp num_dim, intp *starts, intp *ends, uintp num_threads, intp *sched, intp debug) { if (debug) { printf("do_scheduling_signed\n"); printf("num_dim = %d\n", (int)num_dim); printf("ranges = ("); for (unsigned i = 0; i < num_dim; i++) { printf("[%d, %d], ", (int)starts[i], (int)ends[i]); } printf(")\n"); printf("num_threads = %d\n", (int)num_threads); } if (num_threads == 0) return; RangeActual full_space(num_dim, starts, ends); std::vector<RangeActual> ret = create_schedule(full_space, num_threads); flatten_schedule(ret, sched); } extern "C" void do_scheduling_unsigned(uintp num_dim, intp *starts, intp *ends, uintp num_threads, uintp *sched, intp debug) { if (debug) { printf("do_scheduling_unsigned\n"); printf("num_dim = %d\n", (int)num_dim); printf("ranges = ("); for (unsigned i = 0; i < num_dim; i++) { printf("[%d, %d], ", (int)starts[i], (int)ends[i]); } printf(")\n"); printf("num_threads = %d\n", (int)num_threads); } if (num_threads == 0) return; RangeActual full_space(num_dim, starts, ends); std::vector<RangeActual> ret = create_schedule(full_space, num_threads); flatten_schedule(ret, sched); }
6,262
5,547
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _FSL_FXOS_H_ #define _FSL_FXOS_H_ #include "fsl_common.h" #define FXOS8700CQ_ACCEL_RESOLUTION_BITS 14 /* * STATUS Register */ #define STATUS_00_REG 0x00 #define ZYXOW_MASK 0x80 #define ZOW_MASK 0x40 #define YOW_MASK 0x20 #define XOW_MASK 0x10 #define ZYXDR_MASK 0x08 #define ZDR_MASK 0x04 #define YDR_MASK 0x02 #define XDR_MASK 0x01 /* * F_STATUS FIFO Status Register */ #define F_STATUS_REG 0x00 #define F_OVF_MASK 0x80 #define F_WMRK_FLAG_MASK 0x40 #define F_CNT5_MASK 0x20 #define F_CNT4_MASK 0x10 #define F_CNT3_MASK 0x08 #define F_CNT2_MASK 0x04 #define F_CNT1_MASK 0x02 #define F_CNT0_MASK 0x01 #define F_CNT_MASK 0x3F /* * XYZ Data Registers */ #define OUT_X_MSB_REG 0x01 #define OUT_X_LSB_REG 0x02 #define OUT_Y_MSB_REG 0x03 #define OUT_Y_LSB_REG 0x04 #define OUT_Z_MSB_REG 0x05 #define OUT_Z_LSB_REG 0x06 /* * F_SETUP FIFO Setup Register */ #define F_SETUP_REG 0x09 #define F_MODE1_MASK 0x80 #define F_MODE0_MASK 0x40 #define F_WMRK5_MASK 0x20 #define F_WMRK4_MASK 0x10 #define F_WMRK3_MASK 0x08 #define F_WMRK2_MASK 0x04 #define F_WMRK1_MASK 0x02 #define F_WMRK0_MASK 0x01 #define F_MODE_MASK 0xC0 #define F_WMRK_MASK 0x3F #define F_MODE_DISABLED 0x00 #define F_MODE_CIRCULAR (F_MODE0_MASK) #define F_MODE_FILL (F_MODE1_MASK) #define F_MODE_TRIGGER (F_MODE1_MASK + F_MODE0_MASK) /* * TRIG_CFG FIFO Trigger Configuration Register */ #define TRIG_CFG_REG 0x0A #define TRIG_TRANS_MASK 0x20 #define TRIG_LNDPRT_MASK 0x10 #define TRIG_PULSE_MASK 0x08 #define TRIG_FF_MT_MASK 0x04 /* * SYSMOD System Mode Register */ #define SYSMOD_REG 0x0B #define FGERR_MASK 0x80 /* MMA8451 only */ #define FGT_4_MASK 0x40 /* MMA8451 only */ #define FGT_3_MASK 0x20 /* MMA8451 only */ #define FGT_2_MASK 0x10 /* MMA8451 only */ #define FGT_1_MASK 0x08 /* MMA8451 only */ #define FGT_0_MASK 0x04 /* MMA8451 only */ #define FGT_MASK 0x7C /* MMA8451 only */ #define SYSMOD1_MASK 0x02 #define SYSMOD0_MASK 0x01 #define SYSMOD_MASK 0x03 #define SYSMOD_STANDBY 0x00 #define SYSMOD_WAKE (SYSMOD0_MASK) #define SYSMOD_SLEEP (SYSMOD1_MASK) /* * INT_SOURCE System Interrupt Status Register */ #define INT_SOURCE_REG 0x0C #define SRC_ASLP_MASK 0x80 #define SRC_FIFO_MASK 0x40 #define SRC_TRANS_MASK 0x20 #define SRC_LNDPRT_MASK 0x10 #define SRC_PULSE_MASK 0x08 #define SRC_FF_MT_MASK 0x04 #define SRC_DRDY_MASK 0x01 /* * WHO_AM_I Device ID Register */ #define WHO_AM_I_REG 0x0D /* Content */ #define kFXOS_WHO_AM_I_Device_ID 0xC7 /* XYZ_DATA_CFG Sensor Data Configuration Register */ #define XYZ_DATA_CFG_REG 0x0E #define HPF_OUT_MASK 0x10 #define FS1_MASK 0x02 #define FS0_MASK 0x01 #define FS_MASK 0x03 #define FULL_SCALE_2G 0x00 #define FULL_SCALE_4G (FS0_MASK) #define FULL_SCALE_8G (FS1_MASK) /* HP_FILTER_CUTOFF High Pass Filter Register */ #define HP_FILTER_CUTOFF_REG 0x0F #define PULSE_HPF_BYP_MASK 0x20 #define PULSE_LPF_EN_MASK 0x10 #define SEL1_MASK 0x02 #define SEL0_MASK 0x01 #define SEL_MASK 0x03 /* * PL_STATUS Portrait/Landscape Status Register */ #define PL_STATUS_REG 0x10 #define NEWLP_MASK 0x80 #define LO_MASK 0x40 #define LAPO1_MASK 0x04 #define LAPO0_MASK 0x02 #define BAFRO_MASK 0x01 #define LAPO_MASK 0x06 /* * PL_CFG Portrait/Landscape Configuration Register */ #define PL_CFG_REG 0x11 #define DBCNTM_MASK 0x80 #define PL_EN_MASK 0x40 /* * PL_COUNT Portrait/Landscape Debounce Register */ #define PL_COUNT_REG 0x12 /* * PL_BF_ZCOMP Back/Front and Z Compensation Register */ #define PL_BF_ZCOMP_REG 0x13 #define BKFR1_MASK 0x80 #define BKFR0_MASK 0x40 #define ZLOCK2_MASK 0x04 #define ZLOCK1_MASK 0x02 #define ZLOCK0_MASK 0x01 #define BKFR_MASK 0xC0 #define ZLOCK_MASK 0x07 /* * PL_P_L_THS Portrait to Landscape Threshold Register */ #define PL_P_L_THS_REG 0x14 #define P_L_THS4_MASK 0x80 #define P_L_THS3_MASK 0x40 #define P_L_THS2_MASK 0x20 #define P_L_THS1_MASK 0x10 #define P_L_THS0_MASK 0x08 #define HYS2_MASK 0x04 #define HYS1_MASK 0x02 #define HYS0_MASK 0x01 #define P_L_THS_MASK 0xF8 #define HYS_MASK 0x07 /* * FF_MT_CFG Freefall and Motion Configuration Register */ #define FF_MT_CFG_REG 0x15 #define ELE_MASK 0x80 #define OAE_MASK 0x40 #define ZEFE_MASK 0x20 #define YEFE_MASK 0x10 #define XEFE_MASK 0x08 /* * FF_MT_SRC Freefall and Motion Source Registers */ #define FF_MT_SRC_REG 0x16 #define EA_MASK 0x80 #define ZHE_MASK 0x20 #define ZHP_MASK 0x10 #define YHE_MASK 0x08 #define YHP_MASK 0x04 #define XHE_MASK 0x02 #define XHP_MASK 0x01 /* * FF_MT_THS Freefall and Motion Threshold Registers * TRANSIENT_THS Transient Threshold Register */ #define FT_MT_THS_REG 0x17 #define TRANSIENT_THS_REG 0x1F #define DBCNTM_MASK 0x80 #define THS6_MASK 0x40 #define THS5_MASK 0x20 #define THS4_MASK 0x10 #define THS3_MASK 0x08 #define THS2_MASK 0x04 #define TXS1_MASK 0x02 #define THS0_MASK 0x01 #define THS_MASK 0x7F /* FF_MT_COUNT Freefall Motion Count Registers */ #define FF_MT_COUNT_REG 0x18 /* TRANSIENT_CFG Transient Configuration Register */ #define TRANSIENT_CFG_REG 0x1D #define TELE_MASK 0x10 #define ZTEFE_MASK 0x08 #define YTEFE_MASK 0x04 #define XTEFE_MASK 0x02 #define HPF_BYP_MASK 0x01 /* TRANSIENT_SRC Transient Source Register */ #define TRANSIENT_SRC_REG 0x1E #define TEA_MASK 0x40 #define ZTRANSE_MASK 0x20 #define Z_TRANS_POL_MASK 0x10 #define YTRANSE_MASK 0x08 #define Y_TRANS_POL_MASK 0x04 #define XTRANSE_MASK 0x02 #define X_TRANS_POL_MASK 0x01 /* TRANSIENT_COUNT Transient Debounce Register */ #define TRANSIENT_COUNT_REG 0x20 /* PULSE_CFG Pulse Configuration Register */ #define PULSE_CFG_REG 0x21 #define DPA_MASK 0x80 #define PELE_MASK 0x40 #define ZDPEFE_MASK 0x20 #define ZSPEFE_MASK 0x10 #define YDPEFE_MASK 0x08 #define YSPEFE_MASK 0x04 #define XDPEFE_MASK 0x02 #define XSPEFE_MASK 0x01 /* PULSE_SRC Pulse Source Register */ #define PULSE_SRC_REG 0x22 #define PEA_MASK 0x80 #define AXZ_MASK 0x40 #define AXY_MASK 0x20 #define AXX_MASK 0x10 #define DPE_MASK 0x08 #define POLZ_MASK 0x04 #define POLY_MASK 0x02 #define POLX_MASK 0x01 /* PULSE_THS XYZ Pulse Threshold Registers */ #define PULSE_THSX_REG 0x23 #define PULSE_THSY_REG 0x24 #define PULSE_THSZ_REG 0x25 #define PTHS_MASK 0x7F /* PULSE_TMLT Pulse Time Window Register */ #define PULSE_TMLT_REG 0x26 /* PULSE_LTCY Pulse Latency Timer Register */ #define PULSE_LTCY_REG 0x27 /* PULSE_WIND Second Pulse Time Window Register */ #define PULSE_WIND_REG 0x28 /* ASLP_COUNT Auto Sleep Inactivity Timer Register */ #define ASLP_COUNT_REG 0x29 /* CTRL_REG1 System Control 1 Register */ #define CTRL_REG1 0x2A #define ASLP_RATE1_MASK 0x80 #define ASLP_RATE0_MASK 0x40 #define DR2_MASK 0x20 #define DR1_MASK 0x10 #define DR0_MASK 0x08 #define LNOISE_MASK 0x04 #define FREAD_MASK 0x02 #define ACTIVE_MASK 0x01 #define ASLP_RATE_MASK 0xC0 #define DR_MASK 0x38 #define ASLP_RATE_20MS 0x00 #define ASLP_RATE_80MS (ASLP_RATE0_MASK) #define ASLP_RATE_160MS (ASLP_RATE1_MASK) #define ASLP_RATE_640MS (ASLP_RATE1_MASK + ASLP_RATE0_MASK) #define ASLP_RATE_50HZ (ASLP_RATE_20MS) #define ASLP_RATE_12_5HZ (ASLP_RATE_80MS) #define ASLP_RATE_6_25HZ (ASLP_RATE_160MS) #define ASLP_RATE_1_56HZ (ASLP_RATE_640MS) #define HYB_ASLP_RATE_25HZ (ASLP_RATE_20MS) #define HYB_ASLP_RATE_6_25HZ (ASLP_RATE_80MS) #define HYB_ASLP_RATE_1_56HZ (ASLP_RATE_160MS) #define HYB_ASLP_RATE_0_8HZ (ASLP_RATE_640MS) #define DATA_RATE_1250US 0x00 #define DATA_RATE_2500US (DR0_MASK) #define DATA_RATE_5MS (DR1_MASK) #define DATA_RATE_10MS (DR1_MASK + DR0_MASK) #define DATA_RATE_20MS (DR2_MASK) #define DATA_RATE_80MS (DR2_MASK + DR0_MASK) #define DATA_RATE_160MS (DR2_MASK + DR1_MASK) #define DATA_RATE_640MS (DR2_MASK + DR1_MASK + DR0_MASK) #define DATA_RATE_800HZ (DATA_RATE_1250US) #define DATA_RATE_400HZ (DATA_RATE_2500US) #define DATA_RATE_200HZ (DATA_RATE_5MS) #define DATA_RATE_100HZ (DATA_RATE_10MS) #define DATA_RATE_50HZ (DATA_RATE_20MS) #define DATA_RATE_12_5HZ (DATA_RATE_80MS) #define DATA_RATE_6_25HZ (DATA_RATE_160MS) #define DATA_RATE_1_56HZ (DATA_RATE_640MS) /* for hybrid (TO, Aug 2012) */ #define HYB_DATA_RATE_400HZ (DATA_RATE_1250US) #define HYB_DATA_RATE_200HZ (DATA_RATE_2500US) #define HYB_DATA_RATE_100HZ (DATA_RATE_5MS) #define HYB_DATA_RATE_50HZ (DATA_RATE_10MS) #define HYB_DATA_RATE_25HZ (DATA_RATE_20MS) #define HYB_DATA_RATE_6_25HZ (DATA_RATE_80MS) #define HYB_DATA_RATE_3_15HZ (DATA_RATE_160MS) #define HYB_DATA_RATE_0_8HZ (DATA_RATE_640MS) #define ACTIVE (ACTIVE_MASK) #define STANDBY 0x00 /* CTRL_REG2 System Control 2 Register */ #define CTRL_REG2 0x2B #define ST_MASK 0x80 #define RST_MASK 0x40 #define SMODS1_MASK 0x10 #define SMODS0_MASK 0x08 #define SLPE_MASK 0x04 #define MODS1_MASK 0x02 #define MODS0_MASK 0x01 #define SMODS_MASK 0x18 #define MODS_MASK 0x03 #define SMOD_NORMAL 0x00 #define SMOD_LOW_NOISE (SMODS0_MASK) #define SMOD_HIGH_RES (SMODS1_MASK) #define SMOD_LOW_POWER (SMODS1_MASK + SMODS0_MASK) #define MOD_NORMAL 0x00 #define MOD_LOW_NOISE (MODS0_MASK) #define MOD_HIGH_RES (MODS1_MASK) #define MOD_LOW_POWER (MODS1_MASK + MODS0_MASK) /* CTRL_REG3 Interrupt Control Register */ #define CTRL_REG3 0x2C #define FIFO_GATE_MASK 0x80 #define WAKE_TRANS_MASK 0x40 #define WAKE_LNDPRT_MASK 0x20 #define WAKE_PULSE_MASK 0x10 #define WAKE_FF_MT_MASK 0x08 #define IPOL_MASK 0x02 #define PP_OD_MASK 0x01 /* CTRL_REG4 Interrupt Enable Register */ #define CTRL_REG4 0x2D #define INT_EN_ASLP_MASK 0x80 #define INT_EN_FIFO_MASK 0x40 #define INT_EN_TRANS_MASK 0x20 #define INT_EN_LNDPRT_MASK 0x10 #define INT_EN_PULSE_MASK 0x08 #define INT_EN_FF_MT_MASK 0x04 #define INT_EN_DRDY_MASK 0x01 /* CTRL_REG5 Interrupt Configuration Register */ #define CTRL_REG5 0x2E #define INT_CFG_ASLP_MASK 0x80 #define INT_CFG_FIFO_MASK 0x40 #define INT_CFG_TRANS_MASK 0x20 #define INT_CFG_LNDPRT_MASK 0x10 #define INT_CFG_PULSE_MASK 0x08 #define INT_CFG_FF_MT_MASK 0x04 #define INT_CFG_DRDY_MASK 0x01 /* XYZ Offset Correction Registers */ #define OFF_X_REG 0x2F #define OFF_Y_REG 0x30 #define OFF_Z_REG 0x31 /* M_DR_STATUS Register */ #define M_DR_STATUS_REG 0x32 #define ZYXOW_MASK 0x80 #define ZOW_MASK 0x40 #define YOW_MASK 0x20 #define XOW_MASK 0x10 #define ZYXDR_MASK 0x08 #define ZDR_MASK 0x04 #define YDR_MASK 0x02 #define XDR_MASK 0x01 /* MAG XYZ Data Registers */ #define M_OUT_X_MSB_REG 0x33 #define M_OUT_X_LSB_REG 0x34 #define M_OUT_Y_MSB_REG 0x35 #define M_OUT_Y_LSB_REG 0x36 #define M_OUT_Z_MSB_REG 0x37 #define M_OUT_Z_LSB_REG 0x38 /* MAG CMP Data Registers */ #define CMP_X_MSB_REG 0x39 #define CMP_X_LSB_REG 0x3A #define CMP_Y_MSB_REG 0x3B #define CMP_Y_LSB_REG 0x3C #define CMP_Z_MSB_REG 0x3D #define CMP_Z_LSB_REG 0x3E /* MAG XYZ Offset Correction Registers */ #define M_OFF_X_MSB_REG 0x3F #define M_OFF_X_LSB_REG 0x40 #define M_OFF_Y_MSB_REG 0x41 #define M_OFF_Y_LSB_REG 0x42 #define M_OFF_Z_MSB_REG 0x43 #define M_OFF_Z_LSB_REG 0x44 /* MAG MAX XYZ Registers */ #define MAX_X_MSB_REG 0x45 #define MAX_X_LSB_REG 0x46 #define MAX_Y_MSB_REG 0x47 #define MAX_Y_LSB_REG 0x48 #define MAX_Z_MSB_REG 0x49 #define MAX_Z_LSB_REG 0x4A /* MAG MIN XYZ Registers */ #define MIN_X_MSB_REG 0x4B #define MIN_X_LSB_REG 0x4C #define MIN_Y_MSB_REG 0x4D #define MIN_Y_LSB_REG 0x4E #define MIN_Z_MSB_REG 0x4F #define MIN_Z_LSB_REG 0x50 /* TEMP Registers */ #define TEMP_REG 0x51 /* M_THS CONFIG Registers */ #define M_THS_CFG_REG 0x52 /* M_THS SRC Registers */ #define M_THS_SRC_REG 0x53 /* MAG THRESHOLD XYZ Registers */ #define M_THS_X_MSB_REG 0x54 #define M_THS_X_LSB_REG 0x55 #define M_THS_Y_MSB_REG 0x56 #define M_THS_Y_LSB_REG 0x57 #define M_THS_Z_MSB_REG 0x58 #define M_THS_Z_LSB_REG 0x59 /* M_THS COUNT Registers */ #define M_THS_COUNT 0x5A /* MAG CTRL_REG1 System Control 1 Register */ #define M_CTRL_REG1 0x5B #define M_ACAL_MASK 0x80 #define M_RST_MASK 0x40 #define M_OST_MASK 0x20 #define M_OSR2_MASK 0x10 #define M_OSR1_MASK 0x08 #define M_OSR0_MASK 0x04 #define M_HMS1_MASK 0x02 #define M_HMS0_MASK 0x01 #define M_OSR_MASK 0x1C #define M_HMS_MASK 0x03 /* OSR Selections */ #define M_OSR_1_56_HZ 0x00 #define M_OSR_6_25_HZ M_OSR0_MASK #define M_OSR_12_5_HZ M_OSR1_MASK #define M_OSR_50_HZ M_OSR1_MASK + M_OSR0_MASK #define M_OSR_100_HZ M_OSR2_MASK #define M_OSR_200_HZ M_OSR2_MASK + M_OSR0_MASK #define M_OSR_400_HZ M_OSR2_MASK + M_OSR1_MASK #define M_OSR_800_HZ M_OSR2_MASK + M_OSR1_MASK + M_OSR0_MASK /* Hybrid Mode Selection */ #define ACCEL_ACTIVE 0x00 #define MAG_ACTIVE M_HMS0_MASK #define HYBRID_ACTIVE (M_HMS1_MASK | M_HMS0_MASK) /* MAG CTRL_REG2 System Control 2 Register */ #define M_CTRL_REG2 0x5C #define M_HYB_AUTOINC_MASK 0x20 #define M_MAXMIN_DIS_MASK 0x10 #define M_MAXMIN_DIS_THS_MASK 0x08 #define M_MAXMIN_RST_MASK 0x04 #define M_RST_CNT1_MASK 0x02 #define M_RST_CNT0_MASK 0x01 /* Mag Auto-Reset De-Gauss Frequency */ #define RST_ODR_CYCLE 0x00 #define RST_16_ODR_CYCLE M_RST_CNT0_MASK #define RST_512_ODR_CYCLE M_RST_CNT1_MASK #define RST_DISABLED M_RST_CNT1_MASK + M_RST_CNT0_MASK /* MAG CTRL_REG3 System Control 3 Register */ #define M_CTRL_REG3 0x5D #define M_RAW_MASK 0x80 #define M_ASLP_OS_2_MASK 0x40 #define M_ASLP_OS_1_MASK 0x20 #define M_ASLP_OS_0_MASK 0x10 #define M_THS_XYZ_MASK 0x08 #define M_ST_Z_MASK 0x04 #define M_ST_XY1_MASK 0x02 #define M_ST_XY0_MASK 0x01 #define M_ASLP_OSR_MASK 0x70 #define M_ST_XY_MASK 0x03 /* OSR Selections */ #define M_ASLP_OSR_1_56_HZ 0x00 #define M_ASLP_OSR_6_25_HZ M_ASLP_OS_0_MASK #define M_ASLP_OSR_12_5_HZ M_ASLP_OS_1_MASK #define M_ASLP_OSR_50_HZ M_ASLP_OS_1_MASK + M_ASLP_OS_0_MASK #define M_ASLP_OSR_100_HZ M_ASLP_OS_2_MASK #define M_ASLP_OSR_200_HZ M_ASLP_OS_2_MASK + M_ASLP_OS_0_MASK #define M_ASLP_OSR_400_HZ M_ASLP_OS_2_MASK + M_ASLP_OS_1_MASK #define M_ASLP_OSR_800_HZ M_ASLP_OS_2_MASK + M_ASLP_OS_1_MASK + M_ASLP_OS_0_MASK /* MAG INT SOURCE Register */ #define M_INT_SOURCE 0x5E #define SRC_M_DRDY_MASK 0x04 #define SRC_M_VECM_MASK 0x02 #define SRC_M_THS_MASK 0x01 /* ACCEL VECTOR CONFIG Register */ #define A_VECM_CFG 0x5F #define A_VECM_INIT_CFG_MASK 0x40 #define A_VECM_INIT_EN_MASK 0x20 #define A_VECM_WAKE_EN_MASK 0x10 #define A_VECM_EN_MASK 0x08 #define A_VECM_UPDM_MASK 0x04 #define A_VECM_INITM_MASK 0x02 #define A_VECM_ELE_MASK 0x01 /* ACCEL VECTOR THS MSB AND LSB Register */ #define A_VECM_THS_MSB 0x60 #define A_VECM_DBCNTM_MASK 0x80 #define A_VECM_THS_LSB 0x61 /* ACCEL VECTOR CNT Register */ #define A_VECM_CNT 0x62 /* ACCEL INITIAL XYZ VECTORS Register */ #define A_VECM_INITX_MSB 0x63 #define A_VECM_INITX_LSB 0x64 #define A_VECM_INITY_MSB 0x65 #define A_VECM_INITY_LSB 0x66 #define A_VECM_INITZ_MSB 0x67 #define A_VECM_INITZ_LSB 0x68 /* MAG VECTOR CONFIG Register */ #define M_VECM_CFG 0x69 #define M_VECM_INIT_CFG_MASK 0x40 #define M_VECM_INIT_EN_MASK 0x20 #define M_VECM_WAKE_EN_MASK 0x10 #define M_VECM_EN_MASK 0x08 #define M_VECM_UPDM_MASK 0x04 #define M_VECM_INITM_MASK 0x02 #define M_VECM_ELE_MASK 0x01 /* MAG VECTOR THS MSB AND LSB Register */ #define M_VECM_THS_MSB 0x6A #define M_VECM_DBCNTM_MASK 0x80 #define M_VECM_THS_LSB 0x6B /* MAG VECTOR CNT Register */ #define M_VECM_CNT 0x6C /* MAG INITIAL XYZ VECTORS Register */ #define M_VECM_INITX_MSB 0x6D #define M_VECM_INITX_LSB 0x6E #define M_VECM_INITY_MSB 0x6F #define M_VECM_INITY_LSB 0x70 #define M_VECM_INITZ_MSB 0x71 #define M_VECM_INITZ_LSB 0x72 /* ACCEL FFMT THS X MSB AND LSB Register */ #define A_FFMT_THS_X_MSB 0x73 #define A_FFMT_THS_XYZ_EN_MASK 0x80 #define A_FFMT_THS_X_LSB 0x74 #define A_FFMT_THS_X_LSB_MASK 0xFC /* ACCEL FFMT THS Y MSB AND LSB Register */ #define A_FFMT_THS_Y_MSB 0x75 #define A_FFMT_THS_Y_EN_MASK 0x80 #define A_FFMT_THS_Y_LSB 0x76 #define A_FFMT_THS_Y_LSB_MASK 0xFC /* ACCEL FFMT THS Z MSB AND LSB Register */ #define A_FFMT_THS_Z_MSB 0x77 #define A_FFMT_THS_Z_EN_MASK 0x80 #define A_FFMT_THS_Z_LSB 0x78 #define A_FFMT_THS_Z_LSB_MASK 0xFC /* ACCEL TRANSIENT INIT Register */ #define A_TRAN_INIT_XYZ_MSB 0x79 #define A_TRAN_INIT_X_LSB 0x7A #define A_TRAN_INIT_Y_LSB 0x7B #define A_TRAN_INIT_Z_LSB 0x7C /*! @brief Define I2C access function. */ typedef status_t (*I2C_SendFunc_t)(uint8_t deviceAddress, uint32_t subAddress, uint8_t subaddressSize, uint32_t txBuff); typedef status_t (*I2C_ReceiveFunc_t)( uint8_t deviceAddress, uint32_t subAddress, uint8_t subaddressSize, uint8_t *rxBuff, uint8_t rxBuffSize); /*! @brief fxos8700cq configure definition. This structure should be global.*/ typedef struct _fxos_handle { /* Pointer to the user-defined I2C Send Data function. */ I2C_SendFunc_t I2C_SendFunc; /* Pointer to the user-defined I2C Receive Data function. */ I2C_ReceiveFunc_t I2C_ReceiveFunc; /* The I2C slave address . */ uint8_t slaveAddress; } fxos_handle_t; typedef struct _fxos8700cq_data { uint8_t accelXMSB; uint8_t accelXLSB; uint8_t accelYMSB; uint8_t accelYLSB; uint8_t accelZMSB; uint8_t accelZLSB; uint8_t magXMSB; uint8_t magXLSB; uint8_t magYMSB; uint8_t magYLSB; uint8_t magZMSB; uint8_t magZLSB; } fxos_data_t; /*! @brief fxos8700cq configure structure.*/ typedef struct _fxos_config { /* Pointer to the user-defined I2C Send Data function. */ I2C_SendFunc_t I2C_SendFunc; /* Pointer to the user-defined I2C Receive Data function. */ I2C_ReceiveFunc_t I2C_ReceiveFunc; /* The I2C slave address . */ uint8_t slaveAddress; } fxos_config_t; /*! * @addtogroup fxos_common * @{ */ #if defined(__cplusplus) extern "C" { #endif /*! * @brief Verify and initialize fxos_handleice: Hybrid mode with ODR=50Hz, Mag OSR=32, Acc OSR=Normal. * * @param fxos_handle The pointer to accel driver handle. * @param config The configuration structure pointer to accel. * * @return kStatus_Success if success or kStatus_Fail if error. */ status_t FXOS_Init(fxos_handle_t *fxos_handle, fxos_config_t *config); /*! * @brief Read data from sensors, assumes hyb_autoinc_mode is set in M_CTRL_REG2 * * @param fxos_handle The pointer to accel driver handle. * @param sensorData The pointer to the buffer to hold sensor data * * @return kStatus_Success if success or kStatus_Fail if error. */ status_t FXOS_ReadSensorData(fxos_handle_t *fxos_handle, fxos_data_t *sensorData); /*! * @brief Write value to register of sensor. * * @param handle The pointer to fxos8700cq driver handle. * @param reg Register address. * @param val Data want to write. * * @return kStatus_Success if success or kStatus_Fail if error. */ status_t FXOS_WriteReg(fxos_handle_t *handle, uint8_t reg, uint8_t val); /*! * @brief Read n bytes start at register from sensor. * * @param handle The pointer to fxos8700cq driver handle. * @param reg Register address. * @param val The pointer to address which store data. * @param bytesNumber Number of bytes receiver. * * @return kStatus_Success if success or kStatus_Fail if error. */ status_t FXOS_ReadReg(fxos_handle_t *handle, uint8_t reg, uint8_t *val, uint8_t bytesNumber); /*! * @brief Get device accelerator resolution bits. * * @return accelerator resolution bits. */ static inline uint8_t FXOS_GetResolutionBits(void) { return FXOS8700CQ_ACCEL_RESOLUTION_BITS; } #if defined(__cplusplus) } #endif /* __cplusplus */ #endif /* _FSL_FXOS_H_ */
9,235
5,364
{ "name": "<NAME>", "remark": "Showcasing bad cryptography", "url": "http://cryptofails.com" }
45
302
<reponame>sesu089/stackoverflow #include "login.h" #include "ui_login.h" Login::Login(QWidget *parent) : QDialog(parent), ui(new Ui::Login) { ui->setupUi(this); } Login::~Login() { delete ui; } void Login::on_buttonBox_accepted() { User user("1", "2", "3", "4", "5"); emit accept(user); close(); }
130
1,668
# -*- coding: utf-8 -*- from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from ralph.lib.permissions.tests.models import Article, Library, LongArticle class PermissionsTestMixin(object): def _create_users_and_articles(self): self.user1 = get_user_model().objects.create(username='user1') self.user2 = get_user_model().objects.create(username='user2') self.user3 = get_user_model().objects.create(username='user3') self.superuser = get_user_model().objects.create( username='superuser', is_superuser=True ) content_types = [ContentType.objects.get_for_model(m) for m in ( Article, LongArticle, Library, )] base_permissions = Permission.objects.filter( content_type__in=content_types ) for user in (self.user1, self.user2, self.user3): user.user_permissions.add(*base_permissions) # remove some permissions: # user1 doesn't have access to custome_field_1 at all self.user1.user_permissions.remove(Permission.objects.get( content_type=ContentType.objects.get_for_model(Article), codename='change_article_custom_field_1_field' )) self.user1.user_permissions.remove(Permission.objects.get( content_type=ContentType.objects.get_for_model(Article), codename='view_article_custom_field_1_field' )) # user3 doesn't have change permissions on custom_field_1 self.user3.user_permissions.remove(Permission.objects.get( content_type=ContentType.objects.get_for_model(Article), codename='change_article_custom_field_1_field' )) # create two articles for each user self.article_1 = Article.objects.create( author=self.user1, title='1', content='1'*10, custom_field_1='test value', ) self.article_2 = Article.objects.create( author=self.user2, title='2', content='2'*10, ) self.article_3 = Article.objects.create( author=self.user3, title='3', content='3'*10, custom_field_1='test value 2', ) # create group article self.article_1.collaborators.add(self.user2) # create article with long title self.long_article = LongArticle.objects.create( author=self.user1, title='####### long article ########', content='lorem ipsum', custom_field_1='ipsum lorem', ) self.long_article_2 = LongArticle.objects.create( author=self.user1, title='short', content='lorem ipsum', custom_field_2=self.article_1, )
1,347
392
<filename>src/arch/x64/x64-codegen.h /* * x64-codegen.h: Macros for generating x86-64 code * * Authors: * <NAME> (<EMAIL>) * Intel Corporation (ORP Project) * <NAME> (<EMAIL>) * <NAME> (<EMAIL>) * <NAME> * <NAME> * * Copyright (C) 2000 Intel Corporation. All rights reserved. * Copyright (C) 2001, 2002 Ximian, Inc. */ #ifndef X64_H #define X64_H #include "../x86/x86-codegen.h" #include <stdint.h> /* x86-64 general purpose registers */ typedef enum { X64_RAX = 0, X64_RCX = 1, X64_RDX = 2, X64_RBX = 3, X64_RSP = 4, X64_RBP = 5, X64_RSI = 6, X64_RDI = 7, X64_R8 = 8, X64_R9 = 9, X64_R10 = 10, X64_R11 = 11, X64_R12 = 12, X64_R13 = 13, X64_R14 = 14, X64_R15 = 15, X64_RIP = 16, X64_NREG } X64_Reg_No; /* x86-64 XMM registers */ typedef enum { X64_XMM0 = 0, X64_XMM1 = 1, X64_XMM2 = 2, X64_XMM3 = 3, X64_XMM4 = 4, X64_XMM5 = 5, X64_XMM6 = 6, X64_XMM7 = 7, X64_XMM8 = 8, X64_XMM9 = 9, X64_XMM10 = 10, X64_XMM11 = 11, X64_XMM12 = 12, X64_XMM13 = 13, X64_XMM14 = 14, X64_XMM15 = 15, X64_XMM_NREG = 16, } X64_XMM_Reg_No; typedef enum { X64_REX_B = 1, /* The register in r/m field, base register in SIB byte, or reg in opcode is 8-15 rather than 0-7 */ X64_REX_X = 2, /* The index register in SIB byte is 8-15 rather than 0-7 */ X64_REX_R = 4, /* The reg field of ModRM byte is 8-15 rather than 0-7 */ X64_REX_W = 8 /* Opeartion is 64-bits instead of 32 (default) or 16 (with 0x66 prefix) */ } X64_REX_Bits; #if defined(__native_client_codegen__) #define x64_codegen_pre(inst) uint8_t* _codegen_start = (inst); x64_nacl_instruction_pre(); #define x64_codegen_post(inst) (x64_nacl_instruction_post(&_codegen_start, &(inst)), _codegen_start); /* Because of rex prefixes, etc, call sequences are not constant size. */ /* These pre- and post-sequence hooks remedy this by aligning the call */ /* sequence after we emit it, since we will know the exact size then. */ #define x64_call_sequence_pre(inst) uint8_t* _code_start = (inst); #define x64_call_sequence_post(inst) \ (mono_nacl_align_call(&_code_start, &(inst)), _code_start); /* Native client can load/store using one of the following registers */ /* as a base: rip, r15, rbp, rsp. Any other base register needs to have */ /* its upper 32 bits cleared and reference memory using r15 as the base. */ #define x64_is_valid_nacl_base(reg) \ ((reg) == X64_RIP || (reg) == X64_R15 || \ (reg) == X64_RBP || (reg) == X64_RSP) #else #define x64_codegen_pre(inst) #define x64_codegen_post(inst) #endif /* __native_client_codegen__ */ #ifdef TARGET_WIN32 #define X64_ARG_REG1 X64_RCX #define X64_ARG_REG2 X64_RDX #define X64_ARG_REG3 X64_R8 #define X64_ARG_REG4 X64_R9 #else #define X64_ARG_REG1 X64_RDI #define X64_ARG_REG2 X64_RSI #define X64_ARG_REG3 X64_RDX #define X64_ARG_REG4 X64_RCX #endif #ifdef TARGET_WIN32 #define X64_CALLEE_REGS ((1 << X64_RAX) | (1 << X64_RCX) | (1 << X64_RDX) | (1 << X64_R8) | (1 << X64_R9) | (1 << X64_R10)) #define X64_IS_CALLEE_REG(reg) (X64_CALLEE_REGS & (1 << (reg))) #define X64_ARGUMENT_REGS ((1 << X64_RDX) | (1 << X64_RCX) | (1 << X64_R8) | (1 << X64_R9)) #define X64_IS_ARGUMENT_REG(reg) (X64_ARGUMENT_REGS & (1 << (reg))) #define X64_CALLEE_SAVED_REGS ((1 << X64_RDI) | (1 << X64_RSI) | (1 << X64_RBX) | (1 << X64_R12) | (1 << X64_R13) | (1 << X64_R14) | (1 << X64_R15) | (1 << X64_RBP)) #define X64_IS_CALLEE_SAVED_REG(reg) (X64_CALLEE_SAVED_REGS & (1 << (reg))) #elif defined(__native_client_codegen__) /* x64 Native Client code may not write R15 */ #define X64_CALLEE_REGS ((1 << X64_RAX) | (1 << X64_RCX) | (1 << X64_RDX) | (1 << X64_RSI) | (1 << X64_RDI) | (1 << X64_R8) | (1 << X64_R9) | (1 << X64_R10)) #define X64_IS_CALLEE_REG(reg) (X64_CALLEE_REGS & (1 << (reg))) #define X64_ARGUMENT_REGS ((1 << X64_RDI) | (1 << X64_RSI) | (1 << X64_RDX) | (1 << X64_RCX) | (1 << X64_R8) | (1 << X64_R9)) #define X64_IS_ARGUMENT_REG(reg) (X64_ARGUMENT_REGS & (1 << (reg))) #define X64_CALLEE_SAVED_REGS ((1 << X64_RBX) | (1 << X64_R12) | (1 << X64_R13) | (1 << X64_R14) | (1 << X64_RBP)) #define X64_IS_CALLEE_SAVED_REG(reg) (X64_CALLEE_SAVED_REGS & (1 << (reg))) #else #define X64_CALLEE_REGS ((1 << X64_RAX) | (1 << X64_RCX) | (1 << X64_RDX) | (1 << X64_RSI) | (1 << X64_RDI) | (1 << X64_R8) | (1 << X64_R9) | (1 << X64_R10)) #define X64_IS_CALLEE_REG(reg) (X64_CALLEE_REGS & (1 << (reg))) #define X64_ARGUMENT_REGS ((1 << X64_RDI) | (1 << X64_RSI) | (1 << X64_RDX) | (1 << X64_RCX) | (1 << X64_R8) | (1 << X64_R9)) #define X64_IS_ARGUMENT_REG(reg) (X64_ARGUMENT_REGS & (1 << (reg))) #define X64_CALLEE_SAVED_REGS ((1 << X64_RBX) | (1 << X64_R12) | (1 << X64_R13) | (1 << X64_R14) | (1 << X64_R15) | (1 << X64_RBP)) #define X64_IS_CALLEE_SAVED_REG(reg) (X64_CALLEE_SAVED_REGS & (1 << (reg))) #endif #define X64_REX(bits) ((unsigned char)(0x40 | (bits))) #if defined(__native_client_codegen__) #define x64_emit_rex(inst, width, reg_modrm, reg_index, reg_rm_base_opcode) do \ { \ unsigned char _x64_rex_bits = \ (((width) > 4) ? X64_REX_W : 0) | \ (((reg_modrm) > 7) ? X64_REX_R : 0) | \ (((reg_index) > 7) ? X64_REX_X : 0) | \ (((reg_rm_base_opcode) > 7) ? X64_REX_B : 0); \ x64_nacl_tag_rex((inst)); \ if ((_x64_rex_bits != 0) || (((width) == 1))) *(inst)++ = X64_REX(_x64_rex_bits); \ } while (0) #else #define x64_emit_rex(inst, width, reg_modrm, reg_index, reg_rm_base_opcode) do \ { \ unsigned char _x64_rex_bits = \ (((width) > 4) ? X64_REX_W : 0) | \ (((reg_modrm) > 7) ? X64_REX_R : 0) | \ (((reg_index) > 7) ? X64_REX_X : 0) | \ (((reg_rm_base_opcode) > 7) ? X64_REX_B : 0); \ if ((_x64_rex_bits != 0) || (((width) == 1))) *(inst)++ = X64_REX(_x64_rex_bits); \ } while (0) #endif /* __native_client_codegen__ */ typedef union { uint64_t val; unsigned char b[8]; } x64_imm_buf; /* In 64 bit mode, all registers have a low byte subregister */ #undef X86_IS_BYTE_REG #define X86_IS_BYTE_REG(reg) 1 #define x64_modrm_mod(modrm) ((modrm) >> 6) #define x64_modrm_reg(modrm) (((modrm) >> 3) & 0x7) #define x64_modrm_rm(modrm) ((modrm) & 0x7) #define x64_rex_r(rex) ((((rex) >> 2) & 0x1) << 3) #define x64_rex_x(rex) ((((rex) >> 1) & 0x1) << 3) #define x64_rex_b(rex) ((((rex) >> 0) & 0x1) << 3) #define x64_sib_scale(sib) ((sib) >> 6) #define x64_sib_index(sib) (((sib) >> 3) & 0x7) #define x64_sib_base(sib) ((sib) & 0x7) #define x64_is_imm32(val) ((int64_t)val >= -((int64_t)1<<31) && (int64_t)val <= (((int64_t)1<<31)-1)) #define x86_imm_emit64(inst,imm) \ do { \ x64_imm_buf imb; \ imb.val = (uint64_t) (imm); \ *(inst)++ = imb.b [0]; \ *(inst)++ = imb.b [1]; \ *(inst)++ = imb.b [2]; \ *(inst)++ = imb.b [3]; \ *(inst)++ = imb.b [4]; \ *(inst)++ = imb.b [5]; \ *(inst)++ = imb.b [6]; \ *(inst)++ = imb.b [7]; \ } while (0) #define x64_membase_emit(inst,reg,basereg,disp) do { \ if ((basereg) == X64_RIP) { \ x86_address_byte ((inst), 0, (reg)&0x7, 5); \ x86_imm_emit32 ((inst), (disp)); \ } \ else \ x86_membase_emit ((inst),(reg)&0x7, (basereg)&0x7, (disp)); \ } while (0) #define x64_memindex_emit(inst, reg, basereg, disp, indexreg, shift) \ x86_memindex_emit((inst), ((reg) & 0x7), ((basereg) & 0x7), (disp), ((indexreg) & 0x7), (shift)) #define x64_alu_reg_imm_size_body(inst,opc,reg,imm,size) \ do { \ if (x86_is_imm8((imm))) { \ x64_emit_rex(inst, size, 0, 0, (reg)); \ *(inst)++ = (unsigned char)0x83; \ x86_reg_emit ((inst), (opc), (reg)); \ x86_imm_emit8 ((inst), (imm)); \ } else if ((reg) == X64_RAX) { \ x64_emit_rex(inst, size, 0, 0, 0); \ *(inst)++ = (((unsigned char)(opc)) << 3) + 5; \ x86_imm_emit32 ((inst), (imm)); \ } else { \ x64_emit_rex(inst, size, 0, 0, (reg)); \ *(inst)++ = (unsigned char)0x81; \ x86_reg_emit ((inst), (opc), (reg)); \ x86_imm_emit32 ((inst), (imm)); \ } \ } while (0) #define x64_alu_reg_reg_size_body(inst,opc,dreg,reg,size) \ do { \ x64_emit_rex(inst, size, (dreg), 0, (reg)); \ *(inst)++ = (((unsigned char)(opc)) << 3) + 3; \ x86_reg_emit ((inst), (dreg), (reg)); \ } while (0) #if defined(__native_client_codegen__) /* NaCl modules may not directly update RSP or RBP other than direct copies */ /* between them. Instead the lower 4 bytes are updated and then added to R15 */ #define x64_is_nacl_stack_reg(reg) (((reg) == X64_RSP) || ((reg) == X64_RBP)) #define x64_alu_reg_imm_size(inst,opc,reg,imm,size) \ do{ \ x64_codegen_pre(inst); \ if (x64_is_nacl_stack_reg(reg)) { \ if (((opc) != X86_ADD) && ((opc) != X86_SUB)) \ g_assert_not_reached(); \ x64_alu_reg_imm_size_body((inst), (opc), (reg), (imm), 4); \ /* Use LEA instead of ADD to preserve flags */ \ x64_lea_memindex_size((inst), (reg), (reg), 0, X64_R15, 0, 8); \ } else { \ x64_alu_reg_imm_size_body((inst), (opc), (reg), (imm), (size)); \ } \ x64_codegen_post(inst); \ } while(0) #define x64_alu_reg_reg_size(inst,opc,dreg,reg,size) \ do { \ x64_codegen_pre(inst); \ if (x64_is_nacl_stack_reg((dreg)) && ((reg) != X64_R15)) { \ if (((opc) != X86_ADD && (opc) != X86_SUB)) \ g_assert_not_reached(); \ x64_alu_reg_reg_size_body((inst), (opc), (dreg), (reg), 4); \ /* Use LEA instead of ADD to preserve flags */ \ x64_lea_memindex_size((inst), (dreg), (dreg), 0, X64_R15, 0, 8); \ } else { \ x64_alu_reg_reg_size_body((inst), (opc), (dreg), (reg), (size)); \ } \ x64_codegen_post(inst); \ } while (0) #else #define x64_alu_reg_imm_size(inst,opc,reg,imm,size) \ x64_alu_reg_imm_size_body((inst), (opc), (reg), (imm), (size)) #define x64_alu_reg_reg_size(inst,opc,dreg,reg,size) \ x64_alu_reg_reg_size_body((inst), (opc), (dreg), (reg), (size)) #endif /*__native_client_codegen__*/ #define x64_alu_reg_imm(inst,opc,reg,imm) x64_alu_reg_imm_size((inst),(opc),(reg),(imm),8) #define x64_alu_reg_reg(inst,opc,dreg,reg) x64_alu_reg_reg_size ((inst),(opc),(dreg),(reg),8) #define x64_alu_reg_membase_size(inst,opc,reg,basereg,disp,size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst),(size),(reg),0,(basereg)); \ *(inst)++ = (((unsigned char)(opc)) << 3) + 3; \ x64_membase_emit (inst, reg, basereg, disp); \ x64_codegen_post(inst); \ } while (0) #define x64_mov_regp_reg(inst,regp,reg,size) \ do { \ x64_codegen_pre(inst); \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size), (reg), 0, (regp)); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x88; break; \ case 2: case 4: case 8: *(inst)++ = (unsigned char)0x89; break; \ default: assert (0); \ } \ x86_regp_emit ((inst), (reg), (regp)); \ x64_codegen_post(inst); \ } while (0) #define x64_mov_membase_reg(inst,basereg,disp,reg,size) \ do { \ x64_codegen_pre(inst); \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size), (reg), 0, (basereg)); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x88; break; \ case 2: case 4: case 8: *(inst)++ = (unsigned char)0x89; break; \ default: assert (0); \ } \ x86_membase_emit ((inst), ((reg)&0x7), ((basereg)&0x7), (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_mov_mem_reg(inst,mem,reg,size) \ do { \ x64_codegen_pre(inst); \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size), (reg), 0, 0); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x88; break; \ case 2: case 4: case 8: *(inst)++ = (unsigned char)0x89; break; \ default: assert (0); \ } \ x86_address_byte ((inst), 0, (reg), 4); \ x86_address_byte ((inst), 0, 4, 5); \ x86_imm_emit32 ((inst), (mem)); \ x64_codegen_post(inst); \ } while (0) #define x64_mov_reg_reg(inst,dreg,reg,size) \ do { \ x64_codegen_pre(inst); \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size), (dreg), 0, (reg)); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x8a; break; \ case 2: case 4: case 8: *(inst)++ = (unsigned char)0x8b; break; \ default: assert (0); \ } \ x86_reg_emit ((inst), (dreg), (reg)); \ x64_codegen_post(inst); \ } while (0) #define x64_mov_reg_mem_body(inst,reg,mem,size) \ do { \ x64_codegen_pre(inst); \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size), (reg), 0, 0); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x8a; break; \ case 2: case 4: case 8: *(inst)++ = (unsigned char)0x8b; break; \ default: assert (0); \ } \ x86_address_byte ((inst), 0, (reg), 4); \ x86_address_byte ((inst), 0, 4, 5); \ x86_imm_emit32 ((inst), (mem)); \ x64_codegen_post(inst); \ } while (0) #if defined(__native_client_codegen__) /* We have to re-base memory reads because memory isn't zero based. */ #define x64_mov_reg_mem(inst,reg,mem,size) \ do { \ x64_mov_reg_membase((inst),(reg),X64_R15,(mem),(size)); \ } while (0) #else #define x64_mov_reg_mem(inst,reg,mem,size) \ do { \ x64_mov_reg_mem_body((inst),(reg),(mem),(size)); \ } while (0) #endif /* __native_client_codegen__ */ #define x64_mov_reg_membase_body(inst,reg,basereg,disp,size) \ do { \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size), (reg), 0, (basereg)); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x8a; break; \ case 2: case 4: case 8: *(inst)++ = (unsigned char)0x8b; break; \ default: assert (0); \ } \ x64_membase_emit ((inst), (reg), (basereg), (disp)); \ } while (0) #define x64_mov_reg_memindex_size_body(inst,reg,basereg,disp,indexreg,shift,size) \ do { \ x64_emit_rex ((inst),(size),(reg),(indexreg),(basereg)); \ x86_mov_reg_memindex((inst),((reg)&0x7),((basereg)&0x7),(disp),((indexreg)&0x7),(shift),(size) == 8 ? 4 : (size)); \ } while (0) #if defined(__native_client_codegen__) #define x64_mov_reg_memindex_size(inst,reg,basereg,disp,indexreg,shift,size) \ do { \ x64_codegen_pre(inst); \ if (x64_is_nacl_stack_reg((reg))) { \ /* Clear upper 32 bits with mov of size 4 */ \ x64_mov_reg_memindex_size_body((inst), (reg), (basereg), (disp), (indexreg), (shift), 4); \ /* Add %r15 using LEA to preserve flags */ \ x64_lea_memindex_size((inst), (reg), (reg), 0, X64_R15, 0, 8); \ } else { \ x64_mov_reg_memindex_size_body((inst), (reg), (basereg), (disp), (indexreg), (shift), (size)); \ } \ x64_codegen_post(inst); \ } while(0) #define x64_mov_reg_membase(inst,reg,basereg,disp,size) \ do { \ x64_codegen_pre(inst); \ if (x64_is_nacl_stack_reg((reg))) { \ /* Clear upper 32 bits with mov of size 4 */ \ x64_mov_reg_membase_body((inst), (reg), (basereg), (disp), 4); \ /* Add %r15 */ \ x64_lea_memindex_size((inst), (reg), (reg), 0, X64_R15, 0, 8); \ } else { \ x64_mov_reg_membase_body((inst), (reg), (basereg), (disp), (size)); \ } \ x64_codegen_post(inst); \ } while (0) #else #define x64_mov_reg_memindex_size(inst,reg,basereg,disp,indexreg,shift,size) \ x64_mov_reg_memindex_size_body((inst),(reg),(basereg),(disp),(indexreg),(shift),(size)) #define x64_mov_reg_membase(inst,reg,basereg,disp,size) \ do { \ x64_mov_reg_membase_body((inst), (reg), (basereg), (disp), (size)); \ } while (0) #endif /*__native_client_codegen__*/ #define x64_movzx_reg_membase(inst,reg,basereg,disp,size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst, (size), (reg), 0, (basereg)); \ switch ((size)) { \ case 1: *(inst)++ = (unsigned char)0x0f; *(inst)++ = (unsigned char)0xb6; break; \ case 2: *(inst)++ = (unsigned char)0x0f; *(inst)++ = (unsigned char)0xb7; break; \ case 4: case 8: *(inst)++ = (unsigned char)0x8b; break; \ default: assert (0); \ } \ x86_membase_emit ((inst), ((reg)&0x7), ((basereg)&0x7), (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_movsxd_reg_mem(inst,reg,mem) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst,8,(reg),0,0); \ *(inst)++ = (unsigned char)0x63; \ x86_mem_emit ((inst), ((reg)&0x7), (mem)); \ x64_codegen_post(inst); \ } while (0) #define x64_movsxd_reg_membase(inst,reg,basereg,disp) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst,8,(reg),0,(basereg)); \ *(inst)++ = (unsigned char)0x63; \ x86_membase_emit ((inst), ((reg)&0x7), ((basereg)&0x7), (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_movsxd_reg_memindex(inst, reg, basereg, disp, indexreg, shift) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst,8,(reg),0,(basereg)); \ *(inst)++ = (unsigned char)0x63; \ x64_memindex_emit((inst), (reg), (basereg), (disp), (indexreg), (shift)); \ x64_codegen_post(inst); \ } while (0) #define x64_movsxd_reg_reg(inst,dreg,reg) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst,8,(dreg),0,(reg)); \ *(inst)++ = (unsigned char)0x63; \ x86_reg_emit ((inst), (dreg), (reg)); \ x64_codegen_post(inst); \ } while (0) /* Pretty much the only instruction that supports a 64-bit immediate. Optimize for common case of * 32-bit immediate. Pepper with casts to avoid warnings. */ #define x64_mov_reg_imm_size(inst,reg,imm,size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst, (size), 0, 0, (reg)); \ *(inst)++ = (unsigned char)0xb8 + ((reg) & 0x7); \ if ((size) == 8) \ x86_imm_emit64 ((inst), (uint64_t)(imm)); \ else \ x86_imm_emit32 ((inst), (int)(uint64_t)(imm)); \ x64_codegen_post(inst); \ } while (0) #define x64_mov_reg_imm(inst,reg,imm) \ do { \ int _x64_width_temp = ((uint64_t)(imm) == (uint64_t)(int)(uint64_t)(imm)); \ x64_codegen_pre(inst); \ x64_mov_reg_imm_size ((inst), (reg), (imm), (_x64_width_temp ? 4 : 8)); \ x64_codegen_post(inst); \ } while (0) #define x64_set_reg_template(inst,reg) x64_mov_reg_imm_size ((inst),(reg), 0, 8) #define x64_set_template(inst,reg) x64_set_reg_template((inst),(reg)) #define x64_mov_membase_imm(inst,basereg,disp,imm,size) \ do { \ x64_codegen_pre(inst); \ if ((size) == 2) \ x86_prefix((inst), X86_OPERAND_PREFIX); \ x64_emit_rex(inst, (size) == 1 ? 0 : (size), 0, 0, (basereg)); \ if ((size) == 1) { \ *(inst)++ = (unsigned char)0xc6; \ x86_membase_emit ((inst), 0, (basereg) & 0x7, (disp)); \ x86_imm_emit8 ((inst), (imm)); \ } else if ((size) == 2) { \ *(inst)++ = (unsigned char)0xc7; \ x86_membase_emit ((inst), 0, (basereg) & 0x7, (disp)); \ x86_imm_emit16 ((inst), (imm)); \ } else { \ *(inst)++ = (unsigned char)0xc7; \ x86_membase_emit ((inst), 0, (basereg) & 0x7, (disp)); \ x86_imm_emit32 ((inst), (imm)); \ } \ x64_codegen_post(inst); \ } while (0) #define x64_lea_membase_body(inst,reg,basereg,disp) \ do { \ x64_emit_rex(inst, 8, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)0x8d; \ x64_membase_emit ((inst), (reg), (basereg), (disp)); \ } while (0) #if defined(__native_client_codegen__) /* NaCl modules may not write directly into RSP/RBP. Instead, use a */ /* 32-bit LEA and add R15 to the effective address */ #define x64_lea_membase(inst,reg,basereg,disp) \ do { \ x64_codegen_pre(inst); \ if (x64_is_nacl_stack_reg(reg)) { \ /* 32-bit LEA */ \ x64_emit_rex((inst), 4, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)0x8d; \ x64_membase_emit((inst), (reg), (basereg), (disp)); \ /* Use a 64-bit LEA instead of an ADD to preserve flags */ \ x64_lea_memindex_size((inst), (reg), (reg), 0, X64_R15, 0, 8); \ } else { \ x64_lea_membase_body((inst), (reg), (basereg), (disp)); \ } \ x64_codegen_post(inst); \ } while (0) #else #define x64_lea_membase(inst,reg,basereg,disp) \ x64_lea_membase_body((inst), (reg), (basereg), (disp)) #endif /*__native_client_codegen__*/ /* Instruction are implicitly 64-bits so don't generate REX for just the size. */ #define x64_push_reg(inst,reg) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst, 0, 0, 0, (reg)); \ *(inst)++ = (unsigned char)0x50 + ((reg) & 0x7); \ x64_codegen_post(inst); \ } while (0) /* Instruction is implicitly 64-bits so don't generate REX for just the size. */ #define x64_push_membase(inst,basereg,disp) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst, 0, 0, 0, (basereg)); \ *(inst)++ = (unsigned char)0xff; \ x86_membase_emit ((inst), 6, (basereg) & 0x7, (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_pop_reg_body(inst,reg) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex(inst, 0, 0, 0, (reg)); \ *(inst)++ = (unsigned char)0x58 + ((reg) & 0x7); \ x64_codegen_post(inst); \ } while (0) #if defined(__native_client_codegen__) /* Size is ignored for Native Client jumps, we restrict jumping to 32-bits */ #define x64_jump_reg_size(inst,reg,size) \ do { \ x64_codegen_pre((inst)); \ x64_alu_reg_imm_size((inst), X86_AND, (reg), (nacl_align_byte), 4); \ x64_alu_reg_reg_size((inst), X86_ADD, (reg), X64_R15, 8); \ x64_emit_rex ((inst),0,0,0,(reg)); \ x86_jump_reg((inst),((reg)&0x7)); \ x64_codegen_post((inst)); \ } while (0) /* Size is ignored for Native Client jumps, we restrict jumping to 32-bits */ #define x64_jump_mem_size(inst,mem,size) \ do { \ x64_codegen_pre((inst)); \ x64_mov_reg_mem((inst), (mem), X64_R11, 4); \ x64_jump_reg_size((inst), X64_R11, 4); \ x64_codegen_post((inst)); \ } while (0) #define x64_call_reg_internal(inst,reg) \ do { \ x64_codegen_pre((inst)); \ x64_alu_reg_imm_size((inst), X86_AND, (reg), (nacl_align_byte), 4); \ x64_alu_reg_reg_size((inst), X86_ADD, (reg), X64_R15, 8); \ x64_emit_rex((inst), 0, 0, 0, (reg)); \ x86_call_reg((inst), ((reg) & 0x7)); \ x64_codegen_post((inst)); \ } while (0) #define x64_call_reg(inst,reg) \ do { \ x64_codegen_pre((inst)); \ x64_call_sequence_pre(inst); \ x64_call_reg_internal((inst), (reg)); \ x64_call_sequence_post(inst); \ x64_codegen_post((inst)); \ } while (0) #define x64_ret(inst) \ do { \ x64_codegen_pre(inst); \ x64_pop_reg_body((inst), X64_R11); \ x64_jump_reg_size((inst), X64_R11, 8); \ x64_codegen_post(inst); \ } while (0) #define x64_leave(inst) \ do { \ x64_codegen_pre(inst); \ x64_mov_reg_reg((inst), X64_RSP, X64_RBP, 8); \ x64_pop_reg_body((inst), X64_R11); \ x64_mov_reg_reg_size((inst), X64_RBP, X64_R11, 4); \ x64_alu_reg_reg_size((inst), X86_ADD, X64_RBP, X64_R15, 8); \ x64_codegen_post(inst); \ } while (0) #define x64_pop_reg(inst,reg) \ do { \ x64_codegen_pre(inst); \ if (x64_is_nacl_stack_reg((reg))) { \ x64_pop_reg_body((inst), X64_R11); \ x64_mov_reg_reg_size((inst), (reg), X64_R11, 4); \ x64_alu_reg_reg_size((inst), X86_ADD, (reg), X64_R15, 8); \ } else { \ x64_pop_reg_body((inst), (reg)); \ } \ x64_codegen_post(inst); \ } while (0) #else #define x64_call_reg(inst,reg) \ do { \ x64_emit_rex(inst, 0, 0, 0, (reg)); \ *(inst)++ = (unsigned char)0xff; \ x86_reg_emit ((inst), 2, ((reg) & 0x7)); \ } while (0) #define x64_ret(inst) do { *(inst)++ = (unsigned char)0xc3; } while (0) #define x64_leave(inst) do { *(inst)++ = (unsigned char)0xc9; } while (0) #define x64_pop_reg(inst,reg) x64_pop_reg_body((inst), (reg)) #endif /*__native_client_codegen__*/ #define x64_movsd_reg_regp(inst,reg,regp) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf2); \ x64_emit_rex(inst, 0, (reg), 0, (regp)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x10; \ x86_regp_emit ((inst), (reg) & 0x7, (regp) & 0x7); \ x64_codegen_post(inst); \ } while (0) #define x64_movsd_regp_reg(inst,regp,reg) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf2); \ x64_emit_rex(inst, 0, (reg), 0, (regp)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x11; \ x86_regp_emit ((inst), (reg) & 0x7, (regp) & 0x7); \ x64_codegen_post(inst); \ } while (0) #define x64_movss_reg_regp(inst,reg,regp) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf3); \ x64_emit_rex(inst, 0, (reg), 0, (regp)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x10; \ x86_regp_emit ((inst), (reg) & 0x7, (regp) & 0x7); \ x64_codegen_post(inst); \ } while (0) #define x64_movss_regp_reg(inst,regp,reg) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf3); \ x64_emit_rex(inst, 0, (reg), 0, (regp)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x11; \ x86_regp_emit ((inst), (reg) & 0x7, (regp) & 0x7); \ x64_codegen_post(inst); \ } while (0) #define x64_movsd_reg_membase(inst,reg,basereg,disp) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf2); \ x64_emit_rex(inst, 0, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x10; \ x86_membase_emit ((inst), (reg) & 0x7, (basereg) & 0x7, (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_movss_reg_membase(inst,reg,basereg,disp) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf3); \ x64_emit_rex(inst, 0, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x10; \ x86_membase_emit ((inst), (reg) & 0x7, (basereg) & 0x7, (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_movsd_membase_reg(inst,basereg,disp,reg) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf2); \ x64_emit_rex(inst, 0, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x11; \ x86_membase_emit ((inst), (reg) & 0x7, (basereg) & 0x7, (disp)); \ x64_codegen_post(inst); \ } while (0) #define x64_movss_membase_reg(inst,basereg,disp,reg) \ do { \ x64_codegen_pre(inst); \ x86_prefix((inst), 0xf3); \ x64_emit_rex(inst, 0, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)0x0f; \ *(inst)++ = (unsigned char)0x11; \ x86_membase_emit ((inst), (reg) & 0x7, (basereg) & 0x7, (disp)); \ x64_codegen_post(inst); \ } while (0) /* The original inc_reg opcode is used as the REX prefix */ #define x64_inc_reg_size(inst,reg,size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst),(size),0,0,(reg)); \ *(inst)++ = (unsigned char)0xff; \ x86_reg_emit ((inst),0,(reg) & 0x7); \ x64_codegen_post(inst); \ } while (0) #define x64_dec_reg_size(inst,reg,size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst),(size),0,0,(reg)); \ *(inst)++ = (unsigned char)0xff; \ x86_reg_emit ((inst),1,(reg) & 0x7); \ x64_codegen_post(inst); \ } while (0) #define x64_fld_membase_size(inst,basereg,disp,is_double,size) do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst),0,0,0,(basereg)); \ *(inst)++ = (is_double) ? (unsigned char)0xdd : (unsigned char)0xd9; \ x64_membase_emit ((inst), 0, (basereg), (disp)); \ x64_codegen_post(inst); \ } while (0) #if defined(__native_client_codegen__) /* The 3-7 byte NOP sequences in x64_padding_size below are all illegal in */ /* 64-bit Native Client because they load into rSP/rBP or use duplicate */ /* prefixes. Instead we use the NOPs recommended in Section 3.5.1.8 of the */ /* Intel64 and IA-32 Architectures Optimization Reference Manual and */ /* Section 4.13 of AMD Software Optimization Guide for Family 10h Processors. */ #define x64_padding_size(inst,size) \ do { \ unsigned char *code_start = (inst); \ switch ((size)) { \ /* xchg %eax,%eax, recognized by hardware as a NOP */ \ case 1: *(inst)++ = 0x90; break; \ /* xchg %ax,%ax */ \ case 2: *(inst)++ = 0x66; *(inst)++ = 0x90; \ break; \ /* nop (%rax) */ \ case 3: *(inst)++ = 0x0f; *(inst)++ = 0x1f; \ *(inst)++ = 0x00; \ break; \ /* nop 0x0(%rax) */ \ case 4: *(inst)++ = 0x0f; *(inst)++ = 0x1f; \ x86_address_byte ((inst), 1, 0, X64_RAX); \ x86_imm_emit8 ((inst), 0); \ break; \ /* nop 0x0(%rax,%rax) */ \ case 5: *(inst)++ = 0x0f; *(inst)++ = 0x1f; \ x86_address_byte ((inst), 1, 0, 4); \ x86_address_byte ((inst), 0, X64_RAX, X64_RAX); \ x86_imm_emit8 ((inst), 0); \ break; \ /* nopw 0x0(%rax,%rax) */ \ case 6: *(inst)++ = 0x66; *(inst)++ = 0x0f; \ *(inst)++ = 0x1f; \ x86_address_byte ((inst), 1, 0, 4); \ x86_address_byte ((inst), 0, X64_RAX, X64_RAX); \ x86_imm_emit8 ((inst), 0); \ break; \ /* nop 0x0(%rax) (32-bit displacement) */ \ case 7: *(inst)++ = 0x0f; *(inst)++ = 0x1f; \ x86_address_byte ((inst), 2, 0, X64_RAX); \ x86_imm_emit32((inst), 0); \ break; \ /* nop 0x0(%rax,%rax) (32-bit displacement) */ \ case 8: *(inst)++ = 0x0f; *(inst)++ = 0x1f; \ x86_address_byte ((inst), 2, 0, 4); \ x86_address_byte ((inst), 0, X64_RAX, X64_RAX); \ x86_imm_emit32 ((inst), 0); \ break; \ default: \ g_assert_not_reached(); \ } \ g_assert(code_start + (size) == (unsigned char *)(inst)); \ } while (0) /* Size is ignored for Native Client calls, we restrict jumping to 32-bits */ #define x64_call_membase_size(inst,basereg,disp,size) \ do { \ x64_codegen_pre((inst)); \ x64_call_sequence_pre(inst); \ x64_mov_reg_membase((inst), X64_R11, (basereg), (disp), 4); \ x64_call_reg_internal((inst), X64_R11); \ x64_call_sequence_post(inst); \ x64_codegen_post((inst)); \ } while (0) /* Size is ignored for Native Client jumps, we restrict jumping to 32-bits */ #define x64_jump_membase_size(inst,basereg,disp,size) \ do { \ x64_mov_reg_membase((inst), X64_R11, (basereg), (disp), 4); \ x64_jump_reg_size((inst), X64_R11, 4); \ } while (0) /* On Native Client we can't jump more than INT_MAX in either direction */ #define x64_jump_code_size(inst,target,size) \ do { \ /* x86_jump_code used twice in case of */ \ /* relocation by x64_codegen_post */ \ uint8_t* jump_start; \ x64_codegen_pre(inst); \ assert(x64_is_imm32 ((int64_t)(target) - (int64_t)(inst))); \ x86_jump_code((inst),(target)); \ inst = x64_codegen_post(inst); \ jump_start = (inst); \ x86_jump_code((inst),(target)); \ mono_x64_patch(jump_start, (target)); \ } while (0) #else /* From the AMD64 Software Optimization Manual */ #define x64_padding_size(inst,size) \ do { \ switch ((size)) { \ case 1: *(inst)++ = 0x90; break; \ case 2: *(inst)++ = 0x66; *(inst)++ = 0x90; break; \ case 3: *(inst)++ = 0x66; *(inst)++ = 0x66; *(inst)++ = 0x90; break; \ default: x64_emit_rex ((inst),8,0,0,0); x86_padding ((inst), (size) - 1); \ }; \ } while (0) #define x64_call_membase_size(inst,basereg,disp,size) do { x64_emit_rex ((inst),0,0,0,(basereg)); *(inst)++ = (unsigned char)0xff; x64_membase_emit ((inst),2, (basereg),(disp)); } while (0) #define x64_jump_membase_size(inst,basereg,disp,size) do { x64_emit_rex ((inst),0,0,0,(basereg)); *(inst)++ = (unsigned char)0xff; x64_membase_emit ((inst), 4, (basereg), (disp)); } while (0) #define x64_jump_code_size(inst,target,size) do { \ if (x64_is_imm32 ((int64_t)(target) - (int64_t)(inst))) { \ x86_jump_code((inst),(target)); \ } else { \ x64_jump_membase ((inst), X64_RIP, 0); \ *(uint64_t*)(inst) = (uint64_t)(target); \ (inst) += 8; \ } \ } while (0) #endif /*__native_client_codegen__*/ /* * SSE */ //TODO Reorganize SSE opcode defines. /* Two opcode SSE defines */ #define emit_sse_reg_reg_op2(inst, dreg, reg, op1, op2) \ emit_sse_reg_reg_op2_size((inst), (dreg), (reg), (op1), (op2), 0) #define emit_sse_reg_reg_op2_size(inst, dreg, reg, op1, op2, size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst), size, (dreg), 0, (reg)); \ *(inst)++ = (unsigned char)(op1); \ *(inst)++ = (unsigned char)(op2); \ x86_reg_emit ((inst), (dreg), (reg)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_reg_reg_op2_imm(inst, dreg, reg, op1, op2, imm) \ do { \ x64_codegen_pre(inst); \ emit_sse_reg_reg_op2 ((inst), (dreg), (reg), (op1), (op2)); \ x86_imm_emit8 ((inst), (imm)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_membase_reg_op2(inst, basereg, disp, reg, op1, op2) \ emit_sse_membase_reg_op2_size((inst), (basereg), (disp), (reg), (op1), (op2), 0) #define emit_sse_membase_reg_op2_size(inst, basereg, disp, reg, op1, op2, size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst), (size), (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)(op1); \ *(inst)++ = (unsigned char)(op2); \ x64_membase_emit ((inst), (reg), (basereg), (disp)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_memindex_reg_op2(inst, basereg, disp, indexreg, shift, reg, op1, op2) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex (inst, 0, (reg), (indexreg), (basereg)); \ *(inst)++ = (unsigned char)(op1); \ *(inst)++ = (unsigned char)(op2); \ x64_memindex_emit((inst), (reg), (basereg), (disp), (indexreg), (shift)); \ x64_codegen_post(inst); \ } while(0) #define emit_sse_reg_membase_op2(inst, dreg, basereg, disp, op1, op2) \ emit_sse_reg_membase_op2_size((inst), (dreg), (basereg), (disp), (op1), (op2), 0) #define emit_sse_reg_membase_op2_size(inst, dreg, basereg, disp, op1, op2, size) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex ((inst), (size), (dreg), 0, (basereg) == X64_RIP ? 0 : (basereg)); \ *(inst)++ = (unsigned char)(op1); \ *(inst)++ = (unsigned char)(op2); \ x64_membase_emit ((inst), (dreg), (basereg), (disp)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_reg_memindex_op2(inst, dreg, basereg, disp, indexreg, shift, op1, op2) \ do { \ x64_codegen_pre(inst); \ x64_emit_rex (inst, 0, (dreg), (indexreg), (basereg) == X64_RIP ? 0 : (basereg)); \ *(inst)++ = (unsigned char)(op1); \ *(inst)++ = (unsigned char)(op2); \ x64_memindex_emit((inst), (dreg), (basereg), (disp), (indexreg), (shift)); \ x64_codegen_post(inst); \ } while(0) /* Three opcode SSE defines */ #define emit_opcode3(inst,op1,op2,op3) do { \ *(inst)++ = (unsigned char)(op1); \ *(inst)++ = (unsigned char)(op2); \ *(inst)++ = (unsigned char)(op3); \ } while (0) #define emit_sse_reg_reg_size(inst,dreg,reg,op1,op2,op3,size) do { \ x64_codegen_pre(inst); \ *(inst)++ = (unsigned char)(op1); \ x64_emit_rex ((inst), size, (dreg), 0, (reg)); \ *(inst)++ = (unsigned char)(op2); \ *(inst)++ = (unsigned char)(op3); \ x86_reg_emit ((inst), (dreg), (reg)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_reg_reg(inst,dreg,reg,op1,op2,op3) emit_sse_reg_reg_size ((inst), (dreg), (reg), (op1), (op2), (op3), 0) #define emit_sse_reg_reg_imm(inst,dreg,reg,op1,op2,op3,imm) do { \ x64_codegen_pre(inst); \ emit_sse_reg_reg ((inst), (dreg), (reg), (op1), (op2), (op3)); \ x86_imm_emit8 ((inst), (imm)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_membase_reg(inst,basereg,disp,reg,op1,op2,op3) do { \ x64_codegen_pre(inst); \ x86_prefix((inst), (unsigned char)(op1)); \ x64_emit_rex ((inst), 0, (reg), 0, (basereg)); \ *(inst)++ = (unsigned char)(op2); \ *(inst)++ = (unsigned char)(op3); \ x64_membase_emit ((inst), (reg), (basereg), (disp)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_reg_membase(inst,dreg,basereg,disp,op1,op2,op3) do { \ x64_codegen_pre(inst); \ x86_prefix((inst), (unsigned char)(op1)); \ x64_emit_rex ((inst), 0, (dreg), 0, (basereg) == X64_RIP ? 0 : (basereg)); \ *(inst)++ = (unsigned char)(op2); \ *(inst)++ = (unsigned char)(op3); \ x64_membase_emit ((inst), (dreg), (basereg), (disp)); \ x64_codegen_post(inst); \ } while (0) /* Four opcode SSE defines */ #define emit_sse_reg_reg_op4_size(inst,dreg,reg,op1,op2,op3,op4,size) do { \ x64_codegen_pre(inst); \ x86_prefix((inst), (unsigned char)(op1)); \ x64_emit_rex ((inst), size, (dreg), 0, (reg)); \ *(inst)++ = (unsigned char)(op2); \ *(inst)++ = (unsigned char)(op3); \ *(inst)++ = (unsigned char)(op4); \ x86_reg_emit ((inst), (dreg), (reg)); \ x64_codegen_post(inst); \ } while (0) #define emit_sse_reg_reg_op4(inst,dreg,reg,op1,op2,op3,op4) emit_sse_reg_reg_op4_size ((inst), (dreg), (reg), (op1), (op2), (op3), (op4), 0) /* specific SSE opcode defines */ #define x64_sse_xorpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst),(dreg),(reg), 0x66, 0x0f, 0x57) #define x64_sse_xorpd_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst),(dreg),(basereg), (disp), 0x66, 0x0f, 0x57) #define x64_sse_andpd_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst),(dreg),(basereg), (disp), 0x66, 0x0f, 0x54) #define x64_sse_movsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x10) #define x64_sse_movsd_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst), (dreg), (basereg), (disp), 0xf2, 0x0f, 0x10) #define x64_sse_movsd_membase_reg(inst,basereg,disp,reg) emit_sse_membase_reg ((inst), (basereg), (disp), (reg), 0xf2, 0x0f, 0x11) #define x64_sse_movss_membase_reg(inst,basereg,disp,reg) emit_sse_membase_reg ((inst), (basereg), (disp), (reg), 0xf3, 0x0f, 0x11) #define x64_sse_movss_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst), (dreg), (basereg), (disp), 0xf3, 0x0f, 0x10) #define x64_sse_comisd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst),(dreg),(reg),0x66,0x0f,0x2f) #define x64_sse_comisd_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst), (dreg), (basereg), (disp), 0x66, 0x0f, 0x2f) #define x64_sse_ucomisd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst),(dreg),(reg),0x66,0x0f,0x2e) #define x64_sse_cvtsd2si_reg_reg(inst,dreg,reg) emit_sse_reg_reg_size ((inst), (dreg), (reg), 0xf2, 0x0f, 0x2d, 8) #define x64_sse_cvttsd2si_reg_reg_size(inst,dreg,reg,size) emit_sse_reg_reg_size ((inst), (dreg), (reg), 0xf2, 0x0f, 0x2c, (size)) #define x64_sse_cvttsd2si_reg_reg(inst,dreg,reg) x64_sse_cvttsd2si_reg_reg_size ((inst), (dreg), (reg), 8) #define x64_sse_cvtsi2sd_reg_reg_size(inst,dreg,reg,size) emit_sse_reg_reg_size ((inst), (dreg), (reg), 0xf2, 0x0f, 0x2a, (size)) #define x64_sse_cvtsi2sd_reg_reg(inst,dreg,reg) x64_sse_cvtsi2sd_reg_reg_size ((inst), (dreg), (reg), 8) #define x64_sse_cvtsi2ss_reg_reg_size(inst,dreg,reg,size) emit_sse_reg_reg_size ((inst), (dreg), (reg), 0xf3, 0x0f, 0x2a, (size)) #define x64_sse_cvtsi2ss_reg_reg(inst,dreg,reg) x64_sse_cvtsi2ss_reg_reg_size ((inst), (dreg), (reg), 8) #define x64_sse_cvtsd2ss_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x5a) #define x64_sse_cvtss2sd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf3, 0x0f, 0x5a) #define x64_sse_addsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x58) #define x64_sse_subsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x5c) #define x64_sse_mulsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x59) #define x64_sse_divsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x5e) #define x64_sse_sqrtsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf2, 0x0f, 0x51) #define x64_sse_pinsrw_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm ((inst), (dreg), (reg), 0x66, 0x0f, 0xc4, (imm)) #define x64_sse_pextrw_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm ((inst), (dreg), (reg), 0x66, 0x0f, 0xc5, (imm)) #define x64_sse_cvttsd2si_reg_xreg_size(inst,reg,xreg,size) emit_sse_reg_reg_size ((inst), (reg), (xreg), 0xf2, 0x0f, 0x2c, (size)) #define x64_sse_addps_reg_reg(inst, dreg, reg) \ emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x58) #define x64_sse_addps_reg_reg_size(inst, dreg, reg, size) \ emit_sse_reg_reg_op2_size((inst), (dreg), (reg), 0x0f, 0x58, size) #define x64_sse_divps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x5e) #define x64_sse_mulps_reg_reg(inst, dreg, reg) \ emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x59) #define x64_sse_mulps_reg_reg_size(inst, dreg, reg, size) \ emit_sse_reg_reg_op2_size((inst), (dreg), (reg), 0x0f, 0x59, size) #define x64_sse_subps_reg_reg(inst, dreg, reg) \ emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x5c) #define x64_sse_subps_reg_reg_size(inst, dreg, reg, size) \ emit_sse_reg_reg_op2_size((inst), (dreg), (reg), 0x0f, 0x5c, size) #define x64_sse_maxps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x5f) #define x64_sse_minps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x5d) #define x64_sse_cmpps_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_op2_imm((inst), (dreg), (reg), 0x0f, 0xc2, (imm)) #define x64_sse_andps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x54) #define x64_sse_andnps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x55) #define x64_sse_orps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x56) #define x64_sse_xorps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x57) #define x64_sse_sqrtps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x51) #define x64_sse_rsqrtps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x52) #define x64_sse_rcpps_reg_reg(inst,dreg,reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x53) #define x64_sse_addsubps_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf2, 0x0f, 0xd0) #define x64_sse_haddps_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf2, 0x0f, 0x7c) #define x64_sse_hsubps_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf2, 0x0f, 0x7d) #define x64_sse_movshdup_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf3, 0x0f, 0x16) #define x64_sse_movsldup_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf3, 0x0f, 0x12) #define x64_sse_pshufhw_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm((inst), (dreg), (reg), 0xf3, 0x0f, 0x70, (imm)) #define x64_sse_pshuflw_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm((inst), (dreg), (reg), 0xf2, 0x0f, 0x70, (imm)) #define x64_sse_pshufd_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm((inst), (dreg), (reg), 0x66, 0x0f, 0x70, (imm)) #define x64_sse_shufps_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_op2_imm((inst), (dreg), (reg), 0x0f, 0xC6, (imm)) #define x64_sse_shufpd_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm((inst), (dreg), (reg), 0x66, 0x0f, 0xC6, (imm)) #define x64_sse_addpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x58) #define x64_sse_divpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x5e) #define x64_sse_mulpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x59) #define x64_sse_subpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x5c) #define x64_sse_maxpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x5f) #define x64_sse_minpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x5d) #define x64_sse_cmppd_reg_reg_imm(inst,dreg,reg,imm) emit_sse_reg_reg_imm((inst), (dreg), (reg), 0x66, 0x0f, 0xc2, (imm)) #define x64_sse_andpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x54) #define x64_sse_andnpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x55) #define x64_sse_orpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x56) #define x64_sse_sqrtpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x51) #define x64_sse_rsqrtpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x52) #define x64_sse_rcppd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x53) #define x64_sse_addsubpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd0) #define x64_sse_haddpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x7c) #define x64_sse_hsubpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x7d) #define x64_sse_movddup_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xf2, 0x0f, 0x12) #define x64_sse_pmovmskb_reg_reg(inst,dreg,reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd7) #define x64_sse_pand_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xdb) #define x64_sse_por_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xeb) #define x64_sse_pxor_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xef) #define x64_sse_paddb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xfc) #define x64_sse_paddw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xfd) #define x64_sse_paddd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xfe) #define x64_sse_paddq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd4) #define x64_sse_psubb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf8) #define x64_sse_psubw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf9) #define x64_sse_psubd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xfa) #define x64_sse_psubq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xfb) #define x64_sse_pmaxub_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xde) #define x64_sse_pmaxuw_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x3e) #define x64_sse_pmaxud_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x3f) #define x64_sse_pmaxsb_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x3c) #define x64_sse_pmaxsw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xee) #define x64_sse_pmaxsd_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x3d) #define x64_sse_pavgb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe0) #define x64_sse_pavgw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe3) #define x64_sse_pminub_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xda) #define x64_sse_pminuw_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x3a) #define x64_sse_pminud_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x3b) #define x64_sse_pminsb_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x38) #define x64_sse_pminsw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xea) #define x64_sse_pminsd_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x39) #define x64_sse_pcmpeqb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x74) #define x64_sse_pcmpeqw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x75) #define x64_sse_pcmpeqd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x76) #define x64_sse_pcmpeqq_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x29) #define x64_sse_pcmpgtb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x64) #define x64_sse_pcmpgtw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x65) #define x64_sse_pcmpgtd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x66) #define x64_sse_pcmpgtq_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x37) #define x64_sse_psadbw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf6) #define x64_sse_punpcklbw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x60) #define x64_sse_punpcklwd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x61) #define x64_sse_punpckldq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x62) #define x64_sse_punpcklqdq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x6c) #define x64_sse_unpcklpd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x14) #define x64_sse_unpcklps_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x14) #define x64_sse_punpckhbw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x68) #define x64_sse_punpckhwd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x69) #define x64_sse_punpckhdq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x6a) #define x64_sse_punpckhqdq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x6d) #define x64_sse_unpckhpd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x15) #define x64_sse_unpckhps_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x15) #define x64_sse_packsswb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x63) #define x64_sse_packssdw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x6b) #define x64_sse_packuswb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x67) #define x64_sse_packusdw_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x2b) #define x64_sse_paddusb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xdc) #define x64_sse_psubusb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd8) #define x64_sse_paddusw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xdd) #define x64_sse_psubusw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd8) #define x64_sse_paddsb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xec) #define x64_sse_psubsb_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe8) #define x64_sse_paddsw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xed) #define x64_sse_psubsw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe9) #define x64_sse_pmullw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd5) #define x64_sse_pmulld_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op4((inst), (dreg), (reg), 0x66, 0x0f, 0x38, 0x40) #define x64_sse_pmuludq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf4) #define x64_sse_pmulhuw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe4) #define x64_sse_pmulhw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe5) #define x64_sse_psrlw_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SHR, (reg), 0x66, 0x0f, 0x71, (imm)) #define x64_sse_psrlw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd1) #define x64_sse_psraw_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SAR, (reg), 0x66, 0x0f, 0x71, (imm)) #define x64_sse_psraw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe1) #define x64_sse_psllw_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SHL, (reg), 0x66, 0x0f, 0x71, (imm)) #define x64_sse_psllw_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf1) #define x64_sse_psrld_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SHR, (reg), 0x66, 0x0f, 0x72, (imm)) #define x64_sse_psrld_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd2) #define x64_sse_psrad_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SAR, (reg), 0x66, 0x0f, 0x72, (imm)) #define x64_sse_psrad_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe2) #define x64_sse_pslld_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SHL, (reg), 0x66, 0x0f, 0x72, (imm)) #define x64_sse_pslld_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf2) #define x64_sse_psrlq_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SHR, (reg), 0x66, 0x0f, 0x73, (imm)) #define x64_sse_psrlq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xd3) #define x64_sse_psraq_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SAR, (reg), 0x66, 0x0f, 0x73, (imm)) #define x64_sse_psraq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xe3) #define x64_sse_psllq_reg_imm(inst, reg, imm) emit_sse_reg_reg_imm((inst), X86_SSE_SHL, (reg), 0x66, 0x0f, 0x73, (imm)) #define x64_sse_psllq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0xf3) #define x64_sse_cvtdq2pd_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xF3, 0x0F, 0xE6) #define x64_sse_cvtdq2ps_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0F, 0x5B) #define x64_sse_cvtpd2dq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xF2, 0x0F, 0xE6) #define x64_sse_cvtpd2ps_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0F, 0x5A) #define x64_sse_cvtps2dq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0F, 0x5B) #define x64_sse_cvtps2pd_reg_reg(inst, dreg, reg) emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0F, 0x5A) #define x64_sse_cvttpd2dq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0F, 0xE6) #define x64_sse_cvttps2dq_reg_reg(inst, dreg, reg) emit_sse_reg_reg((inst), (dreg), (reg), 0xF3, 0x0F, 0x5B) #define x64_movd_xreg_reg_size(inst,dreg,sreg,size) emit_sse_reg_reg_size((inst), (dreg), (sreg), 0x66, 0x0f, 0x6e, (size)) #define x64_movd_reg_xreg_size(inst,dreg,sreg,size) emit_sse_reg_reg_size((inst), (sreg), (dreg), 0x66, 0x0f, 0x7e, (size)) #define x64_movd_xreg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase((inst), (dreg), (basereg), (disp), 0x66, 0x0f, 0x6e) #define x64_sse_movhlps_reg_reg(inst, dreg, sreg) \ emit_sse_reg_reg_op2((inst), (dreg), (sreg), 0x0f, 0x12) #define x64_sse_movhlps_reg_reg_size(inst, dreg, sreg, size) \ emit_sse_reg_reg_op2_size((inst), (dreg), (sreg), 0x0f, 0x12, size) #define x64_sse_movlhps_reg_reg(inst, dreg, sreg) \ emit_sse_reg_reg_op2((inst), (dreg), (sreg), 0x0f, 0x16) #define x64_sse_movlhps_reg_reg_size(inst, dreg, sreg, size) \ emit_sse_reg_reg_op2_size((inst), (dreg), (sreg), 0x0f, 0x16, size) #define x64_sse_movups_membase_reg(inst, basereg, disp, reg) \ emit_sse_membase_reg_op2((inst), (basereg), (disp), (reg), 0x0f, 0x11) #define x64_sse_movups_membase_reg_size(inst, basereg, disp, reg, size) \ emit_sse_membase_reg_op2_size((inst), (basereg), (disp), (reg), 0x0f, 0x11, (size)) #define x64_sse_movups_reg_membase(inst, dreg, basereg, disp) \ emit_sse_reg_membase_op2((inst), (dreg), (basereg), (disp), 0x0f, 0x10) #define x64_sse_movups_reg_membase_size(inst, dreg, basereg, disp, size) \ emit_sse_reg_membase_op2_size((inst), (dreg), (basereg), (disp), 0x0f, 0x10, (size)) #define x64_sse_movaps_membase_reg(inst, basereg, disp, reg) \ emit_sse_membase_reg_op2((inst), (basereg), (disp), (reg), 0x0f, 0x29) #define x64_sse_movaps_membase_reg_size(inst, basereg, disp, reg, size) \ emit_sse_membase_reg_op2_size((inst), (basereg), (disp), (reg), 0x0f, 0x29, (size)) #define x64_sse_movaps_memindex_reg(inst, basereg, disp, indexreg, shift, reg) \ emit_sse_memindex_reg_op2((inst), (basereg), (disp), (indexreg), (shift), (reg), 0x0f, 0x29); #define x64_sse_movaps_reg_membase(inst, dreg, basereg, disp) \ emit_sse_reg_membase_op2((inst), (dreg), (basereg), (disp), 0x0f, 0x28) #define x64_sse_movaps_reg_membase_size(inst, dreg, basereg, disp, size) \ emit_sse_reg_membase_op2_size((inst), (dreg), (basereg), (disp), 0x0f, 0x28, (size)) #define x64_sse_movaps_reg_memindex(inst, dreg, basereg, disp, indexreg, shift) \ emit_sse_reg_memindex_op2((inst), (dreg), (basereg), (disp), (indexreg), (shift), 0x0f, 0x28); #define x64_sse_movaps_reg_reg(inst, dreg, reg) \ emit_sse_reg_reg_op2((inst), (dreg), (reg), 0x0f, 0x28) #define x64_sse_movaps_reg_reg_size(inst, dreg, reg, size) \ emit_sse_reg_reg_op2_size((inst), (dreg), (reg), 0x0f, 0x28, size) #define x64_sse_movntps_membase_reg(inst, basereg, disp, reg) \ emit_sse_membase_reg_op2((inst), (basereg), (disp), (reg), 0x0f, 0x2b) #define x64_sse_movntps_memindex_reg(inst, basereg, disp, indexreg, shift, reg) \ emit_sse_memindex_reg_op2((inst), (basereg), (disp), (indexreg), (shift), (reg), 0x0f, 0x2b) #define x64_sse_prefetch_reg_membase(inst, arg, basereg, disp) \ emit_sse_reg_membase_op2((inst), (arg), (basereg), (disp), 0x0f, 0x18) #define x64_sse_movdqa_membase_reg(inst, basereg, disp, reg) \ emit_sse_membase_reg((inst), (basereg), (disp), (reg), 0x66, 0x0f, 0x7f) #define x64_sse_movdqa_reg_membase(inst, dreg, basereg, disp) \ emit_sse_reg_membase((inst), (dreg), (basereg), (disp), 0x66, 0x0f, 0x6f) #define x64_sse_movdqa_reg_reg(inst, dreg, reg) \ emit_sse_reg_reg((inst), (dreg), (reg), 0x66, 0x0f, 0x6f) /* Generated from x86-codegen.h */ #define x64_breakpoint_size(inst,size) do { x86_breakpoint(inst); } while (0) #define x64_cld_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_cld(inst); x64_codegen_post(inst); } while (0) #define x64_stosb_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_stosb(inst); x64_codegen_post(inst); } while (0) #define x64_stosl_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_stosl(inst); x64_codegen_post(inst); } while (0) #define x64_stosd_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_stosd(inst); x64_codegen_post(inst); } while (0) #define x64_movsb_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_movsb(inst); x64_codegen_post(inst); } while (0) #define x64_movsl_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_movsl(inst); x64_codegen_post(inst); } while (0) #define x64_movsd_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_movsd(inst); x64_codegen_post(inst); } while (0) #define x64_prefix_size(inst,p,size) do { x86_prefix((inst), p); } while (0) #define x64_rdtsc_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_rdtsc(inst); x64_codegen_post(inst); } while (0) #define x64_cmpxchg_reg_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_cmpxchg_reg_reg((inst),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_cmpxchg_mem_reg_size(inst,mem,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_cmpxchg_mem_reg((inst),(mem),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_cmpxchg_membase_reg_size(inst,basereg,disp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_cmpxchg_membase_reg((inst),((basereg)&0x7),(disp),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_xchg_reg_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_xchg_reg_reg((inst),((dreg)&0x7),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_xchg_mem_reg_size(inst,mem,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_xchg_mem_reg((inst),(mem),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_xchg_membase_reg_size(inst,basereg,disp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_xchg_membase_reg((inst),((basereg)&0x7),(disp),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_inc_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_inc_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_inc_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_inc_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) //#define x64_inc_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_inc_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_dec_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_dec_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_dec_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_dec_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) //#define x64_dec_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_dec_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_not_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_not_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_not_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_not_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_not_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_not_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_neg_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_neg_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_neg_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_neg_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_neg_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_neg_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_nop_size(inst,size) do { x64_codegen_pre(inst); x86_nop(inst); x64_codegen_post(inst); } while (0) //#define x64_alu_reg_imm_size(inst,opc,reg,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_alu_reg_imm((inst),(opc),((reg)&0x7),(imm)); x64_codegen_post(inst); } while (0) #define x64_alu_mem_imm_size(inst,opc,mem,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_alu_mem_imm((inst),(opc),(mem),(imm)); x64_codegen_post(inst); } while (0) #define x64_alu_membase_imm_size(inst,opc,basereg,disp,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_alu_membase_imm((inst),(opc),((basereg)&0x7),(disp),(imm)); x64_codegen_post(inst); } while (0) #define x64_alu_membase8_imm_size(inst,opc,basereg,disp,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_alu_membase8_imm((inst),(opc),((basereg)&0x7),(disp),(imm)); x64_codegen_post(inst); } while (0) #define x64_alu_mem_reg_size(inst,opc,mem,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_alu_mem_reg((inst),(opc),(mem),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_alu_membase_reg_size(inst,opc,basereg,disp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_alu_membase_reg((inst),(opc),((basereg)&0x7),(disp),((reg)&0x7)); x64_codegen_post(inst); } while (0) //#define x64_alu_reg_reg_size(inst,opc,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_alu_reg_reg((inst),(opc),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_alu_reg8_reg8_size(inst,opc,dreg,reg,is_dreg_h,is_reg_h,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_alu_reg8_reg8((inst),(opc),((dreg)&0x7),((reg)&0x7),(is_dreg_h),(is_reg_h)); x64_codegen_post(inst); } while (0) #define x64_alu_reg_mem_size(inst,opc,reg,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_alu_reg_mem((inst),(opc),((reg)&0x7),(mem)); x64_codegen_post(inst); } while (0) //#define x64_alu_reg_membase_size(inst,opc,reg,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_alu_reg_membase((inst),(opc),((reg)&0x7),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_test_reg_imm_size(inst,reg,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_test_reg_imm((inst),((reg)&0x7),(imm)); x64_codegen_post(inst); } while (0) #define x64_test_mem_imm_size(inst,mem,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_test_mem_imm((inst),(mem),(imm)); x64_codegen_post(inst); } while (0) #define x64_test_membase_imm_size(inst,basereg,disp,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_test_membase_imm((inst),((basereg)&0x7),(disp),(imm)); x64_codegen_post(inst); } while (0) #define x64_test_reg_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_test_reg_reg((inst),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_test_mem_reg_size(inst,mem,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_test_mem_reg((inst),(mem),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_test_membase_reg_size(inst,basereg,disp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_test_membase_reg((inst),((basereg)&0x7),(disp),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_shift_reg_imm_size(inst,opc,reg,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_shift_reg_imm((inst),(opc),((reg)&0x7),(imm)); x64_codegen_post(inst); } while (0) #define x64_shift_mem_imm_size(inst,opc,mem,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_shift_mem_imm((inst),(opc),(mem),(imm)); x64_codegen_post(inst); } while (0) #define x64_shift_membase_imm_size(inst,opc,basereg,disp,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_shift_membase_imm((inst),(opc),((basereg)&0x7),(disp),(imm)); x64_codegen_post(inst); } while (0) #define x64_shift_reg_size(inst,opc,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_shift_reg((inst),(opc),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_shift_mem_size(inst,opc,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_shift_mem((inst),(opc),(mem)); x64_codegen_post(inst); } while (0) #define x64_shift_membase_size(inst,opc,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_shift_membase((inst),(opc),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_shrd_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_shrd_reg((inst),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_shrd_reg_imm_size(inst,dreg,reg,shamt,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_shrd_reg_imm((inst),((dreg)&0x7),((reg)&0x7),(shamt)); x64_codegen_post(inst); } while (0) #define x64_shld_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_shld_reg((inst),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_shld_reg_imm_size(inst,dreg,reg,shamt,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_shld_reg_imm((inst),((dreg)&0x7),((reg)&0x7),(shamt)); x64_codegen_post(inst); } while (0) #define x64_mul_reg_size(inst,reg,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_mul_reg((inst),((reg)&0x7),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_mul_mem_size(inst,mem,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_mul_mem((inst),(mem),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_mul_membase_size(inst,basereg,disp,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_mul_membase((inst),((basereg)&0x7),(disp),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_imul_reg_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_imul_reg_reg((inst),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_imul_reg_mem_size(inst,reg,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_imul_reg_mem((inst),((reg)&0x7),(mem)); x64_codegen_post(inst); } while (0) #define x64_imul_reg_membase_size(inst,reg,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_imul_reg_membase((inst),((reg)&0x7),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_imul_reg_reg_imm_size(inst,dreg,reg,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_imul_reg_reg_imm((inst),((dreg)&0x7),((reg)&0x7),(imm)); x64_codegen_post(inst); } while (0) #define x64_imul_reg_mem_imm_size(inst,reg,mem,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_imul_reg_mem_imm((inst),((reg)&0x7),(mem),(imm)); x64_codegen_post(inst); } while (0) #define x64_imul_reg_membase_imm_size(inst,reg,basereg,disp,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_imul_reg_membase_imm((inst),((reg)&0x7),((basereg)&0x7),(disp),(imm)); x64_codegen_post(inst); } while (0) #define x64_div_reg_size(inst,reg,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_div_reg((inst),((reg)&0x7),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_div_mem_size(inst,mem,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_div_mem((inst),(mem),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_div_membase_size(inst,basereg,disp,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_div_membase((inst),((basereg)&0x7),(disp),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_mov_mem_reg_size(inst,mem,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_mov_mem_reg((inst),(mem),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) //#define x64_mov_regp_reg_size(inst,regp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(regp),0,(reg)); x86_mov_regp_reg((inst),(regp),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) //#define x64_mov_membase_reg_size(inst,basereg,disp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_mov_membase_reg((inst),((basereg)&0x7),(disp),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_mov_memindex_reg_size(inst,basereg,disp,indexreg,shift,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),(indexreg),(basereg)); x86_mov_memindex_reg((inst),((basereg)&0x7),(disp),((indexreg)&0x7),(shift),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_mov_reg_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_mov_reg_reg((inst),((dreg)&0x7),((reg)&0x7),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) //#define x64_mov_reg_mem_size(inst,reg,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_mov_reg_mem((inst),((reg)&0x7),(mem),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) //#define x64_mov_reg_membase_size(inst,reg,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_mov_reg_membase((inst),((reg)&0x7),((basereg)&0x7),(disp),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) //#define x64_mov_reg_memindex_size(inst,reg,basereg,disp,indexreg,shift,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),(indexreg),(basereg)); x86_mov_reg_memindex((inst),((reg)&0x7),((basereg)&0x7),(disp),((indexreg)&0x7),(shift),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_clear_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_clear_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) //#define x64_mov_reg_imm_size(inst,reg,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_mov_reg_imm((inst),((reg)&0x7),(imm)); x64_codegen_post(inst); } while (0) #define x64_mov_mem_imm_size(inst,mem,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_mov_mem_imm((inst),(mem),(imm),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) //#define x64_mov_membase_imm_size(inst,basereg,disp,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_mov_membase_imm((inst),((basereg)&0x7),(disp),(imm),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_mov_memindex_imm_size(inst,basereg,disp,indexreg,shift,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,(indexreg),(basereg)); x86_mov_memindex_imm((inst),((basereg)&0x7),(disp),((indexreg)&0x7),(shift),(imm),(size) == 8 ? 4 : (size)); x64_codegen_post(inst); } while (0) #define x64_lea_mem_size(inst,reg,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_lea_mem((inst),((reg)&0x7),(mem)); x64_codegen_post(inst); } while (0) //#define x64_lea_membase_size(inst,reg,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_lea_membase((inst),((reg)&0x7),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_lea_memindex_size(inst,reg,basereg,disp,indexreg,shift,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),(indexreg),(basereg)); x86_lea_memindex((inst),((reg)&0x7),((basereg)&0x7),(disp),((indexreg)&0x7),(shift)); x64_codegen_post(inst); } while (0) #define x64_widen_reg_size(inst,dreg,reg,is_signed,is_half,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_widen_reg((inst),((dreg)&0x7),((reg)&0x7),(is_signed),(is_half)); x64_codegen_post(inst); } while (0) #define x64_widen_mem_size(inst,dreg,mem,is_signed,is_half,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,0); x86_widen_mem((inst),((dreg)&0x7),(mem),(is_signed),(is_half)); x64_codegen_post(inst); } while (0) #define x64_widen_membase_size(inst,dreg,basereg,disp,is_signed,is_half,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(basereg)); x86_widen_membase((inst),((dreg)&0x7),((basereg)&0x7),(disp),(is_signed),(is_half)); x64_codegen_post(inst); } while (0) #define x64_widen_memindex_size(inst,dreg,basereg,disp,indexreg,shift,is_signed,is_half,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),(indexreg),(basereg)); x86_widen_memindex((inst),((dreg)&0x7),((basereg)&0x7),(disp),((indexreg)&0x7),(shift),(is_signed),(is_half)); x64_codegen_post(inst); } while (0) #define x64_cdq_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_cdq(inst); x64_codegen_post(inst); } while (0) #define x64_wait_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_wait(inst); x64_codegen_post(inst); } while (0) #define x64_fp_op_mem_size(inst,opc,mem,is_double,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fp_op_mem((inst),(opc),(mem),(is_double)); x64_codegen_post(inst); } while (0) #define x64_fp_op_membase_size(inst,opc,basereg,disp,is_double,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fp_op_membase((inst),(opc),((basereg)&0x7),(disp),(is_double)); x64_codegen_post(inst); } while (0) #define x64_fp_op_size(inst,opc,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fp_op((inst),(opc),(index)); x64_codegen_post(inst); } while (0) #define x64_fp_op_reg_size(inst,opc,index,pop_stack,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fp_op_reg((inst),(opc),(index),(pop_stack)); x64_codegen_post(inst); } while (0) #define x64_fp_int_op_membase_size(inst,opc,basereg,disp,is_int,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fp_int_op_membase((inst),(opc),((basereg)&0x7),(disp),(is_int)); x64_codegen_post(inst); } while (0) #define x64_fstp_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fstp((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fcompp_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fcompp(inst); x64_codegen_post(inst); } while (0) #define x64_fucompp_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fucompp(inst); x64_codegen_post(inst); } while (0) #define x64_fnstsw_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fnstsw(inst); x64_codegen_post(inst); } while (0) #define x64_fnstcw_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fnstcw((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_fnstcw_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_fnstcw_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_fldcw_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fldcw((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_fldcw_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fldcw_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_fchs_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fchs(inst); x64_codegen_post(inst); } while (0) #define x64_frem_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_frem(inst); x64_codegen_post(inst); } while (0) #define x64_fxch_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fxch((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fcomi_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fcomi((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fcomip_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fcomip((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fucomi_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fucomi((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fucomip_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fucomip((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fld_size(inst,mem,is_double,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fld((inst),(mem),(is_double)); x64_codegen_post(inst); } while (0) //#define x64_fld_membase_size(inst,basereg,disp,is_double,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fld_membase((inst),((basereg)&0x7),(disp),(is_double)); x64_codegen_post(inst); } while (0) #define x64_fld80_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fld80_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_fld80_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_fld80_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_fild_size(inst,mem,is_long,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fild((inst),(mem),(is_long)); x64_codegen_post(inst); } while (0) #define x64_fild_membase_size(inst,basereg,disp,is_long,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fild_membase((inst),((basereg)&0x7),(disp),(is_long)); x64_codegen_post(inst); } while (0) #define x64_fld_reg_size(inst,index,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fld_reg((inst),(index)); x64_codegen_post(inst); } while (0) #define x64_fldz_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fldz(inst); x64_codegen_post(inst); } while (0) #define x64_fld1_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fld1(inst); x64_codegen_post(inst); } while (0) #define x64_fldpi_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fldpi(inst); x64_codegen_post(inst); } while (0) #define x64_fst_size(inst,mem,is_double,pop_stack,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fst((inst),(mem),(is_double),(pop_stack)); x64_codegen_post(inst); } while (0) #define x64_fst_membase_size(inst,basereg,disp,is_double,pop_stack,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fst_membase((inst),((basereg)&0x7),(disp),(is_double),(pop_stack)); x64_codegen_post(inst); } while (0) #define x64_fst80_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fst80_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_fst80_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fst80_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_fist_pop_size(inst,mem,is_long,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_fist_pop((inst),(mem),(is_long)); x64_codegen_post(inst); } while (0) #define x64_fist_pop_membase_size(inst,basereg,disp,is_long,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fist_pop_membase((inst),((basereg)&0x7),(disp),(is_long)); x64_codegen_post(inst); } while (0) #define x64_fstsw_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_fstsw(inst); x64_codegen_post(inst); } while (0) #define x64_fist_membase_size(inst,basereg,disp,is_int,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_fist_membase((inst),((basereg)&0x7),(disp),(is_int)); x64_codegen_post(inst); } while (0) //#define x64_push_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_push_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_push_regp_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_push_regp((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_push_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_push_mem((inst),(mem)); x64_codegen_post(inst); } while (0) //#define x64_push_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_push_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_push_memindex_size(inst,basereg,disp,indexreg,shift,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,(indexreg),(basereg)); x86_push_memindex((inst),((basereg)&0x7),(disp),((indexreg)&0x7),(shift)); x64_codegen_post(inst); } while (0) #define x64_push_imm_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_push_imm((inst),(imm)); x64_codegen_post(inst); } while (0) //#define x64_pop_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_pop_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_pop_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_pop_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #define x64_pop_membase_size(inst,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_pop_membase((inst),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_pushad_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_pushad(inst); x64_codegen_post(inst); } while (0) #define x64_pushfd_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_pushfd(inst); x64_codegen_post(inst); } while (0) #define x64_popad_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_popad(inst); x64_codegen_post(inst); } while (0) #define x64_popfd_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_popfd(inst); x64_codegen_post(inst); } while (0) #define x64_loop_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_loop((inst),(imm)); x64_codegen_post(inst); } while (0) #define x64_loope_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_loope((inst),(imm)); x64_codegen_post(inst); } while (0) #define x64_loopne_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_loopne((inst),(imm)); x64_codegen_post(inst); } while (0) #define x64_jump32_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_jump32((inst),(imm)); x64_codegen_post(inst); } while (0) #define x64_jump8_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_jump8((inst),(imm)); x64_codegen_post(inst); } while (0) #if !defined( __native_client_codegen__ ) /* Defined above for Native Client, so they can be used in other macros */ #define x64_jump_reg_size(inst,reg,size) do { x64_emit_rex ((inst),0,0,0,(reg)); x86_jump_reg((inst),((reg)&0x7)); } while (0) #define x64_jump_mem_size(inst,mem,size) do { x64_emit_rex ((inst),(size),0,0,0); x86_jump_mem((inst),(mem)); } while (0) #endif #define x64_jump_disp_size(inst,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,0); x86_jump_disp((inst),(disp)); x64_codegen_post(inst); } while (0) #define x64_branch8_size(inst,cond,imm,is_signed,size) do { x86_branch8((inst),(cond),(imm),(is_signed)); } while (0) #define x64_branch32_size(inst,cond,imm,is_signed,size) do { x86_branch32((inst),(cond),(imm),(is_signed)); } while (0) #define x64_branch_size_body(inst,cond,target,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_branch((inst),(cond),(target),(is_signed)); x64_codegen_post(inst); } while (0) #if defined(__native_client_codegen__) #define x64_branch_size(inst,cond,target,is_signed,size) \ do { \ /* x64_branch_size_body used twice in */ \ /* case of relocation by x64_codegen_post */ \ uint8_t* branch_start; \ x64_codegen_pre(inst); \ x64_branch_size_body((inst),(cond),(target),(is_signed),(size)); \ inst = x64_codegen_post(inst); \ branch_start = inst; \ x64_branch_size_body((inst),(cond),(target),(is_signed),(size)); \ mono_x64_patch(branch_start, (target)); \ } while (0) #else #define x64_branch_size(inst,cond,target,is_signed,size) do { x64_branch_size_body((inst),(cond),(target),(is_signed),(size)); } while (0) #endif /* __native_client_codegen__ */ #define x64_branch_disp_size(inst,cond,disp,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_branch_disp((inst),(cond),(disp),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_set_reg_size(inst,cond,reg,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex((inst),1,0,0,(reg)); x86_set_reg((inst),(cond),((reg)&0x7),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_set_mem_size(inst,cond,mem,is_signed,size) do { x64_codegen_pre(inst); x86_set_mem((inst),(cond),(mem),(is_signed)); x64_codegen_post(inst); } while (0) #define x64_set_membase_size(inst,cond,basereg,disp,is_signed,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),0,0,0,(basereg)); x86_set_membase((inst),(cond),((basereg)&0x7),(disp),(is_signed)); x64_codegen_post(inst); } while (0) //#define x64_call_reg_size(inst,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_call_reg((inst),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_call_mem_size(inst,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_call_mem((inst),(mem)); x64_codegen_post(inst); } while (0) #if defined(__native_client_codegen__) /* Size is ignored for Native Client calls, we restrict jumping to 32-bits */ #define x64_call_imm_size(inst,disp,size) \ do { \ x64_codegen_pre((inst)); \ x64_call_sequence_pre((inst)); \ x86_call_imm((inst),(disp)); \ x64_call_sequence_post((inst)); \ x64_codegen_post((inst)); \ } while (0) /* x86_call_code is called twice below, first so we can get the size of the */ /* call sequence, and again so the exact offset from "inst" is used, since */ /* the sequence could have moved from x64_call_sequence_post. */ /* Size is ignored for Native Client jumps, we restrict jumping to 32-bits */ #define x64_call_code_size(inst,target,size) \ do { \ x64_codegen_pre((inst)); \ uint8_t* adjusted_start; \ uint8_t* call_start; \ x64_call_sequence_pre((inst)); \ x86_call_code((inst),(target)); \ adjusted_start = x64_call_sequence_post((inst)); \ call_start = adjusted_start; \ x86_call_code(adjusted_start, (target)); \ x64_codegen_post((inst)); \ mono_x64_patch(call_start, (target)); \ } while (0) #else #define x64_call_imm_size(inst,disp,size) do { x86_call_imm((inst),(disp)); } while (0) #define x64_call_code_size(inst,target,size) do { x86_call_code((inst),(target)); } while (0) #endif /*__native_client_codegen__*/ //#define x64_ret_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_ret(inst); x64_codegen_post(inst); } while (0) #define x64_ret_imm_size(inst,imm,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_ret_imm((inst),(imm)); x64_codegen_post(inst); } while (0) #define x64_cmov_reg_size(inst,cond,is_signed,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_cmov_reg((inst),(cond),(is_signed),((dreg)&0x7),((reg)&0x7)); x64_codegen_post(inst); } while (0) #define x64_cmov_mem_size(inst,cond,is_signed,reg,mem,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_cmov_mem((inst),(cond),(is_signed),((reg)&0x7),(mem)); x64_codegen_post(inst); } while (0) #define x64_cmov_membase_size(inst,cond,is_signed,reg,basereg,disp,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(basereg)); x86_cmov_membase((inst),(cond),(is_signed),((reg)&0x7),((basereg)&0x7),(disp)); x64_codegen_post(inst); } while (0) #define x64_enter_size(inst,framesize) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_enter((inst),(framesize)); x64_codegen_post(inst); } while (0) //#define x64_leave_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_leave(inst); x64_codegen_post(inst); } while (0) #define x64_sahf_size(inst,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_sahf(inst); x64_codegen_post(inst); } while (0) #define x64_fsin_size(inst,size) do { x64_codegen_pre(inst); x86_fsin(inst); x64_codegen_post(inst); } while (0) #define x64_fcos_size(inst,size) do { x64_codegen_pre(inst); x86_fcos(inst); x64_codegen_post(inst); } while (0) #define x64_fabs_size(inst,size) do { x64_codegen_pre(inst); x86_fabs(inst); x64_codegen_post(inst); } while (0) #define x64_ftst_size(inst,size) do { x64_codegen_pre(inst); x86_ftst(inst); x64_codegen_post(inst); } while (0) #define x64_fxam_size(inst,size) do { x64_codegen_pre(inst); x86_fxam(inst); x64_codegen_post(inst); } while (0) #define x64_fpatan_size(inst,size) do { x64_codegen_pre(inst); x86_fpatan(inst); x64_codegen_post(inst); } while (0) #define x64_fprem_size(inst,size) do { x64_codegen_pre(inst); x86_fprem(inst); x64_codegen_post(inst); } while (0) #define x64_fprem1_size(inst,size) do { x64_codegen_pre(inst); x86_fprem1(inst); x64_codegen_post(inst); } while (0) #define x64_frndint_size(inst,size) do { x64_codegen_pre(inst); x86_frndint(inst); x64_codegen_post(inst); } while (0) #define x64_fsqrt_size(inst,size) do { x64_codegen_pre(inst); x86_fsqrt(inst); x64_codegen_post(inst); } while (0) #define x64_fptan_size(inst,size) do { x64_codegen_pre(inst); x86_fptan(inst); x64_codegen_post(inst); } while (0) //#define x64_padding_size(inst,size) do { x64_codegen_pre(inst); x86_padding((inst),(size)); x64_codegen_post(inst); } while (0) #define x64_prolog_size(inst,frame_size,reg_mask,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_prolog((inst),(frame_size),(reg_mask)); x64_codegen_post(inst); } while (0) #define x64_epilog_size(inst,reg_mask,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,0); x86_epilog((inst),(reg_mask)); x64_codegen_post(inst); } while (0) #define x64_xadd_reg_reg_size(inst,dreg,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_xadd_reg_reg ((inst), (dreg), (reg), (size)); x64_codegen_post(inst); } while (0) #define x64_xadd_mem_reg_size(inst,mem,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),0,0,(reg)); x86_xadd_mem_reg((inst),(mem),((reg)&0x7), (size)); x64_codegen_post(inst); } while (0) #define x64_xadd_membase_reg_size(inst,basereg,disp,reg,size) do { x64_codegen_pre(inst); x64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_xadd_membase_reg((inst),((basereg)&0x7),(disp),((reg)&0x7),(size)); x64_codegen_post(inst); } while (0) #define x64_breakpoint(inst) x64_breakpoint_size(inst,8) #define x64_cld(inst) x64_cld_size(inst,8) #define x64_stosb(inst) x64_stosb_size(inst,8) #define x64_stosl(inst) x64_stosl_size(inst,8) #define x64_stosd(inst) x64_stosd_size(inst,8) #define x64_movsb(inst) x64_movsb_size(inst,8) #define x64_movsl(inst) x64_movsl_size(inst,8) #define x64_movsd(inst) x64_movsd_size(inst,8) #define x64_prefix(inst,p) x64_prefix_size(inst,p,8) #define x64_rdtsc(inst) x64_rdtsc_size(inst,8) #define x64_cmpxchg_reg_reg(inst,dreg,reg) x64_cmpxchg_reg_reg_size(inst,dreg,reg,8) #define x64_cmpxchg_mem_reg(inst,mem,reg) x64_cmpxchg_mem_reg_size(inst,mem,reg,8) #define x64_cmpxchg_membase_reg(inst,basereg,disp,reg) x64_cmpxchg_membase_reg_size(inst,basereg,disp,reg,8) #define x64_xchg_reg_reg(inst,dreg,reg,size) x64_xchg_reg_reg_size(inst,dreg,reg,size) #define x64_xchg_mem_reg(inst,mem,reg,size) x64_xchg_mem_reg_size(inst,mem,reg,size) #define x64_xchg_membase_reg(inst,basereg,disp,reg,size) x64_xchg_membase_reg_size(inst,basereg,disp,reg,size) #define x64_xadd_reg_reg(inst,dreg,reg,size) x64_xadd_reg_reg_size(inst,dreg,reg,size) #define x64_xadd_mem_reg(inst,mem,reg,size) x64_xadd_mem_reg_size(inst,mem,reg,size) #define x64_xadd_membase_reg(inst,basereg,disp,reg,size) x64_xadd_membase_reg_size(inst,basereg,disp,reg,size) #define x64_inc_mem(inst,mem) x64_inc_mem_size(inst,mem,8) #define x64_inc_membase(inst,basereg,disp) x64_inc_membase_size(inst,basereg,disp,8) #define x64_inc_reg(inst,reg) x64_inc_reg_size(inst,reg,8) #define x64_dec_mem(inst,mem) x64_dec_mem_size(inst,mem,8) #define x64_dec_membase(inst,basereg,disp) x64_dec_membase_size(inst,basereg,disp,8) #define x64_dec_reg(inst,reg) x64_dec_reg_size(inst,reg,8) #define x64_not_mem(inst,mem) x64_not_mem_size(inst,mem,8) #define x64_not_membase(inst,basereg,disp) x64_not_membase_size(inst,basereg,disp,8) #define x64_not_reg(inst,reg) x64_not_reg_size(inst,reg,8) #define x64_neg_mem(inst,mem) x64_neg_mem_size(inst,mem,8) #define x64_neg_membase(inst,basereg,disp) x64_neg_membase_size(inst,basereg,disp,8) #define x64_neg_reg(inst,reg) x64_neg_reg_size(inst,reg,8) #define x64_nop(inst) x64_nop_size(inst,8) //#define x64_alu_reg_imm(inst,opc,reg,imm) x64_alu_reg_imm_size(inst,opc,reg,imm,8) #define x64_alu_mem_imm(inst,opc,mem,imm) x64_alu_mem_imm_size(inst,opc,mem,imm,8) #define x64_alu_membase_imm(inst,opc,basereg,disp,imm) x64_alu_membase_imm_size(inst,opc,basereg,disp,imm,8) #define x64_alu_mem_reg(inst,opc,mem,reg) x64_alu_mem_reg_size(inst,opc,mem,reg,8) #define x64_alu_membase_reg(inst,opc,basereg,disp,reg) x64_alu_membase_reg_size(inst,opc,basereg,disp,reg,8) //#define x64_alu_reg_reg(inst,opc,dreg,reg) x64_alu_reg_reg_size(inst,opc,dreg,reg,8) #define x64_alu_reg8_reg8(inst,opc,dreg,reg,is_dreg_h,is_reg_h) x64_alu_reg8_reg8_size(inst,opc,dreg,reg,is_dreg_h,is_reg_h,8) #define x64_alu_reg_mem(inst,opc,reg,mem) x64_alu_reg_mem_size(inst,opc,reg,mem,8) #define x64_alu_reg_membase(inst,opc,reg,basereg,disp) x64_alu_reg_membase_size(inst,opc,reg,basereg,disp,8) #define x64_test_reg_imm(inst,reg,imm) x64_test_reg_imm_size(inst,reg,imm,8) #define x64_test_mem_imm(inst,mem,imm) x64_test_mem_imm_size(inst,mem,imm,8) #define x64_test_membase_imm(inst,basereg,disp,imm) x64_test_membase_imm_size(inst,basereg,disp,imm,8) #define x64_test_reg_reg(inst,dreg,reg) x64_test_reg_reg_size(inst,dreg,reg,8) #define x64_test_mem_reg(inst,mem,reg) x64_test_mem_reg_size(inst,mem,reg,8) #define x64_test_membase_reg(inst,basereg,disp,reg) x64_test_membase_reg_size(inst,basereg,disp,reg,8) #define x64_shift_reg_imm(inst,opc,reg,imm) x64_shift_reg_imm_size(inst,opc,reg,imm,8) #define x64_shift_mem_imm(inst,opc,mem,imm) x64_shift_mem_imm_size(inst,opc,mem,imm,8) #define x64_shift_membase_imm(inst,opc,basereg,disp,imm) x64_shift_membase_imm_size(inst,opc,basereg,disp,imm,8) #define x64_shift_reg(inst,opc,reg) x64_shift_reg_size(inst,opc,reg,8) #define x64_shift_mem(inst,opc,mem) x64_shift_mem_size(inst,opc,mem,8) #define x64_shift_membase(inst,opc,basereg,disp) x64_shift_membase_size(inst,opc,basereg,disp,8) #define x64_shrd_reg(inst,dreg,reg) x64_shrd_reg_size(inst,dreg,reg,8) #define x64_shrd_reg_imm(inst,dreg,reg,shamt) x64_shrd_reg_imm_size(inst,dreg,reg,shamt,8) #define x64_shld_reg(inst,dreg,reg) x64_shld_reg_size(inst,dreg,reg,8) #define x64_shld_reg_imm(inst,dreg,reg,shamt) x64_shld_reg_imm_size(inst,dreg,reg,shamt,8) #define x64_mul_reg(inst,reg,is_signed) x64_mul_reg_size(inst,reg,is_signed,8) #define x64_mul_mem(inst,mem,is_signed) x64_mul_mem_size(inst,mem,is_signed,8) #define x64_mul_membase(inst,basereg,disp,is_signed) x64_mul_membase_size(inst,basereg,disp,is_signed,8) #define x64_imul_reg_reg(inst,dreg,reg) x64_imul_reg_reg_size(inst,dreg,reg,8) #define x64_imul_reg_mem(inst,reg,mem) x64_imul_reg_mem_size(inst,reg,mem,8) #define x64_imul_reg_membase(inst,reg,basereg,disp) x64_imul_reg_membase_size(inst,reg,basereg,disp,8) #define x64_imul_reg_reg_imm(inst,dreg,reg,imm) x64_imul_reg_reg_imm_size(inst,dreg,reg,imm,8) #define x64_imul_reg_mem_imm(inst,reg,mem,imm) x64_imul_reg_mem_imm_size(inst,reg,mem,imm,8) #define x64_imul_reg_membase_imm(inst,reg,basereg,disp,imm) x64_imul_reg_membase_imm_size(inst,reg,basereg,disp,imm,8) #define x64_div_reg(inst,reg,is_signed) x64_div_reg_size(inst,reg,is_signed,8) #define x64_div_mem(inst,mem,is_signed) x64_div_mem_size(inst,mem,is_signed,8) #define x64_div_membase(inst,basereg,disp,is_signed) x64_div_membase_size(inst,basereg,disp,is_signed,8) //#define x64_mov_mem_reg(inst,mem,reg,size) x64_mov_mem_reg_size(inst,mem,reg,size) //#define x64_mov_regp_reg(inst,regp,reg,size) x64_mov_regp_reg_size(inst,regp,reg,size) //#define x64_mov_membase_reg(inst,basereg,disp,reg,size) x64_mov_membase_reg_size(inst,basereg,disp,reg,size) #define x64_mov_memindex_reg(inst,basereg,disp,indexreg,shift,reg,size) x64_mov_memindex_reg_size(inst,basereg,disp,indexreg,shift,reg,size) //#define x64_mov_reg_reg(inst,dreg,reg,size) x64_mov_reg_reg_size(inst,dreg,reg,size) //#define x64_mov_reg_mem(inst,reg,mem,size) x64_mov_reg_mem_size(inst,reg,mem,size) //#define x64_mov_reg_membase(inst,reg,basereg,disp,size) x64_mov_reg_membase_size(inst,reg,basereg,disp,size) #define x64_mov_reg_memindex(inst,reg,basereg,disp,indexreg,shift,size) x64_mov_reg_memindex_size(inst,reg,basereg,disp,indexreg,shift,size) #define x64_clear_reg(inst,reg) x64_clear_reg_size(inst,reg,8) //#define x64_mov_reg_imm(inst,reg,imm) x64_mov_reg_imm_size(inst,reg,imm,8) #define x64_mov_mem_imm(inst,mem,imm,size) x64_mov_mem_imm_size(inst,mem,imm,size) //#define x64_mov_membase_imm(inst,basereg,disp,imm,size) x64_mov_membase_imm_size(inst,basereg,disp,imm,size) #define x64_mov_memindex_imm(inst,basereg,disp,indexreg,shift,imm,size) x64_mov_memindex_imm_size(inst,basereg,disp,indexreg,shift,imm,size) #define x64_lea_mem(inst,reg,mem) x64_lea_mem_size(inst,reg,mem,8) //#define x64_lea_membase(inst,reg,basereg,disp) x64_lea_membase_size(inst,reg,basereg,disp,8) #define x64_lea_memindex(inst,reg,basereg,disp,indexreg,shift) x64_lea_memindex_size(inst,reg,basereg,disp,indexreg,shift,8) #define x64_widen_reg(inst,dreg,reg,is_signed,is_half) x64_widen_reg_size(inst,dreg,reg,is_signed,is_half,8) #define x64_widen_mem(inst,dreg,mem,is_signed,is_half) x64_widen_mem_size(inst,dreg,mem,is_signed,is_half,8) #define x64_widen_membase(inst,dreg,basereg,disp,is_signed,is_half) x64_widen_membase_size(inst,dreg,basereg,disp,is_signed,is_half,8) #define x64_widen_memindex(inst,dreg,basereg,disp,indexreg,shift,is_signed,is_half) x64_widen_memindex_size(inst,dreg,basereg,disp,indexreg,shift,is_signed,is_half,8) #define x64_cdq(inst) x64_cdq_size(inst,8) #define x64_wait(inst) x64_wait_size(inst,8) #define x64_fp_op_mem(inst,opc,mem,is_double) x64_fp_op_mem_size(inst,opc,mem,is_double,8) #define x64_fp_op_membase(inst,opc,basereg,disp,is_double) x64_fp_op_membase_size(inst,opc,basereg,disp,is_double,8) #define x64_fp_op(inst,opc,index) x64_fp_op_size(inst,opc,index,8) #define x64_fp_op_reg(inst,opc,index,pop_stack) x64_fp_op_reg_size(inst,opc,index,pop_stack,8) #define x64_fp_int_op_membase(inst,opc,basereg,disp,is_int) x64_fp_int_op_membase_size(inst,opc,basereg,disp,is_int,8) #define x64_fstp(inst,index) x64_fstp_size(inst,index,8) #define x64_fcompp(inst) x64_fcompp_size(inst,8) #define x64_fucompp(inst) x64_fucompp_size(inst,8) #define x64_fnstsw(inst) x64_fnstsw_size(inst,8) #define x64_fnstcw(inst,mem) x64_fnstcw_size(inst,mem,8) #define x64_fnstcw_membase(inst,basereg,disp) x64_fnstcw_membase_size(inst,basereg,disp,8) #define x64_fldcw(inst,mem) x64_fldcw_size(inst,mem,8) #define x64_fldcw_membase(inst,basereg,disp) x64_fldcw_membase_size(inst,basereg,disp,8) #define x64_fchs(inst) x64_fchs_size(inst,8) #define x64_frem(inst) x64_frem_size(inst,8) #define x64_fxch(inst,index) x64_fxch_size(inst,index,8) #define x64_fcomi(inst,index) x64_fcomi_size(inst,index,8) #define x64_fcomip(inst,index) x64_fcomip_size(inst,index,8) #define x64_fucomi(inst,index) x64_fucomi_size(inst,index,8) #define x64_fucomip(inst,index) x64_fucomip_size(inst,index,8) #define x64_fld(inst,mem,is_double) x64_fld_size(inst,mem,is_double,8) #define x64_fld_membase(inst,basereg,disp,is_double) x64_fld_membase_size(inst,basereg,disp,is_double,8) #define x64_fld80_mem(inst,mem) x64_fld80_mem_size(inst,mem,8) #define x64_fld80_membase(inst,basereg,disp) x64_fld80_membase_size(inst,basereg,disp,8) #define x64_fild(inst,mem,is_long) x64_fild_size(inst,mem,is_long,8) #define x64_fild_membase(inst,basereg,disp,is_long) x64_fild_membase_size(inst,basereg,disp,is_long,8) #define x64_fld_reg(inst,index) x64_fld_reg_size(inst,index,8) #define x64_fldz(inst) x64_fldz_size(inst,8) #define x64_fld1(inst) x64_fld1_size(inst,8) #define x64_fldpi(inst) x64_fldpi_size(inst,8) #define x64_fst(inst,mem,is_double,pop_stack) x64_fst_size(inst,mem,is_double,pop_stack,8) #define x64_fst_membase(inst,basereg,disp,is_double,pop_stack) x64_fst_membase_size(inst,basereg,disp,is_double,pop_stack,8) #define x64_fst80_mem(inst,mem) x64_fst80_mem_size(inst,mem,8) #define x64_fst80_membase(inst,basereg,disp) x64_fst80_membase_size(inst,basereg,disp,8) #define x64_fist_pop(inst,mem,is_long) x64_fist_pop_size(inst,mem,is_long,8) #define x64_fist_pop_membase(inst,basereg,disp,is_long) x64_fist_pop_membase_size(inst,basereg,disp,is_long,8) #define x64_fstsw(inst) x64_fstsw_size(inst,8) #define x64_fist_membase(inst,basereg,disp,is_int) x64_fist_membase_size(inst,basereg,disp,is_int,8) //#define x64_push_reg(inst,reg) x64_push_reg_size(inst,reg,8) #define x64_push_regp(inst,reg) x64_push_regp_size(inst,reg,8) #define x64_push_mem(inst,mem) x64_push_mem_size(inst,mem,8) //#define x64_push_membase(inst,basereg,disp) x64_push_membase_size(inst,basereg,disp,8) #define x64_push_memindex(inst,basereg,disp,indexreg,shift) x64_push_memindex_size(inst,basereg,disp,indexreg,shift,8) #define x64_push_imm(inst,imm) x64_push_imm_size(inst,imm,8) //#define x64_pop_reg(inst,reg) x64_pop_reg_size(inst,reg,8) #define x64_pop_mem(inst,mem) x64_pop_mem_size(inst,mem,8) #define x64_pop_membase(inst,basereg,disp) x64_pop_membase_size(inst,basereg,disp,8) #define x64_pushad(inst) x64_pushad_size(inst,8) #define x64_pushfd(inst) x64_pushfd_size(inst,8) #define x64_popad(inst) x64_popad_size(inst,8) #define x64_popfd(inst) x64_popfd_size(inst,8) #define x64_loop(inst,imm) x64_loop_size(inst,imm,8) #define x64_loope(inst,imm) x64_loope_size(inst,imm,8) #define x64_loopne(inst,imm) x64_loopne_size(inst,imm,8) #define x64_jump32(inst,imm) x64_jump32_size(inst,imm,8) #define x64_jump8(inst,imm) x64_jump8_size(inst,imm,8) #define x64_jump_reg(inst,reg) x64_jump_reg_size(inst,reg,8) #define x64_jump_mem(inst,mem) x64_jump_mem_size(inst,mem,8) #define x64_jump_membase(inst,basereg,disp) x64_jump_membase_size(inst,basereg,disp,8) #define x64_jump_code(inst,target) x64_jump_code_size(inst,target,8) #define x64_jump_disp(inst,disp) x64_jump_disp_size(inst,disp,8) #define x64_branch8(inst,cond,imm,is_signed) x64_branch8_size(inst,cond,imm,is_signed,8) #define x64_branch32(inst,cond,imm,is_signed) x64_branch32_size(inst,cond,imm,is_signed,8) #define x64_branch(inst,cond,target,is_signed) x64_branch_size(inst,cond,target,is_signed,8) #define x64_branch_disp(inst,cond,disp,is_signed) x64_branch_disp_size(inst,cond,disp,is_signed,8) #define x64_set_reg(inst,cond,reg,is_signed) x64_set_reg_size(inst,cond,reg,is_signed,8) #define x64_set_mem(inst,cond,mem,is_signed) x64_set_mem_size(inst,cond,mem,is_signed,8) #define x64_set_membase(inst,cond,basereg,disp,is_signed) x64_set_membase_size(inst,cond,basereg,disp,is_signed,8) #define x64_call_imm(inst,disp) x64_call_imm_size(inst,disp,8) //#define x64_call_reg(inst,reg) x64_call_reg_size(inst,reg,8) #define x64_call_mem(inst,mem) x64_call_mem_size(inst,mem,8) #define x64_call_membase(inst,basereg,disp) x64_call_membase_size(inst,basereg,disp,8) #define x64_call_code(inst,target) x64_call_code_size(inst,target,8) //#define x64_ret(inst) x64_ret_size(inst,8) #define x64_ret_imm(inst,imm) x64_ret_imm_size(inst,imm,8) #define x64_cmov_reg(inst,cond,is_signed,dreg,reg) x64_cmov_reg_size(inst,cond,is_signed,dreg,reg,8) #define x64_cmov_mem(inst,cond,is_signed,reg,mem) x64_cmov_mem_size(inst,cond,is_signed,reg,mem,8) #define x64_cmov_membase(inst,cond,is_signed,reg,basereg,disp) x64_cmov_membase_size(inst,cond,is_signed,reg,basereg,disp,8) #define x64_enter(inst,framesize) x64_enter_size(inst,framesize) //#define x64_leave(inst) x64_leave_size(inst,8) #define x64_sahf(inst) x64_sahf_size(inst,8) #define x64_fsin(inst) x64_fsin_size(inst,8) #define x64_fcos(inst) x64_fcos_size(inst,8) #define x64_fabs(inst) x64_fabs_size(inst,8) #define x64_ftst(inst) x64_ftst_size(inst,8) #define x64_fxam(inst) x64_fxam_size(inst,8) #define x64_fpatan(inst) x64_fpatan_size(inst,8) #define x64_fprem(inst) x64_fprem_size(inst,8) #define x64_fprem1(inst) x64_fprem1_size(inst,8) #define x64_frndint(inst) x64_frndint_size(inst,8) #define x64_fsqrt(inst) x64_fsqrt_size(inst,8) #define x64_fptan(inst) x64_fptan_size(inst,8) #define x64_padding(inst,size) x64_padding_size(inst,size) #define x64_prolog(inst,frame,reg_mask) x64_prolog_size(inst,frame,reg_mask,8) #define x64_epilog(inst,reg_mask) x64_epilog_size(inst,reg_mask,8) #endif // X64_H
56,052