repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
realrespecter/PUBG-FULL-SDK
SDK/PUBG_SoundOptionWidget_functions.cpp
<reponame>realrespecter/PUBG-FULL-SDK<gh_stars>1-10 // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_SoundOptionWidget_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting // () // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool USoundOptionWidget_C::IsEnable_VoiceSetting() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting"); USoundOptionWidget_C_IsEnable_VoiceSetting_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp // (Event) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool USoundOptionWidget_C::IsKeyUp() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp"); USoundOptionWidget_C_IsKeyUp_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SoundOptionWidget.SoundOptionWidget_C.IsChanged // (Event) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool USoundOptionWidget_C::IsChanged() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsChanged"); USoundOptionWidget_C_IsChanged_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SoundOptionWidget.SoundOptionWidget_C.OnApply // (Event) void USoundOptionWidget_C::OnApply() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnApply"); USoundOptionWidget_C_OnApply_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function SoundOptionWidget.SoundOptionWidget_C.OnDefault // (Event) void USoundOptionWidget_C::OnDefault() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnDefault"); USoundOptionWidget_C_OnDefault_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function SoundOptionWidget.SoundOptionWidget_C.OnReset // (Event) void USoundOptionWidget_C::OnReset() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnReset"); USoundOptionWidget_C_OnReset_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function SoundOptionWidget.SoundOptionWidget_C.Construct // (BlueprintCosmetic, Event) void USoundOptionWidget_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.Construct"); USoundOptionWidget_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget // () // Parameters: // int* EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void USoundOptionWidget_C::ExecuteUbergraph_SoundOptionWidget(int* EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget"); USoundOptionWidget_C_ExecuteUbergraph_SoundOptionWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
enxbayr/CS490-eShop
eshop-admin/src/main/java/edu/miu/eshop/eshopadmin/service/TransactionHistServiceImpl.java
<reponame>enxbayr/CS490-eShop package edu.miu.eshop.eshopadmin.service; import edu.miu.eshop.eshopadmin.domain.TransactionHist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.time.Month; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; @Service public class TransactionHistServiceImpl implements TransactionHistService{ @Autowired private RestTemplate restTemplate; HttpHeaders headers; Properties prop; InputStream inputStream; String propFileName = "application.properties"; @PostConstruct private void initProperty() throws IOException { prop = new Properties(); headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) { prop.load(inputStream); } else { try { throw new FileNotFoundException("Property file '" + propFileName + "' not found in the classpath"); } catch (FileNotFoundException e) { e.printStackTrace(); } } } @Override public double getTotalTransaction(boolean b) { if(b) return restTemplate.getForObject(prop.getProperty("eshop.payment.url.base") + "/card/totalsuccess", Double.class, ""); else return restTemplate.getForObject(prop.getProperty("eshop.payment.url.base") + "/card/totalfailure", Double.class, ""); } @Override public List<TransactionHist> getAllTransactionHist() { ResponseEntity<List<TransactionHist>> response = restTemplate.exchange( prop.getProperty("eshop.payment.url.base") + "/card/allTransaction", HttpMethod.GET, null, new ParameterizedTypeReference<List<TransactionHist>>(){}); return response.getBody(); } @Override public double getTotalTransactionAmt() { return restTemplate.getForObject(prop.getProperty("eshop.payment.url.base") + "/card/totalTransaction", Double.class, ""); } @Override public Map<Month, Double> getTransactionByMonth(int year) { return restTemplate.getForObject(prop.getProperty("eshop.payment.url.base") + "/card/totalamtbymonth", Map.class, ""); } }
519430378qqcom/2017-04-21
YoumiFramework/src/main/java/cn/youmi/framework/main/ContextProvider.java
<filename>YoumiFramework/src/main/java/cn/youmi/framework/main/ContextProvider.java package cn.youmi.framework.main; import android.app.Application; import android.graphics.Bitmap.CompressFormat; public class ContextProvider{ public static final int DISK_IMAGECACHE_SIZE = 1024 * 1024 * 10; public static CompressFormat DISK_IMAGECACHE_COMPRESS_FORMAT = CompressFormat.PNG; public static int DISK_IMAGECACHE_QUALITY = 100; }
XPRIZE/GLEXP-Team-Manzalab
app/modules/user_interface/src/elements/path.js
<filename>app/modules/user_interface/src/elements/path.js<gh_stars>1-10 define([ '../utils/game/state_graphic', '../utils/game/factories/movie_clip_anim_factory', '../utils/game/box_type' ], function ( StateGraphic, MovieClipAnimFactory, BoxType ) { 'use strict'; // ############################################################################################################################################### // ### CONSTRUCTOR ############################################################################################################################# // ############################################################################################################################################### /** * The Path class is ... * @class * @extends Button * @memberof Namespace (e.g. Kalulu.Remediation) * @param parameter {Object} Description of the parameter **/ function Path (description, assetName) { this._description = description; this._assetName = assetName; this._OFF = 0; this._ON = 1; this._id = parseInt(this._assetName.split("_")[1], 10); StateGraphic.call(this); this._assetName = assetName; this._factory = new MovieClipAnimFactory(); this._boxType = BoxType.SELF; this.start(); //console.log(this); } Path.prototype = Object.create(StateGraphic.prototype); Path.prototype.constructor = Path; // ############################################################################################################################################### // ### GETTERS & SETTERS ####################################################################################################################### // ############################################################################################################################################### Object.defineProperties(Path.prototype, { state : { get : function () {return this._state} } }); // ############################################################################################################################################## // ### METHODS ################################################################################################################################ // ############################################################################################################################################## Path.prototype.start = function start(){ this._setState(this._DEFAULT_STATE); this.setModeOff(); } Path.prototype.setModeOff = function setModeOff(){ this._anim.gotoAndStop(this._OFF); this._state = "Off"; } Path.prototype.setModeOn = function setModeOn(){ this._anim.gotoAndStop(this._ON); this._state = "On"; } return Path; });
harshach/streamline-1
streams/functions/src/main/java/com/hortonworks/streamline/streams/udf/Exists.java
<reponame>harshach/streamline-1 package com.hortonworks.streamline.streams.udf; import com.hortonworks.streamline.streams.rule.UDF; public class Exists implements UDF<Integer, Long> { @Override public Integer evaluate(Long input) { if (input == null || input == 0) { return 0; } return 1; } }
apache/uima-ruta
ruta-core-ext/src/test/java/org/apache/uima/ruta/block/DocumentBlockTest.java
<gh_stars>10-100 /* * 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.uima.ruta.block; import java.util.HashMap; import java.util.Map; import org.apache.uima.cas.CAS; import org.apache.uima.ruta.engine.Ruta; import org.apache.uima.ruta.engine.RutaEngine; import org.apache.uima.ruta.engine.RutaTestUtils; import org.junit.Test; public class DocumentBlockTest { @Test public void test() { String document = "some text 1 some text 2 some text"; String script = ""; script += "BLOCK(B) NUM{REGEXP(\"1\")}{\n"; script += "Document{-> T1};\n"; script += "DOCUMENTBLOCK SW{REGEXP(\"text\")}{\n"; script += "Document{-> T2};\n"; script += "}"; script += "}"; Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(RutaEngine.PARAM_ADDITIONAL_EXTENSIONS, new String[] { DocumentBlockExtension.class.getName() }); CAS cas = null; try { cas = RutaTestUtils.getCAS(document); Ruta.apply(cas, script, parameters); } catch (Exception e) { e.printStackTrace(); } RutaTestUtils.assertAnnotationsEquals(cas, 1, 1, "1"); RutaTestUtils.assertAnnotationsEquals(cas, 2, 3, "text", "text", "text"); if (cas != null) { cas.release(); } } }
Gussy/titanium_desktop
modules/ti.Database/ResultSet.h
/* * Copyright (c) 2009-2010 Appcelerator, 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. */ #ifndef ResultSet_h #define ResultSet_h #include <kroll/kroll.h> #include <Poco/Data/RecordSet.h> namespace Titanium { class ResultSet : public StaticBoundObject { public: ResultSet(); ResultSet(Poco::Data::RecordSet& rs); virtual ~ResultSet(); private: void Bind(); void TransformValue(size_t index, KValueRef result); void IsValidRow(const ValueList& args, KValueRef result); void Next(const ValueList& args, KValueRef result); void Close(const ValueList& args, KValueRef result); void RowCount(const ValueList& args, KValueRef result); void FieldCount(const ValueList& args, KValueRef result); void FieldName(const ValueList& args, KValueRef result); void Field(const ValueList& args, KValueRef result); void FieldByName(const ValueList& args, KValueRef result); SharedPtr<Poco::Data::RecordSet> rs; bool eof; }; } // namespace Titanium #endif
sammiler/GDStash_Pro
src/org/gdstash/db/DBFormula.java
/* */ package org.gdstash.db; /* */ /* */ import java.sql.Connection; /* */ import java.sql.PreparedStatement; /* */ import java.sql.ResultSet; /* */ import java.sql.SQLException; /* */ import java.sql.Statement; /* */ import java.util.LinkedList; /* */ import java.util.List; /* */ import net.objecthunter.exp4j.Expression; /* */ import net.objecthunter.exp4j.ExpressionBuilder; /* */ import org.gdstash.util.GDConstants; /* */ import org.gdstash.util.GDMsgFormatter; /* */ import org.gdstash.util.GDMsgLogger; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class DBFormula /* */ { /* */ private static final String TABLE_NAME = "GD_FORMULA"; /* */ private static final int ROW_FORMULASET_ID = 1; /* */ private static final int ROW_FORMULA_ID = 2; /* */ private static final int ROW_FORMULA = 3; /* */ public static final String FORMULA_COST_ARMOR = "armorCostEquation"; /* */ public static final String FORMULA_COST_JEWELRY = "jewelryCostEquation"; /* */ public static final String FORMULA_COST_OFFHAND = "offhandCostEquation"; /* */ public static final String FORMULA_COST_SHIELD = "shieldCostEquation"; /* */ public static final String FORMULA_COST_MELEE_1H = "weaponCostEquation"; /* */ public static final String FORMULA_COST_MELEE_2H = "weaponMelee2hCostEquation"; /* */ public static final String FORMULA_COST_RANGED_1H = "weaponRangedCostEquation"; /* */ public static final String FORMULA_COST_RANGED_2H = "weaponRanged2hCostEquation"; /* */ public static final String FORMULA_DEX_DAGGER = "daggerDexterityEquation"; /* */ public static final String FORMULA_DEX_RANGED_1H = "ranged1hDexterityEquation"; /* */ public static final String FORMULA_DEX_RANGED_2H = "ranged2hDexterityEquation"; /* */ public static final String FORMULA_DEX_SWORD = "swordDexterityEquation"; /* */ public static final String FORMULA_INT_AMULET = "amuletIntelligenceEquation"; /* */ public static final String FORMULA_INT_CHEST = "chestIntelligenceEquation"; /* */ public static final String FORMULA_INT_DAGGER = "daggerIntelligenceEquation"; /* */ public static final String FORMULA_INT_HEAD = "headIntelligenceEquation"; /* */ public static final String FORMULA_INT_OFFHAND = "offhandIntelligenceEquation"; /* */ public static final String FORMULA_INT_RING = "ringIntelligenceEquation"; /* */ public static final String FORMULA_INT_SCEPTER = "scepterIntelligenceEquation"; /* */ public static final String FORMULA_STR_AXE = "axeStrengthEquation"; /* */ public static final String FORMULA_STR_CHEST = "chestStrengthEquation"; /* */ public static final String FORMULA_STR_FEET = "feetStrengthEquation"; /* */ public static final String FORMULA_STR_HANDS = "handsStrengthEquation"; /* */ public static final String FORMULA_STR_HEAD = "headStrengthEquation"; /* */ public static final String FORMULA_STR_LEGS = "legsStrengthEquation"; /* */ public static final String FORMULA_STR_MACE = "maceStrengthEquation"; /* */ public static final String FORMULA_STR_MELEE_2H = "melee2hStrengthEquation"; /* */ public static final String FORMULA_STR_SCEPTER = "scepterStrengthEquation"; /* */ public static final String FORMULA_STR_SHIELD = "shieldStrengthEquation"; /* */ public static final String FORMULA_STR_SHOULDERS = "shouldersStrengthEquation"; /* */ public static final String FORMULA_STR_BELT = "waistStrengthEquation"; /* */ private String formulaSetID; /* */ private String formulaID; /* */ private String formula; /* 69 */ private Expression expression = null; /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getFormulaSetID() { /* 77 */ return this.formulaSetID; /* */ } /* */ /* */ public String getFormulaID() { /* 81 */ return this.formulaID; /* */ } /* */ /* */ public String getFormula() { /* 85 */ return this.formula; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void setFormulaSetID(String formulaSetID) { /* 93 */ this.formulaSetID = formulaSetID; /* */ } /* */ /* */ public void setFormulaID(String formulaID) { /* 97 */ this.formulaID = formulaID; /* */ } /* */ /* */ public void setFormula(String formula) { /* 101 */ this.formula = formula; /* */ /* 103 */ if (formula != null) { /* 104 */ ExpressionBuilder builder = new ExpressionBuilder(formula); /* 105 */ builder = builder.variables(new String[] { "charAttackSpeed", "damageAvgBase", "damageAvgPierceRatio", "defenseAttrArmor", "itemLevel", "itemPrefixCost", "itemSuffixCost", "shieldBlockChance", "shieldBlockDefense", "totalAttCount", "CHARATTACKSPEED", "DAMAGEAVGBASE", "DAMAGEAVGPIERCERATIO", "DEFENSEATTRARMOR", "ITEMLEVEL", "ITEMPREFIXCOST", "ITEMSUFFIXCOST", "SHIELDBLOCKCHANCE", "SHIELDBLOCKDEFENSE", "TOTALATTCOUNT" }); /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 129 */ this.expression = builder.build(); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void setParameterSet(ParameterSet ps) { /* 138 */ if (this.expression == null) { /* */ return; /* */ } /* 141 */ this.expression.setVariable("charAttackSpeed", ps.getCharAttackSpeed()); /* 142 */ this.expression.setVariable("damageAvgBase", ps.getDamageAvgBase()); /* 143 */ this.expression.setVariable("damageAvgPierceRatio", ps.getDamageAvgPierceRatio()); /* 144 */ this.expression.setVariable("defenseAttrArmor", ps.getDefenseAttrArmor()); /* 145 */ this.expression.setVariable("itemLevel", ps.getItemLevel()); /* 146 */ this.expression.setVariable("itemPrefixCost", ps.getItemPrefixCost()); /* 147 */ this.expression.setVariable("itemSuffixCost", ps.getItemSuffixCost()); /* 148 */ this.expression.setVariable("shieldBlockChance", ps.getShieldBlockChance()); /* 149 */ this.expression.setVariable("shieldBlockDefense", ps.getShieldBlockDefense()); /* 150 */ this.expression.setVariable("totalAttCount", ps.getTotalAttCount()); /* */ /* 152 */ this.expression.setVariable("CHARATTACKSPEED", ps.getCharAttackSpeed()); /* 153 */ this.expression.setVariable("DAMAGEAVGBASE", ps.getDamageAvgBase()); /* 154 */ this.expression.setVariable("DAMAGEAVGPIERCERATIO", ps.getDamageAvgPierceRatio()); /* 155 */ this.expression.setVariable("DEFENSEATTRARMOR", ps.getDefenseAttrArmor()); /* 156 */ this.expression.setVariable("ITEMLEVEL", ps.getItemLevel()); /* 157 */ this.expression.setVariable("ITEMPREFIXCOST", ps.getItemPrefixCost()); /* 158 */ this.expression.setVariable("ITEMSUFFIXCOST", ps.getItemSuffixCost()); /* 159 */ this.expression.setVariable("SHIELDBLOCKCHANCE", ps.getShieldBlockChance()); /* 160 */ this.expression.setVariable("SHIELDBLOCKDEFENSE", ps.getShieldBlockDefense()); /* 161 */ this.expression.setVariable("TOTALATTCOUNT", ps.getTotalAttCount()); /* */ } /* */ /* */ public double getValue() { /* 165 */ if (this.expression == null) return 0.0D; /* */ /* 167 */ double value = this.expression.evaluate(); /* */ /* 169 */ return value; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public static void createTable() throws SQLException { /* 177 */ String dropTable = "DROP TABLE GD_FORMULA"; /* 178 */ String createTable = "CREATE TABLE GD_FORMULA (FORMULASET_ID VARCHAR(256) NOT NULL, FORMULA_ID VARCHAR(64), FORMULA VARCHAR(256), PRIMARY KEY (FORMULASET_ID, FORMULA_ID))"; /* */ /* */ /* */ /* */ /* */ /* 184 */ try (Connection conn = GDDBData.getConnection()) { /* 185 */ boolean auto = conn.getAutoCommit(); /* 186 */ conn.setAutoCommit(false); /* */ /* 188 */ try (Statement st = conn.createStatement()) { /* 189 */ if (GDDBUtil.tableExists(conn, "GD_FORMULA")) { /* 190 */ st.execute(dropTable); /* */ } /* 192 */ st.execute(createTable); /* 193 */ st.close(); /* */ /* 195 */ conn.commit(); /* */ /* */ } /* 198 */ catch (SQLException ex) { /* 199 */ conn.rollback(); /* */ /* 201 */ Object[] args = { "GD_FORMULA" }; /* 202 */ String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_CREATE_TABLE", args); /* */ /* 204 */ GDMsgLogger.addError(msg); /* */ /* 206 */ throw ex; /* */ } finally { /* */ /* 209 */ conn.setAutoCommit(auto); /* */ } /* */ } /* */ } /* */ /* */ public static void delete(Connection conn, String formulaSetID) throws SQLException { /* 215 */ String deleteEntry = "DELETE FROM GD_FORMULA WHERE FORMULASET_ID = ?"; /* */ /* 217 */ try (PreparedStatement ps = conn.prepareStatement(deleteEntry)) { /* 218 */ ps.setString(1, formulaSetID); /* 219 */ ps.executeUpdate(); /* 220 */ ps.close(); /* */ } /* 222 */ catch (SQLException ex) { /* 223 */ throw ex; /* */ } /* */ } /* */ /* */ /* */ public static void insert(Connection conn, DBFormulaSet dbFormulaSet) throws SQLException { /* 229 */ if (dbFormulaSet.getFormulaList() == null) /* 230 */ return; if (dbFormulaSet.getFormulaList().isEmpty()) /* */ return; /* 232 */ String insert = "INSERT INTO GD_FORMULA VALUES (?,?,?)"; /* */ /* 234 */ try (PreparedStatement ps = conn.prepareStatement(insert)) { /* 235 */ for (DBFormula formula : dbFormulaSet.getFormulaList()) { /* 236 */ ps.setString(1, dbFormulaSet.getFormulaSetID()); /* 237 */ ps.setString(2, formula.formulaID); /* 238 */ ps.setString(3, formula.formula); /* */ /* 240 */ ps.executeUpdate(); /* */ /* 242 */ ps.clearParameters(); /* */ } /* 244 */ ps.close(); /* */ /* 246 */ conn.commit(); /* */ } /* 248 */ catch (SQLException ex) { /* 249 */ throw ex; /* */ } /* */ } /* */ /* */ public static List<DBFormula> getByFormulaSetID(String formulaSetID) { /* 254 */ List<DBFormula> list = null; /* */ /* 256 */ String command = "SELECT * FROM GD_FORMULA WHERE FORMULASET_ID = ?"; /* */ /* 258 */ try(Connection conn = GDDBData.getConnection(); /* 259 */ PreparedStatement ps = conn.prepareStatement(command)) { /* 260 */ ps.setString(1, formulaSetID); /* */ /* 262 */ try (ResultSet rs = ps.executeQuery()) { /* 263 */ list = wrap(rs); /* */ /* 265 */ conn.commit(); /* */ } /* 267 */ catch (SQLException ex) { /* 268 */ throw ex; /* */ } /* */ /* 271 */ } catch (SQLException ex) { /* 272 */ Object[] args = { formulaSetID, "GD_FORMULA" }; /* 273 */ String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_READ_TABLE_BY_ID", args); /* */ /* 275 */ GDMsgLogger.addError(msg); /* 276 */ GDMsgLogger.addError(ex); /* */ } /* */ /* 279 */ return list; /* */ } /* */ /* */ private static List<DBFormula> wrap(ResultSet rs) throws SQLException { /* 283 */ LinkedList<DBFormula> list = new LinkedList<>(); /* */ /* 285 */ while (rs.next()) { /* 286 */ DBFormula formula = new DBFormula(); /* */ /* 288 */ formula.formulaSetID = rs.getString(1); /* 289 */ formula.formulaID = rs.getString(2); /* 290 */ formula.formula = rs.getString(3); /* */ /* 292 */ if (formula.formula != null) formula.formula = formula.formula.toUpperCase(GDConstants.LOCALE_US); /* */ /* 294 */ formula.setFormula(formula.formula); /* */ /* 296 */ list.add(formula); /* */ } /* */ /* 299 */ return list; /* */ } /* */ } /* Location: C:\game\Grim Dawn\GDStash.jar!\org\gdstash\db\DBFormula.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
jonclothcat/OpenPype
openpype/hosts/photoshop/api/pipeline.py
<gh_stars>0 import os from Qt import QtWidgets import pyblish.api import avalon.api from avalon import pipeline, io from openpype.api import Logger from openpype.lib import register_event_callback from openpype.pipeline import ( LegacyCreator, register_loader_plugin_path, deregister_loader_plugin_path, ) import openpype.hosts.photoshop from . import lib log = Logger.get_logger(__name__) HOST_DIR = os.path.dirname(os.path.abspath(openpype.hosts.photoshop.__file__)) PLUGINS_DIR = os.path.join(HOST_DIR, "plugins") PUBLISH_PATH = os.path.join(PLUGINS_DIR, "publish") LOAD_PATH = os.path.join(PLUGINS_DIR, "load") CREATE_PATH = os.path.join(PLUGINS_DIR, "create") INVENTORY_PATH = os.path.join(PLUGINS_DIR, "inventory") def check_inventory(): if not lib.any_outdated(): return host = avalon.api.registered_host() outdated_containers = [] for container in host.ls(): representation = container['representation'] representation_doc = io.find_one( { "_id": io.ObjectId(representation), "type": "representation" }, projection={"parent": True} ) if representation_doc and not lib.is_latest(representation_doc): outdated_containers.append(container) # Warn about outdated containers. print("Starting new QApplication..") message_box = QtWidgets.QMessageBox() message_box.setIcon(QtWidgets.QMessageBox.Warning) msg = "There are outdated containers in the scene." message_box.setText(msg) message_box.exec_() def on_application_launch(): check_inventory() def on_pyblish_instance_toggled(instance, old_value, new_value): """Toggle layer visibility on instance toggles.""" instance[0].Visible = new_value def install(): """Install Photoshop-specific functionality of avalon-core. This function is called automatically on calling `api.install(photoshop)`. """ log.info("Installing OpenPype Photoshop...") pyblish.api.register_host("photoshop") pyblish.api.register_plugin_path(PUBLISH_PATH) register_loader_plugin_path(LOAD_PATH) avalon.api.register_plugin_path(LegacyCreator, CREATE_PATH) log.info(PUBLISH_PATH) pyblish.api.register_callback( "instanceToggled", on_pyblish_instance_toggled ) register_event_callback("application.launched", on_application_launch) def uninstall(): pyblish.api.deregister_plugin_path(PUBLISH_PATH) deregister_loader_plugin_path(LOAD_PATH) avalon.api.deregister_plugin_path(LegacyCreator, CREATE_PATH) def ls(): """Yields containers from active Photoshop document This is the host-equivalent of api.ls(), but instead of listing assets on disk, it lists assets already loaded in Photoshop; once loaded they are called 'containers' Yields: dict: container """ try: stub = lib.stub() # only after Photoshop is up except lib.ConnectionNotEstablishedYet: print("Not connected yet, ignoring") return if not stub.get_active_document_name(): return layers_meta = stub.get_layers_metadata() # minimalize calls to PS for layer in stub.get_layers(): data = stub.read(layer, layers_meta) # Skip non-tagged layers. if not data: continue # Filter to only containers. if "container" not in data["id"]: continue # Append transient data data["objectName"] = layer.name.replace(stub.LOADED_ICON, '') data["layer"] = layer yield data def list_instances(): """List all created instances to publish from current workfile. Pulls from File > File Info For SubsetManager Returns: (list) of dictionaries matching instances format """ stub = _get_stub() if not stub: return [] instances = [] layers_meta = stub.get_layers_metadata() if layers_meta: for key, instance in layers_meta.items(): schema = instance.get("schema") if schema and "container" in schema: continue instance['uuid'] = key instances.append(instance) return instances def remove_instance(instance): """Remove instance from current workfile metadata. Updates metadata of current file in File > File Info and removes icon highlight on group layer. For SubsetManager Args: instance (dict): instance representation from subsetmanager model """ stub = _get_stub() if not stub: return stub.remove_instance(instance.get("uuid")) layer = stub.get_layer(instance.get("uuid")) if layer: stub.rename_layer(instance.get("uuid"), layer.name.replace(stub.PUBLISH_ICON, '')) def _get_stub(): """Handle pulling stub from PS to run operations on host Returns: (PhotoshopServerStub) or None """ try: stub = lib.stub() # only after Photoshop is up except lib.ConnectionNotEstablishedYet: print("Not connected yet, ignoring") return if not stub.get_active_document_name(): return return stub def containerise( name, namespace, layer, context, loader=None, suffix="_CON" ): """Imprint layer with metadata Containerisation enables a tracking of version, author and origin for loaded assets. Arguments: name (str): Name of resulting assembly namespace (str): Namespace under which to host container layer (PSItem): Layer to containerise context (dict): Asset information loader (str, optional): Name of loader used to produce this container. suffix (str, optional): Suffix of container, defaults to `_CON`. Returns: container (str): Name of container assembly """ layer.name = name + suffix data = { "schema": "openpype:container-2.0", "id": pipeline.AVALON_CONTAINER_ID, "name": name, "namespace": namespace, "loader": str(loader), "representation": str(context["representation"]["_id"]), "members": [str(layer.id)] } stub = lib.stub() stub.imprint(layer, data) return layer
ScalablyTyped/SlinkyTyped
d/dojo/src/main/scala/typingsSlinky/dojo/contextMenuTabMod.scala
package typingsSlinky.dojo import org.scalablytyped.runtime.TopLevel import typingsSlinky.dojo.dojox.gantt.contextMenuTab import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation._ @JSImport("dojox/gantt/contextMenuTab", JSImport.Namespace) @js.native object contextMenuTabMod extends TopLevel[contextMenuTab]
Kirishikesan/haiku
src/servers/app/Layer.cpp
/* * Copyright 2015 <NAME> <<EMAIL>> * All rights reserved. Distributed under the terms of the MIT license. */ #include "Layer.h" #include "AlphaMask.h" #include "BitmapHWInterface.h" #include "DrawingEngine.h" #include "DrawState.h" #include "IntRect.h" #include "PictureBoundingBoxPlayer.h" #include "ServerBitmap.h" #include "View.h" class LayerCanvas : public Canvas { public: LayerCanvas(DrawingEngine* drawingEngine, DrawState* drawState, BRect bitmapBounds) : Canvas(), fDrawingEngine(drawingEngine), fBitmapBounds(bitmapBounds) { delete fDrawState; fDrawState = drawState; } virtual DrawingEngine* GetDrawingEngine() const { return fDrawingEngine; } virtual ServerPicture* GetPicture(int32 token) const { return NULL; } virtual void RebuildClipping(bool) { } virtual void ResyncDrawState() { fDrawingEngine->SetDrawState(fDrawState); } virtual void UpdateCurrentDrawingRegion() { bool hasDrawStateClipping = fDrawState->GetCombinedClippingRegion( &fCurrentDrawingRegion); BRegion bitmapRegion(fBitmapBounds); if (hasDrawStateClipping) fCurrentDrawingRegion.IntersectWith(&bitmapRegion); else fCurrentDrawingRegion = bitmapRegion; fDrawingEngine->ConstrainClippingRegion(&fCurrentDrawingRegion); } virtual IntRect Bounds() const { return fBitmapBounds; } protected: virtual void _LocalToScreenTransform(SimpleTransform&) const { } virtual void _ScreenToLocalTransform(SimpleTransform&) const { } private: DrawingEngine* fDrawingEngine; BRegion fCurrentDrawingRegion; BRect fBitmapBounds; }; Layer::Layer(uint8 opacity) : fOpacity(opacity), fLeftTopOffset(0, 0) { } Layer::~Layer() { } void Layer::PushLayer(Layer* layer) { PushPicture(layer); } Layer* Layer::PopLayer() { Layer* const previousLayer = static_cast<Layer*>(PopPicture()); if (previousLayer != NULL) previousLayer->ReleaseReference(); return previousLayer; } UtilityBitmap* Layer::RenderToBitmap(Canvas* canvas) { BRect boundingBox = _DetermineBoundingBox(canvas); if (!boundingBox.IsValid()) return NULL; fLeftTopOffset = boundingBox.LeftTop(); UtilityBitmap* const layerBitmap = _AllocateBitmap(boundingBox); if (layerBitmap == NULL) return NULL; BitmapHWInterface layerInterface(layerBitmap); DrawingEngine* const layerEngine = layerInterface.CreateDrawingEngine(); if (layerEngine == NULL) { layerBitmap->ReleaseReference(); return NULL; } layerEngine->SetRendererOffset(boundingBox.left, boundingBox.top); // Drawing commands of the layer's picture use coordinates in the // coordinate space of the underlying canvas. The coordinate origin // of the layer bitmap is at boundingBox.LeftTop(). So all the drawing // from the picture needs to be offset to be moved into the bitmap. // We use a low-level offsetting via the AGG renderer here because the // offset needs to be processed independently, after all other // transforms, even after the BAffineTransforms (which are processed in // Painter), to prevent this origin from being further transformed by // e.g. scaling. LayerCanvas layerCanvas(layerEngine, canvas->CurrentState(), boundingBox); AlphaMask* const mask = layerCanvas.GetAlphaMask(); IntPoint oldOffset; if (mask != NULL) { // Move alpha mask to bitmap origin oldOffset = mask->SetCanvasGeometry(IntPoint(0, 0), boundingBox); } canvas->CurrentState()->SetDrawingMode(B_OP_ALPHA); canvas->CurrentState()->SetBlendingMode(B_PIXEL_ALPHA, B_ALPHA_COMPOSITE); layerCanvas.ResyncDrawState(); // Apply state to the new drawing engine of the layer canvas if (layerEngine->LockParallelAccess()) { layerCanvas.UpdateCurrentDrawingRegion(); // Draw recorded picture into bitmap Play(&layerCanvas); layerEngine->UnlockParallelAccess(); } if (mask != NULL) { // Move alpha mask back to its old position // Note: this needs to be adapted if setting alpha masks is // implemented as BPicture command (the mask now might be a different // one than before). layerCanvas.CurrentState()->CombinedTransform().Apply(oldOffset); mask->SetCanvasGeometry(oldOffset, boundingBox); layerCanvas.ResyncDrawState(); } canvas->SetDrawState(layerCanvas.CurrentState()); // Update state in canvas (the top-of-stack state could be a different // state instance now, if the picture commands contained push/pop // commands) delete layerEngine; return layerBitmap; } IntPoint Layer::LeftTopOffset() const { return fLeftTopOffset; } uint8 Layer::Opacity() const { return fOpacity; } BRect Layer::_DetermineBoundingBox(Canvas* canvas) { BRect boundingBox; PictureBoundingBoxPlayer::Play(this, canvas->CurrentState(), &boundingBox); if (!boundingBox.IsValid()) return boundingBox; // Round up and add an additional 2 pixels on the bottom/right to // compensate for the various types of rounding used in Painter. boundingBox.left = floorf(boundingBox.left); boundingBox.right = ceilf(boundingBox.right) + 2; boundingBox.top = floorf(boundingBox.top); boundingBox.bottom = ceilf(boundingBox.bottom) + 2; // TODO: for optimization, crop the bounding box to the underlying // view bounds here return boundingBox; } UtilityBitmap* Layer::_AllocateBitmap(const BRect& bounds) { UtilityBitmap* const layerBitmap = new(std::nothrow) UtilityBitmap(bounds, B_RGBA32, 0); if (layerBitmap == NULL) return NULL; if (!layerBitmap->IsValid()) { delete layerBitmap; return NULL; } memset(layerBitmap->Bits(), 0, layerBitmap->BitsLength()); return layerBitmap; }
Ligh7bringer/Hazel
Hazelnut/src/Panels/SceneHierarchyPanel.hpp
<filename>Hazelnut/src/Panels/SceneHierarchyPanel.hpp #pragma once #include "Hazel/Core/Core.hpp" #include "Hazel/Renderer/Texture.hpp" #include "Hazel/Scene/Entity.hpp" #include "Hazel/Scene/Scene.hpp" namespace Hazel { class SceneHierarchyPanel { public: SceneHierarchyPanel() = default; explicit SceneHierarchyPanel(const Ref<Scene>& context); void SetContext(const Ref<Scene>& context); void OnImGuiRender(); Entity GetSelectedEntity() const { return m_SelectionContext; } void SetSelectedEntity(Entity entity); private: void DrawEntityNode(Entity entity); void DrawComponents(Entity entity); private: Ref<Scene> m_Context; Entity m_SelectionContext; Ref<Texture2D> m_DefaultTexture; }; } // namespace Hazel
valitydev/newway
src/test/java/dev/vality/newway/IntegrationTest.java
package dev.vality.newway; import dev.vality.damsel.domain.*; import dev.vality.damsel.payment_processing.*; import dev.vality.geck.common.util.TypeUtil; import dev.vality.machinegun.eventsink.MachineEvent; import dev.vality.machinegun.msgpack.Value; import dev.vality.newway.config.PostgresqlSpringBootITest; import dev.vality.newway.dao.invoicing.iface.PaymentDao; import dev.vality.newway.domain.enums.PaymentStatus; import dev.vality.newway.domain.tables.pojos.Payment; import dev.vality.newway.service.InvoicingService; import dev.vality.newway.utils.MockUtils; import dev.vality.sink.common.serialization.impl.PaymentEventPayloadSerializer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; @PostgresqlSpringBootITest public class IntegrationTest { @Autowired private InvoicingService invoicingService; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private PaymentDao paymentDao; @Test public void test() { PaymentEventPayloadSerializer serializer = new PaymentEventPayloadSerializer(); String invoiceId = "inv_id"; String paymentId = "1"; List<MachineEvent> machineEventsFirst = List.of( new MachineEvent().setSourceId(invoiceId) .setEventId(1) .setCreatedAt(TypeUtil.temporalToString(LocalDateTime.now())) .setData(Value.bin(serializer.serialize( EventPayload.invoice_changes( List.of(InvoiceChange.invoice_created(new InvoiceCreated() .setInvoice(MockUtils.buildInvoice(invoiceId))), InvoiceChange.invoice_status_changed(new InvoiceStatusChanged() .setStatus( InvoiceStatus.fulfilled( new InvoiceFulfilled("keks")))), InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload(InvoicePaymentChangePayload .invoice_payment_started(new InvoicePaymentStarted() .setPayment( MockUtils.buildPayment(paymentId))))), InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload(InvoicePaymentChangePayload .invoice_payment_cash_flow_changed( new InvoicePaymentCashFlowChanged( List.of(new FinalCashFlowPosting() .setSource( new FinalCashFlowAccount( CashFlowAccount .system(SystemCashFlowAccount.settlement), 1)) .setDestination( new FinalCashFlowAccount( CashFlowAccount .system(SystemCashFlowAccount.settlement), 1)) .setVolume(new Cash(1, new CurrencyRef( "RUB"))))) ))), InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload(InvoicePaymentChangePayload .invoice_payment_risk_score_changed( new InvoicePaymentRiskScoreChanged( RiskScore.high)))), InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload(InvoicePaymentChangePayload .invoice_payment_status_changed( new InvoicePaymentStatusChanged().setStatus( InvoicePaymentStatus.captured( new InvoicePaymentCaptured())) )))))))) ); invoicingService.handleEvents(machineEventsFirst); Assertions.assertEquals(3, Objects.requireNonNull(jdbcTemplate.queryForObject("SELECT count(*) FROM nw.payment " + "WHERE invoice_id = ? and payment_id = ? ", new Object[]{invoiceId, paymentId}, Integer.class)).intValue()); Payment payment = paymentDao.get(invoiceId, paymentId); Assertions.assertEquals(PaymentStatus.captured, payment.getStatus()); Assertions.assertEquals("high", payment.getRiskScore().name()); Assertions.assertEquals(1, Objects.requireNonNull(jdbcTemplate.queryForObject("SELECT count(*) FROM nw.cash_flow WHERE obj_id = ? ", new Object[]{payment.getId()}, Integer.class)).intValue()); //--- second changes - only update List<MachineEvent> machineEventsSecond = List.of( new MachineEvent().setSourceId(invoiceId) .setEventId(2) .setCreatedAt(TypeUtil.temporalToString(LocalDateTime.now())) .setData(Value.bin(serializer.serialize( EventPayload.invoice_changes( List.of(InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload( InvoicePaymentChangePayload .invoice_payment_risk_score_changed( new InvoicePaymentRiskScoreChanged( RiskScore.low)))), InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload(InvoicePaymentChangePayload .invoice_payment_rec_token_acquired( new InvoicePaymentRecTokenAcquired("keks") ))) ))))) ); invoicingService.handleEvents(machineEventsSecond); Assertions.assertEquals(3, Objects.requireNonNull(jdbcTemplate.queryForObject("SELECT count(*) FROM nw.payment " + "WHERE invoice_id = ? and payment_id = ? ", new Object[]{invoiceId, paymentId}, Integer.class)).intValue()); Payment paymentSecond = paymentDao.get(invoiceId, paymentId); Assertions.assertEquals("low", paymentSecond.getRiskScore().name()); Assertions.assertEquals("keks", paymentSecond.getRecurrentIntentionToken()); Assertions.assertEquals(paymentSecond.getId(), payment.getId()); //--- third changes - insert List<MachineEvent> machineEventsThird = List.of( new MachineEvent().setSourceId(invoiceId) .setEventId(3) .setCreatedAt(TypeUtil.temporalToString(LocalDateTime.now())) .setData(Value.bin(serializer.serialize( EventPayload.invoice_changes( List.of(InvoiceChange.invoice_payment_change(new InvoicePaymentChange() .setId(paymentId) .setPayload(InvoicePaymentChangePayload.invoice_payment_status_changed( new InvoicePaymentStatusChanged() .setStatus(InvoicePaymentStatus.failed( new InvoicePaymentFailed(OperationFailure .operation_timeout( new OperationTimeout())))) )))))))) ); invoicingService.handleEvents(machineEventsThird); Assertions.assertEquals(4, Objects.requireNonNull(jdbcTemplate.queryForObject("SELECT count(*) FROM nw.payment " + "WHERE invoice_id = ? and payment_id = ? ", new Object[]{invoiceId, paymentId}, Integer.class)).intValue()); Payment paymentThird = paymentDao.get(invoiceId, paymentId); Assertions.assertEquals(PaymentStatus.failed, paymentThird.getStatus()); Assertions.assertEquals(3, paymentThird.getSequenceId().longValue()); Assertions.assertNotEquals(paymentSecond.getId(), paymentThird.getId()); Assertions.assertEquals(1, Objects.requireNonNull(jdbcTemplate.queryForObject("SELECT count(*) FROM nw.cash_flow WHERE obj_id = ? ", new Object[]{paymentThird.getId()}, Integer.class)).intValue()); //--- duplication check invoicingService.handleEvents(machineEventsFirst); Assertions.assertEquals(4, Objects.requireNonNull(jdbcTemplate.queryForObject("SELECT count(*) FROM nw.payment WHERE invoice_id = ? and payment_id = ? ", new Object[]{invoiceId, paymentId}, Integer.class)).intValue()); } }
straceX/Ectoplasm
linux-1.2.0/linux/arch/i386/kernel/setup.c
/* * linux/arch/i386/kernel/setup.c * * Copyright (C) 1995 <NAME> */ /* * This file handles the architecture-dependent parts of process handling.. */ #include <linux/errno.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/ptrace.h> #include <linux/malloc.h> #include <linux/ldt.h> #include <linux/user.h> #include <linux/a.out.h> #include <linux/tty.h> #include <linux/ioport.h> #include <asm/segment.h> #include <asm/system.h> /* * Tell us the machine setup.. */ char hard_math = 0; /* set by boot/head.S */ char x86 = 0; /* set by boot/head.S to 3 or 4 */ char x86_model = 0; /* set by boot/head.S */ char x86_mask = 0; /* set by boot/head.S */ int x86_capability = 0; /* set by boot/head.S */ int fdiv_bug = 0; /* set if Pentium(TM) with FP bug */ char x86_vendor_id[13] = "Unknown"; char ignore_irq13 = 0; /* set if exception 16 works */ char wp_works_ok = 0; /* set if paging hardware honours WP */ char hlt_works_ok = 1; /* set if the "hlt" instruction works */ /* * Bus types .. */ int EISA_bus = 0; /* * Setup options */ struct drive_info_struct { char dummy[32]; } drive_info; struct screen_info screen_info; unsigned char aux_device_present; extern int ramdisk_size; extern int root_mountflags; extern int etext, edata, end; extern char empty_zero_page[PAGE_SIZE]; /* * This is set up by the setup-routine at boot-time */ #define PARAM empty_zero_page #define EXT_MEM_K (*(unsigned short *) (PARAM+2)) #define DRIVE_INFO (*(struct drive_info_struct *) (PARAM+0x80)) #define SCREEN_INFO (*(struct screen_info *) (PARAM+0)) #define MOUNT_ROOT_RDONLY (*(unsigned short *) (PARAM+0x1F2)) #define RAMDISK_SIZE (*(unsigned short *) (PARAM+0x1F8)) #define ORIG_ROOT_DEV (*(unsigned short *) (PARAM+0x1FC)) #define AUX_DEVICE_INFO (*(unsigned char *) (PARAM+0x1FF)) #define COMMAND_LINE ((char *) (PARAM+2048)) #define COMMAND_LINE_SIZE 256 static char command_line[COMMAND_LINE_SIZE] = { 0, }; void setup_arch(char **cmdline_p, unsigned long * memory_start_p, unsigned long * memory_end_p) { unsigned long memory_start, memory_end; char c = ' ', *to = command_line, *from = COMMAND_LINE; int len = 0; ROOT_DEV = ORIG_ROOT_DEV; drive_info = DRIVE_INFO; screen_info = SCREEN_INFO; aux_device_present = AUX_DEVICE_INFO; memory_end = (1<<20) + (EXT_MEM_K<<10); memory_end &= PAGE_MASK; ramdisk_size = RAMDISK_SIZE; #ifdef CONFIG_MAX_16M if (memory_end > 16*1024*1024) memory_end = 16*1024*1024; #endif if (MOUNT_ROOT_RDONLY) root_mountflags |= MS_RDONLY; memory_start = (unsigned long) &end; init_task.mm->start_code = TASK_SIZE; init_task.mm->end_code = TASK_SIZE + (unsigned long) &etext; init_task.mm->end_data = TASK_SIZE + (unsigned long) &edata; init_task.mm->brk = TASK_SIZE + (unsigned long) &end; for (;;) { if (c == ' ' && *(unsigned long *)from == *(unsigned long *)"mem=") { memory_end = simple_strtoul(from+4, &from, 0); if ( *from == 'K' || *from == 'k' ) { memory_end = memory_end << 10; from++; } else if ( *from == 'M' || *from == 'm' ) { memory_end = memory_end << 20; from++; } } c = *(from++); if (!c) break; if (COMMAND_LINE_SIZE <= ++len) break; *(to++) = c; } *to = '\0'; *cmdline_p = command_line; *memory_start_p = memory_start; *memory_end_p = memory_end; /* request io space for devices used on all i[345]86 PC'S */ request_region(0x00,0x20,"dma1"); request_region(0x40,0x20,"timer"); request_region(0x70,0x10,"rtc"); request_region(0x80,0x20,"dma page reg"); request_region(0xc0,0x20,"dma2"); request_region(0xf0,0x2,"npu"); request_region(0xf8,0x8,"npu"); }
polarG/splunk-connect-for-snmp
test/common/test_humanbool.py
<reponame>polarG/splunk-connect-for-snmp from unittest import TestCase from splunk_connect_for_snmp.common.hummanbool import human_bool class TestHumanBool(TestCase): def test_human_bool_true(self): self.assertTrue(human_bool("t")) self.assertTrue(human_bool("T")) self.assertTrue(human_bool("True")) self.assertTrue(human_bool("true")) self.assertTrue(human_bool("TrUe")) self.assertTrue(human_bool("y")) self.assertTrue(human_bool("yes")) self.assertTrue(human_bool("1")) self.assertTrue(human_bool(True)) def test_human_bool_false(self): self.assertFalse(human_bool("f")) self.assertFalse(human_bool("F")) self.assertFalse(human_bool("False")) self.assertFalse(human_bool("fAlSe")) self.assertFalse(human_bool("n")) self.assertFalse(human_bool("no")) self.assertFalse(human_bool("0")) self.assertFalse(human_bool(False)) def test_human_bool_none(self): self.assertFalse(human_bool(flag=None)) def test_human_bool_default(self): self.assertTrue(human_bool("foo", True)) self.assertFalse(human_bool("1foo", False)) self.assertFalse(human_bool("1FoO"))
AjanShrestha/nfc
client/src/services/h2h/__tests__/epic.test.js
<filename>client/src/services/h2h/__tests__/epic.test.js // npm packages import {ActionsObservable} from 'redux-observable'; import {Observable} from 'rxjs/Observable'; // our packages import H2HEpic from '../epic'; import {FETCH_DATA} from '../actionTypes'; import H2HData from './h2hData.json'; import {h2hLeagueAPI} from '../../api'; jest.mock('../../api', () => ({ h2hLeagueAPI: {getH2HStandings: jest.fn()}, })); describe('H2H Epic', () => { beforeAll(() => { const h2hLeagueAPIMock = jest.fn(); h2hLeagueAPIMock .mockReturnValueOnce(H2HData) .mockReturnValueOnce(Observable.throw('Data Rejected')); h2hLeagueAPI.getH2HStandings.mockImplementation(h2hLeagueAPIMock); }); test('Fetch H2H Standing', () => { const input$ = ActionsObservable.from([{type: FETCH_DATA}]); H2HEpic.fetchH2HStandingsEpic(input$) .toArray() .subscribe(res => { expect(res.length).toBe(8); expect(res).toEqual([ { payload: { league: {id: 1, name: 'Test1'}, matches_next: {results: [{}]}, matches_this: { results: [ { entry_1_entry: 101, entry_1_name: 'Test_101', entry_1_player_name: 'Player 101', entry_1_points: 101, entry_2_entry: 102, entry_2_name: 'Test_102', entry_2_player_name: 'Player 102', entry_2_points: 102, id: 1, }, { entry_1_entry: 103, entry_1_name: 'Test_103', entry_1_player_name: 'Player 103', entry_1_points: 106, entry_2_entry: 104, entry_2_name: 'Test_104', entry_2_player_name: 'Player 104', entry_2_points: 104, id: 2, }, { entry_1_entry: 105, entry_1_name: 'Test_105', entry_1_player_name: 'Player 105', entry_1_points: 105, entry_2_entry: 106, entry_2_name: 'Test_106', entry_2_player_name: 'Player 106', entry_2_points: 106, id: 3, }, ], }, new_entries: {}, standings: { results: [ { entry_name: 'Test_101', id: 101, matches_drawn: 1, matches_lost: 8, matches_won: 15, player_name: 'Player 101', points_for: 1368, points_total: 46, rank: 1, }, ], }, }, type: '@H2H/DATA_FETCHED', }, { payload: { league: {id: 1, name: 'Test1'}, matches_next: {results: [{}]}, matches_this: { results: [ { entry_1_entry: 101, entry_1_name: 'Test_101', entry_1_player_name: 'Player 101', entry_1_points: 101, entry_2_entry: 102, entry_2_name: 'Test_102', entry_2_player_name: 'Player 102', entry_2_points: 102, id: 1, }, { entry_1_entry: 103, entry_1_name: 'Test_103', entry_1_player_name: 'Player 103', entry_1_points: 106, entry_2_entry: 104, entry_2_name: 'Test_104', entry_2_player_name: 'Player 104', entry_2_points: 104, id: 2, }, { entry_1_entry: 105, entry_1_name: 'Test_105', entry_1_player_name: 'Player 105', entry_1_points: 105, entry_2_entry: 106, entry_2_name: 'Test_106', entry_2_player_name: 'Player 106', entry_2_points: 106, id: 3, }, ], }, new_entries: {}, standings: { results: [ { entry_name: 'Test_101', id: 101, matches_drawn: 1, matches_lost: 8, matches_won: 15, player_name: 'Player 101', points_for: 1368, points_total: 46, rank: 1, }, ], }, }, type: '@H2H/EXTRACT_WINNERS', }, {type: '@H2H/SET_LINKS'}, {type: '@H2H/SET_DEFAULT_ROUTE'}, { payload: { league: {id: 2, name: 'Test2'}, matches_next: {results: [{}]}, matches_this: { results: [ { entry_1_entry: 201, entry_1_name: 'Test_201', entry_1_player_name: 'Player 201', entry_1_points: 201, entry_2_entry: 202, entry_2_name: 'Test_202', entry_2_player_name: 'Player 202', entry_2_points: 212, id: 1, }, { entry_1_entry: 203, entry_1_name: 'Test_203', entry_1_player_name: 'Player 203', entry_1_points: 203, entry_2_entry: 204, entry_2_name: 'Test_204', entry_2_player_name: 'Player 204', entry_2_points: 204, id: 2, }, { entry_1_entry: 205, entry_1_name: 'Test_205', entry_1_player_name: 'Player 205', entry_1_points: 205, entry_2_entry: 206, entry_2_name: 'Test_206', entry_2_player_name: 'Player 106', entry_2_points: 206, id: 3, }, ], }, new_entries: {}, standings: { results: [ { entry_name: 'Test_201', id: 201, matches_drawn: 1, matches_lost: 8, matches_won: 15, player_name: 'Player 201', points_for: 1368, points_total: 46, rank: 1, }, ], }, }, type: '@H2H/DATA_FETCHED', }, { payload: { league: {id: 2, name: 'Test2'}, matches_next: {results: [{}]}, matches_this: { results: [ { entry_1_entry: 201, entry_1_name: 'Test_201', entry_1_player_name: 'Player 201', entry_1_points: 201, entry_2_entry: 202, entry_2_name: 'Test_202', entry_2_player_name: 'Player 202', entry_2_points: 212, id: 1, }, { entry_1_entry: 203, entry_1_name: 'Test_203', entry_1_player_name: 'Player 203', entry_1_points: 203, entry_2_entry: 204, entry_2_name: 'Test_204', entry_2_player_name: 'Player 204', entry_2_points: 204, id: 2, }, { entry_1_entry: 205, entry_1_name: 'Test_205', entry_1_player_name: 'Player 205', entry_1_points: 205, entry_2_entry: 206, entry_2_name: 'Test_206', entry_2_player_name: 'Player 106', entry_2_points: 206, id: 3, }, ], }, new_entries: {}, standings: { results: [ { entry_name: 'Test_201', id: 201, matches_drawn: 1, matches_lost: 8, matches_won: 15, player_name: 'Player 201', points_for: 1368, points_total: 46, rank: 1, }, ], }, }, type: '@H2H/EXTRACT_WINNERS', }, {type: '@H2H/SET_LINKS'}, {type: '@H2H/SET_DEFAULT_ROUTE'}, ]); }); }); test('Fetch H2H Data Failture', () => { const input$ = ActionsObservable.from([{type: FETCH_DATA}]); H2HEpic.fetchH2HStandingsEpic(input$) .toArray() .subscribe(response => expect(response).toEqual([ { type: '@H2H/FETCH_DATA_REJECTED', payload: 'Data Rejected', error: true, }, ]) ); }); });
npocmaka/Windows-Server-2003
admin/dsutils/displayspecifierupgrade/test/test.cpp
<filename>admin/dsutils/displayspecifierupgrade/test/test.cpp #include "headers.hxx" #include "..\dspecup.hpp" #include <windows.h> void stepIt(long arg, void *vTotal) { long *total=(long *)vTotal; printf("\r" "\r%ld",(*total)+=arg); } void totalSteps(long arg, void *vTotal) { long *total=(long *)vTotal; *total=0; printf("\n%ld\n",arg); } void __cdecl wmain(int argc,wchar_t *argv[]) { char *usage; usage="\nYou should pass one or more guids to specify the operation(s).\n " "Ex: test.exe 4444c516-f43a-4c12-9c4b-b5c064941d61 ffa5ee3c-1405-476d" "-b344-7ad37d69cc25\n"; if(argc<2) {printf(usage);return;} GUID guid; long total=0; HRESULT hr=S_OK; wchar_t curDir[MAX_PATH+1]; GetCurrentDirectory(MAX_PATH,curDir); PWSTR errorMsg=NULL; do { for(int cont=1;cont<argc;cont++) { if(UuidFromString(argv[cont],&guid)!=RPC_S_OK) {printf(usage);return;} hr=UpgradeDisplaySpecifiers ( curDir, &guid, false, &errorMsg, &total, stepIt, totalSteps ); if(FAILED(hr)) break; } } while(0); if(FAILED(hr)) { if(errorMsg!=NULL) { wprintf(L"%s\n",errorMsg); LocalFree(errorMsg); } } }
npocmaka/Windows-Server-2003
ds/security/protocols/msv_sspi/test/lib/hresult.cxx
<gh_stars>10-100 /*++ Copyright (c) 2001 Microsoft Corporation All rights reserved. Module Name: hresult.cxx Abstract: auto log Author: <NAME> (LZhu) December 6, 2001 Revision History: --*/ #include "precomp.hxx" #pragma hdrstop #include "hresult.hxx" #ifdef DBG /******************************************************************** THResult members ********************************************************************/ THResult:: THResult( IN HRESULT hResult ) : TStatusDerived<HRESULT>(hResult) { } THResult:: ~THResult( VOID ) { } BOOL THResult:: IsErrorSevereEnough( VOID ) const { HRESULT hResult = GetTStatusBase(); return FAILED(hResult); } PCTSTR THResult:: GetErrorServerityDescription( VOID ) const { HRESULT hResult = GetTStatusBase(); return SUCCEEDED(hResult) ? TEXT("SUCCEEDED") : TEXT("FAILED"); } #endif // DBG EXTERN_C HRESULT HResultFromWin32( IN DWORD dwError ) { return HRESULT_FROM_WIN32(dwError); } EXTERN_C HRESULT GetLastErrorAsHResult( VOID ) { return HResultFromWin32(GetLastError()); }
Atomicwallet/lisk-sdk
framework/dist-node/node/utils/error_handlers.js
<reponame>Atomicwallet/lisk-sdk<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class CommonBlockError extends Error { constructor(message, lastBlockID) { super(message); this.lastBlockID = lastBlockID.toString('hex'); } } exports.CommonBlockError = CommonBlockError; exports.convertErrorsToString = (errors) => { if (Array.isArray(errors) && errors.length > 0) { return errors .filter((e) => e instanceof Error) .map((error) => error.message) .join(', '); } if (errors instanceof Error) { return errors.message; } if (typeof errors === 'string') { return errors; } return ''; }; //# sourceMappingURL=error_handlers.js.map
hleclerc/Evel
src/Evel/Signal_WF.h
#pragma once #include <functional> #include "Signal.h" namespace Evel { /** */ class Signal_WF : public Signal { public: using TF_signal = std::function<void( Signal_WF *, int sig )>; Signal_WF( const int *sigs, TF_signal &&f = {} ); TF_signal f_signal; protected: virtual void signal( int s ); }; } // namespace Evel
ExCaVI-Ulm/3D-XGuide
src/interaction/vtkInteractorStyleMy2D.h
#ifndef VTKINTERACTORSTYLEMY2D_H #define VTKINTERACTORSTYLEMY2D_H #include "vtkInteractorStyleTrackballCamera.h" class vtkUnsignedCharArray; /** Triggers a SelectionChangeEvent when the user clicks. * reinterpret_cast<double*>(callData) holds the click * position (x,y,z) in VTK world coordinates. */ class vtkInteractorStyleMy2D : public vtkInteractorStyleTrackballCamera { public: static vtkInteractorStyleMy2D *New() { return new vtkInteractorStyleMy2D(); } void PrintSelf(ostream& os, vtkIndent indent); virtual void OnLeftButtonDown(); virtual void OnLeftButtonUp(); virtual void OnMiddleButtonDown(); virtual void OnMiddleButtonUp(); virtual void OnRightButtonDown(); virtual void OnRightButtonUp(); virtual void OnMouseMove(); virtual void OnMouseWheelForward(); virtual void OnMouseWheelBackward(); //BTX // Description: // Selection types enum { SELECT_NORMAL = 0, SELECT_UNION = 1 }; //ETX // Description: // Current interaction state vtkGetMacro(Interaction, int); //BTX enum { NONE, PANNING, ZOOMING, ROTATING, SELECTING }; //ETX protected: vtkInteractorStyleMy2D(); ~vtkInteractorStyleMy2D(); // The interaction mode int Interaction; /// Draws the selection rubber band void RedrawRubberBand(); // The end position of the selection int StartPosition[2]; // The start position of the selection int EndPosition[2]; // The pixel array for the rubber band vtkUnsignedCharArray* PixelArray; private: vtkInteractorStyleMy2D(const vtkInteractorStyleMy2D&); //Not implemented void operator=(const vtkInteractorStyleMy2D&); // Not implemented }; #endif
LabKey/wnprc-modules
WNPRC_EHR/resources/web/wnprc_ehr/ext4/components/GestationCalculation.js
Ext4.define('WNPRC.ext.plugins.GestationCalculation', { extend: 'Ext4.util.Observable', alias: 'plugin.wnprc-gestationcalculation', init: function(component) { Ext.apply(component, { validationDelay: 1000, validationEvent: 'blur', }); // The following actually trigger the animal abstract pane to update. let GESTATION_CHANGE_EVENT = 'gestationchange_'; let fieldName = component.name; if (fieldName.endsWith('_mm')) { fieldName = fieldName.slice(0, -3); } fieldName += '_gest_day'; component.addEvents(GESTATION_CHANGE_EVENT + fieldName); component.enableBubble(GESTATION_CHANGE_EVENT + fieldName); component.on('change', function(field, val, oldVal) { component.fireEvent(GESTATION_CHANGE_EVENT + fieldName, field.name, val, oldVal); }, this, {buffer: 200}); } });
s1nisteR/JavaProjects
Lab7P2/src/lab7p2/Main.java
//FOR THE REMAINING PROBLEMS, B AND C package lab7p2; import java.util.ArrayList; import java.util.Scanner; class Account { private int id; private double balance; private double annualInterestRate; Account() { this.id = 0; this.balance = 0.0; this.annualInterestRate = 0.0; } Account(int id, double balance, double annualInterestRate) { this.id = id; this.balance = balance; this.annualInterestRate = annualInterestRate; } //getters public int getID() { return this.id; } public double getBalance() { return this.balance; } public double getAnnualInterestRate() { return this.annualInterestRate; } //setters public void setID(int id) { this.id = id; } public void setBalance(double balance) { this.balance = balance; } public void setAnnualInterestRate(double annualInterestRate) { this.annualInterestRate = annualInterestRate; } public double getMonthlyInterestRate() { return this.annualInterestRate / 12; } public double getMonthlyInterestAmount() { return this.balance * (this.getMonthlyInterestRate() / 100); } public void withdraw(double amount) { this.balance -= amount; } public void deposit(double amount) { this.balance += amount; } } class CheckingAccount extends Account { private double overdraftLimit; CheckingAccount() { super(); this.overdraftLimit = 0.0f; } CheckingAccount(int id, double balance, double annualInterestRate, double overdraftLimit) { super(id, balance, annualInterestRate); this.overdraftLimit = overdraftLimit; } public double getOverdraftLimit() { return this.overdraftLimit; } public void setOverdraftLimit(double overdraftLimit) { this.overdraftLimit = overdraftLimit; } } class SavingsAccount extends Account { private String cardNumber; SavingsAccount() { super(); this.cardNumber = ""; } SavingsAccount(int id, double balance, double annualInterestRate, String cardNumber) { super(id, balance, annualInterestRate); this.cardNumber = cardNumber; } public String getCardNumber() { return this.cardNumber; } public void setCardNumber() { this.cardNumber = cardNumber; } public double getCreditBalance() { return 3 * this.getBalance(); } } public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int accountID; double balance; double annualInterestRate; double overdraftLimit; String cardNumber; ArrayList<Account> accounts = new ArrayList<Account>(); for(int i = 0; i < 2; ++i) { System.out.println("Press (1) for creating a Checking Account"); System.out.println("Press (2) for creating a Savings Account"); if(input.nextInt() == 1)//create checking account { System.out.print("Enter Account ID: "); accountID = input.nextInt(); System.out.print("Enter Current Balance: "); balance = input.nextDouble(); System.out.print("Enter Annual Interest Rate: "); annualInterestRate = input.nextDouble(); System.out.print("Enter Overdraft Limit: "); overdraftLimit = input.nextDouble(); accounts.add(new CheckingAccount(accountID, balance, annualInterestRate, overdraftLimit)); } else //create savings account { System.out.print("Enter Account ID: "); accountID = input.nextInt(); System.out.print("Enter Current Balance: "); balance = input.nextDouble(); System.out.print("Enter Annual Interest Rate: "); annualInterestRate = input.nextDouble(); input.nextLine(); System.out.print("Enter Card Number: "); cardNumber = input.nextLine(); accounts.add(new SavingsAccount(accountID, balance, annualInterestRate, cardNumber)); } } System.out.println(""); for(Account x : accounts) { if(x instanceof CheckingAccount) //if x is a Checking Account { System.out.println("This is a Checking Account"); System.out.println("Account ID: " + x.getID()); System.out.println("Current Balance: " + x.getBalance()); System.out.println("Annual Interest Rate: " + x.getAnnualInterestRate()); System.out.println("Monthly Interest Amount: " + x.getMonthlyInterestAmount()); System.out.println("Overdraft Limit: " + ((CheckingAccount) x).getOverdraftLimit()); } else if(x instanceof SavingsAccount) //if x is a Saving Account { System.out.println("This is a Savings Account"); System.out.println("Account ID: " + x.getID()); System.out.println("Current Balance: " + x.getBalance()); System.out.println("Annual Interest Rate: " + x.getAnnualInterestRate()); System.out.println("Monthly Interest Amount: " + x.getMonthlyInterestAmount()); System.out.println("Credit Card Number: " + ((SavingsAccount)x).getCardNumber()); System.out.println("Credit Balance: " + ((SavingsAccount)x).getCreditBalance()); } System.out.println(); } } }
galezra/wix-style-react
src/SelectorList/SelectorList.private.uni.driver.js
import { selectorListUniDriverFactory } from './SelectorList.uni.driver'; import { loaderUniDriverFactory } from '../Loader/Loader.uni.driver'; import { searchUniDriverFactory } from '../Search/Search.uni.driver'; import { selectorUniDriverFactory } from '../Selector/Selector.uni.driver'; import { dataHooks } from './SelectorList.helpers'; export const SelectorListPrivateUniDriverFactory = (base, body) => { const mainLoaderDriver = loaderUniDriverFactory( base.$(`[data-hook="${dataHooks.mainLoader}"]`), body, ); const nextPageLoaderDriver = loaderUniDriverFactory( base.$(`[data-hook="${dataHooks.nextPageLoader}"]`), body, ); const searchDriver = searchUniDriverFactory( base.$(`[data-hook="${dataHooks.search}"]`), body, ); const findInListByDataHook = dataHook => base.$(`[data-hook="${dataHook}"]`); const getList = () => findInListByDataHook(dataHooks.list); const getSelectors = () => getList().$$(`[data-hook="${dataHooks.selector}"]`); const selectorDriverAt = i => selectorUniDriverFactory(getSelectors().get(i)); return { ...selectorListUniDriverFactory(base, body), isMainLoaderMedium: mainLoaderDriver.isMedium, isNextPageLoaderSmall: nextPageLoaderDriver.isSmall, getSearchPlaceholder: searchDriver.inputDriver.getPlaceholder, getSelectorToggleTypeAt: i => selectorDriverAt(i).toggleType(), getSelectorTitleAt: i => selectorDriverAt(i).titleTextDriver().getText(), getSelectorSubtitleAt: i => selectorDriverAt(i).subtitleTextDriver().getText(), getSelectorExtraNodeAt: i => selectorDriverAt(i).getExtraNode(), getSelectorImageAt: i => selectorDriverAt(i).getImage(), isSelectorImageTinyAt: i => selectorDriverAt(i).isImageTiny(), isSelectorImageSmallAt: i => selectorDriverAt(i).isImageSmall(), isSelectorImagePortraitAt: i => selectorDriverAt(i).isImagePortrait(), isSelectorImageLargeAt: i => selectorDriverAt(i).isImageLarge(), isSelectorImageCinemaAt: i => selectorDriverAt(i).isImageCinema(), isSelectorImageCircleAt: i => selectorDriverAt(i).isImageCircle(), isSelectorImageRectangularAt: i => selectorDriverAt(i).isImageRectangular(), }; };
kruore/VRGame_LudensVR
LudensVR_Project_01/Intermediate/Build/Win64/UE4Editor/Inc/LudensVR_Project_01/HPComp.gen.cpp
<filename>LudensVR_Project_01/Intermediate/Build/Win64/UE4Editor/Inc/LudensVR_Project_01/HPComp.gen.cpp // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "LudensVR_Project_01/Public/LV_Enemy/HPComp.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeHPComp() {} // Cross Module References LUDENSVR_PROJECT_01_API UClass* Z_Construct_UClass_UHPComp_NoRegister(); LUDENSVR_PROJECT_01_API UClass* Z_Construct_UClass_UHPComp(); UMG_API UClass* Z_Construct_UClass_UUserWidget(); UPackage* Z_Construct_UPackage__Script_LudensVR_Project_01(); // End Cross Module References void UHPComp::StaticRegisterNativesUHPComp() { } UClass* Z_Construct_UClass_UHPComp_NoRegister() { return UHPComp::StaticClass(); } struct Z_Construct_UClass_UHPComp_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UHPComp_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UUserWidget, (UObject* (*)())Z_Construct_UPackage__Script_LudensVR_Project_01, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UHPComp_Statics::Class_MetaDataParams[] = { { "IncludePath", "LV_Enemy/HPComp.h" }, { "ModuleRelativePath", "Public/LV_Enemy/HPComp.h" }, }; #endif const FCppClassTypeInfoStatic Z_Construct_UClass_UHPComp_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UHPComp>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UHPComp_Statics::ClassParams = { &UHPComp::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x00B010A0u, nullptr, 0, nullptr, 0, nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_UHPComp_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UHPComp_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UHPComp() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UHPComp_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UHPComp, 3155206651); static FCompiledInDefer Z_CompiledInDefer_UClass_UHPComp(Z_Construct_UClass_UHPComp, &UHPComp::StaticClass, TEXT("/Script/LudensVR_Project_01"), TEXT("UHPComp"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UHPComp); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
rajeev02101987/arangodb
3rdParty/boost/1.71.0/libs/yap/example/autodiff_example.cpp
// Copyright (C) 2016-2018 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "autodiff.h" #include <iostream> #include <boost/yap/algorithm.hpp> #include <boost/polymorphic_cast.hpp> #include <boost/hana/for_each.hpp> #define BOOST_TEST_MODULE autodiff_test #include <boost/test/included/unit_test.hpp> double const Epsilon = 10.0e-6; #define CHECK_CLOSE(A,B) do { BOOST_CHECK_CLOSE(A,B,Epsilon); } while(0) using namespace AutoDiff; //[ autodiff_expr_template_decl template <boost::yap::expr_kind Kind, typename Tuple> struct autodiff_expr { static boost::yap::expr_kind const kind = Kind; Tuple elements; }; BOOST_YAP_USER_UNARY_OPERATOR(negate, autodiff_expr, autodiff_expr) BOOST_YAP_USER_BINARY_OPERATOR(plus, autodiff_expr, autodiff_expr) BOOST_YAP_USER_BINARY_OPERATOR(minus, autodiff_expr, autodiff_expr) BOOST_YAP_USER_BINARY_OPERATOR(multiplies, autodiff_expr, autodiff_expr) BOOST_YAP_USER_BINARY_OPERATOR(divides, autodiff_expr, autodiff_expr) //] //[ autodiff_expr_literals_decl namespace autodiff_placeholders { // This defines a placeholder literal operator that creates autodiff_expr // placeholders. BOOST_YAP_USER_LITERAL_PLACEHOLDER_OPERATOR(autodiff_expr) } //] //[ autodiff_function_terminals template <OPCODE Opcode> struct autodiff_fn_expr : autodiff_expr<boost::yap::expr_kind::terminal, boost::hana::tuple<OPCODE>> { autodiff_fn_expr () : autodiff_expr {boost::hana::tuple<OPCODE>{Opcode}} {} BOOST_YAP_USER_CALL_OPERATOR_N(::autodiff_expr, 1); }; // Someone included <math.h>, so we have to add trailing underscores. autodiff_fn_expr<OP_SIN> const sin_; autodiff_fn_expr<OP_COS> const cos_; autodiff_fn_expr<OP_SQRT> const sqrt_; //] //[ autodiff_xform struct xform { // Create a var-node for each placeholder when we see it for the first // time. template <long long I> Node * operator() (boost::yap::expr_tag<boost::yap::expr_kind::terminal>, boost::yap::placeholder<I>) { if (list_.size() < I) list_.resize(I); auto & retval = list_[I - 1]; if (retval == nullptr) retval = create_var_node(); return retval; } // Create a param-node for every numeric terminal in the expression. Node * operator() (boost::yap::expr_tag<boost::yap::expr_kind::terminal>, double x) { return create_param_node(x); } // Create a "uary" node for each call expression, using its OPCODE. template <typename Expr> Node * operator() (boost::yap::expr_tag<boost::yap::expr_kind::call>, OPCODE opcode, Expr const & expr) { return create_uary_op_node( opcode, boost::yap::transform(boost::yap::as_expr<autodiff_expr>(expr), *this) ); } template <typename Expr> Node * operator() (boost::yap::expr_tag<boost::yap::expr_kind::negate>, Expr const & expr) { return create_uary_op_node( OP_NEG, boost::yap::transform(boost::yap::as_expr<autodiff_expr>(expr), *this) ); } // Define a mapping from binary arithmetic expr_kind to OPCODE... static OPCODE op_for_kind (boost::yap::expr_kind kind) { switch (kind) { case boost::yap::expr_kind::plus: return OP_PLUS; case boost::yap::expr_kind::minus: return OP_MINUS; case boost::yap::expr_kind::multiplies: return OP_TIMES; case boost::yap::expr_kind::divides: return OP_DIVID; default: assert(!"This should never execute"); return OPCODE{}; } assert(!"This should never execute"); return OPCODE{}; } // ... and use it to handle all the binary arithmetic operators. template <boost::yap::expr_kind Kind, typename Expr1, typename Expr2> Node * operator() (boost::yap::expr_tag<Kind>, Expr1 const & expr1, Expr2 const & expr2) { return create_binary_op_node( op_for_kind(Kind), boost::yap::transform(boost::yap::as_expr<autodiff_expr>(expr1), *this), boost::yap::transform(boost::yap::as_expr<autodiff_expr>(expr2), *this) ); } vector<Node *> & list_; }; //] //[ autodiff_to_node template <typename Expr, typename ...T> Node * to_auto_diff_node (Expr const & expr, vector<Node *> & list, T ... args) { Node * retval = nullptr; // This fills in list as a side effect. retval = boost::yap::transform(expr, xform{list}); assert(list.size() == sizeof...(args)); // Fill in the values of the value-nodes in list with the "args" // parameter pack. auto it = list.begin(); boost::hana::for_each( boost::hana::make_tuple(args ...), [&it](auto x) { Node * n = *it; VNode * v = boost::polymorphic_downcast<VNode *>(n); v->val = x; ++it; } ); return retval; } //] struct F{ F() { AutoDiff::autodiff_setup(); } ~F(){ AutoDiff::autodiff_cleanup(); } }; BOOST_FIXTURE_TEST_SUITE(all, F) //[ autodiff_original_node_builder Node* build_linear_fun1_manually(vector<Node*>& list) { //f(x1,x2,x3) = -5*x1+sin(10)*x1+10*x2-x3/6 PNode* v5 = create_param_node(-5); PNode* v10 = create_param_node(10); PNode* v6 = create_param_node(6); VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); VNode* x3 = create_var_node(); OPNode* op1 = create_binary_op_node(OP_TIMES,v5,x1); //op1 = v5*x1 OPNode* op2 = create_uary_op_node(OP_SIN,v10); //op2 = sin(v10) OPNode* op3 = create_binary_op_node(OP_TIMES,op2,x1); //op3 = op2*x1 OPNode* op4 = create_binary_op_node(OP_PLUS,op1,op3); //op4 = op1 + op3 OPNode* op5 = create_binary_op_node(OP_TIMES,v10,x2); //op5 = v10*x2 OPNode* op6 = create_binary_op_node(OP_PLUS,op4,op5); //op6 = op4+op5 OPNode* op7 = create_binary_op_node(OP_DIVID,x3,v6); //op7 = x3/v6 OPNode* op8 = create_binary_op_node(OP_MINUS,op6,op7); //op8 = op6 - op7 x1->val = -1.9; x2->val = 2; x3->val = 5./6.; list.push_back(x1); list.push_back(x2); list.push_back(x3); return op8; } //] //[ autodiff_yap_node_builder Node* build_linear_fun1(vector<Node*>& list) { //f(x1,x2,x3) = -5*x1+sin(10)*x1+10*x2-x3/6 using namespace autodiff_placeholders; return to_auto_diff_node( -5 * 1_p + sin_(10) * 1_p + 10 * 2_p - 3_p / 6, list, -1.9, 2, 5./6. ); } //] Node* build_linear_function2_manually(vector<Node*>& list) { //f(x1,x2,x3) = -5*x1+-10*x1+10*x2-x3/6 PNode* v5 = create_param_node(-5); PNode* v10 = create_param_node(10); PNode* v6 = create_param_node(6); VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); VNode* x3 = create_var_node(); list.push_back(x1); list.push_back(x2); list.push_back(x3); OPNode* op1 = create_binary_op_node(OP_TIMES,v5,x1); //op1 = v5*x1 OPNode* op2 = create_uary_op_node(OP_NEG,v10); //op2 = -v10 OPNode* op3 = create_binary_op_node(OP_TIMES,op2,x1);//op3 = op2*x1 OPNode* op4 = create_binary_op_node(OP_PLUS,op1,op3);//op4 = op1 + op3 OPNode* op5 = create_binary_op_node(OP_TIMES,v10,x2);//op5 = v10*x2 OPNode* op6 = create_binary_op_node(OP_PLUS,op4,op5);//op6 = op4+op5 OPNode* op7 = create_binary_op_node(OP_DIVID,x3,v6); //op7 = x3/v6 OPNode* op8 = create_binary_op_node(OP_MINUS,op6,op7);//op8 = op6 - op7 x1->val = -1.9; x2->val = 2; x3->val = 5./6.; return op8; } Node* build_linear_function2(vector<Node*>& list) { //f(x1,x2,x3) = -5*x1+-10*x1+10*x2-x3/6 using namespace autodiff_placeholders; auto ten = boost::yap::make_terminal<autodiff_expr>(10); return to_auto_diff_node( -5 * 1_p + -ten * 1_p + 10 * 2_p - 3_p / 6, list, -1.9, 2, 5./6. ); } Node* build_nl_function1_manually(vector<Node*>& list) { // (x1*x2 * sin(x1))/x3 + x2*x4 - x1/x2 VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); VNode* x3 = create_var_node(); VNode* x4 = create_var_node(); x1->val = -1.23; x2->val = 7.1231; x3->val = 2; x4->val = -10; list.push_back(x1); list.push_back(x2); list.push_back(x3); list.push_back(x4); OPNode* op1 = create_binary_op_node(OP_TIMES,x2,x1); OPNode* op2 = create_uary_op_node(OP_SIN,x1); OPNode* op3 = create_binary_op_node(OP_TIMES,op1,op2); OPNode* op4 = create_binary_op_node(OP_DIVID,op3,x3); OPNode* op5 = create_binary_op_node(OP_TIMES,x2,x4); OPNode* op6 = create_binary_op_node(OP_PLUS,op4,op5); OPNode* op7 = create_binary_op_node(OP_DIVID,x1,x2); OPNode* op8 = create_binary_op_node(OP_MINUS,op6,op7); return op8; } Node* build_nl_function1(vector<Node*>& list) { // (x1*x2 * sin(x1))/x3 + x2*x4 - x1/x2 using namespace autodiff_placeholders; return to_auto_diff_node( (1_p * 2_p * sin_(1_p)) / 3_p + 2_p * 4_p - 1_p / 2_p, list, -1.23, 7.1231, 2, -10 ); } BOOST_AUTO_TEST_CASE( test_linear_fun1 ) { BOOST_TEST_MESSAGE("test_linear_fun1"); vector<Node*> list; Node* root = build_linear_fun1(list); vector<double> grad; double val1 = grad_reverse(root,list,grad); double val2 = eval_function(root); double x1g[] = {-5.5440211108893697744548489936278,10.0,-0.16666666666666666666666666666667}; for(unsigned int i=0;i<3;i++){ CHECK_CLOSE(grad[i],x1g[i]); } double eval = 30.394751221800913; CHECK_CLOSE(val1,eval); CHECK_CLOSE(val2,eval); EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,0); } BOOST_AUTO_TEST_CASE( test_grad_sin ) { BOOST_TEST_MESSAGE("test_grad_sin"); VNode* x1 = create_var_node(); x1->val = 10; OPNode* root = create_uary_op_node(OP_SIN,x1); vector<Node*> nodes; nodes.push_back(x1); vector<double> grad; grad_reverse(root,nodes,grad); double x1g = -0.83907152907645244; //the matlab give cos(10) = -0.839071529076452 CHECK_CLOSE(grad[0],x1g); BOOST_CHECK_EQUAL(nodes.size(),1); EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,1); } BOOST_AUTO_TEST_CASE(test_grad_single_node) { VNode* x1 = create_var_node(); x1->val = -2; vector<Node*> nodes; nodes.push_back(x1); vector<double> grad; double val = grad_reverse(x1,nodes,grad); CHECK_CLOSE(grad[0],1); CHECK_CLOSE(val,-2); EdgeSet s; unsigned int n = 0; nonlinearEdges(x1,s); n = nzHess(s); BOOST_CHECK_EQUAL(n,0); grad.clear(); nodes.clear(); PNode* p = create_param_node(-10); //OPNode* op = create_binary_op_node(TIMES,p,create_param_node(2)); val = grad_reverse(p,nodes,grad); BOOST_CHECK_EQUAL(grad.size(),0); CHECK_CLOSE(val,-10); s.clear(); nonlinearEdges(p,s); n = nzHess(s); BOOST_CHECK_EQUAL(n,0); } BOOST_AUTO_TEST_CASE(test_grad_neg) { VNode* x1 = create_var_node(); x1->val = 10; PNode* p2 = create_param_node(-1); vector<Node*> nodes; vector<double> grad; nodes.push_back(x1); Node* root = create_binary_op_node(OP_TIMES,x1,p2); grad_reverse(root,nodes,grad); CHECK_CLOSE(grad[0],-1); BOOST_CHECK_EQUAL(nodes.size(),1); nodes.clear(); grad.clear(); nodes.push_back(x1); root = create_uary_op_node(OP_NEG,x1); grad_reverse(root,nodes,grad); CHECK_CLOSE(grad[0],-1); EdgeSet s; unsigned int n = 0; nonlinearEdges(root,s); n = nzHess(s); BOOST_CHECK_EQUAL(n,0); } BOOST_AUTO_TEST_CASE( test_nl_function) { vector<Node*> list; Node* root = build_nl_function1(list); double val = eval_function(root); vector<double> grad; grad_reverse(root,list,grad); double eval =-66.929555552886214; double gx[] = {-4.961306690356109,-9.444611307649055,-2.064383410399700,7.123100000000000}; CHECK_CLOSE(val,eval); for(unsigned int i=0;i<4;i++) { CHECK_CLOSE(grad[i],gx[i]); } unsigned int nzgrad = nzGrad(root); unsigned int tol = numTotalNodes(root); BOOST_CHECK_EQUAL(nzgrad,4); BOOST_CHECK_EQUAL(tol,16); EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,11); } BOOST_AUTO_TEST_CASE( test_hess_reverse_1) { vector<Node*> nodes; Node* root = build_linear_fun1(nodes); vector<double> grad; double val = grad_reverse(root,nodes,grad); double eval = eval_function(root); // cout<<eval<<"\t"<<grad[0]<<"\t"<<grad[1]<<"\t"<<grad[2]<<"\t"<<endl; CHECK_CLOSE(val,eval); for(unsigned int i=0;i<nodes.size();i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[0])->u = 1; double hval = 0; vector<double> dhess; hval = hess_reverse(root,nodes,dhess); CHECK_CLOSE(hval,eval); for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],0); } } BOOST_AUTO_TEST_CASE( test_hess_reverse_2) { vector<Node*> nodes; Node* root = build_linear_function2(nodes); vector<double> grad; double val = grad_reverse(root,nodes,grad); double eval = eval_function(root); CHECK_CLOSE(val,eval); for(unsigned int i=0;i<nodes.size();i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[0])->u = 1; double hval = 0; vector<double> dhess; hval = hess_reverse(root,nodes,dhess); CHECK_CLOSE(hval,eval); for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],0); } EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,0); } BOOST_AUTO_TEST_CASE( test_hess_reverse_4) { vector<Node*> nodes; // Node* root = build_nl_function1(nodes); VNode* x1 = create_var_node(); nodes.push_back(x1); x1->val = 1; x1->u =1; Node* op = create_uary_op_node(OP_SIN,x1); Node* root = create_uary_op_node(OP_SIN,op); vector<double> grad; double eval = eval_function(root); vector<double> dhess; double hval = hess_reverse(root,nodes,dhess); CHECK_CLOSE(hval,eval); BOOST_CHECK_EQUAL(dhess.size(),1); CHECK_CLOSE(dhess[0], -0.778395788418109); EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,1); } BOOST_AUTO_TEST_CASE( test_hess_reverse_3) { vector<Node*> nodes; VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); nodes.push_back(x1); nodes.push_back(x2); x1->val = 2.5; x2->val = -9; Node* op1 = create_binary_op_node(OP_TIMES,x1,x2); Node* root = create_binary_op_node(OP_TIMES,x1,op1); double eval = eval_function(root); for(unsigned int i=0;i<nodes.size();i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[0])->u = 1; vector<double> dhess; double hval = hess_reverse(root,nodes,dhess); BOOST_CHECK_EQUAL(dhess.size(),2); CHECK_CLOSE(hval,eval); double hx[]={-18,5}; for(unsigned int i=0;i<dhess.size();i++) { //Print("\t["<<i<<"]="<<dhess[i]); CHECK_CLOSE(dhess[i],hx[i]); } EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,3); } BOOST_AUTO_TEST_CASE( test_hess_reverse_5) { vector<Node*> nodes; VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); nodes.push_back(x1); nodes.push_back(x2); x1->val = 2.5; x2->val = -9; Node* op1 = create_binary_op_node(OP_TIMES,x1,x1); Node* op2 = create_binary_op_node(OP_TIMES,x2,x2); Node* op3 = create_binary_op_node(OP_MINUS,op1,op2); Node* op4 = create_binary_op_node(OP_PLUS,op1,op2); Node* root = create_binary_op_node(OP_TIMES,op3,op4); double eval = eval_function(root); for(unsigned int i=0;i<nodes.size();i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[0])->u = 1; vector<double> dhess; double hval = hess_reverse(root,nodes,dhess); CHECK_CLOSE(hval,eval); double hx[] ={75,0}; for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],hx[i]); } for(unsigned int i=0;i<nodes.size();i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[1])->u = 1; double hx2[] = {0, -972}; hval = hess_reverse(root,nodes,dhess); for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],hx2[i]); } EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,4); } BOOST_AUTO_TEST_CASE( test_hess_reverse_6) { vector<Node*> nodes; // Node* root = build_nl_function1(nodes); VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); nodes.push_back(x1); nodes.push_back(x2); x1->val = 2.5; x2->val = -9; Node* root = create_binary_op_node(OP_POW,x1,x2); double eval = eval_function(root); static_cast<VNode*>(nodes[0])->u=1;static_cast<VNode*>(nodes[1])->u=0; vector<double> dhess; double hval = hess_reverse(root,nodes,dhess); CHECK_CLOSE(hval,eval); double hx1[] ={0.003774873600000 , -0.000759862823419}; double hx2[] ={-0.000759862823419, 0.000220093141567}; for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],hx1[i]); } static_cast<VNode*>(nodes[0])->u=0;static_cast<VNode*>(nodes[1])->u=1; hess_reverse(root,nodes,dhess); for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],hx2[i]); } EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,4); } BOOST_AUTO_TEST_CASE( test_hess_reverse_7) { vector<Node*> nodes; Node* root = build_nl_function1(nodes); double eval = eval_function(root); vector<double> dhess; double hx0[] ={-1.747958066718855, -0.657091724418110, 2.410459188139686, 0}; double hx1[] ={ -0.657091724418110, 0.006806564792590, -0.289815306593997, 1.000000000000000}; double hx2[] ={ 2.410459188139686, -0.289815306593997, 2.064383410399700, 0}; double hx3[] ={0,1,0,0}; for(unsigned int i=0;i<nodes.size();i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[0])->u = 1; double hval = hess_reverse(root,nodes,dhess); CHECK_CLOSE(hval,eval); for(unsigned int i=0;i<dhess.size();i++) { CHECK_CLOSE(dhess[i],hx0[i]); } for (unsigned int i = 0; i < nodes.size(); i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[1])->u = 1; hess_reverse(root, nodes, dhess); for (unsigned int i = 0; i < dhess.size(); i++) { CHECK_CLOSE(dhess[i], hx1[i]); } for (unsigned int i = 0; i < nodes.size(); i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[2])->u = 1; hess_reverse(root, nodes, dhess); for (unsigned int i = 0; i < dhess.size(); i++) { CHECK_CLOSE(dhess[i], hx2[i]); } for (unsigned int i = 0; i < nodes.size(); i++) { static_cast<VNode*>(nodes[i])->u = 0; } static_cast<VNode*>(nodes[3])->u = 1; hess_reverse(root, nodes, dhess); for (unsigned i = 0; i < dhess.size(); i++) { CHECK_CLOSE(dhess[i], hx3[i]); } } #if FORWARD_ENABLED void test_hess_forward(Node* root, unsigned int& nvar) { AutoDiff::num_var = nvar; unsigned int len = (nvar+3)*nvar/2; double* hess = new double[len]; hess_forward(root,nvar,&hess); for(unsigned int i=0;i<len;i++){ cout<<"hess["<<i<<"]="<<hess[i]<<endl; } delete[] hess; } #endif BOOST_AUTO_TEST_CASE( test_hess_reverse_8) { vector<Node*> list; vector<double> dhess; VNode* x1 = create_var_node(); list.push_back(x1); static_cast<VNode*>(list[0])->val = -10.5; static_cast<VNode*>(list[0])->u = 1; double deval = hess_reverse(x1,list,dhess); CHECK_CLOSE(deval,-10.5); BOOST_CHECK_EQUAL(dhess.size(),1); BOOST_CHECK(isnan(dhess[0])); EdgeSet s; nonlinearEdges(x1,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,0); PNode* p1 = create_param_node(-1.5); list.clear(); deval = hess_reverse(p1,list,dhess); CHECK_CLOSE(deval,-1.5); BOOST_CHECK_EQUAL(dhess.size(),0); s.clear(); nonlinearEdges(p1,s); n = nzHess(s); BOOST_CHECK_EQUAL(n,0); } BOOST_AUTO_TEST_CASE( test_hess_revers9) { vector<Node*> list; vector<double> dhess; VNode* x1 = create_var_node(); list.push_back(x1); static_cast<VNode*>(list[0])->val = 2.5; static_cast<VNode*>(list[0])->u =1; Node* op1 = create_binary_op_node(OP_TIMES,x1,x1); Node* root = create_binary_op_node(OP_TIMES,op1,op1); double deval = hess_reverse(root,list,dhess); double eval = eval_function(root); CHECK_CLOSE(eval,deval); BOOST_CHECK_EQUAL(dhess.size(),1); CHECK_CLOSE(dhess[0],75); EdgeSet s; nonlinearEdges(root,s); unsigned int n = nzHess(s); BOOST_CHECK_EQUAL(n,1); } BOOST_AUTO_TEST_CASE( test_hess_revers10) { vector<Node*> list; vector<double> dhess; VNode* x1 = create_var_node(); VNode* x2 = create_var_node(); list.push_back(x1); list.push_back(x2); Node* op1 = create_binary_op_node(OP_TIMES, x1,x2); Node* op2 = create_uary_op_node(OP_SIN,op1); Node* op3 = create_uary_op_node(OP_COS,op1); Node* root = create_binary_op_node(OP_TIMES, op2, op3); static_cast<VNode*>(list[0])->val = 2.1; static_cast<VNode*>(list[1])->val = 1.8; double eval = eval_function(root); //second column static_cast<VNode*>(list[0])->u = 0; static_cast<VNode*>(list[1])->u = 1; double deval = hess_reverse(root,list,dhess); CHECK_CLOSE(eval,deval); BOOST_CHECK_EQUAL(dhess.size(),2); CHECK_CLOSE(dhess[0], -6.945893481707861); CHECK_CLOSE(dhess[1], -8.441601940854081); //first column static_cast<VNode*>(list[0])->u = 1; static_cast<VNode*>(list[1])->u = 0; deval = hess_reverse(root,list,dhess); CHECK_CLOSE(eval,deval); BOOST_CHECK_EQUAL(dhess.size(),2); CHECK_CLOSE(dhess[0], -6.201993262668304); CHECK_CLOSE(dhess[1], -6.945893481707861); } BOOST_AUTO_TEST_CASE( test_grad_reverse11) { vector<Node*> list; VNode* x1 = create_var_node(); Node* p2 = create_param_node(2); list.push_back(x1); Node* op1 = create_binary_op_node(OP_POW,x1,p2); static_cast<VNode*>(x1)->val = 0; vector<double> grad; grad_reverse(op1,list,grad); BOOST_CHECK_EQUAL(grad.size(),1); CHECK_CLOSE(grad[0],0); } BOOST_AUTO_TEST_CASE( test_hess_reverse12) { vector<Node*> list; VNode* x1 = create_var_node(); Node* p2 = create_param_node(2); list.push_back(x1); Node* op1 = create_binary_op_node(OP_POW,x1,p2); x1->val = 0; x1->u = 1; vector<double> hess; hess_reverse(op1,list,hess); BOOST_CHECK_EQUAL(hess.size(),1); CHECK_CLOSE(hess[0],2); } BOOST_AUTO_TEST_CASE( test_grad_reverse13) { vector<Node*> list; VNode* x1 = create_var_node(); PNode* p1 = create_param_node(0.090901); VNode* x2 = create_var_node(); PNode* p2 = create_param_node(0.090901); list.push_back(x1); list.push_back(x2); Node* op1 = create_binary_op_node(OP_TIMES,x1,p1); Node* op2 = create_binary_op_node(OP_TIMES,x2,p2); Node* root = create_binary_op_node(OP_PLUS,op1,op2); x1->val = 1; x2->val = 1; vector<double> grad; grad_reverse(root,list,grad); BOOST_CHECK_EQUAL(grad.size(),2); CHECK_CLOSE(grad[0],0.090901); CHECK_CLOSE(grad[1],0.090901); } BOOST_AUTO_TEST_SUITE_END()
rucub100/graphalytics-platforms-dxram
src/main/java/science/atlarge/graphalytics/dxram/graph/data/BFSResult.java
<gh_stars>0 /* * Copyright (C) 2017 <NAME>, Institute of Computer Science, Department Operating Systems * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package science.atlarge.graphalytics.dxram.graph.data; import de.hhu.bsinfo.dxmem.data.AbstractChunk; import de.hhu.bsinfo.dxmem.data.ChunkID; import de.hhu.bsinfo.dxutils.serialization.Exporter; import de.hhu.bsinfo.dxutils.serialization.Importer; /** * Data structure holding results of a single BFS run. * * @author <NAME>, <EMAIL>, 20.05.2016 */ public class BFSResult extends AbstractChunk { public long m_rootVertexId = ChunkID.INVALID_ID; public long m_graphFullSizeVertices = 0; public long m_graphFullSizeEdges = 0; public long m_graphPartitionSizeVertices = 0; public long m_graphPartitionSizeEdges = 0; public long m_totalVisitedVertices = 0; public long m_totalVisitedEdges = 0; public long m_totalVerticesTraversed = 0; public long m_totalEdgesTraversed = 0; public long m_maxTraversedVertsPerSecond = 0; public long m_maxTraversedEdgesPerSecond = 0; public long m_avgTraversedVertsPerSecond = 0; public long m_avgTraversedEdgesPerSecond = 0; public long m_totalTimeMs = 0; public int m_totalBFSDepth = 0; public BFSResult() { } @Override public void importObject(final Importer p_importer) { m_rootVertexId = p_importer.readLong(m_rootVertexId); m_graphFullSizeVertices = p_importer.readLong(m_graphFullSizeVertices); m_graphFullSizeEdges = p_importer.readLong(m_graphFullSizeEdges); m_graphPartitionSizeVertices = p_importer.readLong(m_graphPartitionSizeVertices); m_graphPartitionSizeEdges = p_importer.readLong(m_graphPartitionSizeEdges); m_totalVisitedVertices = p_importer.readLong(m_totalVisitedVertices); m_totalVisitedEdges = p_importer.readLong(m_totalVisitedEdges); m_totalVerticesTraversed = p_importer.readLong(m_totalVerticesTraversed); m_totalEdgesTraversed = p_importer.readLong(m_totalEdgesTraversed); m_maxTraversedVertsPerSecond = p_importer.readLong(m_maxTraversedVertsPerSecond); m_maxTraversedEdgesPerSecond = p_importer.readLong(m_maxTraversedEdgesPerSecond); m_avgTraversedVertsPerSecond = p_importer.readLong(m_avgTraversedVertsPerSecond); m_avgTraversedEdgesPerSecond = p_importer.readLong(m_avgTraversedEdgesPerSecond); m_totalTimeMs = p_importer.readLong(m_totalTimeMs); m_totalBFSDepth = p_importer.readInt(m_totalBFSDepth); } @Override public int sizeofObject() { return Long.BYTES * 14 + Integer.BYTES; } @Override public void exportObject(final Exporter p_exporter) { p_exporter.writeLong(m_rootVertexId); p_exporter.writeLong(m_graphFullSizeVertices); p_exporter.writeLong(m_graphFullSizeEdges); p_exporter.writeLong(m_graphPartitionSizeVertices); p_exporter.writeLong(m_graphPartitionSizeEdges); p_exporter.writeLong(m_totalVisitedVertices); p_exporter.writeLong(m_totalVisitedEdges); p_exporter.writeLong(m_totalVerticesTraversed); p_exporter.writeLong(m_totalEdgesTraversed); p_exporter.writeLong(m_maxTraversedVertsPerSecond); p_exporter.writeLong(m_maxTraversedEdgesPerSecond); p_exporter.writeLong(m_avgTraversedVertsPerSecond); p_exporter.writeLong(m_avgTraversedEdgesPerSecond); p_exporter.writeLong(m_totalTimeMs); p_exporter.writeInt(m_totalBFSDepth); } @Override public String toString() { return "BFSResult " + ChunkID.toHexString(getID()) + ":\n" + "m_rootVertexId " + ChunkID.toHexString(m_rootVertexId) + '\n' + "m_graphFullSizeVertices " + m_graphFullSizeVertices + '\n' + "m_graphFullSizeEdges " + m_graphFullSizeEdges + '\n' + "m_graphPartitionSizeVertices " + m_graphPartitionSizeVertices + '\n' + "m_graphPartitionSizeEdges " + m_graphPartitionSizeEdges + '\n' + "m_totalVisitedVertices " + m_totalVisitedVertices + '\n' + "m_totalVisitedEdges " + m_totalVisitedEdges + '\n' + "m_totalVerticesTraversed " + m_totalVerticesTraversed + '\n' + "m_totalEdgesTraversed " + m_totalEdgesTraversed + '\n' + "m_maxTraversedVertsPerSecond " + m_maxTraversedVertsPerSecond + '\n' + "m_maxTraversedEdgesPerSecond " + m_maxTraversedEdgesPerSecond + '\n' + "m_avgTraversedVertsPerSecond " + m_avgTraversedVertsPerSecond + '\n' + "m_avgTraversedEdgesPerSecond " + m_avgTraversedEdgesPerSecond + '\n' + "m_totalTimeMs " + m_totalTimeMs + '\n' + "m_totalBFSDepth " + m_totalBFSDepth; } }
ali-sharif/avm
org.aion.avm.userlib/src/org/aion/avm/userlib/AionUtilities.java
<filename>org.aion.avm.userlib/src/org/aion/avm/userlib/AionUtilities.java package org.aion.avm.userlib; /** * A collection of methods to facilitate contract development. */ public class AionUtilities { /** * Returns a new byte array of length 32 that right-aligns the input bytes by padding them on the left with 0. * Note that the input is not truncated if it is larger than 32 bytes. * This method can be used to pad log topics. * * @param topic bytes to pad * @return Zero padded topic * @throws NullPointerException if topic is null */ public static byte[] padLeft(byte[] topic) { int topicSize = 32; byte[] result; if (null == topic) { throw new NullPointerException(); } else if (topic.length < topicSize) { result = new byte[topicSize]; System.arraycopy(topic, 0, result, topicSize - topic.length, topic.length); } else { // if topic is larger than 32 bytes or the right size result = topic; } return result; } }
Minionguyjpro/Ghostly-Skills
sources/com/google/android/gms/dynamic/zaa.java
package com.google.android.gms.dynamic; import android.app.Activity; import android.os.Bundle; import com.google.android.gms.dynamic.DeferredLifecycleHelper; /* compiled from: com.google.android.gms:play-services-base@@17.3.0 */ final class zaa implements DeferredLifecycleHelper.zaa { private final /* synthetic */ Activity zaa; private final /* synthetic */ Bundle zab; private final /* synthetic */ Bundle zac; private final /* synthetic */ DeferredLifecycleHelper zad; zaa(DeferredLifecycleHelper deferredLifecycleHelper, Activity activity, Bundle bundle, Bundle bundle2) { this.zad = deferredLifecycleHelper; this.zaa = activity; this.zab = bundle; this.zac = bundle2; } public final int zaa() { return 0; } public final void zaa(LifecycleDelegate lifecycleDelegate) { this.zad.zaa.onInflate(this.zaa, this.zab, this.zac); } }
finnishtransportagency/ksr
src/main/client/src/reducers/navigation/index.js
<filename>src/main/client/src/reducers/navigation/index.js import { combineReducers } from 'redux'; import activeNav from './activeNav'; export default combineReducers({ activeNav, });
dimddev/NetCatKS-CP
NetCatKS/Validators/api/implementers/validators/xml/__init__.py
<filename>NetCatKS/Validators/api/implementers/validators/xml/__init__.py __author__ = 'dimd' from NetCatKS.Validators.api.interfaces.message import IMessage from NetCatKS.Validators.api.implementers.validators.default import BaseValidator from zope.component import adapts from zope.component import getGlobalSiteManager from lxml import etree class XMLValidator(BaseValidator): adapts(IMessage) def __init__(self, validate_msg): super(XMLValidator, self).__init__(validate_msg) def validate(self): try: __xml = etree.fromstring(self.validate_msg.message) except Exception as e: return self else: self.is_valid = True self.message_type = 'XML' self.message = self.validate_msg.message return self gsm = getGlobalSiteManager() gsm.registerSubscriptionAdapter(XMLValidator)
shurun19851206/sso
hihsoft-sso/JavaSource/com/hihsoft/sso/business/service/impl/TaclUserinfoServiceImpl.java
<filename>hihsoft-sso/JavaSource/com/hihsoft/sso/business/service/impl/TaclUserinfoServiceImpl.java /** * Copyright (c) 2013-2015 www.javahih.com * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.hihsoft.sso.business.service.impl; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.DetachedCriteria; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.stereotype.Service; import com.hihframework.core.utils.ParamUtil; import com.hihframework.core.utils.StringHelpers; import com.hihframework.exception.ServiceException; import com.hihframework.osplugins.json.JsonUtil; import com.hihsoft.baseclass.service.impl.BaseServiceImpl; import com.hihsoft.sso.business.model.TaclDutyuser; import com.hihsoft.sso.business.model.TaclRoleprivilege; import com.hihsoft.sso.business.model.TaclUserinfo; import com.hihsoft.sso.business.model.TaclUserprivilege; import com.hihsoft.sso.business.model.TsysDataprivilege; import com.hihsoft.sso.business.model.TsysDuty; import com.hihsoft.sso.business.model.TsysFlat; import com.hihsoft.sso.business.model.TsysModuleinfo; import com.hihsoft.sso.business.model.TsysModuleoperate; import com.hihsoft.sso.business.model.TsysTreeprivilege; import com.hihsoft.sso.business.service.TaclUserinfoService; import com.mysql.jdbc.StringUtils; @Service(value ="taclUserinfoService") public class TaclUserinfoServiceImpl extends BaseServiceImpl implements TaclUserinfoService { /************ 查询所有的TACLUSERINFO ******************/ private static final String ALLTACLUSERINFO_HQL = " from TaclUserinfo"; /************ 通过主键查询TACLUSERINFO ******************/ private static final String TACLUSERINFOById_HQL = " from TaclUserinfo taclUserinfo where taclUserinfo.userid=?"; /************ 通过不同的条件组合,利用Hibernate HQL查询TACLUSERINFO ******************/ private static final StringBuffer QUERY_TACLUSERINFO_HQL = new StringBuffer( " from TaclUserinfo taclUserinfo where 1=1"); /************ 通过不同的条件组合,利用JDBC SQL查询TACLUSERINFO ******************/ private static final StringBuffer QUERY_TACLUSERINFO_SQL = new StringBuffer( "select * from T_ACL_USERINFO t where 1=1"); /** * 新增、修改TaclUserinfo信息 * * @param taclUserinfo * @throws DataAccessException */ public void saveOrUpdateTaclUserinfo(TaclUserinfo taclUserinfo) throws ServiceException { baseDAO.saveOrUpdateVO(taclUserinfo); } /** * 删除TaclUserinfo信息 * * @param id * @throws DataAccessException */ public void deleteTaclUserinfo(String ids) throws ServiceException { //List<TaclUserinfo> list = new ArrayList<TaclUserinfo>(); if (ids != null && !"".equals(ids)) { String[] arr = ids.split(","); for (String id : arr) { TaclUserinfo obj = getTaclUserinfoById(id); if (obj != null) { obj.setUserstate(ParamUtil.getInstance().getValByKey("userState", "停用")); saveOrUpdateTaclUserinfo(obj); } // list.add(obj); // executeHQL("delete from TsysDataprivilege where userid=?", id); // executeHQL("delete from TaclRoleuser where userid=?", id); } } //deleteBatchVO(list); } /** * 通过HQL构造查询条件来查询符合条件的TaclUserinfo信息 * * @param hql * @return List * @throws DataAccessException */ public List<?> getTaclUserinfoByHQL(String hql) throws ServiceException { return baseDAO.getValueObjectsByHQL(hql); } /** * 查询所有的TaclUserinfo信息 * * @param hql * @return List * @throws DataAccessException */ public List<?> getAllTaclUserinfo() throws ServiceException { return baseDAO.getValueObjectsByHQL(ALLTACLUSERINFO_HQL); } /** * 根据主键查询TaclUserinfo信息明细 * * @param id * @throws DataAccessException */ public TaclUserinfo getTaclUserinfoById(String id) throws ServiceException { TaclUserinfo taclUserinfo = null; List<?> list = baseDAO.getValueObjectsByHQL(TACLUSERINFOById_HQL, new Object[] { id }); if (!list.isEmpty() && list.size() > 0) { taclUserinfo = (TaclUserinfo) list.get(0); } return taclUserinfo; } /** * 把查询条件构造成数组来查询TaclUserinfo信息 * * @param Object * [] object * @return List * @throws DataAccessException */ public List<?> getTaclUserinfoByArray(Object[] filter) throws ServiceException { return baseDAO.getValueObjectsByHQL(QUERY_TACLUSERINFO_HQL.toString(), filter); } /** * 取得分页总数 * * @param hql * @param object * @return * @throws DataAccessException */ public int getTaclUserinfoDataTotalNum(Object[] filter) throws ServiceException { return baseDAO.getDataTotalNum(QUERY_TACLUSERINFO_HQL.toString(), filter); } /** * 把查询条件构造成数组来查询TaclUserinfo信息 * * @param Map * filter * @return List * @throws DataAccessException */ public List<?> getTaclUserinfoByMap(Map<String, Object> filter) throws ServiceException { return baseDAO.getPageDataByHQL(QUERY_TACLUSERINFO_HQL.toString(), filter); } /** * 分页查询 * * @param hql * @param object * @param page_size * @param pageNo * @return * @throws DataAccessException */ public List<?> getTaclUserinfoPageDataByArray(Object[] filter, int page_size, int pageNo) throws ServiceException { return baseDAO.getPageDataByHQL(QUERY_TACLUSERINFO_HQL.toString(), filter, page_size, pageNo); } /** * 分页查询。 * * @param hql * @param obj * :MAP条件构造 * @param page_size * @param pageNo * @return * @throws DataAccessException */ public List<?> getTaclUserinfoPageDataByMap(Map<String, Object> filter, int page_size, int pageNo) throws ServiceException { return baseDAO.getPageDataByHQL(QUERY_TACLUSERINFO_HQL.toString(), filter, page_size, pageNo); } /** * 利用SQL数组条件来查询记录 * * @param sql * @param object * @return * @throws DataAccessException */ public List<?> getTaclUserinfoValueObjectWithSQLByArray(Object[] filter) throws ServiceException { return baseDAO.getValueObjectBySQL(QUERY_TACLUSERINFO_SQL.toString(), filter); } /** * 通过配置SQL来执行查询带多个参数的情况 包括SQL语句、存储过程等 * * @param queryName * @param object * @return * @throws DataAccessException */ public List<?> getTaclUserinfoValueObjectByNameQuery(String queryName, Object[] filter) throws ServiceException { return baseDAO.getValueObjectByNameQuery(queryName, filter); } /** * 动态构造HQL参数 * * @param detachedCriteria * @return * @throws ServiceException */ public List<?> getTaclUserinfoValueObjectByDetachedCriteria( DetachedCriteria detachedCriteria) throws ServiceException { return baseDAO.getValueObjectByDetachedCriteria(detachedCriteria); } /** * 动态构造HQL参数 * * @param detachedCriteria * @return * @throws ServiceException */ public List<?> getTaclUserinfoValueObjectByDetachedCriterias( DetachedCriteria detachedCriteria, int arg1, int arg2) throws ServiceException { return baseDAO.getValueObjectByDetachedCriterias(detachedCriteria, arg1, arg2); } public TaclUserinfo getUserByLoginName(String loginName) throws ServiceException { List<TaclUserinfo> list = baseDAO.loadByField(TaclUserinfo.class, TaclUserinfo.ALIAS_LOGINNAME, loginName); if (list != null && !list.isEmpty()) { return list.get(0); } return null; } @SuppressWarnings("unchecked") public Map<String, Map<String, String>> getUserRoles(TaclUserinfo user) throws ServiceException { String userId = user.getUserid(); Map<String, Map<String, String>> roles = new HashMap<String, Map<String, String>>(); // String sql = "select o.operateno,i.moduleno from t_sys_moduleoperate o,(select * from T_ACL_ROLEPRIVILEGE where roleid in (select roleid from t_acl_roleuser where userid=?)) t,t_sys_moduleinfo i where o.moduleid=t.moduleid and o.operateid=t.operateid and i.moduleid = t.moduleid"; //String sql = "select o.operateno,i.moduleno from t_sys_moduleoperate o,(select distinct moduleid,operateid from (select moduleid,operateid from t_acl_roleprivilege where roleid in (select roleid from t_acl_roleuser where userid=?) union all select moduleid, operateid from t_acl_userprivilege where userid=?)) t,t_sys_moduleinfo i where o.moduleid=t.moduleid and o.operateid=t.operateid and i.moduleid = t.moduleid order by i.moduleno,o.operateno"; //modify by zhujw兼容mysql 、oracle String sql = "SELECT O.OPERATENO,I.MODULENO FROM T_SYS_MODULEOPERATE O,(SELECT DISTINCT C.MODULEID,C.OPERATEID FROM (SELECT R.MODULEID,R.OPERATEID FROM T_ACL_ROLEPRIVILEGE R WHERE R.ROLEID IN (SELECT US.ROLEID FROM T_ACL_ROLEUSER US WHERE US.USERID=?) UNION ALL SELECT AC.MODULEID, AC.OPERATEID FROM T_ACL_USERPRIVILEGE AC WHERE AC.USERID=?) C) T,T_SYS_MODULEINFO I WHERE O.MODULEID=T.MODULEID AND O.OPERATEID=T.OPERATEID AND I.MODULEID = T.MODULEID ORDER BY I.MODULENO,O.OPERATENO"; List<Object[]> rolePrivileges = (List<Object[]>) baseDAO.getValueObjectBySQL(sql, userId, userId); String moduleno = ""; for (Object[] os : rolePrivileges) { Map<String, String> map = null; if (os == null || os[1] == null) continue; if (!moduleno.equals(os[1])) { map = new HashMap<String, String>(); moduleno = (String) os[1]; map.put((String) os[0], moduleno); roles.put(moduleno, map); } else { map = roles.get(moduleno); map.put((String) os[0], moduleno); } } return roles; } @Override public boolean saveDataSet(String userId, String datas) throws ServiceException { String[] dataSets = datas.split(","); String hql = "delete from TsysDataprivilege where userid='"+userId+"'"; executeHQL(hql); for (String set : dataSets) { if ("".equals(set)) continue; TsysDataprivilege td = new TsysDataprivilege(); td.setOrgid(set); td.setUserid(userId); baseDAO.saveOrUpdateVO(td); } return true; } @Override public void clearRole(String userId) throws ServiceException { executeHQL("delete from TaclRoleuser where userid=?", userId); executeHQL("delete from TaclUserprivilege where userid=?", userId); executeHQL("delete from TsysDataprivilege where userid=?", userId); } public String getPrivilegeTree(final String userId, final String curUserId) throws ServiceException { if (StringHelpers.isNull(userId)) return "[]"; List<Map<String, Object>> map = baseDAO.doInHibernate(new HibernateCallback<List<Map<String, Object>>>() { @SuppressWarnings("unchecked") public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException ,SQLException { List<Map<String, Object>> tree = new ArrayList<Map<String, Object>>(); String sql = "SELECT DISTINCT F.* FROM T_SYS_FLAT F,(SELECT DISTINCT MODULEID FROM T_ACL_ROLEPRIVILEGE WHERE ROLEID IN (SELECT ROLEID FROM T_ACL_ROLEUSER WHERE USERID=:USERID) UNION ALL SELECT DISTINCT MODULEID FROM T_ACL_USERPRIVILEGE WHERE USERID=:USERID) MI, T_SYS_MODULEINFO M WHERE MI.MODULEID=M.MODULEID AND M.FLATID = F.FLATID"; List<TsysFlat> flats = session.createSQLQuery(sql) .addEntity(TsysFlat.class) .setString("USERID", curUserId).list(); sql = "SELECT DISTINCT MODULEID,OPERATEID FROM T_ACL_ROLEPRIVILEGE WHERE ROLEID IN (SELECT ROLEID FROM T_ACL_ROLEUSER WHERE USERID=?) UNION ALL SELECT DISTINCT MODULEID,OPERATEID FROM T_ACL_USERPRIVILEGE WHERE USERID=?"; //当前用户可用模块 Map<String, Object> modules = baseDAO.queryAsMapBySQL(sql, curUserId, curUserId); //已授权角色 sql = "SELECT DISTINCT MODULEID,OPERATEID FROM T_ACL_ROLEPRIVILEGE WHERE ROLEID IN (SELECT ROLEID FROM T_ACL_ROLEUSER WHERE USERID=?)"; Map<String, Object> assigned = baseDAO.queryAsMapBySQL(sql, userId); //已授权特权 sql = "SELECT DISTINCT MODULEID,OPERATEID FROM T_ACL_USERPRIVILEGE WHERE USERID=?"; Map<String, Object> privileges = baseDAO.queryAsMapBySQL(sql, userId); for (TsysFlat flat : flats) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", flat.getFlatid()); map.put("text", flat.getFlatname()); Map<String, Object> attr = new HashMap<String, Object>(); attr.put("flatid", flat.getFlatid()); map.put("attributes", attr); Set<TsysModuleinfo> moduleinfos = flat.getTsysModuleinfos(); if (moduleinfos.size() > 0) { List<Map<String, Object>> children = new ArrayList<Map<String, Object>>(); for (TsysModuleinfo info : moduleinfos) { if (!StringUtils.isNullOrEmpty(info.getParentmoduleid())) continue; Map<String, Object> child = new HashMap<String, Object>(); if (!modules.containsKey(info.getModuleid())) continue; buildModuleTree(info, child, modules, assigned, privileges); if (!child.isEmpty()) children.add(child); } map.put("children", children); map.put("state", "closed"); } tree.add(map); } return tree; } }); return JsonUtil.toString(map); } protected void buildModuleTree(TsysModuleinfo info, Map<String, Object> child, Map<String, Object> modules, Map<String, Object> assinged, Map<String, Object> privileges) throws ServiceException { if (!modules.containsKey(info.getModuleid())) return; child.put("id", info.getModuleid()); child.put("text", info.getModulename()); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("moduleid", info.getModuleid()); List<Map<String, Object>> children = new ArrayList<Map<String, Object>>(); boolean disalbedAss = assinged.get(info.getModuleid()) != null; boolean disalbedPri = privileges.get(info.getModuleid()) != null; Set<TsysModuleoperate> opers = info.getTsysModuleoperates(); for (TsysModuleoperate oper : opers) { if (modules.get(oper.getOperateid()) == null) continue; Map<String, Object> operMap = new HashMap<String, Object>(); operMap.put("id", oper.getOperateid()); operMap.put("text", oper.getOperatename()); Map<String, Object> attr = new HashMap<String, Object>(); attr.put("operid", oper.getOperateid()); attr.put("moduleid", info.getModuleid()); operMap.put("attributes", attr); boolean found = false; if (assinged.get(oper.getOperateid()) != null) { found = true; attr.put("disabled", true); } else if (privileges.get(oper.getOperateid()) != null) { found = true; } if (found) operMap.put("checked", true); children.add(operMap); } if (disalbedAss || disalbedPri) { attributes.put("disabled", disalbedAss); child.put("checked", true); } child.put("attributes", attributes); Set<TsysModuleinfo> set = info.getTsysModuleinfos(); for (TsysModuleinfo i : set) { Map<String, Object> chd = new HashMap<String, Object>(); buildModuleTree(i, chd, modules, assinged, privileges); if (!chd.isEmpty()) children.add(chd); } if (children.size() > 0) child.put("children", children); } @Override public void savePrivilege(String userId, String moduleSet) throws ServiceException { String hql = "delete from TaclUserprivilege where userid=?"; executeHQL(hql, userId); String[] modules = moduleSet.split(";"); for (String module : modules) { if ("".equals(module)) continue; String[] m = module.split(","); TaclUserprivilege tu = new TaclUserprivilege(); tu.setOperateid(m[0]); tu.setModuleid(m[1]); tu.setUserid(userId); saveOrUpdateVO(tu); } } @Override public boolean saveTreeSet(String userId, String treeNodes) throws ServiceException { String[] dataSets = treeNodes.split(","); String hql = "delete from TsysTreeprivilege where userid='"+userId+"'"; executeHQL(hql); for (String set : dataSets) { if ("".equals(set)) continue; TsysTreeprivilege td = new TsysTreeprivilege(); td.setOrgid(set); td.setUserid(userId); saveOrUpdateVO(td); } return true; } @Override public List<Map<String, Object>> getModuleTree(final String userId) throws ServiceException { final List<Map<String, Object>> tree = new ArrayList<Map<String, Object>>(); baseDAO.doInHibernate(new HibernateCallback<Object>() { @SuppressWarnings("unchecked") public Object doInHibernate(Session arg0) throws HibernateException, SQLException { String hql = "from TaclRoleprivilege where roleid in (select roleid from TaclRoleuser where userid=?)"; List<TaclRoleprivilege> assigned = (List<TaclRoleprivilege>) getValueObjectsByHQL(hql, userId); hql = "from TaclUserprivilege where userid=?"; List<TaclUserprivilege> userpri = (List<TaclUserprivilege>) getValueObjectsByHQL(hql, userId); for (TaclUserprivilege pri : userpri) { TaclRoleprivilege r = new TaclRoleprivilege(); r.setModuleid(pri.getModuleid()); r.setOperateid(pri.getOperateid()); assigned.add(r); } List<TsysFlat> flats = (List<TsysFlat>) getValueObjectsByHQL("from TsysFlat order by flatdesc"); for (TsysFlat flat : flats) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", flat.getFlatid()); map.put("text", flat.getFlatname()); Map<String, Object> attr = new HashMap<String, Object>(); attr.put("flatid", flat.getFlatid()); map.put("attributes", JsonUtil.toString(attr)); Set<TsysModuleinfo> moduleinfos = flat.getTsysModuleinfos(); if (moduleinfos.size() > 0) { List<Map<String, Object>> children = new ArrayList<Map<String, Object>>(); for (TsysModuleinfo info : moduleinfos) { if (!StringUtils.isNullOrEmpty(info .getParentmoduleid())) continue; Map<String, Object> child = new HashMap<String, Object>(); buildModuleTree(info, child, assigned, true, false); children.add(child); } map.put("children", children); map.put("state", "closed"); } tree.add(map); } return null; } }); return tree; } @Override public boolean saveOrUpdateTaclDutyUser(String userId, String duty) throws ServiceException { String[] dataSets = duty.split(","); String hql = "delete from TaclDutyuser where userid='"+userId+"'"; executeHQL(hql); for (String set : dataSets) { if ("".equals(set)) continue; TaclDutyuser td = new TaclDutyuser(); td.setDutyid(set); td.setUserid(userId); saveOrUpdateVO(td); } return true; } @Override public List<TsysDuty> getDutyAllByUserId(String userId) throws ServiceException { String hql = "from TsysDuty d where d.dutyid in " + "(select du.dutyid from TaclDutyuser du where du.userid = ?)"; @SuppressWarnings("unchecked") List<TsysDuty> dutySet = (List<TsysDuty>) getValueObjectsByHQL(hql, userId); return dutySet; } @Override public String getDutyAllNameByUserId(String userId) throws ServiceException { String result = ""; List<TsysDuty> dutySet = getDutyAllByUserId(userId); for (TsysDuty tsysDuty : dutySet) { result += tsysDuty.getDutyname() + ","; } if(result.endsWith(",")){ result = result.substring(0, result.length() - 1); } return result; } }
mzohreva/PASS
pass-core/src/main/java/pass/core/model/VerificationCode.java
package pass.core.model; import java.io.Serializable; import java.util.Date; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import pass.core.common.Config; import pass.core.common.Util; @Entity @Table (name = "verification_codes") public class VerificationCode implements Serializable { public enum Reason { ACCOUNT_CREATION, PASSWORD_RESET } @Id @Column (columnDefinition = "binary(16)") private UUID code; @Column private Reason reason; @ManyToOne private User user; @Column @Temporal (javax.persistence.TemporalType.TIMESTAMP) private Date creationDate; public VerificationCode() { } public static VerificationCode generate(Reason reason, User user) { VerificationCode vc = new VerificationCode(); vc.code = UUID.randomUUID(); vc.reason = reason; vc.user = user; vc.creationDate = new Date(); return vc; } public UUID getCode() { return code; } public String getLink() { final String serverUrl = Config.getInstance().getServerUrl(); return serverUrl + "verify.do?code=" + code.toString(); } public void setCode(UUID code) { this.code = code; } public Reason getReason() { return reason; } public void setReason(Reason reason) { this.reason = reason; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Date getCreationDate() { return creationDate; } public String getAge() { return Util.dateDifferenceHumanReadable( creationDate, new Date(), Util.DateDifferencePrecision.SECONDS, true); } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public String toString() { return "[" + this.code.toString() + ", " + (this.user != null ? this.user.getUsername() : "?") + ", " + this.reason + "]"; } }
mbarlowvt/Hydrograph
hydrograph.ui/hydrograph.ui.propertywindow/src/main/java/hydrograph/ui/propertywindow/widgets/utility/FilterOperationClassUtility.java
/******************************************************************************* * Copyright 2017 Capital One Services, LLC and Bitwise, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package hydrograph.ui.propertywindow.widgets.utility; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.core.CompilationUnit; import org.eclipse.jdt.internal.core.PackageFragment; import org.eclipse.jdt.ui.actions.OpenNewClassWizardAction; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import hydrograph.ui.common.component.config.Operations; import hydrograph.ui.common.component.config.TypeInfo; import hydrograph.ui.common.datastructures.tooltip.TootlTipErrorMessage; import hydrograph.ui.common.util.Constants; import hydrograph.ui.common.util.OSValidator; import hydrograph.ui.common.util.XMLConfigUtil; import hydrograph.ui.logging.factory.LogFactory; import hydrograph.ui.propertywindow.factory.ListenerFactory; import hydrograph.ui.propertywindow.messages.Messages; import hydrograph.ui.propertywindow.propertydialog.PropertyDialogButtonBar; import hydrograph.ui.propertywindow.widgets.customwidgets.config.OperationClassConfig; import hydrograph.ui.propertywindow.widgets.customwidgets.config.WidgetConfig; import hydrograph.ui.propertywindow.widgets.dialogs.ExternalSchemaFileSelectionDialog; import hydrograph.ui.propertywindow.widgets.gridwidgets.basic.AbstractELTWidget; import hydrograph.ui.propertywindow.widgets.gridwidgets.basic.ELTDefaultButton; import hydrograph.ui.propertywindow.widgets.gridwidgets.basic.ELTDefaultLable; import hydrograph.ui.propertywindow.widgets.gridwidgets.container.ELTDefaultSubgroupComposite; import hydrograph.ui.propertywindow.widgets.interfaces.IOperationClassDialog; import hydrograph.ui.propertywindow.widgets.listeners.ListenerHelper; import hydrograph.ui.propertywindow.widgets.listeners.ListenerHelper.HelperType; /** * The Class FilterOperationClassUtility use to create operation class widget,new class wizard and selection dialog window. * * @author Bitwise */ public class FilterOperationClassUtility { private static final Logger logger = LogFactory.INSTANCE.getLogger(FilterOperationClassUtility.class); public static final FilterOperationClassUtility INSTANCE = new FilterOperationClassUtility(); private static IJavaProject iJavaProject; private Button createBtn; private Button browseBtn; private Button openBtn; private Button btnCheckButton; private String componentName; private String fileNameTextBoxValue; private ELTDefaultButton emptyButton; private AbstractELTWidget browseButton; private FilterOperationClassUtility(){ } /** * Creates the new class wizard. * * @param fileNameTextBox * the file name * @param widgetConfig */ public void createNewClassWizard(Text fileNameTextBox, WidgetConfig widgetConfig) { OpenNewClassWizardAction wizard = new OpenNewClassWizardAction(); wizard.setOpenEditorOnFinish(false); final CustomizeNewClassWizardPage page = new CustomizeNewClassWizardPage(); page.setSuperClass("java.lang.Object", true); page.setMethodStubSelection(false, false, true, true); List<String> interfaceList = new ArrayList<String>(); OperationClassConfig operationClassConfig = (OperationClassConfig) widgetConfig; Operations operations = XMLConfigUtil.INSTANCE.getComponent(getComponentName()).getOperations(); TypeInfo typeInfo=operations.getInterface(); if (operationClassConfig!=null && operationClassConfig.getComponentName().equalsIgnoreCase(typeInfo.getName())) { interfaceList.add(typeInfo.getClazz()); } page.setSuperInterfaces(interfaceList, true); wizard.setConfiguredWizardPage(page); if(OSValidator.isMac()){ Display.getDefault().timerExec(0, new Runnable() { @Override public void run() { page.getControl().forceFocus(); } }); } wizard.run(); if (page.isPageComplete()) { if(!page.getPackageText().equalsIgnoreCase("")){ fileNameTextBox.setText(page.getPackageText()+"." + page.getTypeName()); }else{ fileNameTextBox.setText(page.getTypeName()); } } fileNameTextBox.setData("path", "/" + page.getPackageFragmentRootText() + "/" + page.getPackageText().replace(".", "/") + "/" + page.getTypeName() + ".java"); } /** * Open browse file dialog according extensions. * * @param filterExtension * the filter extension * @param fileName * the file name */ public void browseFile(String filterExtension, Text fileName) { if(Extensions.JAVA.toString().equalsIgnoreCase(filterExtension)) { browseJavaSelectionDialog(filterExtension, fileName); } if(Extensions.JOB.toString().equalsIgnoreCase(filterExtension)) { browseJobSelectionDialog(filterExtension, fileName); } if(Extensions.SCHEMA.toString().equalsIgnoreCase(filterExtension)) { browseSchemaSelectionDialog(filterExtension, fileName); } if(Extensions.XML.toString().equalsIgnoreCase(filterExtension)) { browseXMLSelectionDialog(filterExtension, fileName); } } /** * * Open selection dialog for schema files, File selection restricted to ".schema" extension. * @param filterExtension * @param fileName */ private void browseSchemaSelectionDialog(String filterExtension, Text fileName) { String externalSchemaTextBoxValue = ""; ExternalSchemaFileSelectionDialog dialog = new ExternalSchemaFileSelectionDialog("Project", "Select Schema File (.schema or.xml)", new String[]{filterExtension,Extensions.XML.toString()}, this); if (dialog.open() == IDialogConstants.OK_ID) { String file = fileNameTextBoxValue; IResource resource = (IResource) dialog.getFirstResult(); String path[] = resource.getFullPath().toString().split("/"); if (file.isEmpty()) { for (int i = 1; i < path.length; i++) { externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/"; } } else { for (int i = 1; i < path.length; i++) { if (!path[i].endsWith(".schema") && !path[i].endsWith(".xml")) { externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/"; } } externalSchemaTextBoxValue = externalSchemaTextBoxValue + file; } fileName.setText(externalSchemaTextBoxValue); } } /** * @param filterExtension * @param fileName * Open the dialog to browse .xml file for expression, operation or outputfields */ private void browseXMLSelectionDialog(String filterExtension, Text fileName) { String externalSchemaTextBoxValue = ""; ExternalSchemaFileSelectionDialog dialog = new ExternalSchemaFileSelectionDialog("Project", "Select Input File (.xml)", new String[]{filterExtension,Extensions.XML.toString()}, this); if (dialog.open() == IDialogConstants.OK_ID) { String file = fileNameTextBoxValue; IResource resource = (IResource) dialog.getFirstResult(); String path[] = resource.getFullPath().toString().split("/"); if (file.isEmpty()) { for (int i = 1; i < path.length; i++) { externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/"; } } else { for (int i = 1; i < path.length; i++) { if (!path[i].endsWith(".xml")) { externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/"; } } externalSchemaTextBoxValue = externalSchemaTextBoxValue + file; } fileName.setText(externalSchemaTextBoxValue); } } /** * Open selection dialog for Java files, File selection restricted to ".java" extension. * @param filterExtension * @param fileName */ public static void browseJavaSelectionDialog(String filterExtension, Text fileName) { ResourceFileSelectionDialog dialog = new ResourceFileSelectionDialog( "Project", "Select Java Class (.java)", new String[] { filterExtension }); if (dialog.open() == IDialogConstants.OK_ID) { IResource resource = (IResource) dialog.getFirstResult(); String filePath = resource.getRawLocation().toOSString(); java.nio.file.Path path =Paths.get(filePath); String classFile=path.getFileName().toString(); String name = ""; try(BufferedReader reader= new BufferedReader(new FileReader(filePath))){ String firstLine= reader.readLine(); if(firstLine.contains(Constants.PACKAGE)){ name= firstLine.replaceFirst(Constants.PACKAGE, "").replace(";", ""); if(!name.equalsIgnoreCase("")){ name=name+"."+classFile.substring(0, classFile.lastIndexOf('.')); } }else{ name=classFile.substring(0, classFile.lastIndexOf('.')); } } catch (IOException e) { logger.error("Unable to read file " + filePath,e ); } fileName.setText(name.trim()); filePath = resource.getRawLocation().toOSString(); fileName.setData("path", resource.getFullPath().toString()); } } /** * Open selection dialog for job files, File selection restricted to ".job" extension. * @param filterExtension * @param fileName */ private void browseJobSelectionDialog(String filterExtension, Text fileName) { ResourceFileSelectionDialog dialog = new ResourceFileSelectionDialog( "Project", "Select Sub Job (.job)", new String[] { filterExtension }); if (dialog.open() == IDialogConstants.OK_ID) { IResource resource = (IResource) dialog.getFirstResult(); String filePath = resource.getFullPath().toString(); if(isFileExistsOnLocalFileSystem(new Path(filePath), fileName)){ fileName.setText(filePath.substring(1)); } } } /** * Check if file exist on local file system. * @param jobFilePath * @param textBox * @return */ private boolean isFileExistsOnLocalFileSystem(IPath jobFilePath, Text textBox) { jobFilePath=jobFilePath.removeFileExtension().addFileExtension(Constants.XML_EXTENSION_FOR_IPATH); try { if (ResourcesPlugin.getWorkspace().getRoot().getFile(jobFilePath).exists()){ return true; } else if (jobFilePath.toFile().exists()){ return true; } } catch (Exception exception) { logger.error("Error occured while cheking file on local file system", exception); } MessageBox messageBox = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO); messageBox.setMessage(jobFilePath.lastSegment()+Messages.FILE_DOES_NOT_EXISTS); messageBox.setText(jobFilePath.toString() +Messages.NOT_EXISTS); int response = messageBox.open(); if (response == SWT.YES) { jobFilePath=jobFilePath.removeFileExtension().addFileExtension(Constants.JOB_EXTENSION_FOR_IPATH); textBox.setText(jobFilePath.toString().substring(1)); } else{ textBox.setText(""); } return false; } /** * Open file editor to view java file. * * @param fileName * the file name * @return true, if successful */ @SuppressWarnings("restriction") public boolean openFileEditor(Text filePath,String pathFile) { String fullQualifiedClassName = filePath.getText(); try { logger.debug("Searching "+fullQualifiedClassName+" in project's source folder"); PackageFragment packageFragment = null; String[] packages = StringUtils.split(fullQualifiedClassName, "."); String className = fullQualifiedClassName; String packageStructure=""; IFile javaFile=null; if (packages.length > 1) { className = packages[packages.length - 1]; packageStructure= StringUtils.replace(fullQualifiedClassName, "." + className, ""); } IFileEditorInput editorInput = (IFileEditorInput) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().getActiveEditor().getEditorInput(); IProject project = editorInput.getFile().getProject(); IJavaProject iJavaProject = JavaCore.create(project); IPackageFragmentRoot packageFragmentRoot = iJavaProject .getPackageFragmentRoot(project.getFolder(Constants.ProjectSupport_SRC)); if(packageFragmentRoot!= null){ for (IJavaElement iJavaElement : packageFragmentRoot.getChildren()) { if (iJavaElement instanceof PackageFragment && StringUtils.equals(iJavaElement.getElementName(), packageStructure)) { packageFragment = (PackageFragment) iJavaElement; break; } } } if (packageFragment != null) { for (IJavaElement element : packageFragment.getChildren()) { if (element instanceof CompilationUnit && StringUtils.equalsIgnoreCase(element.getElementName(), className + Constants.JAVA_EXTENSION)) { javaFile = (IFile) element.getCorrespondingResource(); break; } } } if (javaFile !=null && javaFile.exists()) { IFileStore fileStore = EFS.getLocalFileSystem().getStore(javaFile.getLocationURI()); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IDE.openEditorOnFileStore(page, fileStore); return true; } } catch (Exception e) { logger.error("Fail to open file"); return false; } return false; } /** * * Operation class widget creation * @param composite * @param eltOperationClassDialogButtonBar * @param combo * @param isParameterCheckbox * @param fileNameTextBox * @param tootlTipErrorMessage * @param widgetConfig * @param eltOperationClassDialog * @param propertyDialogButtonBar * @param opeartionClassDialogButtonBar */ public void createOperationalClass( Composite composite, PropertyDialogButtonBar eltOperationClassDialogButtonBar, AbstractELTWidget combo, AbstractELTWidget isParameterCheckbox, AbstractELTWidget fileNameTextBox, TootlTipErrorMessage tootlTipErrorMessage, WidgetConfig widgetConfig, IOperationClassDialog eltOperationClassDialog, PropertyDialogButtonBar propertyDialogButtonBar, PropertyDialogButtonBar opeartionClassDialogButtonBar) { ELTDefaultSubgroupComposite eltSuDefaultSubgroupComposite = new ELTDefaultSubgroupComposite(composite); eltSuDefaultSubgroupComposite.createContainerWidget(); eltSuDefaultSubgroupComposite.numberOfBasicWidgets(5); AbstractELTWidget eltDefaultLable = new ELTDefaultLable(Messages.OPERATION_CLASS); eltSuDefaultSubgroupComposite.attachWidget(eltDefaultLable); eltSuDefaultSubgroupComposite.attachWidget(combo); Combo comboOfOperaationClasses = (Combo) combo.getSWTWidgetControl(); eltSuDefaultSubgroupComposite.attachWidget(fileNameTextBox); Text fileName = (Text) fileNameTextBox.getSWTWidgetControl(); fileName.setSize(10, 100); addModifyListenerToFileNameTextBox(fileName); GridData layoutData = (GridData)fileName.getLayoutData(); layoutData.horizontalIndent=6; if(OSValidator.isMac()){ browseButton = new ELTDefaultButton(Messages.BROWSE_BUTTON_TEXT).buttonWidth(35); }else{ browseButton = new ELTDefaultButton(Messages.BROWSE_BUTTON_TEXT).buttonWidth(25); } eltSuDefaultSubgroupComposite.attachWidget(browseButton); browseBtn=(Button)browseButton.getSWTWidgetControl(); eltSuDefaultSubgroupComposite.attachWidget(isParameterCheckbox); ELTDefaultSubgroupComposite eltSuDefaultSubgroupComposite2 = new ELTDefaultSubgroupComposite(composite); eltSuDefaultSubgroupComposite2.createContainerWidget(); eltSuDefaultSubgroupComposite2.numberOfBasicWidgets(3); if(OSValidator.isMac()){ emptyButton = new ELTDefaultButton("").buttonWidth(92); } else{ emptyButton = new ELTDefaultButton("").buttonWidth(89); } eltSuDefaultSubgroupComposite2.attachWidget(emptyButton); emptyButton.visible(false); // Create new button, that use to create operational class AbstractELTWidget createButton = new ELTDefaultButton(Messages.CREATE_NEW_OPEARTION_CLASS_LABEL); eltSuDefaultSubgroupComposite2.attachWidget(createButton); createBtn=(Button)createButton.getSWTWidgetControl(); // Edit new button, that use to edit operational class AbstractELTWidget openButton = new ELTDefaultButton(Messages.OPEN_BUTTON_LABEL); eltSuDefaultSubgroupComposite2.attachWidget(openButton); openBtn=(Button)openButton.getSWTWidgetControl(); btnCheckButton=(Button) isParameterCheckbox.getSWTWidgetControl(); ListenerHelper helper = new ListenerHelper(); helper.put(HelperType.TOOLTIP_ERROR_MESSAGE, tootlTipErrorMessage); helper.put(HelperType.WIDGET_CONFIG, widgetConfig); helper.put(HelperType.OPERATION_CLASS_DIALOG_OK_CONTROL, eltOperationClassDialog); helper.put(HelperType.OPERATION_CLASS_DIALOG_APPLY_BUTTON, opeartionClassDialogButtonBar); helper.put(HelperType.PROPERTY_DIALOG_BUTTON_BAR, propertyDialogButtonBar); helper.put(HelperType.FILE_EXTENSION,"java"); setIJavaProject(); try { openButton.attachListener(ListenerFactory.Listners.OPEN_FILE_EDITOR.getListener(),eltOperationClassDialogButtonBar, helper,comboOfOperaationClasses,fileName); browseButton.attachListener(ListenerFactory.Listners.BROWSE_FILE_LISTNER.getListener(),eltOperationClassDialogButtonBar, helper,fileName); createButton.attachListener(ListenerFactory.Listners.CREATE_NEW_CLASS.getListener(),eltOperationClassDialogButtonBar, helper,comboOfOperaationClasses,fileName); combo.attachListener(ListenerFactory.Listners.COMBO_CHANGE.getListener(),eltOperationClassDialogButtonBar, helper,comboOfOperaationClasses,fileName,btnCheckButton); isParameterCheckbox.attachListener(ListenerFactory.Listners.ENABLE_BUTTON.getListener(),eltOperationClassDialogButtonBar, null,btnCheckButton,browseButton.getSWTWidgetControl(),createButton.getSWTWidgetControl(),openButton.getSWTWidgetControl()); } catch (Exception e) { logger.error("Fail to attach listener "+e); } } private void addModifyListenerToFileNameTextBox(Text fileName) { fileName.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Text classNameTextBox=(Text)e.widget; openBtn.setEnabled(StringUtils.isNotBlank(classNameTextBox.getText())&&!btnCheckButton.getSelection()); } }); } private static void setIJavaProject() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if ((page.getActiveEditor().getEditorInput().getClass()).isAssignableFrom(FileEditorInput.class)) { IFileEditorInput input = (IFileEditorInput) page.getActiveEditor().getEditorInput(); IFile file = input.getFile(); IProject activeProject = file.getProject(); IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(activeProject.getName()); iJavaProject = JavaCore.create(project); } } public static IJavaProject getIJavaProject() { return iJavaProject; } /** * Enable and disable new class creation button and open editor button base on isParam checkbox. * @param value * @param checkboxValue */ public void enableAndDisableButtons(boolean value,boolean checkboxValue) { if (checkboxValue==false) { createBtn.setEnabled(value); browseBtn.setEnabled(value); btnCheckButton.setEnabled(!value); } if (checkboxValue==true) { btnCheckButton.setEnabled(value); openBtn.setEnabled(!value); createBtn.setEnabled(!value); browseBtn.setEnabled(!value); } } public void setComponentName(String name) { componentName = name; } public String getComponentName() { return componentName; } public boolean isCheckBoxSelected() { return btnCheckButton.getSelection(); } /** * Set Operation * @param operationName * @param textBox */ public void setOperationClassNameInTextBox(String operationName, Text textBox) { String operationClassName = null; Operations operations = XMLConfigUtil.INSTANCE.getComponent(getComponentName()) .getOperations(); List<TypeInfo> typeInfos = operations.getStdOperation(); for (int i = 0; i < typeInfos.size(); i++) { if (typeInfos.get(i).getName().equalsIgnoreCase(operationName)) { operationClassName = typeInfos.get(i).getClazz(); break; } } textBox.setText(operationClassName);; } public String getFileNameTextBoxValue() { return fileNameTextBoxValue; } public void setFileNameTextBoxValue(String fileNameTextBoxValue) { this.fileNameTextBoxValue = fileNameTextBoxValue; } /** * @return the openBtn */ public Button getOpenBtn() { return openBtn; } }
tsemaylo/DerivativeSolver
src/MathParser/src/Sin.cpp
<reponame>tsemaylo/DerivativeSolver /* Licensed to <NAME> under the MIT license. * Refer to the LICENSE.txt file in the project root for more information. */ /** * @file Sin.cpp * * Implemntation of Sin class. * * @author agor * @since 16.08.2017 */ #include "Sin.h" #include "Visitor.h" #include "TraverseException.h" Sin::Sin() : Expression(ESin) { } bool Sin::isComplete() const { return (this->arg!=nullptr); } void Sin::traverse(Visitor& visitor) const throw(TraverseException) { visitor.visit(shared_from_this()); }
rchaput/homebrew-core
Formula/server-go.rb
<filename>Formula/server-go.rb class ServerGo < Formula desc "Server for OpenIoTHub" homepage "https://github.com/OpenIoTHub/server-go" url "https://github.com/OpenIoTHub/server-go.git", tag: "v1.1.77", revision: "1c096fa17a6b529bb0002c224c9b035df368f30e" license "MIT" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "3209d8af70df99fe6e18745742bf1676eb4839a3c15c3fd03ba5416c2ed67234" sha256 cellar: :any_skip_relocation, arm64_big_sur: "9b528abc2bddbaf803d475fbb23758db2c018704c34c9b5c492b0a7f29f3fd9c" sha256 cellar: :any_skip_relocation, monterey: "93b4532f5bd3c808e74225db0deec2aff1bc0f585eaada465dcfb3df70b6602f" sha256 cellar: :any_skip_relocation, big_sur: "48b01c329bbf329c08da2d827c3891659f7a82eb15913b5f666cad9ca835d5eb" sha256 cellar: :any_skip_relocation, catalina: "d0c6e7d29e40bdf3535103019722db0dcfdc787e18747b1b3c72b87f7a52c33a" sha256 cellar: :any_skip_relocation, mojave: "80bf7c30103432008ea9fe2e5dea8d32de5d71e0d563e2a5c0aa59192238dad4" sha256 cellar: :any_skip_relocation, x86_64_linux: "3c575de6caf4916eedf3791c3efb703153f171d9b12c3ba9e9bac579b86d2fe6" end depends_on "go" => :build def install (etc/"server-go").mkpath system "go", "build", "-mod=vendor", "-ldflags", "-s -w -X main.version=#{version} -X main.commit=#{Utils.git_head} -X main.builtBy=homebrew", *std_go_args etc.install "server-go.yaml" => "server-go/server-go.yaml" end service do run [opt_bin/"server-go", "-c", etc/"server-go/server-go.yaml"] keep_alive true log_path var/"log/server-go.log" error_log_path var/"log/server-go.log" end test do assert_match version.to_s, shell_output("#{bin}/server-go -v 2>&1") assert_match "config created", shell_output("#{bin}/server-go init --config=server.yml 2>&1") assert_predicate testpath/"server.yml", :exist? end end
privatosan/RayStorm
srcAmiga/rsi/voxel.cpp
<reponame>privatosan/RayStorm /*************** * MODUL: voxel * NAME: voxel.cpp * DESCRIPTION: Functions for voxels * AUTHORS: <NAME>, <NAME> * HISTORY: * DATE NAME COMMENT * 11.02.95 ah initial release ***************/ #ifndef TYPEDEFS_H #include "typedefs.h" #endif #ifndef VECMATH_H #include "vecmath.h" #endif #ifndef VOXEL_H #include "voxel.h" #endif /************* * DESCRIPTION: * INPUT: voxel pointer to voxel * vecotor pointer to vector * OUTPUT: none *************/ #ifndef LOWLEVEL void MinimizeMaximizeVoxel(VOXEL *voxel, VECTOR *vector) { MinimizeVector(&voxel->min, &voxel->min, vector); MaximizeVector(&voxel->max, &voxel->max, vector); } #endif /************* * DESCRIPTION: Union two voxels * INPUT: result result * voxel1 first voxel * voxel2 second voxel * OUTPUT: none *************/ #ifndef LOWLEVEL void UnionVoxel(VOXEL *result, const VOXEL *voxel1, const VOXEL *voxel2) { MinimizeVector(&result->min, &voxel1->min, &voxel2->min); MaximizeVector(&result->max, &voxel1->max, &voxel2->max); } #endif /************* * DESCRIPTION: Test if point is in voxel * INPUT: point point to test * voxel voxel to test with * OUTPUT: TRUE if intersection, else FALSE *************/ #ifndef LOWLEVEL BOOL PointInVoxel(const VECTOR *point, const VOXEL *voxel) { return(((voxel->min.x <= point->x) && (point->x <= voxel->max.x)) && ((voxel->min.y <= point->y) && (point->y <= voxel->max.y)) && ((voxel->min.z <= point->z) && (point->z <= voxel->max.z))); } #endif /************* * DESCRIPTION: Test if ray intersects voxel * INPUT: lambda distance factor * start startposition * ray pointer to ray direction * voxel pointer to voxel * OUTPUT: TRUE if intersection, else FALSE *************/ #ifndef LOWLEVEL BOOL RayVoxelIntersection(float *lambda, const VECTOR *start, const VECTOR *ray, const VOXEL *voxel) { float nearest, farest, lambda1, lambda2, help; nearest = -INFINITY; farest = INFINITY; if((ray->x > 0.f ? ray->x : - ray->x) > EPSILON) { help = 1.f/ray->x; lambda1 = (voxel->min.x-start->x)*help; lambda2 = (voxel->max.x-start->x)*help; if(lambda1 > lambda2) { help = lambda1; lambda1 = lambda2; lambda2 = help; } if(lambda1 > nearest) { nearest = lambda1; } if(lambda2 < farest) { farest = lambda2; } if((nearest > farest) || (farest < 0.f)) { return(FALSE); } } else { if((start->x < voxel->min.x) || (start->x > voxel->max.x)) { return(FALSE); } } if((ray->y > 0.f ? ray->y : - ray->y) > EPSILON) { help = 1.f/ray->y; lambda1 = (voxel->min.y-start->y)*help; lambda2 = (voxel->max.y-start->y)*help; if(lambda1 > lambda2) { help = lambda1; lambda1 = lambda2; lambda2 = help; } if(lambda1 > nearest) { nearest = lambda1; } if(lambda2 < farest) { farest = lambda2; } if((nearest > farest) || (farest < 0.f)) { return(FALSE); } } else { if((start->y < voxel->min.y) || (start->y > voxel->max.y)) { return(FALSE); } } if((ray->z > 0.f ? ray->z : - ray->z) > EPSILON) { help = 1.f/ray->z; lambda1 = (voxel->min.z-start->z)*help; lambda2 = (voxel->max.z-start->z)*help; if(lambda1 > lambda2) { help = lambda1; lambda1 = lambda2; lambda2 = help; } if(lambda1 > nearest) { nearest = lambda1; } if(lambda2 < farest) { farest = lambda2; } if((nearest > farest) || (farest < 0.f)) { return(FALSE); } } else { if((start->z < voxel->min.z) || (start->z > voxel->max.z)) { return(FALSE); } } *lambda = nearest; return TRUE; } #endif /************* * DESCRIPTION: Accumulate Point * INPUT: voxel * v voxel is extended so that this vector fits inside * pos position * ox,oy,oz orientation * OUTPUT: none *************/ static void AccumulatePoint(VOXEL *voxel, VECTOR *v, VECTOR *pos, VECTOR *ox, VECTOR *oy, VECTOR *oz) { VECTOR v1; v1.x = dotp(v, ox); v1.y = dotp(v, oy); v1.z = dotp(v, oz); VecAdd(&v1, pos, &v1); if(v1.x < voxel->min.x) voxel->min.x = v1.x; if(v1.x > voxel->max.x) voxel->max.x = v1.x; if(v1.y < voxel->min.y) voxel->min.y = v1.y; if(v1.y > voxel->max.y) voxel->max.y = v1.y; if(v1.z < voxel->min.z) voxel->min.z = v1.z; if(v1.z > voxel->max.z) voxel->max.z = v1.z; } /************* * DESCRIPTION: Accumulate Voxel * INPUT: voxel * min,max * pos position * ox,oy,oz orientation * OUTPUT: none *************/ void AccumulateVoxel(VOXEL *voxel, VECTOR *min, VECTOR *max, VECTOR *pos, VECTOR *ox, VECTOR *oy, VECTOR *oz) { VECTOR v; SetVector(&voxel->min, INFINITY, INFINITY, INFINITY); SetVector(&voxel->max, -INFINITY, -INFINITY, -INFINITY); // generate voxel v = *min; AccumulatePoint(voxel, &v, pos, ox, oy, oz); SetVector(&v, min->x, min->y, max->z); AccumulatePoint(voxel, &v, pos, ox, oy, oz); SetVector(&v, min->x, max->y, min->z); AccumulatePoint(voxel, &v, pos, ox, oy, oz); SetVector(&v, min->x, max->y, max->z); AccumulatePoint(voxel, &v, pos, ox, oy, oz); SetVector(&v, max->x, min->y, min->z); AccumulatePoint(voxel, &v, pos, ox, oy, oz); SetVector(&v, max->x, min->y, max->z); AccumulatePoint(voxel, &v, pos, ox, oy, oz); SetVector(&v, max->x, max->y, min->z); AccumulatePoint(voxel, &v, pos, ox, oy, oz); v = *max; AccumulatePoint(voxel, &v, pos, ox, oy, oz); }
iondv/ion-old-java-version-20140819
ion-web-admin/src/main/java/ion/web/admin/LoginController.java
package ion.web.admin; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LoginController extends BasicController { @RequestMapping(value="/login", method = RequestMethod.GET) public String login(ModelMap model) { return themeDir+"/login"; } @RequestMapping(value="/logout", method = RequestMethod.GET) public String logout(ModelMap model) { return themeDir+"/login"; } @RequestMapping(value="/loginfailed", method = RequestMethod.GET) public String loginerror(ModelMap model) { model.addAttribute("error", "true"); return themeDir+"/login"; } @RequestMapping(value="/403", method = RequestMethod.GET) public String accessDenied(ModelMap model) { return themeDir+"/403"; } }
kuolei/incubator-doris
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionKeyDesc.java
// 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.doris.analysis; import org.apache.doris.common.AnalysisException; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import java.util.List; // Describe the partition key values in create table or add partition clause public class PartitionKeyDesc { public static final PartitionKeyDesc MAX_VALUE = new PartitionKeyDesc(); public enum PartitionKeyValueType { INVALID, LESS_THAN, FIXED, IN } private List<PartitionValue> lowerValues; private List<PartitionValue> upperValues; private List<List<PartitionValue>> inValues; private PartitionKeyValueType partitionKeyValueType; public static PartitionKeyDesc createMaxKeyDesc() { return MAX_VALUE; } private PartitionKeyDesc() { partitionKeyValueType = PartitionKeyValueType.LESS_THAN; // LESS_THAN is default type. } public static PartitionKeyDesc createLessThan(List<PartitionValue> upperValues) { PartitionKeyDesc desc = new PartitionKeyDesc(); desc.upperValues = upperValues; desc.partitionKeyValueType = PartitionKeyValueType.LESS_THAN; return desc; } public static PartitionKeyDesc createIn(List<List<PartitionValue>> inValues) { PartitionKeyDesc desc = new PartitionKeyDesc(); desc.inValues = inValues; desc.partitionKeyValueType = PartitionKeyValueType.IN; return desc; } public static PartitionKeyDesc createFixed(List<PartitionValue> lowerValues, List<PartitionValue> upperValues) { PartitionKeyDesc desc = new PartitionKeyDesc(); desc.lowerValues = lowerValues; desc.upperValues = upperValues; desc.partitionKeyValueType = PartitionKeyValueType.FIXED; return desc; } public List<PartitionValue> getLowerValues() { return lowerValues; } public List<PartitionValue> getUpperValues() { return upperValues; } public List<List<PartitionValue>> getInValues() { return inValues; } public boolean isMax() { return this == MAX_VALUE; } public boolean hasLowerValues() { return lowerValues != null; } public boolean hasUpperValues() { return upperValues != null; } public PartitionKeyValueType getPartitionType() { return partitionKeyValueType; } public void analyze(int partColNum) throws AnalysisException { if (!isMax()) { if ((upperValues != null && (upperValues.isEmpty() || upperValues.size() > partColNum))) { throw new AnalysisException("Partition values number is more than partition column number: " + toSql()); } } // Currently, we do not support MAXVALUE in multi partition range values. eg: ("100", "200", MAXVALUE); // Because we still don’t support expressing such values on the BE side. // Maybe support later. // But we can support MAXVALUE in single partition values. if (lowerValues != null && lowerValues.size() > 1) { for (PartitionValue lowerVal : lowerValues) { if (lowerVal.isMax()) { throw new AnalysisException("Not support MAXVALUE in multi partition range values."); } } } if (upperValues != null && upperValues.size() > 1) { for (PartitionValue upperVal : upperValues) { if (upperVal.isMax()) { throw new AnalysisException("Not support MAXVALUE in multi partition range values."); } } } } // returns: // 1: MAXVALUE // 2: ("100", "200", MAXVALUE) // 3: [("100", "200"), ("300", "200")) public String toSql() { if (isMax()) { return "MAXVALUE"; } if (partitionKeyValueType == PartitionKeyValueType.LESS_THAN) { return getPartitionValuesStr(upperValues); } else if (partitionKeyValueType == PartitionKeyValueType.FIXED) { StringBuilder sb = new StringBuilder("["); sb.append(getPartitionValuesStr(lowerValues)).append(", ").append(getPartitionValuesStr(upperValues)); sb.append(")"); return sb.toString(); } else if (partitionKeyValueType == PartitionKeyValueType.IN) { StringBuilder sb = new StringBuilder("("); for (int i = 0; i < inValues.size(); i++) { String valueStr = getPartitionValuesStr(inValues.get(i)); if (inValues.get(i).size() == 1) { valueStr = valueStr.substring(1, valueStr.length() - 1); } sb.append(valueStr); if (i < inValues.size() - 1) { sb.append(","); } } sb.append(")"); return sb.toString(); } else { return "INVALID"; } } private String getPartitionValuesStr(List<PartitionValue> values) { StringBuilder sb = new StringBuilder("("); Joiner.on(", ").appendTo(sb, Lists.transform(values, new Function<PartitionValue, String>() { @Override public String apply(PartitionValue v) { if (v.isMax()) { return v.getStringValue(); } else { return "'" + v.getStringValue() + "'"; } } })).append(")"); return sb.toString(); } }
charliealpha094/Project_Data_Visualization
Chapter_16_Downloading_Data/Mapping_global_datasets_json/eq_explore_data2.py
<reponame>charliealpha094/Project_Data_Visualization #Done by <NAME> (25/07/2020) #Extracting magnitudes import json filename = 'data/eq_data_1_day_m1.json' with open(filename) as f: all_eq_data = json.load(f) readable_file = 'data/readable_eq_data.json' with open(readable_file, 'w') as f: json.dump(all_eq_data, f, indent=4) #Making a list of all earthquackes. all_eq_dicts = all_eq_data['features'] mags = [] #Empty list to store the magnitudes. for eq_dict in all_eq_dicts: #Inside the loop each earthquake is represented by eq_dict. mag = eq_dict['properties']['mag'] #Each earthquake's magnitude is stored in 'properties' section of the dictionary under 'mag' key mags.append(mag) #Store each magnitude in variable mag, and then append to the lists mags. print(mags[:10]) #print 1st 10 magnitudes.
extact-io/rms
rms-client-ui-console/src/main/java/io/extact/rms/client/console/login/LoggedInAuditLog.java
package io.extact.rms.client.console.login; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import lombok.extern.slf4j.Slf4j; import io.extact.rms.client.api.login.LoggedInEvent; @ApplicationScoped @Slf4j public class LoggedInAuditLog { void onLoggedInEvent(@Observes LoggedInEvent event) { log.info("{}さんがログインしました!", event.getLoginUser().getUserName()); } }
bostick/Deadlock
Capsloc/src/main/java/com/brentonbostick/capsloc/geom/MutableAABB.java
<filename>Capsloc/src/main/java/com/brentonbostick/capsloc/geom/MutableAABB.java<gh_stars>0 package com.brentonbostick.capsloc.geom; import java.io.Serializable; import com.brentonbostick.capsloc.math.DMath; import com.brentonbostick.capsloc.math.Point; import com.brentonbostick.capsloc.ui.paint.RenderingContext; public class MutableAABB implements Serializable { private static final long serialVersionUID = 1L; public double x = Double.NaN; public double y = Double.NaN; public double width = Double.NaN; public double height = Double.NaN; public final Point n01 = Point.UP; public final Point n12 = Point.RIGHT; private transient double[] n01Projection; private transient double[] n12Projection; public MutableAABB() { } public void reset() { x = Double.NaN; y = Double.NaN; width = Double.NaN; height = Double.NaN; n01Projection = null; n12Projection = null; } public void setLocation(double x, double y) { this.x = x; this.y = y; n01Projection = null; n12Projection = null; } public void setDimension(double width, double height) { this.width = width; this.height = height; n01Projection = null; n12Projection = null; } public void setShape(double x, double y, double width, double height) { this.x = x; this.y = y; this.width = width; this.height = height; n01Projection = null; n12Projection = null; } public AABB copy() { return new AABB(x, y, width, height); } public void union(AABB a) { if (Double.isNaN(x)) { x = a.x; y = a.y; width = a.width; height = a.height; } else { double brx = x+width; double bry = y+height; if (a.x < x) { x = a.x; } if (a.y < y) { y = a.y; } if (a.brX > brx) { brx = a.brX; } if (a.brY > bry) { bry = a.brY; } width = brx-x; height = bry-y; } } public boolean completelyWithin(AABB parent) { return DMath.lessThanEquals(parent.x, x) && DMath.lessThanEquals(x+width, parent.brX) && DMath.lessThanEquals(parent.y, y) && DMath.lessThanEquals(y+height, parent.brY); } /** * returns 0.0 if completely outside parent, returns 1.0 if completely within parent * * assumes only overlapping on an edge, and not on a corner */ public double fractionWithin(AABB inner, AABB outer) { if (DMath.lessThan(x, inner.x)) { if (DMath.lessThan(y+height, outer.y)) { return 0.0; } if (DMath.greaterThan(y, outer.brY)) { return 0.0; } double diff = inner.x - outer.x; double innerLen = inner.x - x; return DMath.greaterThan(innerLen, (diff+width)) ? 0.0 : 1.0 - innerLen / (diff+width); } if (DMath.greaterThan(x+width, inner.brX)) { if (DMath.lessThan(y+height, outer.y)) { return 0.0; } if (DMath.greaterThan(y, outer.brY)) { return 0.0; } double diff = outer.brX - inner.brX; double innerLen = x+width - inner.brX; return DMath.greaterThan(innerLen, (diff+width)) ? 0.0 : 1.0 - innerLen / (diff+width); } if (DMath.lessThan(y, inner.y)) { if (DMath.lessThan(x+width, outer.x)) { assert false; } if (DMath.greaterThan(x, outer.brX)) { assert false; } double diff = inner.y - outer.y; double innerLen = inner.y - y; if (DMath.greaterThan(innerLen, (diff+height))) { return 0.0; } else { return 1.0 - innerLen / (diff+height); } } if (DMath.greaterThan(y+height, inner.brY)) { if (DMath.lessThan(x+width, outer.x)) { assert false; } if (DMath.greaterThan(x, outer.brX)) { assert false; } double diff = outer.brY - inner.brY; double innerLen = y+height - inner.brY; return DMath.greaterThan(innerLen, (diff+height)) ? 0.0 : 1.0 - innerLen / (diff+height); } return 1.0; } public void project(Point axis, double[] out) { Point p0 = new Point(x, y); Point p1 = new Point(x + width, y); Point p2 = new Point(x+width, y+height); Point p3 = new Point(x, y + height); double min = Point.dot(axis, p0); double max = min; double p = Point.dot(axis, p1); if (p < min) { min = p; } else if (p > max) { max = p; } p = Point.dot(axis, p2); if (p < min) { min = p; } else if (p > max) { max = p; } p = Point.dot(axis, p3); if (p < min) { min = p; } else if (p > max) { max = p; } out[0] = min; out[1] = max; } public Point getN01() { return n01; } public Point getN12() { return n12; } public void projectN01(double[] out) { if (n01Projection == null) { computeProjections(); } out[0] = n01Projection[0]; out[1] = n01Projection[1]; } public void projectN12(double[] out) { if (n12Projection == null) { computeProjections(); } out[0] = n12Projection[0]; out[1] = n12Projection[1]; } private void computeProjections() { n01Projection = new double[2]; project(n01, n01Projection); n12Projection = new double[2]; project(n12, n12Projection); } public void draw(RenderingContext ctxt) { ctxt.drawAABB(this); } public void paint(RenderingContext ctxt) { ctxt.paintAABB(this); } }
lxxhome/JsExamples
test/headers.js
console.log(headers);
LgcyNetwork/Cosmos
lgcy/common/src/main/java/org/tron/common/overlay/discover/node/Node.java
<filename>lgcy/common/src/main/java/org/tron/common/overlay/discover/node/Node.java package org.tron.common.overlay.discover.node; import java.io.Serializable; import java.util.Random; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.spongycastle.util.encoders.Hex; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Utils; @Slf4j(topic = "discover") public class Node implements Serializable { private static final long serialVersionUID = -4267600517925770636L; private byte[] id; private String host; private int port; @Getter private int bindPort; @Setter private int p2pVersion; private boolean isFakeNodeId = false; public Node(byte[] id, String host, int port) { this.id = id; this.host = host; this.port = port; this.isFakeNodeId = true; } public Node(byte[] id, String host, int port, int bindPort) { this.id = id; this.host = host; this.port = port; this.bindPort = bindPort; } public static Node instanceOf(String hostPort) { try { String[] sz = hostPort.split(":"); int port = Integer.parseInt(sz[1]); return new Node(Node.getNodeId(), sz[0], port); } catch (Exception e) { logger.error("Parse node failed, {}", hostPort); throw e; } } public static byte[] getNodeId() { int NODE_ID_LENGTH = 64; Random gen = new Random(); byte[] id = new byte[NODE_ID_LENGTH]; gen.nextBytes(id); return id; } public boolean isConnectible(int argsP2PVersion) { return port == bindPort && p2pVersion == argsP2PVersion; } public String getHexId() { return Hex.toHexString(id); } public String getHexIdShort() { return Utils.getIdShort(getHexId()); } public boolean isDiscoveryNode() { return isFakeNodeId; } public byte[] getId() { return id; } public void setId(byte[] id) { this.id = id; } public String getHost() { return host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getIdString() { if (id == null) { return null; } return new String(id); } @Override public String toString() { return "Node{" + " host='" + host + '\'' + ", port=" + port + ", id=" + ByteArray.toHexString(id) + '}'; } @Override public int hashCode() { return this.toString().hashCode(); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() == getClass()) { return StringUtils.equals(getIdString(), ((Node) o).getIdString()); } return false; } }
krypt/krypt
test/helper.rb
<reponame>krypt/krypt begin require 'simplecov' SimpleCov.start rescue LoadError end require 'krypt' require 'test/unit' require_relative 'resources'
curtcox/ScreenRecorder
src/main/java/com/neomemex/shared/Pad.java
package com.neomemex.shared; public final class Pad { public static String last(int digitCount,int number) { String text = "0000" + number; return text.substring(text.length() - digitCount); } }
ProjectEdenGG/Nexus
src/main/java/gg/projecteden/nexus/features/particles/effects/CircleEffect.java
<filename>src/main/java/gg/projecteden/nexus/features/particles/effects/CircleEffect.java package gg.projecteden.nexus.features.particles.effects; import com.google.common.util.concurrent.AtomicDouble; import gg.projecteden.nexus.features.particles.ParticleUtils; import gg.projecteden.nexus.features.particles.VectorUtils; import gg.projecteden.nexus.framework.exceptions.postconfigured.InvalidInputException; import gg.projecteden.nexus.models.particle.ParticleService; import gg.projecteden.nexus.utils.Tasks; import gg.projecteden.utils.TimeUtils.TickTime; import lombok.Builder; import lombok.Getter; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Particle; import org.bukkit.Particle.DustOptions; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.concurrent.atomic.AtomicInteger; public class CircleEffect { @Getter private int taskId; @Builder(buildMethodName = "start") public CircleEffect(HumanEntity player, Location location, boolean updateLoc, Vector updateVector, Particle particle, boolean whole, boolean randomRotation, boolean rainbow, Color color, int count, int density, int ticks, double radius, double speed, boolean fast, double disX, double disY, double disZ, int startDelay, int pulseDelay, boolean clientSide) { if (player != null && location == null) location = player.getLocation(); if (player == null) throw new InvalidInputException("No player was provided"); if (density == 0) density = 20; double inc = (2 * Math.PI) / density; int steps = whole ? density : 1; int loops = 1; if (fast) loops = 10; if (updateVector != null) updateLoc = true; if (updateVector == null && updateLoc) updateVector = new Vector(0, 0, 0); if (color != null) { disX = color.getRed(); disY = color.getGreen(); disZ = color.getBlue(); } if (pulseDelay < 1) pulseDelay = 1; if (speed <= 0) speed = 0.1; if (count <= 0) count = 1; if (ticks == 0) ticks = TickTime.SECOND.x(5); if (particle == null) particle = Particle.REDSTONE; if (particle.equals(Particle.REDSTONE)) { count = 0; speed = 1; if (rainbow) { disX = 255; disY = 0; disZ = 0; } } double angularVelocityX = Math.PI / 200; double angularVelocityY = Math.PI / 170; double angularVelocityZ = Math.PI / 155; double finalSpeed = speed; int finalCount = count; int finalTicks = ticks; Particle finalParticle = particle; int finalLoops = loops; Location finalLocation = location; boolean finalUpdateLoc = updateLoc; Vector finalUpdateVector = updateVector; final AtomicDouble hue = new AtomicDouble(0); final AtomicInteger red = new AtomicInteger((int) disX); final AtomicInteger green = new AtomicInteger((int) disY); final AtomicInteger blue = new AtomicInteger((int) disZ); AtomicInteger ticksElapsed = new AtomicInteger(0); AtomicInteger step = new AtomicInteger(0); taskId = Tasks.repeat(startDelay, pulseDelay, () -> { if (finalTicks != -1 && ticksElapsed.get() >= finalTicks) { new ParticleService().get(player).cancel(taskId); return; } drawCircle(player, randomRotation, rainbow, radius, inc, steps, angularVelocityX, angularVelocityY, angularVelocityZ, finalSpeed, finalCount, finalParticle, finalLoops, finalLocation, finalUpdateLoc, finalUpdateVector, hue, red, green, blue, step, clientSide); if (finalTicks != -1) ticksElapsed.incrementAndGet(); }); } private static void drawCircle(HumanEntity player, boolean randomRotation, boolean rainbow, double radius, double inc, int steps, double angularVelocityX, double angularVelocityY, double angularVelocityZ, double finalSpeed, int finalCount, Particle finalParticle, int finalLoops, Location finalLocation, boolean finalUpdateLoc, Vector finalUpdateVector, AtomicDouble hue, AtomicInteger red, AtomicInteger green, AtomicInteger blue, AtomicInteger step, boolean clientSide) { for (int j = 0; j < finalLoops; j++) { if (rainbow) { hue.set(ParticleUtils.incHue(hue.get())); int[] rgb = ParticleUtils.incRainbow(hue.get()); red.set(rgb[0]); green.set(rgb[1]); blue.set(rgb[2]); } Location loc = finalLocation; if (finalUpdateLoc) loc = player.getLocation().add(finalUpdateVector); for (int i = 0; i < steps; i++) { double angle = step.get() * inc; Vector v = new Vector(); v.setX(Math.cos(angle) * radius); v.setZ(Math.sin(angle) * radius); if (randomRotation) VectorUtils.rotateVector(v, angularVelocityX * step.get(), angularVelocityY * step.get(), angularVelocityZ * step.get()); Particle.DustOptions dustOptions = ParticleUtils.newDustOption(finalParticle, red.get(), green.get(), blue.get()); display(player, finalSpeed, finalCount, finalParticle, red, green, blue, clientSide, loc, v, dustOptions); step.getAndIncrement(); } } } private static void display(HumanEntity player, double finalSpeed, int finalCount, Particle finalParticle, AtomicInteger red, AtomicInteger green, AtomicInteger blue, boolean clientSide, Location loc, Vector v, DustOptions dustOptions) { if (clientSide) { if (player instanceof Player) ParticleUtils.display((Player) player, finalParticle, loc.clone().add(v), finalCount, red.get(), green.get(), blue.get(), finalSpeed, dustOptions); } else ParticleUtils.display(finalParticle, loc.clone().add(v), finalCount, red.get(), green.get(), blue.get(), finalSpeed, dustOptions); } }
rupendrab/py_unstr_parse
csvreader.py
<filename>csvreader.py<gh_stars>0 #!/usr/bin/env python3.5 import csv def read(f, cols): r = csv.reader(f) # r = csv.reader(f, delimiter='~') for row in r: print([row[col-1] for col in cols]) if __name__ == '__main__': import sys args = sys.argv[1:] if (len(args) >= 1): cols = [int(val) for val in args] f = sys.stdin read(f, cols)
fstgerm/framework.js-modules
src/modules/history.js
/** * history * @author <NAME> */ (function ($, undefined) { 'use strict'; var STORAGE_KEY = 'history'; var scope = $('#site'); var sels = { input: '.js-history-input' }; var urls = []; try { urls = JSON.parse(App.storage.local.get(STORAGE_KEY) || []); } catch (error) { App.log(error); } var update = function () { urls.push(window.location.href); scope.find(sels.input).each(function () { var t = $(this); var value = urls.join('\n'); if (t.attr('data-history-unique') === 'true') { value = _.uniq(urls).join('\n'); } t.val(value); }); App.storage.local.set(STORAGE_KEY, JSON.stringify(urls)); }; var onPageEnter = function (key, data) { update(); }; var onArticleEnter = function (key, data) { update(); }; var actions = function () { return { page: { enter: onPageEnter }, articleChanger: { enter: onArticleEnter } }; }; App.modules.exports('history', { actions: actions }); })(jQuery);
asantoz/trino
plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/PartitionWithStatistics.java
<filename>plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/PartitionWithStatistics.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. */ package io.trino.plugin.hive.metastore; import io.trino.plugin.hive.PartitionStatistics; import static com.google.common.base.Preconditions.checkArgument; import static io.trino.plugin.hive.util.HiveUtil.toPartitionValues; import static java.util.Objects.requireNonNull; public class PartitionWithStatistics { private final Partition partition; private final String partitionName; private final PartitionStatistics statistics; public PartitionWithStatistics(Partition partition, String partitionName, PartitionStatistics statistics) { this.partition = requireNonNull(partition, "partition is null"); this.partitionName = requireNonNull(partitionName, "partitionName is null"); checkArgument(toPartitionValues(partitionName).equals(partition.getValues()), "unexpected partition name: %s != %s", partitionName, partition.getValues()); this.statistics = requireNonNull(statistics, "statistics is null"); } public Partition getPartition() { return partition; } public String getPartitionName() { return partitionName; } public PartitionStatistics getStatistics() { return statistics; } }
elseboy/my-collection
java-utils/src/main/java/com/utils/tools/upload/pojo/SysFileDomain.java
package com.utils.tools.upload.pojo; import lombok.Data; import javax.persistence.Table; @Data @Table(name = "sys_file") public class SysFileDomain { private Long id; private String fileName; private String fileSuffix; private Long fileSize; private Integer fileType; private String filePath; private String fileUrl; private String thumbName; private String thumbPath; private String thumbUrl; private Long createTime; }
joeleg/laconia
packages/laconia-adapter/src/KinesisJsonInputConverter.js
<filename>packages/laconia-adapter/src/KinesisJsonInputConverter.js const { kinesis } = require("@laconia/event"); module.exports = class KinesisJsonInputConverter { convert(event) { return kinesis(event).records.map(r => r.jsonData); } };
NikolovV/C-Language
SoftUni/C Programming/C Conditional Statements-Homework/02-Bonus Score/main.c
/* Write a program that applies bonus score to given score in the range [1...9] by the following rules: * If the score is between 1 and 3, the program multiplies it by 10. * If the score is between 4 and 6, the program multiplies it by 100. * If the score is between 7 and 9, the program multiplies it by 1000. * If the score is 0 or more than 9, the program prints “invalid score”. */ #include <stdio.h> #include <stdlib.h> void checkInput(int *); int main() { int score; printf("Enter score: "); checkInput(&score); switch (score) { case 1: case 2: case 3: printf("result: %d", score*10); break; case 4: case 5: case 6: printf("result: %d", score*100); break; case 7: case 8: case 9: printf("result: %d", score*1000); break; default: printf("Invalid score!"); } return (EXIT_SUCCESS); } void checkInput(int *a) { if ((scanf("%d", a)) != 1) { fprintf(stderr, "Wrong input values!"); exit(EXIT_FAILURE); } }
tedi21/SisypheReview
Sisyphe/cppbase/src/debugTypeInfo.hpp
/* * debugTypeInfo.hpp * * * @date 14-07-2020 * @author <NAME> * @version 1.00 * cppBase generated by gensources. */ #ifndef _DEBUGTYPEINFO_HPP_ #define _DEBUGTYPEINFO_HPP_ #include <boost/shared_ptr.hpp> #include <boost/container/vector.hpp> #include "copy_ptr.h" #include "config.hpp" #include "convert.hpp" #include "encoding.hpp" #include "cppBaseExport.hpp" #define A(str) encode<EncodingT,ansi>(str) #define C(str) encode<ansi,EncodingT>(str) NAMESPACE_BEGIN(data_access) template <class EncodingT> class _DebugTypeInfoAccess; NAMESPACE_END NAMESPACE_BEGIN(entity) using namespace log4cpp; using namespace fctr; using namespace enc; using namespace boost; template <class EncodingT> class _DebugTypeInfo; template <class EncodingT> class _DebugFunctionInfo; template <class EncodingT> class _DebugVariableInfo; template <class EncodingT> class _DebugTypeInfo; /// debugTypeInfo table represents type information for debug. template <class EncodingT> class _DebugTypeInfo { private : boost::shared_ptr< _DebugTypeInfo<EncodingT> > m_primitiveType; long long m_identifier; long long m_isChar; long long m_isString; long long m_isBool; long long m_isFloat; long long m_isSigned; long long m_isWide; long long m_isPointer; long long m_isReference; long long m_isArray; long long m_isConst; long long m_isVolatile; long long m_isStruct; long long m_isClass; long long m_isUnion; long long m_isInterface; long long m_isEnum; long long m_isFunction; typename EncodingT::string_t m_baseName; typename EncodingT::string_t m_name; long long m_sizeOf; long long m_typeId; long long m_arrayDim; typedef std::vector< boost::shared_ptr< _DebugTypeInfo<EncodingT> > > vector_richType; vector_richType m_richTypes; typedef std::vector< boost::shared_ptr< _DebugFunctionInfo<EncodingT> > > vector_debugFunctionInfo; vector_debugFunctionInfo m_debugFunctionInfos; typedef std::vector< boost::shared_ptr< _DebugVariableInfo<EncodingT> > > vector_debugVariableInfo; vector_debugVariableInfo m_debugVariableInfos; Category* m_logger; protected : friend class data_access::_DebugTypeInfoAccess<EncodingT>; /** Creates a new element DebugTypeInfo. @param identifier @param isChar @param isString @param isBool @param isFloat @param isSigned @param isWide @param isPointer @param isReference @param isArray @param isConst @param isVolatile @param isStruct @param isClass @param isUnion @param isInterface @param isEnum @param isFunction @param baseName @param name @param sizeOf @param typeId @param arrayDim */ _DebugTypeInfo(long long identifier, long long isChar, long long isString, long long isBool, long long isFloat, long long isSigned, long long isWide, long long isPointer, long long isReference, long long isArray, long long isConst, long long isVolatile, long long isStruct, long long isClass, long long isUnion, long long isInterface, long long isEnum, long long isFunction, const typename EncodingT::string_t& baseName, const typename EncodingT::string_t& name, long long sizeOf, long long typeId, long long arrayDim) : m_identifier(identifier), m_isChar(isChar), m_isString(isString), m_isBool(isBool), m_isFloat(isFloat), m_isSigned(isSigned), m_isWide(isWide), m_isPointer(isPointer), m_isReference(isReference), m_isArray(isArray), m_isConst(isConst), m_isVolatile(isVolatile), m_isStruct(isStruct), m_isClass(isClass), m_isUnion(isUnion), m_isInterface(isInterface), m_isEnum(isEnum), m_isFunction(isFunction), m_baseName(baseName), m_name(name), m_sizeOf(sizeOf), m_typeId(typeId), m_arrayDim(arrayDim) { m_logger = &Category::getInstance(LOGNAME); m_logger->debugStream() << "constructor _DebugTypeInfo " << m_identifier << ' ' << m_isChar << ' ' << m_isString << ' ' << m_isBool << ' ' << m_isFloat << ' ' << m_isSigned << ' ' << m_isWide << ' ' << m_isPointer << ' ' << m_isReference << ' ' << m_isArray << ' ' << m_isConst << ' ' << m_isVolatile << ' ' << m_isStruct << ' ' << m_isClass << ' ' << m_isUnion << ' ' << m_isInterface << ' ' << m_isEnum << ' ' << m_isFunction << ' ' << A(m_baseName) << ' ' << A(m_name) << ' ' << m_sizeOf << ' ' << m_typeId << ' ' << m_arrayDim << ' '; } /** Sets a value of the element <i>identifier</i> in DebugTypeInfo. @param identifier */ void setIdentifier(long long identifier) { m_identifier = identifier; } public : /** Creates a new element DebugTypeInfo. */ _DebugTypeInfo() : m_identifier(-1), m_isChar(0), m_isString(0), m_isBool(0), m_isFloat(0), m_isSigned(0), m_isWide(0), m_isPointer(0), m_isReference(0), m_isArray(0), m_isConst(0), m_isVolatile(0), m_isStruct(0), m_isClass(0), m_isUnion(0), m_isInterface(0), m_isEnum(0), m_isFunction(0), m_baseName(EncodingT::EMPTY), m_name(EncodingT::EMPTY), m_sizeOf(0), m_typeId(0), m_arrayDim(0) { m_logger = &Category::getInstance(LOGNAME); m_logger->debugStream() << "constructor _DebugTypeInfo "; } /** Creates a new element DebugTypeInfo. @param isChar @param isString @param isBool @param isFloat @param isSigned @param isWide @param isPointer @param isReference @param isArray @param isConst @param isVolatile @param isStruct @param isClass @param isUnion @param isInterface @param isEnum @param isFunction @param baseName @param name @param sizeOf @param typeId @param arrayDim */ _DebugTypeInfo(long long isChar, long long isString, long long isBool, long long isFloat, long long isSigned, long long isWide, long long isPointer, long long isReference, long long isArray, long long isConst, long long isVolatile, long long isStruct, long long isClass, long long isUnion, long long isInterface, long long isEnum, long long isFunction, const typename EncodingT::string_t& baseName, const typename EncodingT::string_t& name, long long sizeOf, long long typeId, long long arrayDim) : m_identifier(-1), m_isChar(isChar), m_isString(isString), m_isBool(isBool), m_isFloat(isFloat), m_isSigned(isSigned), m_isWide(isWide), m_isPointer(isPointer), m_isReference(isReference), m_isArray(isArray), m_isConst(isConst), m_isVolatile(isVolatile), m_isStruct(isStruct), m_isClass(isClass), m_isUnion(isUnion), m_isInterface(isInterface), m_isEnum(isEnum), m_isFunction(isFunction), m_baseName(baseName), m_name(name), m_sizeOf(sizeOf), m_typeId(typeId), m_arrayDim(arrayDim) { m_logger = &Category::getInstance(LOGNAME); m_logger->debugStream() << "constructor _DebugTypeInfo " << m_identifier << ' ' << m_isChar << ' ' << m_isString << ' ' << m_isBool << ' ' << m_isFloat << ' ' << m_isSigned << ' ' << m_isWide << ' ' << m_isPointer << ' ' << m_isReference << ' ' << m_isArray << ' ' << m_isConst << ' ' << m_isVolatile << ' ' << m_isStruct << ' ' << m_isClass << ' ' << m_isUnion << ' ' << m_isInterface << ' ' << m_isEnum << ' ' << m_isFunction << ' ' << A(m_baseName) << ' ' << A(m_name) << ' ' << m_sizeOf << ' ' << m_typeId << ' ' << m_arrayDim << ' '; } /** Returns a const reference to the element <i>primitiveType</i> in DebugTypeInfo. @return */ boost::shared_ptr< _DebugTypeInfo<EncodingT> > getPrimitiveType() const { return m_primitiveType; } /** Sets a value of the element <i>primitiveType</i> in DebugTypeInfo. @param primitiveType */ void setPrimitiveType(boost::shared_ptr< _DebugTypeInfo<EncodingT> > primitiveType) { m_primitiveType = primitiveType; } /** Returns whether the element <i>primitiveType</i> in DebugTypeInfo is NULL. @return True if the element <i>primitiveType</i> is NULL, false otherwise. */ bool isNullPrimitiveType() const { return !m_primitiveType; } /** Removes from DebugTypeInfo an element <i>primitiveType</i>. */ void erasePrimitiveType() { m_primitiveType.reset(); } /** Returns a const reference to the element <i>identifier</i> in DebugTypeInfo. @return */ long long getIdentifier() const { return m_identifier; } /** Returns a const reference to the element <i>isChar</i> in DebugTypeInfo. @return */ long long getIsChar() const { return m_isChar; } /** Sets a value of the element <i>isChar</i> in DebugTypeInfo. @param isChar */ void setIsChar(long long isChar) { m_isChar = isChar; } /** Returns a const reference to the element <i>isString</i> in DebugTypeInfo. @return */ long long getIsString() const { return m_isString; } /** Sets a value of the element <i>isString</i> in DebugTypeInfo. @param isString */ void setIsString(long long isString) { m_isString = isString; } /** Returns a const reference to the element <i>isBool</i> in DebugTypeInfo. @return */ long long getIsBool() const { return m_isBool; } /** Sets a value of the element <i>isBool</i> in DebugTypeInfo. @param isBool */ void setIsBool(long long isBool) { m_isBool = isBool; } /** Returns a const reference to the element <i>isFloat</i> in DebugTypeInfo. @return */ long long getIsFloat() const { return m_isFloat; } /** Sets a value of the element <i>isFloat</i> in DebugTypeInfo. @param isFloat */ void setIsFloat(long long isFloat) { m_isFloat = isFloat; } /** Returns a const reference to the element <i>isSigned</i> in DebugTypeInfo. @return */ long long getIsSigned() const { return m_isSigned; } /** Sets a value of the element <i>isSigned</i> in DebugTypeInfo. @param isSigned */ void setIsSigned(long long isSigned) { m_isSigned = isSigned; } /** Returns a const reference to the element <i>isWide</i> in DebugTypeInfo. @return */ long long getIsWide() const { return m_isWide; } /** Sets a value of the element <i>isWide</i> in DebugTypeInfo. @param isWide */ void setIsWide(long long isWide) { m_isWide = isWide; } /** Returns a const reference to the element <i>isPointer</i> in DebugTypeInfo. @return */ long long getIsPointer() const { return m_isPointer; } /** Sets a value of the element <i>isPointer</i> in DebugTypeInfo. @param isPointer */ void setIsPointer(long long isPointer) { m_isPointer = isPointer; } /** Returns a const reference to the element <i>isReference</i> in DebugTypeInfo. @return */ long long getIsReference() const { return m_isReference; } /** Sets a value of the element <i>isReference</i> in DebugTypeInfo. @param isReference */ void setIsReference(long long isReference) { m_isReference = isReference; } /** Returns a const reference to the element <i>isArray</i> in DebugTypeInfo. @return */ long long getIsArray() const { return m_isArray; } /** Sets a value of the element <i>isArray</i> in DebugTypeInfo. @param isArray */ void setIsArray(long long isArray) { m_isArray = isArray; } /** Returns a const reference to the element <i>isConst</i> in DebugTypeInfo. @return */ long long getIsConst() const { return m_isConst; } /** Sets a value of the element <i>isConst</i> in DebugTypeInfo. @param isConst */ void setIsConst(long long isConst) { m_isConst = isConst; } /** Returns a const reference to the element <i>isVolatile</i> in DebugTypeInfo. @return */ long long getIsVolatile() const { return m_isVolatile; } /** Sets a value of the element <i>isVolatile</i> in DebugTypeInfo. @param isVolatile */ void setIsVolatile(long long isVolatile) { m_isVolatile = isVolatile; } /** Returns a const reference to the element <i>isStruct</i> in DebugTypeInfo. @return */ long long getIsStruct() const { return m_isStruct; } /** Sets a value of the element <i>isStruct</i> in DebugTypeInfo. @param isStruct */ void setIsStruct(long long isStruct) { m_isStruct = isStruct; } /** Returns a const reference to the element <i>isClass</i> in DebugTypeInfo. @return */ long long getIsClass() const { return m_isClass; } /** Sets a value of the element <i>isClass</i> in DebugTypeInfo. @param isClass */ void setIsClass(long long isClass) { m_isClass = isClass; } /** Returns a const reference to the element <i>isUnion</i> in DebugTypeInfo. @return */ long long getIsUnion() const { return m_isUnion; } /** Sets a value of the element <i>isUnion</i> in DebugTypeInfo. @param isUnion */ void setIsUnion(long long isUnion) { m_isUnion = isUnion; } /** Returns a const reference to the element <i>isInterface</i> in DebugTypeInfo. @return */ long long getIsInterface() const { return m_isInterface; } /** Sets a value of the element <i>isInterface</i> in DebugTypeInfo. @param isInterface */ void setIsInterface(long long isInterface) { m_isInterface = isInterface; } /** Returns a const reference to the element <i>isEnum</i> in DebugTypeInfo. @return */ long long getIsEnum() const { return m_isEnum; } /** Sets a value of the element <i>isEnum</i> in DebugTypeInfo. @param isEnum */ void setIsEnum(long long isEnum) { m_isEnum = isEnum; } /** Returns a const reference to the element <i>isFunction</i> in DebugTypeInfo. @return */ long long getIsFunction() const { return m_isFunction; } /** Sets a value of the element <i>isFunction</i> in DebugTypeInfo. @param isFunction */ void setIsFunction(long long isFunction) { m_isFunction = isFunction; } /** Returns a const reference to the element <i>baseName</i> in DebugTypeInfo. @return */ const typename EncodingT::string_t& getBaseName() const { return m_baseName; } /** Sets a value of the element <i>baseName</i> in DebugTypeInfo. @param baseName */ void setBaseName(const typename EncodingT::string_t& baseName) { m_baseName = baseName; } /** Returns a const reference to the element <i>name</i> in DebugTypeInfo. @return */ const typename EncodingT::string_t& getName() const { return m_name; } /** Sets a value of the element <i>name</i> in DebugTypeInfo. @param name */ void setName(const typename EncodingT::string_t& name) { m_name = name; } /** Returns a const reference to the element <i>sizeOf</i> in DebugTypeInfo. @return */ long long getSizeOf() const { return m_sizeOf; } /** Sets a value of the element <i>sizeOf</i> in DebugTypeInfo. @param sizeOf */ void setSizeOf(long long sizeOf) { m_sizeOf = sizeOf; } /** Returns a const reference to the element <i>typeId</i> in DebugTypeInfo. @return */ long long getTypeId() const { return m_typeId; } /** Sets a value of the element <i>typeId</i> in DebugTypeInfo. @param typeId */ void setTypeId(long long typeId) { m_typeId = typeId; } /** Returns a const reference to the element <i>arrayDim</i> in DebugTypeInfo. @return */ long long getArrayDim() const { return m_arrayDim; } /** Sets a value of the element <i>arrayDim</i> in DebugTypeInfo. @param arrayDim */ void setArrayDim(long long arrayDim) { m_arrayDim = arrayDim; } /// Random access iterator types for RichType vector. typedef typename vector_richType::iterator RichTypeIterator; typedef typename vector_richType::const_iterator RichTypeConstIterator; /// Random access iterator types for DebugFunctionInfo vector. typedef typename vector_debugFunctionInfo::iterator DebugFunctionInfoIterator; typedef typename vector_debugFunctionInfo::const_iterator DebugFunctionInfoConstIterator; /// Random access iterator types for DebugVariableInfo vector. typedef typename vector_debugVariableInfo::iterator DebugVariableInfoIterator; typedef typename vector_debugVariableInfo::const_iterator DebugVariableInfoConstIterator; /** Returns an iterator referring to the first element in the vector container RichType. @return An iterator to the beginning of the sequence. */ RichTypeIterator getRichTypesBeginning() { return m_richTypes.begin(); } /** Returns an iterator referring to the past-the-end element in the vector container RichType. @return An iterator to the element past the end of the sequence. */ RichTypeIterator getRichTypesEnd() { return m_richTypes.end(); } /** Returns a const iterator referring to the first element in the vector container RichType. @return A const iterator to the beginning of the sequence. */ RichTypeConstIterator getRichTypesBeginning() const { return m_richTypes.begin(); } /** Returns a const iterator referring to the past-the-end element in the vector container RichType. @return A const iterator to the element past the end of the sequence. */ RichTypeConstIterator getRichTypesEnd() const { return m_richTypes.end(); } /** Returns a reference to the element at position n in the vector RichType. @param n Position of an element in the vector. @return The element at the specified position in the vector. */ boost::shared_ptr< _DebugTypeInfo<EncodingT> >& getRichTypeAt(size_t n) { return m_richTypes.at(n); } /** Returns a const reference to the element at position n in the vector RichType. @param n Position of an element in the vector. @return The element at the specified position in the vector. */ boost::shared_ptr< _DebugTypeInfo<EncodingT> > getRichTypeAt(size_t n) const { return m_richTypes.at(n); } /** Returns the number of elements in the vector container RichType. @return The number of elements that conform the vector's content. */ size_t getRichTypesSize() const { return m_richTypes.size(); } /** Returns whether the vector container RichType is empty, i.e. whether its size is 0. @return True if the vector size is 0, false otherwise. */ bool isRichTypesEmpty() const { return m_richTypes.empty(); } /** Adds a new element at the end of the vector RichType, after its current last element. The content of this new element is initialized to a copy of x. @param o Value to be copied to the new element. */ void addRichType(boost::shared_ptr< _DebugTypeInfo<EncodingT> > o) { m_richTypes.push_back(copy_ptr(o)); } /** The vector RichType is extended by inserting new elements before the element at position pos. @param pos Position in the vector where the new elements are inserted. @param o Value to be used to initialize the inserted elements. @return An iterator that points to the newly inserted element. */ RichTypeIterator insertRichType(RichTypeIterator pos, boost::shared_ptr< _DebugTypeInfo<EncodingT> > o) { return m_richTypes.insert(pos, copy_ptr(o)); } /** The vector RichType is extended by inserting new elements before the element at position pos. @param pos Position in the vector where the new elements are inserted. @param first First iterator specifying a range of elements. @param last Last iterator specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position pos. */ void insertRichType(RichTypeIterator pos, RichTypeIterator first, RichTypeIterator last) { std::transform(first, last, std::inserter(m_richTypes, pos), static_cast< boost::shared_ptr< _DebugTypeInfo<EncodingT> >(*)(boost::shared_ptr< _DebugTypeInfo<EncodingT> >) >(copy_ptr)); } /** Removes from the vector container RichType a single element. @param pos Iterator pointing to a single element to be removed from the vector. */ RichTypeIterator eraseRichType(RichTypeIterator pos) { return m_richTypes.erase(pos); } /** Removes from the vector container RichType a range of elements ([first,last)). @param first First iterator specifying a range within the vector to be removed: [first,last). @param last Last iterator specifying a range within the vector to be removed: [first,last). */ RichTypeIterator eraseRichType(RichTypeIterator first, RichTypeIterator last) { return m_richTypes.erase(first, last); } /** All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container RichType, leaving the container with a size of 0. */ void clearRichTypes() { m_richTypes.clear(); } /** Returns an iterator referring to the first element in the vector container DebugFunctionInfo. @return An iterator to the beginning of the sequence. */ DebugFunctionInfoIterator getDebugFunctionInfosBeginning() { return m_debugFunctionInfos.begin(); } /** Returns an iterator referring to the past-the-end element in the vector container DebugFunctionInfo. @return An iterator to the element past the end of the sequence. */ DebugFunctionInfoIterator getDebugFunctionInfosEnd() { return m_debugFunctionInfos.end(); } /** Returns a const iterator referring to the first element in the vector container DebugFunctionInfo. @return A const iterator to the beginning of the sequence. */ DebugFunctionInfoConstIterator getDebugFunctionInfosBeginning() const { return m_debugFunctionInfos.begin(); } /** Returns a const iterator referring to the past-the-end element in the vector container DebugFunctionInfo. @return A const iterator to the element past the end of the sequence. */ DebugFunctionInfoConstIterator getDebugFunctionInfosEnd() const { return m_debugFunctionInfos.end(); } /** Returns a reference to the element at position n in the vector DebugFunctionInfo. @param n Position of an element in the vector. @return The element at the specified position in the vector. */ boost::shared_ptr< _DebugFunctionInfo<EncodingT> >& getDebugFunctionInfoAt(size_t n) { return m_debugFunctionInfos.at(n); } /** Returns a const reference to the element at position n in the vector DebugFunctionInfo. @param n Position of an element in the vector. @return The element at the specified position in the vector. */ boost::shared_ptr< _DebugFunctionInfo<EncodingT> > getDebugFunctionInfoAt(size_t n) const { return m_debugFunctionInfos.at(n); } /** Returns the number of elements in the vector container DebugFunctionInfo. @return The number of elements that conform the vector's content. */ size_t getDebugFunctionInfosSize() const { return m_debugFunctionInfos.size(); } /** Returns whether the vector container DebugFunctionInfo is empty, i.e. whether its size is 0. @return True if the vector size is 0, false otherwise. */ bool isDebugFunctionInfosEmpty() const { return m_debugFunctionInfos.empty(); } /** Adds a new element at the end of the vector DebugFunctionInfo, after its current last element. The content of this new element is initialized to a copy of x. @param o Value to be copied to the new element. */ void addDebugFunctionInfo(boost::shared_ptr< _DebugFunctionInfo<EncodingT> > o) { m_debugFunctionInfos.push_back(copy_ptr(o)); } /** The vector DebugFunctionInfo is extended by inserting new elements before the element at position pos. @param pos Position in the vector where the new elements are inserted. @param o Value to be used to initialize the inserted elements. @return An iterator that points to the newly inserted element. */ DebugFunctionInfoIterator insertDebugFunctionInfo(DebugFunctionInfoIterator pos, boost::shared_ptr< _DebugFunctionInfo<EncodingT> > o) { return m_debugFunctionInfos.insert(pos, copy_ptr(o)); } /** The vector DebugFunctionInfo is extended by inserting new elements before the element at position pos. @param pos Position in the vector where the new elements are inserted. @param first First iterator specifying a range of elements. @param last Last iterator specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position pos. */ void insertDebugFunctionInfo(DebugFunctionInfoIterator pos, DebugFunctionInfoIterator first, DebugFunctionInfoIterator last) { std::transform(first, last, std::inserter(m_debugFunctionInfos, pos), static_cast< boost::shared_ptr< _DebugFunctionInfo<EncodingT> >(*)(boost::shared_ptr< _DebugFunctionInfo<EncodingT> >) >(copy_ptr)); } /** Removes from the vector container DebugFunctionInfo a single element. @param pos Iterator pointing to a single element to be removed from the vector. */ DebugFunctionInfoIterator eraseDebugFunctionInfo(DebugFunctionInfoIterator pos) { return m_debugFunctionInfos.erase(pos); } /** Removes from the vector container DebugFunctionInfo a range of elements ([first,last)). @param first First iterator specifying a range within the vector to be removed: [first,last). @param last Last iterator specifying a range within the vector to be removed: [first,last). */ DebugFunctionInfoIterator eraseDebugFunctionInfo(DebugFunctionInfoIterator first, DebugFunctionInfoIterator last) { return m_debugFunctionInfos.erase(first, last); } /** All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container DebugFunctionInfo, leaving the container with a size of 0. */ void clearDebugFunctionInfos() { m_debugFunctionInfos.clear(); } /** Returns an iterator referring to the first element in the vector container DebugVariableInfo. @return An iterator to the beginning of the sequence. */ DebugVariableInfoIterator getDebugVariableInfosBeginning() { return m_debugVariableInfos.begin(); } /** Returns an iterator referring to the past-the-end element in the vector container DebugVariableInfo. @return An iterator to the element past the end of the sequence. */ DebugVariableInfoIterator getDebugVariableInfosEnd() { return m_debugVariableInfos.end(); } /** Returns a const iterator referring to the first element in the vector container DebugVariableInfo. @return A const iterator to the beginning of the sequence. */ DebugVariableInfoConstIterator getDebugVariableInfosBeginning() const { return m_debugVariableInfos.begin(); } /** Returns a const iterator referring to the past-the-end element in the vector container DebugVariableInfo. @return A const iterator to the element past the end of the sequence. */ DebugVariableInfoConstIterator getDebugVariableInfosEnd() const { return m_debugVariableInfos.end(); } /** Returns a reference to the element at position n in the vector DebugVariableInfo. @param n Position of an element in the vector. @return The element at the specified position in the vector. */ boost::shared_ptr< _DebugVariableInfo<EncodingT> >& getDebugVariableInfoAt(size_t n) { return m_debugVariableInfos.at(n); } /** Returns a const reference to the element at position n in the vector DebugVariableInfo. @param n Position of an element in the vector. @return The element at the specified position in the vector. */ boost::shared_ptr< _DebugVariableInfo<EncodingT> > getDebugVariableInfoAt(size_t n) const { return m_debugVariableInfos.at(n); } /** Returns the number of elements in the vector container DebugVariableInfo. @return The number of elements that conform the vector's content. */ size_t getDebugVariableInfosSize() const { return m_debugVariableInfos.size(); } /** Returns whether the vector container DebugVariableInfo is empty, i.e. whether its size is 0. @return True if the vector size is 0, false otherwise. */ bool isDebugVariableInfosEmpty() const { return m_debugVariableInfos.empty(); } /** Adds a new element at the end of the vector DebugVariableInfo, after its current last element. The content of this new element is initialized to a copy of x. @param o Value to be copied to the new element. */ void addDebugVariableInfo(boost::shared_ptr< _DebugVariableInfo<EncodingT> > o) { m_debugVariableInfos.push_back(copy_ptr(o)); } /** The vector DebugVariableInfo is extended by inserting new elements before the element at position pos. @param pos Position in the vector where the new elements are inserted. @param o Value to be used to initialize the inserted elements. @return An iterator that points to the newly inserted element. */ DebugVariableInfoIterator insertDebugVariableInfo(DebugVariableInfoIterator pos, boost::shared_ptr< _DebugVariableInfo<EncodingT> > o) { return m_debugVariableInfos.insert(pos, copy_ptr(o)); } /** The vector DebugVariableInfo is extended by inserting new elements before the element at position pos. @param pos Position in the vector where the new elements are inserted. @param first First iterator specifying a range of elements. @param last Last iterator specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position pos. */ void insertDebugVariableInfo(DebugVariableInfoIterator pos, DebugVariableInfoIterator first, DebugVariableInfoIterator last) { std::transform(first, last, std::inserter(m_debugVariableInfos, pos), static_cast< boost::shared_ptr< _DebugVariableInfo<EncodingT> >(*)(boost::shared_ptr< _DebugVariableInfo<EncodingT> >) >(copy_ptr)); } /** Removes from the vector container DebugVariableInfo a single element. @param pos Iterator pointing to a single element to be removed from the vector. */ DebugVariableInfoIterator eraseDebugVariableInfo(DebugVariableInfoIterator pos) { return m_debugVariableInfos.erase(pos); } /** Removes from the vector container DebugVariableInfo a range of elements ([first,last)). @param first First iterator specifying a range within the vector to be removed: [first,last). @param last Last iterator specifying a range within the vector to be removed: [first,last). */ DebugVariableInfoIterator eraseDebugVariableInfo(DebugVariableInfoIterator first, DebugVariableInfoIterator last) { return m_debugVariableInfos.erase(first, last); } /** All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container DebugVariableInfo, leaving the container with a size of 0. */ void clearDebugVariableInfos() { m_debugVariableInfos.clear(); } /** Prints DebugTypeInfo object on a C++ stream. @param o Reference of C++ stream object. @return The reference of C++ stream object. */ ostream& printConsole(ostream& o) const { return o << "DebugTypeInfo" << endl << "identifier : " << m_identifier << endl << "isChar : " << m_isChar << endl << "isString : " << m_isString << endl << "isBool : " << m_isBool << endl << "isFloat : " << m_isFloat << endl << "isSigned : " << m_isSigned << endl << "isWide : " << m_isWide << endl << "isPointer : " << m_isPointer << endl << "isReference : " << m_isReference << endl << "isArray : " << m_isArray << endl << "isConst : " << m_isConst << endl << "isVolatile : " << m_isVolatile << endl << "isStruct : " << m_isStruct << endl << "isClass : " << m_isClass << endl << "isUnion : " << m_isUnion << endl << "isInterface : " << m_isInterface << endl << "isEnum : " << m_isEnum << endl << "isFunction : " << m_isFunction << endl << "baseName : " << A(m_baseName) << endl << "name : " << A(m_name) << endl << "sizeOf : " << m_sizeOf << endl << "typeId : " << m_typeId << endl << "arrayDim : " << m_arrayDim; } /** Defines <i> operator<< </i> for DebugTypeInfo. @param o Reference of C++ stream object. @param elem Const reference of DebugTypeInfo object. @return The reference of C++ stream object. */ friend ostream& operator<<(ostream& o, const _DebugTypeInfo<EncodingT>& elem) { return elem.printConsole(o<<"[ ")<<" ]"; } class DebugTypeInfoIDEquality; class IsCharEquality; class IsCharInferior; class IsCharSuperior; class IsStringEquality; class IsStringInferior; class IsStringSuperior; class IsBoolEquality; class IsBoolInferior; class IsBoolSuperior; class IsFloatEquality; class IsFloatInferior; class IsFloatSuperior; class IsSignedEquality; class IsSignedInferior; class IsSignedSuperior; class IsWideEquality; class IsWideInferior; class IsWideSuperior; class IsPointerEquality; class IsPointerInferior; class IsPointerSuperior; class IsReferenceEquality; class IsReferenceInferior; class IsReferenceSuperior; class IsArrayEquality; class IsArrayInferior; class IsArraySuperior; class IsConstEquality; class IsConstInferior; class IsConstSuperior; class IsVolatileEquality; class IsVolatileInferior; class IsVolatileSuperior; class IsStructEquality; class IsStructInferior; class IsStructSuperior; class IsClassEquality; class IsClassInferior; class IsClassSuperior; class IsUnionEquality; class IsUnionInferior; class IsUnionSuperior; class IsInterfaceEquality; class IsInterfaceInferior; class IsInterfaceSuperior; class IsEnumEquality; class IsEnumInferior; class IsEnumSuperior; class IsFunctionEquality; class IsFunctionInferior; class IsFunctionSuperior; class BaseNameEquality; class BaseNameInferior; class BaseNameSuperior; class NameEquality; class NameInferior; class NameSuperior; class SizeOfEquality; class SizeOfInferior; class SizeOfSuperior; class TypeIdEquality; class TypeIdInferior; class TypeIdSuperior; class ArrayDimEquality; class ArrayDimInferior; class ArrayDimSuperior; }; typedef _DebugTypeInfo<ucs> UniDebugTypeInfo; typedef _DebugTypeInfo<ansi> DebugTypeInfo; NAMESPACE_END #undef C #undef A #include "debugTypeInfoPredicate.hpp" #endif
brentcroft/gtd
gui-driver-adapter-swt/src/main/java/com/brentcroft/gtd/camera/SwtCameraObjectService.java
<reponame>brentcroft/gtd package com.brentcroft.gtd.camera; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; import com.brentcroft.gtd.adapter.model.GuiObject; import com.brentcroft.gtd.camera.CameraObjectManager.FactorySpecification; import com.brentcroft.gtd.camera.model.SwtGuiObjectConsultant; import com.brentcroft.gtd.camera.model.SwtSnapshotGuiObject; import com.brentcroft.gtd.camera.model.swt.TableGuiObject; import com.brentcroft.gtd.camera.model.swt.TreeGuiObject; import com.brentcroft.gtd.camera.model.swt.WidgetGuiObject; /** * Created by Alaric on 15/07/2017. */ public class SwtCameraObjectService extends FxCameraObjectService { @Override protected < C, H extends GuiObject< C > > void addAdapters( List< FactorySpecification< C, H > > adapters, Properties properties ) { super.addAdapters( adapters, properties ); adapters.addAll( buildSWTAdapters( properties ) ); } @SuppressWarnings( "unchecked" ) private < C, H extends GuiObject< C > > List< FactorySpecification< C, H > > buildSWTAdapters( Properties properties ) { List< FactorySpecification< C, H > > adapters = new ArrayList<>(); CameraObjectManager gom = getManager(); adapters.add( ( FactorySpecification< C, H > ) gom.newFactorySpecification( Widget.class, WidgetGuiObject.class, new SwtGuiObjectConsultant< Widget >( properties ) ) ); adapters.add( ( FactorySpecification< C, H > ) gom.newFactorySpecification( Table.class, TableGuiObject.class ) ); adapters.add( ( FactorySpecification< C, H > ) gom.newFactorySpecification( Tree.class, TreeGuiObject.class ) ); adapters.add( ( FactorySpecification< C, H > ) gom.newFactorySpecification( SwtSnapshot.class, SwtSnapshotGuiObject.class ) ); return adapters; } }
frozenspider/maelstrom-downloader
src/test/scala/org/fs/mael/test/stub/StoringEventManager.scala
package org.fs.mael.test.stub import org.fs.mael.core.event.EventManager import org.fs.mael.core.event.EventSubscriber import org.fs.mael.core.event.PriorityEvent /** Event manager that accumulates events */ class StoringEventManager extends EventManager { var events: IndexedSeq[PriorityEvent] = IndexedSeq.empty override def subscribe(subscriber: EventSubscriber): Unit = { /* NOOP */ } override def unsubscribe(id: String): Unit = { /* NOOP */ } override def fire(event: PriorityEvent): Unit = { events = events :+ event } def reset(): Unit = events = IndexedSeq.empty }
Marlon992058/111_portal
src/com/rc/portal/dao/impl/TGoodsBrokerageDAOImpl.java
<filename>src/com/rc/portal/dao/impl/TGoodsBrokerageDAOImpl.java package com.rc.portal.dao.impl; import java.sql.SQLException; import java.util.List; import com.ibatis.sqlmap.client.SqlMapClient; import com.rc.app.framework.webapp.model.page.PageManager; import com.rc.app.framework.webapp.model.page.PageWraper; import com.rc.portal.dao.TGoodsBrokerageDAO; import com.rc.portal.vo.TGoodsBrokerage; import com.rc.portal.vo.TGoodsBrokerageExample; public class TGoodsBrokerageDAOImpl implements TGoodsBrokerageDAO { private SqlMapClient sqlMapClient; public void setSqlMapClient(SqlMapClient sqlMapClient) { this.sqlMapClient = sqlMapClient; } public SqlMapClient getSqlMapClient() { return sqlMapClient; } public TGoodsBrokerageDAOImpl() { super(); } public TGoodsBrokerageDAOImpl(SqlMapClient sqlMapClient) { super(); this.sqlMapClient = sqlMapClient; } public int countByExample(TGoodsBrokerageExample example) throws SQLException { Integer count = (Integer) sqlMapClient.queryForObject("t_goods_brokerage.ibatorgenerated_countByExample", example); return count.intValue(); } public int deleteByExample(TGoodsBrokerageExample example) throws SQLException { int rows = sqlMapClient.delete("t_goods_brokerage.ibatorgenerated_deleteByExample", example); return rows; } public int deleteByPrimaryKey(Long id) throws SQLException { TGoodsBrokerage key = new TGoodsBrokerage(); key.setId(id); int rows = sqlMapClient.delete("t_goods_brokerage.ibatorgenerated_deleteByPrimaryKey", key); return rows; } public Long insert(TGoodsBrokerage record) throws SQLException { return (Long) sqlMapClient.insert("t_goods_brokerage.ibatorgenerated_insert", record); } public Long insertSelective(TGoodsBrokerage record) throws SQLException { return (Long) sqlMapClient.insert("t_goods_brokerage.ibatorgenerated_insertSelective", record); } public List selectByExample(TGoodsBrokerageExample example) throws SQLException { List list = sqlMapClient.queryForList("t_goods_brokerage.ibatorgenerated_selectByExample", example); return list; } public TGoodsBrokerage selectByPrimaryKey(Long id) throws SQLException { TGoodsBrokerage key = new TGoodsBrokerage(); key.setId(id); TGoodsBrokerage record = (TGoodsBrokerage) sqlMapClient.queryForObject("t_goods_brokerage.ibatorgenerated_selectByPrimaryKey", key); return record; } public int updateByExampleSelective(TGoodsBrokerage record, TGoodsBrokerageExample example) throws SQLException { UpdateByExampleParms parms = new UpdateByExampleParms(record, example); int rows = sqlMapClient.update("t_goods_brokerage.ibatorgenerated_updateByExampleSelective", parms); return rows; } public int updateByExample(TGoodsBrokerage record, TGoodsBrokerageExample example) throws SQLException { UpdateByExampleParms parms = new UpdateByExampleParms(record, example); int rows = sqlMapClient.update("t_goods_brokerage.ibatorgenerated_updateByExample", parms); return rows; } public int updateByPrimaryKeySelective(TGoodsBrokerage record) throws SQLException { int rows = sqlMapClient.update("t_goods_brokerage.ibatorgenerated_updateByPrimaryKeySelective", record); return rows; } public int updateByPrimaryKey(TGoodsBrokerage record) throws SQLException { int rows = sqlMapClient.update("t_goods_brokerage.ibatorgenerated_updateByPrimaryKey", record); return rows; } private static class UpdateByExampleParms extends TGoodsBrokerageExample { private Object record; public UpdateByExampleParms(Object record, TGoodsBrokerageExample example) { super(example); this.record = record; } public Object getRecord() { return record; } } public PageWraper selectByRepositoryByPage(TGoodsBrokerageExample example) throws SQLException { PageWraper pw=null; int count=this.countByExample(example); List list = sqlMapClient.queryForList("t_goods_brokerage.selectByExampleByPage", example); System.out.println("��Դ��ҳ��ѯlist.size="+list.size()); pw=PageManager.getPageWraper(example.getPageInfo(), list, count); return pw; } //查询最高的返佣商品 public List select(int pageSize) throws SQLException { List list = sqlMapClient.queryForList("t_goods_brokerage.selectLeaderGoodsListDesc", null); return list; } }
arvimal/100DaysofCode-Python
Day-095/us_to_uk_dates.py
<reponame>arvimal/100DaysofCode-Python<gh_stars>1-10 #!/usr/bin/env python3 """ Convert dates from US format `MM-DD-YYYY` to UK format `DD-MM-YYYY`. """
MikeBull94/svg-stockpile
gradle-plugin/src/integTest/java/com/mikebull94/stockpile/gradle/StockpilePluginTest.java
<filename>gradle-plugin/src/integTest/java/com/mikebull94/stockpile/gradle/StockpilePluginTest.java package com.mikebull94.stockpile.gradle; import com.google.common.collect.ImmutableList; import com.mikebull94.stockpile.util.PathUtils; import org.gradle.testkit.runner.GradleRunner; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import static com.google.common.io.Files.copy; import static com.mikebull94.stockpile.gradle.GradleBuildFileBehaviour.arguments; import static com.mikebull94.stockpile.gradle.GradleBuildFileBehaviour.correctOutput; import static com.mikebull94.stockpile.gradle.GradleBuildFileBehaviour.gradleFile; import static com.mikebull94.stockpile.gradle.GradleBuildFileBehaviour.outputContains; import static com.mikebull94.stockpile.gradle.GradleBuildFileBehaviour.taskOutcome; import static com.mikebull94.stockpile.gradle.GradleBuildFileTester.test; import static org.gradle.testkit.runner.TaskOutcome.SUCCESS; public final class StockpilePluginTest { @Rule public final TemporaryFolder projectDir = new TemporaryFolder(); private File buildFile; @Before public void setUp() throws IOException { buildFile = projectDir.newFile("build.gradle"); Path inputDir = Paths.get("src/integTest/resources/svgs"); ImmutableList<Path> input = PathUtils.filterPathsIn(inputDir, PathUtils::hasSvgExtension); for (Path path : input) { Path fileName = path.getFileName(); if (fileName != null) { File file = projectDir.newFile(fileName.toString()); copy(path.toFile(), file); } } } @Test public void createNewTask() { test(projectDir, buildFile) .given(gradleFile("custom_task")) .given(arguments("customTask")) .given(GradleRunner::forwardOutput) .when(GradleRunner::build) .thenBuildResult("Expected start debug output.", outputContains("Starting SVG stockpile...")) .thenBuildResult("Expected outcome of :customTask to be " + SUCCESS, taskOutcome(":customTask", SUCCESS)) .thenBuildResult("Expected finish debug output", outputContains("Finished stockpiling SVGs.")) .thenTemporaryFolder("Actual SVG does not match expected", correctOutput("custom_task.svg")); } @Test public void modifyExistingTask() { test(projectDir, buildFile) .given(gradleFile("default_task")) .given(arguments("stockpile")) .when(GradleRunner::build) .thenBuildResult("Expected outcome of :stockpile to be " + SUCCESS, taskOutcome(":stockpile", SUCCESS)) .thenTemporaryFolder("Actual SVG does not match expected", correctOutput("default_task.svg")); } }
navikt/testnorge
apps/pdl-forvalter/src/main/java/no/nav/pdl/forvalter/config/ApplicationConfig.java
package no.nav.pdl.forvalter.config; import no.nav.testnav.libs.servletcore.config.ApplicationCoreConfig; import no.nav.testnav.libs.servletsecurity.config.SecureOAuth2ServerToServerConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({ApplicationCoreConfig.class, SecureOAuth2ServerToServerConfiguration.class}) public class ApplicationConfig { }
Cory-jbpm/jbpm
jbpm-case-mgmt/jbpm-case-mgmt-impl/src/main/java/org/jbpm/casemgmt/impl/audit/CaseInstanceAuditEventListener.java
<reponame>Cory-jbpm/jbpm /* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.casemgmt.impl.audit; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jbpm.casemgmt.api.auth.AuthorizationManager; import org.jbpm.casemgmt.api.event.CaseDataEvent; import org.jbpm.casemgmt.api.event.CaseEventListener; import org.jbpm.casemgmt.api.event.CaseReopenEvent; import org.jbpm.casemgmt.api.event.CaseRoleAssignmentEvent; import org.jbpm.casemgmt.api.event.CaseStartEvent; import org.jbpm.casemgmt.api.model.instance.CaseFileInstance; import org.jbpm.casemgmt.api.model.instance.CaseRoleInstance; import org.jbpm.casemgmt.impl.model.instance.CaseFileInstanceImpl; import org.jbpm.shared.services.impl.TransactionalCommandService; import org.jbpm.shared.services.impl.commands.MergeObjectCommand; import org.jbpm.shared.services.impl.commands.PersistObjectCommand; import org.jbpm.shared.services.impl.commands.QueryStringCommand; import org.jbpm.shared.services.impl.commands.UpdateStringCommand; import org.kie.internal.runtime.Cacheable; import org.kie.internal.task.api.TaskModelProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CaseInstanceAuditEventListener implements CaseEventListener, Cacheable { private static final Logger logger = LoggerFactory.getLogger(CaseInstanceAuditEventListener.class); private static final String UPDATE_CASE_PROCESS_INST_ID_QUERY = "update CaseRoleAssignmentLog set processInstanceId =:piID where caseId =:caseId"; private static final String DELETE_CASE_ROLE_ASSIGNMENT_QUERY = "delete from CaseRoleAssignmentLog where caseId =:caseId and roleName =:role and entityId =:entity"; private static final String FIND_CASE_PROCESS_INST_ID_QUERY = "select processInstanceId from ProcessInstanceLog where correlationKey =:caseId"; private static final String FIND_CASE_DATA_QUERY = "select itemName from CaseFileDataLog where caseId =:caseId"; private static final String FIND_CASE_DATA_BY_NAME_QUERY = "select cfdl from CaseFileDataLog cfdl where cfdl.caseId =:caseId and cfdl.itemName =:itemName"; private static final String DELETE_CASE_DATA_BY_NAME_QUERY = "delete from CaseFileDataLog where caseId =:caseId and itemName in (:itemNames)"; private TransactionalCommandService commandService; public CaseInstanceAuditEventListener(TransactionalCommandService commandService) { this.commandService = commandService; } @Override public void afterCaseStarted(CaseStartEvent event) { CaseFileInstance caseFile = event.getCaseFile(); if (caseFile == null) { return; } Collection<CaseRoleInstance> caseRoleAssignments = ((CaseFileInstanceImpl)caseFile).getAssignments(); if (caseRoleAssignments != null && !caseRoleAssignments.isEmpty()) { for (CaseRoleInstance roleAssignment : caseRoleAssignments) { logger.debug("Role {} has following assignments {}", roleAssignment.getRoleName(), roleAssignment.getRoleAssignments()); if (roleAssignment.getRoleAssignments() != null && !roleAssignment.getRoleAssignments().isEmpty()) { List<CaseRoleAssignmentLog> objects = new ArrayList<>(); roleAssignment.getRoleAssignments().forEach(entity -> { CaseRoleAssignmentLog assignmentLog = new CaseRoleAssignmentLog(event.getProcessInstanceId(), event.getCaseId(), roleAssignment.getRoleName(), entity); objects.add(assignmentLog); }); commandService.execute(new PersistObjectCommand(objects.toArray())); } } } else { // add public role so it can be found by queries that take assignments into consideration CaseRoleAssignmentLog assignmentLog = new CaseRoleAssignmentLog(event.getProcessInstanceId(), event.getCaseId(), "*", TaskModelProvider.getFactory().newGroup(AuthorizationManager.PUBLIC_GROUP)); commandService.execute(new PersistObjectCommand(assignmentLog)); } Map<String, Object> initialData = caseFile.getData(); if (initialData.isEmpty()) { return; } List<CaseFileDataLog> insert = new ArrayList<>(); initialData.forEach((name, value) -> { if (value != null) { CaseFileDataLog caseFileDataLog = new CaseFileDataLog(event.getCaseId(), caseFile.getDefinitionId(), name); insert.add(caseFileDataLog); caseFileDataLog.setItemType(value.getClass().getName()); caseFileDataLog.setItemValue(value.toString()); caseFileDataLog.setLastModified(new Date()); caseFileDataLog.setLastModifiedBy(event.getUser()); } }); commandService.execute(new PersistObjectCommand(insert.toArray())); } @Override public void afterCaseReopen(CaseReopenEvent event) { logger.debug("Updating process instance id ({})in case assignment log for case id {}", event.getProcessInstanceId(), event.getCaseId()); Map<String, Object> parameters = new HashMap<>(); parameters.put("piID", event.getProcessInstanceId()); parameters.put("caseId", event.getCaseId()); UpdateStringCommand updateCommand = new UpdateStringCommand(UPDATE_CASE_PROCESS_INST_ID_QUERY, parameters); int updated = commandService.execute(updateCommand); logger.debug("Updated {} role assignment entries for case id {}", updated, event.getCaseId()); updateCaseFileItems(event.getData(), event.getCaseId(), event.getCaseDefinitionId(), event.getUser()); } @Override public void afterCaseRoleAssignmentAdded(CaseRoleAssignmentEvent event) { Map<String, Object> parameters = new HashMap<>(); parameters.put("caseId", event.getCaseId()); QueryStringCommand<List<Long>> queryCommand = new QueryStringCommand<List<Long>>(FIND_CASE_PROCESS_INST_ID_QUERY, parameters); List<Long> processInstanceId = commandService.execute(queryCommand); if (processInstanceId.isEmpty()) { return; } CaseRoleAssignmentLog assignmentLog = new CaseRoleAssignmentLog(processInstanceId.get(0), event.getCaseId(), event.getRole(), event.getEntity()); commandService.execute(new PersistObjectCommand(assignmentLog)); } @Override public void afterCaseRoleAssignmentRemoved(CaseRoleAssignmentEvent event) { Map<String, Object> parameters = new HashMap<>(); parameters.put("caseId", event.getCaseId()); parameters.put("role", event.getRole()); parameters.put("entity", event.getEntity().getId()); UpdateStringCommand updateCommand = new UpdateStringCommand(DELETE_CASE_ROLE_ASSIGNMENT_QUERY, parameters); commandService.execute(updateCommand); logger.debug("Removed {} role assignment for entity {} for case id {}", event.getRole(), event.getEntity(), event.getCaseId()); } @Override public void afterCaseDataAdded(CaseDataEvent event) { updateCaseFileItems(event.getData(), event.getCaseId(), event.getDefinitionId(), event.getUser()); } @Override public void afterCaseDataRemoved(CaseDataEvent event) { Map<String, Object> parameters = new HashMap<>(); parameters.put("caseId", event.getCaseId()); parameters.put("itemNames", new ArrayList<>(event.getData().keySet())); UpdateStringCommand updateCommand = new UpdateStringCommand(DELETE_CASE_DATA_BY_NAME_QUERY, parameters); commandService.execute(updateCommand); } @Override public void close() { // no-op } /* * Helper methods */ protected List<String> currentCaseData(String caseId) { Map<String, Object> parameters = new HashMap<>(); parameters.put("caseId", caseId); QueryStringCommand<List<String>> queryCommand = new QueryStringCommand<List<String>>(FIND_CASE_DATA_QUERY, parameters); List<String> caseDataLog = commandService.execute(queryCommand); return caseDataLog; } protected CaseFileDataLog caseFileDataByName(String caseId, String name) { Map<String, Object> parameters = new HashMap<>(); parameters.put("caseId", caseId); parameters.put("itemName", name); QueryStringCommand<List<CaseFileDataLog>> queryCommand = new QueryStringCommand<List<CaseFileDataLog>>(FIND_CASE_DATA_BY_NAME_QUERY, parameters); List<CaseFileDataLog> caseDataLog = commandService.execute(queryCommand); return caseDataLog.get(0); } protected void updateCaseFileItems(Map<String, Object> addedData, String caseId, String caseDefinitionId, String user) { if (addedData.isEmpty()) { return; } List<CaseFileDataLog> insert = new ArrayList<>(); List<CaseFileDataLog> update = new ArrayList<>(); List<String> currentCaseData = currentCaseData(caseId); addedData.forEach((name, value) -> { if (value != null) { CaseFileDataLog caseFileDataLog = null; if (currentCaseData.contains(name)) { logger.debug("Case instance {} has already stored log value for {} thus it's going to be updated", caseId, name); caseFileDataLog = caseFileDataByName(caseId, name); update.add(caseFileDataLog); } else { logger.debug("Case instance {} has no log value for {} thus it's going to be inserted", caseId, name); caseFileDataLog = new CaseFileDataLog(caseId, caseDefinitionId, name); insert.add(caseFileDataLog); } caseFileDataLog.setItemType(value.getClass().getName()); caseFileDataLog.setItemValue(value.toString()); caseFileDataLog.setLastModified(new Date()); caseFileDataLog.setLastModifiedBy(user); } }); commandService.execute(new PersistObjectCommand(insert.toArray())); commandService.execute(new MergeObjectCommand(update.toArray())); } }
cosmo-jana/numerics-physics-stuff
double_pendulum.py
<reponame>cosmo-jana/numerics-physics-stuff # coding: utf-8 import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint def rhs(y, t, m1, m2, l1, l2): g = 9.81 theta1, theta2, dtheta1, dtheta2 = tuple(y) beta = np.cos(theta1 - theta2) M = m1 + m2 alpha = -(l1*l2*m2*dtheta2**2*np.sin(theta1 - theta2) + g*M*l1*np.sin(theta1)) alpha_tick = -(m2*theta1**2*l1 + l2*np.sin(theta2 - theta1) + g*m2*l2*np.sin(theta2)) gamma = m1*M*l1**2*l2**2 - m1*m2*l1**2*l2**2*beta**2 theta1_accel = (m1*l2**2*alpha - m1*l1*l2*beta*alpha_tick)/gamma theta2_accel = (M*l1**2*alpha_tick - m2*l1*l2*beta*alpha)/gamma return np.array([dtheta1, dtheta2, theta1_accel, theta2_accel]) y0 = np.array([np.pi/4, np.pi/8, 0, 0]) t = np.linspace(0, 20, 1000) # s m1 = 2.0 # kg m2 = 1.0 # kg l1 = 1.0 # m l2 = 0.5 # m args = (m1, m2, l1, l2) ys = odeint(rhs, y0, t, args=args) theta1, theta2, theta1_dot, theta2_dot = ys[:,0], ys[:,1], ys[:,2], ys[:,3] plt.plot(t, theta1, label=r"$\theta_1$") plt.plot(t, theta2, label=r"$\theta_2$") plt.title(r"Double pendulum with $m_1 = 2\mathrm{kg}$, $m_2 = 1\mathrm{kg}$, $l_1 = 1\mathrm{m}$, $l_2 = 0.5\mathrm{m}$") plt.xlabel("Time [sec]") plt.ylabel("Angle [Rad]") plt.grid() plt.legend() plt.show()
amahussein/vespa
searchcore/src/vespa/searchcore/proton/documentmetastore/document_meta_store_versions.h
<filename>searchcore/src/vespa/searchcore/proton/documentmetastore/document_meta_store_versions.h // Copyright 2017 <NAME>. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once namespace proton::documentmetastore { constexpr uint32_t NO_DOCUMENT_SIZE_TRACKING_VERSION = 0u; constexpr uint32_t DOCUMENT_SIZE_TRACKING_VERSION = 1u; }
DatabasKarlsson/MaxScale
system-test/auth_sqlmode_ansi.cpp
/** * @file bug705.cpp regression case for bug 705 ("Authentication fails when the user connects to a database * when the SQL mode includes ANSI_QUOTES") * * - use only one backend * - derectly to backend SET GLOBAL sql_mode="ANSI" * - restart MaxScale * - check log for "Error : Loading database names for service RW_Split encountered error: Unknown column" */ /* * <EMAIL> 2015-01-26 14:01:11 UTC * When the sql_mode includes ANSI_QUOTES, maxscale fails to execute the SQL at LOAD_MYSQL_DATABASE_NAMES * string * * https://github.com/mariadb-corporation/MaxScale/blob/master/server/core/dbusers.c * line 90: #define LOAD_MYSQL_DATABASE_NAMES "SELECT * FROM ( (SELECT COUNT(1) AS ndbs FROM INFORMATION_SCHEMA.SCHEMATA) * AS tbl1, (SELECT GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES WHERE privilege_type='SHOW * DATABASES' AND REPLACE(GRANTEE, \"\'\",\"\")=CURRENT_USER()) AS tbl2)" * * the error log outputs that string: * "Error : Loading database names for service galera_bs_router encountered error: Unknown column ''' in * 'where clause'" * * I think the quotes in LOAD_MYSQL_DATABASE_NAMES and all the SQL used by MaxScale should be adjusted * according to the recent sql_mode at the backend server. * * How to repeat: * mysql root@centos-7-minimal:[Mon Jan 26 15:00:48 2015][(none)]> SET SESSION sql_mode = "ORACLE"; select * @@sql_mode; * Query OK, 0 rows affected (0.00 sec) * +----------------------------------------------------------------------------------------------------------------------+ | @@sql_mode | | +----------------------------------------------------------------------------------------------------------------------+ | PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER || +----------------------------------------------------------------------------------------------------------------------+ | 1 row in set (0.00 sec) | | mysql root@centos-7-minimal:[Mon Jan 26 15:00:55 2015][(none)]> SELECT |@@innodb_version,@@version,@@version_comment, GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES |WHERE privilege_type='SHOW DATABASES' AND REPLACE(GRANTEE, "\'","")=CURRENT_USER(); | ERROR 1054 (42S22): Unknown column '\'' in 'where clause' | mysql root@centos-7-minimal:[Mon Jan 26 15:00:57 2015][(none)]> | Comment 1 <EMAIL> 2015-01-26 14:02:42 UTC | Work around: set the sql_mode without ANSI_QUOTES: | | mysql root@centos-7-minimal:[Mon Jan 26 15:00:57 2015][(none)]> SET SESSION sql_mode = "MYSQL323"; select |@@sql_mode; | Query OK, 0 rows affected (0.00 sec) | +------------------------------+ | @@sql_mode | +------------------------------+ | MYSQL323,HIGH_NOT_PRECEDENCE | +------------------------------+ | 1 row in set (0.00 sec) | | mysql root@centos-7-minimal:[Mon Jan 26 15:01:52 2015][(none)]> SELECT |@@innodb_version,@@version,@@version_comment, GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES |WHERE privilege_type='SHOW DATABASES' AND REPLACE(GRANTEE, "\'","")=CURRENT_USER(); +------------------+-----------------------+-----------------------------------+--------------------+----------------+ | @@innodb_version | @@version | @@version_comment | GRANTEE | |PRIVILEGE_TYPE | +------------------+-----------------------+-----------------------------------+--------------------+----------------+ | 5.6.21-70.0 | 10.0.15-MariaDB-wsrep | MariaDB Server, wsrep_25.10.r4144 | 'root'@'localhost' | SHOW |DATABASES | +------------------+-----------------------+-----------------------------------+--------------------+----------------+ | 1 row in set (0.00 sec) | Comment 2 Massimiliano 2015-01-26 14:19:45 UTC | More informations needed for "the recent sql_mode at the backend server" | | Is that an issue with a particular mysql/mariadb backend version? | Comment 3 <EMAIL> 2015-01-26 14:30:08 UTC | No, it is not related to any particular version. | | I tested on Percona, MySQL , MariaDB 5.5, MariaDB 10.0.15 with the same result: | | [Mon Jan 26 16:24:34 2015][mysql]> SET SESSION sql_mode = ""; SELECT @@sql_mode; | Query OK, 0 rows affected (0.00 sec) | +------------+ | @@sql_mode | +------------+ | | +------------+ | 1 row in set (0.00 sec) | [Mon Jan 26 16:24:53 2015][mysql]> SELECT @@innodb_version,@@version,@@version_comment, |GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES WHERE privilege_type='SHOW DATABASES' AND |REPLACE(GRANTEE, "\'","")=CURRENT_USER(); +------------------+-----------------+--------------------------------------------------+--------------------+----------------+ | @@innodb_version | @@version | @@version_comment | GRANTEE | | PRIVILEGE_TYPE | +------------------+-----------------+--------------------------------------------------+--------------------+----------------+ | 5.5.41-37.0 | 5.5.41-37.0-log | Percona Server (GPL), Release 37.0, Revision 727 | 'seik'@'localhost' || SHOW DATABASES | +------------------+-----------------+--------------------------------------------------+--------------------+----------------+ | 1 row in set (0.00 sec) | | [Mon Jan 26 16:24:57 2015][mysql]> SET SESSION sql_mode = "DB2";SELECT @@sql_mode; | Query OK, 0 rows affected (0.00 sec) | +-----------------------------------------------------------------------------------------------+ | @@sql_mode | +-----------------------------------------------------------------------------------------------+ | PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,DB2,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS | +-----------------------------------------------------------------------------------------------+ | 1 row in set (0.00 sec) | | :[Mon Jan 26 16:26:19 2015][mysql]> SELECT @@innodb_version,@@version,@@version_comment, |GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES WHERE privilege_type='SHOW DATABASES' AND |REPLACE(GRANTEE, "\'","")=CURRENT_USER(); | ERROR 1054 (42S22): Unknown column '\'' in 'where clause' | | mysql root@centos-7-minimal:[Mon Jan 26 14:27:33 2015][(none)]> SET SESSION sql_mode = "POSTGRESQL"; |select @@sql_mode; | | | | | | Query |OK, 0 rows affected (0.00 sec) | +------------------------------------------------------------------------------------------------------+ | @@sql_mode | +------------------------------------------------------------------------------------------------------+ | PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,POSTGRESQL,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS | +------------------------------------------------------------------------------------------------------+ | 1 row in set (0.01 sec) | | mysql root@centos-7-minimal:[Mon Jan 26 14:42:23 2015][(none)]> SELECT |@@innodb_version,@@version,@@version_comment, GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES |WHERE privilege_type='SHOW DATABASES' AND REPLACE(GRANTEE, "\'","")=CURRENT_USER(); | ERROR 1054 (42S22): Unknown column '\'' in 'where clause' | mysql root@centos-7-minimal:[Mon Jan 26 14:58:57 2015][(none)]> SET SESSION sql_mode = ""; select |@@sql_mode; | Query OK, 0 rows affected (0.00 sec) | +------------+ | @@sql_mode | +------------+ | | +------------+ | 1 row in set (0.00 sec) | | mysql root@centos-7-minimal:[Mon Jan 26 14:59:03 2015][(none)]> SELECT |@@innodb_version,@@version,@@version_comment, GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES |WHERE privilege_type='SHOW DATABASES' AND REPLACE(GRANTEE, "\'","")=CURRENT_USER(); +------------------+-----------+------------------------------+--------------------+----------------+ | @@innodb_version | @@version | @@version_comment | GRANTEE | PRIVILEGE_TYPE | +------------------+-----------+------------------------------+--------------------+----------------+ | 5.6.22 | 5.6.22 | MySQL Community Server (GPL) | 'root'@'localhost' | SHOW DATABASES | +------------------+-----------+------------------------------+--------------------+----------------+ | 1 row in set (0.00 sec) | | mysql <EMAIL>:[Mon Jan 26 15:28:12 2015][(none)]> SET SESSION sql_mode = "DB2"; SELECT |@@sql_mode; | Query OK, 0 rows affected (0.00 sec) | +-----------------------------------------------------------------------------------------------+ | @@sql_mode | +-----------------------------------------------------------------------------------------------+ | PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,DB2,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS | +-----------------------------------------------------------------------------------------------+ | 1 row in set (0.00 sec) | | mysql <EMAIL>:[Mon Jan 26 15:28:19 2015][(none)]> SELECT |@@innodb_version,@@version,@@version_comment, GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES |WHERE privilege_type='SHOW DATABASES' AND REPLACE(GRANTEE, "\'","")=CURRENT_USER(); | ERROR 1054 (42S22): Unknown column '\'' in 'where clause' | mysql <EMAIL>:[Mon Jan 26 15:28:32 2015][(none)]> SET SESSION sql_mode = "MYSQL40"; | SELECT @@sql_mode; | Query OK, 0 rows affected (0.00 sec) | +-----------------------------+ | @@sql_mode | +-----------------------------+ | MYSQL40,HIGH_NOT_PRECEDENCE | +-----------------------------+ | 1 row in set (0.00 sec) | | mysql <EMAIL>:[Mon Jan 26 15:29:09 2015][(none)]> SELECT |@@innodb_version,@@version,@@version_comment, GRANTEE,PRIVILEGE_TYPE from INFORMATION_SCHEMA.USER_PRIVILEGES |WHERE privilege_type='SHOW DATABASES' AND REPLACE(GRANTEE, "\'","")=CURRENT_USER(); +---------------------+--------------------+-------------------+--------------------+----------------+ | @@innodb_version | @@version | @@version_comment | GRANTEE | PRIVILEGE_TYPE | +---------------------+--------------------+-------------------+--------------------+----------------+ | 5.5.38-MariaDB-35.2 | 5.5.39-MariaDB-log | MariaDB Server | 'root'@'localhost' | SHOW DATABASES | +---------------------+--------------------+-------------------+--------------------+----------------+ | 1 row in set (0.00 sec) | Comment 4 Massimiliano 2015-01-26 14:48:04 UTC | It's still not clear if the issue is related to MaxScale or it's spotted only when yoy send the statements |via mysql client | Comment 5 <EMAIL> 2015-01-26 16:37:32 UTC | There is at least one case that after setting the sql_mode to string : | |"REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ONLY_FULL_GROUP_BY,ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" |at 10.0.15-MariaDB-wsrep-log , using maxscale in this way returned an error. | | $ mysql --host max-scale-host --user=test --password=xxx --port 4449 mysqlslap | ERROR 1045 (28000): Access denied for user 'test'@'IP (using password: <PASSWORD>) to database 'mysqlslap' | | error at the maxscale log: | Error : Loading database names for service galera_bs_router encountered error: Unknown column ''' in |'where clause'. | | the following test was OK: | $ mysql --host max-scale-host --user=test --password=<PASSWORD> --port 4449 | | After switch sql_mode to '' as "mysql> set global sql_mode='';", | the connection of the user to a database seems to work OK: | $ mysql --host max-scale-host --user=test --password=<PASSWORD> -D mysqlslap | Reading table information for completion of table and column names | You can turn off this feature to get a quicker startup with -A | | Welcome to the MySQL monitor. Commands end with ; or \g. | Your MySQL connection id is 2532 | Server version: 5.5.41-MariaDB MariaDB Server, wsrep_25.10.r4144 | | Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. | | Oracle is a registered trademark of Oracle Corporation and/or its | affiliates. Other names may be trademarks of their respective | owners. | | Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. | | mysql> Bye | | | If needed , I will prepare other test case ? | Comment 6 Massimiliano 2015-01-26 16:40:45 UTC | Yes, please provide us other test cases and we will try to reproduce it | Comment 7 <NAME> 2015-01-26 18:23:25 UTC | Changed the double quotation marks to single quotation marks because the MySQL client manual says that |ANSI_QUOTES still accepts single quotes. | | This can be verified by first setting sql_mode to ANSI: | | set global sql_mode="ANSI"; | | after that, start MaxScale and the error log contains: | | MariaDB Corporation MaxScale /home/markus/build/log/skygw_err1.log Mon Jan 26 20:16:17 2015 | ----------------------------------------------------------------------- | --- Logging is enabled. | 2015-01-26 20:16:17 Error : Loading database names for service RW Split Router encountered error: |Unknown column ''' in 'where clause'. | 2015-01-26 20:16:17 Error : Loading database names for service RW Split Hint Router encountered error: |Unknown column ''' in 'where clause'. | 2015-01-26 20:16:17 Error : Loading database names for service Read Connection Router encountered error: |Unknown column ''' in 'where clause'. | | After the change the error is gone. | Comment 8 Massimiliano 2015-01-26 21:16:03 UTC | I managed to reproduce it in my environment: | | - created a setup with 1 server in a service named "RW_Split" | | - issued SET GLOBAL sql_mode="ANSI" via mysql client to that server | | - started MaxScale and found an error in the log: | | | 2015-01-26 16:10:52 Error : Loading database names for service RW_Split encountered error: Unknown |column ''' in 'where clause'. | */ #include <iostream> #include <maxtest/testconnections.hh> int main(int argc, char* argv[]) { TestConnections* Test = new TestConnections(argc, argv); Test->set_timeout(20); auto node_ip = Test->repl->ip4(0); printf("Connecting to backend %s\n", node_ip); fflush(stdout); Test->repl->connect(); Test->tprintf("Sending SET GLOBAL sql_mode=\"ANSI\" to backend %s\n", node_ip); execute_query(Test->repl->nodes[0], "SET GLOBAL sql_mode=\"ANSI\""); Test->repl->close_connections(); Test->tprintf("Restarting MaxScale\n"); Test->set_timeout(120); Test->maxscales->restart_maxscale(0); Test->log_excludes(0, "Loading database names"); Test->log_excludes(0, "Unknown column"); int rval = Test->global_result; delete Test; return rval; // } }
twitchyliquid64/kcdb
src/github.com/nsf/sexp/node_test.go
package sexp import ( "errors" "reflect" "regexp" "strings" "testing" ) func must_contain(t *testing.T, err, what string) { re := regexp.MustCompile(what) if !re.MatchString(err) { t.Errorf(`expected: "%s", got: "%s"`, what, err) } else { t.Logf(`ok: %s`, err) } } func error_must_contain(t *testing.T, err error, what string) { if err == nil { t.Errorf("non-nil error expected") return } must_contain(t, err.Error(), what) } func test_unmarshal_generic(t *testing.T, data string, f func(*Node, ...interface{}) error, v ...interface{}) { root, err := Parse(strings.NewReader(data), nil) if err != nil { t.Error(err) return } err = f(root, v...) if err != nil { t.Error(err) } } func test_unmarshal(t *testing.T, data string, v ...interface{}) { test_unmarshal_generic(t, data, (*Node).Unmarshal, v...) } func test_unmarshal_children(t *testing.T, data string, v ...interface{}) { test_unmarshal_generic(t, data, (*Node).UnmarshalChildren, v...) } const countries = ` ;; a list of arbitrary countries (countries ( Spain Russia ; I live here :-D Japan China England Germany France Sweden Iraq Iran Indonesia India USA Canada Brazil )) ` // just to test Unmarshaler interface type smiley string func (s *smiley) UnmarshalSexp(n *Node) error { if !n.IsScalar() { return NewUnmarshalError(n, reflect.TypeOf(s), "scalar value required") } *s = smiley(n.Value + " :-D") return nil } // always fails type neversmiley string func (s *neversmiley) UnmarshalSexp(n *Node) error { return NewUnmarshalError(n, reflect.TypeOf(s), ":-( Y U NO HAPPY?") } type neversmiley2 string func (s *neversmiley2) UnmarshalSexp(n *Node) error { return errors.New("inevitable failure") } func TestUnmarshal(t *testing.T) { var a [3]int8 test_unmarshal(t, "5 10 -15", &a) t.Logf("%d %d %d", a[0], a[1], a[2]) var b [3]uint16 test_unmarshal(t, "1024 750 300", &b) t.Logf("%d %d %d", b[0], b[1], b[2]) var m map[string][]string test_unmarshal(t, countries, &m) for _, country := range m["countries"] { t.Logf("%q", country) } var s []smiley test_unmarshal(t, `what if we try`, &s) for _, s := range s { t.Logf("%q", s) } } func test_unmarshal_error(t *testing.T, source, what string, args ...interface{}) { ast, err := Parse(strings.NewReader(source), nil) if err != nil { t.Error(err) } err = ast.Unmarshal(args...) error_must_contain(t, err, what) } func TestUnmarshalErrors(t *testing.T) { var ( a [3]uint8 b neversmiley c [1]neversmiley2 d [][]string e []bool f map[string]int g chan int h [3]int8 i **int j [1]float64 k interface { String() string } ) expect_panic(func() { test_unmarshal_error(t, "1 2 3", "", a) }, func(v interface{}) { if s, ok := v.(string); ok { must_contain(t, s, "Node.Unmarshal expects a non-nil pointer") } else { t.Errorf("unexpected panic: %s", v) } }) test_unmarshal_error(t, "123", "Y U NO HAPPY", &b) test_unmarshal_error(t, "123", "inevitable failure", &c) test_unmarshal_error(t, "123", "list value required", &d) test_unmarshal_error(t, "(true (1 2 3) false)", "scalar value required", &e) test_unmarshal_error(t, "256", "integer overflow", &a) test_unmarshal_error(t, "abc", "invalid syntax", &a) test_unmarshal_error(t, "trUe", "undefined boolean", &e) test_unmarshal_error(t, "(a 1) (b 2) (c 3) oops", "node is not a list", &f) test_unmarshal_error(t, "hello", "unsupported type", &g) test_unmarshal_error(t, "-129", "integer overflow", &h) test_unmarshal_error(t, "abc", "invalid syntax", &h) test_unmarshal_error(t, "11", "unsupported type", &i) // only one level of indirection test_unmarshal_error(t, "3.1415f", "invalid syntax", &j) test_unmarshal_error(t, "xxx", "unsupported type", &k) } func TestNodeNth(t *testing.T) { root, err := Parse(strings.NewReader("0 1 2 3"), nil) if err != nil { t.Error(err) return } assert := func(cond bool, msg interface{}) { if !cond { t.Error(msg) } } n, err := root.Nth(0) assert(err == nil, err) assert(n != nil, "non-nil node expected") assert(n.Value == "0", "0 expected") _, err = n.Nth(234) error_must_contain(t, err, "is not a list") _, err = root.Nth(3) assert(err == nil, err) _, err = root.Nth(4) error_must_contain(t, err, "cannot retrieve 5th") } func TestNodeIterKeyValues(t *testing.T) { root, err := Parse(strings.NewReader(` ( (x y) (z w) (a 1) (b 2) (c 3) ) ( (x y) (z) ) ( not-a-list ) `), nil) if err != nil { t.Error(err) return } nth_must := func(n *Node, err error) *Node { if err != nil { t.Fatal(err) } return n } list1 := nth_must(root.Nth(0)) list2 := nth_must(root.Nth(1)) list3 := nth_must(root.Nth(2)) items := []struct{ key, value string }{ {"x", "y"}, {"z", "w"}, {"a", "1"}, {"b", "2"}, {"c", "3"}, } i := 0 err = list1.IterKeyValues(func(k, v *Node) error { if k.Value != items[i].key { t.Errorf("%q != %q", k.Value, items[i].key) } if v.Value != items[i].value { t.Errorf("%q != %q", v.Value, items[i].value) } i++ return nil }) if err != nil { t.Error(err) return } err = list2.IterKeyValues(func(k, v *Node) error { return nil }) error_must_contain(t, err, "cannot retrieve 2nd") err = list3.IterKeyValues(func(k, v *Node) error { return nil }) error_must_contain(t, err, "node is not a list") }
linasmk/appointments_scheduling_react
src/store/appointmentsReducer.js
<filename>src/store/appointmentsReducer.js /* ============== Dependencies ================ */ import appointmentData from "../data/data"; /* ================================================= =========== APPOINTMENTS REDUCER ================ ================================================= */ const appointmentsReducerDefaultState = appointmentData; export default (state = appointmentsReducerDefaultState, action) => { switch (action.type) { case "ADD_APPOINTMENT": return [...state, action.appointment]; case "REMOVE_APPOINTMENT": return state.filter((appointment) => { return appointment.id !== action.id; }); case "EDIT_APPOINTMENT": return state.map((appointment) => { if (appointment.id === action.id) { return { ...appointment, ...action.updates, }; } else { return appointment; } }); default: return state; } };
sho25/hbase
hbase-server/src/main/java/org/apache/hadoop/hbase/wal/WALSplitter.java
<filename>hbase-server/src/main/java/org/apache/hadoop/hbase/wal/WALSplitter.java begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal package|; end_package begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|BoundedRecoveredHFilesOutputSink operator|. name|DEFAULT_WAL_SPLIT_TO_HFILE import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|BoundedRecoveredHFilesOutputSink operator|. name|WAL_SPLIT_TO_HFILE import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WALSplitUtil operator|. name|finishSplitLogFile import|; end_import begin_import import|import name|java operator|. name|io operator|. name|EOFException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|FileNotFoundException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|InterruptedIOException import|; end_import begin_import import|import name|java operator|. name|text operator|. name|ParseException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|TreeMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ConcurrentHashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|atomic operator|. name|AtomicReference import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|lang3 operator|. name|ArrayUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileStatus import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileSystem import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseConfiguration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|TableDescriptors import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coordination operator|. name|SplitLogWorkerCoordination import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|master operator|. name|SplitLogManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|monitoring operator|. name|MonitoredTask import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|monitoring operator|. name|TaskMonitor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|procedure2 operator|. name|util operator|. name|StringUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|LastSequenceId import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|RegionServerServices import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|wal operator|. name|WALCellCodec import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Bytes import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|CancelableProgressable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|EnvironmentEdgeManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|FSTableDescriptors import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|FSUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WAL operator|. name|Entry import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WAL operator|. name|Reader import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|zookeeper operator|. name|ZKSplitLog import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|RemoteException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|yetus operator|. name|audience operator|. name|InterfaceAudience import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|com operator|. name|google operator|. name|common operator|. name|annotations operator|. name|VisibleForTesting import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|com operator|. name|google operator|. name|common operator|. name|base operator|. name|Preconditions import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|com operator|. name|google operator|. name|protobuf operator|. name|TextFormat import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|shaded operator|. name|protobuf operator|. name|generated operator|. name|ClusterStatusProtos operator|. name|RegionStoreSequenceIds import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|shaded operator|. name|protobuf operator|. name|generated operator|. name|ClusterStatusProtos operator|. name|StoreSequenceId import|; end_import begin_comment comment|/** * This class is responsible for splitting up a bunch of regionserver commit log * files that are no longer being written to, into new files, one per region, for * recovering data on startup. Delete the old log files when finished. */ end_comment begin_class annotation|@ name|InterfaceAudience operator|. name|Private specifier|public class|class name|WALSplitter block|{ specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|WALSplitter operator|. name|class argument_list|) decl_stmt|; comment|/** By default we retry errors in splitting, rather than skipping. */ specifier|public specifier|static specifier|final name|boolean name|SPLIT_SKIP_ERRORS_DEFAULT init|= literal|false decl_stmt|; comment|// Parameters for split process specifier|protected specifier|final name|Path name|walDir decl_stmt|; specifier|protected specifier|final name|FileSystem name|walFS decl_stmt|; specifier|protected specifier|final name|Configuration name|conf decl_stmt|; specifier|final name|Path name|rootDir decl_stmt|; specifier|final name|FileSystem name|rootFS decl_stmt|; specifier|final name|RegionServerServices name|rsServices decl_stmt|; specifier|final name|TableDescriptors name|tableDescriptors decl_stmt|; comment|// Major subcomponents of the split process. comment|// These are separated into inner classes to make testing easier. name|OutputSink name|outputSink decl_stmt|; specifier|private name|EntryBuffers name|entryBuffers decl_stmt|; specifier|private name|SplitLogWorkerCoordination name|splitLogWorkerCoordination decl_stmt|; specifier|private specifier|final name|WALFactory name|walFactory decl_stmt|; specifier|private name|MonitoredTask name|status decl_stmt|; comment|// For checking the latest flushed sequence id specifier|protected specifier|final name|LastSequenceId name|sequenceIdChecker decl_stmt|; comment|// Map encodedRegionName -> lastFlushedSequenceId specifier|protected name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|lastFlushedSequenceIds init|= operator|new name|ConcurrentHashMap argument_list|<> argument_list|() decl_stmt|; comment|// Map encodedRegionName -> maxSeqIdInStores specifier|protected name|Map argument_list|< name|String argument_list|, name|Map argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> argument_list|> name|regionMaxSeqIdInStores init|= operator|new name|ConcurrentHashMap argument_list|<> argument_list|() decl_stmt|; comment|// the file being split currently specifier|private name|FileStatus name|fileBeingSplit decl_stmt|; specifier|private specifier|final name|String name|tmpDirName decl_stmt|; specifier|public specifier|final specifier|static name|String name|SPLIT_WRITER_CREATION_BOUNDED init|= literal|"hbase.split.writer.creation.bounded" decl_stmt|; specifier|public specifier|final specifier|static name|String name|SPLIT_WAL_BUFFER_SIZE init|= literal|"hbase.regionserver.hlog.splitlog.buffersize" decl_stmt|; specifier|public specifier|final specifier|static name|String name|SPLIT_WAL_WRITER_THREADS init|= literal|"hbase.regionserver.hlog.splitlog.writer.threads" decl_stmt|; annotation|@ name|VisibleForTesting name|WALSplitter parameter_list|( specifier|final name|WALFactory name|factory parameter_list|, name|Configuration name|conf parameter_list|, name|Path name|walDir parameter_list|, name|FileSystem name|walFS parameter_list|, name|Path name|rootDir parameter_list|, name|FileSystem name|rootFS parameter_list|, name|LastSequenceId name|idChecker parameter_list|, name|SplitLogWorkerCoordination name|splitLogWorkerCoordination parameter_list|, name|RegionServerServices name|rsServices parameter_list|) block|{ name|this operator|. name|conf operator|= name|HBaseConfiguration operator|. name|create argument_list|( name|conf argument_list|) expr_stmt|; name|String name|codecClassName init|= name|conf operator|. name|get argument_list|( name|WALCellCodec operator|. name|WAL_CELL_CODEC_CLASS_KEY argument_list|, name|WALCellCodec operator|. name|class operator|. name|getName argument_list|() argument_list|) decl_stmt|; name|this operator|. name|conf operator|. name|set argument_list|( name|HConstants operator|. name|RPC_CODEC_CONF_KEY argument_list|, name|codecClassName argument_list|) expr_stmt|; name|this operator|. name|walDir operator|= name|walDir expr_stmt|; name|this operator|. name|walFS operator|= name|walFS expr_stmt|; name|this operator|. name|rootDir operator|= name|rootDir expr_stmt|; name|this operator|. name|rootFS operator|= name|rootFS expr_stmt|; name|this operator|. name|sequenceIdChecker operator|= name|idChecker expr_stmt|; name|this operator|. name|splitLogWorkerCoordination operator|= name|splitLogWorkerCoordination expr_stmt|; name|this operator|. name|rsServices operator|= name|rsServices expr_stmt|; if|if condition|( name|rsServices operator|!= literal|null condition|) block|{ name|this operator|. name|tableDescriptors operator|= name|rsServices operator|. name|getTableDescriptors argument_list|() expr_stmt|; block|} else|else block|{ name|this operator|. name|tableDescriptors operator|= operator|new name|FSTableDescriptors argument_list|( name|rootFS argument_list|, name|rootDir argument_list|, literal|true argument_list|, literal|true argument_list|) expr_stmt|; block|} name|this operator|. name|walFactory operator|= name|factory expr_stmt|; name|PipelineController name|controller init|= operator|new name|PipelineController argument_list|() decl_stmt|; name|this operator|. name|tmpDirName operator|= name|conf operator|. name|get argument_list|( name|HConstants operator|. name|TEMPORARY_FS_DIRECTORY_KEY argument_list|, name|HConstants operator|. name|DEFAULT_TEMPORARY_HDFS_DIRECTORY argument_list|) expr_stmt|; comment|// if we limit the number of writers opened for sinking recovered edits name|boolean name|splitWriterCreationBounded init|= name|conf operator|. name|getBoolean argument_list|( name|SPLIT_WRITER_CREATION_BOUNDED argument_list|, literal|false argument_list|) decl_stmt|; name|boolean name|splitToHFile init|= name|conf operator|. name|getBoolean argument_list|( name|WAL_SPLIT_TO_HFILE argument_list|, name|DEFAULT_WAL_SPLIT_TO_HFILE argument_list|) decl_stmt|; name|long name|bufferSize init|= name|this operator|. name|conf operator|. name|getLong argument_list|( name|SPLIT_WAL_BUFFER_SIZE argument_list|, literal|128 operator|* literal|1024 operator|* literal|1024 argument_list|) decl_stmt|; name|int name|numWriterThreads init|= name|this operator|. name|conf operator|. name|getInt argument_list|( name|SPLIT_WAL_WRITER_THREADS argument_list|, literal|3 argument_list|) decl_stmt|; if|if condition|( name|splitToHFile condition|) block|{ name|entryBuffers operator|= operator|new name|BoundedEntryBuffers argument_list|( name|controller argument_list|, name|bufferSize argument_list|) expr_stmt|; name|outputSink operator|= operator|new name|BoundedRecoveredHFilesOutputSink argument_list|( name|this argument_list|, name|controller argument_list|, name|entryBuffers argument_list|, name|numWriterThreads argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|splitWriterCreationBounded condition|) block|{ name|entryBuffers operator|= operator|new name|BoundedEntryBuffers argument_list|( name|controller argument_list|, name|bufferSize argument_list|) expr_stmt|; name|outputSink operator|= operator|new name|BoundedRecoveredEditsOutputSink argument_list|( name|this argument_list|, name|controller argument_list|, name|entryBuffers argument_list|, name|numWriterThreads argument_list|) expr_stmt|; block|} else|else block|{ name|entryBuffers operator|= operator|new name|EntryBuffers argument_list|( name|controller argument_list|, name|bufferSize argument_list|) expr_stmt|; name|outputSink operator|= operator|new name|RecoveredEditsOutputSink argument_list|( name|this argument_list|, name|controller argument_list|, name|entryBuffers argument_list|, name|numWriterThreads argument_list|) expr_stmt|; block|} block|} name|WALFactory name|getWalFactory parameter_list|() block|{ return|return name|this operator|. name|walFactory return|; block|} name|FileStatus name|getFileBeingSplit parameter_list|() block|{ return|return name|fileBeingSplit return|; block|} name|String name|getTmpDirName parameter_list|() block|{ return|return name|this operator|. name|tmpDirName return|; block|} name|Map argument_list|< name|String argument_list|, name|Map argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> argument_list|> name|getRegionMaxSeqIdInStores parameter_list|() block|{ return|return name|regionMaxSeqIdInStores return|; block|} comment|/** * Splits a WAL file into region's recovered-edits directory. * This is the main entry point for distributed log splitting from SplitLogWorker. *<p> * If the log file has N regions then N recovered.edits files will be produced. *<p> * @return false if it is interrupted by the progress-able. */ specifier|public specifier|static name|boolean name|splitLogFile parameter_list|( name|Path name|walDir parameter_list|, name|FileStatus name|logfile parameter_list|, name|FileSystem name|walFS parameter_list|, name|Configuration name|conf parameter_list|, name|CancelableProgressable name|reporter parameter_list|, name|LastSequenceId name|idChecker parameter_list|, name|SplitLogWorkerCoordination name|splitLogWorkerCoordination parameter_list|, name|WALFactory name|factory parameter_list|, name|RegionServerServices name|rsServices parameter_list|) throws|throws name|IOException block|{ name|Path name|rootDir init|= name|FSUtils operator|. name|getRootDir argument_list|( name|conf argument_list|) decl_stmt|; name|FileSystem name|rootFS init|= name|rootDir operator|. name|getFileSystem argument_list|( name|conf argument_list|) decl_stmt|; name|WALSplitter name|s init|= operator|new name|WALSplitter argument_list|( name|factory argument_list|, name|conf argument_list|, name|walDir argument_list|, name|walFS argument_list|, name|rootDir argument_list|, name|rootFS argument_list|, name|idChecker argument_list|, name|splitLogWorkerCoordination argument_list|, name|rsServices argument_list|) decl_stmt|; return|return name|s operator|. name|splitLogFile argument_list|( name|logfile argument_list|, name|reporter argument_list|) return|; block|} comment|// A wrapper to split one log folder using the method used by distributed comment|// log splitting. Used by tools and unit tests. It should be package private. comment|// It is public only because TestWALObserver is in a different package, comment|// which uses this method to do log splitting. annotation|@ name|VisibleForTesting specifier|public specifier|static name|List argument_list|< name|Path argument_list|> name|split parameter_list|( name|Path name|walDir parameter_list|, name|Path name|logDir parameter_list|, name|Path name|oldLogDir parameter_list|, name|FileSystem name|walFS parameter_list|, name|Configuration name|conf parameter_list|, specifier|final name|WALFactory name|factory parameter_list|) throws|throws name|IOException block|{ name|Path name|rootDir init|= name|FSUtils operator|. name|getRootDir argument_list|( name|conf argument_list|) decl_stmt|; name|FileSystem name|rootFS init|= name|rootDir operator|. name|getFileSystem argument_list|( name|conf argument_list|) decl_stmt|; specifier|final name|FileStatus index|[] name|logfiles init|= name|SplitLogManager operator|. name|getFileList argument_list|( name|conf argument_list|, name|Collections operator|. name|singletonList argument_list|( name|logDir argument_list|) argument_list|, literal|null argument_list|) decl_stmt|; name|List argument_list|< name|Path argument_list|> name|splits init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; if|if condition|( name|ArrayUtils operator|. name|isNotEmpty argument_list|( name|logfiles argument_list|) condition|) block|{ for|for control|( name|FileStatus name|logfile range|: name|logfiles control|) block|{ name|WALSplitter name|s init|= operator|new name|WALSplitter argument_list|( name|factory argument_list|, name|conf argument_list|, name|walDir argument_list|, name|walFS argument_list|, name|rootDir argument_list|, name|rootFS argument_list|, literal|null argument_list|, literal|null argument_list|, literal|null argument_list|) decl_stmt|; if|if condition|( name|s operator|. name|splitLogFile argument_list|( name|logfile argument_list|, literal|null argument_list|) condition|) block|{ name|finishSplitLogFile argument_list|( name|walDir argument_list|, name|oldLogDir argument_list|, name|logfile operator|. name|getPath argument_list|() argument_list|, name|conf argument_list|) expr_stmt|; if|if condition|( name|s operator|. name|outputSink operator|. name|splits operator|!= literal|null condition|) block|{ name|splits operator|. name|addAll argument_list|( name|s operator|. name|outputSink operator|. name|splits argument_list|) expr_stmt|; block|} block|} block|} block|} if|if condition|( operator|! name|walFS operator|. name|delete argument_list|( name|logDir argument_list|, literal|true argument_list|) condition|) block|{ throw|throw operator|new name|IOException argument_list|( literal|"Unable to delete src dir: " operator|+ name|logDir argument_list|) throw|; block|} return|return name|splits return|; block|} comment|/** * log splitting implementation, splits one log file. * @param logfile should be an actual log file. */ annotation|@ name|VisibleForTesting name|boolean name|splitLogFile parameter_list|( name|FileStatus name|logfile parameter_list|, name|CancelableProgressable name|reporter parameter_list|) throws|throws name|IOException block|{ name|Preconditions operator|. name|checkState argument_list|( name|status operator|== literal|null argument_list|) expr_stmt|; name|Preconditions operator|. name|checkArgument argument_list|( name|logfile operator|. name|isFile argument_list|() argument_list|, literal|"passed in file status is for something other than a regular file." argument_list|) expr_stmt|; name|boolean name|isCorrupted init|= literal|false decl_stmt|; name|boolean name|skipErrors init|= name|conf operator|. name|getBoolean argument_list|( literal|"hbase.hlog.split.skip.errors" argument_list|, name|SPLIT_SKIP_ERRORS_DEFAULT argument_list|) decl_stmt|; name|int name|interval init|= name|conf operator|. name|getInt argument_list|( literal|"hbase.splitlog.report.interval.loglines" argument_list|, literal|1024 argument_list|) decl_stmt|; name|Path name|logPath init|= name|logfile operator|. name|getPath argument_list|() decl_stmt|; name|boolean name|outputSinkStarted init|= literal|false decl_stmt|; name|boolean name|progressFailed init|= literal|false decl_stmt|; name|int name|editsCount init|= literal|0 decl_stmt|; name|int name|editsSkipped init|= literal|0 decl_stmt|; name|status operator|= name|TaskMonitor operator|. name|get argument_list|() operator|. name|createStatus argument_list|( literal|"Splitting log file " operator|+ name|logfile operator|. name|getPath argument_list|() operator|+ literal|"into a temporary staging area." argument_list|) expr_stmt|; name|Reader name|logFileReader init|= literal|null decl_stmt|; name|this operator|. name|fileBeingSplit operator|= name|logfile expr_stmt|; name|long name|startTS init|= name|EnvironmentEdgeManager operator|. name|currentTime argument_list|() decl_stmt|; try|try block|{ name|long name|logLength init|= name|logfile operator|. name|getLen argument_list|() decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"Splitting WAL={}, size={} ({} bytes)" argument_list|, name|logPath argument_list|, name|StringUtils operator|. name|humanSize argument_list|( name|logLength argument_list|) argument_list|, name|logLength argument_list|) expr_stmt|; name|status operator|. name|setStatus argument_list|( literal|"Opening log file" argument_list|) expr_stmt|; if|if condition|( name|reporter operator|!= literal|null operator|&& operator|! name|reporter operator|. name|progress argument_list|() condition|) block|{ name|progressFailed operator|= literal|true expr_stmt|; return|return literal|false return|; block|} name|logFileReader operator|= name|getReader argument_list|( name|logfile argument_list|, name|skipErrors argument_list|, name|reporter argument_list|) expr_stmt|; if|if condition|( name|logFileReader operator|== literal|null condition|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Nothing to split in WAL={}" argument_list|, name|logPath argument_list|) expr_stmt|; return|return literal|true return|; block|} name|long name|openCost init|= name|EnvironmentEdgeManager operator|. name|currentTime argument_list|() operator|- name|startTS decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"Open WAL={} cost {} ms" argument_list|, name|logPath argument_list|, name|openCost argument_list|) expr_stmt|; name|int name|numOpenedFilesBeforeReporting init|= name|conf operator|. name|getInt argument_list|( literal|"hbase.splitlog.report.openedfiles" argument_list|, literal|3 argument_list|) decl_stmt|; name|int name|numOpenedFilesLastCheck init|= literal|0 decl_stmt|; name|outputSink operator|. name|setReporter argument_list|( name|reporter argument_list|) expr_stmt|; name|outputSink operator|. name|startWriterThreads argument_list|() expr_stmt|; name|outputSinkStarted operator|= literal|true expr_stmt|; name|Entry name|entry decl_stmt|; name|Long name|lastFlushedSequenceId init|= operator|- literal|1L decl_stmt|; name|startTS operator|= name|EnvironmentEdgeManager operator|. name|currentTime argument_list|() expr_stmt|; while|while condition|( operator|( name|entry operator|= name|getNextLogLine argument_list|( name|logFileReader argument_list|, name|logPath argument_list|, name|skipErrors argument_list|) operator|) operator|!= literal|null condition|) block|{ name|byte index|[] name|region init|= name|entry operator|. name|getKey argument_list|() operator|. name|getEncodedRegionName argument_list|() decl_stmt|; name|String name|encodedRegionNameAsStr init|= name|Bytes operator|. name|toString argument_list|( name|region argument_list|) decl_stmt|; name|lastFlushedSequenceId operator|= name|lastFlushedSequenceIds operator|. name|get argument_list|( name|encodedRegionNameAsStr argument_list|) expr_stmt|; if|if condition|( name|lastFlushedSequenceId operator|== literal|null condition|) block|{ if|if condition|( name|sequenceIdChecker operator|!= literal|null condition|) block|{ name|RegionStoreSequenceIds name|ids init|= name|sequenceIdChecker operator|. name|getLastSequenceId argument_list|( name|region argument_list|) decl_stmt|; name|Map argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> name|maxSeqIdInStores init|= operator|new name|TreeMap argument_list|<> argument_list|( name|Bytes operator|. name|BYTES_COMPARATOR argument_list|) decl_stmt|; for|for control|( name|StoreSequenceId name|storeSeqId range|: name|ids operator|. name|getStoreSequenceIdList argument_list|() control|) block|{ name|maxSeqIdInStores operator|. name|put argument_list|( name|storeSeqId operator|. name|getFamilyName argument_list|() operator|. name|toByteArray argument_list|() argument_list|, name|storeSeqId operator|. name|getSequenceId argument_list|() argument_list|) expr_stmt|; block|} name|regionMaxSeqIdInStores operator|. name|put argument_list|( name|encodedRegionNameAsStr argument_list|, name|maxSeqIdInStores argument_list|) expr_stmt|; name|lastFlushedSequenceId operator|= name|ids operator|. name|getLastFlushedSequenceId argument_list|() expr_stmt|; if|if condition|( name|LOG operator|. name|isDebugEnabled argument_list|() condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"DLS Last flushed sequenceid for " operator|+ name|encodedRegionNameAsStr operator|+ literal|": " operator|+ name|TextFormat operator|. name|shortDebugString argument_list|( name|ids argument_list|) argument_list|) expr_stmt|; block|} block|} if|if condition|( name|lastFlushedSequenceId operator|== literal|null condition|) block|{ name|lastFlushedSequenceId operator|= operator|- literal|1L expr_stmt|; block|} name|lastFlushedSequenceIds operator|. name|put argument_list|( name|encodedRegionNameAsStr argument_list|, name|lastFlushedSequenceId argument_list|) expr_stmt|; block|} if|if condition|( name|lastFlushedSequenceId operator|>= name|entry operator|. name|getKey argument_list|() operator|. name|getSequenceId argument_list|() condition|) block|{ name|editsSkipped operator|++ expr_stmt|; continue|continue; block|} comment|// Don't send Compaction/Close/Open region events to recovered edit type sinks. if|if condition|( name|entry operator|. name|getEdit argument_list|() operator|. name|isMetaEdit argument_list|() operator|&& operator|! name|outputSink operator|. name|keepRegionEvent argument_list|( name|entry argument_list|) condition|) block|{ name|editsSkipped operator|++ expr_stmt|; continue|continue; block|} name|entryBuffers operator|. name|appendEntry argument_list|( name|entry argument_list|) expr_stmt|; name|editsCount operator|++ expr_stmt|; name|int name|moreWritersFromLastCheck init|= name|this operator|. name|getNumOpenWriters argument_list|() operator|- name|numOpenedFilesLastCheck decl_stmt|; comment|// If sufficient edits have passed, check if we should report progress. if|if condition|( name|editsCount operator|% name|interval operator|== literal|0 operator||| name|moreWritersFromLastCheck operator|> name|numOpenedFilesBeforeReporting condition|) block|{ name|numOpenedFilesLastCheck operator|= name|this operator|. name|getNumOpenWriters argument_list|() expr_stmt|; name|String name|countsStr init|= operator|( name|editsCount operator|- operator|( name|editsSkipped operator|+ name|outputSink operator|. name|getTotalSkippedEdits argument_list|() operator|) operator|) operator|+ literal|" edits, skipped " operator|+ name|editsSkipped operator|+ literal|" edits." decl_stmt|; name|status operator|. name|setStatus argument_list|( literal|"Split " operator|+ name|countsStr argument_list|) expr_stmt|; if|if condition|( name|reporter operator|!= literal|null operator|&& operator|! name|reporter operator|. name|progress argument_list|() condition|) block|{ name|progressFailed operator|= literal|true expr_stmt|; return|return literal|false return|; block|} block|} block|} block|} catch|catch parameter_list|( name|InterruptedException name|ie parameter_list|) block|{ name|IOException name|iie init|= operator|new name|InterruptedIOException argument_list|() decl_stmt|; name|iie operator|. name|initCause argument_list|( name|ie argument_list|) expr_stmt|; throw|throw name|iie throw|; block|} catch|catch parameter_list|( name|CorruptedLogFileException name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Could not parse, corrupted WAL={}" argument_list|, name|logPath argument_list|, name|e argument_list|) expr_stmt|; if|if condition|( name|splitLogWorkerCoordination operator|!= literal|null condition|) block|{ comment|// Some tests pass in a csm of null. name|splitLogWorkerCoordination operator|. name|markCorrupted argument_list|( name|walDir argument_list|, name|logfile operator|. name|getPath argument_list|() operator|. name|getName argument_list|() argument_list|, name|walFS argument_list|) expr_stmt|; block|} else|else block|{ comment|// for tests only name|ZKSplitLog operator|. name|markCorrupted argument_list|( name|walDir argument_list|, name|logfile operator|. name|getPath argument_list|() operator|. name|getName argument_list|() argument_list|, name|walFS argument_list|) expr_stmt|; block|} name|isCorrupted operator|= literal|true expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ name|e operator|= name|e operator|instanceof name|RemoteException condition|? operator|( operator|( name|RemoteException operator|) name|e operator|) operator|. name|unwrapRemoteException argument_list|() else|: name|e expr_stmt|; throw|throw name|e throw|; block|} finally|finally block|{ name|LOG operator|. name|debug argument_list|( literal|"Finishing writing output logs and closing down" argument_list|) expr_stmt|; try|try block|{ if|if condition|( literal|null operator|!= name|logFileReader condition|) block|{ name|logFileReader operator|. name|close argument_list|() expr_stmt|; block|} block|} catch|catch parameter_list|( name|IOException name|exception parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Could not close WAL reader" argument_list|, name|exception argument_list|) expr_stmt|; block|} try|try block|{ if|if condition|( name|outputSinkStarted condition|) block|{ comment|// Set progress_failed to true as the immediate following statement will reset its value comment|// when close() throws exception, progress_failed has the right value name|progressFailed operator|= literal|true expr_stmt|; name|progressFailed operator|= name|outputSink operator|. name|close argument_list|() operator|== literal|null expr_stmt|; block|} block|} finally|finally block|{ name|long name|processCost init|= name|EnvironmentEdgeManager operator|. name|currentTime argument_list|() operator|- name|startTS decl_stmt|; comment|// See if length got updated post lease recovery name|String name|msg init|= literal|"Processed " operator|+ name|editsCount operator|+ literal|" edits across " operator|+ name|outputSink operator|. name|getNumberOfRecoveredRegions argument_list|() operator|+ literal|" regions cost " operator|+ name|processCost operator|+ literal|" ms; edits skipped=" operator|+ name|editsSkipped operator|+ literal|"; WAL=" operator|+ name|logPath operator|+ literal|", size=" operator|+ name|StringUtils operator|. name|humanSize argument_list|( name|logfile operator|. name|getLen argument_list|() argument_list|) operator|+ literal|", length=" operator|+ name|logfile operator|. name|getLen argument_list|() operator|+ literal|", corrupted=" operator|+ name|isCorrupted operator|+ literal|", progress failed=" operator|+ name|progressFailed decl_stmt|; name|LOG operator|. name|info argument_list|( name|msg argument_list|) expr_stmt|; name|status operator|. name|markComplete argument_list|( name|msg argument_list|) expr_stmt|; block|} block|} return|return operator|! name|progressFailed return|; block|} comment|/** * Create a new {@link Reader} for reading logs to split. */ specifier|private name|Reader name|getReader parameter_list|( name|FileStatus name|file parameter_list|, name|boolean name|skipErrors parameter_list|, name|CancelableProgressable name|reporter parameter_list|) throws|throws name|IOException throws|, name|CorruptedLogFileException block|{ name|Path name|path init|= name|file operator|. name|getPath argument_list|() decl_stmt|; name|long name|length init|= name|file operator|. name|getLen argument_list|() decl_stmt|; name|Reader name|in decl_stmt|; comment|// Check for possibly empty file. With appends, currently Hadoop reports a comment|// zero length even if the file has been sync'd. Revisit if HDFS-376 or comment|// HDFS-878 is committed. if|if condition|( name|length operator|<= literal|0 condition|) block|{ name|LOG operator|. name|warn argument_list|( literal|"File {} might be still open, length is 0" argument_list|, name|path argument_list|) expr_stmt|; block|} try|try block|{ name|FSUtils operator|. name|getInstance argument_list|( name|walFS argument_list|, name|conf argument_list|) operator|. name|recoverFileLease argument_list|( name|walFS argument_list|, name|path argument_list|, name|conf argument_list|, name|reporter argument_list|) expr_stmt|; try|try block|{ name|in operator|= name|getReader argument_list|( name|path argument_list|, name|reporter argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|EOFException name|e parameter_list|) block|{ if|if condition|( name|length operator|<= literal|0 condition|) block|{ comment|// TODO should we ignore an empty, not-last log file if skip.errors comment|// is false? Either way, the caller should decide what to do. E.g. comment|// ignore if this is the last log in sequence. comment|// TODO is this scenario still possible if the log has been comment|// recovered (i.e. closed) name|LOG operator|. name|warn argument_list|( literal|"Could not open {} for reading. File is empty" argument_list|, name|path argument_list|, name|e argument_list|) expr_stmt|; block|} comment|// EOFException being ignored return|return literal|null return|; block|} block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ if|if condition|( name|e operator|instanceof name|FileNotFoundException condition|) block|{ comment|// A wal file may not exist anymore. Nothing can be recovered so move on name|LOG operator|. name|warn argument_list|( literal|"File {} does not exist anymore" argument_list|, name|path argument_list|, name|e argument_list|) expr_stmt|; return|return literal|null return|; block|} if|if condition|( operator|! name|skipErrors operator||| name|e operator|instanceof name|InterruptedIOException condition|) block|{ throw|throw name|e throw|; comment|// Don't mark the file corrupted if interrupted, or not skipErrors block|} throw|throw operator|new name|CorruptedLogFileException argument_list|( literal|"skipErrors=true Could not open wal " operator|+ name|path operator|+ literal|" ignoring" argument_list|, name|e argument_list|) throw|; block|} return|return name|in return|; block|} specifier|private name|Entry name|getNextLogLine parameter_list|( name|Reader name|in parameter_list|, name|Path name|path parameter_list|, name|boolean name|skipErrors parameter_list|) throws|throws name|CorruptedLogFileException throws|, name|IOException block|{ try|try block|{ return|return name|in operator|. name|next argument_list|() return|; block|} catch|catch parameter_list|( name|EOFException name|eof parameter_list|) block|{ comment|// truncated files are expected if a RS crashes (see HBASE-2643) name|LOG operator|. name|info argument_list|( literal|"EOF from wal {}. Continuing." argument_list|, name|path argument_list|) expr_stmt|; return|return literal|null return|; block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ comment|// If the IOE resulted from bad file format, comment|// then this problem is idempotent and retrying won't help if|if condition|( name|e operator|. name|getCause argument_list|() operator|!= literal|null operator|&& operator|( name|e operator|. name|getCause argument_list|() operator|instanceof name|ParseException operator||| name|e operator|. name|getCause argument_list|() operator|instanceof name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|ChecksumException operator|) condition|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Parse exception from wal {}. Continuing" argument_list|, name|path argument_list|, name|e argument_list|) expr_stmt|; return|return literal|null return|; block|} if|if condition|( operator|! name|skipErrors condition|) block|{ throw|throw name|e throw|; block|} throw|throw operator|new name|CorruptedLogFileException argument_list|( literal|"skipErrors=true Ignoring exception" operator|+ literal|" while parsing wal " operator|+ name|path operator|+ literal|". Marking as corrupted" argument_list|, name|e argument_list|) throw|; block|} block|} comment|/** * Create a new {@link WALProvider.Writer} for writing log splits. * @return a new Writer instance, caller should close */ specifier|protected name|WALProvider operator|. name|Writer name|createWriter parameter_list|( name|Path name|logfile parameter_list|) throws|throws name|IOException block|{ return|return name|walFactory operator|. name|createRecoveredEditsWriter argument_list|( name|walFS argument_list|, name|logfile argument_list|) return|; block|} comment|/** * Create a new {@link Reader} for reading logs to split. * @return new Reader instance, caller should close */ specifier|protected name|Reader name|getReader parameter_list|( name|Path name|curLogFile parameter_list|, name|CancelableProgressable name|reporter parameter_list|) throws|throws name|IOException block|{ return|return name|walFactory operator|. name|createReader argument_list|( name|walFS argument_list|, name|curLogFile argument_list|, name|reporter argument_list|) return|; block|} comment|/** * Get current open writers */ specifier|private name|int name|getNumOpenWriters parameter_list|() block|{ name|int name|result init|= literal|0 decl_stmt|; if|if condition|( name|this operator|. name|outputSink operator|!= literal|null condition|) block|{ name|result operator|+= name|this operator|. name|outputSink operator|. name|getNumOpenWriters argument_list|() expr_stmt|; block|} return|return name|result return|; block|} comment|/** * Contains some methods to control WAL-entries producer / consumer interactions */ specifier|public specifier|static class|class name|PipelineController block|{ comment|// If an exception is thrown by one of the other threads, it will be comment|// stored here. name|AtomicReference argument_list|< name|Throwable argument_list|> name|thrown init|= operator|new name|AtomicReference argument_list|<> argument_list|() decl_stmt|; comment|// Wait/notify for when data has been produced by the writer thread, comment|// consumed by the reader thread, or an exception occurred specifier|final name|Object name|dataAvailable init|= operator|new name|Object argument_list|() decl_stmt|; name|void name|writerThreadError parameter_list|( name|Throwable name|t parameter_list|) block|{ name|thrown operator|. name|compareAndSet argument_list|( literal|null argument_list|, name|t argument_list|) expr_stmt|; block|} comment|/** * Check for errors in the writer threads. If any is found, rethrow it. */ name|void name|checkForErrors parameter_list|() throws|throws name|IOException block|{ name|Throwable name|thrown init|= name|this operator|. name|thrown operator|. name|get argument_list|() decl_stmt|; if|if condition|( name|thrown operator|== literal|null condition|) block|{ return|return; block|} if|if condition|( name|thrown operator|instanceof name|IOException condition|) block|{ throw|throw operator|new name|IOException argument_list|( name|thrown argument_list|) throw|; block|} else|else block|{ throw|throw operator|new name|RuntimeException argument_list|( name|thrown argument_list|) throw|; block|} block|} block|} specifier|static class|class name|CorruptedLogFileException extends|extends name|Exception block|{ specifier|private specifier|static specifier|final name|long name|serialVersionUID init|= literal|1L decl_stmt|; name|CorruptedLogFileException parameter_list|( name|String name|s parameter_list|) block|{ name|super argument_list|( name|s argument_list|) expr_stmt|; block|} comment|/** * CorruptedLogFileException with cause * * @param message the message for this exception * @param cause the cause for this exception */ name|CorruptedLogFileException parameter_list|( name|String name|message parameter_list|, name|Throwable name|cause parameter_list|) block|{ name|super argument_list|( name|message argument_list|, name|cause argument_list|) expr_stmt|; block|} block|} block|} end_class end_unit
speedfirst/leetcode
cpp/TrappingRainWater.cc
<gh_stars>0 namespace TrappingRainWater { class Solution { public: int trap(int A[], int n) { if (n == 0) return 0; int area = 0; int prevHeight = 0; // scan from left to right int curArea = 0; for (int i = 0; i < n; i++) { if (A[i] >= prevHeight) { // Note here ">=" is used, and below ">" is used area += curArea; curArea = 0; prevHeight = A[i]; } else { curArea += (prevHeight - A[i]); } } // scan from right to left prevHeight = 0; curArea = 0; for (int i = n - 1; i >= 0; i--) { if (A[i] > prevHeight) { area += curArea; curArea = 0; prevHeight = A[i]; } else { curArea += (prevHeight - A[i]); } } return area; } }; }
lmdelbahia/TFProtocol
tfprotocol/v2.4.1/src/com/nerox/client/connection/Easyproxy.java
package com.nerox.client.connection; import java.net.*; import java.util.HashMap; public class Easyproxy { public static HashMap<Proxy.Type, InetSocketAddress> parse_address(String address){ HashMap<Proxy.Type, InetSocketAddress> res = new HashMap<>(); String proto; String user = ""; String pass = ""; String addr; int port; proto = address.split("://")[0].trim().toUpperCase(); address = address.replaceFirst(proto.toLowerCase()+"://",""); if (address.contains("@")) { user = address.split("@")[0].split(":")[0]; pass = address.split("@")[0].split(":")[1]; address = address.replaceFirst(user+":"+pass+"@",""); Authenticator.setDefault( new Auth(user, pass) ); System.setProperty("http.proxyUser", user); System.setProperty("http.proxyPassword", <PASSWORD>); //System.setProperty("http.auth.preference","basic"); System.setProperty("jdk.http.auth.tunneling.disabledSchemes",""); } addr = address.split(":")[0]; port = Integer.parseInt(address.split(":")[1]); res.put(Proxy.Type.valueOf(proto), InetSocketAddress.createUnresolved(addr, port)); return res; } } class Auth extends Authenticator{ final String user; final char[] pass; Auth(String user, String pass){ this.user = user; this.pass = pass.toCharArray(); } @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(this.user, this.pass); } }
fredryce/stocker
btplotting-master/btplotting/analyzer_tables/sharperatio.py
<filename>btplotting-master/btplotting/analyzer_tables/sharperatio.py from ..helper.datatable import ColummDataType def datatable(self): cols = [['', ColummDataType.STRING], ['Value', ColummDataType.FLOAT]] cols[0].append('Sharpe-Ratio') a = self.get_analysis() cols[1].append(a['sharperatio']) return 'Sharpe-Ratio', [cols]
igloo-project/artifact-listener
maven-artifact-notifier-core/src/main/java/fr/openwide/maven/artifact/notifier/core/business/project/model/ProjectVersionStatus.java
package fr.openwide.maven.artifact.notifier.core.business.project.model; public enum ProjectVersionStatus { IN_PROGRESS, PUBLISHED_ON_MAVEN_CENTRAL }
Criss-zhang/JavaStudy
src/package02/homework/Cart.java
package package02.homework; public class Cart extends Car { public double weight; public int carLong; public Cart(int wheels,double weight){ super(wheels); this.weight = weight; } @Override int getLong(int carLong) { return carLong; } }
spunkmars/django-aops
aops/cmdb/forms/contacts.py
#coding=utf-8 from django import forms from django.utils.translation import ugettext_lazy as _ from django.utils.translation import string_concat from libs.forms.common import newModelForm, newChoiceField class ContactsForm(newModelForm): name = forms.CharField(max_length=255, label=string_concat(_('Contact')," ", _('name')), widget=forms.TextInput(attrs={'class':'form-control'})) job_titles = forms.CharField(max_length=255, label=_('Job titles'), widget=forms.TextInput(attrs={'class':'form-control'})) company = newChoiceField(choices=(), label= _('Company'), widget=forms.Select(attrs={'class':'form-control'})) mail = forms.EmailField(max_length=255, label=_('Email'), required=False, widget=forms.EmailInput(attrs={'class':'form-control'})) im_num = forms.CharField(max_length=255, label=_('IM'), required=False, widget=forms.TextInput(attrs={'class':'form-control'})) phone = forms.CharField(max_length=255, label=_('Phone'), required=False, widget=forms.TextInput(attrs={'class':'form-control'})) mobile_phone = forms.CharField(max_length=255, label=_('Mobile phone'), widget=forms.TextInput(attrs={'class':'form-control'})) address = forms.CharField(max_length=255, label=_('Address'), required=False, widget=forms.TextInput(attrs={'class':'form-control'})) comment = forms.CharField(max_length=255, label=_('Comment'), required=False, widget=forms.TextInput(attrs={'class':'form-control'}))
Hics0000/Console-Based-Cpp-Programs
Lab-Assignments/Data-Structure-Lab/Assignment-6/Question-4.cpp
#include <bits/stdc++.h> using namespace std; class node { public: int val; int freq; node *l, *r; node() { l = r = NULL; val = freq = 0; } node(int x) { val = x; freq = 1; l = r = NULL; } }; void in(node *r) { if (r == NULL) return; in(r->l); cout << r->val << " "; in(r->r); } node *insert_val(int x, node *r) { if (r == NULL) { node *new_n = new node(x); return new_n; } else if (r->val == x) { r->freq++; return r; } else if (r->val > x) r->l = insert_val(x, r->l); else r->r = insert_val(x, r->r); } node *successor(node *h) { if (h->l == NULL) return h; else return successor(h->l); } node *remove(int x, node *r) { if (r == NULL) return r; else if (r->val == x) { if (r->freq > 1) { r->freq--; return r; } if (r->l == NULL && r->r == NULL) return NULL; else if (r->r == NULL) r->l; else if (r->l == NULL) return r->r; else { node *suc = successor(r->r); r->val = suc->val; r->r = remove(suc->val, r->r); return r; } } else if (r->val > x) r->l = remove(x, r->l); else r->r = remove(x, r->r); } int main() { int n, x; cin >> n; node *h; for (int i = 0; i < n; ++i) { cin >> x; h = insert_val(x, h); } }
maze-runnar/modal-component
modal/node_modules/@storybook/ui/dist/libs/shortcut.js
"use strict"; require("core-js/modules/es.array.find"); require("core-js/modules/es.array.includes"); require("core-js/modules/es.array.join"); require("core-js/modules/es.array.map"); require("core-js/modules/es.object.define-property"); require("core-js/modules/es.regexp.exec"); require("core-js/modules/es.string.match"); Object.defineProperty(exports, "__esModule", { value: true }); exports.shortcutToHumanString = exports.keyToSymbol = exports.eventMatchesShortcut = exports.shortcutMatchesShortcut = exports.eventToShortcut = exports.isShortcutTaken = exports.optionOrAltSymbol = exports.controlOrMetaKey = exports.controlOrMetaSymbol = exports.isMacLike = void 0; var _global = require("global"); // The shortcut is our JSON-ifiable representation of a shortcut combination var isMacLike = function isMacLike() { return _global.navigator && _global.navigator.platform ? !!_global.navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) : false; }; exports.isMacLike = isMacLike; var controlOrMetaSymbol = function controlOrMetaSymbol() { return isMacLike() ? '⌘' : 'ctrl'; }; exports.controlOrMetaSymbol = controlOrMetaSymbol; var controlOrMetaKey = function controlOrMetaKey() { return isMacLike() ? 'meta' : 'control'; }; exports.controlOrMetaKey = controlOrMetaKey; var optionOrAltSymbol = function optionOrAltSymbol() { return isMacLike() ? '⌥' : 'alt'; }; exports.optionOrAltSymbol = optionOrAltSymbol; var isShortcutTaken = function isShortcutTaken(arr1, arr2) { return JSON.stringify(arr1) === JSON.stringify(arr2); }; // Map a keyboard event to a keyboard shortcut // NOTE: if we change the fields on the event that we need, we'll need to update the serialization in core/preview/start.js exports.isShortcutTaken = isShortcutTaken; var eventToShortcut = function eventToShortcut(e) { // Meta key only doesn't map to a shortcut if (['Meta', 'Alt', 'Control', 'Shift'].includes(e.key)) { return null; } var keys = []; if (e.altKey) { keys.push('alt'); } if (e.ctrlKey) { keys.push('control'); } if (e.metaKey) { keys.push('meta'); } if (e.shiftKey) { keys.push('shift'); } if (e.key && e.key.length === 1 && e.key !== ' ') { keys.push(e.key.toUpperCase()); } if (e.key === ' ') { keys.push('space'); } if (e.key === 'Escape') { keys.push('escape'); } if (e.key === 'ArrowRight') { keys.push('ArrowRight'); } if (e.key === 'ArrowDown') { keys.push('ArrowDown'); } if (e.key === 'ArrowUp') { keys.push('ArrowUp'); } if (e.key === 'ArrowLeft') { keys.push('ArrowLeft'); } return keys.length > 0 ? keys : null; }; exports.eventToShortcut = eventToShortcut; var shortcutMatchesShortcut = function shortcutMatchesShortcut(inputShortcut, shortcut) { return inputShortcut && inputShortcut.length === shortcut.length && !inputShortcut.find(function (key, i) { return key !== shortcut[i]; }); }; // Should this keyboard event trigger this keyboard shortcut? exports.shortcutMatchesShortcut = shortcutMatchesShortcut; var eventMatchesShortcut = function eventMatchesShortcut(e, shortcut) { return shortcutMatchesShortcut(eventToShortcut(e), shortcut); }; exports.eventMatchesShortcut = eventMatchesShortcut; var keyToSymbol = function keyToSymbol(key) { if (key === 'alt') { return optionOrAltSymbol(); } if (key === 'control') { return '⌃'; } if (key === 'meta') { return '⌘'; } if (key === 'shift') { return '⇧​'; } if (key === 'Enter' || key === 'Backspace' || key === 'Esc') { return ''; } if (key === 'escape') { return ''; } if (key === ' ') { return 'SPACE'; } if (key === 'ArrowUp') { return '↑'; } if (key === 'ArrowDown') { return '↓'; } if (key === 'ArrowLeft') { return '←'; } if (key === 'ArrowRight') { return '→'; } return key.toUpperCase(); }; // Display the shortcut as a human readable string exports.keyToSymbol = keyToSymbol; var shortcutToHumanString = function shortcutToHumanString(shortcut) { return shortcut.map(keyToSymbol).join(' '); }; exports.shortcutToHumanString = shortcutToHumanString;
gKouros/my_arduino_sketches
libraries/ros_lib/stdr_msgs/ThermalSourceVector.h
#ifndef _ROS_stdr_msgs_ThermalSourceVector_h #define _ROS_stdr_msgs_ThermalSourceVector_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "stdr_msgs/ThermalSource.h" namespace stdr_msgs { class ThermalSourceVector : public ros::Msg { public: uint8_t thermal_sources_length; stdr_msgs::ThermalSource st_thermal_sources; stdr_msgs::ThermalSource * thermal_sources; ThermalSourceVector(): thermal_sources_length(0), thermal_sources(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset++) = thermal_sources_length; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = 0; for( uint8_t i = 0; i < thermal_sources_length; i++){ offset += this->thermal_sources[i].serialize(outbuffer + offset); } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint8_t thermal_sources_lengthT = *(inbuffer + offset++); if(thermal_sources_lengthT > thermal_sources_length) this->thermal_sources = (stdr_msgs::ThermalSource*)realloc(this->thermal_sources, thermal_sources_lengthT * sizeof(stdr_msgs::ThermalSource)); offset += 3; thermal_sources_length = thermal_sources_lengthT; for( uint8_t i = 0; i < thermal_sources_length; i++){ offset += this->st_thermal_sources.deserialize(inbuffer + offset); memcpy( &(this->thermal_sources[i]), &(this->st_thermal_sources), sizeof(stdr_msgs::ThermalSource)); } return offset; } const char * getType(){ return "stdr_msgs/ThermalSourceVector"; }; const char * getMD5(){ return "dddbbf1cf2eb1ad9e8f6f398fb8b44ac"; }; }; } #endif
pip-services-archive/pip-services-runtime-java
src/org/pipservices/runtime/cache/CacheEntry.java
<filename>src/org/pipservices/runtime/cache/CacheEntry.java package org.pipservices.runtime.cache; /** * Holds cached value for in-memory cache. * * @author <NAME> * @version 1.0 * @since 2016-06-09 */ public class CacheEntry { private long _created = System.currentTimeMillis(); private String _key; private Object _value; /** * Creates instance of the cache entry. * @param key the unique key used to identify and locate the value. * @param value the cached value. */ public CacheEntry(String key, Object value) { _key = key; _value = value; } /** * Gets the unique key to identify and locate the value. * @return the value key. */ public String getKey() { return _key; } /** * Gets the cached value. * @return the currently cached value. */ public Object getValue() { return _value; } /** * Changes the cached value and updates creation time. * @param value the new cached value. */ public void setValue(Object value) { _value = value; _created = System.currentTimeMillis(); } /** * Gets time when the cached value was stored. * @return the value creation time. */ public long getCreated() { return _created; } }
ghsecuritylab/esp_alexa_idf
components/nghttp/nghttp2/lib/nghttp2_hd_huffman.h
<gh_stars>100-1000 /* * nghttp2 - HTTP/2 C Library * * Copyright (c) 2013 <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. */ #ifndef NGHTTP2_HD_HUFFMAN_H #define NGHTTP2_HD_HUFFMAN_H #ifdef HAVE_CONFIG_H #include <config.h> #endif /* HAVE_CONFIG_H */ #include <nghttp2/nghttp2.h> typedef enum { /* FSA accepts this state as the end of huffman encoding sequence. */ NGHTTP2_HUFF_ACCEPTED = 1, /* This state emits symbol */ NGHTTP2_HUFF_SYM = (1 << 1), /* If state machine reaches this state, decoding fails. */ NGHTTP2_HUFF_FAIL = (1 << 2) } nghttp2_huff_decode_flag; typedef struct { /* huffman decoding state, which is actually the node ID of internal huffman tree. We have 257 leaf nodes, but they are identical to root node other than emitting a symbol, so we have 256 internal nodes [1..255], inclusive. */ uint8_t state; /* bitwise OR of zero or more of the nghttp2_huff_decode_flag */ uint8_t flags; /* symbol if NGHTTP2_HUFF_SYM flag set */ uint8_t sym; } nghttp2_huff_decode; typedef nghttp2_huff_decode huff_decode_table_type[16]; typedef struct { /* Current huffman decoding state. We stripped leaf nodes, so the value range is [0..255], inclusive. */ uint8_t state; /* nonzero if we can say that the decoding process succeeds at this state */ uint8_t accept; } nghttp2_hd_huff_decode_context; typedef struct { /* The number of bits in this code */ uint32_t nbits; /* Huffman code aligned to LSB */ uint32_t code; } nghttp2_huff_sym; extern const nghttp2_huff_sym huff_sym_table[]; extern const nghttp2_huff_decode huff_decode_table[][16]; #endif /* NGHTTP2_HD_HUFFMAN_H */
stsnel/TESTAR_dev
testar/src/org/testar/statemodel/ConcreteStateTransition.java
<reponame>stsnel/TESTAR_dev package org.testar.statemodel; import org.testar.statemodel.persistence.Persistable; public class ConcreteStateTransition implements Persistable { // a transition is a trinity consisting of two states as endpoints and an action to tie these together private ConcreteState sourceState; private ConcreteState targetState; private ConcreteAction action; /** * Constructor * @param sourceState * @param targetState * @param action */ public ConcreteStateTransition(ConcreteState sourceState, ConcreteState targetState, ConcreteAction action) { this.sourceState = sourceState; this.targetState = targetState; this.action = action; } /** * Get the id for the source state of this transition * @return */ public String getSourceStateId() { return sourceState.getId(); } /** * Get the id for the target state of this transition * @return */ public String getTargetStateId() { return targetState.getId(); } /** * Get the id for the executed action in this transition * @return */ public String getActionId() { return action.getActionId(); } /** * Get the source state for this transition * @param sourceState */ public void setSourceState(ConcreteState sourceState) { this.sourceState = sourceState; } /** * Get the target state for this transition * @param targetState */ public void setTargetState(ConcreteState targetState) { this.targetState = targetState; } /** * Get the action for this transition * @param action */ public void setAction(ConcreteAction action) { this.action = action; } /** * Get the source state for this transition * @return */ public ConcreteState getSourceState() { return sourceState; } /** * Get the target state for this transition * @return */ public ConcreteState getTargetState() { return targetState; } /** * Get the executed action for this transition * @return */ public ConcreteAction getAction() { return action; } @Override public boolean canBeDelayed() { return true; } }
dyle71/hcs-crypt
test/unit/symmetric_cipher/test_copy.cpp
<reponame>dyle71/hcs-crypt /* * This file is part of the headcode.space crypt. * * The 'LICENSE.txt' file in the project root holds the software license. * Copyright (C) 2020-2021 headcode.space e.U. * <NAME> <<EMAIL>>, https://www.headcode.space */ #include <gtest/gtest.h> #include <headcode/crypt/crypt.hpp> #include <headcode/mem/mem.hpp> #include "shared/ipsum_lorem.hpp" TEST(SymmetricCipher_Copy, creation) { auto algo = headcode::crypt::Factory::Create("copy"); ASSERT_NE(algo.get(), nullptr); headcode::crypt::Algorithm::Description const & description = algo->GetDescription(); EXPECT_STREQ(description.name_.c_str(), "copy"); EXPECT_EQ(description.family_, headcode::crypt::Family::kSymmetricCipher); EXPECT_FALSE(description.description_short_.empty()); EXPECT_FALSE(description.description_long_.empty()); EXPECT_EQ(description.block_size_incoming_, 0ul); EXPECT_EQ(description.block_size_outgoing_, 0ul); EXPECT_EQ(description.result_size_, 0ul); EXPECT_TRUE(description.initialization_argument_.empty()); EXPECT_TRUE(description.finalization_argument_.empty()); } TEST(SymmetricCipher_Copy, simple) { auto algo = headcode::crypt::Factory::Create("copy"); ASSERT_NE(algo.get(), nullptr); auto text = std::string{"The quick brown fox jumps over the lazy dog"}; std::vector<std::byte> cipher{text.size()}; algo->Add(text, cipher); // COPY: copies from input to output EXPECT_EQ(std::memcmp(text.c_str(), cipher.data(), text.size()), 0); std::vector<std::byte> result; algo->Finalize(result); EXPECT_TRUE(result.empty()); EXPECT_TRUE(algo->IsFinalized()); } TEST(SymmetricCipher_Copy, regular) { auto algo = headcode::crypt::Factory::Create("copy"); ASSERT_NE(algo.get(), nullptr); ASSERT_STREQ(algo->GetDescription().name_.c_str(), "copy"); EXPECT_EQ(algo->Initialize(), 0); EXPECT_TRUE(algo->IsInitialized()); EXPECT_FALSE(algo->IsFinalized()); // COPY: copies from input to output std::vector<std::byte> cipher{kIpsumLoremText.size()}; algo->Add(kIpsumLoremText, cipher); EXPECT_EQ(std::memcmp(kIpsumLoremText.c_str(), cipher.data(), kIpsumLoremText.size()), 0); std::vector<std::byte> result; algo->Finalize(result); EXPECT_TRUE(result.empty()); EXPECT_TRUE(algo->IsFinalized()); } TEST(SymmetricCipher_Copy, empty) { auto algo = headcode::crypt::Factory::Create("copy"); ASSERT_NE(algo.get(), nullptr); ASSERT_STREQ(algo->GetDescription().name_.c_str(), "copy"); EXPECT_EQ(algo->Initialize(), 0); std::vector<std::byte> plain; std::vector<std::byte> cipher; algo->Add(plain, cipher); EXPECT_EQ(plain.size(), 0ul); EXPECT_EQ(cipher.size(), 0ul); std::vector<std::byte> result; ASSERT_EQ(algo->Finalize(result), 0); EXPECT_TRUE(result.empty()); EXPECT_TRUE(algo->IsFinalized()); } TEST(SymmetricCipher_Copy, noinit) { auto algo = headcode::crypt::Factory::Create("copy"); ASSERT_NE(algo.get(), nullptr); ASSERT_STREQ(algo->GetDescription().name_.c_str(), "copy"); std::vector<std::byte> cipher{kIpsumLoremText.size()}; algo->Add(kIpsumLoremText, cipher); EXPECT_EQ(std::memcmp(kIpsumLoremText.c_str(), cipher.data(), kIpsumLoremText.size()), 0); std::vector<std::byte> result; algo->Finalize(result); EXPECT_TRUE(result.empty()); EXPECT_TRUE(algo->IsFinalized()); }
qinpastor/WeatherAppJS
node_modules/rc-table/lib/utils/fixUtil.js
<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCellFixedInfo = getCellFixedInfo; function getCellFixedInfo(colStart, colEnd, columns, stickyOffsets) { var startColumn = columns[colStart] || {}; var endColumn = columns[colEnd] || {}; var fixLeft; var fixRight; if (startColumn.fixed === 'left') { fixLeft = stickyOffsets.left[colStart]; } else if (endColumn.fixed === 'right') { fixRight = stickyOffsets.right[colEnd]; } var lastFixLeft = false; var firstFixRight = false; if (fixLeft !== undefined) { var nextColumn = columns[colEnd + 1]; var nextFixLeft = nextColumn && nextColumn.fixed === 'left'; lastFixLeft = !nextFixLeft; } else if (fixRight !== undefined) { var prevColumn = columns[colStart - 1]; var prevFixRight = prevColumn && prevColumn.fixed === 'right'; firstFixRight = !prevFixRight; } return { fixLeft: fixLeft, fixRight: fixRight, lastFixLeft: lastFixLeft, firstFixRight: firstFixRight }; }
ntdatjoker/wae-thesis
wae-thesis-model-api/src/main/java/wae/thesis/indiv/api/exception/ServiceNotFoundException.java
<reponame>ntdatjoker/wae-thesis package wae.thesis.indiv.api.exception; import wae.thesis.indiv.api.item.ErrorCode; /** * Created by <NAME>. */ public class ServiceNotFoundException extends CoreException { public ServiceNotFoundException(String message, ErrorCode errorCode) { super(message, errorCode); } }
avetisk/mineral-ui
packages/mineral-ui-icons/src/IconFormatShapes.js
<reponame>avetisk/mineral-ui<filename>packages/mineral-ui-icons/src/IconFormatShapes.js /* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconFormatShapes(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/> </g> </Icon> ); } IconFormatShapes.displayName = 'IconFormatShapes'; IconFormatShapes.category = 'editor';
erikedwards4/dsp
c/ifft.kiss.c
//Does 1-D IFFT (inverse fast Fourier transform) of each vector in X along dim. //The input X is complex-valued. //The output Y has the same size as X, except along dim, where Y has length nfft. //Y is real-valued for ifft_kiss_s and ifft_kiss_d, //and complex-valued for ifft_kiss_c and ifft_kiss_z. //In the former case, X has only nonnegative freqs, so Lx = nfft/2 + 1. //If sc, then scales Y by 2.0*sqrt(2.0)/nfft, so that invertible with ifft. //This uses the fully-open-source KISS FFTS (Keep-it-simple-stupid FFT library) library //https://github.com/mborgerding/kissfft //I installed into: /opt/kissfft. //So, either use that, change the #include, and/or use the -I flag. //This definitely requires allocating Y1 and copying Y1 into Y. //However, this appears to work fine without a separate X1, //for a single FFT only; but fails for multiple FFTs, so using X1 for now. //Odd-length FFT supported, but must make X1 complex. //Double-precision is not supported! //So, I cast to float for X1, Y1 to support this, and issue a warning. #include <stdio.h> #include <stdlib.h> #include <math.h> #include "/opt/kissfft/kiss_fft.h" #include "/opt/kissfft/kiss_fft.c" #include "/opt/kissfft/kiss_fftr.h" #include "/opt/kissfft/kiss_fftr.c" #ifdef __cplusplus namespace codee { extern "C" { #endif int ifft_kiss_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc); int ifft_kiss_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc); int ifft_kiss_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc); int ifft_kiss_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc); int ifft_kiss_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc) { if (dim>3u) { fprintf(stderr,"error in ifft_kiss_s: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; const float s = sc ? 2.0f*sqrtf(0.5f*(float)nfft)/(float)nfft : 1.0f/(float)nfft; if (Lx!=nfft/2u+1u) { fprintf(stderr,"error in ifft_kiss_s: nfrqs (vec length in X) must equal nfft/2+1\n"); return 1; } if (nfft==0u || N==0u) {} else if (nfft==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X * s; } } else { //Initialize IFFT kiss_fft_cpx *X1, *Y1; X1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); Y1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); if (!X1) { fprintf(stderr,"error in ifft_kiss_s: problem with calloc. "); perror("calloc"); return 1; } if (!Y1) { fprintf(stderr,"error in ifft_kiss_s: problem with calloc. "); perror("calloc"); return 1; } kiss_fft_cfg kiss_fft_state; #ifdef __cplusplus kiss_fft_state = kiss_fft_alloc((int)nfft,1,nullptr,nullptr); #else kiss_fft_state = kiss_fft_alloc((int)nfft,1,NULL,NULL); #endif if (Lx==N) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = *X; X1->i = *++X; } X -= 2u + 2u*(1u-nfft%2u); for (size_t l=nfft-Lx; l>0u; --l, X-=2u, ++X1) { X1->r = *X; X1->i = -*(X+1u); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = Y1->r * s; } Y1 -= nfft; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=2u*Lx) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = *X; X1->i = *++X; } X -= 2u + 2u*(1u-nfft%2u); for (size_t l=nfft-Lx; l>0u; --l, X-=2u, ++X1) { X1->r = *X; X1->i = -*(X+1u); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = Y1->r * s; } Y1 -= nfft; } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=B*(nfft-1u)) { for (size_t b=B; b>0u; --b, X+=2u, Y-=K*nfft-1u) { for (size_t l=Lx; l>0u; --l, X+=2u*K, ++X1) { X1->r = *X; X1->i = *(X+1u); } X -= K*(2u + 2u*(1u-nfft%2u)); for (size_t l=nfft-Lx; l>0u; --l, X-=2u*K, ++X1) { X1->r = *X; X1->i = -*(X+1u); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, Y+=K) { *Y = Y1->r * s; } Y1 -= nfft; } } } } //Free free(kiss_fft_state); free(X1); free(Y1); } return 0; } int ifft_kiss_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc) { if (dim>3u) { fprintf(stderr,"error in ifft_kiss_d: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; const double s = sc ? 2.0*sqrt(0.5*(double)nfft)/(double)nfft : 1.0/(double)nfft; if (Lx!=nfft/2u+1u) { fprintf(stderr,"error in ifft_kiss_d: nfrqs (vec length in X) must equal nfft/2+1\n"); return 1; } //Double not directly supported! fprintf(stderr,"warning in ifft_kiss_d: double precision not directly supported, casting to float for FFT part\n"); if (nfft==0u || N==0u) {} else if (nfft==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X * s; } } else { //Initialize IFFT kiss_fft_cpx *X1, *Y1; X1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); Y1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); if (!X1) { fprintf(stderr,"error in ifft_kiss_d: problem with calloc. "); perror("calloc"); return 1; } if (!Y1) { fprintf(stderr,"error in ifft_kiss_d: problem with calloc. "); perror("calloc"); return 1; } kiss_fft_cfg kiss_fft_state; #ifdef __cplusplus kiss_fft_state = kiss_fft_alloc((int)nfft,1,nullptr,nullptr); #else kiss_fft_state = kiss_fft_alloc((int)nfft,1,NULL,NULL); #endif if (Lx==N) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = (kiss_fft_scalar)*++X; } X -= 2u + 2u*(1u-nfft%2u); for (size_t l=nfft-Lx; l>0u; --l, X-=2u, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = -(kiss_fft_scalar)*(X+1u); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = (double)Y1->r * s; } Y1 -= nfft; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, X+=2u*Lx) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = (kiss_fft_scalar)*++X; } X -= 2u + 2u*(1u-nfft%2u); for (size_t l=nfft-Lx; l>0u; --l, X-=2u, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = -(kiss_fft_scalar)*(X+1u); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = (double)Y1->r * s; } Y1 -= nfft; } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=B*(nfft-1u)) { for (size_t b=B; b>0u; --b, X+=2u, Y-=K*nfft-1u) { for (size_t l=Lx; l>0u; --l, X+=2u*K, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = (kiss_fft_scalar)*(X+1u); } X -= K*(2u + 2u*(1u-nfft%2u)); for (size_t l=nfft-Lx; l>0u; --l, X-=2u*K, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = -(kiss_fft_scalar)*(X+1u); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, Y+=K) { *Y = (double)Y1->r * s; } Y1 -= nfft; } } } } //Free free(kiss_fft_state); free(X1); free(Y1); } return 0; } int ifft_kiss_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc) { if (dim>3u) { fprintf(stderr,"error in ifft_kiss_c: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; const float s = sc ? 2.0f*sqrtf(0.5f*(float)nfft)/(float)nfft : 1.0f/(float)nfft; if (Lx!=nfft) { fprintf(stderr,"error in ifft_kiss_c: nfrqs (vec length in X) must equal nfft\n"); return 1; } if (nfft==0u || N==0u) {} else if (nfft==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X * s; } } else { //Initialize IFFT kiss_fft_cpx *X1, *Y1; X1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); Y1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); if (!X1) { fprintf(stderr,"error in ifft_kiss_c: problem with calloc. "); perror("calloc"); return 1; } if (!Y1) { fprintf(stderr,"error in ifft_kiss_c: problem with calloc. "); perror("calloc"); return 1; } kiss_fft_cfg kiss_fft_state; #ifdef __cplusplus kiss_fft_state = kiss_fft_alloc((int)nfft,1,nullptr,nullptr); #else kiss_fft_state = kiss_fft_alloc((int)nfft,1,NULL,NULL); #endif if (Lx==N) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = *X; X1->i = *++X; } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = Y1->r * s; *++Y = Y1->i * s; } Y1 -= nfft; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = *X; X1->i = *++X; } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = Y1->r * s; *++Y = Y1->i * s; } Y1 -= nfft; } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(nfft-1u)) { for (size_t b=B; b>0u; --b, X-=2u*K*Lx-2u, Y-=2u*K*nfft-2u) { for (size_t l=Lx; l>0u; --l, X+=2u*K, ++X1) { X1->r = *X; X1->i = *(X+1); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, Y+=2u*K) { *Y = Y1->r * s; *(Y+1) = Y1->i * s; } Y1 -= nfft; } } } } //Free free(kiss_fft_state); free(X1); free(Y1); } return 0; } int ifft_kiss_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t nfft, const int sc) { if (dim>3u) { fprintf(stderr,"error in ifft_kiss_z: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; const double s = sc ? 2.0*sqrt(0.5*(double)nfft)/(double)nfft : 1.0/(double)nfft; if (Lx!=nfft) { fprintf(stderr,"error in ifft_kiss_z: nfrqs (vec length in X) must equal nfft\n"); return 1; } //Double not directly supported! fprintf(stderr,"warning in ifft_kiss_z: double precision not directly supported, casting to float for FFT part\n"); if (nfft==0u || N==0u) {} else if (nfft==1u) { for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = *X * s; } } else { //Initialize IFFT kiss_fft_cpx *X1, *Y1; X1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); Y1 = (kiss_fft_cpx *)calloc(sizeof(kiss_fft_cpx),nfft*sizeof(kiss_fft_cpx)); if (!X1) { fprintf(stderr,"error in ifft_kiss_z: problem with calloc. "); perror("calloc"); return 1; } if (!Y1) { fprintf(stderr,"error in ifft_kiss_z: problem with calloc. "); perror("calloc"); return 1; } kiss_fft_cfg kiss_fft_state; #ifdef __cplusplus kiss_fft_state = kiss_fft_alloc((int)nfft,1,nullptr,nullptr); #else kiss_fft_state = kiss_fft_alloc((int)nfft,1,NULL,NULL); #endif if (Lx==N) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = (kiss_fft_scalar)*++X; } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = (double)Y1->r * s; *++Y = (double)Y1->i * s; } Y1 -= nfft; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v) { for (size_t l=Lx; l>0u; --l, ++X, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = (kiss_fft_scalar)*++X; } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, ++Y) { *Y = (double)Y1->r * s; *++Y = (double)Y1->i * s; } Y1 -= nfft; } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(nfft-1u)) { for (size_t b=B; b>0u; --b, X-=2u*K*Lx-2u, Y-=2u*K*nfft-2u) { for (size_t l=Lx; l>0u; --l, X+=2u*K, ++X1) { X1->r = (kiss_fft_scalar)*X; X1->i = (kiss_fft_scalar)*(X+1); } X1 -= nfft; kiss_fft(kiss_fft_state,X1,Y1); for (size_t l=nfft; l>0u; --l, ++Y1, Y+=2u*K) { *Y = (double)Y1->r * s; *(Y+1) = (double)Y1->i * s; } Y1 -= nfft; } } } } //Free free(kiss_fft_state); free(X1); free(Y1); } return 0; } #ifdef __cplusplus } } #endif
mphan6/30-seconds-of-code
test/httpPut/httpPut.test.js
const expect = require('expect'); const httpPut = require('./httpPut.js'); test('httpPut is a Function', () => { expect(httpPut).toBeInstanceOf(Function); });
Samuel789/MediPi
MediPiPatient/MediPi/src/main/java/org/medipi/medication/ui/ShowMedicationsMenu.java
package org.medipi.medication.ui; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Insets; import javafx.scene.input.MouseEvent; import org.medipi.MediPi; import org.medipi.medication.MedicationManager; import org.medipi.medication.model.Medication; import org.medipi.medication.model.Schedule; import org.medipi.ui.*; import java.util.*; public class ShowMedicationsMenu extends TileMenu { TileMenu mainPane; MediPi medipi; public ShowMedicationsMenu(MediPi medipi, TileMenu upperMenu) { super(new WindowManager(), 3, 2.15, upperMenu); setPadding(new Insets(15, 0, 10, 0)); DualButtonTile medTile1 = new DualButtonTile(new SimpleBooleanProperty(true), 1, 1); medTile1.setMajorText("Back"); this.medipi = medipi; medTile1.setOnMajorClick((MouseEvent event) -> { upperMenu.closeOverlayWindow(); }); medTile1.setMinorText("Help"); System.out.println(getUnitWidth()); System.out.println(this.getTargetWidth()); TileMenu sidebar = new TileMenu(getUnitWidth(), getUnitHeight() * 2, 1, 2.2, this); Tile sidebarTile = new Tile(new SimpleBooleanProperty(true), 1, 2); mainPane = new TileMenu(getUnitWidth() * 2, getUnitHeight() * 2, 2, 2.2, this); Tile mainPaneTile = new Tile(new SimpleBooleanProperty(true), 2, 2); sidebarTile.getContent().setCenter(sidebar); mainPaneTile.getContent().setCenter(mainPane); this.addTile(sidebarTile); this.addTile(mainPaneTile); sidebar.addTile(medTile1); ScrollControlTile scTile = new ScrollControlTile(new SimpleBooleanProperty(true), 1, 1); scTile.setOnUpClick((MouseEvent event) -> { mainPane.scrollUp(); }); scTile.setOnDownClick((MouseEvent event) -> { mainPane.scrollDown(); }); sidebar.addTile(scTile); sidebar.setMargin(0); populateMedicationTiles(); } private void populateMedicationTiles() { for (Schedule schedule : ((MedicationManager) medipi.getElement("Medication")).getDatestore().getActiveSchedules()) { mainPane.addTile(new MedicationTile(new SimpleBooleanProperty(true), 1, 1, schedule)); } List<Schedule> sorted_schedules = new ArrayList<>(((MedicationManager) medipi.getElement("Medication")).getDatestore().getUpcomingSchedules()); sorted_schedules.sort(Comparator.comparing(Schedule::determineDisplayName)); for (Schedule schedule : sorted_schedules) { MedicationTile tile = new MedicationTile(new SimpleBooleanProperty(true), 1, 1, schedule); tile.setUpcoming(true); mainPane.addTile(tile); } } }
tonioshikanlu/tubman-hack
sources/androidx/transition/Visibility.java
<filename>sources/androidx/transition/Visibility.java package androidx.transition; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.core.content.res.TypedArrayUtils; import androidx.transition.AnimatorUtils; import androidx.transition.Transition; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public abstract class Visibility extends Transition { public static final int MODE_IN = 1; public static final int MODE_OUT = 2; private static final String PROPNAME_PARENT = "android:visibility:parent"; private static final String PROPNAME_SCREEN_LOCATION = "android:visibility:screenLocation"; public static final String PROPNAME_VISIBILITY = "android:visibility:visibility"; private static final String[] sTransitionProperties = {PROPNAME_VISIBILITY, PROPNAME_PARENT}; private int mMode = 3; public static class DisappearListener extends AnimatorListenerAdapter implements Transition.TransitionListener, AnimatorUtils.AnimatorPauseListenerCompat { public boolean mCanceled = false; private final int mFinalVisibility; private boolean mLayoutSuppressed; private final ViewGroup mParent; private final boolean mSuppressLayout; private final View mView; public DisappearListener(View view, int i2, boolean z) { this.mView = view; this.mFinalVisibility = i2; this.mParent = (ViewGroup) view.getParent(); this.mSuppressLayout = z; suppressLayout(true); } private void hideViewWhenNotCanceled() { if (!this.mCanceled) { ViewUtils.setTransitionVisibility(this.mView, this.mFinalVisibility); ViewGroup viewGroup = this.mParent; if (viewGroup != null) { viewGroup.invalidate(); } } suppressLayout(false); } private void suppressLayout(boolean z) { ViewGroup viewGroup; if (this.mSuppressLayout && this.mLayoutSuppressed != z && (viewGroup = this.mParent) != null) { this.mLayoutSuppressed = z; ViewGroupUtils.suppressLayout(viewGroup, z); } } public void onAnimationCancel(Animator animator) { this.mCanceled = true; } public void onAnimationEnd(Animator animator) { hideViewWhenNotCanceled(); } public void onAnimationPause(Animator animator) { if (!this.mCanceled) { ViewUtils.setTransitionVisibility(this.mView, this.mFinalVisibility); } } public void onAnimationRepeat(Animator animator) { } public void onAnimationResume(Animator animator) { if (!this.mCanceled) { ViewUtils.setTransitionVisibility(this.mView, 0); } } public void onAnimationStart(Animator animator) { } public void onTransitionCancel(@NonNull Transition transition) { } public void onTransitionEnd(@NonNull Transition transition) { hideViewWhenNotCanceled(); transition.removeListener(this); } public void onTransitionPause(@NonNull Transition transition) { suppressLayout(false); } public void onTransitionResume(@NonNull Transition transition) { suppressLayout(true); } public void onTransitionStart(@NonNull Transition transition) { } } @SuppressLint({"UniqueConstants"}) @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP_PREFIX}) @Retention(RetentionPolicy.SOURCE) public @interface Mode { } public static class VisibilityInfo { public ViewGroup mEndParent; public int mEndVisibility; public boolean mFadeIn; public ViewGroup mStartParent; public int mStartVisibility; public boolean mVisibilityChange; } public Visibility() { } @SuppressLint({"RestrictedApi"}) public Visibility(Context context, AttributeSet attributeSet) { super(context, attributeSet); TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, Styleable.VISIBILITY_TRANSITION); int namedInt = TypedArrayUtils.getNamedInt(obtainStyledAttributes, (XmlResourceParser) attributeSet, "transitionVisibilityMode", 0, 0); obtainStyledAttributes.recycle(); if (namedInt != 0) { setMode(namedInt); } } private void captureValues(TransitionValues transitionValues) { transitionValues.values.put(PROPNAME_VISIBILITY, Integer.valueOf(transitionValues.view.getVisibility())); transitionValues.values.put(PROPNAME_PARENT, transitionValues.view.getParent()); int[] iArr = new int[2]; transitionValues.view.getLocationOnScreen(iArr); transitionValues.values.put(PROPNAME_SCREEN_LOCATION, iArr); } /* JADX WARNING: Code restructure failed: missing block: B:21:0x0075, code lost: if (r9 == 0) goto L_0x0088; */ /* JADX WARNING: Code restructure failed: missing block: B:25:0x007f, code lost: if (r0.mStartParent == null) goto L_0x0088; */ /* JADX WARNING: Code restructure failed: missing block: B:33:0x0091, code lost: if (r0.mStartVisibility == 0) goto L_0x0093; */ /* Code decompiled incorrectly, please refer to instructions dump. */ private androidx.transition.Visibility.VisibilityInfo getVisibilityChangeInfo(androidx.transition.TransitionValues r8, androidx.transition.TransitionValues r9) { /* r7 = this; androidx.transition.Visibility$VisibilityInfo r0 = new androidx.transition.Visibility$VisibilityInfo r0.<init>() r1 = 0 r0.mVisibilityChange = r1 r0.mFadeIn = r1 java.lang.String r2 = "android:visibility:parent" r3 = 0 r4 = -1 java.lang.String r5 = "android:visibility:visibility" if (r8 == 0) goto L_0x0033 java.util.Map<java.lang.String, java.lang.Object> r6 = r8.values boolean r6 = r6.containsKey(r5) if (r6 == 0) goto L_0x0033 java.util.Map<java.lang.String, java.lang.Object> r6 = r8.values java.lang.Object r6 = r6.get(r5) java.lang.Integer r6 = (java.lang.Integer) r6 int r6 = r6.intValue() r0.mStartVisibility = r6 java.util.Map<java.lang.String, java.lang.Object> r6 = r8.values java.lang.Object r6 = r6.get(r2) android.view.ViewGroup r6 = (android.view.ViewGroup) r6 r0.mStartParent = r6 goto L_0x0037 L_0x0033: r0.mStartVisibility = r4 r0.mStartParent = r3 L_0x0037: if (r9 == 0) goto L_0x005a java.util.Map<java.lang.String, java.lang.Object> r6 = r9.values boolean r6 = r6.containsKey(r5) if (r6 == 0) goto L_0x005a java.util.Map<java.lang.String, java.lang.Object> r3 = r9.values java.lang.Object r3 = r3.get(r5) java.lang.Integer r3 = (java.lang.Integer) r3 int r3 = r3.intValue() r0.mEndVisibility = r3 java.util.Map<java.lang.String, java.lang.Object> r3 = r9.values java.lang.Object r2 = r3.get(r2) android.view.ViewGroup r2 = (android.view.ViewGroup) r2 r0.mEndParent = r2 goto L_0x005e L_0x005a: r0.mEndVisibility = r4 r0.mEndParent = r3 L_0x005e: r2 = 1 if (r8 == 0) goto L_0x0082 if (r9 == 0) goto L_0x0082 int r8 = r0.mStartVisibility int r9 = r0.mEndVisibility if (r8 != r9) goto L_0x0070 android.view.ViewGroup r3 = r0.mStartParent android.view.ViewGroup r4 = r0.mEndParent if (r3 != r4) goto L_0x0070 return r0 L_0x0070: if (r8 == r9) goto L_0x0078 if (r8 != 0) goto L_0x0075 goto L_0x0093 L_0x0075: if (r9 != 0) goto L_0x0096 goto L_0x0088 L_0x0078: android.view.ViewGroup r8 = r0.mEndParent if (r8 != 0) goto L_0x007d goto L_0x0093 L_0x007d: android.view.ViewGroup r8 = r0.mStartParent if (r8 != 0) goto L_0x0096 goto L_0x0088 L_0x0082: if (r8 != 0) goto L_0x008d int r8 = r0.mEndVisibility if (r8 != 0) goto L_0x008d L_0x0088: r0.mFadeIn = r2 L_0x008a: r0.mVisibilityChange = r2 goto L_0x0096 L_0x008d: if (r9 != 0) goto L_0x0096 int r8 = r0.mStartVisibility if (r8 != 0) goto L_0x0096 L_0x0093: r0.mFadeIn = r1 goto L_0x008a L_0x0096: return r0 */ throw new UnsupportedOperationException("Method not decompiled: androidx.transition.Visibility.getVisibilityChangeInfo(androidx.transition.TransitionValues, androidx.transition.TransitionValues):androidx.transition.Visibility$VisibilityInfo"); } public void captureEndValues(@NonNull TransitionValues transitionValues) { captureValues(transitionValues); } public void captureStartValues(@NonNull TransitionValues transitionValues) { captureValues(transitionValues); } @Nullable public Animator createAnimator(@NonNull ViewGroup viewGroup, @Nullable TransitionValues transitionValues, @Nullable TransitionValues transitionValues2) { VisibilityInfo visibilityChangeInfo = getVisibilityChangeInfo(transitionValues, transitionValues2); if (!visibilityChangeInfo.mVisibilityChange) { return null; } if (visibilityChangeInfo.mStartParent == null && visibilityChangeInfo.mEndParent == null) { return null; } if (visibilityChangeInfo.mFadeIn) { return onAppear(viewGroup, transitionValues, visibilityChangeInfo.mStartVisibility, transitionValues2, visibilityChangeInfo.mEndVisibility); } return onDisappear(viewGroup, transitionValues, visibilityChangeInfo.mStartVisibility, transitionValues2, visibilityChangeInfo.mEndVisibility); } public int getMode() { return this.mMode; } @Nullable public String[] getTransitionProperties() { return sTransitionProperties; } public boolean isTransitionRequired(TransitionValues transitionValues, TransitionValues transitionValues2) { if (transitionValues == null && transitionValues2 == null) { return false; } if (transitionValues != null && transitionValues2 != null && transitionValues2.values.containsKey(PROPNAME_VISIBILITY) != transitionValues.values.containsKey(PROPNAME_VISIBILITY)) { return false; } VisibilityInfo visibilityChangeInfo = getVisibilityChangeInfo(transitionValues, transitionValues2); if (visibilityChangeInfo.mVisibilityChange) { return visibilityChangeInfo.mStartVisibility == 0 || visibilityChangeInfo.mEndVisibility == 0; } return false; } public boolean isVisible(TransitionValues transitionValues) { if (transitionValues == null) { return false; } return ((Integer) transitionValues.values.get(PROPNAME_VISIBILITY)).intValue() == 0 && ((View) transitionValues.values.get(PROPNAME_PARENT)) != null; } public Animator onAppear(ViewGroup viewGroup, View view, TransitionValues transitionValues, TransitionValues transitionValues2) { return null; } public Animator onAppear(ViewGroup viewGroup, TransitionValues transitionValues, int i2, TransitionValues transitionValues2, int i3) { if ((this.mMode & 1) != 1 || transitionValues2 == null) { return null; } if (transitionValues == null) { View view = (View) transitionValues2.view.getParent(); if (getVisibilityChangeInfo(getMatchedTransitionValues(view, false), getTransitionValues(view, false)).mVisibilityChange) { return null; } } return onAppear(viewGroup, transitionValues2.view, transitionValues, transitionValues2); } public Animator onDisappear(ViewGroup viewGroup, View view, TransitionValues transitionValues, TransitionValues transitionValues2) { return null; } /* JADX WARNING: Code restructure failed: missing block: B:37:0x0089, code lost: if (r0.mCanRemoveViews != false) goto L_0x008b; */ /* JADX WARNING: Removed duplicated region for block: B:23:0x004a */ /* Code decompiled incorrectly, please refer to instructions dump. */ public android.animation.Animator onDisappear(android.view.ViewGroup r18, androidx.transition.TransitionValues r19, int r20, androidx.transition.TransitionValues r21, int r22) { /* r17 = this; r0 = r17 r1 = r18 r2 = r19 r3 = r21 r4 = r22 int r5 = r0.mMode r6 = 2 r5 = r5 & r6 r7 = 0 if (r5 == r6) goto L_0x0012 return r7 L_0x0012: if (r2 != 0) goto L_0x0015 return r7 L_0x0015: android.view.View r5 = r2.view if (r3 == 0) goto L_0x001c android.view.View r8 = r3.view goto L_0x001d L_0x001c: r8 = r7 L_0x001d: int r9 = androidx.transition.R.id.save_overlay_view java.lang.Object r10 = r5.getTag(r9) android.view.View r10 = (android.view.View) r10 r11 = 0 r12 = 1 if (r10 == 0) goto L_0x002d r8 = r7 r13 = r12 goto L_0x0095 L_0x002d: if (r8 == 0) goto L_0x0040 android.view.ViewParent r10 = r8.getParent() if (r10 != 0) goto L_0x0036 goto L_0x0040 L_0x0036: r10 = 4 if (r4 != r10) goto L_0x003a goto L_0x003c L_0x003a: if (r5 != r8) goto L_0x0045 L_0x003c: r10 = r8 r13 = r11 r8 = r7 goto L_0x0048 L_0x0040: if (r8 == 0) goto L_0x0045 r10 = r7 r13 = r11 goto L_0x0048 L_0x0045: r8 = r7 r10 = r8 r13 = r12 L_0x0048: if (r13 == 0) goto L_0x008f android.view.ViewParent r13 = r5.getParent() if (r13 != 0) goto L_0x0051 goto L_0x008b L_0x0051: android.view.ViewParent r13 = r5.getParent() boolean r13 = r13 instanceof android.view.View if (r13 == 0) goto L_0x008f android.view.ViewParent r13 = r5.getParent() android.view.View r13 = (android.view.View) r13 androidx.transition.TransitionValues r14 = r0.getTransitionValues(r13, r12) androidx.transition.TransitionValues r15 = r0.getMatchedTransitionValues(r13, r12) androidx.transition.Visibility$VisibilityInfo r14 = r0.getVisibilityChangeInfo(r14, r15) boolean r14 = r14.mVisibilityChange if (r14 != 0) goto L_0x0074 android.view.View r8 = androidx.transition.TransitionUtils.copyViewImage(r1, r5, r13) goto L_0x008f L_0x0074: int r14 = r13.getId() android.view.ViewParent r13 = r13.getParent() if (r13 != 0) goto L_0x008f r13 = -1 if (r14 == r13) goto L_0x008f android.view.View r13 = r1.findViewById(r14) if (r13 == 0) goto L_0x008f boolean r13 = r0.mCanRemoveViews if (r13 == 0) goto L_0x008f L_0x008b: r8 = r10 r13 = r11 r10 = r5 goto L_0x0095 L_0x008f: r13 = r11 r16 = r10 r10 = r8 r8 = r16 L_0x0095: if (r10 == 0) goto L_0x00e5 if (r13 != 0) goto L_0x00c9 java.util.Map<java.lang.String, java.lang.Object> r4 = r2.values java.lang.String r7 = "android:visibility:screenLocation" java.lang.Object r4 = r4.get(r7) int[] r4 = (int[]) r4 r7 = r4[r11] r4 = r4[r12] int[] r6 = new int[r6] r1.getLocationOnScreen(r6) r8 = r6[r11] int r7 = r7 - r8 int r8 = r10.getLeft() int r7 = r7 - r8 r10.offsetLeftAndRight(r7) r6 = r6[r12] int r4 = r4 - r6 int r6 = r10.getTop() int r4 = r4 - r6 r10.offsetTopAndBottom(r4) androidx.transition.ViewGroupOverlayImpl r4 = androidx.transition.ViewGroupUtils.getOverlay(r18) r4.add(r10) L_0x00c9: android.animation.Animator r2 = r0.onDisappear(r1, r10, r2, r3) if (r13 != 0) goto L_0x00e4 if (r2 != 0) goto L_0x00d9 androidx.transition.ViewGroupOverlayImpl r1 = androidx.transition.ViewGroupUtils.getOverlay(r18) r1.remove(r10) goto L_0x00e4 L_0x00d9: r5.setTag(r9, r10) androidx.transition.Visibility$1 r3 = new androidx.transition.Visibility$1 r3.<init>(r1, r10, r5) r0.addListener(r3) L_0x00e4: return r2 L_0x00e5: if (r8 == 0) goto L_0x0107 int r5 = r8.getVisibility() androidx.transition.ViewUtils.setTransitionVisibility(r8, r11) android.animation.Animator r1 = r0.onDisappear(r1, r8, r2, r3) if (r1 == 0) goto L_0x0103 androidx.transition.Visibility$DisappearListener r2 = new androidx.transition.Visibility$DisappearListener r2.<init>(r8, r4, r12) r1.addListener(r2) androidx.transition.AnimatorUtils.addPauseListener(r1, r2) r0.addListener(r2) goto L_0x0106 L_0x0103: androidx.transition.ViewUtils.setTransitionVisibility(r8, r5) L_0x0106: return r1 L_0x0107: return r7 */ throw new UnsupportedOperationException("Method not decompiled: androidx.transition.Visibility.onDisappear(android.view.ViewGroup, androidx.transition.TransitionValues, int, androidx.transition.TransitionValues, int):android.animation.Animator"); } public void setMode(int i2) { if ((i2 & -4) == 0) { this.mMode = i2; return; } throw new IllegalArgumentException("Only MODE_IN and MODE_OUT flags are allowed"); } }
changwookyou/ckeditor5
packages/ckeditor5-basic-styles/tests/code/codeui.js
/** * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ /* globals document */ import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor'; import CodeEditing from '../../src/code/codeediting'; import CodeUI from '../../src/code/codeui'; import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview'; import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils'; import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph'; describe( 'CodeUI', () => { let editor, codeView, editorElement; testUtils.createSinonSandbox(); beforeEach( () => { editorElement = document.createElement( 'div' ); document.body.appendChild( editorElement ); return ClassicTestEditor .create( editorElement, { plugins: [ Paragraph, CodeEditing, CodeUI ] } ) .then( newEditor => { editor = newEditor; codeView = editor.ui.componentFactory.create( 'code' ); } ); } ); afterEach( () => { editorElement.remove(); return editor.destroy(); } ); it( 'should register code feature component', () => { expect( codeView ).to.be.instanceOf( ButtonView ); expect( codeView.isOn ).to.be.false; expect( codeView.label ).to.equal( 'Code' ); expect( codeView.icon ).to.match( /<svg / ); expect( codeView.isToggleable ).to.be.true; } ); it( 'should execute code command on model execute event', () => { const executeSpy = testUtils.sinon.spy( editor, 'execute' ); codeView.fire( 'execute' ); sinon.assert.calledOnce( executeSpy ); sinon.assert.calledWithExactly( executeSpy, 'code' ); } ); it( 'should bind model to code command', () => { const command = editor.commands.get( 'code' ); expect( codeView.isOn ).to.be.false; expect( codeView.isEnabled ).to.be.true; command.value = true; expect( codeView.isOn ).to.be.true; command.isEnabled = false; expect( codeView.isEnabled ).to.be.false; } ); } );
r-neal-kelly/nkr
nkr_tests/maybe_t/src/maybe_t_user_defined_sp.cpp
<gh_stars>0 /* Copyright 2021 r-neal-kelly */ #include "nkr/z_bool_t.h" #include "nkr/z_intrinsics.h" #include "nkr/z_maybe_t.h" #include "nkr/z_utils.h" #include "doctest.h" namespace nkr { TEST_SUITE("maybe_t<user_defined_p>") { #define nkr_ALL_PARAMS(QUALIFIER_p, UNIT_p) \ QUALIFIER_p maybe_t<UNIT_p>, \ QUALIFIER_p maybe_t<const UNIT_p>, \ QUALIFIER_p maybe_t<volatile UNIT_p>, \ QUALIFIER_p maybe_t<const volatile UNIT_p> #define nkr_VALUES(QUALIFIER_p) \ nkr_ALL_PARAMS(QUALIFIER_p, bool_t) #define nkr_NON_QUALIFIED \ nkr_VALUES(nkr_BLANK) #define nkr_NON_CONST \ nkr_VALUES(nkr_BLANK), \ nkr_VALUES(volatile) #define nkr_CONST \ nkr_VALUES(const), \ nkr_VALUES(const volatile) #define nkr_ALL \ nkr_NON_CONST, \ nkr_CONST TEST_SUITE("aliases") { TEST_SUITE("value_t") { TEST_CASE_TEMPLATE("should have a value_t", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; static_assert(is_tr<value_t, value_t>); } } } TEST_SUITE("objects") { TEST_SUITE("default_ctor()") { TEST_CASE_TEMPLATE("should equal the default value", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t value; maybe_p maybe; CHECK(maybe == value); } TEST_CASE_TEMPLATE("may equal none_t()", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; maybe_p maybe; if (maybe == none_t()) { CHECK(maybe == none_t()); } } } TEST_SUITE("copy_ctor()") { TEST_CASE_TEMPLATE("should copy another", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); maybe_p other = random; maybe_p maybe = other; CHECK(maybe == other); CHECK(other == random); } TEST_CASE_TEMPLATE("should copy another value", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); value_t other = random; maybe_p maybe = other; CHECK(maybe == other); CHECK(other == random); } } TEST_SUITE("move_ctor()") { TEST_CASE_TEMPLATE("should move another, setting it to none_t()", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; if constexpr (any_non_const_tr<value_t>) { value_t random = Random<value_t>(); std::remove_const_t<maybe_p> other = random; maybe_p maybe = nkr::Move(other); CHECK(maybe == random); CHECK(other == none_t()); } } TEST_CASE_TEMPLATE("should move another value, setting it to none_t()", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); std::remove_const_t<value_t> other = random; maybe_p maybe = nkr::Move(other); CHECK(maybe == random); CHECK(other == none_t()); } } TEST_SUITE("copy_assignment_ctor()") { TEST_CASE_TEMPLATE("should copy another", maybe_p, nkr_NON_CONST) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); std::add_const_t<maybe_p> other = random; maybe_p maybe; maybe = other; CHECK(maybe == other); CHECK(other == random); } TEST_CASE_TEMPLATE("should copy another value", maybe_p, nkr_NON_CONST) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); std::add_const_t<value_t> other = random; maybe_p maybe; maybe = other; CHECK(maybe == other); CHECK(other == random); } } TEST_SUITE("move_assignment_ctor()") { TEST_CASE_TEMPLATE("should move another, setting it to none_t()", maybe_p, nkr_NON_CONST) { using value_t = maybe_p::value_t; if constexpr (any_non_const_tr<value_t>) { value_t random = Random<value_t>(); maybe_p other = random; maybe_p maybe; maybe = nkr::Move(other); CHECK(maybe == random); CHECK(other == none_t()); } } TEST_CASE_TEMPLATE("should move another value, setting it to none_t()", maybe_p, nkr_NON_CONST) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); std::remove_const_t<value_t> other = random; maybe_p maybe; maybe = nkr::Move(other); CHECK(maybe == random); CHECK(other == none_t()); } } TEST_SUITE("dtor()") { TEST_CASE_TEMPLATE("may set the value to none_t()", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); maybe_p maybe = random; maybe.~maybe_p(); if (maybe == none_t()) { CHECK(maybe == none_t()); } } } } TEST_SUITE("casts") { TEST_SUITE("value_t") { TEST_CASE_TEMPLATE("should explicitly return a reference to its value", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); maybe_p maybe = random; if constexpr (just_non_qualified_tr<maybe_p>) { CHECK(static_cast<value_t&>(maybe) == random); } else if constexpr (just_const_tr<maybe_p>) { CHECK(static_cast<const value_t&>(maybe) == random); } else if constexpr (just_volatile_tr<maybe_p>) { CHECK(static_cast<volatile value_t&>(maybe) == random); } else if constexpr (just_const_volatile_tr<maybe_p>) { CHECK(static_cast<const volatile value_t&>(maybe) == random); } } TEST_CASE_TEMPLATE("should implicitly return a reference to its value", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); maybe_p maybe = random; CHECK(maybe == random); } TEST_CASE_TEMPLATE("should be able to alter non-const values", maybe_p, nkr_NON_CONST) { using value_t = maybe_p::value_t; if constexpr (any_non_const_tr<value_t>) { value_t random_a = Random<value_t>(); value_t random_b = Random<value_t>(); maybe_p maybe = random_a; if constexpr (just_non_qualified_tr<maybe_p>) { static_cast<value_t&>(maybe) = random_b; } else if constexpr (just_const_tr<maybe_p>) { static_cast<const value_t&>(maybe) = random_b; } else if constexpr (just_volatile_tr<maybe_p>) { static_cast<volatile value_t&>(maybe) = random_b; } else if constexpr (just_const_volatile_tr<maybe_p>) { static_cast<const volatile value_t&>(maybe) = random_b; } CHECK(maybe == random_b); } } TEST_CASE_TEMPLATE("should implicitly allow for base_t constructors", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; if constexpr (is_any_tr<value_t, bool_t>) { c_bool_t random = Random<c_bool_t>(); maybe_p maybe(random); CHECK(maybe == random); } } TEST_CASE_TEMPLATE("should implicitly allow for logical operators", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; if constexpr (is_any_tr<value_t, bool_t>) { maybe_p maybe(true); CHECK(maybe); CHECK(!!maybe); CHECK(maybe || false); CHECK(maybe && true); CHECK((maybe ? true : false)); } } TEST_CASE_TEMPLATE("should implicitly allow for comparison operators", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; if constexpr (is_any_tr<value_t, bool_t>) { value_t random = Random<value_t>(); maybe_p maybe(random); CHECK(maybe == random); CHECK_FALSE(maybe != random); } } } TEST_SUITE("c_bool_t") { TEST_CASE_TEMPLATE("should cast to true if its underlying value does not equal none_t()", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); maybe_p maybe = random; if (random != none_t()) { CHECK(maybe); } else { CHECK(!maybe); } } } } TEST_SUITE("operators") { TEST_SUITE("()()") { TEST_CASE_TEMPLATE("should return a reference to its value", maybe_p, nkr_ALL) { using value_t = maybe_p::value_t; value_t random = Random<value_t>(); maybe_p maybe = random; CHECK(maybe() == random); } TEST_CASE_TEMPLATE("should be able to alter its value", maybe_p, nkr_NON_CONST) { using value_t = maybe_p::value_t; if constexpr (not_any_const_tr<value_t>) { value_t random_a = Random<value_t>(); value_t random_b = Random<value_t>(); maybe_p maybe = random_a; maybe() = random_b; CHECK(maybe == random_b); } } } } } }
wobushiren79/VedioChat
app/src/main/java/com/huanmedia/videochat/pay/MyAccountPresenter.java
<reponame>wobushiren79/VedioChat<gh_stars>0 package com.huanmedia.videochat.pay; import com.huanmedia.ilibray.utils.data.assist.Check; import com.huanmedia.videochat.common.manager.UserManager; import com.huanmedia.videochat.common.widget.dialog.HintDialog; import com.huanmedia.videochat.repository.datasouce.impl.MainRepostiory; import com.huanmedia.videochat.repository.entity.UserAccountBoundEntity; import mvp.presenter.Presenter; /** * Create by Administrator * time: 2017/12/21. * Email:<EMAIL> * version: ${VERSION} */ public class MyAccountPresenter extends Presenter<MyAccountView> { private final MainRepostiory mMainRepostiory; private UserAccountBoundEntity mUserAccount; public MyAccountPresenter() { mMainRepostiory = new MainRepostiory(); } private boolean checkMoney(String moneyStr) { if (mUserAccount == null) { getView().showHint(HintDialog.HintType.WARN, "提现错误,未能获取到账户信息"); return false; } if (mUserAccount.getIsBindPay() != 1) { getView().showHint(HintDialog.HintType.WARN, "未绑定提现账户"); return false; } if (!Check.isEmpty(moneyStr)) { try { double money = Double.parseDouble(moneyStr); if (money <= UserManager.getInstance().getRealMoney(mUserAccount.getExchangecoin()).doubleValue()) { if (money >= 200) {//money 必须是10的倍数 切大于200 if (money % 10 == 0) {//money 必须是10的倍数 return true; } else { getView().showHint(HintDialog.HintType.WARN, "提现数额必须是10的倍数"); } } else { getView().showHint(HintDialog.HintType.WARN, "最低提现额度为200"); } } else { getView().showHint(HintDialog.HintType.WARN, "可提现余额不足"); } } catch (Exception e) { return false; } } return false; } public void cashMoney(String moneystr) { if (checkMoney(moneystr)) { getView().showLoading(null); addDisposable(mMainRepostiory.userdocash((int)Math.floor(Integer.parseInt(moneystr) / UserManager.getInstance().getExchangeRate())).subscribe( response -> { getView().hideLoading(); getView().showHint(4, "系统将在5工作日内转入您的账户"); }, throwable -> { if (!isNullView()) { getView().hideLoading(); getView().showHint(HintDialog.HintType.WARN, getGeneralErrorStr(throwable)); } } )); } } public UserAccountBoundEntity getUserAccount() { return mUserAccount; } public void getData() { getView().showLoading(null); addDisposable(mMainRepostiory.userAccountBoundInfo().subscribe(userAccountBoundEntity -> { this.mUserAccount = userAccountBoundEntity; getView().hideLoading(); getView().showData(userAccountBoundEntity); }, throwable -> { if (!isNullView()) { getView().hideLoading(); getView().showError(0, getGeneralErrorStr(throwable)); } })); } }
tolorukooba/hedera-mirror-node
hedera-mirror-importer/src/main/java/com/hedera/mirror/importer/parser/record/transactionhandler/CryptoUpdateTransactionHandler.java
package com.hedera.mirror.importer.parser.record.transactionhandler; /*- * ‌ * Hedera Mirror Node * ​ * Copyright (C) 2019 - 2022 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import static com.hederahashgraph.api.proto.java.CryptoUpdateTransactionBody.StakedIdCase.STAKEDID_NOT_SET; import javax.inject.Named; import com.hedera.mirror.common.converter.AccountIdConverter; import com.hedera.mirror.common.domain.entity.Entity; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.common.domain.transaction.RecordItem; import com.hedera.mirror.common.domain.transaction.TransactionType; import com.hedera.mirror.common.util.DomainUtils; import com.hedera.mirror.importer.domain.EntityIdService; import com.hedera.mirror.importer.parser.record.RecordParserProperties; import com.hedera.mirror.importer.parser.record.entity.EntityListener; import com.hedera.mirror.importer.util.Utility; @Named class CryptoUpdateTransactionHandler extends AbstractEntityCrudTransactionHandler<Entity> { CryptoUpdateTransactionHandler(EntityIdService entityIdService, EntityListener entityListener, RecordParserProperties recordParserProperties) { super(entityIdService, entityListener, recordParserProperties, TransactionType.CRYPTOUPDATEACCOUNT); } @Override public EntityId getEntity(RecordItem recordItem) { return EntityId.of(recordItem.getTransactionBody().getCryptoUpdateAccount().getAccountIDToUpdate()); } @Override @SuppressWarnings("java:S1874") protected void doUpdateEntity(Entity entity, RecordItem recordItem) { var transactionBody = recordItem.getTransactionBody().getCryptoUpdateAccount(); if (transactionBody.hasAutoRenewPeriod()) { entity.setAutoRenewPeriod(transactionBody.getAutoRenewPeriod().getSeconds()); } if (transactionBody.hasExpirationTime()) { entity.setExpirationTimestamp(DomainUtils.timestampInNanosMax(transactionBody.getExpirationTime())); } if (transactionBody.hasKey()) { entity.setKey(transactionBody.getKey().toByteArray()); } if (transactionBody.hasMaxAutomaticTokenAssociations()) { entity.setMaxAutomaticTokenAssociations(transactionBody.getMaxAutomaticTokenAssociations().getValue()); } if (transactionBody.hasMemo()) { entity.setMemo(transactionBody.getMemo().getValue()); } if (transactionBody.hasProxyAccountID()) { entity.setProxyAccountId(EntityId.of(transactionBody.getProxyAccountID())); } if (transactionBody.hasReceiverSigRequiredWrapper()) { entity.setReceiverSigRequired(transactionBody.getReceiverSigRequiredWrapper().getValue()); } else if (transactionBody.getReceiverSigRequired()) { // support old transactions entity.setReceiverSigRequired(transactionBody.getReceiverSigRequired()); } updateStakingInfo(recordItem, entity); entityListener.onEntity(entity); } private void updateStakingInfo(RecordItem recordItem, Entity entity) { var transactionBody = recordItem.getTransactionBody().getCryptoUpdateAccount(); if (transactionBody.hasDeclineReward()) { entity.setDeclineReward(transactionBody.getDeclineReward().getValue()); } switch (transactionBody.getStakedIdCase()) { case STAKEDID_NOT_SET: break; case STAKED_NODE_ID: entity.setStakedNodeId(transactionBody.getStakedNodeId()); entity.setStakedAccountId(-1L); break; case STAKED_ACCOUNT_ID: EntityId accountId = EntityId.of(transactionBody.getStakedAccountId()); entity.setStakedAccountId(AccountIdConverter.INSTANCE.convertToDatabaseColumn(accountId)); entity.setStakedNodeId(-1L); break; } // If the stake node id or the decline reward value has changed, we start a new stake period. if (transactionBody.getStakedIdCase() != STAKEDID_NOT_SET || transactionBody.hasDeclineReward()) { entity.setStakePeriodStart(Utility.getEpochDay(recordItem.getConsensusTimestamp())); } } }
Bytom-Community/Bytom-Ruby-SDK
lib/bytom/api/core_config.rb
module Bytom class CoreConfig attr_reader :client private :client def initialize(client) @client = client end ## # Returns the information of current network node. # def net_info client.make_request('/net-info', 'post', params: {}) end def gas_rate client.make_request('/gas-rate', 'post', params: {}) end ## # Returns the mining status. # def is_mining client.make_request('/is-mining', 'post', params: {}) end ## # Start up node mining. # def set_mining(is_mining: true) client.make_request('/set-mining', 'post', params: {is_mining: is_mining}) end end end
fnrizzi/pressio-demoapps
tests_py/3d_sedov_symmetry/weno3_nxnynz_equal/test_3d_sedov_weno3_nxnynz_equal.py
<filename>tests_py/3d_sedov_symmetry/weno3_nxnynz_equal/test_3d_sedov_weno3_nxnynz_equal.py<gh_stars>1-10 import pathlib, sys file_path = pathlib.Path(__file__).parent.absolute() import numpy as np import time import matplotlib.pyplot as plt from numpy import linalg as LA from matplotlib import cm import pressiodemoapps as pda def computePressure(rho, u, v, w, E): gamma_ = (5.+2.)/5. vel = u**2 + v**2 + w**2 return (gamma_ - 1.) * (E - rho*vel*0.5) def test_run(): meshPath = str(file_path) meshObj = pda.load_cellcentered_uniform_mesh(meshPath) appObj = pda.create_problem(meshObj, pda.Euler3d.SedovSymmetry, pda.InviscidFluxReconstruction.Weno3) dt = 0.0001 Nsteps = int(0.025/dt) yn = appObj.initialCondition() pda.advanceSSP3(appObj, yn, dt, Nsteps, showProgress=True) gold = np.loadtxt(str(file_path)+"/gold_state.txt") assert(np.allclose(yn.shape, gold.shape)) assert(np.isnan(yn).all() == False) assert(np.isnan(gold).all() == False) assert(np.allclose(yn, gold,rtol=1e-8, atol=1e-10)) error = LA.norm(yn-gold) print("error = ", error) # fig = plt.figure() # ax = plt.axes(projection ="3d") # coords = np.loadtxt('coordinates.dat', dtype=float) # x, y, z = coords[:,1], coords[:,2], coords[:,3] # rho = yn[0::5] # u = yn[1::5]/rho # v = yn[2::5]/rho # w = yn[3::5]/rho # p = computePressure(rho, u, v, w, yn[4::5]) # print(np.min(p), np.max(p)) # ax.scatter3D(x, y, z, c=p, marker='o', s=5) # ax.set_xlim([0., 0.4]) # ax.set_ylim([0., 0.4]) # ax.set_zlim([0., 0.4]) # plt.show() # --------------------------- if __name__ == '__main__': # --------------------------- test_run()
mahendra-panchal/Hyperledger-Node_JS-Cli
node_modules/mock-couch/lib/convertViews.js
<filename>node_modules/mock-couch/lib/convertViews.js<gh_stars>10-100 /*jslint node: true, indent: 2 , nomen : true, evil : true */ 'use strict'; var R = require('ramda'), createMD5 = require('./createMD5'), nl = /(?:\\r|\\n|\n|\r)/g; module.exports = function (doc) { if (doc.views && (!doc.id || (doc.id && doc._id.substr(0, 8) === '_design/'))) { Object.keys(doc.views).forEach(function (view) { var fn, thisView = doc.views[view]; if (thisView.hasOwnProperty('map')) { fn = 'return ' + thisView.map.replace(nl, ''); thisView.map = (new Function(fn))(); } if (thisView.hasOwnProperty('reduce') && thisView.reduce !== '_sum' && thisView.reduce !== '_count') { fn = 'return ' + thisView.reduce.replace(nl, ''); thisView.reduce = (new Function(fn))(); } }); } return doc; };
andreazammarchi3/OOP_Lab
OOP-Lab09/src/it/unibo/oop/lab/lambda/ex02/TestMusicGroup.java
package it.unibo.oop.lab.lambda.ex02; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Test; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; /* * CHECKSTYLE: MagicNumber OFF * The above comment shuts down checkstyle: in a test suite, magic numbers may be tolerated. */ /** * * */ public final class TestMusicGroup { private static final String UNTITLED = "untitled"; private static final String III = "III"; private MusicGroup lz; /** * Sets up the testing. */ @Before public void setUp() { lz = new MusicGroupImpl(); lz.addAlbum("I", 1969); lz.addAlbum("II", 1969); lz.addAlbum(III, 1970); lz.addAlbum(UNTITLED, 1971); lz.addSong("Dazed and Confused", Optional.of("I"), 6.5); lz.addSong("I Can't Quit You Baby", Optional.of("I"), 4.6); lz.addSong("Whole Lotta Love", Optional.of("II"), 5.5); lz.addSong("Ramble On", Optional.of("II"), 4.6); lz.addSong("Immigrant Song", Optional.of(III), 2.4); lz.addSong("That's the Way", Optional.of(III), 5.4); lz.addSong("Black Dog", Optional.of("untitled"), 4.9); lz.addSong("When the Levee Breaks", Optional.of("untitled"), 7.1); lz.addSong("Travelling Riverside Blues", Optional.empty(), 5.2); } /** * Tests album names. */ @Test public void testAlbumNames() { final List<String> result = new ArrayList<>(); result.add("II"); result.add(UNTITLED); result.add("III"); result.add("I"); final List<String> actual = lz.albumNames().collect(toList()); assertTrue(actual.containsAll(result)); assertTrue(lz.albumNames().collect(toList()).containsAll(result)); } /** * Tests ordering of song names. */ @Test public void testOrderedSongNames() { final List<String> result = Arrays.asList(new String[] { "Black Dog", "Dazed and Confused", "I Can't Quit You Baby", "Immigrant Song", "Ramble On", "That's the Way", "Travelling Riverside Blues", "When the Levee Breaks", "Whole Lotta Love" }); final List<String> actual = lz.orderedSongNames().collect(toList()); assertEquals(result, actual); } /** * Tests albums in year. */ @Test public void testAlbumInYear() { final List<String> result = Arrays.asList(new String[] { "II", "I" }); final List<String> actual = lz.albumInYear(1969).collect(toList()); assertEquals(result, actual); } /** * Tests song counting. */ @Test public void testCountSongs() { assertEquals(2, lz.countSongs("I")); } /** * Tests ordering song not in albums. */ @Test public void testCountSongsInNoAlbum() { assertEquals(1, lz.countSongsInNoAlbum()); } /** * Tests average duration. */ @Test public void testAverageDuration() { assertEquals(6.0, lz.averageDurationOfSongs(UNTITLED).getAsDouble(), 0.0); } /** * Tests selecting the longest song. */ @Test public void testLongest() { assertEquals("When the Levee Breaks", lz.longestSong().get()); assertEquals(UNTITLED, lz.longestAlbum().get()); } }
DreiMu/Create
src/main/java/com/simibubi/create/content/contraptions/base/IRotate.java
package com.simibubi.create.content.contraptions.base; import com.simibubi.create.content.contraptions.goggles.IHaveGoggleInformation; import com.simibubi.create.content.contraptions.wrench.IWrenchable; import com.simibubi.create.foundation.config.AllConfigs; import com.simibubi.create.foundation.item.ItemDescription; import com.simibubi.create.foundation.utility.Lang; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextComponent; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockState; public interface IRotate extends IWrenchable { enum SpeedLevel { NONE(ChatFormatting.DARK_GRAY, 0x000000, 0), SLOW(ChatFormatting.GREEN, 0x22FF22, 10), MEDIUM(ChatFormatting.AQUA, 0x0084FF, 20), FAST(ChatFormatting.LIGHT_PURPLE, 0xFF55FF, 30); private final ChatFormatting textColor; private final int color; private final int particleSpeed; SpeedLevel(ChatFormatting textColor, int color, int particleSpeed) { this.textColor = textColor; this.color = color; this.particleSpeed = particleSpeed; } public ChatFormatting getTextColor() { return textColor; } public int getColor() { return color; } public int getParticleSpeed() { return particleSpeed; } public float getSpeedValue() { switch (this) { case FAST: return AllConfigs.SERVER.kinetics.fastSpeed.get().floatValue(); case MEDIUM: return AllConfigs.SERVER.kinetics.mediumSpeed.get().floatValue(); case SLOW: return 1; case NONE: default: return 0; } } public static SpeedLevel of(float speed) { speed = Math.abs(speed); if (speed >= AllConfigs.SERVER.kinetics.fastSpeed.get()) return FAST; if (speed >= AllConfigs.SERVER.kinetics.mediumSpeed.get()) return MEDIUM; if (speed >= 1) return SLOW; return NONE; } public static Component getFormattedSpeedText(float speed, boolean overstressed) { SpeedLevel speedLevel = of(speed); MutableComponent level = new TextComponent(ItemDescription.makeProgressBar(3, speedLevel.ordinal())); level.append(Lang.translate("tooltip.speedRequirement." + Lang.asId(speedLevel.name()))); level.append(" (" + IHaveGoggleInformation.format(Math.abs(speed))).append(Lang.translate("generic.unit.rpm")).append(") "); if (overstressed) level.withStyle(ChatFormatting.DARK_GRAY, ChatFormatting.STRIKETHROUGH); else level.withStyle(speedLevel.getTextColor()); return level; } } enum StressImpact { LOW(ChatFormatting.YELLOW, ChatFormatting.GREEN), MEDIUM(ChatFormatting.GOLD, ChatFormatting.YELLOW), HIGH(ChatFormatting.RED, ChatFormatting.GOLD), OVERSTRESSED(ChatFormatting.RED, ChatFormatting.RED); private final ChatFormatting absoluteColor; private final ChatFormatting relativeColor; StressImpact(ChatFormatting absoluteColor, ChatFormatting relativeColor) { this.absoluteColor = absoluteColor; this.relativeColor = relativeColor; } public ChatFormatting getAbsoluteColor() { return absoluteColor; } public ChatFormatting getRelativeColor() { return relativeColor; } public static StressImpact of(double stressPercent) { if (stressPercent > 1) return StressImpact.OVERSTRESSED; if (stressPercent > .75d) return StressImpact.HIGH; if (stressPercent > .5d) return StressImpact.MEDIUM; return StressImpact.LOW; } public static boolean isEnabled() { return !AllConfigs.SERVER.kinetics.disableStress.get(); } public static Component getFormattedStressText(double stressPercent) { StressImpact stressLevel = of(stressPercent); MutableComponent level = new TextComponent(ItemDescription.makeProgressBar(3, Math.min(stressLevel.ordinal() + 1, 3))); level.append(Lang.translate("tooltip.stressImpact." + Lang.asId(stressLevel.name()))); level.append(String.format(" (%s%%) ", (int) (stressPercent * 100))); return level.withStyle(stressLevel.getRelativeColor()); } } public boolean hasShaftTowards(LevelReader world, BlockPos pos, BlockState state, Direction face); public Axis getRotationAxis(BlockState state); public default SpeedLevel getMinimumRequiredSpeedLevel() { return SpeedLevel.SLOW; } public default boolean hideStressImpact() { return false; } public default boolean showCapacityWithAnnotation() { return false; } }
akiellor/selenium
third_party/gecko-2/win32/include/nsIProtocolProxyService2.h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/netwerk/base/public/nsIProtocolProxyService2.idl */ #ifndef __gen_nsIProtocolProxyService2_h__ #define __gen_nsIProtocolProxyService2_h__ #ifndef __gen_nsIProtocolProxyService_h__ #include "nsIProtocolProxyService.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIProtocolProxyService2 */ #define NS_IPROTOCOLPROXYSERVICE2_IID_STR "dbd9565d-29b1-437a-bff5-2fc339e2c5df" #define NS_IPROTOCOLPROXYSERVICE2_IID \ {0xdbd9565d, 0x29b1, 0x437a, \ { 0xbf, 0xf5, 0x2f, 0xc3, 0x39, 0xe2, 0xc5, 0xdf }} /** * An extension of nsIProtocolProxyService */ class NS_NO_VTABLE NS_SCRIPTABLE nsIProtocolProxyService2 : public nsIProtocolProxyService { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPROTOCOLPROXYSERVICE2_IID) /** * Call this method to cause the PAC file (if any is configured) to be * reloaded. The PAC file is loaded asynchronously. */ /* void reloadPAC (); */ NS_SCRIPTABLE NS_IMETHOD ReloadPAC(void) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIProtocolProxyService2, NS_IPROTOCOLPROXYSERVICE2_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIPROTOCOLPROXYSERVICE2 \ NS_SCRIPTABLE NS_IMETHOD ReloadPAC(void); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIPROTOCOLPROXYSERVICE2(_to) \ NS_SCRIPTABLE NS_IMETHOD ReloadPAC(void) { return _to ReloadPAC(); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIPROTOCOLPROXYSERVICE2(_to) \ NS_SCRIPTABLE NS_IMETHOD ReloadPAC(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->ReloadPAC(); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsProtocolProxyService2 : public nsIProtocolProxyService2 { public: NS_DECL_ISUPPORTS NS_DECL_NSIPROTOCOLPROXYSERVICE2 nsProtocolProxyService2(); private: ~nsProtocolProxyService2(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsProtocolProxyService2, nsIProtocolProxyService2) nsProtocolProxyService2::nsProtocolProxyService2() { /* member initializers and constructor code */ } nsProtocolProxyService2::~nsProtocolProxyService2() { /* destructor code */ } /* void reloadPAC (); */ NS_IMETHODIMP nsProtocolProxyService2::ReloadPAC() { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIProtocolProxyService2_h__ */
DataBooster/PyWebApi
Sample/UserApps/PowerBIPusher/pbi_authorization.py
<filename>Sample/UserApps/PowerBIPusher/pbi_authorization.py<gh_stars>1-10 # Sourced: # https://github.com/microsoft/PowerBI-Developer-Samples/blob/master/Python/Embed%20for%20your%20customers/powerbiembedding/aadservice.py # import msal from pbi_config import config def get_accesstoken(): '''Returns AAD token using MSAL''' response = None try: if config['AUTHENTICATION_MODE'].lower() == 'masteruser': # Create a public client to authorize the app with the AAD app clientapp = msal.PublicClientApplication(config['CLIENT_ID'], authority=config['AUTHORITY']) accounts = clientapp.get_accounts(username=config['POWER_BI_USER']) if accounts: # Retrieve Access token from cache if available response = clientapp.acquire_token_silent(config['SCOPE'], account=accounts[0]) if not response: # Make a client call if Access token is not available in cache response = clientapp.acquire_token_by_username_password(config['POWER_BI_USER'], config['POWER_BI_PASS'], scopes=config['SCOPE']) elif config['AUTHENTICATION_MODE'].lower() == 'serviceprincipal': authority = config['AUTHORITY'].replace('organizations', config['TENANT_ID']) clientapp = msal.ConfidentialClientApplication(config['CLIENT_ID'], client_credential=config['CLIENT_SECRET'], authority=authority) # Retrieve Access token from cache if available response = clientapp.acquire_token_silent(scopes=config['SCOPE'], account=None) if not response: # Make a client call if Access token is not available in cache response = clientapp.acquire_token_for_client(scopes=config['SCOPE']) try: return response['access_token'] except KeyError: raise Exception(response['error_description']) except Exception as ex: raise Exception('Error retrieving access token\n' + str(ex))
gauravgarg17/Compressonator
Compressonator/CMP_Framework/CMP_Framework.h
//===================================================================== // Copyright (c) 2007-2016 Advanced Micro Devices, Inc. All rights reserved. // Copyright (c) 2004-2006 ATI Technologies Inc. // // 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 CMP_FRAMEWORK_H #define CMP_FRAMEWORK_H #include <stdint.h> #include <vector> typedef int CMP_INT; typedef unsigned int CMP_UINT; typedef bool CMP_BOOL; typedef void CMP_VOID; typedef float CMP_FLOAT; typedef unsigned char CMP_BYTE; typedef std::uint16_t CMP_WORD; typedef std::uint32_t CMP_DWORD; typedef short CMP_HALFSHORT; typedef std::vector<uint8_t> CMP_VEC8; typedef size_t CMP_DWORD_PTR; #if defined(WIN32) || defined(_WIN64) #define CMP_API __cdecl #else #define CMP_API #endif //=================================== // Common with Compressonator SDK //=================================== #ifndef CMP_FORMAT typedef enum { CMP_FORMAT_Unknown = 0, // Undefined texture format. // Channel Component formats -------------------------------------------------------------------------------- CMP_FORMAT_ARGB_8888, // ARGB format with 8-bit fixed channels. CMP_FORMAT_ABGR_8888, // ABGR format with 8-bit fixed channels. CMP_FORMAT_RGBA_8888, // RGBA format with 8-bit fixed channels. CMP_FORMAT_BGRA_8888, // BGRA format with 8-bit fixed channels. CMP_FORMAT_RGB_888, // RGB format with 8-bit fixed channels. CMP_FORMAT_BGR_888, // BGR format with 8-bit fixed channels. CMP_FORMAT_RG_8, // Two component format with 8-bit fixed channels. CMP_FORMAT_R_8, // Single component format with 8-bit fixed channels. CMP_FORMAT_ARGB_2101010, // ARGB format with 10-bit fixed channels for color & a 2-bit fixed channel for alpha. CMP_FORMAT_ARGB_16, // ARGB format with 16-bit fixed channels. CMP_FORMAT_ABGR_16, // ABGR format with 16-bit fixed channels. CMP_FORMAT_RGBA_16, // RGBA format with 16-bit fixed channels. CMP_FORMAT_BGRA_16, // BGRA format with 16-bit fixed channels. CMP_FORMAT_RG_16, // Two component format with 16-bit fixed channels. CMP_FORMAT_R_16, // Single component format with 16-bit fixed channels. CMP_FORMAT_RGBE_32F, // RGB format with 9-bit floating point each channel and shared 5 bit exponent CMP_FORMAT_ARGB_16F, // ARGB format with 16-bit floating-point channels. CMP_FORMAT_ABGR_16F, // ABGR format with 16-bit floating-point channels. CMP_FORMAT_RGBA_16F, // RGBA format with 16-bit floating-point channels. CMP_FORMAT_BGRA_16F, // BGRA format with 16-bit floating-point channels. CMP_FORMAT_RG_16F, // Two component format with 16-bit floating-point channels. CMP_FORMAT_R_16F, // Single component with 16-bit floating-point channels. CMP_FORMAT_ARGB_32F, // ARGB format with 32-bit floating-point channels. CMP_FORMAT_ABGR_32F, // ABGR format with 32-bit floating-point channels. CMP_FORMAT_RGBA_32F, // RGBA format with 32-bit floating-point channels. CMP_FORMAT_BGRA_32F, // BGRA format with 32-bit floating-point channels. CMP_FORMAT_RGB_32F, // RGB format with 32-bit floating-point channels. CMP_FORMAT_BGR_32F, // BGR format with 32-bit floating-point channels. CMP_FORMAT_RG_32F, // Two component format with 32-bit floating-point channels. CMP_FORMAT_R_32F, // Single component with 32-bit floating-point channels. // Compression formats ----------------------------------------------------------------------------------- CMP_FORMAT_ASTC, // ASTC (Adaptive Scalable Texture Compression) open texture compression standard CMP_FORMAT_ATI1N, // Single component compression format using the same technique as DXT5 alpha. Four bits per pixel. CMP_FORMAT_ATI2N, // Two component compression format using the same technique as DXT5 alpha. Designed for compression of tangent space normal maps. Eight bits per pixel. CMP_FORMAT_ATI2N_XY, // Two component compression format using the same technique as DXT5 alpha. The same as ATI2N but with the channels swizzled. Eight bits per pixel. CMP_FORMAT_ATI2N_DXT5, // ATI2N like format using DXT5. Intended for use on GPUs that do not natively support ATI2N. Eight bits per pixel. CMP_FORMAT_ATC_RGB, // CMP - a compressed RGB format. CMP_FORMAT_ATC_RGBA_Explicit, // CMP - a compressed ARGB format with explicit alpha. CMP_FORMAT_ATC_RGBA_Interpolated, // CMP - a compressed ARGB format with interpolated alpha. CMP_FORMAT_BC1, // A four component opaque (or 1-bit alpha) compressed texture format for Microsoft DirectX10. Identical to DXT1. Four bits per pixel. CMP_FORMAT_BC2, // A four component compressed texture format with explicit alpha for Microsoft DirectX10. Identical to DXT3. Eight bits per pixel. CMP_FORMAT_BC3, // A four component compressed texture format with interpolated alpha for Microsoft DirectX10. Identical to DXT5. Eight bits per pixel. CMP_FORMAT_BC4, // A single component compressed texture format for Microsoft DirectX10. Identical to ATI1N. Four bits per pixel. CMP_FORMAT_BC5, // A two component compressed texture format for Microsoft DirectX10. Identical to ATI2N_XY. Eight bits per pixel. CMP_FORMAT_BC6H, // BC6H compressed texture format (UF) CMP_FORMAT_BC6H_SF, // BC6H compressed texture format (SF) CMP_FORMAT_BC7, // BC7 compressed texture format CMP_FORMAT_DXT1, // An DXTC compressed texture matopaque (or 1-bit alpha). Four bits per pixel. CMP_FORMAT_DXT3, // DXTC compressed texture format with explicit alpha. Eight bits per pixel. CMP_FORMAT_DXT5, // DXTC compressed texture format with interpolated alpha. Eight bits per pixel. CMP_FORMAT_DXT5_xGBR, // DXT5 with the red component swizzled into the alpha channel. Eight bits per pixel. CMP_FORMAT_DXT5_RxBG, // swizzled DXT5 format with the green component swizzled into the alpha channel. Eight bits per pixel. CMP_FORMAT_DXT5_RBxG, // swizzled DXT5 format with the green component swizzled into the alpha channel & the blue component swizzled into the green channel. Eight bits per pixel. CMP_FORMAT_DXT5_xRBG, // swizzled DXT5 format with the green component swizzled into the alpha channel & the red component swizzled into the green channel. Eight bits per pixel. CMP_FORMAT_DXT5_RGxB, // swizzled DXT5 format with the blue component swizzled into the alpha channel. Eight bits per pixel. CMP_FORMAT_DXT5_xGxR, // two-component swizzled DXT5 format with the red component swizzled into the alpha channel & the green component in the green channel. Eight bits per pixel. CMP_FORMAT_ETC_RGB, // ETC GL_COMPRESSED_RGB8_ETC2 backward compatible CMP_FORMAT_ETC2_RGB, // ETC2 GL_COMPRESSED_RGB8_ETC2 CMP_FORMAT_ETC2_SRGB, // ETC2 GL_COMPRESSED_SRGB8_ETC2 CMP_FORMAT_ETC2_RGBA, // ETC2 GL_COMPRESSED_RGBA8_ETC2_EAC CMP_FORMAT_ETC2_RGBA1, // ETC2 GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 CMP_FORMAT_ETC2_SRGBA, // ETC2 GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC CMP_FORMAT_ETC2_SRGBA1, // ETC2 GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 CMP_FORMAT_PVRTC, // Transcoder formats - ------------------------------------------------------------ CMP_FORMAT_GTC, ///< GTC Fast Gradient Texture Compressor CMP_FORMAT_BASIS, ///< BASIS compression // End of list CMP_FORMAT_MAX = CMP_FORMAT_BASIS } CMP_FORMAT; #endif /// Compress error codes #ifndef CMP_ERROR typedef enum { CMP_OK = 0, // Ok. CMP_ABORTED, // The conversion was aborted. CMP_ERR_INVALID_SOURCE_TEXTURE, // The source texture is invalid. CMP_ERR_INVALID_DEST_TEXTURE, // The destination texture is invalid. CMP_ERR_UNSUPPORTED_SOURCE_FORMAT, // The source format is not a supported format. CMP_ERR_UNSUPPORTED_DEST_FORMAT, // The destination format is not a supported format. CMP_ERR_UNSUPPORTED_GPU_ASTC_DECODE, // The gpu hardware is not supported. CMP_ERR_UNSUPPORTED_GPU_BASIS_DECODE, // The gpu hardware is not supported. CMP_ERR_SIZE_MISMATCH, // The source and destination texture sizes do not match. CMP_ERR_UNABLE_TO_INIT_CODEC, // Compressonator was unable to initialize the codec needed for conversion. CMP_ERR_UNABLE_TO_INIT_DECOMPRESSLIB, // GPU_Decode Lib was unable to initialize the codec needed for decompression . CMP_ERR_UNABLE_TO_INIT_COMPUTELIB, // Compute Lib was unable to initialize the codec needed for compression. CMP_ERR_CMP_DESTINATION, // Error in compressing destination texture CMP_ERR_MEM_ALLOC_FOR_MIPSET, // Memory Error: allocating MIPSet compression level data buffer CMP_ERR_UNKNOWN_DESTINATION_FORMAT, // The destination Codec Type is unknown! In SDK refer to GetCodecType() CMP_ERR_FAILED_HOST_SETUP, // Failed to setup Host for processing CMP_ERR_PLUGIN_FILE_NOT_FOUND, // The required plugin library was not found CMP_ERR_UNABLE_TO_LOAD_FILE, // The requested file was not loaded CMP_ERR_UNABLE_TO_CREATE_ENCODER, // Request to create an encoder failed CMP_ERR_UNABLE_TO_LOAD_ENCODER, // Unable to load an encode library CMP_ERR_NOSHADER_CODE_DEFINED, // No shader code is available for the requested framework CMP_ERR_GPU_DOESNOT_SUPPORT_COMPUTE, // The GPU device selected does not support compute CMP_ERR_GENERIC // An unknown error occurred. } CMP_ERROR; #endif //=================================== // Definitions for CMP MipSet //=================================== /// The format of data in the channels of texture. typedef enum { CF_8bit = 0, // 8-bit integer data. CF_Float16 = 1, // 16-bit float data. CF_Float32 = 2, // 32-bit float data. CF_Compressed = 3, // Compressed data. CF_16bit = 4, // 16-bit integer data. CF_2101010 = 5, // 10-bit integer data in the color channels & 2-bit integer data in the alpha channel. CF_32bit = 6, // 32-bit integer data. CF_Float9995E = 7, // 32-bit partial precision float. CF_YUV_420 = 8, // YUV Chroma formats CF_YUV_422 = 9, // YUV Chroma formats CF_YUV_444 = 10, // YUV Chroma formats CF_YUV_4444 = 11, // YUV Chroma formats } CMP_ChannelFormat; typedef CMP_ChannelFormat ChannelFormat; /// The type of data the texture represents. typedef enum { TDT_XRGB = 0, // An RGB texture padded to DWORD width. TDT_ARGB = 1, // An ARGB texture. TDT_NORMAL_MAP = 2, // A normal map. TDT_R = 3, // A single component texture. TDT_RG = 4, // A two component texture. TDT_YUV_SD = 5, // An YUB Standard Definition texture. TDT_YUV_HD = 6, // An YUB High Definition texture. } CMP_TextureDataType; typedef CMP_TextureDataType TextureDataType; /// The type of the texture. typedef enum { TT_2D = 0, // A regular 2D texture. data stored linearly (rgba,rgba,...rgba) TT_CubeMap = 1, // A cubemap texture. TT_VolumeTexture = 2, // A volume texture. TT__2D_Block = 3, // 2D texture data stored as [Height][Width] blocks as individual channels using cmp_rgb_t or cmp_yuv_t TT_Unknown = 4, // Unknown type of texture : No data is stored for this type } CMP_TextureType; typedef CMP_TextureType TextureType; typedef struct { union { CMP_BYTE rgba[4]; ///< The color as an array of components. CMP_DWORD asDword; ///< The color as a DWORD. }; } CMP_COLOR; /// A MipLevel is the fundamental unit for containing texture data. /// \remarks /// One logical mip level can be composed of many MipLevels, see the documentation of MipSet for explanation. /// \sa \link TC_AppAllocateMipLevelData() TC_AppAllocateMipLevelData \endlink, /// \link TC_AppAllocateCompressedMipLevelData() TC_AppAllocateCompressedMipLevelData \endlink, /// \link MipSet \endlink typedef struct { CMP_INT m_nWidth; ///< Width of the data in pixels. CMP_INT m_nHeight; ///< Height of the data in pixels. CMP_DWORD m_dwLinearSize; ///< Size of the data in bytes. union { CMP_BYTE* m_pbData; ///< pointer unsigned 8 bit.data blocks CMP_WORD* m_pwData; ///< pointer unsigned 16 bit.data blocks CMP_COLOR* m_pcData; ///< pointer to a union (array of 4 unsigned 8 bits or one 32 bit) data blocks CMP_FLOAT* m_pfData; ///< pointer to 32-bit signed float data blocks CMP_HALFSHORT* m_phfsData; ///< pointer to 16 bit short data blocks CMP_DWORD* m_pdwData; ///< pointer to 32 bit data blocks CMP_VEC8* m_pvec8Data; ///< std::vector unsigned 8 bits data blocks }; } CMP_MipLevel; typedef CMP_MipLevel MipLevel; typedef CMP_MipLevel* CMP_MipLevelTable; ///< A pointer to a set of MipLevels. // Each texture and all its mip-map levels are encapsulated in a MipSet. // Do not depend on m_pMipLevelTable being there, it is an implementation detail that you see only because there is no easy cross-complier // way of passing data around in internal classes. // // For 2D textures there are m_nMipLevels MipLevels. // Cube maps have multiple faces or sides for each mip-map level . Instead of making a totally new data type, we just made each one of these faces be represented by a MipLevel, even though the terminology can be a bit confusing at first. So if your cube map consists of 6 faces for each mip-map level, then your first mip-map level will consist of 6 MipLevels, each having the same m_nWidth, m_nHeight. The next mip-map level will have half the m_nWidth & m_nHeight as the previous, but will be composed of 6 MipLevels still. // A volume texture is a 3D texture. Again, instead of creating a new data type, we chose to make use of multiple MipLevels to create a single mip-map level of a volume texture. So a single mip-map level of a volume texture will consist of many MipLevels, all having the same m_nWidth and m_nHeight. The next mip-map level will have m_nWidth and m_nHeight half of the previous mip-map level's (to a minimum of 1) and will be composed of half as many MipLevels as the previous mip-map level (the first mip-map level takes this number from the MipSet it's part of), to a minimum of one. typedef struct { CMP_INT m_nWidth; // User Setting: Width in pixels of the topmost mip-map level of the mip-map set. Initialized by TC_AppAllocateMipSet. CMP_INT m_nHeight; // User Setting: Height in pixels of the topmost mip-map level of the mip-map set. Initialized by TC_AppAllocateMipSet. CMP_INT m_nDepth; // User Setting: Depth in MipLevels of the topmost mip-map level of the mip-map set. Initialized by TC_AppAllocateMipSet. See Remarks. CMP_FORMAT m_format; // User Setting: Format for this MipSet // set by various API for internal use and user ref ChannelFormat m_ChannelFormat; // A texture is usually composed of channels, such as RGB channels for a texture with red green and blue image data. m_ChannelFormat indicates the representation of each of these channels. So a texture where each channel is an 8 bit integer would have CF_8bit for this. A compressed texture would use CF_Compressed. TextureDataType m_TextureDataType; // An indication of the type of data that the texture contains. A texture with just RGB values would use TDT_XRGB, while a texture that also uses the alpha channel would use TDT_ARGB. TextureType m_TextureType; // Indicates whether the texture is 2D, a cube map, or a volume texture. Used to determine how to treat MipLevels, among other things. CMP_UINT m_Flags; // Flags that mip-map set. CMP_BYTE m_CubeFaceMask; // A mask of MS_CubeFace values indicating which cube-map faces are present. CMP_DWORD m_dwFourCC; // The FourCC for this mip-map set. 0 if the mip-map set is uncompressed. Generated using MAKEFOURCC (defined in the Platform SDK or DX SDK). CMP_DWORD m_dwFourCC2; // An extra FourCC used by The Compressonator internally. Our DDS plugin saves/loads m_dwFourCC2 from pDDSD ddpfPixelFormat.dwPrivateFormatBitCount (since it's not really used by anything else) whether or not it is 0. Generated using MAKEFOURCC (defined in the Platform SDK or DX SDK). The FourCC2 field is currently used to allow differentiation between the various swizzled DXT5 formats. These formats must have a FourCC of DXT5 to be supported by the DirectX runtime but The Compressonator needs to know the swizzled FourCC to correctly display the texture. CMP_INT m_nMaxMipLevels; // Set by The Compressonator when you call TC_AppAllocateMipSet based on the width, height, depth, and textureType values passed in. Is really the maximum number of mip-map levels possible for that texture including the topmost mip-map level if you integer divide width height and depth by 2, rounding down but never falling below 1 until all three of them are 1. So a 5x10 2D texture would have a m_nMaxMipLevels of 4 (5x10 2x5 1x2 1x1). CMP_INT m_nMipLevels; // The number of mip-map levels in the mip-map set that actually have data. Always less than or equal to m_nMaxMipLevels. Set to 0 after TC_AppAllocateMipSet. CMP_FORMAT m_transcodeFormat; // For universal format: Sets the target data format for data processing and analysis CMP_BOOL m_compressed; // New Flags if data is compressed (example Block Compressed data in form of BCxx) CMP_FORMAT m_isDeCompressed; // The New MipSet is a decompressed result from a prior Compressed MipSet Format specified CMP_BOOL m_swizzle; // Flag is used by image load and save to indicate channels were swizzled from the origial source CMP_BYTE m_nBlockWidth; // Width in pixels of the Compression Block that is to be processed default for ASTC is 4 CMP_BYTE m_nBlockHeight; // Height in pixels of the Compression Block that is to be processed default for ASTC is 4 CMP_BYTE m_nBlockDepth; // Depth in pixels of the Compression Block that is to be processed default for ASTC is 1 // set by various API for internal use. These values change when processing MipLevels CMP_DWORD dwWidth; // set by various API for ref,Width of the current active miplevel. if toplevel mipmap then value is same as m_nWidth CMP_DWORD dwHeight; // set by various API for ref,Height of the current active miplevel. if toplevel mipmap then value is same as m_nHeight CMP_DWORD dwDataSize; // set by various API for ref,Size of the current active miplevel allocated texture data. CMP_BYTE* pData; // set by various API for ref,Pointer to the current active miplevel texture data: used in MipLevelTable // Structure to hold all mip levels buffers CMP_MipLevelTable* m_pMipLevelTable; // set by various API for ref, This is an implementation dependent way of storing the MipLevels that this mip-map set contains. Do not depend on it, use TC_AppGetMipLevel to access a mip-map set's MipLevels. void* m_pReservedData; // Reserved for ArchitectMF ImageLoader } CMP_MipSet; //=================================== // API Definitions for CMP Framework //=================================== typedef struct { CMP_FLOAT mipProgress; // The percentage progress of the current MIP level texture compression CMP_INT mipLevel; // returns the current MIP level been processed 0..max available for the image CMP_INT cubeFace; // returns the current Cube Face been processed 1..6 } CMP_MIPPROGRESSPARAM; /// An enum selecting the different GPU driver types. typedef enum { CMP_CPU = 0, //Use CPU Only, encoders defined CMP_CPUEncode or Compressonator lib will be used CMP_HPC = 1, //Use CPU High Performance Compute Encoders with SPMD support defined in CMP_CPUEncode) CMP_GPU = 2, //Use GPU Kernel Encoders to compress textures using Default GPU Framework auto set by the codecs been used CMP_GPU_OCL = 3, //Use GPU Kernel Encoders to compress textures using OpenCL Framework CMP_GPU_DXC = 4, //Use GPU Kernel Encoders to compress textures using DirectX Compute Framework CMP_GPU_VLK = 5 //Use GPU Kernel Encoders to compress textures using Vulkan Compute Framework } CMP_Compute_type; typedef enum CMPComputeExtensions { CMP_COMPUTE_FP16 = 0x0001, ///< Enable Packed Math Option for GPU CMP_COMPUTE_MAX_ENUM = 0x7FFF } CMP_ComputeExtensions; struct KernelOptions { CMP_ComputeExtensions Extensions; // Compute extentions to use, set to 0 if you are not using any extensions CMP_DWORD height; // Height of the encoded texture. CMP_DWORD width; // Width of the encoded texture. CMP_FLOAT fquality; // Set the quality used for encoders 0.05 is the lowest and 1.0 for highest. CMP_FORMAT format; // Encoder codec format to use for processing CMP_Compute_type encodeWith; // Host Type : default is HPC, options are [HPC or GPU] CMP_INT threads; // requested number of threads to use (1= single) max is 128 for HPC //private: data settings: Do not use it will be removed from this interface! CMP_UINT size; // Size of *data void *data; // Data to pass down from CPU to kernel void *dataSVM; // Data allocated as Shared by CPU and GPU (used only when code is running in 64bit and devices support SVM) char *srcfile; // Shader source file location }; struct ComputeOptions { //public: data settings bool force_rebuild; ///<Force the GPU host framework to rebuild shaders //private: data settings: Do not use or set these void *plugin_compute; ///< Ref to Encoder codec plugin: For Internal use (will be removed!) }; // The structure describing block encoder level settings. typedef struct { unsigned int width; // Width of the encoded texture. unsigned int height; // Height of the encoded texture. unsigned int pitch; // Distance to start of next line.. float quality; // Set the quality used for encoders 0.05 is the lowest and 1.0 for highest. unsigned int format; // Format of the encoder to use: this is a enum set see compressonator.h CMP_FORMAT } CMP_EncoderSetting; /// CMP_Feedback_Proc /// Feedback function for conversion. /// \param[in] fProgress The percentage progress of the texture compression. /// \param[in] mipProgress The current MIP level been processed, value of fProgress = mipProgress /// \return non-NULL(true) value to abort conversion typedef bool(CMP_API* CMP_Feedback_Proc)(CMP_FLOAT fProgress, CMP_DWORD_PTR pUser1, CMP_DWORD_PTR pUser2); #ifdef __cplusplus extern "C" { #endif /// MIP MAP Interfaces extern CMP_INT CMP_MaxFacesOrSlices(const CMP_MipSet* pMipSet, CMP_INT nMipLevel); CMP_INT CMP_API CMP_CalcMinMipSize(CMP_INT nHeight, CMP_INT nWidth, CMP_INT MipsLevel); CMP_INT CMP_API CMP_GenerateMIPLevels(CMP_MipSet *pMipSet, CMP_INT nMinSize); CMP_ERROR CMP_API CMP_CreateCompressMipSet(CMP_MipSet* pMipSetCMP, CMP_MipSet* pMipSetSRC); /// CMP_MIPFeedback_Proc /// Feedback function for conversion. /// \param[in] fProgress The percentage progress of the texture compression. /// \param[in] mipProgress The current MIP level been processed, value of fProgress = mipProgress /// \return non-NULL(true) value to abort conversion typedef bool(CMP_API* CMP_MIPFeedback_Proc)(CMP_MIPPROGRESSPARAM mipProgress); //-------------------------------------------- // CMP_Compute Lib: Texture Encoder Interfaces //-------------------------------------------- CMP_ERROR CMP_API CMP_LoadTexture(const char *sourceFile, CMP_MipSet *pMipSet); CMP_ERROR CMP_API CMP_SaveTexture(const char *destFile, CMP_MipSet *pMipSet); CMP_ERROR CMP_API CMP_ProcessTexture(CMP_MipSet* srcMipSet, CMP_MipSet* dstMipSet, KernelOptions kernelOptions, CMP_Feedback_Proc pFeedbackProc); CMP_ERROR CMP_API CMP_CompressTexture(KernelOptions *options,CMP_MipSet srcMipSet,CMP_MipSet dstMipSet,CMP_Feedback_Proc pFeedback); CMP_VOID CMP_API CMP_Format2FourCC(CMP_FORMAT format, CMP_MipSet *pMipSet); CMP_FORMAT CMP_API CMP_ParseFormat(char* pFormat); CMP_INT CMP_API CMP_NumberOfProcessors(); CMP_VOID CMP_API CMP_FreeMipSet(CMP_MipSet *MipSetIn); CMP_VOID CMP_API CMP_GetMipLevel(CMP_MipLevel *data, const CMP_MipSet* pMipSet, CMP_INT nMipLevel, CMP_INT nFaceOrSlice); //-------------------------------------------- // CMP_Compute Lib: Host level interface //-------------------------------------------- CMP_ERROR CMP_API CMP_CreateComputeLibrary(CMP_MipSet *srcTexture, KernelOptions *kernelOptions, void *Reserved); CMP_ERROR CMP_API CMP_DestroyComputeLibrary(CMP_BOOL forceClose); CMP_ERROR CMP_API CMP_SetComputeOptions(ComputeOptions *options); //--------------------------------------------------------- // Generic API to access the core using CMP_EncoderSetting //---------------------------------------------------------- CMP_ERROR CMP_API CMP_CreateBlockEncoder(void **blockEncoder, CMP_EncoderSetting encodeSettings); CMP_ERROR CMP_API CMP_CompressBlock(void **blockEncoder,void *srcBlock, unsigned int sourceStride, void *dstBlock, unsigned int dstStride); CMP_ERROR CMP_API CMP_CompressBlockXY(void **blockEncoder,unsigned int blockx, unsigned int blocky, void *imgSrc, unsigned int sourceStride, void *cmpDst, unsigned int dstStride); void CMP_API CMP_DestroyBlockEncoder(void **blockEncoder); #ifdef __cplusplus }; #endif #endif // CMP_FRAMEWORK_H
aliyun/aliyun-openapi-cpp-sdk
dms-enterprise/src/model/SearchTableRequest.cc
<reponame>aliyun/aliyun-openapi-cpp-sdk<filename>dms-enterprise/src/model/SearchTableRequest.cc /* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/dms-enterprise/model/SearchTableRequest.h> using AlibabaCloud::Dms_enterprise::Model::SearchTableRequest; SearchTableRequest::SearchTableRequest() : RpcServiceRequest("dms-enterprise", "2018-11-01", "SearchTable") { setMethod(HttpRequest::Method::Post); } SearchTableRequest::~SearchTableRequest() {} bool SearchTableRequest::getReturnGuid() const { return returnGuid_; } void SearchTableRequest::setReturnGuid(bool returnGuid) { returnGuid_ = returnGuid; setParameter(std::string("ReturnGuid"), returnGuid ? "true" : "false"); } std::string SearchTableRequest::getSearchKey() const { return searchKey_; } void SearchTableRequest::setSearchKey(const std::string &searchKey) { searchKey_ = searchKey; setParameter(std::string("SearchKey"), searchKey); } std::string SearchTableRequest::getSearchRange() const { return searchRange_; } void SearchTableRequest::setSearchRange(const std::string &searchRange) { searchRange_ = searchRange; setParameter(std::string("SearchRange"), searchRange); } long SearchTableRequest::getTid() const { return tid_; } void SearchTableRequest::setTid(long tid) { tid_ = tid; setParameter(std::string("Tid"), std::to_string(tid)); } int SearchTableRequest::getPageNumber() const { return pageNumber_; } void SearchTableRequest::setPageNumber(int pageNumber) { pageNumber_ = pageNumber; setParameter(std::string("PageNumber"), std::to_string(pageNumber)); } std::string SearchTableRequest::getSearchTarget() const { return searchTarget_; } void SearchTableRequest::setSearchTarget(const std::string &searchTarget) { searchTarget_ = searchTarget; setParameter(std::string("SearchTarget"), searchTarget); } int SearchTableRequest::getPageSize() const { return pageSize_; } void SearchTableRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter(std::string("PageSize"), std::to_string(pageSize)); } std::string SearchTableRequest::getEnvType() const { return envType_; } void SearchTableRequest::setEnvType(const std::string &envType) { envType_ = envType; setParameter(std::string("EnvType"), envType); } std::string SearchTableRequest::getDbType() const { return dbType_; } void SearchTableRequest::setDbType(const std::string &dbType) { dbType_ = dbType; setParameter(std::string("DbType"), dbType); }