repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
ksean/steamwebapi-node-sdk
util.js
2920
/** * steamwebapi * * Unofficial Steam Node.js SDK for interfacing with Steam's Web API * * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * * For more information, please refer to <http://unlicense.org/> * * @author Kennedy Software Solutions Inc. * @version 0.0.4 */ module.exports = { /********************************************************************************************************************** Helper functions **********************************************************************************************************************/ /** * Is object defined * * Helper function to determine if the obj parameter has been defined * * @param obj The object to check if defined * @returns {boolean} True if the object is defined, else false */ isDefined: function(obj) { return !(typeof obj === 'undefined') && obj !== null; }, /** * Is object a number * * Helper function to determine if the provided object is a number * * @param obj The object to check if a number * @returns {boolean} True if the object is a number, else false */ isNumber: function(obj) { return !isNaN(obj) && obj % 1 === 0; }, /** * Is object an array * * Helper function to determine if the provided object is an array * * @param obj The object to check if an array * @returns {boolean} True if the object is an array, else false */ isArray: function(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } };
unlicense
zakaihamilton/screens
packages/code/cmd/browser/cmd_mem.js
544
/* @author Zakai Hamilton @component CmdMem */ screens.cmd.mem = function CmdMem(me, { core }) { me.cmd = async function (terminal) { const memoryUsage = await core.server.memoryUsage(); const used = parseInt(memoryUsage.heapUsed / 1024 / 1024); core.property.set(terminal, "print", `The server uses approximately ${used} MB`); for (let param in memoryUsage) { core.property.set(terminal, "print", param + ": " + memoryUsage[param]); } core.cmd.exit(terminal); }; };
unlicense
marmorkuchen-net/mission-control-server
app/assets/scripts/info.js
311
(function(window, $, UNM) { 'use strict'; var INFO_ENDPOINT = '/info'; // public var info = {}; info.get = function(eSuccess) { $.ajax(INFO_ENDPOINT, { success: function(eResponse) { eSuccess(JSON.parse(eResponse)); } }); }; UNM.info = info; })(window, $, UNM);
unlicense
CaddyDz/Ruby
p2/ch9/hashes/s5/invert.rb
41
h = { 1 => "one", 2 => "two"} p h.invert
unlicense
gvlfm78/BukkitOldCombatMechanics
src/main/java/kernitus/plugin/OldCombatMechanics/module/Module.java
3150
package kernitus.plugin.OldCombatMechanics.module; import kernitus.plugin.OldCombatMechanics.OCMMain; import kernitus.plugin.OldCombatMechanics.utilities.Config; import kernitus.plugin.OldCombatMechanics.utilities.Messenger; import org.apache.commons.lang.WordUtils; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.Listener; /** * A module providing some specific functionality, e.g. restoring fishing rod knockback. */ public abstract class Module implements Listener { protected OCMMain plugin; private final String configName; private final String moduleName; /** * Creates a new module. * * @param plugin the plugin instance * @param configName the name of the module in the config */ protected Module(OCMMain plugin, String configName){ this.plugin = plugin; this.configName = configName; this.moduleName = getClass().getSimpleName(); } /** * Checks whether the module is enabled in the given world. * * @param world the world to check. Null to check whether it is globally disabled * @return true if the module is enabled in that world */ public boolean isEnabled(World world){ return Config.moduleEnabled(configName, world); } /** * Checks whether this module is globally en/disabled. * * @return true if this module is globally enabled */ public boolean isEnabled(){ return isEnabled(null); } /** * Checks whether a given setting for this module is enabled. * * @param name the name of the setting * @return true if the setting with that name is enabled. Returns false if the setting did not exist. */ public boolean isSettingEnabled(String name){ return plugin.getConfig().getBoolean(configName + "." + name, false); } /** * Returns the configuration section for this module. * * @return the configuration section for this module */ public ConfigurationSection module(){ return plugin.getConfig().getConfigurationSection(configName); } /** * Called when the plugin is reloaded. Should re-read all relevant config keys and other resources that might have * changed. */ public void reload(){ // Intentionally left blank! Meant for individual modules to use. } /** * Outputs a debug message. * * @param text the message text */ protected void debug(String text){ Messenger.debug("[" + moduleName + "] " + text); } /** * Sends a debug message to the given command sender. * * @param text the message text * @param sender the sender to send it to */ protected void debug(String text, CommandSender sender){ if(Config.debugEnabled()){ Messenger.send(sender, "&8&l[&fDEBUG&8&l][&f" + moduleName + "&8&l]&7 " + text); } } @Override public String toString(){ return WordUtils.capitalizeFully(configName.replaceAll("-", " ")); } }
unlicense
dm1024/leetcode
c++/best_time_to_buy_and_sell_stock_iv/test.cpp
700
#include <gtest/gtest.h> #include "solution.h" using namespace std; TEST(test, testcase0) { vector<int> prices = {5,4,6,7,9,1,8,7}; EXPECT_EQ(7, Solution().maxProfit(1, prices)); EXPECT_EQ(12, Solution().maxProfit(2, prices)); } TEST(test, testcase1) { vector<int> prices = {6,1,3,2,4,7}; EXPECT_EQ(6, Solution().maxProfit(1, prices)); EXPECT_EQ(7, Solution().maxProfit(2, prices)); } TEST(test, testcase2) { vector<int> prices = {1,2,4,2,5,7,2,4,9,0}; EXPECT_EQ(8, Solution().maxProfit(1, prices)); EXPECT_EQ(13, Solution().maxProfit(2, prices)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
unlicense
greenrobot-team/greenrobot-examples
greendao/app/src/main/java/com/example/greendao/ExampleApp.java
1565
package com.example.greendao; import android.app.Application; import android.content.Context; import com.example.greendao.model.DaoMaster; import com.example.greendao.model.DaoSession; import com.example.greendao.model.NoteDao; import org.greenrobot.greendao.database.Database; public class ExampleApp extends Application { private static DaoSession daoSession; @Override public void onCreate() { super.onCreate(); getDaoSession(this); } public static DaoSession getDaoSession(Context context) { if (daoSession == null) { ExampleOpenHelper openHelper = new ExampleOpenHelper(context.getApplicationContext(), "example.db"); DaoMaster daoMaster = new DaoMaster(openHelper.getWritableDatabase()); daoSession = daoMaster.newSession(); } return daoSession; } public static class ExampleOpenHelper extends DaoMaster.OpenHelper { public ExampleOpenHelper(Context context, String name) { super(context, name); } @Override public void onCreate(Database db) { super.onCreate(db); // INSERT INTO NOTE (_id, DATE, TEXT) VALUES(1, 0, 'Example Note') db.execSQL("INSERT INTO " + NoteDao.TABLENAME + " (" + NoteDao.Properties.Id.columnName + ", " + NoteDao.Properties.Date.columnName + ", " + NoteDao.Properties.Text.columnName + ") VALUES(1, 0, 'Example Note')"); } } }
unlicense
tiduszhang/WPFSolution
01.Base/01.Common/Common/WorkPath.cs
4040
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Common { /// <summary> /// FileName: WorkPath.cs /// CLRVersion: 4.0.30319.42000 /// @author zhangsx /// @date 2017/04/12 11:18:19 /// Corporation: /// Description: /// </summary> public static class WorkPath { /// <summary> /// 公共工作目录-该目录根据程序集名称创建-访问时一般不需要管理员权限,若目录不存在需要手动创建。 /// </summary> public static readonly string ApplicationDataPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\"; /// <summary> /// 公共工作目录-该目录根据程序集名称创建-访问时一般不需要管理员权限,若目录不存在需要手动创建。 /// </summary> public static readonly string ApplicationWorkPath = ApplicationDataPath + @"\" + System.Reflection.Assembly.GetEntryAssembly().GetName().Name + @"\"; /// <summary> /// 应用程序所在目录-应用程序安装目录,可能需要管理员权限,该目录一定存在。 /// </summary> public static readonly string ExecPath = System.AppDomain.CurrentDomain.BaseDirectory; /// <summary> /// 当前应用程序集执行程序名称 /// </summary> public static readonly string AssemblyName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; /// <summary> /// 获取私有目录-只允许程序集安装目录下子目录 /// </summary> /// <returns></returns> public static string GetPrivetePath() { string strPrivatePath = ""; try { var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); System.Xml.XmlDocument configFile = new System.Xml.XmlDocument(); configFile.Load(config.FilePath); strPrivatePath = configFile.SelectSingleNode("configuration/runtime").FirstChild.ChildNodes[0].Attributes[0].Value; } catch { } return strPrivatePath; } /// <summary> /// 创建应用程序域 /// </summary> /// <returns></returns> public static AppDomain CreateDomain(string DomainName = "Domain") { //启动应用程序,并且开启影像复制。 if (!System.IO.Directory.Exists(WorkPath.ApplicationWorkPath)) { System.IO.Directory.CreateDirectory(WorkPath.ApplicationWorkPath); } string strPrivatePath = WorkPath.GetPrivetePath(); string strWorkPath = WorkPath.ExecPath; // + ";" + WorkPath.ExecPath + @"\Plugins\"; string[] directories = strPrivatePath.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); if (directories != null && directories.Length > 0) { directories.ToList().ForEach(directorie => { strWorkPath += ";" + WorkPath.ExecPath + directorie; }); } AppDomainSetup appDomainSetup = new AppDomainSetup(); //appDomainSetup.PrivateBinPath = strWorkPath; appDomainSetup.ApplicationBase = WorkPath.ExecPath; appDomainSetup.CachePath = WorkPath.ApplicationDataPath; appDomainSetup.ShadowCopyDirectories = strWorkPath; appDomainSetup.ShadowCopyFiles = "true"; appDomainSetup.ApplicationName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; System.AppDomain appDomain = System.AppDomain.CreateDomain(DomainName, new System.Security.Policy.Evidence(AppDomain.CurrentDomain.Evidence), appDomainSetup); return appDomain; } } }
unlicense
rabbit-aaron/australia-nsw-public-holidays
test/isAdditionalDay.php
1045
<?php error_reporting(E_ALL); require_once dirname(__FILE__).'/../holidays.php'; function testNotAdditionalDay0(){ // Christmas Day falls on Thursday, no Additional Days assert(!isAdditionalDay(new DateTime('2014-12-27'))); } testNotAdditionalDay0(); function testIsAdditionalDay0(){ // Boxing Day falls on Saturday // One Additional Day on the next Monday assert(isAdditionalDay(new DateTime('2015-12-28'))); assert(!isAdditionalDay(new DateTime('2015-12-29'))); } testIsAdditionalDay0(); function testIsAdditionalDay1(){ // Christmas Day falls on Saturday and Boxing Day falls on Sunday // Two Additional Days on the next Monday and Tuesday assert(isAdditionalDay(new DateTime('2004-12-27'))); assert(isAdditionalDay(new DateTime('2004-12-28'))); } testIsAdditionalDay1(); function testIsAdditionalDay2(){ // Christmas Day on Sunday, Boxing Day falls on Monday // One Additional Day on the next Tuesday assert(isAdditionalDay(new DateTime('2011-12-27'))); } testIsAdditionalDay2();
unlicense
spaceyjase/Survivor
Assets/AstarPathfindingProject/Core/Serialization/TinyJson.cs
12548
using UnityEngine; using System.Collections.Generic; using Pathfinding.WindowsStore; using System; #if NETFX_CORE using System.Linq; using WinRTLegacy; #endif namespace Pathfinding.Serialization { public class JsonMemberAttribute : System.Attribute { } public class JsonOptInAttribute : System.Attribute { } /** A very tiny json serializer. * It is not supposed to have lots of features, it is only intended to be able to serialize graph settings * well enough. */ public class TinyJsonSerializer { System.Text.StringBuilder output = new System.Text.StringBuilder(); Dictionary<Type, Action<System.Object> > serializers = new Dictionary<Type, Action<object> >(); static readonly System.Globalization.CultureInfo invariantCulture = System.Globalization.CultureInfo.InvariantCulture; public static void Serialize (System.Object obj, System.Text.StringBuilder output) { new TinyJsonSerializer() { output = output }.Serialize(obj); } TinyJsonSerializer () { serializers[typeof(float)] = v => output.Append(((float)v).ToString("R", invariantCulture)); serializers[typeof(bool)] = v => output.Append((bool)v ? "true" : "false"); serializers[typeof(Version)] = serializers[typeof(uint)] = serializers[typeof(int)] = v => output.Append(v.ToString()); serializers[typeof(string)] = v => output.AppendFormat("\"{0}\"", v.ToString().Replace("\"", "\\\"")); serializers[typeof(Vector2)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1} }}", ((Vector2)v).x.ToString("R", invariantCulture), ((Vector2)v).y.ToString("R", invariantCulture)); serializers[typeof(Vector3)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1}, \"z\": {2} }}", ((Vector3)v).x.ToString("R", invariantCulture), ((Vector3)v).y.ToString("R", invariantCulture), ((Vector3)v).z.ToString("R", invariantCulture)); serializers[typeof(Pathfinding.Util.Guid)] = v => output.AppendFormat("{{ \"value\": \"{0}\" }}", v.ToString()); serializers[typeof(LayerMask)] = v => output.AppendFormat("{{ \"value\": {0} }}", ((int)(LayerMask)v).ToString()); } void Serialize (System.Object obj) { if (obj == null) { output.Append("null"); return; } var type = obj.GetType(); var typeInfo = WindowsStoreCompatibility.GetTypeInfo(type); if (serializers.ContainsKey(type)) { serializers[type] (obj); } else if (typeInfo.IsEnum) { output.Append('"' + obj.ToString() + '"'); } else if (obj is System.Collections.IList) { output.Append("["); var arr = obj as System.Collections.IList; for (int i = 0; i < arr.Count; i++) { if (i != 0) output.Append(", "); Serialize(arr[i]); } output.Append("]"); } else if (obj is UnityEngine.Object) { SerializeUnityObject(obj as UnityEngine.Object); } else { #if NETFX_CORE var optIn = typeInfo.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonOptInAttribute)); #else var optIn = typeInfo.GetCustomAttributes(typeof(JsonOptInAttribute), true).Length > 0; #endif output.Append("{"); #if NETFX_CORE var fields = typeInfo.DeclaredFields.Where(f => !f.IsStatic).ToArray(); #else var fields = type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); #endif bool earlier = false; foreach (var field in fields) { if ((!optIn && field.IsPublic) || #if NETFX_CORE field.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonMemberAttribute)) #else field.GetCustomAttributes(typeof(JsonMemberAttribute), true).Length > 0 #endif ) { if (earlier) { output.Append(", "); } earlier = true; output.AppendFormat("\"{0}\": ", field.Name); Serialize(field.GetValue(obj)); } } output.Append("}"); } } void QuotedField (string name, string contents) { output.AppendFormat("\"{0}\": \"{1}\"", name, contents); } void SerializeUnityObject (UnityEngine.Object obj) { // Note that a unityengine can be destroyed as well if (obj == null) { Serialize(null); return; } output.Append("{"); QuotedField("Name", obj.name); output.Append(", "); QuotedField("Type", obj.GetType().FullName); //Write scene path if the object is a Component or GameObject var component = obj as Component; var go = obj as GameObject; if (component != null || go != null) { if (component != null && go == null) { go = component.gameObject; } var helper = go.GetComponent<UnityReferenceHelper>(); if (helper == null) { Debug.Log("Adding UnityReferenceHelper to Unity Reference '"+obj.name+"'"); helper = go.AddComponent<UnityReferenceHelper>(); } //Make sure it has a unique GUID helper.Reset(); output.Append(", "); QuotedField("GUID", helper.GetGUID().ToString()); } output.Append("}"); } } /** A very tiny json deserializer. * It is not supposed to have lots of features, it is only intended to be able to deserialize graph settings * well enough. Not much validation of the input is done. */ public class TinyJsonDeserializer { System.IO.TextReader reader; static readonly System.Globalization.NumberFormatInfo numberFormat = System.Globalization.NumberFormatInfo.InvariantInfo; /** Deserializes an object of the specified type. * Will load all fields into the \a populate object if it is set (only works for classes). */ public static System.Object Deserialize (string text, Type type, System.Object populate = null) { return new TinyJsonDeserializer() { reader = new System.IO.StringReader(text) }.Deserialize(type, populate); } /** Deserializes an object of type tp. * Will load all fields into the \a populate object if it is set (only works for classes). */ System.Object Deserialize (Type tp, System.Object populate = null) { var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp); if (tpInfo.IsEnum) { return Enum.Parse(tp, EatField()); } else if (TryEat('n')) { Eat("ull"); TryEat(','); return null; } else if (Type.Equals(tp, typeof(float))) { return float.Parse(EatField(), numberFormat); } else if (Type.Equals(tp, typeof(int))) { return int.Parse(EatField(), numberFormat); } else if (Type.Equals(tp, typeof(uint))) { return uint.Parse(EatField(), numberFormat); } else if (Type.Equals(tp, typeof(bool))) { return bool.Parse(EatField()); } else if (Type.Equals(tp, typeof(string))) { return EatField(); } else if (Type.Equals(tp, typeof(Version))) { return new Version(EatField()); } else if (Type.Equals(tp, typeof(Vector2))) { Eat("{"); var result = new Vector2(); EatField(); result.x = float.Parse(EatField(), numberFormat); EatField(); result.y = float.Parse(EatField(), numberFormat); Eat("}"); return result; } else if (Type.Equals(tp, typeof(Vector3))) { Eat("{"); var result = new Vector3(); EatField(); result.x = float.Parse(EatField(), numberFormat); EatField(); result.y = float.Parse(EatField(), numberFormat); EatField(); result.z = float.Parse(EatField(), numberFormat); Eat("}"); return result; } else if (Type.Equals(tp, typeof(Pathfinding.Util.Guid))) { Eat("{"); EatField(); var result = Pathfinding.Util.Guid.Parse(EatField()); Eat("}"); return result; } else if (Type.Equals(tp, typeof(LayerMask))) { Eat("{"); EatField(); var result = (LayerMask)int.Parse(EatField()); Eat("}"); return result; } else if (Type.Equals(tp, typeof(List<string>))) { System.Collections.IList result = new List<string>(); Eat("["); while (!TryEat(']')) { result.Add(Deserialize(typeof(string))); TryEat(','); } return result; } else if (tpInfo.IsArray) { List<System.Object> ls = new List<System.Object>(); Eat("["); while (!TryEat(']')) { ls.Add(Deserialize(tp.GetElementType())); TryEat(','); } var arr = Array.CreateInstance(tp.GetElementType(), ls.Count); ls.ToArray().CopyTo(arr, 0); return arr; } else if (Type.Equals(tp, typeof(Mesh)) || Type.Equals(tp, typeof(Texture2D)) || Type.Equals(tp, typeof(Transform)) || Type.Equals(tp, typeof(GameObject))) { return DeserializeUnityObject(); } else { var obj = populate ?? Activator.CreateInstance(tp); Eat("{"); while (!TryEat('}')) { var name = EatField(); var field = tp.GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (field == null) { SkipFieldData(); } else { field.SetValue(obj, Deserialize(field.FieldType)); } TryEat(','); } return obj; } } UnityEngine.Object DeserializeUnityObject () { Eat("{"); var result = DeserializeUnityObjectInner(); Eat("}"); return result; } UnityEngine.Object DeserializeUnityObjectInner () { // Ignore InstanceID field (compatibility only) var fieldName = EatField(); if (fieldName == "InstanceID") { EatField(); fieldName = EatField(); } if (fieldName != "Name") throw new Exception("Expected 'Name' field"); string name = EatField(); if (name == null) return null; if (EatField() != "Type") throw new Exception("Expected 'Type' field"); string typename = EatField(); // Remove assembly information if (typename.IndexOf(',') != -1) { typename = typename.Substring(0, typename.IndexOf(',')); } // Note calling through assembly is more stable on e.g WebGL var type = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly.GetType(typename); type = type ?? WindowsStoreCompatibility.GetTypeInfo(typeof(Transform)).Assembly.GetType(typename); if (Type.Equals(type, null)) { Debug.LogError("Could not find type '"+typename+"'. Cannot deserialize Unity reference"); return null; } // Check if there is another field there EatWhitespace(); if ((char)reader.Peek() == '"') { if (EatField() != "GUID") throw new Exception("Expected 'GUID' field"); string guid = EatField(); foreach (var helper in UnityEngine.Object.FindObjectsOfType<UnityReferenceHelper>()) { if (helper.GetGUID() == guid) { if (Type.Equals(type, typeof(GameObject))) { return helper.gameObject; } else { return helper.GetComponent(type); } } } } // Try to load from resources UnityEngine.Object[] objs = Resources.LoadAll(name, type); for (int i = 0; i < objs.Length; i++) { if (objs[i].name == name || objs.Length == 1) { return objs[i]; } } return null; } void EatWhitespace () { while (char.IsWhiteSpace((char)reader.Peek())) reader.Read(); } void Eat (string s) { EatWhitespace(); for (int i = 0; i < s.Length; i++) { var c = (char)reader.Read(); if (c != s[i]) { throw new Exception("Expected '" + s[i] + "' found '" + c + "'\n\n..." + reader.ReadLine()); } } } System.Text.StringBuilder builder = new System.Text.StringBuilder(); string EatUntil (string c, bool inString) { builder.Length = 0; bool escape = false; while (true) { var readInt = reader.Peek(); if (!escape && (char)readInt == '"') { inString = !inString; } var readChar = (char)readInt; if (readInt == -1) { throw new Exception("Unexpected EOF"); } else if (!escape && readChar == '\\') { escape = true; reader.Read(); } else if (!inString && c.IndexOf(readChar) != -1) { break; } else { builder.Append(readChar); reader.Read(); escape = false; } } return builder.ToString(); } bool TryEat (char c) { EatWhitespace(); if ((char)reader.Peek() == c) { reader.Read(); return true; } return false; } string EatField () { var result = EatUntil("\",}]", TryEat('"')); TryEat('\"'); TryEat(':'); TryEat(','); return result; } void SkipFieldData () { var indent = 0; while (true) { EatUntil(",{}[]", false); var last = (char)reader.Peek(); switch (last) { case '{': case '[': indent++; break; case '}': case ']': indent--; if (indent < 0) return; break; case ',': if (indent == 0) { reader.Read(); return; } break; default: throw new System.Exception("Should not reach this part"); } reader.Read(); } } } }
unlicense
rudo6/MealPlanet_version2.0
src/test/java/sk/upjs/ics/mealplanet/MySqlIngredientDaoTest.java
2183
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sk.upjs.ics.mealplanet; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Patrik */ public class MySqlIngredientDaoTest { public MySqlIngredientDaoTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of addIngredient method, of class MySqlIngredientDao. */ @Test public void testAddIngredient() { System.out.println("addIngredient"); MySqlIngredientDao instance = new MySqlIngredientDao(); Ingredient ingredient = new Ingredient(); ingredient.setName("Potkan"); ingredient.setCarb(20); ingredient.setFat(30); ingredient.setProtein(20); List<Ingredient> ingredients = instance.getAllOrdered(); int pocetPred=ingredients.size(); instance.addIngredient(ingredient); ingredients=instance.getAllOrdered(); int pocetPo=ingredients.size(); assertEquals(pocetPred+1, pocetPo); } /** * Test of getAllOrdered method, of class MySqlIngredientDao. */ @Test public void testGetAllOrdered() { System.out.println("getAllOrdered"); MySqlIngredientDao instance = new MySqlIngredientDao(); int expResult = 44; String prve = "Bean"; String posledne = "Wholmeal flour"; List<Ingredient> result = instance.getAllOrdered(); assertEquals(expResult, result.size()); assertEquals(prve, result.get(0).getName()); assertEquals(posledne, result.get(result.size()-1).getName()); } }
unlicense
T-Gee/com.tongge.tools
packageMaker/src/main/java/com/tongge/createPackage/exception/AppException.java
1538
package com.tongge.createPackage.exception; /** * * Created on 2010-9-18 * <p>Title: ³ö²î²¹Öú_[×ÓϵͳͳÃû]_[Ä£¿éÃû]/p> * <p>Description: [ÃèÊö¸ÃÀà¸ÅÒª¹¦ÄܽéÉÜ]</p> * <p>Copyright: Copyright (c) 2009</p> * <p>Company: </p> * <p>Department: </p> * @author:Ù¡¹ã¶÷ * @email:[email protected] * @version 1.0 */ public class AppException extends Exception { /** * {×ֶι¦ÄÜÃèÊö} */ private static final long serialVersionUID = -3618558822682089670L; /** * * Created on 2010-9-18 * <p>Description: [ʹÓÃlogicTxt,cause°ü×°Ò»¸öAppException]</p> * @author:Ù¡¹ã¶÷ [email protected] * @update:[ÈÕÆÚYYYY-MM-DD] [¸ü¸ÄÈËÐÕÃû][ÐÞ¸Ä˵Ã÷] * @param logicTxt * @param cause * @return. */ public static AppException pack(String logicTxt, Exception cause) { AppException logicException = new AppException(logicTxt, cause); return logicException; } /** * <p>Discription:[´ø²ÎÊýµÄ¹¹ÔìÆ÷]</p> * @coustructor */ public AppException(String arg0) { super(arg0); System.exit(1); } /** * <p>Discription:[´ø²ÎÊýµÄ¹¹ÔìÆ÷ÖØÔØ]</p> * @coustructor */ public AppException(Throwable arg0) { super(arg0); System.exit(1); } /** * * <p>Discription:[´ø²ÎÊýµÄ¹¹ÔìÆ÷ÖØÔØ</p> * @coustructor ·½·¨. */ public AppException(String arg0, Throwable arg1) { super(arg0, arg1); System.exit(1); } }
unlicense
romalxr/MyRep
Patterns/PatternStrategy/PatternStrategy/Ducks/SimpleDuck.cs
514
using PatternStrategy.Fly; using PatternStrategy.Quack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PatternStrategy.Ducks { class SimpleDuck : DuckBase { public SimpleDuck() { quackBehavior = new SimpleQuack(); flyBehavior = new FlyWithWings(); } public override void Display() { Console.WriteLine("Hi! I'm a simple duck!"); } } }
unlicense
KamilSzot/365_programs
2017-03-10/app/src/test/java/com/niceshotapps/sendsms/ExampleUnitTest.java
418
package com.niceshotapps.sendsms; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
unlicense
reenigne/reenigne
8088/asset_manager/asset_manager.cpp
4509
// static const int assetCount = 99; // Filled in by asset preparer Word getLowestFreeSegment() { // TODO } Word getEndOfConventionalMemorySegment() { geninterrupt(0x12); // returns amount of conventional RAM in 1kB blocks return _AX << 6; // multiply by 64 to get segments } Word getCurrentTime() { // TODO } struct AssetData { Word segment; // 0 for not loaded Word firstUsed; Word lastUsed; Word uncompressedLength; // in segments DWord diskOffset; // 0x80000000 = locked from moving // 0x40000000 = locked from discarding Byte decompressorAsset; Byte dictionaryAsset; Word previousAsset; // or previous free segment, if it points to past the end of the asset table }; class AssetManager { public: AssetManager() { tableSegment = getLowestFreeSegment(); startSegment = tableSegment + assetCount; endSegment = getEndOfConventionalMemorySegment(); firstFreeSegment = startSegment; // TODO: read asset data } Word getAsset(Word asset, bool lock = false) { AssetData far* data = getAssetData(asset); // See if it's already loaded data->lastUsed = getCurrentTime(); if (data->segment != 0) return data->segment; // See if we have room to load it } private: AssetData far* getAssetData(Word asset) { return (AssetData far *)MK_FP(tableSegment + asset, 0); } Word tableSegment; Word startSegment; Word endSegment; Word firstFreeSegment; }; // Types of asset: // Loaded but not compressed on disk // Initial decompressor // Dictionaries? // Normal (loaded, compressed on disk) // Generated (decompressor but no on-disk data - dictionary and diskOffset may be used as parameters) // read only data // read/write data - locked from unloading // BSS // Uninitialised // Stack // Allocated data // Disk cluster cache // Do we need a segment header with the uncompressed data? // Probably not - keep all data for loaded assets in the AssetData arrays, and thread free areas together in a list // How should we organise the data structures? Linked list? Tree? // When program is loaded, load an initial set of assets as well (asset table, decompressor, dictionary needed to load the first thing) /* * Ideal asset manager for this sort of thing: * Keeps track of most recently used * Timestamps are 16-bit. 1 second resolution gives 18 hour span, 2 second resolution gives 36 hour span * If we run out of time, make timestamps in first half of span updated to midpoint. * When a new asset requested, all unlocked older asset pointers are invalidated * Preload all assets for a particular level * When we run out of memory, mark as "to unload" assets is LRU order until there will be enough room * Then work backwards towards LRU, unmarking assets if doing so would not cause there to be not enough room * If there is enough room but not enough contiguous room, compact * We want to try to keep assets at low addresses that are likely to stick around for a long time - the ones which have a long lifespan * So keep track of loaded time as well as last used * Try to find a gap to move the highest block into * If there is one, move it and try again * If there isn't one, mark as "to unload" a set of assets until we have a big enough space (then unmark any that we don't actually need to unload) * Game can hint that an old asset is unimportant by changing its load time to "just now". * Game can hint that a new asset will be needed again by changing its load time to old. * Same with compressed versions of assets * To take advantage of EMS/XMS, just use as a disk cache * What about intermediate, may-be-needed-again assets? Can move those to EMS/XMS from conventional memory * Use https://github.com/vkrasnov/dictator to make an initial dictionary so that we get compression on small items * Add an asynchronous load from floppy routine * We want to cache sectors so that a sector that spans assets doesn't need to reloaded when decompressing both */ /* Rejected: // It'd be nice to not have to keep AssetData for entire game in memory at once - have directories? // Two level lookup for asset data - AssetData page and then item within page // Then pages loaded on demand // Only do this if we are spending too much RAM on AssetData - it slows everything down */
unlicense
vanzhiganov/NewsArggregator
WEB-INC/class.post.php
649
<?php class post { public function create() {} public function view($post_id) {} public function delete($post_id, $feed_id) {} public function get_item($intItemID) { $strQuery = "SELECT * FROM `feed_items` WHERE `item_id`={$intItemID}"; $doQuery = mysql_query($strQuery); if (mysql_error() <> "") { echo mysql_error()."<br>".$strQuery; } $res = mysql_fetch_object($doQuery); $item = new container_item($res->item_id, $res->feed_id, $res->pubdate_int, $res->title, $res->link, $res->description, $res->author, $res->category, $res->comments, $res->enclousure, $res->guid, $res->pubdate, $res->source); return $item; } }
unlicense
candr002/CS150
Lab 11/lab_11_template2016.cpp
5123
///lab 10 on linked lists. This is an important one. You will see /// a question similar to this on the lab final. //Programmer : fill this information in, or receive a zero for a grade. //Date : //Lab : //Description: #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; ///employeeType struct, node struct, typedef statement go here. // Function Prototypes void print(nodeType *); // Function to print a LL void printOne (employeeType one); nodeType* linkdListCreate2 (ifstream& inFile); nodeType* linkdListCreate1 (ifstream& inFile); employeeType getOne ( ifstream& dataIn ); int avgDependents (nodeType *list); int locateId(nodeType *list, int targetID); nodeType* deleteNode( nodeType *first, int deleteID); int main () { //get our input file stream handling taken care of ifstream dataFile; dataFile.open ( "Employees.txt" ); if (!dataFile) { cout << "\n\n\t INPUT FILE ERROR \n\n"; } //------------------------------------------------ ///Declare and initialize a head pointer to first node in list char choice ='U'; while((choice != 'B')&&(choice !='F')) { cout<<"Create list: Forwards(enter F) Backwards(enter B)\n"; cin >>choice; } ///Use a decision structure to create the list /// either forwards or backwards, according to the user input. ///print the list of employees /// calculate the average number of dependents cout<<"\nAverage # dependents: "; ///use locateID function to determine target value, then deleteNode ///to remove the employee at that node number from the LL int id=0, location=0; cout<<"\nEnter an ID to fire someone: "; cin>>id; loc = locateId(first, id); if(location!=0){ cout<<"\nID Number "<<id<<" was at node "<<location<<", and has been terminated.\n"<<loc; ///terminate the employee with the target ID number, by deleting the node cout <<"\n\nNew list:\n"; ///print the list of employees } else cout <"\nThat ID is not in our list.\n"; cout <<"\n"; return 0; } ///-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=:-@ ///----------------------------------------------------------------- //Creates a linked list by adding a new last node after each call to // the getOne function, thus inserting the nodes into the list in the // same order as the input file - returns pointer to first node in list. nodeType* linkdListCreate1 (ifstream& inFile){ return NULL; } ///----------------------------------------------------------------- //Creates a linked list by setting the first pointer to the new node // after each call to the getOne function, thus inserting nodes into // list in reverse order. returns pointer to first node in list. nodeType* linkdListCreate2 (ifstream& inFile){ return NULL; } ///----------------------------------------------------------------- //print makes a temp pointer to head of LL, and moves node //to node displaying the values of the members of each element void print(nodeType *first){ } ///----------------------------------------------------------------- //the getOne function reads one line of input data from the file stream, // and loads it into an employeeType class or struct object // that it returns to the calling function employeeType getOne ( ifstream& dataIn ){ employeeType one; dataIn >> one.firstName >> one.lastName >> one.gender >> one.idNum >> one.payrate >> one.dependents; return one; } ///----------------------------------------------------------------- //print out one employeeType class or struct object void printOne ( employeeType one){ cout << fixed << showpoint << setprecision (2); cout << "ID Num: " << one.idNum << endl; cout << "Name: " <<one.firstName << " " << one.lastName<< endl; cout << "-Gender: " << one.gender <<"\n"; cout << "-Payrate $"<< one.payrate <<"\n"; cout << "-Dependents " << one.dependents <<"\n"; } ///----------------------------------------------------------------- // in case of duplicates, the first occurrence of deleteItem is removed. // list can be ordered or unordered nodeType * deleteNode(nodeType *first, int deleteID) { }//end deleteNode //======================================================================= //calculates average number of dependents for all employees int avgDependents (nodeType *list){ }// end of average function //======================================================================= //======================================================================= //locates the number of the node in the list that //contains the target ID value. int locateId(nodeType *list, int targetID){ }// end of locate the ID function //======================================================================= ///-=-=-=-=-=-=-=-=-=-=-=-=-endOf-main=-=-=-=-=-=-=-=-=-=-=-=-=-=:-@
unlicense
tristen/leaflet-interact-intent
index.js
949
var hoverintent = require('hoverintent'); module.exports = window.L.Control.extend({ options: { clicktoplay: false }, onAdd: function(map) { var opts = { interval: 200 }; var container = L.DomUtil.create('div', 'interaction-intent-control'); var mask = map._createPane('leaflet-mask', map._container); if (this.options.clicktoplay) L.DomUtil.addClass(mask, 'leaflet-playback'); L.DomEvent.disableScrollPropagation(mask); hoverintent(map._container, function() { if (!L.DomUtil.hasClass(mask, 'leaflet-playback')) mask.style.display = 'none'; }, function() { mask.style.display = 'block'; }).options(opts); L.DomEvent.addListener(mask, 'click', function() { L.DomUtil.removeClass(mask, 'leaflet-playback'); mask.style.display = 'none'; }); return container; } });
unlicense
amarchen/log4qt-demo-sailfish
src/engine/person.cpp
1801
#include "person.h" #include "Logger" #include <QDebug> #include "LogStream" LOG4QT_DECLARE_STATIC_LOGGER(logger, Person) Person::Person(const QString& name, QObject *parent) : QObject(parent) { setName(name); logger()->debug("Person created with name %1", name); // I don't know why, but sometimes this message is missing from exactly syslog appender // when object is instantiated from QML (and with empty name) // Previous message (with %1) still prints fine // // TODO: Figure out what sort of magic happens there // Must be somehow related to default function parameter instantiation // ..but why only syslog appender is affected? logger()->info() << "Person created, name is " << name; } QString Person::name() const { return m_name; } void Person::setName(QString arg) { // For performance reasons it is better to use %1 syntax whenever you are not too lazy to do so // Then arg is not converted to string unless it is needed // (can be not needed if whole INFO level is disabled) logger()->info("setName for %1", arg); // Streaming syntax is a little easier to type, but less efficient // logger()->info() << "setName for " << arg; if (m_name != arg) { m_name = arg; emit nameChanged(arg); } } // QDebug and log4qt's streaming support // Unfortunately you need to have two functions to support both LOG4QTDEMOENGINE_EXPORT QDebug operator<<(QDebug dbg, const Person &person) { dbg.nospace() << "(qD: " << person.name() << ")"; return dbg.maybeSpace(); } LOG4QTDEMOENGINE_EXPORT Log4Qt::LogStream &operator<<(Log4Qt::LogStream rStream, const Person &rPerson) { rStream << "(lS: " << rPerson.name() << ")"; return rStream; }
unlicense
nature-track/wenCollege-CSharp
Web/teacher/Add.aspx.designer.cs
1788
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace Maticsoft.Web.teacher { public partial class Add { /// <summary> /// txtname 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtname; /// <summary> /// txtqita 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtqita; /// <summary> /// btnSave 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnSave; /// <summary> /// btnCancle 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnCancle; } }
unlicense
pra85/Android
PrimeNumberToast/gen/com/primenumbertoast/BuildConfig.java
162
/** Automatically generated file. DO NOT MODIFY */ package com.primenumbertoast; public final class BuildConfig { public final static boolean DEBUG = true; }
unlicense
dhcmrlchtdj/toolkit
javascript/fps.js
758
// https://github.com/mathieuancelin/js-repaint-perfs/blob/gh-pages/lib/monitor.js function FPS() { var bucketSize = 20; var bucket = []; var lastTime = Date.now(); this.ping = function() { var start = lastTime; var stop = Date.now(); var rate = 1000 / (stop - start); bucket.push(rate); if (bucket.length > bucketSize) bucket.shift(); var sum = 0; for (var i = 0; i < bucket.length; i++) sum = sum + bucket[i]; var fps = sum / bucket.length; lastTime = stop; return fps; }; } (function() { var fps = new FPS(); requestAnimationFrame(function loop() { console.log(Math.round(fps.ping())); requestAnimationFrame(loop); }); })();
unlicense
componavt/wcorpus
resources/views/lemma/context_intersection.blade.php
3881
<?php $list_count = $url_args['limit_num'] * ($url_args['page']-1) + 1; ?> @extends('layouts.page') @section('title') Lemma context intersection @stop @section('panel-heading') Lemma context intersection @stop @section('headExtra') {!!Html::style('css/select2.min.css')!!} {!!Html::style('css/text.css')!!} @stop @section('panel-body') {!! Form::open(['url' => '/lemma/context_intersection/', 'method' => 'get', 'class' => 'form-inline']) !!} @include('widgets.form._formitem_select2', ['name' => 'search_lemma1', 'class'=>'select-lemma1 form-control search-lemma', 'value' =>$url_args['search_lemma1'], 'values' => $lemma1_values, 'is_multiple' => false, 'attributes'=>['placeholder' => 'Lemma 1' ]]) @include('widgets.form._formitem_select2', ['name' => 'search_lemma2', 'class'=>'select-lemma2 form-control search-lemma', 'value' =>$url_args['search_lemma2'], 'values' => $lemma2_values, 'is_multiple' => false, 'attributes'=>['placeholder' => 'Lemma 2' ]]) @include('widgets.form._formitem_btn_submit', ['title' => 'View']) by @include('widgets.form._formitem_text', ['name' => 'limit_sentences', 'value' => $url_args['limit_sentences'], 'attributes'=>['size' => 5, 'placeholder' => 'Number of records' ]]) sentences,<span style='padding-right:20px'></span> by @include('widgets.form._formitem_text', ['name' => 'limit_lemmas', 'value' => $url_args['limit_lemmas'], 'attributes'=>['size' => 5, 'placeholder' => 'Number of records' ]]) lemmas {!! Form::close() !!} <div class="row"> <div class="col-sm-8"> <img src="http://latex.numberempire.com/render?Dist({v}^{1},{v}^{2}) := \frac{\, {\left|{context}_{1}\bigcap{context}_{2}\right|}^{2}\, }{\left|{context}_{1}\right|\cdot \left|{context}_{2}\right|} = \mathbf{{{$dist}}}" alt="Distance"> @include('lemma._sentence_list',[ 'limit'=>$url_args['limit_sentences'], 'list' => $sentence_list]) </div> <div class="col-sm-4"> @include('lemma._context_lemma_intersection',[ 'limit'=>$url_args['limit_lemmas'], 'list' => $lemma_list]) </div> </div> @stop @section('footScriptExtra') {!!Html::script('js/select2.min.js')!!} @stop @section('jqueryFunc') $(".select-lemma1").select2({ width: '300px', ajax: { url: "/lemma/list_with_pos", dataType: 'json', delay: 250, data: function (params) { return { q: params.term // search term }; }, processResults: function (data) { return { results: data }; }, cache: true } }); $(".select-lemma2").select2({ width: '300px', ajax: { url: "/lemma/list_with_pos", dataType: 'json', delay: 250, data: function (params) { return { q: params.term // search term }; }, processResults: function (data) { return { results: data }; }, cache: true } }); @stop
unlicense
ECain/ArcGISOnlineInteraction
AGORestCallTestFS/DataContractObjects/FeatureServiceObject.cs
660
using System.Runtime.Serialization; //Help: http://services.arcgis.com/help/index.html?applyedits.html namespace AGORestCallTestFS { [DataContract] class FeatureServiceObject { [DataMember] public string name { get; set; } [DataMember] public string type { get; set; } [DataMember] public string status { get; set; } [DataMember] public Database database { get; set; } [DataMember] public string capabilities { get; set; } [DataMember] public ConnectionAttributes connectionAttributes { get; set; } [DataMember] public int maxRecordCount { get; set; } } }
unlicense
SixtenLabs/SpawnOfVulkan
src/SixtenLabs.SpawnOfVulkan/Enums/ImageViewCreateFlags.cs
147
/// <summary> /// /// </summary> namespace SixtenLabs.SpawnOfVulkan { public enum ImageViewCreateFlags : int { None = 0 } }
unlicense
jan25/code_sorted
leetcode/weekly148/zigzag_array.py
913
''' https://leetcode.com/contest/weekly-contest-148/problems/decrease-elements-to-make-array-zigzag/ ''' def oddSolver(nums, st): if len(nums) - 1 - st >= 2: l, r = nums[st], nums[st + 2] l = min(nums[st + 1] - 1, l) r = min(nums[st + 1] - 1, r) diff = nums[st] - l + nums[st + 2] - r nums[st], nums[st + 2] = l, r return diff + oddSolver(nums, st + 2) if len(nums) - 1 - st <= 0: return 0 if nums[st + 1] <= nums[st]: diff = nums[st] - (nums[st + 1] - 1) nums[st] = nums[st + 1] - 1 return diff return 0 class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: if len(nums) < 2: return 0 odds = oddSolver([*nums], 0) evens = oddSolver(nums, 1) if nums[0] <= nums[1]: evens += nums[1] - nums[0] + 1 print (odds, evens, nums) return min(odds, evens)
unlicense
gacalves/GAC_ERP
GAC_ERP.Infrastructure.Identity/Models/SystemClaims.cs
742
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GAC_ERP.Infrastructure.Identity.Models { [Table("AspNetSystemClaimTypes")] public class SystemClaimType { public SystemClaimType() { Id = Guid.NewGuid(); } [Key] public Guid Id { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Fornceça um nome para a Claim")] [MaxLength(128, ErrorMessage = "Tamanho máximo {0} excedido")] [Display(Name = "Nome da Claim")] public string Name { get; set; } } }
unlicense
bitmovin/bitmovin-python
bitmovin/resources/models/codecconfigurations/h265_codec_configuration.py
19289
from bitmovin.errors import InvalidTypeError from bitmovin.resources.enums import H265Profile, H265Level, BAdapt, MaxCTUSize, TUInterDepth, TUIntraDepth, \ MotionSearch, VideoFormat, H265AdaptiveQuantizationMode from bitmovin.utils import Serializable from .video_codec_configuration import VideoCodecConfiguration from .color_config import ColorConfig class H265CodecConfiguration(VideoCodecConfiguration, Serializable): def __init__(self, name, bitrate, rate, profile, id_=None, description=None, custom_data=None, width=None, height=None, bframes=None, ref_frames=None, qp=None, max_bitrate=None, min_bitrate=None, bufsize=None, min_gop=None, max_gop=None, level=None, rc_lookahead=None, b_adapt=None, max_ctu_size=None, tu_intra_depth=None, tu_inter_depth=None, motion_search=None, sub_me=None, motion_search_range=None, weight_prediction_on_p_slice=None, weight_prediction_on_b_slice=None, sao=None, crf=None, pixel_format=None, color_config=None, max_keyframe_interval=None, min_keyframe_interval=None, scene_cut_threshold=None, enable_hlg_signaling=None, video_format=None, hdr=None, master_display=None, max_content_light_level=None, max_picture_average_light_level=None, sample_aspect_ratio_numerator=None, sample_aspect_ratio_denominator=None, adaptive_quantization_mode=None, psy_rate_distortion_optimization=None, psy_rate_distortion_optimization_quantization=None, cutree=None, qp_min=None, qp_max=None): super().__init__(id_=id_, custom_data=custom_data, name=name, description=description, bitrate=bitrate, rate=rate, width=width, height=height, pixel_format=pixel_format) self._profile = None self.profile = profile self.bframes = bframes self.refFrames = ref_frames self.qp = qp self.maxBitrate = max_bitrate self.minBitrate = min_bitrate self.bufsize = bufsize self.minGop = min_gop self.maxGop = max_gop self._level = None self.level = level self.rcLookahead = rc_lookahead self._bAdapt = None self.bAdapt = b_adapt self._maxCTUSize = None self.maxCTUSize = max_ctu_size self._tuIntraDepth = None self.tuIntraDepth = tu_intra_depth self._tuInterDepth = None self.tuInterDepth = tu_inter_depth self._motionSearch = None self.motionSearch = motion_search self.subMe = sub_me self.motionSearchRange = motion_search_range self.weightPredictionOnPSlice = weight_prediction_on_p_slice self.weightPredictionOnBSlice = weight_prediction_on_b_slice self.sao = sao self._crf = None self.crf = crf self._colorConfig = None self.colorConfig = color_config self.maxKeyframeInterval = max_keyframe_interval self.minKeyframeInterval = min_keyframe_interval self.sceneCutThreshold = scene_cut_threshold self.enableHlgSignaling = enable_hlg_signaling self._videoFormat = None self.videoFormat = video_format self.hdr = hdr self.masterDisplay = master_display self.maxContentLightLevel = max_content_light_level self.maxPictureAverageLightLevel = max_picture_average_light_level self.sampleAspectRatioNumerator = sample_aspect_ratio_numerator self.sampleAspectRatioDenominator = sample_aspect_ratio_denominator self._adaptive_quantization_mode = None self.adaptiveQuantizationMode = adaptive_quantization_mode self.psyRateDistortionOptimization = psy_rate_distortion_optimization self.psyRateDistortionOptimizedQuantization = psy_rate_distortion_optimization_quantization self.cutree = cutree self.qpMin = qp_min self.qpMax = qp_max @property def colorConfig(self): return self._colorConfig @colorConfig.setter def colorConfig(self, new_color_config): if new_color_config is None: self._colorConfig = None elif isinstance(new_color_config, ColorConfig): self._colorConfig = new_color_config else: raise InvalidTypeError('colorConfig has to be of type ColorConfig') @property def profile(self): return self._profile @profile.setter def profile(self, new_profile): if new_profile is None: return if isinstance(new_profile, str): self._profile = new_profile elif isinstance(new_profile, H265Profile): self._profile = new_profile.value else: raise InvalidTypeError( 'Invalid type {} for profile: must be either str or H265Profile!'.format(type(new_profile))) @property def level(self): return self._level @level.setter def level(self, new_level): if new_level is None: return if isinstance(new_level, str): self._level = new_level elif isinstance(new_level, H265Level): self._level = new_level.value else: raise InvalidTypeError( 'Invalid type {} for level: must be either str or H265Level!'.format(type(new_level))) @property def bAdapt(self): if self._bAdapt is not None: return self._bAdapt else: return BAdapt.default().value @bAdapt.setter def bAdapt(self, new_badapt): if new_badapt is None: return if isinstance(new_badapt, str): self._bAdapt = new_badapt elif isinstance(new_badapt, BAdapt): self._bAdapt = new_badapt.value else: raise InvalidTypeError( 'Invalid type {} for bAdapt: must be either str or BAdapt!'.format(type(new_badapt))) @property def maxCTUSize(self): if self._maxCTUSize is not None: return self._maxCTUSize else: return MaxCTUSize.default().value @maxCTUSize.setter def maxCTUSize(self, new_max_ctu_size): if new_max_ctu_size is None: return if isinstance(new_max_ctu_size, str): self._maxCTUSize = new_max_ctu_size elif isinstance(new_max_ctu_size, MaxCTUSize): self._maxCTUSize = new_max_ctu_size.value else: raise InvalidTypeError( 'Invalid type {} for maxCTUSize: must be either str or MaxCTUSize!'.format(type(new_max_ctu_size))) @property def tuIntraDepth(self): if self._tuIntraDepth is not None: return self._tuIntraDepth else: return TUIntraDepth.default().value @tuIntraDepth.setter def tuIntraDepth(self, new_tu_intra_depth): if new_tu_intra_depth is None: return if isinstance(new_tu_intra_depth, str): self._tuIntraDepth = new_tu_intra_depth elif isinstance(new_tu_intra_depth, TUIntraDepth): self._tuIntraDepth = new_tu_intra_depth.value else: raise InvalidTypeError( 'Invalid type {} for tuIntraDepth: must be either str or TUIntraDepth!'.format( type(new_tu_intra_depth))) @property def tuInterDepth(self): if self._tuInterDepth is not None: return self._tuInterDepth else: return TUInterDepth.default().value @tuInterDepth.setter def tuInterDepth(self, new_tu_inter_depth): if new_tu_inter_depth is None: return if isinstance(new_tu_inter_depth, str): self._tuInterDepth = new_tu_inter_depth elif isinstance(new_tu_inter_depth, TUInterDepth): self._tuInterDepth = new_tu_inter_depth.value else: raise InvalidTypeError( 'Invalid type {} for tuInterDepth: must be either str or TUInterDepth!'.format( type(new_tu_inter_depth))) @property def motionSearch(self): if self._motionSearch is not None: return self._motionSearch else: return MotionSearch.default().value @motionSearch.setter def motionSearch(self, new_motion_search): if new_motion_search is None: return if isinstance(new_motion_search, str): self._motionSearch = new_motion_search elif isinstance(new_motion_search, MotionSearch): self._motionSearch = new_motion_search.value else: raise InvalidTypeError( 'Invalid type {} for motionSearch: must be either str or MotionSearch!'.format(type(new_motion_search))) @property def crf(self): return self._crf @crf.setter def crf(self, new_value): if new_value is None: return if not isinstance(new_value, float): raise InvalidTypeError('crf has to be a float value') self._crf = new_value @property def videoFormat(self): return self._videoFormat @videoFormat.setter def videoFormat(self, new_value): if new_value is None: self._videoFormat = None return if isinstance(new_value, str): self._videoFormat = new_value elif isinstance(new_value, VideoFormat): self._videoFormat = new_value.value else: raise InvalidTypeError( 'Invalid type {} for videoFormat: must be either str or VideoFormat!'.format(type(new_value))) @property def adaptiveQuantizationMode(self): return self._adaptive_quantization_mode @adaptiveQuantizationMode.setter def adaptiveQuantizationMode(self, new_adaptive_quantization_mode): if new_adaptive_quantization_mode is None: self._adaptive_quantization_mode = None elif isinstance(new_adaptive_quantization_mode, str): self._adaptive_quantization_mode = new_adaptive_quantization_mode elif isinstance(new_adaptive_quantization_mode, H265AdaptiveQuantizationMode): self._adaptive_quantization_mode = new_adaptive_quantization_mode.value else: raise InvalidTypeError( 'Invalid type {} for adaptiveQuantizationMode: '.format(type(new_adaptive_quantization_mode)) + 'must be either str or H265AdaptiveQuantizationMode.' ) @classmethod def parse_from_json_object(cls, json_object): video_codec_configuration = VideoCodecConfiguration.parse_from_json_object(json_object=json_object) id_ = video_codec_configuration.id custom_data = video_codec_configuration.customData name = video_codec_configuration.name description = video_codec_configuration.description width = video_codec_configuration.width height = video_codec_configuration.height bitrate = video_codec_configuration.bitrate rate = video_codec_configuration.rate pixel_format = video_codec_configuration.pixelFormat profile = json_object.get('profile') bframes = json_object.get('bframes') ref_frames = json_object.get('refFrames') qp = json_object.get('qp') max_bitrate = json_object.get('maxBitrate') min_bitrate = json_object.get('minBitrate') bufsize = json_object.get('bufsize') min_gop = json_object.get('minGop') max_gop = json_object.get('maxGop') level = json_object.get('level') rc_lookahead = json_object.get('rcLookahead') b_adapt = json_object.get('bAdapt') max_ctu_size = json_object.get('maxCTUSize') tu_intra_depth = json_object.get('tuIntraDepth') tu_inter_depth = json_object.get('tuInterDepth') motion_search = json_object.get('motionSearch') sub_me = json_object.get('subMe') motion_search_range = json_object.get('motionSearchRange') weight_prediction_on_p_slice = json_object.get('weightPredictionOnPSlice') weight_prediction_on_b_slice = json_object.get('weightPredictionOnBSlice') sao = json_object.get('sao') crf = json_object.get('crf') max_keyframe_interval = json_object.get('maxKeyframeInterval') min_keyframe_interval = json_object.get('minKeyframeInterval') scene_cut_threshold = json_object.get('sceneCutThreshold') enable_hlg_signaling = json_object.get('enableHlgSignaling') video_format = json_object.get('videoFormat') hdr = json_object.get('hdr') master_display = json_object.get('masterDisplay') max_content_light_level = json_object.get('maxContentLightLevel') max_picture_average_light_level = json_object.get('maxPictureAverageLightLevel') aspect_ratio_numerator = json_object.get('sampleAspectRatioNumerator') aspect_ratio_denominator = json_object.get('sampleAspectRatioDenominator') adaptive_quantization_mode = json_object.get('adaptiveQuantizationMode') psy_rate_distortion_optimization = json_object.get('psyRateDistortionOptimization') psy_rate_distortion_optimization_quantization = json_object.get('psyRateDistortionOptimizedQuantization') cutree = json_object.get('cutree') qp_min = json_object.get('qpMin') qp_max = json_object.get('qpMax') color_config = None color_config_json = json_object.get('colorConfig') if color_config_json is not None: copy_chroma_location_flag = color_config_json.get('copyChromaLocationFlag') copy_color_space_flag = color_config_json.get('copyColorSpaceFlag') copy_color_primaries_flag = color_config_json.get('copyColorPrimariesFlag') copy_color_range_flag = color_config_json.get('copyColorRangeFlag') copy_color_transfer_flag = color_config_json.get('copyColorTransferFlag') chroma_location = color_config_json.get('chromaLocation') color_space = color_config_json.get('colorSpace') color_primaries = color_config_json.get('colorPrimaries') color_range = color_config_json.get('colorRange') color_transfer = color_config_json.get('colorTransfer') input_color_space = color_config_json.get('inputColorSpace') input_color_range = color_config_json.get('inputColorRange') color_config = ColorConfig(copy_chroma_location_flag=copy_chroma_location_flag, copy_color_space_flag=copy_color_space_flag, copy_color_primaries_flag=copy_color_primaries_flag, copy_color_range_flag=copy_color_range_flag, copy_color_transfer_flag=copy_color_transfer_flag, chroma_location=chroma_location, color_space=color_space, color_primaries=color_primaries, color_range=color_range, color_transfer=color_transfer, input_color_space=input_color_space, input_color_range=input_color_range) h265_codec_configuration = H265CodecConfiguration(name=name, bitrate=bitrate, rate=rate, profile=profile, id_=id_, description=description, custom_data=custom_data, width=width, height=height, bframes=bframes, ref_frames=ref_frames, qp=qp, max_bitrate=max_bitrate, min_bitrate=min_bitrate, bufsize=bufsize, min_gop=min_gop, max_gop=max_gop, level=level, rc_lookahead=rc_lookahead, b_adapt=b_adapt, max_ctu_size=max_ctu_size, tu_intra_depth=tu_intra_depth, tu_inter_depth=tu_inter_depth, motion_search=motion_search, sub_me=sub_me, motion_search_range=motion_search_range, weight_prediction_on_p_slice=weight_prediction_on_p_slice, weight_prediction_on_b_slice=weight_prediction_on_b_slice, sao=sao, crf=crf, pixel_format=pixel_format, color_config=color_config, max_keyframe_interval=max_keyframe_interval, min_keyframe_interval=min_keyframe_interval, scene_cut_threshold=scene_cut_threshold, enable_hlg_signaling=enable_hlg_signaling, video_format=video_format, hdr=hdr, master_display=master_display, max_content_light_level=max_content_light_level, max_picture_average_light_level=max_picture_average_light_level, sample_aspect_ratio_numerator=aspect_ratio_numerator, sample_aspect_ratio_denominator=aspect_ratio_denominator, adaptive_quantization_mode=adaptive_quantization_mode, psy_rate_distortion_optimization=psy_rate_distortion_optimization, psy_rate_distortion_optimization_quantization=psy_rate_distortion_optimization_quantization, cutree=cutree, qp_min=qp_min, qp_max=qp_max) return h265_codec_configuration def serialize(self): serialized = super().serialize() serialized['profile'] = self.profile serialized['level'] = self.level serialized['bAdapt'] = self.bAdapt serialized['maxCTUSize'] = self.maxCTUSize serialized['tuIntraDepth'] = self.tuIntraDepth serialized['tuInterDepth'] = self.tuInterDepth serialized['motionSearch'] = self.motionSearch serialized['crf'] = self.crf serialized['videoFormat'] = self.videoFormat serialized['adaptiveQuantizationMode'] = self.adaptiveQuantizationMode if isinstance(self.colorConfig, ColorConfig): serialized['colorConfig'] = self.colorConfig.serialize() return serialized
unlicense
PoroShadows/Testcraft1.8
src/main/java/com/poroshadows/testcraft/proxy/CommonProxy.java
158
package com.poroshadows.testcraft.proxy; public abstract class CommonProxy implements IProxy{ @Override public void RenderInformation() { } }
unlicense
wespital/wespital-frontend
src/utils.js
645
(function () {'use strict'; wespital.filter('paymentMethodToString', function () { return function (input) { if (input == 'insurance') return 'Страховка'; else if (input == 'cash') return 'Наличные'; else return input; }; }); wespital.filter('dateToString', function () { function padNum(value, padding) { var str = value.toString(); while (str.length < padding) str = '0' + str; return str; } return function(date) { return padNum(date.day, 2) + '.' + padNum(date.month, 2) + '.' + padNum(date.year, 4); }; }); })();
unlicense
Hemofektik/Druckwelle
src/utils/VectorTiles/VectorTiles.cpp
13869
#include <ogr_api.h> #include <ogr_spatialref.h> #pragma warning (push) #pragma warning (disable:4251) #include <gdal_priv.h> #include <ogr_api.h> #include <ogr_geometry.h> #include <ogrsf_frmts.h> #pragma warning (pop) #include <zlib.h> #include <vector> #include <ZFXMath.h> #include "VectorTiles.h" #include "vector_tile.pb.h" using namespace std; using namespace ZFXMath; const int SEG_MOVETO = 1; const int SEG_LINETO = 2; const int SEG_CLOSE = 7; int32_t ZigZagUint32ToInt32(uint32_t zigzag) { return (int32_t)((zigzag & 1) ? -(int64_t)(zigzag >> 1) - 1 : (int64_t)(zigzag >> 1)); } std::string decompress_gzip(const uint8_t* data, uint32_t dataSize) { z_stream zs; // z_stream is zlib's control structure memset(&zs, 0, sizeof(zs)); if (inflateInit2(&zs, MAX_WBITS + 16) != Z_OK) { return ""; } zs.next_in = (Bytef*)data; zs.avail_in = dataSize; int ret; char outbuffer[32768]; std::string outstring; // get the decompressed bytes blockwise using repeated calls to inflate do { zs.next_out = reinterpret_cast<Bytef*>(outbuffer); zs.avail_out = sizeof(outbuffer); ret = inflate(&zs, 0); if (outstring.size() < zs.total_out) { outstring.append(outbuffer, zs.total_out - outstring.size()); } } while (ret == Z_OK); inflateEnd(&zs); if (ret != Z_STREAM_END) { return "";// an error occurred that was not EOF } return outstring; } void AddFielDefn(OGRFeatureDefn* featureDefn, const vector_tile::Tile_Layer& layer, uint32_t keyIndex, uint32_t valueIndex) { const auto& key = layer.keys(keyIndex); const auto& value = layer.values(valueIndex); if (value.has_string_value()) { featureDefn->AddFieldDefn(new OGRFieldDefn(key.c_str(), OFTString)); } else if (value.has_float_value()) { auto field = new OGRFieldDefn(key.c_str(), OFTReal); field->SetSubType(OFSTFloat32); featureDefn->AddFieldDefn(field); } else if (value.has_double_value()) { auto field = new OGRFieldDefn(key.c_str(), OFTReal); featureDefn->AddFieldDefn(field); } else if (value.has_int_value()) { auto field = new OGRFieldDefn(key.c_str(), OFTInteger64); featureDefn->AddFieldDefn(field); } else if (value.has_uint_value()) { auto field = new OGRFieldDefn(key.c_str(), OFTInteger64); featureDefn->AddFieldDefn(field); } else if (value.has_sint_value()) { auto field = new OGRFieldDefn(key.c_str(), OFTInteger64); featureDefn->AddFieldDefn(field); } else if (value.has_bool_value()) { auto field = new OGRFieldDefn(key.c_str(), OFTInteger); field->SetSubType(OFSTBoolean); featureDefn->AddFieldDefn(field); } } void SetFeatureField(OGRFeature* feature, const vector_tile::Tile_Layer& layer, uint32_t keyIndex, uint32_t valueIndex) { const auto& key = layer.keys(keyIndex); const auto& value = layer.values(valueIndex); if (value.has_string_value()) { feature->SetField(key.c_str(), value.string_value().c_str()); } else if (value.has_float_value()) { feature->SetField(key.c_str(), (double)value.float_value()); } else if (value.has_double_value()) { feature->SetField(key.c_str(), (double)value.double_value()); } else if (value.has_int_value()) { feature->SetField(key.c_str(), (GIntBig)value.int_value()); } else if (value.has_uint_value()) { feature->SetField(key.c_str(), (GIntBig)value.uint_value()); } else if (value.has_sint_value()) { feature->SetField(key.c_str(), (GIntBig)value.sint_value()); } else if (value.has_bool_value()) { feature->SetField(key.c_str(), (int)(value.bool_value() ? 1 : 0)); } } template<typename OGRGeometryType, bool CloseRing> OGRGeometryType* CreateOGRGeometry( double tileScale, double left, double top, const TPolygon2D<int32_t>& polygon) { OGRGeometryType* geo = new OGRGeometryType(); const uint32_t numVertices = polygon.GetNumVertices(); if (CloseRing && numVertices < 3) return NULL; if (!CloseRing && numVertices < 2) return NULL; geo->setNumPoints(numVertices); for (uint32_t v = 0; v < numVertices; v++) { const auto& vertex = polygon.GetVertex(v); double x = left + vertex.x * tileScale; double y = top - vertex.y * tileScale; geo->setPoint(v, x, y); } if (CloseRing) { geo->closeRings(); } return geo; } OGRPolygon* CreateOGRPolygon(double tileScale, double left, double top, const TPolygon2D<int32_t>& exterior, const TPolygon2D<int32_t>* interior, const uint32_t numInteriors) { OGRPolygon* ogrPoly = new OGRPolygon(); auto geo = CreateOGRGeometry<OGRLinearRing, true>(tileScale, left, top, exterior); if (!geo) return NULL; ogrPoly->addRingDirectly(geo); if (!interior || numInteriors <= 0) return ogrPoly; for (uint32_t i = 0; i < numInteriors; i++) { auto innerGeo = CreateOGRGeometry<OGRLinearRing, true>(tileScale, left, top, interior[i]); if (innerGeo) { ogrPoly->addRingDirectly(innerGeo); } } return ogrPoly; } bool ConvertVectorTileToOGRDataset( vector_tile::Tile& tile, GDALDataset* dataset, OGRSpatialReference* webmercator, int zoomLevel, int x, int y) { // transform integer vector tile coordinates into web mercator int numTiles = 1 << zoomLevel; double tileSize = VectorTiles::MapWidth / (double)numTiles; double left = VectorTiles::MapLeft + x * tileSize; double top = VectorTiles::MapTop - (numTiles - y - 1) * tileSize; for (int l = 0; l < tile.layers_size(); l++) { vector_tile::Tile_Layer const& srcLayer = tile.layers(l); const double tileScale = tileSize / srcLayer.extent(); auto dstLayer = dataset->GetLayerByName(srcLayer.name().c_str()); if (!dstLayer) { dstLayer = dataset->CreateLayer(srcLayer.name().c_str(), webmercator->Clone()); } //dstLayer->SetMetadataItem("version", to_string(srcLayer.version()).c_str()); vector<TPolygon2D<double>> lineStrings; for (int featureIndex = 0; featureIndex < srcLayer.features_size(); featureIndex++) { int32_t cursorX = 0; int32_t cursorY = 0; const vector_tile::Tile_Feature& srcFeature = srcLayer.features(featureIndex); vector<TPolygon2D<int32_t>> vtPolys; TPolygon2D<int32_t> vtPoly; // read geometry { int cmd = -1; const int cmd_bits = 3; unsigned int length = 0; for (int k = 0; k < srcFeature.geometry_size();) { if (!length) { unsigned cmd_length = srcFeature.geometry(k++); cmd = cmd_length & ((1 << cmd_bits) - 1); length = cmd_length >> cmd_bits; } if (length > 0) { length--; if (cmd == SEG_MOVETO || cmd == SEG_LINETO) { uint32_t xZigZag = srcFeature.geometry(k++); uint32_t yZigZag = srcFeature.geometry(k++); int32_t xRel = ZigZagUint32ToInt32(xZigZag); int32_t yRel = ZigZagUint32ToInt32(yZigZag); cursorX += xRel; cursorY += yRel; if (cmd == SEG_MOVETO) { if (vtPoly.GetNumVertices() > 0) { vtPolys.push_back(move(vtPoly)); vtPoly = TPolygon2D<int32_t>(); vtPoly.ReserveNumVertices(10); } } else if (cmd == SEG_LINETO) { } vtPoly.AddVertex(TVector2D<int32_t>(cursorX, cursorY)); } else if (cmd == (SEG_CLOSE & ((1 << cmd_bits) - 1))) { vtPolys.push_back(move(vtPoly)); vtPoly = TPolygon2D<int32_t>(); vtPoly.ReserveNumVertices(10); } else { return false; // unknown command } } } } OGRFeature* dstFeature = NULL; // read tags { auto featureDefn = new OGRFeatureDefn(); for (int t = 0; t < srcFeature.tags_size(); t += 2) { uint32_t keyIndex = srcFeature.tags(t + 0); uint32_t valueIndex = srcFeature.tags(t + 1); AddFielDefn(featureDefn, srcLayer, keyIndex, valueIndex); } dstFeature = new OGRFeature(featureDefn); GIntBig id = srcFeature.id(); dstFeature->SetFID(Abs(id)); for (int t = 0; t < srcFeature.tags_size(); t += 2) { uint32_t keyIndex = srcFeature.tags(t + 0); uint32_t valueIndex = srcFeature.tags(t + 1); SetFeatureField(dstFeature, srcLayer, keyIndex, valueIndex); } } OGRGeometry* geo = NULL; // convert read geometry to OGRGeometry switch (srcFeature.type()) { case vector_tile::Tile_GeomType_POLYGON: { vector<OGRPolygon*> polygons; size_t polyStartIndex = 0; for (size_t p = 0; p < vtPolys.size(); p++) { double polyArea = vtPolys[p].ComputeArea<double>(); if (p > polyStartIndex && polyArea < 0.0) // test for multipolygons including interior polys { auto& poly = vtPolys[polyStartIndex]; const auto* nextPoly = &vtPolys[polyStartIndex + 1]; auto ogrPolygon = CreateOGRPolygon(tileScale, left, top, poly, (polyStartIndex + 1 < vtPolys.size()) ? nextPoly : NULL, (uint32_t)(p - polyStartIndex - 1)); if (ogrPolygon) { polygons.push_back(ogrPolygon); } polyStartIndex = p; } } if (polyStartIndex < vtPolys.size()) { auto ogrPolygon = CreateOGRPolygon(tileScale, left, top, vtPolys[polyStartIndex], (polyStartIndex + 1 < vtPolys.size()) ? &vtPolys[polyStartIndex + 1] : NULL, (uint32_t)(vtPolys.size() - 1 - polyStartIndex)); if (ogrPolygon) { polygons.push_back(ogrPolygon); } } if (polygons.size() > 1) { auto multiPoly = new OGRMultiPolygon(); for (auto poly : polygons) { multiPoly->addGeometryDirectly(poly); } geo = multiPoly; } else if (polygons.size() == 1) { geo = polygons[0]; } break; } case vector_tile::Tile_GeomType_LINESTRING: { vtPolys.push_back(move(vtPoly)); for (const auto& vtp : vtPolys) { lineStrings.push_back(move(vtp.Clone<double>(tileScale))); } if (vtPolys.size() > 1) { auto multiLine = new OGRMultiLineString(); for (const auto& vtPoly : vtPolys) { multiLine->addGeometryDirectly(CreateOGRGeometry<OGRLineString, false>(tileScale, left, top, vtPoly)); } geo = multiLine; } else if (vtPolys.size() == 1) { geo = CreateOGRGeometry<OGRLineString, false>(tileScale, left, top, vtPolys[0]); } break; } case vector_tile::Tile_GeomType_POINT: { if (vtPoly.GetNumVertices() > 1) { auto multiPoint = new OGRMultiPoint(); for (uint32_t v = 0; v < vtPoly.GetNumVertices(); v++) { const auto& vertex = vtPoly.GetVertex(v); double x = left + vertex.x * tileScale; double y = top - vertex.y * tileScale; multiPoint->addGeometry(new OGRPoint(x, y)); } geo = multiPoint; } else if (vtPoly.GetNumVertices() == 1) { const auto& vertex = vtPoly.GetVertex(0); double x = left + vertex.x * tileScale; double y = top - vertex.y * tileScale; geo = new OGRPoint(x, y); } break; } default: return false; } dstFeature->SetGeometryDirectly(geo); if (dstLayer->CreateFeature(dstFeature) != OGRERR_NONE) { return false; } } } return true; } const double VectorTiles::MapLeft = -20037508.34; const double VectorTiles::MapRight = 20037508.34; const double VectorTiles::MapTop = 20037508.34; const double VectorTiles::MapBottom = -20037508.34; const double VectorTiles::MapWidth = VectorTiles::MapRight - VectorTiles::MapLeft; const double VectorTiles::MapHeight = VectorTiles::MapTop - VectorTiles::MapBottom; VectorTiles::VectorTiles(const char* path2mbtiles) : mbtiles(NULL) , webMercator((OGRSpatialReference*)OSRNewSpatialReference(NULL)) , emptyTile(NULL) { GOOGLE_PROTOBUF_VERIFY_VERSION; RegisterOGRMEM(); RegisterOGRSQLite(); auto sqliteDriver = OGRGetDriverByName("SQLite"); mbtiles = (GDALDataset*)OGROpen(path2mbtiles, GA_ReadOnly, &sqliteDriver); auto memDriver = (GDALDriver*)OGRGetDriverByName("Memory"); emptyTile = memDriver->Create("VectorTile", 0, 0, 0, GDT_Unknown, NULL); emptyTile->MarkAsShared(); webMercator->importFromEPSG(3857); } VectorTiles::~VectorTiles() { if (mbtiles) { mbtiles->Release(); } emptyTile->Release(); OGRSpatialReference::DestroySpatialReference(webMercator); //google::protobuf::ShutdownProtobufLibrary(); } struct IntermediateQueryData { GDALDataset* dataset; OGRLayer* layer; OGRFeature* feature; IntermediateQueryData(GDALDataset* dataset) : dataset(dataset) , layer(NULL) , feature(NULL) { } ~IntermediateQueryData() { if (feature) OGRFeature::DestroyFeature(feature); if (layer) dataset->ReleaseResultSet(layer); } }; GDALDataset* VectorTiles::Open(int zoomLevel, int x, int y) { if (!mbtiles) return NULL; string pbf; { IntermediateQueryData qd(mbtiles); string query = "SELECT tile_data FROM tiles WHERE zoom_level=" + to_string(zoomLevel) + " AND tile_column=" + to_string(x) + " AND tile_row=" + to_string(y); qd.layer = mbtiles->ExecuteSQL(query.c_str(), NULL, "SQLITE"); if (!qd.layer || qd.layer->GetFeatureCount() == 0) { return NULL; } qd.feature = qd.layer->GetNextFeature(); int zippedPBFSize = 0; GByte* zippedPBF = qd.feature->GetFieldAsBinary(0, &zippedPBFSize); if (!zippedPBF || !zippedPBFSize) { emptyTile->Reference(); return emptyTile; } pbf = decompress_gzip(zippedPBF, zippedPBFSize); if (pbf.size() == 0) { return NULL; } } vector_tile::Tile tile; if (!tile.ParseFromArray(pbf.data(), (int)pbf.size())) { return NULL; } auto driver = (GDALDriver*)OGRGetDriverByName("Memory"); auto dataset = driver->Create("VectorTile", 0, 0, 0, GDT_Unknown, NULL); if (!ConvertVectorTileToOGRDataset(tile, dataset, webMercator, zoomLevel, x, y)) { dataset->Release(); return NULL; } return dataset; } bool VectorTiles::IsOk() const { return mbtiles != NULL; }
unlicense
lizij/Leetcode
src/Freedom_Trail/Solution.java
2812
package Freedom_Trail; import java.util.HashMap; import java.util.Map; public class Solution { public int findRotateSteps(String ring, String key) { /** * use String.indexOf and lastIndexOf to implement clockwise and anticlockwise rotation. * Use String as the key type of map will reduce the efficiency of get(). But code is less. * 79ms */ // Map<String, Map<Integer, Integer>> map = new HashMap<>(); // int steps = dfs(ring, key, 0); /** * use Dial to implement clockwise and anticlockwise rotation * 42ms */ int[][] mem = new int[ring.length()][key.length()]; int steps = dfs(new Dial(ring), key, 0, mem); return steps + key.length(); } private int dfs(String ring, String key, int pos, Map<String, Map<Integer, Integer>> map){ if (pos == key.length()) return 0; if (map.containsKey(ring) && map.get(ring).containsKey(pos)) return map.get(ring).get(pos); char c = key.charAt(pos); int left = ring.indexOf(c); int right = ring.lastIndexOf(c); int afterLeft = left + dfs(ring.substring(left) + ring.substring(0, left), key, pos + 1, map); int afterRight = ring.length() - right + dfs(ring.substring(right) + ring.substring(0, right), key, pos + 1, map); int res = Math.min(afterLeft, afterRight); Map<Integer, Integer> ans = map.getOrDefault(ring, new HashMap<>()); ans.put(pos, res); map.put(ring, ans); return res; } private int dfs(Dial dial, String key, int pos, int[][] mem){ if (pos == key.length()) return 0; int precur = dial.getCur(); if (mem[precur][pos] != 0) return mem[precur][pos]; char c = key.charAt(pos); int left = dial.rotate(c, false) + dfs(dial, key, pos + 1, mem); dial.setCur(precur); int right = dial.rotate(c, true) + dfs(dial, key, pos + 1, mem); dial.setCur(precur); mem[precur][pos] = Math.min(left, right); return mem[precur][pos]; } class Dial{ char[] ring; int cur; Dial(String ring){ this.ring = ring.toCharArray(); cur = 0; } int rotate(char c, boolean right){ int count = 0; while (ring[cur] != c){ cur = (right ? cur + 1: cur - 1 + ring.length) % ring.length; count++; } return count; } int getCur() { return cur; } void setCur(int cur) { this.cur = cur; } } public static void main(String[] args) { Solution s = new Solution(); // System.out.println(s.findRotateSteps("godding", "gd"));//4 System.out.println(s.findRotateSteps("iotfo", "fioot")); } }
unlicense
SWHS-PC/Users
AidanStuff/Fizzbuzz/Aidan - Fizzbuzz/FizzBuzz.cs
4842
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aidan___Fizzbuzz { class FizzBuzz { [Flags] enum FizzFlags { None = 0, // Define Fizz, Buzz, and Boom flags as different powers of 2. // Because they are different powers of 2 they correspond to // different bits (i.e., binary digits), so each flag can be set // without affecting the other flags. Fizz = 0x01, Buzz = 0x02, Boom = 0x04, // Defined named values for combinations of two or more flags. FizzBuzz = Fizz | Buzz, FizzBoom = Fizz | Boom, BuzzBoom = Buzz | Boom, FizzBuzzBoom = Fizz | Buzz | Boom } //method using flags public static void RunWithFlags() { for (int i = 1; i <= 105; i++) { FizzFlags flags = 0; // Use the bitwise OR operator to set the individual bits of the flags // variable based on the value of i. if (i % 3 == 0) { flags |= FizzFlags.Fizz; } if (i % 5 == 0) { flags |= FizzFlags.Buzz; } if (i % 7 == 0) { flags |= FizzFlags.Boom; } // At this point the value of flags is the combination of the bits we // set. For example, if i is divisible by both 3 and 5 then we've set both // the Fizz and Buzz bits, so flags is the combination (bitwise OR) of // those, namely FizzBuzz. switch (flags) { case FizzFlags.None: //I would write none here except i want it to print the number if its not divisible by those numbers Console.WriteLine(i); break; case FizzFlags.Fizz: Console.WriteLine("Fizz"); break; case FizzFlags.Buzz: Console.WriteLine("Buzz"); break; case FizzFlags.Boom: Console.WriteLine("Boom"); break; case FizzFlags.FizzBuzz: Console.WriteLine("FizzBuzz"); break; case FizzFlags.FizzBoom: Console.WriteLine("FizzBoom"); break; case FizzFlags.FizzBuzzBoom: Console.WriteLine("FizzBuzzBoom"); break; } } //allowing user to close program upon pressing enter Console.WriteLine("\r\nPress Enter to Close"); //(char)13 is the enter key if (Console.ReadKey().KeyChar == (char)13) { return; } } //main method public static void Run() { //uses a for loop to loop i from 1 to 105 for (int i = 1; i <= 105; i++) { //boolean variables for i % 3, 5, and 7, % meaning remainder of i divided by 3 equalling 0 bool fizz = i % 3 == 0; bool buzz = i % 5 == 0; bool boom = i % 7 == 0; //if statements where it writes Fizz, Buzz and Boom for the divisions of the i var //105 is the only instance of FizzBuzzBoom if (fizz && buzz && boom) Console.WriteLine("FizzBuzzBoom"); else if (fizz && boom) Console.WriteLine("Fizz...Boom"); else if (fizz && buzz) Console.WriteLine("FizzBuzz"); else if (fizz) Console.WriteLine("Fizz"); else if (buzz) Console.WriteLine("Buzz"); else if (boom) Console.WriteLine("Boom"); //for where i equals more than one of the boolean variables //writes the i variable if the remainder isnt equal to the booleans else Console.WriteLine(i); } //allowing user to close program upon pressing enter Console.WriteLine("\r\nPress Enter to Close"); //(char)13 is the enter key if (Console.ReadKey().KeyChar == (char)13) { return; } } } }
unlicense
ruby-rdf/rdf-trig
lib/rdf/trig/writer.rb
7327
require 'rdf/turtle' require 'rdf/trig/streaming_writer' module RDF::TriG ## # A TriG serialiser # # Note that the natural interface is to write a whole repository at a time. # Writing statements or Triples will create a repository to add them to # and then serialize the repository. # # @example Obtaining a TriG writer class # RDF::Writer.for(:trig) #=> RDF::TriG::Writer # RDF::Writer.for("etc/test.trig") # RDF::Writer.for(:file_name => "etc/test.trig") # RDF::Writer.for(file_extension: "trig") # RDF::Writer.for(:content_type => "application/trig") # # @example Serializing RDF repo into an TriG file # RDF::TriG::Writer.open("etc/test.trig") do |writer| # writer << repo # end # # @example Serializing RDF statements into an TriG file # RDF::TriG::Writer.open("etc/test.trig") do |writer| # repo.each_statement do |statement| # writer << statement # end # end # # @example Serializing RDF statements into an TriG string # RDF::TriG::Writer.buffer do |writer| # repo.each_statement do |statement| # writer << statement # end # end # # @example Serializing RDF statements to a string in streaming mode # RDF::TriG::Writer.buffer(stream: true) do |writer| # repo.each_statement do |statement| # writer << statement # end # end # # The writer will add prefix definitions, and use them for creating @prefix definitions, and minting QNames # # @example Creating @base and @prefix definitions in output # RDF::TriG::Writer.buffer(base_uri: "http://example.com/", prefixes: { # nil => "http://example.com/ns#", # foaf: "http://xmlns.com/foaf/0.1/"} # ) do |writer| # repo.each_statement do |statement| # writer << statement # end # end # # @author [Gregg Kellogg](https://greggkellogg.net/) class Writer < RDF::Turtle::Writer include StreamingWriter format RDF::TriG::Format ## # Initializes the TriG writer instance. # # @param [IO, File] output # the output stream # @param [Hash{Symbol => Object}] options # any additional options # @option options [Encoding] :encoding (Encoding::UTF_8) # the encoding to use on the output stream (Ruby 1.9+) # @option options [Boolean] :canonicalize (false) # whether to canonicalize literals when serializing # @option options [Hash] :prefixes (Hash.new) # the prefix mappings to use (not supported by all writers) # @option options [#to_s] :base_uri (nil) # the base URI to use when constructing relative URIs # @option options [Integer] :max_depth (3) # Maximum depth for recursively defining resources, defaults to 3 # @option options [Boolean] :standard_prefixes (false) # Add standard prefixes to @prefixes, if necessary. # @option options [Boolean] :stream (false) # Do not attempt to optimize graph presentation, suitable for streaming large repositories. # @option options [String] :default_namespace (nil) # URI to use as default namespace, same as `prefixes\[nil\]` # @yield [writer] `self` # @yieldparam [RDF::Writer] writer # @yieldreturn [void] # @yield [writer] # @yieldparam [RDF::Writer] writer def initialize(output = $stdout, **options, &block) super do # Set both @repo and @graph to a new repository. @repo = @graph = RDF::Repository.new if block_given? case block.arity when 0 then instance_eval(&block) else block.call(self) end end end end ## # Adds a triple to be serialized # @param [RDF::Resource] subject # @param [RDF::URI] predicate # @param [RDF::Value] object # @param [RDF::Resource] graph_name # @return [void] def write_quad(subject, predicate, object, graph_name) statement = RDF::Statement.new(subject, predicate, object, graph_name: graph_name) if @options[:stream] stream_statement(statement) else @graph.insert(statement) end end ## # Write out declarations # @return [void] `self` def write_prologue case when @options[:stream] stream_prologue else super end end ## # Outputs the TriG representation of all stored triples. # # @return [void] # @see #write_triple def write_epilogue case when @options[:stream] stream_epilogue else @max_depth = @options[:max_depth] || 3 @base_uri = RDF::URI(@options[:base_uri]) reset log_debug {"serialize: repo: #{@repo.size}"} preprocess start_document @graph_names = order_graphs @graph_names.each do |graph_name| log_depth do log_debug {"graph_name: #{graph_name.inspect}"} reset @options[:log_depth] = graph_name ? 1 : 0 if graph_name @output.write("\n#{format_term(graph_name)} {") end # Restrict view to the particular graph @graph = @repo.project_graph(graph_name) # Pre-process statements again, but in the specified graph @graph.each {|st| preprocess_statement(st)} # Remove lists that are referenced and have non-list properties, # or are present in more than one graph, or have elements # that are present in more than one graph; # these are legal, but can't be serialized as lists @lists.reject! do |node, list| ref_count(node) > 0 && prop_count(node) > 0 || list.subjects.any? {|elt| !resource_in_single_graph?(elt)} end order_subjects.each do |subject| unless is_done?(subject) statement(subject) end end @output.puts("}") if graph_name end end end raise RDF::WriterError, "Errors found during processing" if log_statistics[:error] end protected # Add additional constraint that the resource must be in a single graph # and must not be a graph name def blankNodePropertyList?(resource, position) super && resource_in_single_graph?(resource) && !@graph_names.include?(resource) end def resource_in_single_graph?(resource) graph_names = @repo.query({subject: resource}).map(&:graph_name) graph_names += @repo.query({object: resource}).map(&:graph_name) graph_names.uniq.length <= 1 end # Order graphs for output def order_graphs log_debug("order_graphs") {@repo.graph_names.to_a.inspect} graph_names = @repo.graph_names.to_a.sort # include default graph, if necessary graph_names.unshift(nil) unless @repo.query({graph_name: false}).to_a.empty? graph_names end # Perform any statement preprocessing required. This is used to perform reference counts and determine required # prefixes. # @param [Statement] statement def preprocess_statement(statement) super get_pname(statement.graph_name) if statement.has_graph? end end end
unlicense
clilystudio/NetBook
allsrc/android/support/v4/app/RemoteInputCompatBase$RemoteInput$Factory.java
610
package android.support.v4.app; import android.os.Bundle; public abstract interface RemoteInputCompatBase$RemoteInput$Factory { public abstract RemoteInputCompatBase.RemoteInput build(String paramString, CharSequence paramCharSequence, CharSequence[] paramArrayOfCharSequence, boolean paramBoolean, Bundle paramBundle); public abstract RemoteInputCompatBase.RemoteInput[] newArray(int paramInt); } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: android.support.v4.app.RemoteInputCompatBase.RemoteInput.Factory * JD-Core Version: 0.6.0 */
unlicense
cc14514/hq6
hq-server/src/main/java/org/hyperic/hq/bizapp/server/session/EventsBossImpl.java
55486
/* * NOTE: This copyright does *not* cover user programs that use Hyperic * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004-2010], VMware, Inc. * This file is part of Hyperic. * * Hyperic is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.hq.bizapp.server.session; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import javax.security.auth.login.LoginException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperic.hibernate.PageInfo; import org.hyperic.hq.appdef.shared.AppdefEntityConstants; import org.hyperic.hq.appdef.shared.AppdefEntityID; import org.hyperic.hq.appdef.shared.AppdefEntityNotFoundException; import org.hyperic.hq.appdef.shared.AppdefEntityTypeID; import org.hyperic.hq.appdef.shared.AppdefEntityValue; import org.hyperic.hq.appdef.shared.AppdefGroupValue; import org.hyperic.hq.appdef.shared.AppdefUtil; import org.hyperic.hq.appdef.shared.InvalidAppdefTypeException; import org.hyperic.hq.appdef.shared.PlatformManager; import org.hyperic.hq.appdef.shared.ServerManager; import org.hyperic.hq.appdef.shared.ServiceManager; import org.hyperic.hq.auth.shared.SessionException; import org.hyperic.hq.auth.shared.SessionManager; import org.hyperic.hq.auth.shared.SessionNotFoundException; import org.hyperic.hq.auth.shared.SessionTimeoutException; import org.hyperic.hq.authz.server.session.AuthzSubject; import org.hyperic.hq.authz.server.session.Resource; import org.hyperic.hq.authz.server.session.ResourceGroup; import org.hyperic.hq.authz.shared.AuthzSubjectManager; import org.hyperic.hq.authz.shared.PermissionException; import org.hyperic.hq.authz.shared.PermissionManager; import org.hyperic.hq.authz.shared.ResourceGroupManager; import org.hyperic.hq.authz.shared.ResourceManager; import org.hyperic.hq.bizapp.shared.AppdefBoss; import org.hyperic.hq.bizapp.shared.AuthBoss; import org.hyperic.hq.bizapp.shared.EventsBoss; import org.hyperic.hq.common.ApplicationException; import org.hyperic.hq.common.DuplicateObjectException; import org.hyperic.hq.common.SystemException; import org.hyperic.hq.escalation.server.session.Escalatable; import org.hyperic.hq.escalation.server.session.Escalation; import org.hyperic.hq.escalation.server.session.EscalationAlertType; import org.hyperic.hq.escalation.server.session.EscalationState; import org.hyperic.hq.escalation.server.session.PerformsEscalations; import org.hyperic.hq.escalation.shared.EscalationManager; import org.hyperic.hq.events.ActionConfigInterface; import org.hyperic.hq.events.ActionCreateException; import org.hyperic.hq.events.ActionExecuteException; import org.hyperic.hq.events.ActionInterface; import org.hyperic.hq.events.AlertConditionCreateException; import org.hyperic.hq.events.AlertDefinitionCreateException; import org.hyperic.hq.events.AlertDefinitionInterface; import org.hyperic.hq.events.AlertInterface; import org.hyperic.hq.events.AlertNotFoundException; import org.hyperic.hq.events.AlertSeverity; import org.hyperic.hq.events.EventConstants; import org.hyperic.hq.events.MaintenanceEvent; import org.hyperic.hq.events.TriggerCreateException; import org.hyperic.hq.events.ext.RegisterableTriggerInterface; import org.hyperic.hq.events.server.session.Action; import org.hyperic.hq.events.server.session.Alert; import org.hyperic.hq.events.server.session.AlertDefinition; import org.hyperic.hq.events.server.session.AlertSortField; import org.hyperic.hq.events.server.session.ClassicEscalationAlertType; import org.hyperic.hq.events.server.session.TriggersCreatedZevent; import org.hyperic.hq.events.shared.ActionManager; import org.hyperic.hq.events.shared.ActionValue; import org.hyperic.hq.events.shared.AlertDefinitionManager; import org.hyperic.hq.events.shared.AlertDefinitionValue; import org.hyperic.hq.events.shared.AlertManager; import org.hyperic.hq.events.shared.MaintenanceEventManager; import org.hyperic.hq.events.shared.RegisteredTriggerManager; import org.hyperic.hq.events.shared.RegisteredTriggerValue; import org.hyperic.hq.galerts.server.session.GalertDef; import org.hyperic.hq.galerts.server.session.GalertEscalationAlertType; import org.hyperic.hq.galerts.server.session.GalertLogSortField; import org.hyperic.hq.galerts.shared.GalertManager; import org.hyperic.hq.measurement.MeasurementNotFoundException; import org.hyperic.util.ConfigPropertyException; import org.hyperic.util.config.ConfigResponse; import org.hyperic.util.config.ConfigSchema; import org.hyperic.util.config.EncodingException; import org.hyperic.util.config.InvalidOptionException; import org.hyperic.util.config.InvalidOptionValueException; import org.hyperic.util.pager.PageControl; import org.hyperic.util.pager.PageList; import org.hyperic.util.timer.StopWatch; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * The BizApp's interface to the Events Subsystem */ @Service @Transactional public class EventsBossImpl implements EventsBoss { private Log log = LogFactory.getLog(EventsBossImpl.class); private static final String BUNDLE = "org.hyperic.hq.bizapp.Resources"; private SessionManager sessionManager; private ActionManager actionManager; private AlertDefinitionManager alertDefinitionManager; private AlertManager alertManager; private AppdefBoss appdefBoss; private AuthBoss authBoss; private EscalationManager escalationManager; private PlatformManager platformManager; private RegisteredTriggerManager registeredTriggerManager; private ResourceManager resourceManager; private ServerManager serverManager; private ServiceManager serviceManager; private PermissionManager permissionManager; private GalertManager galertManager; private ResourceGroupManager resourceGroupManager; private AuthzSubjectManager authzSubjectManager; @Autowired public EventsBossImpl(SessionManager sessionManager, ActionManager actionManager, AlertDefinitionManager alertDefinitionManager, AlertManager alertManager, AppdefBoss appdefBoss, AuthBoss authBoss, EscalationManager escalationManager, PlatformManager platformManager, RegisteredTriggerManager registeredTriggerManager, ResourceManager resourceManager, ServerManager serverManager, ServiceManager serviceManager, PermissionManager permissionManager, GalertManager galertManager, ResourceGroupManager resourceGroupManager, AuthzSubjectManager authzSubjectManager) { this.sessionManager = sessionManager; this.actionManager = actionManager; this.alertDefinitionManager = alertDefinitionManager; this.alertManager = alertManager; this.appdefBoss = appdefBoss; this.authBoss = authBoss; this.escalationManager = escalationManager; this.platformManager = platformManager; this.registeredTriggerManager = registeredTriggerManager; this.resourceManager = resourceManager; this.serverManager = serverManager; this.serviceManager = serviceManager; this.permissionManager = permissionManager; this.galertManager = galertManager; this.resourceGroupManager = resourceGroupManager; this.authzSubjectManager = authzSubjectManager; } /** * TODO possibly find another way to return the correct impl of interface if * in HQ or HQ EE. Previously, this had to be lazy b/c using SPEL * permissionManager.maintenanceEventManager causes the * Bootstrap.getBean(MaintenanceEventManager) to be invoked during creation * of ejb-context.xml (which doesn't work b/c Boostrap.context is still set * to dao-context.xml) * @return */ private MaintenanceEventManager getMaintenanceEventManager() { return permissionManager.getMaintenanceEventManager(); } /** * Get the number of alerts for the given array of AppdefEntityID's * */ @Transactional(readOnly = true) public int[] getAlertCount(int sessionID, AppdefEntityID[] ids) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); int[] counts = alertManager.getAlertCount(ids); counts = galertManager.fillAlertCount(subject, ids, counts); return counts; } /** * Get the number of alerts for the given array of AppdefEntityID's, mapping AppdefEntityID to it's alerts count * */ @Transactional(readOnly = true) public Map<AppdefEntityID, Integer> getAlertCountMapped(int sessionID, AppdefEntityID[] ids) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); Map<AppdefEntityID, Integer> counts = alertManager.getAlertCountMapped(ids); galertManager.fillAlertCount(subject, ids, counts); return counts; } /** * Create an alert definition */ public AlertDefinitionValue createAlertDefinition(int sessionID, AlertDefinitionValue adval) throws AlertDefinitionCreateException, PermissionException, InvalidOptionException, InvalidOptionValueException, SessionException { AuthzSubject subject = sessionManager.getSubject(sessionID); // Verify that there are some conditions to evaluate if (adval.getConditions().length == 0) { throw new AlertDefinitionCreateException("Conditions cannot be " + "null or empty"); } // Create list of ID's to create the alert definition List<AppdefEntityID> appdefIds = new ArrayList<AppdefEntityID>(); final AppdefEntityID aeid = getAppdefEntityID(adval); appdefIds.add(aeid); if (aeid.isGroup()) { // Look up the group AppdefGroupValue group; try { group = appdefBoss.findGroup(sessionID, adval.getAppdefId()); } catch (InvalidAppdefTypeException e) { throw new AlertDefinitionCreateException(e); } appdefIds.addAll(group.getAppdefGroupEntries()); } ArrayList<RegisteredTriggerValue> triggers = new ArrayList<RegisteredTriggerValue>(); AlertDefinitionValue parent = null; // Iterate through to create the appropriate triggers and alertdef for (AppdefEntityID id : appdefIds) { // Reset the value object with this entity ID adval.setAppdefType(id.getType()); adval.setAppdefId(id.getId()); // Scrub the triggers just in case adval.removeAllTriggers(); if (!id.isGroup()) { // If this is for the members of a group, we need to // scrub and copy the parent's conditions // 这是很奇怪的逻辑,因为 parent = null 之后再也没有被实例化过,此处判断相当与 if(false) if (parent != null) { adval.setParentId(parent.getId()); try { alertDefinitionManager.cloneParentConditions(subject, id, adval, parent .getConditions(), false, true); } catch (MeasurementNotFoundException e) { throw new AlertConditionCreateException(e); } } // Create the triggers registeredTriggerManager.createTriggers(subject, adval); triggers.addAll(Arrays.asList(adval.getTriggers())); } // Now create the alert definition AlertDefinitionValue created = alertDefinitionManager.createAlertDefinition(subject, adval); if (parent == null) { parent = created; } } return parent; } /** * Create an alert definition for a resource type * * */ public AlertDefinitionValue createResourceTypeAlertDefinition(int sessionID, AppdefEntityTypeID aetid, AlertDefinitionValue adval) throws AlertDefinitionCreateException, PermissionException, InvalidOptionException, InvalidOptionValueException, SessionNotFoundException, SessionTimeoutException { final boolean debug = log.isDebugEnabled(); StopWatch watch = new StopWatch(); AuthzSubject subject = sessionManager.getSubject(sessionID); // Verify that there are some conditions to evaluate if (adval.getConditions().length == 0) { throw new AlertDefinitionCreateException("Conditions cannot be null or empty"); } AlertDefinitionValue parent; // Create the parent alert definition adval.setAppdefType(aetid.getType()); adval.setAppdefId(aetid.getId()); adval.setParentId(EventConstants.TYPE_ALERT_DEF_ID); // Now create the alert definition if (debug) watch.markTimeBegin("createParentAlertDefinition"); parent = alertDefinitionManager.createAlertDefinition(subject, adval); if (debug) watch.markTimeEnd("createParentAlertDefinition"); adval.setParentId(parent.getId()); if (debug) watch.markTimeBegin("lookupResources"); // Lookup resources Integer[] entIds; switch (aetid.getType()) { case AppdefEntityConstants.APPDEF_TYPE_PLATFORM: entIds = platformManager.getPlatformIds(subject, aetid.getId()); break; case AppdefEntityConstants.APPDEF_TYPE_SERVER: entIds = serverManager.getServerIds(subject, aetid.getId()); break; case AppdefEntityConstants.APPDEF_TYPE_SERVICE: entIds = serviceManager.getServiceIds(subject, aetid.getId()); break; default: throw new InvalidOptionException("Alerts cannot be defined on appdef entity type " + aetid.getType()); } if (debug) watch.markTimeEnd("lookupResources"); List zevents = new ArrayList(entIds.length); if (debug) watch.markTimeBegin("createChildAlertDefinitions[" + entIds.length + "]"); // Iterate through to create the appropriate triggers and alertdef for (int ei = 0; ei < entIds.length; ei++) { StopWatch childWatch = new StopWatch(); AppdefEntityID id = new AppdefEntityID(aetid.getType(), entIds[ei]); // Reset the value object with this entity ID adval.setAppdefId(id.getId()); // Scrub the triggers just in case adval.removeAllTriggers(); try { boolean succeeded = alertDefinitionManager.cloneParentConditions(subject, id, adval, parent.getConditions(), true, true); if (!succeeded) { continue; } } catch (MeasurementNotFoundException e) { throw new AlertDefinitionCreateException( "Expected parent condition cloning to fail silently", e); } // Create the triggers if (debug) childWatch.markTimeBegin("createTriggers"); // HHQ-3423: Do not add the TriggersCreatedListener here. // Add it at the end after all the triggers are created. registeredTriggerManager.createTriggers(subject, adval, false); if (debug) childWatch.markTimeEnd("createTriggers"); // Make sure the actions have the proper parentId alertDefinitionManager.cloneParentActions(id, adval, parent.getActions()); // Now create the alert definition if (debug) childWatch.markTimeBegin("createAlertDefinition"); AlertDefinitionValue newAdval = alertDefinitionManager.createAlertDefinition(subject, adval); if (debug) { childWatch.markTimeEnd("createAlertDefinition"); log.debug("createChildAlertDefinition[" + id + "]: time=" + childWatch); } zevents.add(new TriggersCreatedZevent(newAdval.getId())); } if (debug) watch.markTimeEnd("createChildAlertDefinitions[" + entIds.length + "]"); // HHQ-3423: Add the TransactionListener after all the triggers are created if (!zevents.isEmpty()) { if (debug) watch.markTimeBegin("addTriggersCreatedTxListener"); registeredTriggerManager.addTriggersCreatedTxListener(zevents); if (debug) watch.markTimeEnd("addTriggersCreatedTxListener"); } if (debug) { log.debug("createResourceTypeAlertDefinition: time=" + watch); } return parent; } /** * */ public Action createAction(int sessionID, Integer adid, String className, ConfigResponse config) throws SessionNotFoundException, SessionTimeoutException, ActionCreateException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); ArrayList<AlertDefinition> alertdefs = new ArrayList<AlertDefinition>(); // check that the user can actually manage alerts for this resource AlertDefinition ad = alertDefinitionManager.getByIdAndCheck(subject, adid); alertdefs.add(ad); // If there are any children alertdefs.addAll(ad.getChildren()); Action root = null; for (AlertDefinition alertDef : alertdefs) { try { if (root == null) { root = actionManager.createAction(alertDef, className, config, null); } else { actionManager.createAction(alertDef, className, config, root); } } catch (EncodingException e) { throw new SystemException("Couldn't encode.", e); } } return root; } /** * Activate/deactivate a collection of alert definitions * * */ public void activateAlertDefinitions(int sessionID, Integer[] ids, boolean activate) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); alertDefinitionManager.updateAlertDefinitionsActiveStatus(subject, ids, activate); } /** * Activate or deactivate alert definitions by AppdefEntityID. * * */ public void activateAlertDefinitions(int sessionID, AppdefEntityID[] eids, boolean activate) throws SessionNotFoundException, SessionTimeoutException, AppdefEntityNotFoundException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); boolean debugEnabled = log.isDebugEnabled(); String status = (activate ? "enabled" : "disabled"); for (int i = 0; i < eids.length; i++) { AppdefEntityID eid = eids[i]; if (debugEnabled) { log.debug("AppdefEntityID [" + eid + "]"); } if (eid.isGroup()) { ResourceGroup group = resourceGroupManager.findResourceGroupById(eid.getId()); // Get the group alerts Collection<GalertDef> allAlerts = galertManager.findAlertDefs(group, PageControl.PAGE_ALL); for (GalertDef galertDef : allAlerts) { galertManager.enable(galertDef, activate); if (debugEnabled) { log.debug("Group Alert [" + galertDef + "] " + status); } } // Get the resource alerts of the group Collection<Resource> resources = resourceGroupManager.getMembers(group); for (Resource res : resources) { updateAlertDefinitionsActiveStatus(subject, res, activate); } } else { updateAlertDefinitionsActiveStatus(subject, resourceManager.findResource(eid), activate); } } } private void updateAlertDefinitionsActiveStatus(AuthzSubject subject, Resource res, boolean activate) throws PermissionException { boolean debugEnabled = log.isDebugEnabled(); String status = (activate ? "enabled" : "disabled"); Collection<AlertDefinition> allAlerts = alertDefinitionManager.findRelatedAlertDefinitions( subject, res); for (AlertDefinition alertDef : allAlerts) { alertDefinitionManager.updateAlertDefinitionActiveStatus(subject, alertDef, activate); if (debugEnabled) { log.debug("Resource Alert [" + alertDef + "] " + status); } } } /** * Update just the basics * * */ public void updateAlertDefinitionBasic(int sessionID, Integer alertDefId, String name, String desc, int priority, boolean activate) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); alertDefinitionManager.updateAlertDefinitionBasic(subject, alertDefId, name, desc, priority, activate); } /** * */ public void updateAlertDefinition(int sessionID, AlertDefinitionValue adval) throws TriggerCreateException, InvalidOptionException, InvalidOptionValueException, AlertConditionCreateException, ActionCreateException, SessionNotFoundException, SessionTimeoutException { final boolean debug = log.isDebugEnabled(); StopWatch watch = new StopWatch(); AuthzSubject subject = sessionManager.getSubject(sessionID); // Verify that there are some conditions to evaluate if (adval.getConditions().length < 1) { throw new InvalidOptionValueException("Conditions cannot be null or empty"); } if (EventConstants.TYPE_ALERT_DEF_ID.equals(adval.getParentId()) || adval.getAppdefType() == AppdefEntityConstants.APPDEF_TYPE_GROUP) { // A little more work to do for group and type alert definition if (debug) watch.markTimeBegin("updateParentAlertDefinition"); adval = alertDefinitionManager.updateAlertDefinition(adval); if (debug) { watch.markTimeEnd("updateParentAlertDefinition"); watch.markTimeBegin("findAlertDefinitionChildren"); } List<AlertDefinitionValue> children = alertDefinitionManager .findAlertDefinitionChildren(adval.getId()); if (debug) { watch.markTimeEnd("findAlertDefinitionChildren"); watch.markTimeBegin("updateChildAlertDefinitions[" + children.size() + "]"); } List zevents = new ArrayList(children.size()); for (AlertDefinitionValue child : children) { StopWatch childWatch = new StopWatch(); AppdefEntityID id = new AppdefEntityID(child.getAppdefType(), child.getAppdefId()); // Now add parent's conditions, actions, and new triggers try { alertDefinitionManager.cloneParentConditions(subject, id, child, adval .getConditions(), false, true); } catch (MeasurementNotFoundException e) { throw new AlertConditionCreateException(e); } alertDefinitionManager.cloneParentActions(id, child, adval.getActions()); // Set the alert definition frequency type child.setFrequencyType(adval.getFrequencyType()); child.setCount(adval.getCount()); child.setRange(adval.getRange()); // Set the alert definition filtering options child.setWillRecover(adval.getWillRecover()); child.setNotifyFiltered(adval.getNotifyFiltered()); child.setControlFiltered(adval.getControlFiltered()); // Triggers are deleted by the manager if (debug) childWatch.markTimeBegin("deleteAlertDefinitionTriggers"); registeredTriggerManager.deleteTriggers(child.getId()); if (debug) childWatch.markTimeEnd("deleteAlertDefinitionTriggers"); child.removeAllTriggers(); if (debug) childWatch.markTimeBegin("createTriggers"); // HHQ-3423: Do not add the TransactionListener here. // Add it at the end after all the triggers are created. registeredTriggerManager.createTriggers(subject, child, false); if (debug) childWatch.markTimeEnd("createTriggers"); // Now update the alert definition if (debug) childWatch.markTimeBegin("updateAlertDefinition"); AlertDefinitionValue updatedChild = alertDefinitionManager.updateAlertDefinition(child); if (debug) { childWatch.markTimeEnd("updateAlertDefinition"); log.debug("updateChildAlertDefinition[" + id + "]: time=" + childWatch); } zevents.add(new TriggersCreatedZevent(updatedChild.getId())); } if (debug) watch.markTimeEnd("updateChildAlertDefinitions[" + children.size() + "]"); // HHQ-3423: Add the TransactionListener after all the triggers are created if (!zevents.isEmpty()) { if (debug) watch.markTimeBegin("addTriggersCreatedTxListener"); registeredTriggerManager.addTriggersCreatedTxListener(zevents); if (debug) watch.markTimeEnd("addTriggersCreatedTxListener"); } } else { // First, get rid of the current triggers registeredTriggerManager.deleteTriggers(adval.getId()); adval.removeAllTriggers(); // Now create the new triggers registeredTriggerManager.createTriggers(subject, adval); // Now update the alert definition alertDefinitionManager.updateAlertDefinition(adval); } if (debug) { log.debug("updateAlertDefinition: time=" + watch); } } /** * Get actions for a given alert. * * @param alertId the alert id * * */ @Transactional(readOnly = true) public List<ActionValue> getActionsForAlert(int sessionId, Integer alertId) throws SessionNotFoundException, SessionTimeoutException { sessionManager.authenticate(sessionId); return actionManager.getActionsForAlert(alertId.intValue()); } /** * Update an action * * */ public void updateAction(int sessionID, ActionValue aval) throws SessionNotFoundException, SessionTimeoutException { sessionManager.authenticate(sessionID); actionManager.updateAction(aval); } /** * Delete a collection of alert definitions * * */ public void deleteAlertDefinitions(int sessionID, Integer[] ids) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); alertDefinitionManager.deleteAlertDefinitions(subject, ids); } /** * Delete list of alerts * * */ public void deleteAlerts(int sessionID, Integer[] ids) throws SessionNotFoundException, SessionTimeoutException, PermissionException { sessionManager.authenticate(sessionID); alertManager.deleteAlerts(ids); } /** * Delete all alerts for a list of alert definitions * * * */ public int deleteAlertsForDefinitions(int sessionID, Integer[] adids) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); // Delete alerts for definition and its children int count = 0; for (int i = 0; i < adids.length; i++) { AlertDefinition def = alertDefinitionManager.getByIdAndCheck(subject, adids[i]); count += alertManager.deleteAlerts(subject, def); Collection<AlertDefinition> children = def.getChildren(); for (AlertDefinition child : children) { count += alertManager.deleteAlerts(subject, child); } } return count; } /** * Get an alert definition by ID * * */ @Transactional(readOnly = true) public AlertDefinitionValue getAlertDefinition(int sessionID, Integer id) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); return alertDefinitionManager.getById(subject, id); } /** * Find an alert by ID * * */ @Transactional(readOnly = true) public Alert getAlert(int sessionID, Integer id) throws SessionNotFoundException, SessionTimeoutException, AlertNotFoundException { sessionManager.authenticate(sessionID); Alert alert = alertManager.findAlertById(id); if (alert == null) throw new AlertNotFoundException(id); return alert; } /** * Get a list of all alert definitions * * */ @Transactional(readOnly = true) public PageList<AlertDefinitionValue> findAllAlertDefinitions(int sessionID) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); return alertDefinitionManager.findAllAlertDefinitions(subject); } /** * Get a collection of alert definitions for a resource * * */ @Transactional(readOnly = true) public PageList<AlertDefinitionValue> findAlertDefinitions(int sessionID, AppdefEntityID id, PageControl pc) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); return alertDefinitionManager.findAlertDefinitions(subject, id, pc); } /** * Get a collection of alert definitions for a resource or resource type * */ @Transactional(readOnly = true) public PageList<AlertDefinitionValue> findAlertDefinitions(int sessionID, AppdefEntityTypeID id, PageControl pc) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); return alertDefinitionManager.findAlertDefinitions(subject, id, pc); } /** * Find all alert definition names for a resource * @return Map of AlertDefinition names and IDs * */ @Transactional(readOnly = true) public Map<String, Integer> findAlertDefinitionNames(int sessionID, AppdefEntityID id, Integer parentId) throws SessionNotFoundException, SessionTimeoutException, AppdefEntityNotFoundException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); return alertDefinitionManager.findAlertDefinitionNames(subject, id, parentId); } /** * Find all alerts for an appdef resource * * */ @Transactional(readOnly = true) public PageList<Alert> findAlerts(int sessionID, AppdefEntityID id, long begin, long end, PageControl pc) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); return alertManager.findAlerts(subject, id, begin, end, pc); } /** * Search alerts given a set of criteria * @param username the username * @param count the maximum number of alerts to return * @param priority allowable values: 0 (all), 1, 2, or 3 * @param timeRange the amount of time from current time to include * @param ids the IDs of resources to include or null for ALL * @return a list of {@link Escalatable}s * */ @Transactional(readOnly = true) public List<Escalatable> findRecentAlerts(String username, int count, int priority, long timeRange, AppdefEntityID[] ids) throws LoginException, ApplicationException, ConfigPropertyException { int sessionId = authBoss.getUnauthSessionId(username); return findRecentAlerts(sessionId, count, priority, timeRange, ids); } /** * Search recent alerts given a set of criteria * @param sessionID the session token * @param count the maximum number of alerts to return * @param priority allowable values: 0 (all), 1, 2, or 3 * @param timeRange the amount of time from current time to include * @param ids the IDs of resources to include or null for ALL * @return a list of {@link Escalatable}s * */ @Transactional(readOnly = true) public List<Escalatable> findRecentAlerts(int sessionID, int count, int priority, long timeRange, AppdefEntityID[] ids) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); long cur = System.currentTimeMillis(); final boolean debug = log.isDebugEnabled(); final StopWatch watch = new StopWatch(); List<AppdefEntityID> appentResources = ids != null ? appentResources = Arrays.asList(ids) : null; // Assume if user can be alerted, then they can view resource, // otherwise, it'll be filtered out later anyways if (debug) watch.markTimeBegin("findEscalatables"); List<Escalatable> alerts = alertManager.findEscalatables(subject, count, priority, timeRange, cur, appentResources); if (debug) watch.markTimeEnd("findEscalatables"); // CheckAlertingScope now only used for galerts if (ids == null) { // find ALL alertable resources if (debug) watch.markTimeBegin("checkAlertingScope"); appentResources = permissionManager.checkAlertingScope(subject); if (debug) watch.markTimeEnd("checkAlertingScope"); } if (debug) watch.markTimeBegin("galertManager.findEscalatables"); List<Escalatable> galerts = galertManager.findEscalatables(subject, count, priority, timeRange, cur, appentResources); if (debug) watch.markTimeEnd("galertManager.findEscalatables"); alerts.addAll(galerts); Collections.sort(alerts, new Comparator<Escalatable>() { public int compare(Escalatable o1, Escalatable o2) { if (o1 == o2) { return 0; } Long l1 = o1.getAlertInfo().getTimestamp(); Long l2 = o2.getAlertInfo().getTimestamp(); // Reverse sort return l2.compareTo(l1); } }); Set<AppdefEntityID> goodIds = new HashSet<AppdefEntityID>(); Set<AppdefEntityID> badIds = new HashSet<AppdefEntityID>(); List<Escalatable> res = new ArrayList<Escalatable>(); if (debug) watch.markTimeBegin("loop"); for (Iterator<Escalatable> i = alerts.iterator(); i.hasNext() && res.size() < count;) { Escalatable alert = i.next(); PerformsEscalations def = alert.getDefinition(); AlertDefinitionInterface defInfo = def.getDefinitionInfo(); AppdefEntityID aeid; aeid = AppdefUtil.newAppdefEntityId(defInfo.getResource()); if (badIds.contains(aeid)) continue; // Check to see if we already have the resource in the hash map if (!goodIds.contains(aeid)) { AppdefEntityValue entVal = new AppdefEntityValue(aeid, subject); try { entVal.getName(); goodIds.add(aeid); } catch (Exception e) { // Probably because the resource does not exist badIds.add(aeid); continue; } } res.add(alert); } if (debug) watch.markTimeEnd("loop"); if (debug) log.debug(watch); return res; } /** * Get config schema info for an action class * * */ @Transactional(readOnly = true) public ConfigSchema getActionConfigSchema(int sessionID, String actionClass) throws SessionNotFoundException, SessionTimeoutException, EncodingException { sessionManager.authenticate(sessionID); ActionInterface iface; try { Class<?> c = Class.forName(actionClass); iface = (ActionInterface) c.newInstance(); } catch (Exception exc) { throw new EncodingException("Failed to instantiate class: " + exc); } return iface.getConfigSchema(); } /* * The following trigger API's are specific to the CLI only */ /** * Get config schema info for a trigger class * * */ @Transactional(readOnly = true) public ConfigSchema getRegisteredTriggerConfigSchema(int sessionID, String triggerClass) throws SessionNotFoundException, SessionTimeoutException, EncodingException { sessionManager.authenticate(sessionID); RegisterableTriggerInterface iface; Class<?> c; try { c = Class.forName(triggerClass); iface = (RegisterableTriggerInterface) c.newInstance(); } catch (Exception exc) { throw new EncodingException("Failed to instantiate class: " + exc); } return iface.getConfigSchema(); } /** * */ public void deleteEscalationByName(int sessionID, String name) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ApplicationException { AuthzSubject subject = sessionManager.getSubject(sessionID); Escalation e = escalationManager.findByName(name); escalationManager.deleteEscalation(subject, e); } /** * */ public void deleteEscalationById(int sessionID, Integer id) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ApplicationException { deleteEscalationById(sessionID, new Integer[] { id }); } /** * remove escalation by id * */ public void deleteEscalationById(int sessionID, Integer[] ids) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ApplicationException { AuthzSubject subject = sessionManager.getSubject(sessionID); for (int i = 0; i < ids.length; i++) { Escalation e = escalationManager.findById(ids[i]); escalationManager.deleteEscalation(subject, e); } } /** * retrieve escalation by alert definition id. */ @Transactional(readOnly = true) private Escalation findEscalationByAlertDefId(Integer id, EscalationAlertType type) throws PermissionException { return escalationManager.findByDefId(type, id); } /** * retrieve escalation name by alert definition id. * * */ @Transactional(readOnly = true) public Integer getEscalationIdByAlertDefId(int sessionID, Integer id, EscalationAlertType alertType) throws SessionTimeoutException, SessionNotFoundException, PermissionException { sessionManager.authenticate(sessionID); Escalation esc = findEscalationByAlertDefId(id, alertType); return esc == null ? null : esc.getId(); } /** * set escalation name by alert definition id. * * */ public void setEscalationByAlertDefId(int sessionID, Integer id, Integer escId, EscalationAlertType alertType) throws SessionTimeoutException, SessionNotFoundException, PermissionException { sessionManager.authenticate(sessionID); Escalation escalation = findEscalationById(sessionID, escId); // TODO: check permission escalationManager.setEscalation(alertType, id, escalation); } /** * unset escalation by alert definition id. * * */ public void unsetEscalationByAlertDefId(int sessionID, Integer id, EscalationAlertType alertType) throws SessionTimeoutException, SessionNotFoundException, PermissionException { sessionManager.authenticate(sessionID); // TODO: check permission escalationManager.setEscalation(alertType, id, null); } /** * retrieve escalation JSONObject by alert definition id. * * */ public JSONObject jsonEscalationByAlertDefId(int sessionID, Integer id, EscalationAlertType alertType) throws SessionException, PermissionException, JSONException { sessionManager.authenticate(sessionID); Escalation e = findEscalationByAlertDefId(id, alertType); return e == null ? null : new JSONObject().put(e.getJsonName(), e.toJSON()); } /** * retrieve escalation object by escalation id. * * */ @Transactional(readOnly = true) public Escalation findEscalationById(int sessionID, Integer id) throws SessionTimeoutException, SessionNotFoundException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); Escalation e = escalationManager.findById(subject, id); // XXX: Temporarily get around lazy loading problem e.isPauseAllowed(); e.getMaxPauseTime(); return e; } /** * */ public void addAction(int sessionID, Escalation e, ActionConfigInterface cfg, long waitTime) throws SessionTimeoutException, SessionNotFoundException, PermissionException { sessionManager.authenticate(sessionID); escalationManager.addAction(e, cfg, waitTime); } /** * */ public void removeAction(int sessionID, Integer escId, Integer actId) throws SessionTimeoutException, SessionNotFoundException, PermissionException { sessionManager.authenticate(sessionID); Escalation e = escalationManager.findById(escId); if (e != null) { escalationManager.removeAction(e, actId); } } /** * Retrieve a list of {@link EscalationState}s, representing the active * escalations in the system. * * */ @Transactional(readOnly = true) public List<EscalationState> getActiveEscalations(int sessionId, int maxEscalations) throws SessionException { sessionManager.authenticate(sessionId); return escalationManager.getActiveEscalations(maxEscalations); } /** * Gets the escalatable associated with the specified state * */ @Transactional(readOnly = true) public Escalatable getEscalatable(int sessionId, EscalationState state) throws SessionException { sessionManager.authenticate(sessionId); return escalationManager.getEscalatable(state); } /** * retrieve all escalation policy names as a Array of JSONObject. * * Escalation json finders begin with json* to be consistent with DAO finder * convention * * */ @Transactional(readOnly = true) public JSONArray listAllEscalationName(int sessionID) throws JSONException, SessionTimeoutException, SessionNotFoundException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); Collection<Escalation> all = escalationManager.findAll(subject); JSONArray jarr = new JSONArray(); for (Escalation esc : all) { jarr.put(new JSONObject().put("id", esc.getId()).put("name", esc.getName())); } return jarr; } private AppdefEntityID getAppdefEntityID(AlertDefinitionValue ad) { return new AppdefEntityID(ad.getAppdefType(), ad.getAppdefId()); } /** * Create a new escalation. If alertDefId is non-null, the escalation will * also be associated with the given alert definition. * * */ public Escalation createEscalation(int sessionID, String name, String desc, boolean allowPause, long maxWaitTime, boolean notifyAll, boolean repeat, EscalationAlertType alertType, Integer alertDefId) throws SessionTimeoutException, SessionNotFoundException, PermissionException, DuplicateObjectException { sessionManager.authenticate(sessionID); // XXX -- We need to do perm-checking here Escalation res = escalationManager.createEscalation(name, desc, allowPause, maxWaitTime, notifyAll, repeat); if (alertDefId != null) { // The alert def needs to use this escalation escalationManager.setEscalation(alertType, alertDefId, res); } return res; } /** * Update basic escalation properties * * */ public void updateEscalation(int sessionID, Escalation escalation, String name, String desc, long maxWait, boolean pausable, boolean notifyAll, boolean repeat) throws SessionTimeoutException, SessionNotFoundException, PermissionException, DuplicateObjectException { AuthzSubject subject = sessionManager.getSubject(sessionID); escalationManager.updateEscalation(subject, escalation, name, desc, pausable, maxWait, notifyAll, repeat); } /** * */ public boolean acknowledgeAlert(int sessionID, EscalationAlertType alertType, Integer alertID, long pauseWaitTime, String moreInfo) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ActionExecuteException { AuthzSubject subject = sessionManager.getSubject(sessionID); return escalationManager.acknowledgeAlert(subject, alertType, alertID, moreInfo, pauseWaitTime); } /** * Fix a single alert. TODO: remove comment below Method WAS "NotSupported" * since all the alert fixes may take longer than the transaction timeout. * No need for a transaction in this context. * */ public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID, String moreInfo) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ActionExecuteException { fixAlert(sessionID, alertType, alertID, moreInfo, false); } /** * Fix a batch of alerts. TODO: remove comment below Method is * "NotSupported" since all the alert fixes may take longer than the * transaction timeout. No need for a transaction in this context. * */ public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID, String moreInfo, boolean fixAllPrevious) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ActionExecuteException { AuthzSubject subject = sessionManager.getSubject(sessionID); if (fixAllPrevious) { long fixCount = fixPreviousAlerts(sessionID, alertType, alertID, moreInfo); if (fixCount > 0) { if (moreInfo == null) { moreInfo = ""; } StringBuffer sb = new StringBuffer(); MessageFormat messageFormat = new MessageFormat(ResourceBundle.getBundle(BUNDLE) .getString("events.alert.fixAllPrevious")); messageFormat.format(new String[] { Long.toString(fixCount) }, sb, null); moreInfo = sb.toString() + moreInfo; } } // fix the selected alert escalationManager.fixAlert(subject, alertType, alertID, moreInfo, false); } /** * Fix all previous alerts. Method is "NotSupported" since all the alert * fixes may take longer than the transaction timeout. No need for a * transaction in this context. */ @SuppressWarnings("unchecked") private long fixPreviousAlerts(int sessionID, EscalationAlertType alertType, Integer alertID, String moreInfo) throws SessionTimeoutException, SessionNotFoundException, PermissionException, ActionExecuteException { StopWatch watch = new StopWatch(); AuthzSubject subject = sessionManager.getSubject(sessionID); long fixCount = 0; List<? extends AlertInterface> alertsToFix = null; // Get all previous unfixed alerts. watch.markTimeBegin("fixPreviousAlerts: findAlerts"); if (alertType.equals(ClassicEscalationAlertType.CLASSIC)) { AlertInterface alert = alertManager.findAlertById(alertID); alertsToFix = alertManager.findAlerts(subject.getId(), 0, alert.getTimestamp(), alert .getTimestamp(), false, true, null, alert.getAlertDefinitionInterface().getId(), PageInfo.getAll(AlertSortField.DATE, false)); } else if (alertType.equals(GalertEscalationAlertType.GALERT)) { AlertInterface alert = galertManager.findAlertLog(alertID); alertsToFix = galertManager.findAlerts(subject, AlertSeverity.LOW, alert.getTimestamp(), alert.getTimestamp(), false, true, null, alert .getAlertDefinitionInterface().getId(), PageInfo.getAll( GalertLogSortField.DATE, false)); } else { alertsToFix = Collections.EMPTY_LIST; } watch.markTimeEnd("fixPreviousAlerts: findAlerts"); log.debug("fixPreviousAlerts: alertId = " + alertID + ", previous alerts to fix = " + (alertsToFix.size() - 1) + ", time = " + watch); watch.markTimeBegin("fixPreviousAlerts: fixAlert"); try { for (AlertInterface alert : alertsToFix) { try { // Suppress notifications for all previous alerts. if (!alert.getId().equals(alertID)) { escalationManager.fixAlert(subject, alertType, alert.getId(), moreInfo, true); fixCount++; } } catch (PermissionException pe) { throw pe; } catch (Exception e) { // continue with next alert log.error("Could not fix alert id " + alert.getId() + ": " + e.getMessage(), e); } } } finally { watch.markTimeEnd("fixPreviousAlerts: fixAlert"); log.debug("fixPreviousAlerts: alertId = " + alertID + ", previous alerts fixed = " + fixCount + ", time = " + watch); } return fixCount; } /** * Get the last fix if available * */ @Transactional(readOnly = true) public String getLastFix(int sessionID, Integer defId) throws SessionNotFoundException, SessionTimeoutException, PermissionException { AuthzSubject subject = sessionManager.getSubject(sessionID); // Look for the last fixed alert AlertDefinition def = alertDefinitionManager.getByIdAndCheck(subject, defId); return escalationManager.getLastFix(def); } /** * Get a maintenance event by group id * * */ @Transactional(readOnly = true) public MaintenanceEvent getMaintenanceEvent(int sessionId, Integer groupId) throws SessionNotFoundException, SessionTimeoutException, PermissionException, SchedulerException { AuthzSubject subject = sessionManager.getSubject(sessionId); return getMaintenanceEventManager().getMaintenanceEvent(subject, groupId); } /** * Schedule a maintenance event * * */ public MaintenanceEvent scheduleMaintenanceEvent(int sessionId, MaintenanceEvent event) throws SessionNotFoundException, SessionTimeoutException, PermissionException, SchedulerException { AuthzSubject subject = sessionManager.getSubject(sessionId); return getMaintenanceEventManager().schedule(subject, event); } /** * Schedule a maintenance event * * */ public void unscheduleMaintenanceEvent(int sessionId, MaintenanceEvent event) throws SessionNotFoundException, SessionTimeoutException, PermissionException, SchedulerException { AuthzSubject subject = sessionManager.getSubject(sessionId); event.setModifiedBy(subject.getName()); getMaintenanceEventManager().unschedule(subject, event); } }
unlicense
BlackPeachLawn/HelloWorld
ZFS-master/ZFS-master/FileServer/src/StNodeInfo.java
1606
import java.io.IOException; public class StNodeInfo implements Comparable{ String nodeName; String nodeIP; int nodePort; Volume volume; String uuid; long lastVis; public StNodeInfo(){} public StNodeInfo(String name,String ip,int port,long tot,long avi){ volume=new Volume(avi,tot);nodeIP=ip; nodeName=name; nodePort=port; } public static void main(String[] args) throws IOException { StNodeInfo t1=new StNodeInfo(); t1.volume=new Volume(1000,100000000); StNodeInfo t2=new StNodeInfo(); t2.volume=new Volume(546546879,100000000); System.out.println(t1.compareTo(t2)); } @Override public int compareTo(Object o) { return volume.compareTo(((StNodeInfo)o).volume); } } class Volume implements Comparable{ private long length; private long available; Volume(long avi,long tot){ length=tot; available=avi; } public long getTotalBytes(){ return length; } public long getAvailalblebytes(){ return available; } public static String volumeToString(int byteLength){ if(byteLength<1024) return byteLength+"bytes"; else if(byteLength<1024*1024) return (double)byteLength/1024+"KB"; else if(byteLength<1024*1024*1024) return (double)byteLength/1024/1024+"MB"; else return (double)byteLength/1024/1024/1024+"GB"; } @Override public int compareTo(Object o) { return (int)(-available+((Volume)o).available); } }
unlicense
socialenemy/rails-blog
config/routes.rb
310
Rails.application.routes.draw do mount Ckeditor::Engine => '/ckeditor' root 'posts#index' get '/life', to: 'posts#index_life' get '/code', to: 'posts#index_code' get '/contact', to: 'posts#index_contact' get '/:slug', to: 'posts#show', as: 'post' resources :posts devise_for :users end
unlicense
nobesnickr/ApiTimesheets
apigility/module/ApiTimesheets/src/ApiTimesheets/V1/Doctrine/ClientAware/Traits/ClientAware.php
452
<?php namespace ApiTimesheets\Doctrine\ClientAware\Traits; use ApiTimesheets\Entity\Client; /** * ClientAware Trait, usable with PHP >= 5.4 */ trait ClientAware { /** * @var Client */ protected $client; /** * @return Client */ public function getClient() { return $this->client; } /** * @param Client $client * * @return $this */ public function setClient( $client ) { $this->client = $client; return $this; } }
unlicense
JoKolov/ocp3
modules/commentaires/classes/commentaire.class.php
6514
<?php if (!defined('EXECUTION')) exit; /** * @project : Blog Jean Forteroche * @author <[email protected]> * * MODULE : Commentaires * FILE/ROLE : Classe Commentaire * * File Last Update : 2017 09 26 * * File Description : * -> gestion des attributs des commentaires * -> contient en attribut tous les éléments de la table Commentaire * -> permet de contrôler l'intégrité des données du commentaire avant insertion dans la BDD */ class Commentaire { //------------------------------------------------------------ // Attributs // liés à la BDD protected $_id; // BDD : int > id Commentaire protected $_billet_id; // BDD : int > id Billet commenté protected $_com_id; // BDD : int > id Commentaire commenté protected $_com_level; // BDD : int > niveau d'affichage du commentaire protected $_auteur_id; // BDD : int > id Membre protected $_contenu; // BDD : text protected $_date_publie; // BDD : datetime > date_publie (date de publication) protected $_approuve; // BDD : tinyint > TRUE (1) FALSE (0) protected $_signalement; // BDD : int > nombre de signalements public $_enfants = []; // tableau d'enfants protected $_auteur; // récupéré par controleur // constantes de la classe const COM_LEVEL_MAX = 5; const NB_SIGNALEMENTS_MAX = 10; //------------------------------------------------------------ // Constructeur et méthodes magiques // public function __construct() { } //------------------------------------------------------------ // Getteurs // liés à la BDD public function get_id() { return $this->_id; } public function get_billet_id() { return $this->_billet_id; } public function get_com_id() { return $this->_com_id; } public function get_com_level() { return $this->_com_level; } public function get_auteur_id() { return $this->_auteur_id; } public function get_contenu() { return $this->_contenu; } public function get_date_publie() { return $this->_date_publie; } public function get_approuve() { return $this->_approuve; } public function get_signalement() { return $this->_signalement; } public function getAuteur() { return $this->_auteur; } public function getNbLimitSignalements() { return self::NB_SIGNALEMENTS_MAX; } //------------------------------------------------------------ // Setteurs // liés à la BDD public function set_id($id) { return $this->setteur_id($id); } public function set_billet_id($id) { return $this->setteur_billet_id($id); } public function set_com_id($id) { return $this->setteur_com_id($id); } public function set_com_level($nombre) { return $this->setteur_com_level($nombre); } public function set_auteur_id($id) { return $this->setteur_auteur_id($id); } public function set_contenu($text) { return $this->setteur_contenu($text); } public function set_date_publie($date) { return $this->setteur_date_publie($date); } public function set_approuve($etat) { return $this->setteur_approuve($etat); } public function set_signalement($nombre) { return $this->setteur_signalement($nombre); } // non lié à la BDD public function setAuteur($auteur) { $this->_auteur = $auteur; } //==================== // SET ID //==================== protected function setteur_id($id) { $id = (int) $id; if (is_int($id) AND $id > 0) { $this->_id = $id; return TRUE; } return FALSE; } //==================== // SET BILLET_ID //==================== protected function setteur_billet_id($id) { $id = (int) $id; if (is_int($id) AND $id > 0) { $this->_billet_id = $id; return TRUE; } // Erreur return FALSE; } //==================== // SET COM_ID //==================== protected function setteur_com_id($id) { if (is_null($id) OR $id == '') { $this->_com_id = 0; return TRUE; } if ($id >= 0) { $this->_com_id = $id; return TRUE; } // Erreur return FALSE; } //==================== // SET COM_LEVEL //==================== protected function setteur_com_level($nombre) { $nombre = (int) $nombre; if ($nombre < 0) { $nombre = 0; } if ($nombre > 5) { $nombre = 5; } $this->_com_level = $nombre; return TRUE; } //==================== // SET AUTEUR_ID //==================== protected function setteur_auteur_id($id) { $id = (int) $id; if ($id < 0) { $id = 0; } $this->_auteur_id = $id; return TRUE; } //==================== // SET TITRE //==================== protected function setteur_contenu($text) { if (is_string($text) AND $text <> '') { $text = htmlspecialchars($text, ENT_NOQUOTES); $this->_contenu = $text; return TRUE; } // Erreur $this->_contenu = ''; return FALSE; } //==================== // SET DATE_PUBLIE //==================== protected function setteur_date_publie($date) { $this->_date_publie = $date; return TRUE; } //==================== // SET IMAGE ID //==================== protected function setteur_approuve($etat) { if ($etat === TRUE OR $etat == 1 OR $etat === FALSE OR $etat == 0) { $this->_approuve = $etat; return TRUE; } return FALSE; } //==================== // SET IMAGE ID //==================== protected function setteur_signalement($nombre) { $nombre = (int) $nombre; $this->_signalement = $nombre; return TRUE; } //------------------------------------------------------------ // Hydratation /** * [ setValues permet d'hydrater l'objet en appelant les méthodes selon les clés du tableau en argument] * @param array $donnees [tableau contenant des $key associées à des $value] * @return TRUE si toutes les données ont été setté correctement, FALSE si aucune donnée n'a été envoyée, string contenant le nom des données non settés */ public function setValues(array $donnees) { foreach ($donnees as $key => $value) { $method = 'set_' . $key; if (method_exists($this, $method)) { if ($this->$method($value)) { unset($donnees[$key]); } } } if (in_array(FALSE, $donnees)) { return $donnees; } return $this; } //------------------------------------------------------------ // Méthodes }
unlicense
fmottard/conjugation-service
src/main/java/com/notesonjava/conjugations/model/Persona.java
438
package com.notesonjava.conjugations.model; import lombok.Getter; public enum Persona { NONE(0), YO(1), TU(2), VOS(4), EL(5), ELLO(7), NOSOTROS(8), VOSOTROS(10), ELLOS(13); @Getter private int value; Persona(int value) { this.value = value; } public static Persona valueOf(int value){ for(Persona p : Persona.values()){ if(p.getValue() == value){ return p; } } return Persona.NONE; } }
unlicense
maikodaraine/EnlightenmentUbuntu
bindings/python/python-efl/examples/elementary/test_theme.py
2429
#!/usr/bin/env python # encoding: utf-8 import os from efl import elementary from efl.elementary.window import StandardWindow from efl.elementary.box import Box from efl.elementary.separator import Separator from efl.elementary.button import Button from efl.elementary.theme import Theme from efl.evas import EVAS_HINT_FILL, EVAS_HINT_EXPAND script_path = os.path.dirname(os.path.abspath(__file__)) theme_file = os.path.join(script_path, "test_theme.edj") th = Theme.default_get() def add_ext_clicked_cb(obj): th.extension_add(theme_file) print("Estensions: " + str(th.extension_list)) def del_ext_clicked_cb(obj): th.extension_del(theme_file) print("Estensions: " + str(th.extension_list)) def add_ovr_clicked_cb(obj): th.overlay_add(theme_file) print("Overlays: " + str(th.overlay_list)) def del_ovr_clicked_cb(obj): th.overlay_del(theme_file) print("Overlays: " + str(th.overlay_list)) def theme_clicked(obj, data=None): win = StandardWindow("config", "Theme", autodel=True, size=(400,200)) if obj is None: win.callback_delete_request_add(lambda o: elementary.exit()) box = Box(win) box.size_hint_weight = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND box.show() win.resize_object_add(box) bt = Button(win, text = "A button with a custom style") bt.size_hint_weight = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND bt.style = "my_custom_style" bt.show() box.pack_end(bt) bt = Button(win, text = "A button with default style") bt.size_hint_weight = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND bt.show() box.pack_end(bt) sep = Separator(win, horizontal=True) sep.show() box.pack_end(sep) hbox = Box(win, horizontal=True) hbox.show() box.pack_end(hbox) bt = Button(win, text = "Add Extension") bt.callback_clicked_add(add_ext_clicked_cb) bt.show() hbox.pack_end(bt) bt = Button(win, text = "Remove Extension") bt.callback_clicked_add(del_ext_clicked_cb) bt.show() hbox.pack_end(bt) bt = Button(win, text = "Add Overlay") bt.callback_clicked_add(add_ovr_clicked_cb) bt.show() hbox.pack_end(bt) bt = Button(win, text = "Remove Overlay") bt.callback_clicked_add(del_ovr_clicked_cb) bt.show() hbox.pack_end(bt) win.show() if __name__ == "__main__": elementary.init() theme_clicked(None) elementary.run() elementary.shutdown()
unlicense
WUSTL-GIS-Programming-spring-2014/classinfo
Classes/Class4/modulesymboltables.py
220
a = 0 def myName(): print "When called by a function in my namespace, my name is", __name__ def whatisa(): a = 1 print a def whatisglobala(): global a print a print "Right now, my name is:", __name__
unlicense
D-Inc/EnderIO
src/main/java/crazypants/enderio/loot/LootSelector.java
7394
package crazypants.enderio.loot; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import crazypants.enderio.EnderIO; import crazypants.enderio.Log; import crazypants.enderio.capacitor.CapacitorHelper; import crazypants.enderio.capacitor.CapacitorHelper.SetType; import crazypants.util.NbtValue; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.WeightedRandom; import net.minecraft.world.storage.loot.LootContext; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; public class LootSelector extends LootFunction { public LootSelector(LootCondition[] conditionsIn) { super(conditionsIn); } @Override public ItemStack apply(ItemStack stack, Random rand, LootContext context) { Map<WeightedUpgrade, Float> keys = new HashMap<WeightedUpgrade, Float>(); float baselevel = getRandomBaseLevel(rand); int no = getRandomCount(rand); for (int i = 0; i < no; i++) { WeightedUpgrade randomKey = getUpgrade(rand); float randomLevel = getRandomLevel(baselevel, rand); baselevel = Math.max(baselevel - randomLevel / 10f * rand.nextFloat(), .5f); if (keys.containsKey(randomKey)) { randomLevel = Math.max(randomLevel, keys.get(randomKey)); } keys.put(randomKey, randomLevel); } String name = buildBaseName(EnderIO.lang.localize("itemBasicCapacitor.name"), baselevel); stack = CapacitorHelper.addCapData(stack, SetType.LEVEL, null, baselevel); for (Entry<WeightedUpgrade, Float> entry : keys.entrySet()) { stack = CapacitorHelper.addCapData(stack, entry.getKey().setType, entry.getKey().capacitorKey, entry.getValue()); name = buildName(EnderIO.lang.localize(entry.getKey().langKey, name), entry.getValue()); } NbtValue.CAPNAME.setString(stack, name); String count_s = EnderIO.lang.localize("loot.capacitor.entry.count"); int count = 8; try { count = Integer.valueOf(count_s); } catch (NumberFormatException e) { Log.warn("The value of the language key 'enderio.loot.capacitor.entry.count' is not a valid number!"); } NbtValue.CAPNO.setInt(stack, rand.nextInt(count)); count_s = EnderIO.lang.localize("loot.capacitor.title.count"); count = 8; try { count = Integer.valueOf(count_s); } catch (NumberFormatException e) { Log.warn("The value of the language key 'enderio.loot.capacitor.title.count' is not a valid number!"); } stack.setStackDisplayName(EnderIO.lang.localize("loot.capacitor.title." + rand.nextInt(count))); NbtValue.GLINT.setInt(stack, 1); return stack; } private static final List<WeightedInteger> weightedCount = new ArrayList<WeightedInteger>(); static { weightedCount.add(new WeightedInteger(1, 5)); weightedCount.add(new WeightedInteger(3, 4)); weightedCount.add(new WeightedInteger(6, 3)); weightedCount.add(new WeightedInteger(6, 2)); weightedCount.add(new WeightedInteger(24, 1)); } private int getRandomCount(Random rand) { return WeightedRandom.getRandomItem(rand, weightedCount).getInteger(); } public static String buildBaseName(String name, float level) { if (level < 1f) { name = EnderIO.lang.localize("loot.capacitor.baselevel.10", name); } else if (level < 1.5f) { name = EnderIO.lang.localize("loot.capacitor.baselevel.15", name); } else if (level < 2.5f) { name = EnderIO.lang.localize("loot.capacitor.baselevel.25", name); } else if (level < 3.5f) { name = EnderIO.lang.localize("loot.capacitor.baselevel.35", name); } else { name = EnderIO.lang.localize("loot.capacitor.baselevel.45", name); } return name; } public static String buildName(String name, float level) { if (level < 1f) { name = EnderIO.lang.localize("loot.capacitor.level.10", name); } else if (level < 1.5f) { name = EnderIO.lang.localize("loot.capacitor.level.15", name); } else if (level < 2.5f) { name = EnderIO.lang.localize("loot.capacitor.level.25", name); } else if (level < 3f) { name = EnderIO.lang.localize("loot.capacitor.level.30", name); } else if (level < 3.5f) { name = EnderIO.lang.localize("loot.capacitor.level.35", name); } else if (level < 4f) { name = EnderIO.lang.localize("loot.capacitor.level.40", name); } else if (level < 4.25f) { name = EnderIO.lang.localize("loot.capacitor.level.42", name); } else { name = EnderIO.lang.localize("loot.capacitor.level.45", name); } return name; } private float getRandomBaseLevel(Random rand) { if (rand.nextFloat() < .3f) { return 1f + (rand.nextFloat() - rand.nextFloat()) * .5f; } else { return 1f + rand.nextFloat() + rand.nextFloat() + rand.nextFloat() + rand.nextFloat(); } } /** * Gets a random value that is: * * <p> * For baselevel==1: Centered around 1.8, spread from 0.8 to 2.8 * <p> * For baselevel==2: Centered around 2.7, spread from 1.4 to 3.8 * <p> * For baselevel==3: Centered around 3.6, spread from 2.5 to 4.2 */ private static float getRandomLevel(float baseLevel, Random rand) { return (getRandomLevel2(baseLevel - .6f, rand) + getRandomLevel2(baseLevel + .5f, rand)) / 2 - .5f; } private static float getRandomLevel2(float baseLevel, Random rand) { float result = baseLevel + rand.nextFloat() * (4 - baseLevel) / 3; for (int i = 1; i < 2; i++) { result += rand.nextFloat() / i * 2; if (result >= baseLevel + 1) result -= rand.nextFloat() / (i + 1); } return Math.min(result, 4.75f); } private WeightedUpgrade getUpgrade(Random rand) { return WeightedRandom.getRandomItem(rand, WeightedUpgrade.getWeightedupgrades()).getUpgrade(); } public static class Serializer extends LootFunction.Serializer<LootSelector> { public Serializer() { super(new ResourceLocation(EnderIO.DOMAIN, "set_capacitor"), LootSelector.class); } @Override public void serialize(JsonObject object, LootSelector functionClazz, JsonSerializationContext serializationContext) { } @Override public LootSelector deserialize(JsonObject object, JsonDeserializationContext deserializationContext, LootCondition[] conditionsIn) { return new LootSelector(conditionsIn); } } // debug only static void test_getRandomLevel(float baselevel) { Random rand = new Random(); int runs = 100000; int[] a = new int[50]; for (int i = 0; i < runs; i++) { float randomLevel = getRandomLevel(baselevel, rand); int idx = (int) (randomLevel * 10); a[idx]++; } int max = 0; for (int j = 0; j < 50; j++) { if (a[j] >= max) { max = a[j]; } } for (int i = max; i > 0; i -= max / 20) { for (int j = 0; j < 50; j++) { if (a[j] >= i) { System.out.print("#"); } else { System.out.print(" "); } } System.out.println(); } System.out.println("0....|...1.0...|...2.0...|...3.0...|...4.0...|...5.0"); } }
unlicense
jlaura/isis3
isis/src/base/objs/ShapeModel/unitTest.cpp
19893
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include <iostream> #include <iomanip> #include <QVector> #include "Angle.h" #include "Camera.h" #include "CameraFactory.h" #include "Cube.h" #include "Distance.h" #include "IException.h" #include "Latitude.h" #include "Longitude.h" #include "Preference.h" #include "Pvl.h" #include "ShapeModel.h" #include "SurfacePoint.h" #include "Target.h" using namespace std; using namespace Isis; /** * This application tests the ShapeModel class * * @author 2010-10-11 Debbie A. Cook * * @internal * @history 2015-05-04 Jeannie Backer - Added test for isDEM() and improved * overall test coverage. * @history 2016-08-28 Kelvin Rodriguez - Changed print statements to properly flush * std out before exceptions to better suit differences in OSX 10.11 * part of porting to 10.11. * * testcoverage 2015-04-30 - 78.947% scope, 91.057% line, 96.154% function * testcoverage 2015-05-04 - 94.737% scope, 100% line, 100% function */ class MyShape : public ShapeModel { public: MyShape(Target *target) : ShapeModel (target) { setName("Test"); } using Isis::ShapeModel::intersectSurface; bool intersectSurface(std::vector<double> observerPos, std::vector<double> lookDirection) { cout << " intersectSurface called with observer position = " << observerPos[0] << ", " << observerPos[1] << ", " << observerPos[2] << endl << " lookDirection = " << lookDirection[0] << ", " << lookDirection[1] << ", " << lookDirection[2] << endl; intersectEllipsoid(observerPos, lookDirection); SpiceDouble intersectionPoint[3] = {-2123.362258286, -2380.3717812236, 1194.6783966636}; surfaceIntersection()->FromNaifArray(intersectionPoint); setHasIntersection(true); return true; } bool isDEM() const { return false; } bool ellipsoidIntersection() { return hasEllipsoidIntersection(); } virtual void calculateDefaultNormal() { calculateSurfaceNormal(); } virtual void calculateLocalNormal(QVector<double *> cornerNeighborPoints) { std::vector<double> myNormal(3); myNormal[0] = -0.581842; myNormal[1] = -0.703663; myNormal[2] = 0.407823; setNormal(myNormal); setHasNormal(true); } virtual void calculateSurfaceNormal() { setNormal( -0.623384, -0.698838, 0.350738); setHasNormal(true); } virtual void calculateEllipsoidNormal() { calculateEllipsoidalSurfaceNormal(); } Distance localRadius(const Latitude &lat, const Longitude &lon) { double a = 6378.14; double b = 6378.14; double c = 6356.75; double rlat = lat.degrees(); double rlon = lon.degrees(); double xyradius = a * b / sqrt(pow(b * cos(rlon), 2) + pow(a * sin(rlon), 2)); const double &radius = xyradius * c / sqrt(pow(c * cos(rlat), 2) + pow(xyradius * sin(rlat), 2)); return Distance(radius, Distance::Kilometers); } bool normalStatus() { return hasNormal(); } void setSmallNormal() { std::vector<double> normal(3, 10.); setNormal(normal); setHasNormal(true); } void setBigNormal() { std::vector<double> normal(3, -10.); setNormal(normal); setHasNormal(true); } double resolution() { return ShapeModel::resolution(); } void setNoNormal() { setHasNormal(false); } }; class MyEllipse : public ShapeModel { public: MyEllipse(Target *target) : ShapeModel (target) { setName("Ellipsoid"); } MyEllipse() : ShapeModel() { setName("DefaultConstructor"); } bool intersectSurface(std::vector<double> observerPos, std::vector<double> lookDirection) { cout << " intersectSurface called with observer position = " << observerPos[0] << ", " << observerPos[1] << ", " << observerPos[2] << endl << " lookDirection = " << lookDirection[0] << ", " << lookDirection[1] << ", " << lookDirection[2] << endl; return (intersectEllipsoid(observerPos, lookDirection)); } bool isDEM() const { return false; } virtual void calculateLocalNormal(QVector<double *> cornerNeighborPoints) { std::vector<Distance> radii = targetRadii(); std::vector<double> normal(3, 0.); SpiceDouble point[3]; surfaceIntersection()->ToNaifArray(point); surfnm_c(radii[0].kilometers(), radii[1].kilometers(), radii[2].kilometers(), point, (SpiceDouble *) &normal[0]); setNormal(normal); setHasNormal(true); } virtual void calculateSurfaceNormal() { std::vector<Distance> radii = targetRadii(); std::vector<double> normal(3, 0.); SpiceDouble point[3]; surfaceIntersection()->ToNaifArray(point); surfnm_c(radii[0].kilometers(), radii[1].kilometers(), radii[2].kilometers(), point, (SpiceDouble *) &normal[0]); setNormal(normal); setHasNormal(true); } virtual void calculateDefaultNormal() { setNormal(1, 0, 0); setHasNormal(true); } Distance localRadius(const Latitude &lat, const Longitude &lon) { std::vector<Distance> radii = targetRadii(); double a = radii[0].kilometers(); double b = radii[1].kilometers(); double c = radii[2].kilometers(); double rlat = lat.degrees(); double rlon = lon.degrees(); double xyradius = a * b / sqrt(pow(b * cos(rlon), 2) + pow(a * sin(rlon), 2)); const double &radius = xyradius * c / sqrt(pow(c * cos(rlat), 2) + pow(xyradius * sin(rlat), 2)); return Distance(radius, Distance::Kilometers); } bool normalStatus() { return hasNormal(); } double resolution() { return ShapeModel::resolution(); } }; int main() { try { Preference::Preferences(true); QString inputFile = "$ISISTESTDATA/isis/src/mgs/unitTestData/ab102401.cub"; Cube cube; cube.open(inputFile); Camera *c = cube.camera(); std::vector<Distance> radii = c->target()->radii(); Pvl pvl = *cube.label(); Spice spi(cube); Target targ(&spi, pvl); targ.setRadii(radii); cout << "Begin testing Shape Model base class...." << endl; MyShape shape(&targ); cout << endl << " Shape name is " << shape.name() << endl; cout << " Do we have an intersection? " << shape.hasIntersection() << endl; cout << " Do we have an ellipsoid intersection? " << shape.ellipsoidIntersection() << endl; try { shape.resolution(); } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } try { shape.calculateDefaultNormal(); } catch (IException &e) { cout << " Test setNormal(double,double,double) error message " "when there is no intersection:" << endl; e.print(); } QVector<double *> notUsed(4); for (int i = 0; i < notUsed.size(); i ++) notUsed[i] = new double[3]; try { shape.calculateLocalNormal(notUsed); } catch (IException &e) { cout << " Test setNormal(vector) error message when there is no intersection:" << endl; e.print(); } cout << " Set a pixel in the image and check again." << endl; double line = 453.0; double sample = 534.0; c->SetImage(sample, line); std::vector<double> sB(3); c->instrumentPosition((double *) &sB[0]); std::vector<double> uB(3); c->sunPosition((double *) &uB[0]); std::vector<double> lookB(3); c->SpacecraftSurfaceVector((double *) &lookB[0]); /* Sample/Line = 534/453 surface normal = -0.623384, -0.698838, 0.350738 Local normal = -0.581842, -0.703663, 0.407823 Phase = 40.787328112158 Incidence = 85.341094499768 Emission = 46.966269013795 */ cout << endl << " Testing pure virtual method intersectSurface..." << endl; if (!shape.intersectSurface(sB, lookB)) { cout << " ... intersectSurface method failed" << endl; return -1; } cout << " Do we have an intersection? " << shape.hasIntersection() << endl; cout << " Do we have an ellipsoid intersection? " << shape.ellipsoidIntersection() << endl; try { cout << " Get the resolution: "; cout << shape.resolution() << endl; } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } SurfacePoint *sp = shape.surfaceIntersection(); cout << " surface point = (" << sp->GetX().kilometers() << ", " << sp->GetY().kilometers() << ", " << sp->GetZ().kilometers() << ")" << endl; try { cout << endl << " Testing class method normal() when no normal exists..." << endl; cout << " Do we have a normal? " << shape.normalStatus() << endl; std::vector<double> badnormal = shape.normal(); } catch(Isis::IException &e) { e.print(); } cout << endl << " Testing photometric angle calculations before normal computation..." << endl; cout << " Do we have a normal? " << shape.normalStatus() << endl; double emission = shape.emissionAngle(sB); double incidence = shape.incidenceAngle(uB); cout << " Emission angle = " << emission; cout << " Incidence angle = " << incidence; cout << endl; cout << endl << " Testing class method calculateLocalNormal..." << endl; shape.calculateLocalNormal(notUsed); cout << " Do we have a normal? " << shape.normalStatus() << endl; vector<double> myNormal(3); myNormal = shape.normal(); cout << " local normal = (" << myNormal[0] << ", " << myNormal[1] << ", " << myNormal[2] << ")" << endl; cout << endl << " Testing class method calculateSurfaceNormal..." << endl; shape.calculateSurfaceNormal(); myNormal = shape.normal(); cout << " surface normal = (" << myNormal[0] << ", " << myNormal[1] << ", " << myNormal[2] << ")" << endl; cout << endl << " Testing photometric angle calculations with undersize normal..." << endl; shape.setSmallNormal(); emission = shape.emissionAngle(sB); incidence = shape.incidenceAngle(uB); cout << " Emission angle = " << emission; cout << " Incidence angle = " << incidence; cout << endl; cout << endl << " Testing photometric angle calculations with oversize normal..." << endl; shape.setBigNormal(); emission = shape.emissionAngle(sB); incidence = shape.incidenceAngle(uB); cout << " Emission angle = " << emission; cout << " Incidence angle = " << incidence; cout << endl; cout << " Testing class method calculateDefaultNormal..." << endl; shape.calculateDefaultNormal(); myNormal = shape.normal(); cout << " default normal = (" << myNormal[0] << ", " << myNormal[1] << ", " << myNormal[2] << ")" << endl; cout << endl << " Testing photometric angle calculations..." << endl; // reset has normal to false to test (!hasNormal) scope for incidenceAngle() shape.setNoNormal(); incidence = shape.incidenceAngle(uB); emission = shape.emissionAngle(sB); cout << " Emission angle = " << emission; cout << " Incidence angle = " << incidence; cout << " Phase angle = " << shape.phaseAngle(sB, uB); cout << endl; cout << endl << " Testing localRadius method ..." << endl; cout << " Local radius = " << shape.localRadius(Latitude(20.532461495381, Angle::Degrees), Longitude(228.26609149754, Angle::Degrees)).kilometers() << endl; // Mars radii = 3397. 3397. 3375. cout << endl << " Testing intersection with occlusion check..." << endl; if (!shape.intersectSurface(Latitude(20.532461495381, Angle::Degrees), Longitude(228.26609149754, Angle::Degrees), sB, true)) { cout << " ... intersectSurface method failed" << endl; return -1; } cout << " Do we have an intersection? " << shape.hasIntersection() << endl; cout << " Do we have an ellipsoid intersection? " << shape.ellipsoidIntersection() << endl; cout << " Is the intersection visible? " << shape.isVisibleFrom(sB, lookB) << endl; SurfacePoint *occPoint = shape.surfaceIntersection(); std::vector<double> occPosition(3, 0.0); occPosition[0] = occPoint->GetX().kilometers() * 1.1; occPosition[1] = occPoint->GetY().kilometers() * 1.1; occPosition[2] = occPoint->GetZ().kilometers() * 1.1; cout << " Is the intersection visible from just above it? " << shape.isVisibleFrom(occPosition, lookB) << endl; cout << " Calculate the ellipsoid normal" << endl; shape.calculateEllipsoidNormal(); cout << " Do we have a normal? " << shape.normalStatus() << endl; myNormal = shape.normal(); cout << " local normal = (" << myNormal[0] << ", " << myNormal[1] << ", " << myNormal[2] << ")" << endl; cout << endl << " Testing setHasIntersection method" << endl; shape.setHasIntersection(false); cout << " Do we have an intersection? " << shape.hasIntersection() << endl; try { cout << " Get the resolution: "; cout << shape.resolution() << endl; } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } try { cout << " Attempt to calculate the ellipsoid normal without an intersection" << endl; shape.calculateEllipsoidNormal(); cout << " Calculation successful" << endl; } catch (IException &e) { e.print(); } cout << endl << " Testing setSurfacePoint method ..." << endl; shape.setSurfacePoint(*sp); cout << " Do we have an intersection? " << shape.hasIntersection() << endl; try { cout << " Get the resolution: "; cout << shape.resolution() << endl; } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } cout << " surface point = (" << sp->GetX().kilometers() << ", " << sp->GetY().kilometers() << ", " << sp->GetZ().kilometers() << ")" << endl; // Test ellipse methods in base class MyEllipse eshape(&targ); try { cout << endl << " Testing ellipsoid methods in base class" << endl; cout << " Do we have an intersection? "; cout << eshape.hasIntersection() << endl; try { cout << " Get the resolution: "; cout << eshape.resolution() << endl; } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } cout << endl << " Testing failing of method intersectEllipsoid..." << endl; std::vector<double> badlook(3,1.); badlook[0] = -1.; if (!eshape.intersectSurface(sB, badlook)) { cout << " ... intersectSurface method failed -- no intersection" << endl; } cout << " Do we have an intersection? " << eshape.hasIntersection() << endl; try { cout << " Get the resolution: "; cout << eshape.resolution() << endl; } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } cout << endl << " Testing method intersectEllipsoid..." << endl; if (eshape.intersectSurface(sB, lookB)) { SurfacePoint *sp = eshape.surfaceIntersection(); cout << " surface point = (" << sp->GetX().kilometers() << ", " << sp->GetY().kilometers() << ", " << sp->GetZ().kilometers() << ")" << endl; } cout << " Do we have an intersection? " << eshape.hasIntersection() << endl; cout << " Get the resolution: " << eshape.resolution() << endl; SurfacePoint *sp = eshape.surfaceIntersection(); cout << " surface point = (" << sp->GetX().kilometers() << ", " << sp->GetY().kilometers() << ", " << sp->GetZ().kilometers() << ")" << endl; try { cout << endl << " Testing method calculateEllipsoidalSurfaceNormal with invalid intersection..." << endl; SurfacePoint badsp; eshape.setSurfacePoint(badsp); eshape.setHasIntersection(true); eshape.calculateLocalNormal(notUsed); } catch(Isis::IException &e) { e.print(); } cout << endl << " Testing method setHasIntersection false..." << endl; eshape.setHasIntersection(false); cout << " Do we have an intersection? " << eshape.hasIntersection() << endl; try { cout << " Get the resolution: "; cout << eshape.resolution() << endl; } catch (IException &e) { cout << " Test resolution() error message when there is no intersection:" << endl; e.print(); } try { cout << endl << " Testing method calculateEllipsoidalSurfaceNormal with no intersection..." << endl; eshape.calculateLocalNormal(notUsed); } catch(Isis::IException &e) { e.print(); } cout << endl << " Testing method calculateEllipsoidalSurfaceNormal with valid intersection..." << endl; if (eshape.intersectSurface(sB, lookB)) cout << " Intersection set" << endl; cout << " Do we have a normal? " << eshape.normalStatus() << endl; eshape.calculateLocalNormal(notUsed); cout << " Do we have a normal? " << eshape.normalStatus() << endl; myNormal = eshape.normal(); cout << " local normal = (" << myNormal[0] << ", " << myNormal[1] << ", " << myNormal[2] << ")" << endl; eshape.calculateSurfaceNormal(); myNormal = eshape.normal(); cout << endl << " Testing method targetRadii..." << endl; cout << " true normal = (" << myNormal[0] << ", " << myNormal[1] << ", " << myNormal[2] << ")" << endl; } catch(Isis::IException &e) { IException(e, IException::Unknown, "Test ellipse methods failed.", _FILEINFO_).print(); } // Test MyEllipse defaultShape; cout << endl << " Testing default constructor..." << endl; cout << " Shape is " << defaultShape.name() << endl; cout << " Do we have an intersection? " << defaultShape.hasIntersection() << endl; cout << " Is there a normal? " << defaultShape.normalStatus() << endl; try { defaultShape.resolution(); } catch (IException &e) { cout << " Test resolution() error message when there is no target:" << endl; e.print(); } try { defaultShape.calculateSurfaceNormal(); } catch (IException &e) { cout << " Test targetRadii() error message when there is no target:" << endl; e.print(); } defaultShape.setHasIntersection(true); defaultShape.calculateDefaultNormal(); cout << " Is there a normal? " << defaultShape.normalStatus() << endl; cout << " Number of normal components = " << defaultShape.normal().size() << endl; cube.close(); } catch (IException &e) { cout << endl << endl; QString msg = "**************** UNIT TEST FAILED! **************** "; IException(e, IException::Unknown, msg, _FILEINFO_).print(); } }
unlicense
Elideb/UnExt
Test/Scripts/TestTransformExtensions.cs
1222
using UnityEngine; using UnExt; public class TestTransformExtensions : MonoBehaviour { private GameObject origin; private GameObject target; private Vector3 point = new Vector3( 3, 2, 4 ); Quaternion rotation = Quaternion.Euler( 0, 0, 0 ); void Start() { this.origin = new GameObject( "Origin" ); this.origin.transform.position = Vector3.zero; this.target = new GameObject( "Target" ); this.target.transform.position = this.point; } // Update is called once per frame void Update() { rotation = Quaternion.Euler( new Vector3( 0, 0, Time.time * 10 ) ); target.transform.position = point.Rotate( rotation ); } void OnDrawGizmos() { if (this.origin != null && this.target != null) { Color prevColor = Gizmos.color; Gizmos.color = Color.magenta; foreach (var cam in GameObject.FindObjectsOfType<Camera>()) { Gizmos.DrawLine( cam.transform.ProjectPointInPlane( this.origin.transform.position ), cam.transform.ProjectPointInPlane( this.target.transform.position ) ); } Gizmos.color = prevColor; } } }
unlicense
thermaleagle/neowork
neowork/Fast Loan App Reviewer/src/com/example/loanapp/frontend/shared/vo/CaseSearchResultVO.java
1801
package com.example.loanapp.frontend.shared.vo; import java.io.Serializable; import java.util.Map; import java.util.Set; import com.example.loanapp.frontend.shared.types.MatchingBasis; public class CaseSearchResultVO implements Serializable { /** * */ private static final long serialVersionUID = -6862485070905904825L; private Map<MatchingBasis, String> countOfCasesByBasis; private Set<String> caseIdsMatchingAllCriteria; private String countOfCaseIdsMatchingAllCriteria; /** * @return the countOfCaseIdsMatchingAllCriteria */ public String getCountOfCaseIdsMatchingAllCriteria() { return countOfCaseIdsMatchingAllCriteria; } /** * @param countOfCaseIdsMatchingAllCriteria * the countOfCaseIdsMatchingAllCriteria to set */ public void setCountOfCaseIdsMatchingAllCriteria(final String countOfCaseIdsMatchingAllCriteria) { this.countOfCaseIdsMatchingAllCriteria = countOfCaseIdsMatchingAllCriteria; } /** * @return the countOfCasesByBasis */ public Map<MatchingBasis, String> getCountOfCasesByBasis() { return countOfCasesByBasis; } /** * @param countOfCasesByBasis * the countOfCasesByBasis to set */ public void setCountOfCasesByBasis(final Map<MatchingBasis, String> countOfCasesByBasis) { this.countOfCasesByBasis = countOfCasesByBasis; } /** * @return the caseIdsMatchingAllCriteria */ public Set<String> getCaseIdsMatchingAllCriteria() { return caseIdsMatchingAllCriteria; } /** * @param caseIdsMatchingAllCriteria * the caseIdsMatchingAllCriteria to set */ public void setCaseIdsMatchingAllCriteria(final Set<String> caseIdsMatchingAllCriteria) { this.caseIdsMatchingAllCriteria = caseIdsMatchingAllCriteria; } }
unlicense
RedTriplane/RedTriplane
r3-box2d-jf/src/org/jbox2d/f/particle/ParticleSystem.java
77151
package org.jbox2d.f.particle; import java.lang.reflect.Array; import java.util.Arrays; import org.jbox2d.f.callbacks.ParticleDestructionListener; import org.jbox2d.f.callbacks.ParticleQueryCallback; import org.jbox2d.f.callbacks.ParticleRaycastCallback; import org.jbox2d.f.callbacks.QueryCallback; import org.jbox2d.f.collision.AABB; import org.jbox2d.f.collision.RayCastInput; import org.jbox2d.f.collision.RayCastOutput; import org.jbox2d.f.collision.shapes.Shape; import org.jbox2d.f.common.BufferUtils; import org.jbox2d.f.common.MathUtils; import org.jbox2d.f.common.Rot; import org.jbox2d.f.common.Settings; import org.jbox2d.f.common.Transform; import org.jbox2d.f.common.Vector2; import org.jbox2d.f.dynamics.Body; import org.jbox2d.f.dynamics.Fixture; import org.jbox2d.f.dynamics.TimeStep; import org.jbox2d.f.dynamics.World; import org.jbox2d.f.particle.VoronoiDiagram.VoronoiDiagramCallback; public class ParticleSystem { /** All particle types that require creating pairs */ private static final int k_pairFlags = ParticleType.b2_springParticle; /** All particle types that require creating triads */ private static final int k_triadFlags = ParticleType.b2_elasticParticle; /** All particle types that require computing depth */ private static final int k_noPressureFlags = ParticleType.b2_powderParticle; static final int xTruncBits = 12; static final int yTruncBits = 12; static final int tagBits = 8 * 4 - 1 /* sizeof(int) */; static final long yOffset = 1 << (yTruncBits - 1); static final int yShift = tagBits - yTruncBits; static final int xShift = tagBits - yTruncBits - xTruncBits; static final long xScale = 1 << xShift; static final long xOffset = xScale * (1 << (xTruncBits - 1)); static final int xMask = (1 << xTruncBits) - 1; static final int yMask = (1 << yTruncBits) - 1; static long computeTag(float x, float y) { return (((long) (y + yOffset)) << yShift) + (((long) (xScale * x)) + xOffset); } static long computeRelativeTag(long tag, int x, int y) { return tag + (y << yShift) + (x << xShift); } static int limitCapacity(int capacity, int maxCount) { return maxCount != 0 && capacity > maxCount ? maxCount : capacity; } int m_timestamp; int m_allParticleFlags; int m_allGroupFlags; float m_density; float m_inverseDensity; float m_gravityScale; float m_particleDiameter; float m_inverseDiameter; float m_squaredDiameter; int m_count; int m_internalAllocatedCapacity; int m_maxCount; ParticleBufferInt m_flagsBuffer; ParticleBuffer<Vector2> m_positionBuffer; ParticleBuffer<Vector2> m_velocityBuffer; float[] m_accumulationBuffer; // temporary values Vector2[] m_accumulation2Buffer; // temporary vector values float[] m_depthBuffer; // distance from the surface public ParticleBuffer<ParticleColor> m_colorBuffer; ParticleGroup[] m_groupBuffer; ParticleBuffer<Object> m_userDataBuffer; int m_proxyCount; int m_proxyCapacity; Proxy[] m_proxyBuffer; public int m_contactCount; int m_contactCapacity; public ParticleContact[] m_contactBuffer; public int m_bodyContactCount; int m_bodyContactCapacity; public ParticleBodyContact[] m_bodyContactBuffer; int m_pairCount; int m_pairCapacity; Pair[] m_pairBuffer; int m_triadCount; int m_triadCapacity; Triad[] m_triadBuffer; int m_groupCount; ParticleGroup m_groupList; float m_pressureStrength; float m_dampingStrength; float m_elasticStrength; float m_springStrength; float m_viscousStrength; float m_surfaceTensionStrengthA; float m_surfaceTensionStrengthB; float m_powderStrength; float m_ejectionStrength; float m_colorMixingStrength; World m_world; public ParticleSystem(World world) { m_world = world; m_timestamp = 0; m_allParticleFlags = 0; m_allGroupFlags = 0; m_density = 1; m_inverseDensity = 1; m_gravityScale = 1; m_particleDiameter = 1; m_inverseDiameter = 1; m_squaredDiameter = 1; m_count = 0; m_internalAllocatedCapacity = 0; m_maxCount = 0; m_proxyCount = 0; m_proxyCapacity = 0; m_contactCount = 0; m_contactCapacity = 0; m_bodyContactCount = 0; m_bodyContactCapacity = 0; m_pairCount = 0; m_pairCapacity = 0; m_triadCount = 0; m_triadCapacity = 0; m_groupCount = 0; m_pressureStrength = 0.05f; m_dampingStrength = 1.0f; m_elasticStrength = 0.25f; m_springStrength = 0.25f; m_viscousStrength = 0.25f; m_surfaceTensionStrengthA = 0.1f; m_surfaceTensionStrengthB = 0.2f; m_powderStrength = 0.5f; m_ejectionStrength = 0.5f; m_colorMixingStrength = 0.5f; m_flagsBuffer = new ParticleBufferInt(); m_positionBuffer = new ParticleBuffer<Vector2>(Vector2.class); m_velocityBuffer = new ParticleBuffer<Vector2>(Vector2.class); m_colorBuffer = new ParticleBuffer<ParticleColor>(ParticleColor.class); m_userDataBuffer = new ParticleBuffer<Object>(Object.class); } // public void assertNotSamePosition() { // for (int i = 0; i < m_count; i++) { // Vec2 vi = m_positionBuffer.data[i]; // for (int j = i + 1; j < m_count; j++) { // Vec2 vj = m_positionBuffer.data[j]; // assert(vi.x != vj.x || vi.y != vj.y); // } // } // } public int createParticle(ParticleDef def) { if (m_count >= m_internalAllocatedCapacity) { int capacity = m_count != 0 ? 2 * m_count : Settings.minParticleBufferCapacity; capacity = limitCapacity(capacity, m_maxCount); capacity = limitCapacity(capacity, m_flagsBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_positionBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_velocityBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_colorBuffer.userSuppliedCapacity); capacity = limitCapacity(capacity, m_userDataBuffer.userSuppliedCapacity); if (m_internalAllocatedCapacity < capacity) { m_flagsBuffer.data = reallocateBuffer(m_flagsBuffer, m_internalAllocatedCapacity, capacity, false); m_positionBuffer.data = reallocateBuffer(m_positionBuffer, m_internalAllocatedCapacity, capacity, false); m_velocityBuffer.data = reallocateBuffer(m_velocityBuffer, m_internalAllocatedCapacity, capacity, false); m_accumulationBuffer = BufferUtils.reallocateBuffer(m_accumulationBuffer, 0, m_internalAllocatedCapacity, capacity, false); m_accumulation2Buffer = BufferUtils.reallocateBuffer(Vector2.class, m_accumulation2Buffer, 0, m_internalAllocatedCapacity, capacity, true); m_depthBuffer = BufferUtils.reallocateBuffer(m_depthBuffer, 0, m_internalAllocatedCapacity, capacity, true); m_colorBuffer.data = reallocateBuffer(m_colorBuffer, m_internalAllocatedCapacity, capacity, true); m_groupBuffer = BufferUtils.reallocateBuffer(ParticleGroup.class, m_groupBuffer, 0, m_internalAllocatedCapacity, capacity, false); m_userDataBuffer.data = reallocateBuffer(m_userDataBuffer, m_internalAllocatedCapacity, capacity, true); m_internalAllocatedCapacity = capacity; } } if (m_count >= m_internalAllocatedCapacity) { return Settings.invalidParticleIndex; } int index = m_count++; m_flagsBuffer.data[index] = def.flags; m_positionBuffer.data[index].set(def.position); // assertNotSamePosition(); m_velocityBuffer.data[index].set(def.velocity); m_groupBuffer[index] = null; if (m_depthBuffer != null) { m_depthBuffer[index] = 0; } if (m_colorBuffer.data != null || def.color != null) { m_colorBuffer.data = requestParticleBuffer(m_colorBuffer.dataClass, m_colorBuffer.data); m_colorBuffer.data[index].set(def.color); } if (m_userDataBuffer.data != null || def.userData != null) { m_userDataBuffer.data = requestParticleBuffer(m_userDataBuffer.dataClass, m_userDataBuffer.data); m_userDataBuffer.data[index] = def.userData; } if (m_proxyCount >= m_proxyCapacity) { int oldCapacity = m_proxyCapacity; int newCapacity = m_proxyCount != 0 ? 2 * m_proxyCount : Settings.minParticleBufferCapacity; m_proxyBuffer = BufferUtils.reallocateBuffer(Proxy.class, m_proxyBuffer, oldCapacity, newCapacity); m_proxyCapacity = newCapacity; } m_proxyBuffer[m_proxyCount++].index = index; return index; } public void destroyParticle(int index, boolean callDestructionListener) { int flags = ParticleType.b2_zombieParticle; if (callDestructionListener) { flags |= ParticleType.b2_destructionListener; } m_flagsBuffer.data[index] |= flags; } private final AABB temp = new AABB(); private final DestroyParticlesInShapeCallback dpcallback = new DestroyParticlesInShapeCallback(); public int destroyParticlesInShape(Shape shape, Transform xf, boolean callDestructionListener) { dpcallback.init(this, shape, xf, callDestructionListener); shape.computeAABB(temp, xf, 0); m_world.queryAABB(dpcallback, temp); return dpcallback.destroyed; } public void destroyParticlesInGroup(ParticleGroup group, boolean callDestructionListener) { for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { destroyParticle(i, callDestructionListener); } } private final AABB temp2 = new AABB(); private final Vector2 tempVec = new Vector2(); private final Transform tempTransform = new Transform(); private final Transform tempTransform2 = new Transform(); private CreateParticleGroupCallback createParticleGroupCallback = new CreateParticleGroupCallback(); private final ParticleDef tempParticleDef = new ParticleDef(); public ParticleGroup createParticleGroup(ParticleGroupDef groupDef) { float stride = getParticleStride(); final Transform identity = tempTransform; identity.setIdentity(); Transform transform = tempTransform2; transform.setIdentity(); int firstIndex = m_count; if (groupDef.shape != null) { final ParticleDef particleDef = tempParticleDef; particleDef.flags = groupDef.flags; particleDef.color = groupDef.color; particleDef.userData = groupDef.userData; Shape shape = groupDef.shape; transform.set(groupDef.position, groupDef.angle); AABB aabb = temp; int childCount = shape.getChildCount(); for (int childIndex = 0; childIndex < childCount; childIndex++) { if (childIndex == 0) { shape.computeAABB(aabb, identity, childIndex); } else { AABB childAABB = temp2; shape.computeAABB(childAABB, identity, childIndex); aabb.combine(childAABB); } } final float upperBoundY = aabb.upperBound.y; final float upperBoundX = aabb.upperBound.x; for (float y = MathUtils.floor(aabb.lowerBound.y / stride) * stride; y < upperBoundY; y += stride) { for (float x = MathUtils.floor(aabb.lowerBound.x / stride) * stride; x < upperBoundX; x += stride) { Vector2 p = tempVec; p.x = x; p.y = y; if (shape.testPoint(identity, p)) { Transform.mulToOut(transform, p, p); particleDef.position.x = p.x; particleDef.position.y = p.y; p.subLocal(groupDef.position); Vector2.crossToOutUnsafe(groupDef.angularVelocity, p, particleDef.velocity); particleDef.velocity.addLocal(groupDef.linearVelocity); createParticle(particleDef); } } } } int lastIndex = m_count; ParticleGroup group = new ParticleGroup(); group.m_system = this; group.m_firstIndex = firstIndex; group.m_lastIndex = lastIndex; group.m_groupFlags = groupDef.groupFlags; group.m_strength = groupDef.strength; group.m_userData = groupDef.userData; group.m_transform.set(transform); group.m_destroyAutomatically = groupDef.destroyAutomatically; group.m_prev = null; group.m_next = m_groupList; if (m_groupList != null) { m_groupList.m_prev = group; } m_groupList = group; ++m_groupCount; for (int i = firstIndex; i < lastIndex; i++) { m_groupBuffer[i] = group; } updateContacts(true); if ((groupDef.flags & k_pairFlags) != 0) { for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a > b) { int temp = a; a = b; b = temp; } if (firstIndex <= a && b < lastIndex) { if (m_pairCount >= m_pairCapacity) { int oldCapacity = m_pairCapacity; int newCapacity = m_pairCount != 0 ? 2 * m_pairCount : Settings.minParticleBufferCapacity; m_pairBuffer = BufferUtils.reallocateBuffer(Pair.class, m_pairBuffer, oldCapacity, newCapacity); m_pairCapacity = newCapacity; } Pair pair = m_pairBuffer[m_pairCount]; pair.indexA = a; pair.indexB = b; pair.flags = contact.flags; pair.strength = groupDef.strength; pair.distance = MathUtils.distance(m_positionBuffer.data[a], m_positionBuffer.data[b]); m_pairCount++; } } } if ((groupDef.flags & k_triadFlags) != 0) { VoronoiDiagram diagram = new VoronoiDiagram(lastIndex - firstIndex); for (int i = firstIndex; i < lastIndex; i++) { diagram.addGenerator(m_positionBuffer.data[i], i); } diagram.generate(stride / 2); createParticleGroupCallback.system = this; createParticleGroupCallback.def = groupDef; createParticleGroupCallback.firstIndex = firstIndex; diagram.getNodes(createParticleGroupCallback); } if ((groupDef.groupFlags & ParticleGroupType.b2_solidParticleGroup) != 0) { computeDepthForGroup(group); } return group; } public void joinParticleGroups(ParticleGroup groupA, ParticleGroup groupB) { assert (groupA != groupB); RotateBuffer(groupB.m_firstIndex, groupB.m_lastIndex, m_count); assert (groupB.m_lastIndex == m_count); RotateBuffer(groupA.m_firstIndex, groupA.m_lastIndex, groupB.m_firstIndex); assert (groupA.m_lastIndex == groupB.m_firstIndex); int particleFlags = 0; for (int i = groupA.m_firstIndex; i < groupB.m_lastIndex; i++) { particleFlags |= m_flagsBuffer.data[i]; } updateContacts(true); if ((particleFlags & k_pairFlags) != 0) { for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a > b) { int temp = a; a = b; b = temp; } if (groupA.m_firstIndex <= a && a < groupA.m_lastIndex && groupB.m_firstIndex <= b && b < groupB.m_lastIndex) { if (m_pairCount >= m_pairCapacity) { int oldCapacity = m_pairCapacity; int newCapacity = m_pairCount != 0 ? 2 * m_pairCount : Settings.minParticleBufferCapacity; m_pairBuffer = BufferUtils.reallocateBuffer(Pair.class, m_pairBuffer, oldCapacity, newCapacity); m_pairCapacity = newCapacity; } Pair pair = m_pairBuffer[m_pairCount]; pair.indexA = a; pair.indexB = b; pair.flags = contact.flags; pair.strength = MathUtils.min(groupA.m_strength, groupB.m_strength); pair.distance = MathUtils.distance(m_positionBuffer.data[a], m_positionBuffer.data[b]); m_pairCount++; } } } if ((particleFlags & k_triadFlags) != 0) { VoronoiDiagram diagram = new VoronoiDiagram(groupB.m_lastIndex - groupA.m_firstIndex); for (int i = groupA.m_firstIndex; i < groupB.m_lastIndex; i++) { if ((m_flagsBuffer.data[i] & ParticleType.b2_zombieParticle) == 0) { diagram.addGenerator(m_positionBuffer.data[i], i); } } diagram.generate(getParticleStride() / 2); JoinParticleGroupsCallback callback = new JoinParticleGroupsCallback(); callback.system = this; callback.groupA = groupA; callback.groupB = groupB; diagram.getNodes(callback); } for (int i = groupB.m_firstIndex; i < groupB.m_lastIndex; i++) { m_groupBuffer[i] = groupA; } int groupFlags = groupA.m_groupFlags | groupB.m_groupFlags; groupA.m_groupFlags = groupFlags; groupA.m_lastIndex = groupB.m_lastIndex; groupB.m_firstIndex = groupB.m_lastIndex; destroyParticleGroup(groupB); if ((groupFlags & ParticleGroupType.b2_solidParticleGroup) != 0) { computeDepthForGroup(groupA); } } // Only called from solveZombie() or joinParticleGroups(). void destroyParticleGroup(ParticleGroup group) { assert (m_groupCount > 0); assert (group != null); if (m_world.getParticleDestructionListener() != null) { m_world.getParticleDestructionListener().sayGoodbye(group); } for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { m_groupBuffer[i] = null; } if (group.m_prev != null) { group.m_prev.m_next = group.m_next; } if (group.m_next != null) { group.m_next.m_prev = group.m_prev; } if (group == m_groupList) { m_groupList = group.m_next; } --m_groupCount; } public void computeDepthForGroup(ParticleGroup group) { for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { m_accumulationBuffer[i] = 0; } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a >= group.m_firstIndex && a < group.m_lastIndex && b >= group.m_firstIndex && b < group.m_lastIndex) { float w = contact.weight; m_accumulationBuffer[a] += w; m_accumulationBuffer[b] += w; } } m_depthBuffer = requestParticleBuffer(m_depthBuffer); for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { float w = m_accumulationBuffer[i]; m_depthBuffer[i] = w < 0.8f ? 0 : Float.MAX_VALUE; } int interationCount = group.getParticleCount(); for (int t = 0; t < interationCount; t++) { boolean updated = false; for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (a >= group.m_firstIndex && a < group.m_lastIndex && b >= group.m_firstIndex && b < group.m_lastIndex) { float r = 1 - contact.weight; float ap0 = m_depthBuffer[a]; float bp0 = m_depthBuffer[b]; float ap1 = bp0 + r; float bp1 = ap0 + r; if (ap0 > ap1) { m_depthBuffer[a] = ap1; updated = true; } if (bp0 > bp1) { m_depthBuffer[b] = bp1; updated = true; } } } if (!updated) { break; } } for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { float p = m_depthBuffer[i]; if (p < Float.MAX_VALUE) { m_depthBuffer[i] *= m_particleDiameter; } else { m_depthBuffer[i] = 0; } } } public void addContact(int a, int b) { assert(a != b); Vector2 pa = m_positionBuffer.data[a]; Vector2 pb = m_positionBuffer.data[b]; float dx = pb.x - pa.x; float dy = pb.y - pa.y; float d2 = dx * dx + dy * dy; // assert(d2 != 0); if (d2 < m_squaredDiameter) { if (m_contactCount >= m_contactCapacity) { int oldCapacity = m_contactCapacity; int newCapacity = m_contactCount != 0 ? 2 * m_contactCount : Settings.minParticleBufferCapacity; m_contactBuffer = BufferUtils.reallocateBuffer(ParticleContact.class, m_contactBuffer, oldCapacity, newCapacity); m_contactCapacity = newCapacity; } float invD = d2 != 0 ? MathUtils.sqrt(1 / d2) : Float.MAX_VALUE; ParticleContact contact = m_contactBuffer[m_contactCount]; contact.indexA = a; contact.indexB = b; contact.flags = m_flagsBuffer.data[a] | m_flagsBuffer.data[b]; contact.weight = 1 - d2 * invD * m_inverseDiameter; contact.normal.x = invD * dx; contact.normal.y = invD * dy; m_contactCount++; } } public void updateContacts(boolean exceptZombie) { for (int p = 0; p < m_proxyCount; p++) { Proxy proxy = m_proxyBuffer[p]; int i = proxy.index; Vector2 pos = m_positionBuffer.data[i]; proxy.tag = computeTag(m_inverseDiameter * pos.x, m_inverseDiameter * pos.y); } Arrays.sort(m_proxyBuffer, 0, m_proxyCount); m_contactCount = 0; int c_index = 0; for (int i = 0; i < m_proxyCount; i++) { Proxy a = m_proxyBuffer[i]; long rightTag = computeRelativeTag(a.tag, 1, 0); for (int j = i + 1; j < m_proxyCount; j++) { Proxy b = m_proxyBuffer[j]; if (rightTag < b.tag) { break; } addContact(a.index, b.index); } long bottomLeftTag = computeRelativeTag(a.tag, -1, 1); for (; c_index < m_proxyCount; c_index++) { Proxy c = m_proxyBuffer[c_index]; if (bottomLeftTag <= c.tag) { break; } } long bottomRightTag = computeRelativeTag(a.tag, 1, 1); for (int b_index = c_index; b_index < m_proxyCount; b_index++) { Proxy b = m_proxyBuffer[b_index]; if (bottomRightTag < b.tag) { break; } addContact(a.index, b.index); } } if (exceptZombie) { int j = m_contactCount; for (int i = 0; i < j; i++) { if ((m_contactBuffer[i].flags & ParticleType.b2_zombieParticle) != 0) { --j; ParticleContact temp = m_contactBuffer[j]; m_contactBuffer[j] = m_contactBuffer[i]; m_contactBuffer[i] = temp; --i; } } m_contactCount = j; } } private final UpdateBodyContactsCallback ubccallback = new UpdateBodyContactsCallback(); public void updateBodyContacts() { final AABB aabb = temp; aabb.lowerBound.x = Float.MAX_VALUE; aabb.lowerBound.y = Float.MAX_VALUE; aabb.upperBound.x = -Float.MAX_VALUE; aabb.upperBound.y = -Float.MAX_VALUE; for (int i = 0; i < m_count; i++) { Vector2 p = m_positionBuffer.data[i]; Vector2.minToOut(aabb.lowerBound, p, aabb.lowerBound); Vector2.maxToOut(aabb.upperBound, p, aabb.upperBound); } aabb.lowerBound.x -= m_particleDiameter; aabb.lowerBound.y -= m_particleDiameter; aabb.upperBound.x += m_particleDiameter; aabb.upperBound.y += m_particleDiameter; m_bodyContactCount = 0; ubccallback.system = this; m_world.queryAABB(ubccallback, aabb); } private SolveCollisionCallback sccallback = new SolveCollisionCallback(); public void solveCollision(TimeStep step) { final AABB aabb = temp; final Vector2 lowerBound = aabb.lowerBound; final Vector2 upperBound = aabb.upperBound; lowerBound.x = Float.MAX_VALUE; lowerBound.y = Float.MAX_VALUE; upperBound.x = -Float.MAX_VALUE; upperBound.y = -Float.MAX_VALUE; for (int i = 0; i < m_count; i++) { final Vector2 v = m_velocityBuffer.data[i]; final Vector2 p1 = m_positionBuffer.data[i]; final float p1x = p1.x; final float p1y = p1.y; final float p2x = p1x + step.dt * v.x; final float p2y = p1y + step.dt * v.y; final float bx = p1x < p2x ? p1x : p2x; final float by = p1y < p2y ? p1y : p2y; lowerBound.x = lowerBound.x < bx ? lowerBound.x : bx; lowerBound.y = lowerBound.y < by ? lowerBound.y : by; final float b1x = p1x > p2x ? p1x : p2x; final float b1y = p1y > p2y ? p1y : p2y; upperBound.x = upperBound.x > b1x ? upperBound.x : b1x; upperBound.y = upperBound.y > b1y ? upperBound.y : b1y; } sccallback.step = step; sccallback.system = this; m_world.queryAABB(sccallback, aabb); } public void solve(TimeStep step) { ++m_timestamp; if (m_count == 0) { return; } m_allParticleFlags = 0; for (int i = 0; i < m_count; i++) { m_allParticleFlags |= m_flagsBuffer.data[i]; } if ((m_allParticleFlags & ParticleType.b2_zombieParticle) != 0) { solveZombie(); } if (m_count == 0) { return; } m_allGroupFlags = 0; for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { m_allGroupFlags |= group.m_groupFlags; } final float gravityx = step.dt * m_gravityScale * m_world.getGravity().x; final float gravityy = step.dt * m_gravityScale * m_world.getGravity().y; float criticalVelocytySquared = getCriticalVelocitySquared(step); for (int i = 0; i < m_count; i++) { Vector2 v = m_velocityBuffer.data[i]; v.x += gravityx; v.y += gravityy; float v2 = v.x * v.x + v.y * v.y; if (v2 > criticalVelocytySquared) { float a = v2 == 0 ? Float.MAX_VALUE : MathUtils.sqrt(criticalVelocytySquared / v2); v.x *= a; v.y *= a; } } solveCollision(step); if ((m_allGroupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { solveRigid(step); } if ((m_allParticleFlags & ParticleType.b2_wallParticle) != 0) { solveWall(step); } for (int i = 0; i < m_count; i++) { Vector2 pos = m_positionBuffer.data[i]; Vector2 vel = m_velocityBuffer.data[i]; pos.x += step.dt * vel.x; pos.y += step.dt * vel.y; } updateBodyContacts(); updateContacts(false); if ((m_allParticleFlags & ParticleType.b2_viscousParticle) != 0) { solveViscous(step); } if ((m_allParticleFlags & ParticleType.b2_powderParticle) != 0) { solvePowder(step); } if ((m_allParticleFlags & ParticleType.b2_tensileParticle) != 0) { solveTensile(step); } if ((m_allParticleFlags & ParticleType.b2_elasticParticle) != 0) { solveElastic(step); } if ((m_allParticleFlags & ParticleType.b2_springParticle) != 0) { solveSpring(step); } if ((m_allGroupFlags & ParticleGroupType.b2_solidParticleGroup) != 0) { solveSolid(step); } if ((m_allParticleFlags & ParticleType.b2_colorMixingParticle) != 0) { solveColorMixing(step); } solvePressure(step); solveDamping(step); } void solvePressure(TimeStep step) { // calculates the sum of contact-weights for each particle // that means dimensionless density for (int i = 0; i < m_count; i++) { m_accumulationBuffer[i] = 0; } for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; float w = contact.weight; m_accumulationBuffer[a] += w; } for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; float w = contact.weight; m_accumulationBuffer[a] += w; m_accumulationBuffer[b] += w; } // ignores powder particles if ((m_allParticleFlags & k_noPressureFlags) != 0) { for (int i = 0; i < m_count; i++) { if ((m_flagsBuffer.data[i] & k_noPressureFlags) != 0) { m_accumulationBuffer[i] = 0; } } } // calculates pressure as a linear function of density float pressurePerWeight = m_pressureStrength * getCriticalPressure(step); for (int i = 0; i < m_count; i++) { float w = m_accumulationBuffer[i]; float h = pressurePerWeight * MathUtils.max(0.0f, MathUtils.min(w, Settings.maxParticleWeight) - Settings.minParticleWeight); m_accumulationBuffer[i] = h; } // applies pressure between each particles in contact float velocityPerPressure = step.dt / (m_density * m_particleDiameter); for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; Body b = contact.body; float w = contact.weight; float m = contact.mass; Vector2 n = contact.normal; Vector2 p = m_positionBuffer.data[a]; float h = m_accumulationBuffer[a] + pressurePerWeight * w; final Vector2 f = tempVec; final float coef = velocityPerPressure * w * m * h; f.x = coef * n.x; f.y = coef * n.y; final Vector2 velData = m_velocityBuffer.data[a]; final float particleInvMass = getParticleInvMass(); velData.x -= particleInvMass * f.x; velData.y -= particleInvMass * f.y; b.applyLinearImpulse(f, p, true); } for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vector2 n = contact.normal; float h = m_accumulationBuffer[a] + m_accumulationBuffer[b]; final float fx = velocityPerPressure * w * h * n.x; final float fy = velocityPerPressure * w * h * n.y; final Vector2 velDataA = m_velocityBuffer.data[a]; final Vector2 velDataB = m_velocityBuffer.data[b]; velDataA.x -= fx; velDataA.y -= fy; velDataB.x += fx; velDataB.y += fy; } } void solveDamping(TimeStep step) { // reduces normal velocity of each contact float damping = m_dampingStrength; for (int k = 0; k < m_bodyContactCount; k++) { final ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; Body b = contact.body; float w = contact.weight; float m = contact.mass; Vector2 n = contact.normal; Vector2 p = m_positionBuffer.data[a]; final float tempX = p.x - b.m_sweep.c.x; final float tempY = p.y - b.m_sweep.c.y; final Vector2 velA = m_velocityBuffer.data[a]; // getLinearVelocityFromWorldPointToOut, with -= velA float vx = -b.m_angularVelocity * tempY + b.m_linearVelocity.x - velA.x; float vy = b.m_angularVelocity * tempX + b.m_linearVelocity.y - velA.y; // done float vn = vx * n.x + vy * n.y; if (vn < 0) { final Vector2 f = tempVec; f.x = damping * w * m * vn * n.x; f.y = damping * w * m * vn * n.y; final float invMass = getParticleInvMass(); velA.x += invMass * f.x; velA.y += invMass * f.y; f.x = -f.x; f.y = -f.y; b.applyLinearImpulse(f, p, true); } } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vector2 n = contact.normal; final Vector2 velA = m_velocityBuffer.data[a]; final Vector2 velB = m_velocityBuffer.data[b]; final float vx = velB.x - velA.x; final float vy = velB.y - velA.y; float vn = vx * n.x + vy * n.y; if (vn < 0) { float fx = damping * w * vn * n.x; float fy = damping * w * vn * n.y; velA.x += fx; velA.y += fy; velB.x -= fx; velB.y -= fy; } } } public void solveWall(TimeStep step) { for (int i = 0; i < m_count; i++) { if ((m_flagsBuffer.data[i] & ParticleType.b2_wallParticle) != 0) { final Vector2 r = m_velocityBuffer.data[i]; r.x = 0.0f; r.y = 0.0f; } } } private final Vector2 tempVec2 = new Vector2(); private final Rot tempRot = new Rot(); private final Transform tempXf = new Transform(); private final Transform tempXf2 = new Transform(); void solveRigid(final TimeStep step) { for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { if ((group.m_groupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { group.updateStatistics(); Vector2 temp = tempVec; Vector2 cross = tempVec2; Rot rotation = tempRot; rotation.set(step.dt * group.m_angularVelocity); Rot.mulToOutUnsafe(rotation, group.m_center, cross); temp.set(group.m_linearVelocity).mulLocal(step.dt).addLocal(group.m_center).subLocal(cross); tempXf.p.set(temp); tempXf.q.set(rotation); Transform.mulToOut(tempXf, group.m_transform, group.m_transform); final Transform velocityTransform = tempXf2; velocityTransform.p.x = step.inv_dt * tempXf.p.x; velocityTransform.p.y = step.inv_dt * tempXf.p.y; velocityTransform.q.s = step.inv_dt * tempXf.q.s; velocityTransform.q.c = step.inv_dt * (tempXf.q.c - 1); for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { Transform.mulToOutUnsafe(velocityTransform, m_positionBuffer.data[i], m_velocityBuffer.data[i]); } } } } void solveElastic(final TimeStep step) { float elasticStrength = step.inv_dt * m_elasticStrength; for (int k = 0; k < m_triadCount; k++) { final Triad triad = m_triadBuffer[k]; if ((triad.flags & ParticleType.b2_elasticParticle) != 0) { int a = triad.indexA; int b = triad.indexB; int c = triad.indexC; final Vector2 oa = triad.pa; final Vector2 ob = triad.pb; final Vector2 oc = triad.pc; final Vector2 pa = m_positionBuffer.data[a]; final Vector2 pb = m_positionBuffer.data[b]; final Vector2 pc = m_positionBuffer.data[c]; final float px = 1f / 3 * (pa.x + pb.x + pc.x); final float py = 1f / 3 * (pa.y + pb.y + pc.y); float rs = Vector2.cross(oa, pa) + Vector2.cross(ob, pb) + Vector2.cross(oc, pc); float rc = Vector2.dot(oa, pa) + Vector2.dot(ob, pb) + Vector2.dot(oc, pc); float r2 = rs * rs + rc * rc; float invR = r2 == 0 ? Float.MAX_VALUE : MathUtils.sqrt(1f / r2); rs *= invR; rc *= invR; final float strength = elasticStrength * triad.strength; final float roax = rc * oa.x - rs * oa.y; final float roay = rs * oa.x + rc * oa.y; final float robx = rc * ob.x - rs * ob.y; final float roby = rs * ob.x + rc * ob.y; final float rocx = rc * oc.x - rs * oc.y; final float rocy = rs * oc.x + rc * oc.y; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; final Vector2 vc = m_velocityBuffer.data[c]; va.x += strength * (roax - (pa.x - px)); va.y += strength * (roay - (pa.y - py)); vb.x += strength * (robx - (pb.x - px)); vb.y += strength * (roby - (pb.y - py)); vc.x += strength * (rocx - (pc.x - px)); vc.y += strength * (rocy - (pc.y - py)); } } } void solveSpring(final TimeStep step) { float springStrength = step.inv_dt * m_springStrength; for (int k = 0; k < m_pairCount; k++) { final Pair pair = m_pairBuffer[k]; if ((pair.flags & ParticleType.b2_springParticle) != 0) { int a = pair.indexA; int b = pair.indexB; final Vector2 pa = m_positionBuffer.data[a]; final Vector2 pb = m_positionBuffer.data[b]; final float dx = pb.x - pa.x; final float dy = pb.y - pa.y; float r0 = pair.distance; float r1 = MathUtils.sqrt(dx * dx + dy * dy); if (r1 == 0) r1 = Float.MAX_VALUE; float strength = springStrength * pair.strength; final float fx = strength * (r0 - r1) / r1 * dx; final float fy = strength * (r0 - r1) / r1 * dy; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } void solveTensile(final TimeStep step) { m_accumulation2Buffer = requestParticleBuffer(Vector2.class, m_accumulation2Buffer); for (int i = 0; i < m_count; i++) { m_accumulationBuffer[i] = 0; m_accumulation2Buffer[i].setZero(); } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_tensileParticle) != 0) { int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vector2 n = contact.normal; m_accumulationBuffer[a] += w; m_accumulationBuffer[b] += w; final Vector2 a2A = m_accumulation2Buffer[a]; final Vector2 a2B = m_accumulation2Buffer[b]; final float inter = (1 - w) * w; a2A.x -= inter * n.x; a2A.y -= inter * n.y; a2B.x += inter * n.x; a2B.y += inter * n.y; } } float strengthA = m_surfaceTensionStrengthA * getCriticalVelocity(step); float strengthB = m_surfaceTensionStrengthB * getCriticalVelocity(step); for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_tensileParticle) != 0) { int a = contact.indexA; int b = contact.indexB; float w = contact.weight; Vector2 n = contact.normal; final Vector2 a2A = m_accumulation2Buffer[a]; final Vector2 a2B = m_accumulation2Buffer[b]; float h = m_accumulationBuffer[a] + m_accumulationBuffer[b]; final float sx = a2B.x - a2A.x; final float sy = a2B.y - a2A.y; float fn = (strengthA * (h - 2) + strengthB * (sx * n.x + sy * n.y)) * w; final float fx = fn * n.x; final float fy = fn * n.y; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } void solveViscous(final TimeStep step) { float viscousStrength = m_viscousStrength; for (int k = 0; k < m_bodyContactCount; k++) { final ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; if ((m_flagsBuffer.data[a] & ParticleType.b2_viscousParticle) != 0) { Body b = contact.body; float w = contact.weight; float m = contact.mass; Vector2 p = m_positionBuffer.data[a]; final Vector2 va = m_velocityBuffer.data[a]; final float tempX = p.x - b.m_sweep.c.x; final float tempY = p.y - b.m_sweep.c.y; final float vx = -b.m_angularVelocity * tempY + b.m_linearVelocity.x - va.x; final float vy = b.m_angularVelocity * tempX + b.m_linearVelocity.y - va.y; final Vector2 f = tempVec; final float pInvMass = getParticleInvMass(); f.x = viscousStrength * m * w * vx; f.y = viscousStrength * m * w * vy; va.x += pInvMass * f.x; va.y += pInvMass * f.y; f.x = -f.x; f.y = -f.y; b.applyLinearImpulse(f, p, true); } } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_viscousParticle) != 0) { int a = contact.indexA; int b = contact.indexB; float w = contact.weight; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; final float vx = vb.x - va.x; final float vy = vb.y - va.y; final float fx = viscousStrength * w * vx; final float fy = viscousStrength * w * vy; va.x += fx; va.y += fy; vb.x -= fx; vb.y -= fy; } } } void solvePowder(final TimeStep step) { float powderStrength = m_powderStrength * getCriticalVelocity(step); float minWeight = 1.0f - Settings.particleStride; for (int k = 0; k < m_bodyContactCount; k++) { final ParticleBodyContact contact = m_bodyContactBuffer[k]; int a = contact.index; if ((m_flagsBuffer.data[a] & ParticleType.b2_powderParticle) != 0) { float w = contact.weight; if (w > minWeight) { Body b = contact.body; float m = contact.mass; Vector2 p = m_positionBuffer.data[a]; Vector2 n = contact.normal; final Vector2 f = tempVec; final Vector2 va = m_velocityBuffer.data[a]; final float inter = powderStrength * m * (w - minWeight); final float pInvMass = getParticleInvMass(); f.x = inter * n.x; f.y = inter * n.y; va.x -= pInvMass * f.x; va.y -= pInvMass * f.y; b.applyLinearImpulse(f, p, true); } } } for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; if ((contact.flags & ParticleType.b2_powderParticle) != 0) { float w = contact.weight; if (w > minWeight) { int a = contact.indexA; int b = contact.indexB; Vector2 n = contact.normal; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; final float inter = powderStrength * (w - minWeight); final float fx = inter * n.x; final float fy = inter * n.y; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } } void solveSolid(final TimeStep step) { // applies extra repulsive force from solid particle groups m_depthBuffer = requestParticleBuffer(m_depthBuffer); float ejectionStrength = step.inv_dt * m_ejectionStrength; for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if (m_groupBuffer[a] != m_groupBuffer[b]) { float w = contact.weight; Vector2 n = contact.normal; float h = m_depthBuffer[a] + m_depthBuffer[b]; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; final float inter = ejectionStrength * h * w; final float fx = inter * n.x; final float fy = inter * n.y; va.x -= fx; va.y -= fy; vb.x += fx; vb.y += fy; } } } void solveColorMixing(final TimeStep step) { // mixes color between contacting particles m_colorBuffer.data = requestParticleBuffer(ParticleColor.class, m_colorBuffer.data); int colorMixing256 = (int) (256 * m_colorMixingStrength); for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; if ((m_flagsBuffer.data[a] & m_flagsBuffer.data[b] & ParticleType.b2_colorMixingParticle) != 0) { ParticleColor colorA = m_colorBuffer.data[a]; ParticleColor colorB = m_colorBuffer.data[b]; int dr = (colorMixing256 * (colorB.r - colorA.r)) >> 8; int dg = (colorMixing256 * (colorB.g - colorA.g)) >> 8; int db = (colorMixing256 * (colorB.b - colorA.b)) >> 8; int da = (colorMixing256 * (colorB.a - colorA.a)) >> 8; colorA.r += dr; colorA.g += dg; colorA.b += db; colorA.a += da; colorB.r -= dr; colorB.g -= dg; colorB.b -= db; colorB.a -= da; } } } void solveZombie() { // removes particles with zombie flag int newCount = 0; int[] newIndices = new int[m_count]; for (int i = 0; i < m_count; i++) { int flags = m_flagsBuffer.data[i]; if ((flags & ParticleType.b2_zombieParticle) != 0) { ParticleDestructionListener destructionListener = m_world.getParticleDestructionListener(); if ((flags & ParticleType.b2_destructionListener) != 0 && destructionListener != null) { destructionListener.sayGoodbye(i); } newIndices[i] = Settings.invalidParticleIndex; } else { newIndices[i] = newCount; if (i != newCount) { m_flagsBuffer.data[newCount] = m_flagsBuffer.data[i]; m_positionBuffer.data[newCount].set(m_positionBuffer.data[i]); m_velocityBuffer.data[newCount].set(m_velocityBuffer.data[i]); m_groupBuffer[newCount] = m_groupBuffer[i]; if (m_depthBuffer != null) { m_depthBuffer[newCount] = m_depthBuffer[i]; } if (m_colorBuffer.data != null) { m_colorBuffer.data[newCount].set(m_colorBuffer.data[i]); } if (m_userDataBuffer.data != null) { m_userDataBuffer.data[newCount] = m_userDataBuffer.data[i]; } } newCount++; } } // update proxies for (int k = 0; k < m_proxyCount; k++) { Proxy proxy = m_proxyBuffer[k]; proxy.index = newIndices[proxy.index]; } // Proxy lastProxy = std.remove_if( // m_proxyBuffer, m_proxyBuffer + m_proxyCount, // Test.IsProxyInvalid); // m_proxyCount = (int) (lastProxy - m_proxyBuffer); int j = m_proxyCount; for (int i = 0; i < j; i++) { if (Test.IsProxyInvalid(m_proxyBuffer[i])) { --j; Proxy temp = m_proxyBuffer[j]; m_proxyBuffer[j] = m_proxyBuffer[i]; m_proxyBuffer[i] = temp; --i; } } m_proxyCount = j; // update contacts for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; contact.indexA = newIndices[contact.indexA]; contact.indexB = newIndices[contact.indexB]; } // ParticleContact lastContact = std.remove_if( // m_contactBuffer, m_contactBuffer + m_contactCount, // Test.IsContactInvalid); // m_contactCount = (int) (lastContact - m_contactBuffer); j = m_contactCount; for (int i = 0; i < j; i++) { if (Test.IsContactInvalid(m_contactBuffer[i])) { --j; ParticleContact temp = m_contactBuffer[j]; m_contactBuffer[j] = m_contactBuffer[i]; m_contactBuffer[i] = temp; --i; } } m_contactCount = j; // update particle-body contacts for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; contact.index = newIndices[contact.index]; } // ParticleBodyContact lastBodyContact = std.remove_if( // m_bodyContactBuffer, m_bodyContactBuffer + m_bodyContactCount, // Test.IsBodyContactInvalid); // m_bodyContactCount = (int) (lastBodyContact - m_bodyContactBuffer); j = m_bodyContactCount; for (int i = 0; i < j; i++) { if (Test.IsBodyContactInvalid(m_bodyContactBuffer[i])) { --j; ParticleBodyContact temp = m_bodyContactBuffer[j]; m_bodyContactBuffer[j] = m_bodyContactBuffer[i]; m_bodyContactBuffer[i] = temp; --i; } } m_bodyContactCount = j; // update pairs for (int k = 0; k < m_pairCount; k++) { Pair pair = m_pairBuffer[k]; pair.indexA = newIndices[pair.indexA]; pair.indexB = newIndices[pair.indexB]; } // Pair lastPair = std.remove_if(m_pairBuffer, m_pairBuffer + m_pairCount, Test.IsPairInvalid); // m_pairCount = (int) (lastPair - m_pairBuffer); j = m_pairCount; for (int i = 0; i < j; i++) { if (Test.IsPairInvalid(m_pairBuffer[i])) { --j; Pair temp = m_pairBuffer[j]; m_pairBuffer[j] = m_pairBuffer[i]; m_pairBuffer[i] = temp; --i; } } m_pairCount = j; // update triads for (int k = 0; k < m_triadCount; k++) { Triad triad = m_triadBuffer[k]; triad.indexA = newIndices[triad.indexA]; triad.indexB = newIndices[triad.indexB]; triad.indexC = newIndices[triad.indexC]; } // Triad lastTriad = // std.remove_if(m_triadBuffer, m_triadBuffer + m_triadCount, Test.isTriadInvalid); // m_triadCount = (int) (lastTriad - m_triadBuffer); j = m_triadCount; for (int i = 0; i < j; i++) { if (Test.IsTriadInvalid(m_triadBuffer[i])) { --j; Triad temp = m_triadBuffer[j]; m_triadBuffer[j] = m_triadBuffer[i]; m_triadBuffer[i] = temp; --i; } } m_triadCount = j; // update groups for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { int firstIndex = newCount; int lastIndex = 0; boolean modified = false; for (int i = group.m_firstIndex; i < group.m_lastIndex; i++) { j = newIndices[i]; if (j >= 0) { firstIndex = MathUtils.min(firstIndex, j); lastIndex = MathUtils.max(lastIndex, j + 1); } else { modified = true; } } if (firstIndex < lastIndex) { group.m_firstIndex = firstIndex; group.m_lastIndex = lastIndex; if (modified) { if ((group.m_groupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { group.m_toBeSplit = true; } } } else { group.m_firstIndex = 0; group.m_lastIndex = 0; if (group.m_destroyAutomatically) { group.m_toBeDestroyed = true; } } } // update particle count m_count = newCount; // m_world.m_stackAllocator.Free(newIndices); // destroy bodies with no particles for (ParticleGroup group = m_groupList; group != null;) { ParticleGroup next = group.getNext(); if (group.m_toBeDestroyed) { destroyParticleGroup(group); } else if (group.m_toBeSplit) { // TODO: split the group } group = next; } } private static class NewIndices { int start, mid, end; final int getIndex(final int i) { if (i < start) { return i; } else if (i < mid) { return i + end - mid; } else if (i < end) { return i + start - mid; } else { return i; } } } private final NewIndices newIndices = new NewIndices(); void RotateBuffer(int start, int mid, int end) { // move the particles assigned to the given group toward the end of array if (start == mid || mid == end) { return; } newIndices.start = start; newIndices.mid = mid; newIndices.end = end; BufferUtils.rotate(m_flagsBuffer.data, start, mid, end); BufferUtils.rotate(m_positionBuffer.data, start, mid, end); BufferUtils.rotate(m_velocityBuffer.data, start, mid, end); BufferUtils.rotate(m_groupBuffer, start, mid, end); if (m_depthBuffer != null) { BufferUtils.rotate(m_depthBuffer, start, mid, end); } if (m_colorBuffer.data != null) { BufferUtils.rotate(m_colorBuffer.data, start, mid, end); } if (m_userDataBuffer.data != null) { BufferUtils.rotate(m_userDataBuffer.data, start, mid, end); } // update proxies for (int k = 0; k < m_proxyCount; k++) { Proxy proxy = m_proxyBuffer[k]; proxy.index = newIndices.getIndex(proxy.index); } // update contacts for (int k = 0; k < m_contactCount; k++) { ParticleContact contact = m_contactBuffer[k]; contact.indexA = newIndices.getIndex(contact.indexA); contact.indexB = newIndices.getIndex(contact.indexB); } // update particle-body contacts for (int k = 0; k < m_bodyContactCount; k++) { ParticleBodyContact contact = m_bodyContactBuffer[k]; contact.index = newIndices.getIndex(contact.index); } // update pairs for (int k = 0; k < m_pairCount; k++) { Pair pair = m_pairBuffer[k]; pair.indexA = newIndices.getIndex(pair.indexA); pair.indexB = newIndices.getIndex(pair.indexB); } // update triads for (int k = 0; k < m_triadCount; k++) { Triad triad = m_triadBuffer[k]; triad.indexA = newIndices.getIndex(triad.indexA); triad.indexB = newIndices.getIndex(triad.indexB); triad.indexC = newIndices.getIndex(triad.indexC); } // update groups for (ParticleGroup group = m_groupList; group != null; group = group.getNext()) { group.m_firstIndex = newIndices.getIndex(group.m_firstIndex); group.m_lastIndex = newIndices.getIndex(group.m_lastIndex - 1) + 1; } } public void setParticleRadius(float radius) { m_particleDiameter = 2 * radius; m_squaredDiameter = m_particleDiameter * m_particleDiameter; m_inverseDiameter = 1 / m_particleDiameter; } public void setParticleDensity(float density) { m_density = density; m_inverseDensity = 1 / m_density; } public float getParticleDensity() { return m_density; } public void setParticleGravityScale(float gravityScale) { m_gravityScale = gravityScale; } public float getParticleGravityScale() { return m_gravityScale; } public void setParticleDamping(float damping) { m_dampingStrength = damping; } public float getParticleDamping() { return m_dampingStrength; } public float getParticleRadius() { return m_particleDiameter / 2; } float getCriticalVelocity(final TimeStep step) { return m_particleDiameter * step.inv_dt; } float getCriticalVelocitySquared(final TimeStep step) { float velocity = getCriticalVelocity(step); return velocity * velocity; } float getCriticalPressure(final TimeStep step) { return m_density * getCriticalVelocitySquared(step); } float getParticleStride() { return Settings.particleStride * m_particleDiameter; } float getParticleMass() { float stride = getParticleStride(); return m_density * stride * stride; } float getParticleInvMass() { return 1.777777f * m_inverseDensity * m_inverseDiameter * m_inverseDiameter; } public int[] getParticleFlagsBuffer() { return m_flagsBuffer.data; } public Vector2[] getParticlePositionBuffer() { return m_positionBuffer.data; } public Vector2[] getParticleVelocityBuffer() { return m_velocityBuffer.data; } public ParticleColor[] getParticleColorBuffer() { m_colorBuffer.data = requestParticleBuffer(ParticleColor.class, m_colorBuffer.data); return m_colorBuffer.data; } public Object[] getParticleUserDataBuffer() { m_userDataBuffer.data = requestParticleBuffer(Object.class, m_userDataBuffer.data); return m_userDataBuffer.data; } public int getParticleMaxCount() { return m_maxCount; } public void setParticleMaxCount(int count) { assert (m_count <= count); m_maxCount = count; } void setParticleBuffer(ParticleBufferInt buffer, int[] newData, int newCapacity) { assert ((newData != null && newCapacity != 0) || (newData == null && newCapacity == 0)); if (buffer.userSuppliedCapacity != 0) { // m_world.m_blockAllocator.Free(buffer.data, sizeof(T) * m_internalAllocatedCapacity); } buffer.data = newData; buffer.userSuppliedCapacity = newCapacity; } <T> void setParticleBuffer(ParticleBuffer<T> buffer, T[] newData, int newCapacity) { assert ((newData != null && newCapacity != 0) || (newData == null && newCapacity == 0)); if (buffer.userSuppliedCapacity != 0) { // m_world.m_blockAllocator.Free(buffer.data, sizeof(T) * m_internalAllocatedCapacity); } buffer.data = newData; buffer.userSuppliedCapacity = newCapacity; } public void setParticleFlagsBuffer(int[] buffer, int capacity) { setParticleBuffer(m_flagsBuffer, buffer, capacity); } public void setParticlePositionBuffer(Vector2[] buffer, int capacity) { setParticleBuffer(m_positionBuffer, buffer, capacity); } public void setParticleVelocityBuffer(Vector2[] buffer, int capacity) { setParticleBuffer(m_velocityBuffer, buffer, capacity); } public void setParticleColorBuffer(ParticleColor[] buffer, int capacity) { setParticleBuffer(m_colorBuffer, buffer, capacity); } public ParticleGroup[] getParticleGroupBuffer() { return m_groupBuffer; } public int getParticleGroupCount() { return m_groupCount; } public ParticleGroup[] getParticleGroupList() { return m_groupBuffer; } public int getParticleCount() { return m_count; } public void setParticleUserDataBuffer(Object[] buffer, int capacity) { setParticleBuffer(m_userDataBuffer, buffer, capacity); } private static final int lowerBound(Proxy[] ray, int length, long tag) { int left = 0; int step, curr; while (length > 0) { step = length / 2; curr = left + step; if (ray[curr].tag < tag) { left = curr + 1; length -= step + 1; } else { length = step; } } return left; } private static final int upperBound(Proxy[] ray, int length, long tag) { int left = 0; int step, curr; while (length > 0) { step = length / 2; curr = left + step; if (ray[curr].tag <= tag) { left = curr + 1; length -= step + 1; } else { length = step; } } return left; } public void queryAABB(ParticleQueryCallback callback, final AABB aabb) { if (m_proxyCount == 0) { return; } final float lowerBoundX = aabb.lowerBound.x; final float lowerBoundY = aabb.lowerBound.y; final float upperBoundX = aabb.upperBound.x; final float upperBoundY = aabb.upperBound.y; int firstProxy = lowerBound(m_proxyBuffer, m_proxyCount, computeTag(m_inverseDiameter * lowerBoundX, m_inverseDiameter * lowerBoundY)); int lastProxy = upperBound(m_proxyBuffer, m_proxyCount, computeTag(m_inverseDiameter * upperBoundX, m_inverseDiameter * upperBoundY)); for (int proxy = firstProxy; proxy < lastProxy; ++proxy) { int i = m_proxyBuffer[proxy].index; final Vector2 p = m_positionBuffer.data[i]; if (lowerBoundX < p.x && p.x < upperBoundX && lowerBoundY < p.y && p.y < upperBoundY) { if (!callback.reportParticle(i)) { break; } } } } /** * @param callback * @param point1 * @param point2 */ public void raycast(ParticleRaycastCallback callback, final Vector2 point1, final Vector2 point2) { if (m_proxyCount == 0) { return; } int firstProxy = lowerBound( m_proxyBuffer, m_proxyCount, computeTag(m_inverseDiameter * MathUtils.min(point1.x, point2.x) - 1, m_inverseDiameter * MathUtils.min(point1.y, point2.y) - 1)); int lastProxy = upperBound( m_proxyBuffer, m_proxyCount, computeTag(m_inverseDiameter * MathUtils.max(point1.x, point2.x) + 1, m_inverseDiameter * MathUtils.max(point1.y, point2.y) + 1)); float fraction = 1; // solving the following equation: // ((1-t)*point1+t*point2-position)^2=diameter^2 // where t is a potential fraction final float vx = point2.x - point1.x; final float vy = point2.y - point1.y; float v2 = vx * vx + vy * vy; if (v2 == 0) v2 = Float.MAX_VALUE; for (int proxy = firstProxy; proxy < lastProxy; ++proxy) { int i = m_proxyBuffer[proxy].index; final Vector2 posI = m_positionBuffer.data[i]; final float px = point1.x - posI.x; final float py = point1.y - posI.y; float pv = px * vx + py * vy; float p2 = px * px + py * py; float determinant = pv * pv - v2 * (p2 - m_squaredDiameter); if (determinant >= 0) { float sqrtDeterminant = MathUtils.sqrt(determinant); // find a solution between 0 and fraction float t = (-pv - sqrtDeterminant) / v2; if (t > fraction) { continue; } if (t < 0) { t = (-pv + sqrtDeterminant) / v2; if (t < 0 || t > fraction) { continue; } } final Vector2 n = tempVec; tempVec.x = px + t * vx; tempVec.y = py + t * vy; n.normalize(); final Vector2 point = tempVec2; point.x = point1.x + t * vx; point.y = point1.y + t * vy; float f = callback.reportParticle(i, point, n, t); fraction = MathUtils.min(fraction, f); if (fraction <= 0) { break; } } } } public float computeParticleCollisionEnergy() { float sum_v2 = 0; for (int k = 0; k < m_contactCount; k++) { final ParticleContact contact = m_contactBuffer[k]; int a = contact.indexA; int b = contact.indexB; Vector2 n = contact.normal; final Vector2 va = m_velocityBuffer.data[a]; final Vector2 vb = m_velocityBuffer.data[b]; final float vx = vb.x - va.x; final float vy = vb.y - va.y; float vn = vx * n.x + vy * n.y; if (vn < 0) { sum_v2 += vn * vn; } } return 0.5f * getParticleMass() * sum_v2; } // reallocate a buffer static <T> T[] reallocateBuffer(ParticleBuffer<T> buffer, int oldCapacity, int newCapacity, boolean deferred) { assert (newCapacity > oldCapacity); return BufferUtils.reallocateBuffer(buffer.dataClass, buffer.data, buffer.userSuppliedCapacity, oldCapacity, newCapacity, deferred); } static int[] reallocateBuffer(ParticleBufferInt buffer, int oldCapacity, int newCapacity, boolean deferred) { assert (newCapacity > oldCapacity); return BufferUtils.reallocateBuffer(buffer.data, buffer.userSuppliedCapacity, oldCapacity, newCapacity, deferred); } @SuppressWarnings("unchecked") <T> T[] requestParticleBuffer(Class<T> klass, T[] buffer) { if (buffer == null) { buffer = (T[]) Array.newInstance(klass, m_internalAllocatedCapacity); for (int i = 0; i < m_internalAllocatedCapacity; i++) { try { buffer[i] = klass.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } } return buffer; } float[] requestParticleBuffer(float[] buffer) { if (buffer == null) { buffer = new float[m_internalAllocatedCapacity]; } return buffer; } public static class ParticleBuffer<T> { public T[] data; final Class<T> dataClass; int userSuppliedCapacity; public ParticleBuffer(Class<T> dataClass) { this.dataClass = dataClass; } } static class ParticleBufferInt { int[] data; int userSuppliedCapacity; } /** Used for detecting particle contacts */ public static class Proxy implements Comparable<Proxy> { int index; long tag; @Override public int compareTo(Proxy o) { return (tag - o.tag) < 0 ? -1 : (o.tag == tag ? 0 : 1); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Proxy other = (Proxy) obj; if (tag != other.tag) return false; return true; } } /** Connection between two particles */ public static class Pair { int indexA, indexB; int flags; float strength; float distance; } /** Connection between three particles */ public static class Triad { int indexA, indexB, indexC; int flags; float strength; final Vector2 pa = new Vector2(), pb = new Vector2(), pc = new Vector2(); float ka, kb, kc, s; } // Callback used with VoronoiDiagram. static class CreateParticleGroupCallback implements VoronoiDiagramCallback { public void callback(int a, int b, int c) { final Vector2 pa = system.m_positionBuffer.data[a]; final Vector2 pb = system.m_positionBuffer.data[b]; final Vector2 pc = system.m_positionBuffer.data[c]; final float dabx = pa.x - pb.x; final float daby = pa.y - pb.y; final float dbcx = pb.x - pc.x; final float dbcy = pb.y - pc.y; final float dcax = pc.x - pa.x; final float dcay = pc.y - pa.y; float maxDistanceSquared = Settings.maxTriadDistanceSquared * system.m_squaredDiameter; if (dabx * dabx + daby * daby < maxDistanceSquared && dbcx * dbcx + dbcy * dbcy < maxDistanceSquared && dcax * dcax + dcay * dcay < maxDistanceSquared) { if (system.m_triadCount >= system.m_triadCapacity) { int oldCapacity = system.m_triadCapacity; int newCapacity = system.m_triadCount != 0 ? 2 * system.m_triadCount : Settings.minParticleBufferCapacity; system.m_triadBuffer = BufferUtils.reallocateBuffer(Triad.class, system.m_triadBuffer, oldCapacity, newCapacity); system.m_triadCapacity = newCapacity; } Triad triad = system.m_triadBuffer[system.m_triadCount]; triad.indexA = a; triad.indexB = b; triad.indexC = c; triad.flags = system.m_flagsBuffer.data[a] | system.m_flagsBuffer.data[b] | system.m_flagsBuffer.data[c]; triad.strength = def.strength; final float midPointx = (float) 1 / 3 * (pa.x + pb.x + pc.x); final float midPointy = (float) 1 / 3 * (pa.y + pb.y + pc.y); triad.pa.x = pa.x - midPointx; triad.pa.y = pa.y - midPointy; triad.pb.x = pb.x - midPointx; triad.pb.y = pb.y - midPointy; triad.pc.x = pc.x - midPointx; triad.pc.y = pc.y - midPointy; triad.ka = -(dcax * dabx + dcay * daby); triad.kb = -(dabx * dbcx + daby * dbcy); triad.kc = -(dbcx * dcax + dbcy * dcay); triad.s = Vector2.cross(pa, pb) + Vector2.cross(pb, pc) + Vector2.cross(pc, pa); system.m_triadCount++; } } ParticleSystem system; ParticleGroupDef def; // pointer int firstIndex; } // Callback used with VoronoiDiagram. static class JoinParticleGroupsCallback implements VoronoiDiagramCallback { public void callback(int a, int b, int c) { // Create a triad if it will contain particles from both groups. int countA = ((a < groupB.m_firstIndex) ? 1 : 0) + ((b < groupB.m_firstIndex) ? 1 : 0) + ((c < groupB.m_firstIndex) ? 1 : 0); if (countA > 0 && countA < 3) { int af = system.m_flagsBuffer.data[a]; int bf = system.m_flagsBuffer.data[b]; int cf = system.m_flagsBuffer.data[c]; if ((af & bf & cf & k_triadFlags) != 0) { final Vector2 pa = system.m_positionBuffer.data[a]; final Vector2 pb = system.m_positionBuffer.data[b]; final Vector2 pc = system.m_positionBuffer.data[c]; final float dabx = pa.x - pb.x; final float daby = pa.y - pb.y; final float dbcx = pb.x - pc.x; final float dbcy = pb.y - pc.y; final float dcax = pc.x - pa.x; final float dcay = pc.y - pa.y; float maxDistanceSquared = Settings.maxTriadDistanceSquared * system.m_squaredDiameter; if (dabx * dabx + daby * daby < maxDistanceSquared && dbcx * dbcx + dbcy * dbcy < maxDistanceSquared && dcax * dcax + dcay * dcay < maxDistanceSquared) { if (system.m_triadCount >= system.m_triadCapacity) { int oldCapacity = system.m_triadCapacity; int newCapacity = system.m_triadCount != 0 ? 2 * system.m_triadCount : Settings.minParticleBufferCapacity; system.m_triadBuffer = BufferUtils.reallocateBuffer(Triad.class, system.m_triadBuffer, oldCapacity, newCapacity); system.m_triadCapacity = newCapacity; } Triad triad = system.m_triadBuffer[system.m_triadCount]; triad.indexA = a; triad.indexB = b; triad.indexC = c; triad.flags = af | bf | cf; triad.strength = MathUtils.min(groupA.m_strength, groupB.m_strength); final float midPointx = (float) 1 / 3 * (pa.x + pb.x + pc.x); final float midPointy = (float) 1 / 3 * (pa.y + pb.y + pc.y); triad.pa.x = pa.x - midPointx; triad.pa.y = pa.y - midPointy; triad.pb.x = pb.x - midPointx; triad.pb.y = pb.y - midPointy; triad.pc.x = pc.x - midPointx; triad.pc.y = pc.y - midPointy; triad.ka = -(dcax * dabx + dcay * daby); triad.kb = -(dabx * dbcx + daby * dbcy); triad.kc = -(dbcx * dcax + dbcy * dcay); triad.s = Vector2.cross(pa, pb) + Vector2.cross(pb, pc) + Vector2.cross(pc, pa); system.m_triadCount++; } } } } ParticleSystem system; ParticleGroup groupA; ParticleGroup groupB; }; static class DestroyParticlesInShapeCallback implements ParticleQueryCallback { ParticleSystem system; Shape shape; Transform xf; boolean callDestructionListener; int destroyed; public DestroyParticlesInShapeCallback() { // TODO Auto-generated constructor stub } public void init(ParticleSystem system, Shape shape, Transform xf, boolean callDestructionListener) { this.system = system; this.shape = shape; this.xf = xf; this.destroyed = 0; this.callDestructionListener = callDestructionListener; } @Override public boolean reportParticle(int index) { assert (index >= 0 && index < system.m_count); if (shape.testPoint(xf, system.m_positionBuffer.data[index])) { system.destroyParticle(index, callDestructionListener); destroyed++; } return true; } } static class UpdateBodyContactsCallback implements QueryCallback { ParticleSystem system; private final Vector2 tempVec = new Vector2(); @Override public boolean reportFixture(Fixture fixture) { if (fixture.isSensor()) { return true; } final Shape shape = fixture.getShape(); Body b = fixture.getBody(); Vector2 bp = b.getWorldCenter(); float bm = b.getMass(); float bI = b.getInertia() - bm * b.getLocalCenter().lengthSquared(); float invBm = bm > 0 ? 1 / bm : 0; float invBI = bI > 0 ? 1 / bI : 0; int childCount = shape.getChildCount(); for (int childIndex = 0; childIndex < childCount; childIndex++) { AABB aabb = fixture.getAABB(childIndex); final float aabblowerBoundx = aabb.lowerBound.x - system.m_particleDiameter; final float aabblowerBoundy = aabb.lowerBound.y - system.m_particleDiameter; final float aabbupperBoundx = aabb.upperBound.x + system.m_particleDiameter; final float aabbupperBoundy = aabb.upperBound.y + system.m_particleDiameter; int firstProxy = lowerBound( system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabblowerBoundx, system.m_inverseDiameter * aabblowerBoundy)); int lastProxy = upperBound( system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabbupperBoundx, system.m_inverseDiameter * aabbupperBoundy)); for (int proxy = firstProxy; proxy != lastProxy; ++proxy) { int a = system.m_proxyBuffer[proxy].index; Vector2 ap = system.m_positionBuffer.data[a]; if (aabblowerBoundx <= ap.x && ap.x <= aabbupperBoundx && aabblowerBoundy <= ap.y && ap.y <= aabbupperBoundy) { float d; final Vector2 n = tempVec; d = fixture.computeDistance(ap, childIndex, n); if (d < system.m_particleDiameter) { float invAm = (system.m_flagsBuffer.data[a] & ParticleType.b2_wallParticle) != 0 ? 0 : system .getParticleInvMass(); final float rpx = ap.x - bp.x; final float rpy = ap.y - bp.y; float rpn = rpx * n.y - rpy * n.x; if (system.m_bodyContactCount >= system.m_bodyContactCapacity) { int oldCapacity = system.m_bodyContactCapacity; int newCapacity = system.m_bodyContactCount != 0 ? 2 * system.m_bodyContactCount : Settings.minParticleBufferCapacity; system.m_bodyContactBuffer = BufferUtils.reallocateBuffer(ParticleBodyContact.class, system.m_bodyContactBuffer, oldCapacity, newCapacity); system.m_bodyContactCapacity = newCapacity; } ParticleBodyContact contact = system.m_bodyContactBuffer[system.m_bodyContactCount]; contact.index = a; contact.body = b; contact.weight = 1 - d * system.m_inverseDiameter; contact.normal.x = -n.x; contact.normal.y = -n.y; contact.mass = 1 / (invAm + invBm + invBI * rpn * rpn); system.m_bodyContactCount++; } } } } return true; } } static class SolveCollisionCallback implements QueryCallback { ParticleSystem system; TimeStep step; private final RayCastInput input = new RayCastInput(); private final RayCastOutput output = new RayCastOutput(); private final Vector2 tempVec = new Vector2(); private final Vector2 tempVec2 = new Vector2(); @Override public boolean reportFixture(Fixture fixture) { if (fixture.isSensor()) { return true; } final Shape shape = fixture.getShape(); Body body = fixture.getBody(); int childCount = shape.getChildCount(); for (int childIndex = 0; childIndex < childCount; childIndex++) { AABB aabb = fixture.getAABB(childIndex); final float aabblowerBoundx = aabb.lowerBound.x - system.m_particleDiameter; final float aabblowerBoundy = aabb.lowerBound.y - system.m_particleDiameter; final float aabbupperBoundx = aabb.upperBound.x + system.m_particleDiameter; final float aabbupperBoundy = aabb.upperBound.y + system.m_particleDiameter; int firstProxy = lowerBound( system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabblowerBoundx, system.m_inverseDiameter * aabblowerBoundy)); int lastProxy = upperBound( system.m_proxyBuffer, system.m_proxyCount, computeTag(system.m_inverseDiameter * aabbupperBoundx, system.m_inverseDiameter * aabbupperBoundy)); for (int proxy = firstProxy; proxy != lastProxy; ++proxy) { int a = system.m_proxyBuffer[proxy].index; Vector2 ap = system.m_positionBuffer.data[a]; if (aabblowerBoundx <= ap.x && ap.x <= aabbupperBoundx && aabblowerBoundy <= ap.y && ap.y <= aabbupperBoundy) { Vector2 av = system.m_velocityBuffer.data[a]; final Vector2 temp = tempVec; Transform.mulTransToOutUnsafe(body.m_xf0, ap, temp); Transform.mulToOutUnsafe(body.m_xf, temp, input.p1); input.p2.x = ap.x + step.dt * av.x; input.p2.y = ap.y + step.dt * av.y; input.maxFraction = 1; if (fixture.raycast(output, input, childIndex)) { final Vector2 p = tempVec; p.x = (1 - output.fraction) * input.p1.x + output.fraction * input.p2.x + Settings.linearSlop * output.normal.x; p.y = (1 - output.fraction) * input.p1.y + output.fraction * input.p2.y + Settings.linearSlop * output.normal.y; final float vx = step.inv_dt * (p.x - ap.x); final float vy = step.inv_dt * (p.y - ap.y); av.x = vx; av.y = vy; final float particleMass = system.getParticleMass(); final float ax = particleMass * (av.x - vx); final float ay = particleMass * (av.y - vy); Vector2 b = output.normal; final float fdn = ax * b.x + ay * b.y; final Vector2 f = tempVec2; f.x = fdn * b.x; f.y = fdn * b.y; body.applyLinearImpulse(f, p, true); } } } } return true; } } static class Test { static boolean IsProxyInvalid(final Proxy proxy) { return proxy.index < 0; } static boolean IsContactInvalid(final ParticleContact contact) { return contact.indexA < 0 || contact.indexB < 0; } static boolean IsBodyContactInvalid(final ParticleBodyContact contact) { return contact.index < 0; } static boolean IsPairInvalid(final Pair pair) { return pair.indexA < 0 || pair.indexB < 0; } static boolean IsTriadInvalid(final Triad triad) { return triad.indexA < 0 || triad.indexB < 0 || triad.indexC < 0; } }; }
unlicense
billyninja/pgtools
rnd/table.go
12
package rnd
unlicense
forabi/hollowverse
server/src/redux.store.ts
134
import { createStore } from 'redux'; import { reducer } from 'client/src/store/reducers'; export const store = createStore(reducer);
unlicense
fczbkk/jasmine-helpers
helpers/simulate-event.js
691
var simulateEvent; simulateEvent = function(obj, type) { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(type, true, true); } else if (document.createEventObject) { event = document.createEventObject(); event.eventType = type; event.eventName = type; } if (obj.dispatchEvent) { return obj.dispatchEvent(event); } else if (obj.fireEvent && (typeof htmlEvents !== "undefined" && htmlEvents !== null ? htmlEvents["on" + type] : void 0)) { return obj.fireEvent("on" + type, event); } else if (obj[type]) { return obj[type](); } else if (obj["on" + type]) { return obj["on" + type](); } };
unlicense
zschuessler/DeltaE
src/dE94.js
3191
'use strict'; /** * @class dE94 * @classdesc * The CIE94 algorithm: an iteration of the CIE76 algorithm. * http://en.wikipedia.org/wiki/Color_difference#CIE94 * @constructs dE94 * @memberOf DeltaE * @property {object} x1 The LAB color configuration object. * @property {number} x1.L The lightness value, on scale of 0-100. * @property {number} x1.A The chroma value, on scale of -128 to 128. * @property {number} x1.B The hue value, on scale of -128 to 128. * @property {object} x2 The LAB color configuration object. * @property {number} x2.L The lightness value, on scale of 0-100. * @property {number} x2.A The chroma value, on scale of -128 to 128. * @property {number} x2.B The hue value, on scale of -128 to 128. * @property {object} weights The weights configuration object. * @property {number} weights.lightness A weight factor to apply to lightness. * @property {number} weights.chroma A weight factor to apply to chroma. * @property {number} weights.hue A weight factor to apply to hue. * @example * var deltaE = new dE94( * {L:50, A:50, B:50}, * {L:100, A:50, B:50}, * ); * console.log(deltaE.getDeltaE()); */ function dE94(x1, x2, weights) { this.x1 = x1; this.x2 = x2; this.weights = weights || {}; this.weights.lightness = this.weights.lightness || 1; this.weights.chroma = this.weights.chroma || 1; this.weights.hue = this.weights.hue || 1; if (1 === this.weights.lightness) { this.weights.K1 = 0.045; this.weights.K2 = 0.015; } else { this.weights.K1 = 0.048; this.weights.K2 = 0.014; } } /** * Returns the dE94 value. * @method * @returns {number} */ dE94.prototype.getDeltaE = function() { var x1 = this.x1; var x2 = this.x2; var sqrt = Math.sqrt; var pow = Math.pow; return sqrt( pow(this.calculateL(x1, x2), 2) + pow(this.calculateA(x1, x2), 2) + pow(this.calculateB(x1, x2), 2) ); }; /** * Calculates the lightness value. * @method * @returns {number} */ dE94.prototype.calculateL = function(x1, x2) { return (x1.L - x2.L) / this.weights.lightness; }; /** * Calculates the chroma value. * @method * @returns {number} */ dE94.prototype.calculateA = function(x1, x2) { var sqrt = Math.sqrt; var pow = Math.pow; //top var c1 = sqrt(pow(x1.A, 2) + pow(x1.B, 2)); var c2 = sqrt(pow(x2.A, 2) + pow(x2.B, 2)); var cab = c1 - c2; // bottom var sc = 1 + (this.weights.K1 * c1); return cab / (this.weights.chroma * sc); }; /** * Calculates the hue value. * @method * @returns {number} */ dE94.prototype.calculateB = function(x1, x2) { var sqrt = Math.sqrt; var pow = Math.pow; // cab var c1 = sqrt(pow(x1.A, 2) + pow(x1.B, 2)); var c2 = sqrt(pow(x2.A, 2) + pow(x2.B, 2)); var cab = c1 - c2; // top var a = x1.A - x2.A; var b = x1.B - x2.B; var hab = sqrt( pow(a, 2) + pow(b, 2) - pow(cab, 2) ) || 0; // bottom var c1 = sqrt(pow(x1.A, 2) + pow(x1.B, 2)); var sh = 1 + (this.weights.K2 * c1); return hab / sh; }; module.exports = dE94;
unlicense
Eric-Guo/product_hunt
config/environments/production.rb
5379
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass config.assets.js_compressor = :terser # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "product_hunt_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
unlicense
marquee/static-sdk
entry/__tests__/renderEntryContent-test.js
1001
const React = require('react') const renderEntryContent = require('../renderEntryContent') const renderer = require('react-test-renderer') const SAMPLE_ENTRY = require('./SAMPLE_ENTRY.json') describe('renderEntryContent', () => { it('renders', () => { const component = renderer.create( React.createElement('div', null, ...renderEntryContent(SAMPLE_ENTRY.content)) ) expect( component.toJSON() ).toMatchSnapshot() }) it('renders plain', () => { const component = renderer.create( React.createElement('div', null, ...renderEntryContent(SAMPLE_ENTRY.content, { plain: true })) ) expect( component.toJSON() ).toMatchSnapshot() }) it('renders plain', () => { const component = renderer.create( React.createElement('div', null, ...renderEntryContent([])) ) expect( component.toJSON() ).toMatchSnapshot() }) })
unlicense
DT9/lonelyTwitter
src/ca/ualberta/cs/lonelytwitter/Followers.java
287
package ca.ualberta.cs.lonelytwitter; import java.util.ArrayList; public interface Followers { static ArrayList <User> followers = new ArrayList <User>(); public String getNames(); public int getNumberUsers(); public ArrayList<User> getUsers(); public void setUsers(User user); }
unlicense
dalealleshouse/RelativeStrengthCalculator
RelativeStrengthCalculator.Api/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs
816
// -------------------------------- // <copyright file="ModelNameAttribute.cs"> // Copyright (c) 2015 All rights reserved. // </copyright> // <author>dallesho</author> // <date>05/30/2015</date> // --------------------------------- #pragma warning disable 1591 namespace RelativeStrengthCalculator.Api.Areas.HelpPage.ModelDescriptions { using System; /// <summary> /// Use this attribute to change the name of the <see cref="ModelDescription"/> generated for a type. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false)] public sealed class ModelNameAttribute : Attribute { public ModelNameAttribute(string name) { this.Name = name; } public string Name { get; } } }
unlicense
GHJGHJJHG/CTYJava
Roman Numerals/src/RomanNumeral.java
1985
public class RomanNumeral { public final static int M = 1000; public final static int D = 500; public final static int C = 100; public final static int L = 50; public final static int X = 10; public final static int V = 5; public final static int I = 1; private int value; public RomanNumeral() { value = 0; } public RomanNumeral(int input) { value = input; } public RomanNumeral(String input) { value = toInt(input); } public int toInt() { return value; } public static int toInt(String input) { int result = 0; for(char ch : input.toCharArray()) { if (ch == 'M') result += M; else if (ch == 'D') result += D; else if (ch == 'C') result += C; else if (ch == 'L') result += L; else if (ch == 'X') result += X; else if (ch == 'V') result += V; else if (ch == 'I') result += I; } return result; } public String toString() { return ("IRN String: " + ((value != 0) ? toString(value) : "Zero")+ "\tInt Value: " + Integer.toString(value)); } public static String toString(int input) { String result = ""; int in = input; while (in >= M) { in -= M; result += 'M'; } while (in >= D) { in -= D; result += 'D'; } while (in >= C) { in -= C; result += 'C'; } while (in >= L) { in -= L; result += 'L'; } while (in >= X) { in -= X; result += 'X'; } while (in >= V) { in -= V; result += 'V'; } while (in >= I) { in -= I; result += 'I'; } return result; } public RomanNumeral add(RomanNumeral other) { return new RomanNumeral(this.value + other.toInt()); } public RomanNumeral subtract(RomanNumeral other) { return new RomanNumeral(this.value - other.toInt()); } public RomanNumeral multiply(RomanNumeral other) { return new RomanNumeral(this.value * other.toInt()); } public RomanNumeral divide(RomanNumeral other) { return new RomanNumeral(this.value / other.toInt()); } }
unlicense
clilystudio/NetBook
allsrc/android/support/v7/appcompat/R$color.java
4678
package android.support.v7.appcompat; public final class R$color { public static final int abc_background_cache_hint_selector_material_dark = 2131427554; public static final int abc_background_cache_hint_selector_material_light = 2131427555; public static final int abc_input_method_navigation_guard = 2131427329; public static final int abc_primary_text_disable_only_material_dark = 2131427556; public static final int abc_primary_text_disable_only_material_light = 2131427557; public static final int abc_primary_text_material_dark = 2131427558; public static final int abc_primary_text_material_light = 2131427559; public static final int abc_search_url_text = 2131427560; public static final int abc_search_url_text_normal = 2131427330; public static final int abc_search_url_text_pressed = 2131427331; public static final int abc_search_url_text_selected = 2131427332; public static final int abc_secondary_text_material_dark = 2131427561; public static final int abc_secondary_text_material_light = 2131427562; public static final int accent_material_dark = 2131427333; public static final int accent_material_light = 2131427334; public static final int background_floating_material_dark = 2131427341; public static final int background_floating_material_light = 2131427342; public static final int background_material_dark = 2131427343; public static final int background_material_light = 2131427344; public static final int bright_foreground_disabled_material_dark = 2131427369; public static final int bright_foreground_disabled_material_light = 2131427370; public static final int bright_foreground_inverse_material_dark = 2131427371; public static final int bright_foreground_inverse_material_light = 2131427372; public static final int bright_foreground_material_dark = 2131427373; public static final int bright_foreground_material_light = 2131427374; public static final int button_material_dark = 2131427380; public static final int button_material_light = 2131427381; public static final int dim_foreground_disabled_material_dark = 2131427400; public static final int dim_foreground_disabled_material_light = 2131427401; public static final int dim_foreground_material_dark = 2131427402; public static final int dim_foreground_material_light = 2131427403; public static final int highlighted_text_material_dark = 2131427418; public static final int highlighted_text_material_light = 2131427419; public static final int hint_foreground_material_dark = 2131427420; public static final int hint_foreground_material_light = 2131427421; public static final int link_text_material_dark = 2131427450; public static final int link_text_material_light = 2131427451; public static final int material_blue_grey_800 = 2131427457; public static final int material_blue_grey_900 = 2131427458; public static final int material_blue_grey_950 = 2131427459; public static final int material_deep_teal_200 = 2131427460; public static final int material_deep_teal_500 = 2131427461; public static final int primary_dark_material_dark = 2131427476; public static final int primary_dark_material_light = 2131427477; public static final int primary_material_dark = 2131427482; public static final int primary_material_light = 2131427483; public static final int primary_text_default_material_dark = 2131427489; public static final int primary_text_default_material_light = 2131427490; public static final int primary_text_disabled_material_dark = 2131427491; public static final int primary_text_disabled_material_light = 2131427492; public static final int ripple_material_dark = 2131427511; public static final int ripple_material_light = 2131427512; public static final int secondary_text_default_material_dark = 2131427514; public static final int secondary_text_default_material_light = 2131427515; public static final int secondary_text_disabled_material_dark = 2131427516; public static final int secondary_text_disabled_material_light = 2131427517; public static final int switch_thumb_disabled_material_dark = 2131427532; public static final int switch_thumb_disabled_material_light = 2131427533; public static final int switch_thumb_material_dark = 2131427564; public static final int switch_thumb_material_light = 2131427565; public static final int switch_thumb_normal_material_dark = 2131427534; public static final int switch_thumb_normal_material_light = 2131427535; } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: android.support.v7.appcompat.R.color * JD-Core Version: 0.6.0 */
unlicense
softindex/datakernel
core-csp/src/main/java/io/datakernel/csp/process/ChannelByteChunker.java
2362
/* * Copyright (C) 2015-2018 SoftIndex 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. */ package io.datakernel.csp.process; import io.datakernel.bytebuf.ByteBuf; import io.datakernel.bytebuf.ByteBufQueue; import io.datakernel.common.MemSize; import io.datakernel.promise.Promise; import io.datakernel.promise.Promises; import org.jetbrains.annotations.NotNull; import static io.datakernel.common.Preconditions.checkArgument; import static java.lang.Math.min; public final class ChannelByteChunker extends AbstractChannelTransformer<ChannelByteChunker, ByteBuf, ByteBuf> { private final ByteBufQueue bufs = new ByteBufQueue(); private final int minChunkSize; private final int maxChunkSize; private ChannelByteChunker(int minChunkSize, int maxChunkSize) { this.minChunkSize = checkArgument(minChunkSize, minSize -> minSize > 0, "Minimal chunk size should be greater than 0"); this.maxChunkSize = checkArgument(maxChunkSize, maxSize -> maxSize >= minChunkSize, "Maximal chunk size cannot be less than minimal chunk size"); } public static ChannelByteChunker create(MemSize minChunkSize, MemSize maxChunkSize) { return new ChannelByteChunker(minChunkSize.toInt(), maxChunkSize.toInt()); } @NotNull @Override protected Promise<Void> onItem(ByteBuf item) { bufs.add(item); return Promises.loop( null, $ -> bufs.hasRemainingBytes(minChunkSize), $ -> { int exactSize = 0; for (int i = 0; i != bufs.remainingBufs(); i++) { exactSize += bufs.peekBuf(i).readRemaining(); if (exactSize >= minChunkSize) { break; } } return send(bufs.takeExactSize(min(exactSize, maxChunkSize))); }); } @Override protected Promise<Void> onProcessFinish() { return bufs.hasRemaining() ? send(bufs.takeRemaining()) .then(this::sendEndOfStream) : sendEndOfStream(); } }
apache-2.0
GoogleCloudPlatform/declarative-resource-client-library
services/google/bigqueryreservation/beta/assignment.go
13270
// Copyright 2022 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package beta import ( "context" "fmt" "time" "google.golang.org/api/googleapi" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" ) type Assignment struct { Name *string `json:"name"` Assignee *string `json:"assignee"` JobType *AssignmentJobTypeEnum `json:"jobType"` State *AssignmentStateEnum `json:"state"` Project *string `json:"project"` Location *string `json:"location"` Reservation *string `json:"reservation"` } func (r *Assignment) String() string { return dcl.SprintResource(r) } // The enum AssignmentJobTypeEnum. type AssignmentJobTypeEnum string // AssignmentJobTypeEnumRef returns a *AssignmentJobTypeEnum with the value of string s // If the empty string is provided, nil is returned. func AssignmentJobTypeEnumRef(s string) *AssignmentJobTypeEnum { v := AssignmentJobTypeEnum(s) return &v } func (v AssignmentJobTypeEnum) Validate() error { if string(v) == "" { // Empty enum is okay. return nil } for _, s := range []string{"JOB_TYPE_UNSPECIFIED", "PIPELINE", "QUERY"} { if string(v) == s { return nil } } return &dcl.EnumInvalidError{ Enum: "AssignmentJobTypeEnum", Value: string(v), Valid: []string{}, } } // The enum AssignmentStateEnum. type AssignmentStateEnum string // AssignmentStateEnumRef returns a *AssignmentStateEnum with the value of string s // If the empty string is provided, nil is returned. func AssignmentStateEnumRef(s string) *AssignmentStateEnum { v := AssignmentStateEnum(s) return &v } func (v AssignmentStateEnum) Validate() error { if string(v) == "" { // Empty enum is okay. return nil } for _, s := range []string{"STATE_UNSPECIFIED", "PENDING", "ACTIVE"} { if string(v) == s { return nil } } return &dcl.EnumInvalidError{ Enum: "AssignmentStateEnum", Value: string(v), Valid: []string{}, } } // Describe returns a simple description of this resource to ensure that automated tools // can identify it. func (r *Assignment) Describe() dcl.ServiceTypeVersion { return dcl.ServiceTypeVersion{ Service: "bigquery_reservation", Type: "Assignment", Version: "beta", } } func (r *Assignment) ID() (string, error) { if err := extractAssignmentFields(r); err != nil { return "", err } nr := r.urlNormalized() params := map[string]interface{}{ "name": dcl.ValueOrEmptyString(nr.Name), "assignee": dcl.ValueOrEmptyString(nr.Assignee), "jobType": dcl.ValueOrEmptyString(nr.JobType), "state": dcl.ValueOrEmptyString(nr.State), "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), "reservation": dcl.ValueOrEmptyString(nr.Reservation), } return dcl.Nprintf("projects/{{project}}/locations/{{location}}/reservations/{{reservation}}/assignments/{{name}}", params), nil } const AssignmentMaxPage = -1 type AssignmentList struct { Items []*Assignment nextToken string pageSize int32 resource *Assignment } func (l *AssignmentList) HasNext() bool { return l.nextToken != "" } func (l *AssignmentList) Next(ctx context.Context, c *Client) error { ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() if !l.HasNext() { return fmt.Errorf("no next page") } items, token, err := c.listAssignment(ctx, l.resource, l.nextToken, l.pageSize) if err != nil { return err } l.Items = items l.nextToken = token return err } func (c *Client) ListAssignment(ctx context.Context, project, location, reservation string) (*AssignmentList, error) { ctx = dcl.ContextWithRequestID(ctx) ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() return c.ListAssignmentWithMaxResults(ctx, project, location, reservation, AssignmentMaxPage) } func (c *Client) ListAssignmentWithMaxResults(ctx context.Context, project, location, reservation string, pageSize int32) (*AssignmentList, error) { ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() // Create a resource object so that we can use proper url normalization methods. r := &Assignment{ Project: &project, Location: &location, Reservation: &reservation, } items, token, err := c.listAssignment(ctx, r, "", pageSize) if err != nil { return nil, err } return &AssignmentList{ Items: items, nextToken: token, pageSize: pageSize, resource: r, }, nil } func (c *Client) GetAssignment(ctx context.Context, r *Assignment) (*Assignment, error) { ctx = dcl.ContextWithRequestID(ctx) ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() // This is *purposefully* supressing errors. // This function is used with url-normalized values + not URL normalized values. // URL Normalized values will throw unintentional errors, since those values are not of the proper parent form. extractAssignmentFields(r) b, err := c.getAssignmentRaw(ctx, r) if err != nil { if dcl.IsNotFound(err) { return nil, &googleapi.Error{ Code: 404, Message: err.Error(), } } return nil, err } result, err := unmarshalAssignment(b, c) if err != nil { return nil, err } result.Project = r.Project result.Location = r.Location result.Reservation = r.Reservation c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result) c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r) result, err = canonicalizeAssignmentNewState(c, result, r) if err != nil { return nil, err } if err := postReadExtractAssignmentFields(result); err != nil { return result, err } c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result) return result, nil } func (c *Client) DeleteAssignment(ctx context.Context, r *Assignment) error { ctx = dcl.ContextWithRequestID(ctx) ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() if r == nil { return fmt.Errorf("Assignment resource is nil") } c.Config.Logger.InfoWithContext(ctx, "Deleting Assignment...") deleteOp := deleteAssignmentOperation{} return deleteOp.do(ctx, r, c) } // DeleteAllAssignment deletes all resources that the filter functions returns true on. func (c *Client) DeleteAllAssignment(ctx context.Context, project, location, reservation string, filter func(*Assignment) bool) error { listObj, err := c.ListAssignment(ctx, project, location, reservation) if err != nil { return err } err = c.deleteAllAssignment(ctx, filter, listObj.Items) if err != nil { return err } for listObj.HasNext() { err = listObj.Next(ctx, c) if err != nil { return nil } err = c.deleteAllAssignment(ctx, filter, listObj.Items) if err != nil { return err } } return nil } func (c *Client) ApplyAssignment(ctx context.Context, rawDesired *Assignment, opts ...dcl.ApplyOption) (*Assignment, error) { ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() ctx = dcl.ContextWithRequestID(ctx) var resultNewState *Assignment err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { newState, err := applyAssignmentHelper(c, ctx, rawDesired, opts...) resultNewState = newState if err != nil { // If the error is 409, there is conflict in resource update. // Here we want to apply changes based on latest state. if dcl.IsConflictError(err) { return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err} } return nil, err } return nil, nil }, c.Config.RetryProvider) return resultNewState, err } func applyAssignmentHelper(c *Client, ctx context.Context, rawDesired *Assignment, opts ...dcl.ApplyOption) (*Assignment, error) { c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyAssignment...") c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired) // 1.1: Validation of user-specified fields in desired state. if err := rawDesired.validate(); err != nil { return nil, err } if err := extractAssignmentFields(rawDesired); err != nil { return nil, err } initial, desired, fieldDiffs, err := c.assignmentDiffsForRawDesired(ctx, rawDesired, opts...) if err != nil { return nil, fmt.Errorf("failed to create a diff: %w", err) } diffs, err := convertFieldDiffsToAssignmentDiffs(c.Config, fieldDiffs, opts) if err != nil { return nil, err } // TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far). // 2.3: Lifecycle Directive Check var create bool lp := dcl.FetchLifecycleParams(opts) if initial == nil { if dcl.HasLifecycleParam(lp, dcl.BlockCreation) { return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)} } create = true } else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) { return nil, dcl.ApplyInfeasibleError{ Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial), } } else { for _, d := range diffs { if d.RequiresRecreate { return nil, dcl.ApplyInfeasibleError{ Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d), } } if dcl.HasLifecycleParam(lp, dcl.BlockModification) { return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)} } } } // 2.4 Imperative Request Planning var ops []assignmentApiOperation if create { ops = append(ops, &createAssignmentOperation{}) } else { for _, d := range diffs { ops = append(ops, d.UpdateOp) } } c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops) // 2.5 Request Actuation for _, op := range ops { c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op) if err := op.do(ctx, desired, c); err != nil { c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err) return nil, err } c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op) } return applyAssignmentDiff(c, ctx, desired, rawDesired, ops, opts...) } func applyAssignmentDiff(c *Client, ctx context.Context, desired *Assignment, rawDesired *Assignment, ops []assignmentApiOperation, opts ...dcl.ApplyOption) (*Assignment, error) { // 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...") rawNew, err := c.GetAssignment(ctx, desired.urlNormalized()) if err != nil { return nil, err } // Get additional values from the first response. // These values should be merged into the newState above. if len(ops) > 0 { lastOp := ops[len(ops)-1] if o, ok := lastOp.(*createAssignmentOperation); ok { if r, hasR := o.FirstResponse(); hasR { c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...") fullResp, err := unmarshalMapAssignment(r, c) if err != nil { return nil, err } rawNew, err = canonicalizeAssignmentNewState(c, rawNew, fullResp) if err != nil { return nil, err } } } } c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired) // 3.2b Canonicalization of raw new state using raw desired state newState, err := canonicalizeAssignmentNewState(c, rawNew, rawDesired) if err != nil { return rawNew, err } c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState) // 3.3 Comparison of the new state and raw desired state. // TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE newDesired, err := canonicalizeAssignmentDesiredState(rawDesired, newState) if err != nil { return newState, err } if err := postReadExtractAssignmentFields(newState); err != nil { return newState, err } // Need to ensure any transformations made here match acceptably in differ. if err := postReadExtractAssignmentFields(newDesired); err != nil { return newState, err } c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired) newDiffs, err := diffAssignment(c, newDesired, newState) if err != nil { return newState, err } if len(newDiffs) == 0 { c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.") } else { c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs) diffMessages := make([]string, len(newDiffs)) for i, d := range newDiffs { diffMessages[i] = fmt.Sprintf("%v", d) } return newState, dcl.DiffAfterApplyError{Diffs: diffMessages} } c.Config.Logger.InfoWithContext(ctx, "Done Apply.") return newState, nil }
apache-2.0
dcarbone/php-fhir-generated
src/DCarbone/PHPFHIRGenerated/STU3/FHIRResource/FHIRDomainResource/FHIRPaymentNotice.php
51514
<?php namespace DCarbone\PHPFHIRGenerated\STU3\FHIRResource\FHIRDomainResource; /*! * This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using * class definitions from HL7 FHIR (https://www.hl7.org/fhir/) * * Class creation date: December 26th, 2019 15:43+0000 * * PHPFHIR Copyright: * * Copyright 2016-2019 Daniel Carbone ([email protected]) * * 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. * * * FHIR Copyright Notice: * * Copyright (c) 2011+, HL7, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of HL7 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * Generated on Wed, Apr 19, 2017 07:44+1000 for FHIR v3.0.1 * * Note: the schemas & schematrons do not contain all of the rules about what makes resources * valid. Implementers will still need to be familiar with the content of the specification and with * any profiles that apply to the resources in order to make a conformant implementation. * */ use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCodeableConcept; use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDate; use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDateTime; use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFinancialResourceStatusCodes; use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRIdentifier; use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference; use DCarbone\PHPFHIRGenerated\STU3\FHIRResource\FHIRDomainResource; use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRConstants; use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRContainedTypeInterface; use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTypeInterface; /** * This resource provides the status of the payment for goods and services * rendered, and the request and response resource references. * If the element is present, it must have either a \@value, an \@id, or extensions * * Class FHIRPaymentNotice * @package \DCarbone\PHPFHIRGenerated\STU3\FHIRResource\FHIRDomainResource */ class FHIRPaymentNotice extends FHIRDomainResource implements PHPFHIRContainedTypeInterface { // name of FHIR type this class describes const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE; const FIELD_CREATED = 'created'; const FIELD_CREATED_EXT = '_created'; const FIELD_IDENTIFIER = 'identifier'; const FIELD_ORGANIZATION = 'organization'; const FIELD_PAYMENT_STATUS = 'paymentStatus'; const FIELD_PROVIDER = 'provider'; const FIELD_REQUEST = 'request'; const FIELD_RESPONSE = 'response'; const FIELD_STATUS = 'status'; const FIELD_STATUS_EXT = '_status'; const FIELD_STATUS_DATE = 'statusDate'; const FIELD_STATUS_DATE_EXT = '_statusDate'; const FIELD_TARGET = 'target'; /** @var string */ private $_xmlns = 'http://hl7.org/fhir'; /** * A date, date-time or partial date (e.g. just year or year + month). If hours and * minutes are specified, a time zone SHALL be populated. The format is a union of * the schema types gYear, gYearMonth, date and dateTime. Seconds must be provided * due to schema type constraints but may be zero-filled and may be ignored. Dates * SHALL be valid dates. * If the element is present, it must have either a \@value, an \@id, or extensions * * The date when this resource was created. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDateTime */ protected $created = null; /** * A technical identifier - identifies some entity uniquely and unambiguously. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The notice business identifier. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRIdentifier[] */ protected $identifier = []; /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The organization which is responsible for the services rendered to the patient. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ protected $organization = null; /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The payment status, typically paid: payment sent, cleared: payment received. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCodeableConcept */ protected $paymentStatus = null; /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The practitioner who is responsible for the services rendered to the patient. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ protected $provider = null; /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Reference of resource for which payment is being made. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ protected $request = null; /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Reference of response to resource for which payment is being made. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ protected $response = null; /** * A code specifying the state of the resource instance. * If the element is present, it must have either a \@value, an \@id, or extensions * * The status of the resource instance. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFinancialResourceStatusCodes */ protected $status = null; /** * A date or partial date (e.g. just year or year + month). There is no time zone. * The format is a union of the schema types gYear, gYearMonth and date. Dates * SHALL be valid dates. * If the element is present, it must have either a \@value, an \@id, or extensions * * The date when the above payment action occurrred. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDate */ protected $statusDate = null; /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The Insurer who is target of the request. * * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ protected $target = null; /** * Validation map for fields in type PaymentNotice * @var array */ private static $_validationRules = [ ]; /** * FHIRPaymentNotice Constructor * @param null|array $data */ public function __construct($data = null) { if (null === $data || [] === $data) { return; } if (!is_array($data)) { throw new \InvalidArgumentException(sprintf( 'FHIRPaymentNotice::_construct - $data expected to be null or array, %s seen', gettype($data) )); } parent::__construct($data); if (isset($data[self::FIELD_CREATED]) || isset($data[self::FIELD_CREATED_EXT])) { if (isset($data[self::FIELD_CREATED])) { $value = $data[self::FIELD_CREATED]; } else { $value = null; } if (isset($data[self::FIELD_CREATED_EXT]) && is_array($data[self::FIELD_CREATED_EXT])) { $ext = $data[self::FIELD_CREATED_EXT]; } else { $ext = []; } if (null !== $value) { if ($value instanceof FHIRDateTime) { $this->setCreated($value); } else if (is_array($value)) { $this->setCreated(new FHIRDateTime(array_merge($ext, $value))); } else { $this->setCreated(new FHIRDateTime([FHIRDateTime::FIELD_VALUE => $value] + $ext)); } } else if ([] !== $ext) { $this->setCreated(new FHIRDateTime($ext)); } } if (isset($data[self::FIELD_IDENTIFIER])) { if (is_array($data[self::FIELD_IDENTIFIER])) { foreach($data[self::FIELD_IDENTIFIER] as $v) { if (null === $v) { continue; } if ($v instanceof FHIRIdentifier) { $this->addIdentifier($v); } else { $this->addIdentifier(new FHIRIdentifier($v)); } } } else if ($data[self::FIELD_IDENTIFIER] instanceof FHIRIdentifier) { $this->addIdentifier($data[self::FIELD_IDENTIFIER]); } else { $this->addIdentifier(new FHIRIdentifier($data[self::FIELD_IDENTIFIER])); } } if (isset($data[self::FIELD_ORGANIZATION])) { if ($data[self::FIELD_ORGANIZATION] instanceof FHIRReference) { $this->setOrganization($data[self::FIELD_ORGANIZATION]); } else { $this->setOrganization(new FHIRReference($data[self::FIELD_ORGANIZATION])); } } if (isset($data[self::FIELD_PAYMENT_STATUS])) { if ($data[self::FIELD_PAYMENT_STATUS] instanceof FHIRCodeableConcept) { $this->setPaymentStatus($data[self::FIELD_PAYMENT_STATUS]); } else { $this->setPaymentStatus(new FHIRCodeableConcept($data[self::FIELD_PAYMENT_STATUS])); } } if (isset($data[self::FIELD_PROVIDER])) { if ($data[self::FIELD_PROVIDER] instanceof FHIRReference) { $this->setProvider($data[self::FIELD_PROVIDER]); } else { $this->setProvider(new FHIRReference($data[self::FIELD_PROVIDER])); } } if (isset($data[self::FIELD_REQUEST])) { if ($data[self::FIELD_REQUEST] instanceof FHIRReference) { $this->setRequest($data[self::FIELD_REQUEST]); } else { $this->setRequest(new FHIRReference($data[self::FIELD_REQUEST])); } } if (isset($data[self::FIELD_RESPONSE])) { if ($data[self::FIELD_RESPONSE] instanceof FHIRReference) { $this->setResponse($data[self::FIELD_RESPONSE]); } else { $this->setResponse(new FHIRReference($data[self::FIELD_RESPONSE])); } } if (isset($data[self::FIELD_STATUS]) || isset($data[self::FIELD_STATUS_EXT])) { if (isset($data[self::FIELD_STATUS])) { $value = $data[self::FIELD_STATUS]; } else { $value = null; } if (isset($data[self::FIELD_STATUS_EXT]) && is_array($data[self::FIELD_STATUS_EXT])) { $ext = $data[self::FIELD_STATUS_EXT]; } else { $ext = []; } if (null !== $value) { if ($value instanceof FHIRFinancialResourceStatusCodes) { $this->setStatus($value); } else if (is_array($value)) { $this->setStatus(new FHIRFinancialResourceStatusCodes(array_merge($ext, $value))); } else { $this->setStatus(new FHIRFinancialResourceStatusCodes([FHIRFinancialResourceStatusCodes::FIELD_VALUE => $value] + $ext)); } } else if ([] !== $ext) { $this->setStatus(new FHIRFinancialResourceStatusCodes($ext)); } } if (isset($data[self::FIELD_STATUS_DATE]) || isset($data[self::FIELD_STATUS_DATE_EXT])) { if (isset($data[self::FIELD_STATUS_DATE])) { $value = $data[self::FIELD_STATUS_DATE]; } else { $value = null; } if (isset($data[self::FIELD_STATUS_DATE_EXT]) && is_array($data[self::FIELD_STATUS_DATE_EXT])) { $ext = $data[self::FIELD_STATUS_DATE_EXT]; } else { $ext = []; } if (null !== $value) { if ($value instanceof FHIRDate) { $this->setStatusDate($value); } else if (is_array($value)) { $this->setStatusDate(new FHIRDate(array_merge($ext, $value))); } else { $this->setStatusDate(new FHIRDate([FHIRDate::FIELD_VALUE => $value] + $ext)); } } else if ([] !== $ext) { $this->setStatusDate(new FHIRDate($ext)); } } if (isset($data[self::FIELD_TARGET])) { if ($data[self::FIELD_TARGET] instanceof FHIRReference) { $this->setTarget($data[self::FIELD_TARGET]); } else { $this->setTarget(new FHIRReference($data[self::FIELD_TARGET])); } } } /** * @return string */ public function _getFHIRTypeName() { return self::FHIR_TYPE_NAME; } /** * @return string */ public function _getFHIRXMLElementDefinition() { $xmlns = $this->_getFHIRXMLNamespace(); if (null !== $xmlns) { $xmlns = " xmlns=\"{$xmlns}\""; } return "<PaymentNotice{$xmlns}></PaymentNotice>"; } /** * @return string */ public function _getResourceType() { return static::FHIR_TYPE_NAME; } /** * A date, date-time or partial date (e.g. just year or year + month). If hours and * minutes are specified, a time zone SHALL be populated. The format is a union of * the schema types gYear, gYearMonth, date and dateTime. Seconds must be provided * due to schema type constraints but may be zero-filled and may be ignored. Dates * SHALL be valid dates. * If the element is present, it must have either a \@value, an \@id, or extensions * * The date when this resource was created. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDateTime */ public function getCreated() { return $this->created; } /** * A date, date-time or partial date (e.g. just year or year + month). If hours and * minutes are specified, a time zone SHALL be populated. The format is a union of * the schema types gYear, gYearMonth, date and dateTime. Seconds must be provided * due to schema type constraints but may be zero-filled and may be ignored. Dates * SHALL be valid dates. * If the element is present, it must have either a \@value, an \@id, or extensions * * The date when this resource was created. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDateTime $created * @return static */ public function setCreated($created = null) { if (null === $created) { $this->created = null; return $this; } if ($created instanceof FHIRDateTime) { $this->created = $created; return $this; } $this->created = new FHIRDateTime($created); return $this; } /** * A technical identifier - identifies some entity uniquely and unambiguously. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The notice business identifier. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRIdentifier[] */ public function getIdentifier() { return $this->identifier; } /** * A technical identifier - identifies some entity uniquely and unambiguously. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The notice business identifier. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRIdentifier $identifier * @return static */ public function addIdentifier(FHIRIdentifier $identifier = null) { $this->identifier[] = $identifier; return $this; } /** * A technical identifier - identifies some entity uniquely and unambiguously. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The notice business identifier. * * @param \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRIdentifier[] $identifier * @return static */ public function setIdentifier(array $identifier = []) { $this->identifier = []; if ([] === $identifier) { return $this; } foreach($identifier as $v) { if ($v instanceof FHIRIdentifier) { $this->addIdentifier($v); } else { $this->addIdentifier(new FHIRIdentifier($v)); } } return $this; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The organization which is responsible for the services rendered to the patient. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ public function getOrganization() { return $this->organization; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The organization which is responsible for the services rendered to the patient. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference $organization * @return static */ public function setOrganization(FHIRReference $organization = null) { $this->organization = $organization; return $this; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The payment status, typically paid: payment sent, cleared: payment received. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCodeableConcept */ public function getPaymentStatus() { return $this->paymentStatus; } /** * A concept that may be defined by a formal reference to a terminology or ontology * or may be provided by text. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The payment status, typically paid: payment sent, cleared: payment received. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCodeableConcept $paymentStatus * @return static */ public function setPaymentStatus(FHIRCodeableConcept $paymentStatus = null) { $this->paymentStatus = $paymentStatus; return $this; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The practitioner who is responsible for the services rendered to the patient. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ public function getProvider() { return $this->provider; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The practitioner who is responsible for the services rendered to the patient. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference $provider * @return static */ public function setProvider(FHIRReference $provider = null) { $this->provider = $provider; return $this; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Reference of resource for which payment is being made. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ public function getRequest() { return $this->request; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Reference of resource for which payment is being made. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference $request * @return static */ public function setRequest(FHIRReference $request = null) { $this->request = $request; return $this; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Reference of response to resource for which payment is being made. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ public function getResponse() { return $this->response; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * Reference of response to resource for which payment is being made. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference $response * @return static */ public function setResponse(FHIRReference $response = null) { $this->response = $response; return $this; } /** * A code specifying the state of the resource instance. * If the element is present, it must have either a \@value, an \@id, or extensions * * The status of the resource instance. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFinancialResourceStatusCodes */ public function getStatus() { return $this->status; } /** * A code specifying the state of the resource instance. * If the element is present, it must have either a \@value, an \@id, or extensions * * The status of the resource instance. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFinancialResourceStatusCodes $status * @return static */ public function setStatus(FHIRFinancialResourceStatusCodes $status = null) { $this->status = $status; return $this; } /** * A date or partial date (e.g. just year or year + month). There is no time zone. * The format is a union of the schema types gYear, gYearMonth and date. Dates * SHALL be valid dates. * If the element is present, it must have either a \@value, an \@id, or extensions * * The date when the above payment action occurrred. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDate */ public function getStatusDate() { return $this->statusDate; } /** * A date or partial date (e.g. just year or year + month). There is no time zone. * The format is a union of the schema types gYear, gYearMonth and date. Dates * SHALL be valid dates. * If the element is present, it must have either a \@value, an \@id, or extensions * * The date when the above payment action occurrred. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRDate $statusDate * @return static */ public function setStatusDate($statusDate = null) { if (null === $statusDate) { $this->statusDate = null; return $this; } if ($statusDate instanceof FHIRDate) { $this->statusDate = $statusDate; return $this; } $this->statusDate = new FHIRDate($statusDate); return $this; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The Insurer who is target of the request. * * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference */ public function getTarget() { return $this->target; } /** * A reference from one resource to another. * If the element is present, it must have a value for at least one of the defined * elements, an \@id referenced from the Narrative, or extensions * * The Insurer who is target of the request. * * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRReference $target * @return static */ public function setTarget(FHIRReference $target = null) { $this->target = $target; return $this; } /** * Returns the validation rules that this type's fields must comply with to be considered "valid" * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]] * * @return array */ public function _getValidationRules() { return self::$_validationRules; } /** * Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as * passing. * * @return array */ public function _getValidationErrors() { $errs = parent::_getValidationErrors(); $validationRules = $this->_getValidationRules(); if (null !== ($v = $this->getCreated())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_CREATED] = $fieldErrs; } } if ([] !== ($vs = $this->getIdentifier())) { foreach($vs as $i => $v) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[sprintf('%s.%d', self::FIELD_IDENTIFIER, $i)] = $fieldErrs; } } } if (null !== ($v = $this->getOrganization())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_ORGANIZATION] = $fieldErrs; } } if (null !== ($v = $this->getPaymentStatus())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_PAYMENT_STATUS] = $fieldErrs; } } if (null !== ($v = $this->getProvider())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_PROVIDER] = $fieldErrs; } } if (null !== ($v = $this->getRequest())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_REQUEST] = $fieldErrs; } } if (null !== ($v = $this->getResponse())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_RESPONSE] = $fieldErrs; } } if (null !== ($v = $this->getStatus())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_STATUS] = $fieldErrs; } } if (null !== ($v = $this->getStatusDate())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_STATUS_DATE] = $fieldErrs; } } if (null !== ($v = $this->getTarget())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_TARGET] = $fieldErrs; } } if (isset($validationRules[self::FIELD_CREATED])) { $v = $this->getCreated(); foreach($validationRules[self::FIELD_CREATED] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_CREATED, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_CREATED])) { $errs[self::FIELD_CREATED] = []; } $errs[self::FIELD_CREATED][$rule] = $err; } } } if (isset($validationRules[self::FIELD_IDENTIFIER])) { $v = $this->getIdentifier(); foreach($validationRules[self::FIELD_IDENTIFIER] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_IDENTIFIER, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_IDENTIFIER])) { $errs[self::FIELD_IDENTIFIER] = []; } $errs[self::FIELD_IDENTIFIER][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ORGANIZATION])) { $v = $this->getOrganization(); foreach($validationRules[self::FIELD_ORGANIZATION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_ORGANIZATION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ORGANIZATION])) { $errs[self::FIELD_ORGANIZATION] = []; } $errs[self::FIELD_ORGANIZATION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_PAYMENT_STATUS])) { $v = $this->getPaymentStatus(); foreach($validationRules[self::FIELD_PAYMENT_STATUS] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_PAYMENT_STATUS, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_PAYMENT_STATUS])) { $errs[self::FIELD_PAYMENT_STATUS] = []; } $errs[self::FIELD_PAYMENT_STATUS][$rule] = $err; } } } if (isset($validationRules[self::FIELD_PROVIDER])) { $v = $this->getProvider(); foreach($validationRules[self::FIELD_PROVIDER] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_PROVIDER, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_PROVIDER])) { $errs[self::FIELD_PROVIDER] = []; } $errs[self::FIELD_PROVIDER][$rule] = $err; } } } if (isset($validationRules[self::FIELD_REQUEST])) { $v = $this->getRequest(); foreach($validationRules[self::FIELD_REQUEST] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_REQUEST, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_REQUEST])) { $errs[self::FIELD_REQUEST] = []; } $errs[self::FIELD_REQUEST][$rule] = $err; } } } if (isset($validationRules[self::FIELD_RESPONSE])) { $v = $this->getResponse(); foreach($validationRules[self::FIELD_RESPONSE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_RESPONSE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_RESPONSE])) { $errs[self::FIELD_RESPONSE] = []; } $errs[self::FIELD_RESPONSE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_STATUS])) { $v = $this->getStatus(); foreach($validationRules[self::FIELD_STATUS] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_STATUS, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_STATUS])) { $errs[self::FIELD_STATUS] = []; } $errs[self::FIELD_STATUS][$rule] = $err; } } } if (isset($validationRules[self::FIELD_STATUS_DATE])) { $v = $this->getStatusDate(); foreach($validationRules[self::FIELD_STATUS_DATE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_STATUS_DATE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_STATUS_DATE])) { $errs[self::FIELD_STATUS_DATE] = []; } $errs[self::FIELD_STATUS_DATE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_TARGET])) { $v = $this->getTarget(); foreach($validationRules[self::FIELD_TARGET] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_PAYMENT_NOTICE, self::FIELD_TARGET, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_TARGET])) { $errs[self::FIELD_TARGET] = []; } $errs[self::FIELD_TARGET][$rule] = $err; } } } if (isset($validationRules[self::FIELD_CONTAINED])) { $v = $this->getContained(); foreach($validationRules[self::FIELD_CONTAINED] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_CONTAINED, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_CONTAINED])) { $errs[self::FIELD_CONTAINED] = []; } $errs[self::FIELD_CONTAINED][$rule] = $err; } } } if (isset($validationRules[self::FIELD_EXTENSION])) { $v = $this->getExtension(); foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_EXTENSION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_EXTENSION])) { $errs[self::FIELD_EXTENSION] = []; } $errs[self::FIELD_EXTENSION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) { $v = $this->getModifierExtension(); foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) { $errs[self::FIELD_MODIFIER_EXTENSION] = []; } $errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_TEXT])) { $v = $this->getText(); foreach($validationRules[self::FIELD_TEXT] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_DOMAIN_RESOURCE, self::FIELD_TEXT, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_TEXT])) { $errs[self::FIELD_TEXT] = []; } $errs[self::FIELD_TEXT][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ID])) { $v = $this->getId(); foreach($validationRules[self::FIELD_ID] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_ID, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ID])) { $errs[self::FIELD_ID] = []; } $errs[self::FIELD_ID][$rule] = $err; } } } if (isset($validationRules[self::FIELD_IMPLICIT_RULES])) { $v = $this->getImplicitRules(); foreach($validationRules[self::FIELD_IMPLICIT_RULES] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_IMPLICIT_RULES, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_IMPLICIT_RULES])) { $errs[self::FIELD_IMPLICIT_RULES] = []; } $errs[self::FIELD_IMPLICIT_RULES][$rule] = $err; } } } if (isset($validationRules[self::FIELD_LANGUAGE])) { $v = $this->getLanguage(); foreach($validationRules[self::FIELD_LANGUAGE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_LANGUAGE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_LANGUAGE])) { $errs[self::FIELD_LANGUAGE] = []; } $errs[self::FIELD_LANGUAGE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_META])) { $v = $this->getMeta(); foreach($validationRules[self::FIELD_META] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_META, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_META])) { $errs[self::FIELD_META] = []; } $errs[self::FIELD_META][$rule] = $err; } } } return $errs; } /** * @param \SimpleXMLElement|string|null $sxe * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRResource\FHIRDomainResource\FHIRPaymentNotice $type * @param null|int $libxmlOpts * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRResource\FHIRDomainResource\FHIRPaymentNotice */ public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872) { if (null === $sxe) { return null; } if (is_string($sxe)) { libxml_use_internal_errors(true); $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false); if ($sxe === false) { throw new \DomainException(sprintf('FHIRPaymentNotice::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors())))); } libxml_use_internal_errors(false); } if (!($sxe instanceof \SimpleXMLElement)) { throw new \InvalidArgumentException(sprintf('FHIRPaymentNotice::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe))); } if (null === $type) { $type = new FHIRPaymentNotice; } elseif (!is_object($type) || !($type instanceof FHIRPaymentNotice)) { throw new \RuntimeException(sprintf( 'FHIRPaymentNotice::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\STU3\FHIRResource\FHIRDomainResource\FHIRPaymentNotice or null, %s seen.', is_object($type) ? get_class($type) : gettype($type) )); } FHIRDomainResource::xmlUnserialize($sxe, $type); $xmlNamespaces = $sxe->getDocNamespaces(false, false); if ([] !== $xmlNamespaces) { $ns = reset($xmlNamespaces); if (false !== $ns && '' !== $ns) { $type->_xmlns = $ns; } } $attributes = $sxe->attributes(); $children = $sxe->children(); if (isset($children->created)) { $type->setCreated(FHIRDateTime::xmlUnserialize($children->created)); } if (isset($attributes->created)) { $pt = $type->getCreated(); if (null !== $pt) { $pt->setValue((string)$attributes->created); } else { $type->setCreated((string)$attributes->created); } } if (isset($children->identifier)) { foreach($children->identifier as $child) { $type->addIdentifier(FHIRIdentifier::xmlUnserialize($child)); } } if (isset($children->organization)) { $type->setOrganization(FHIRReference::xmlUnserialize($children->organization)); } if (isset($children->paymentStatus)) { $type->setPaymentStatus(FHIRCodeableConcept::xmlUnserialize($children->paymentStatus)); } if (isset($children->provider)) { $type->setProvider(FHIRReference::xmlUnserialize($children->provider)); } if (isset($children->request)) { $type->setRequest(FHIRReference::xmlUnserialize($children->request)); } if (isset($children->response)) { $type->setResponse(FHIRReference::xmlUnserialize($children->response)); } if (isset($children->status)) { $type->setStatus(FHIRFinancialResourceStatusCodes::xmlUnserialize($children->status)); } if (isset($children->statusDate)) { $type->setStatusDate(FHIRDate::xmlUnserialize($children->statusDate)); } if (isset($attributes->statusDate)) { $pt = $type->getStatusDate(); if (null !== $pt) { $pt->setValue((string)$attributes->statusDate); } else { $type->setStatusDate((string)$attributes->statusDate); } } if (isset($children->target)) { $type->setTarget(FHIRReference::xmlUnserialize($children->target)); } return $type; } /** * @param null|\SimpleXMLElement $sxe * @param null|int $libxmlOpts * @return \SimpleXMLElement */ public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872) { if (null === $sxe) { $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false); } parent::xmlSerialize($sxe); if (null !== ($v = $this->getCreated())) { $v->xmlSerialize($sxe->addChild(self::FIELD_CREATED, null, $v->_getFHIRXMLNamespace())); } if ([] !== ($vs = $this->getIdentifier())) { foreach($vs as $v) { if (null === $v) { continue; } $v->xmlSerialize($sxe->addChild(self::FIELD_IDENTIFIER, null, $v->_getFHIRXMLNamespace())); } } if (null !== ($v = $this->getOrganization())) { $v->xmlSerialize($sxe->addChild(self::FIELD_ORGANIZATION, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getPaymentStatus())) { $v->xmlSerialize($sxe->addChild(self::FIELD_PAYMENT_STATUS, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getProvider())) { $v->xmlSerialize($sxe->addChild(self::FIELD_PROVIDER, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getRequest())) { $v->xmlSerialize($sxe->addChild(self::FIELD_REQUEST, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getResponse())) { $v->xmlSerialize($sxe->addChild(self::FIELD_RESPONSE, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getStatus())) { $v->xmlSerialize($sxe->addChild(self::FIELD_STATUS, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getStatusDate())) { $v->xmlSerialize($sxe->addChild(self::FIELD_STATUS_DATE, null, $v->_getFHIRXMLNamespace())); } if (null !== ($v = $this->getTarget())) { $v->xmlSerialize($sxe->addChild(self::FIELD_TARGET, null, $v->_getFHIRXMLNamespace())); } return $sxe; } /** * @return array */ public function jsonSerialize() { $a = parent::jsonSerialize(); if (null !== ($v = $this->getCreated())) { $a[self::FIELD_CREATED] = $v->getValue(); $enc = $v->jsonSerialize(); $cnt = count($enc); if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRDateTime::FIELD_VALUE, $enc)))) { unset($enc[FHIRDateTime::FIELD_VALUE]); $a[self::FIELD_CREATED_EXT] = $enc; } } if ([] !== ($vs = $this->getIdentifier())) { $a[self::FIELD_IDENTIFIER] = []; foreach($vs as $v) { if (null === $v) { continue; } $a[self::FIELD_IDENTIFIER][] = $v; } } if (null !== ($v = $this->getOrganization())) { $a[self::FIELD_ORGANIZATION] = $v; } if (null !== ($v = $this->getPaymentStatus())) { $a[self::FIELD_PAYMENT_STATUS] = $v; } if (null !== ($v = $this->getProvider())) { $a[self::FIELD_PROVIDER] = $v; } if (null !== ($v = $this->getRequest())) { $a[self::FIELD_REQUEST] = $v; } if (null !== ($v = $this->getResponse())) { $a[self::FIELD_RESPONSE] = $v; } if (null !== ($v = $this->getStatus())) { $a[self::FIELD_STATUS] = $v->getValue(); $enc = $v->jsonSerialize(); $cnt = count($enc); if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRFinancialResourceStatusCodes::FIELD_VALUE, $enc)))) { unset($enc[FHIRFinancialResourceStatusCodes::FIELD_VALUE]); $a[self::FIELD_STATUS_EXT] = $enc; } } if (null !== ($v = $this->getStatusDate())) { $a[self::FIELD_STATUS_DATE] = $v->getValue(); $enc = $v->jsonSerialize(); $cnt = count($enc); if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRDate::FIELD_VALUE, $enc)))) { unset($enc[FHIRDate::FIELD_VALUE]); $a[self::FIELD_STATUS_DATE_EXT] = $enc; } } if (null !== ($v = $this->getTarget())) { $a[self::FIELD_TARGET] = $v; } if ([] !== ($vs = $this->_getFHIRComments())) { $a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs; } return [PHPFHIRConstants::JSON_FIELD_RESOURCE_TYPE => $this->_getResourceType()] + $a; } /** * @return string */ public function __toString() { return self::FHIR_TYPE_NAME; } }
apache-2.0
DICE-UNC/indexing
src/databook/edsl/googql/Devaluate.java
3483
/** Code generated by EriLex */ package databook.edsl.googql; public class Devaluate extends Visitor { public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDtime d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final Dactionuri d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDsel d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDfollow d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDmatch d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDnumber d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDback d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDend d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDstring d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionDinteger d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DactionHeadDnode d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DmatchTailDwith d) { return new Evaluators().evaluate(d, nodes, counter, selects); } public java.lang.Object visit( final java.util.Stack<String> nodes, final java.lang.Integer counter, final java.util.Map<String,Class> selects, final DqueryDuse d) { return new Evaluators().evaluate(d, nodes, counter, selects); } }
apache-2.0
iziteq/izi-travel-java-api
api/src/main/java/travel/izi/api/model/entity/WebFeaturedObject.java
3892
/* * Copyright (C) 2014 IZITEQ B.V. * * 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 travel.izi.api.model.entity; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.google.auto.value.AutoValue; import travel.izi.api.model.enumeration.MtgObjectType; import travel.izi.api.model.enumeration.Status; import javax.annotation.Nullable; import java.io.Serializable; import java.util.List; /** * Promoted or most popular tours, museums and cities. */ @SuppressWarnings("unused") @AutoValue @JsonDeserialize(builder = AutoValue_WebFeaturedObject.Builder.class) public abstract class WebFeaturedObject implements Serializable { public static Builder builder() { return new AutoValue_WebFeaturedObject.Builder(); } /** * Universally Unique Identifier of the object. */ public abstract String uuid(); /** * Object type (museum, tour or city). */ public abstract MtgObjectType type(); /** * Content publication status. */ public abstract Status status(); /** * Requested content language. */ public abstract String language(); /** * Language of returned content. */ public abstract String contentLanguage(); /** * Array of all available languages of content, ISO 639-1. Typical for museum and tour. */ @Nullable public abstract List<String> contentLanguages(); /** * Localized (see content_language) name of object (title). */ @Nullable public abstract String name(); /** * Localized (see content_language) description of the object. */ @Nullable public abstract String description(); /** * Reserved field. Don’t use for now. */ @Nullable public abstract Boolean promoted(); /** * Universally Unique Identifier of city object. Typical for museum and tour. */ @Nullable public abstract String cityUuid(); /** * Universally Unique Identifier of country object. Typical for museum and tour. */ @Nullable public abstract String countryUuid(); /** * A position of object on a dashboard. Values: [1..5] */ @Nullable public abstract Integer position(); /** * Images of the content. */ @Nullable public abstract List<Media> images(); @AutoValue.Builder @JsonPOJOBuilder(withPrefix = "") public abstract static class Builder { public abstract Builder uuid(String uuid); public abstract Builder type(MtgObjectType type); public abstract Builder status(Status status); public abstract Builder language(String language); public abstract Builder contentLanguage(String contentLanguage); public abstract Builder contentLanguages(List<String> contentLanguages); public abstract Builder name(String name); public abstract Builder description(String description); public abstract Builder promoted(Boolean promoted); public abstract Builder cityUuid(String cityUuid); public abstract Builder countryUuid(String countryUuid); public abstract Builder position(Integer position); public abstract Builder images(List<Media> images); public abstract WebFeaturedObject build(); } }
apache-2.0
IAPH-NAS-Belarus-lab10/iaph.lab10.devices
Auris/B380 example/B380/Properties/AssemblyInfo.cs
1415
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("B380")] [assembly: AssemblyDescription("B380 example")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("BSU")] [assembly: AssemblyProduct("B380")] [assembly: AssemblyCopyright("Copyright © 2015 Barsukov Eugene")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a5ee71f1-e4e0-4099-8f22-da865960340f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
apache-2.0
LQJJ/demo
126-go-common-master/app/admin/main/dm/http/dm.go
7094
package http import ( "strconv" "go-common/app/admin/main/dm/model" "go-common/library/ecode" "go-common/library/log" bm "go-common/library/net/http/blademaster" "go-common/library/xstr" ) func contentList(c *bm.Context) { var ( v = new(model.SearchDMParams) ) if err := c.Bind(v); err != nil { return } c.JSON(dmSvc.DMSearch(c, v)) } // xmlCacheFlush flush danmu xml cache. func xmlCacheFlush(c *bm.Context) { var ( err error tp = int64(model.SubTypeVideo) p = c.Request.Form ) if p.Get("type") != "" { if tp, err = strconv.ParseInt(p.Get("type"), 10, 64); err != nil { c.JSON(nil, ecode.RequestErr) return } } oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } dmSvc.XMLCacheFlush(c, int32(tp), oid) c.JSON(nil, nil) } // dmSearch danmu content List by cid func dmSearch(c *bm.Context) { p := c.Request.Form params := &model.SearchDMParams{ Mid: model.CondIntNil, State: p.Get("state"), Pool: p.Get("pool"), ProgressFrom: model.CondIntNil, ProgressTo: model.CondIntNil, CtimeFrom: model.CondIntNil, CtimeTo: model.CondIntNil, Page: 1, Size: 100, Sort: p.Get("sort"), Order: p.Get("order"), Keyword: p.Get("keyword"), IP: p.Get("ip"), Attrs: p.Get("attrs"), } tp, err := strconv.ParseInt(p.Get("type"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } params.Type = int32(tp) oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { log.Error("param err oid %s %v", p.Get("oid"), err) c.JSON(nil, ecode.RequestErr) return } params.Oid = oid if p.Get("page") != "" { if params.Page, err = strconv.ParseInt(p.Get("page"), 10, 64); err != nil { log.Error("param err page %s %v", p.Get("page"), err) c.JSON(nil, ecode.RequestErr) return } } if p.Get("page_size") != "" { if params.Size, err = strconv.ParseInt(p.Get("page_size"), 10, 64); err != nil { log.Error("param err page_size %s %v", p.Get("page_size"), err) c.JSON(nil, ecode.RequestErr) return } } if p.Get("mid") != "" { if params.Mid, err = strconv.ParseInt(p.Get("mid"), 10, 64); err != nil { log.Error("param err mid %s %v", p.Get("mid"), err) c.JSON(nil, ecode.RequestErr) return } } if p.Get("progress_from") != "" { if params.ProgressFrom, err = strconv.ParseInt(p.Get("progress_from"), 10, 64); err != nil { log.Error("param err progress_from %s %v", p.Get("progress_from"), err) c.JSON(nil, ecode.RequestErr) return } } if p.Get("progress_to") != "" { if params.ProgressTo, err = strconv.ParseInt(p.Get("progress_to"), 10, 64); err != nil { log.Error("param err progress_to %s %v", p.Get("progress_to"), err) c.JSON(nil, ecode.RequestErr) return } } if p.Get("ctime_from") != "" { if params.CtimeFrom, err = strconv.ParseInt(p.Get("ctime_from"), 10, 64); err != nil { log.Error("param err ctime_from %s %v", p.Get("ctime_from"), err) c.JSON(nil, ecode.RequestErr) return } } if p.Get("ctime_to") != "" { if params.CtimeTo, err = strconv.ParseInt(p.Get("ctime_to"), 10, 64); err != nil { log.Error("param err ctime_to %s %v", p.Get("ctime_to"), err) c.JSON(nil, ecode.RequestErr) return } } data, err := dmSvc.DMSearch(c, params) c.JSON(data, err) } // editDMState batch operation by danmu content id func editDMState(c *bm.Context) { var ( moral, reason int64 p = c.Request.Form ) tp, err := strconv.ParseInt(p.Get("type"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } if p.Get("reason_id") != "" { reason, err = strconv.ParseInt(p.Get("reason_id"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } } state, err := strconv.ParseInt(p.Get("state"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } if p.Get("moral") != "" { moral, err = strconv.ParseInt(p.Get("moral"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } } adminID, err := strconv.ParseInt(p.Get("adminId"), 10, 64) if err != nil || adminID <= 0 { c.JSON(nil, ecode.RequestErr) return } uname := p.Get("uname") if uname == "" { c.JSON(nil, ecode.RequestErr) log.Error("empty uname is not allow") return } remark := p.Get("remark") dmids, err := xstr.SplitInts(p.Get("dmids")) if err != nil || len(dmids) == 0 { c.JSON(nil, ecode.RequestErr) return } err = dmSvc.EditDMState(c, int32(tp), int32(state), oid, int8(reason), dmids, float64(moral), adminID, uname, remark) c.JSON(nil, err) } // editDMPool batch operation by danmu content id func editDMPool(c *bm.Context) { p := c.Request.Form tp, err := strconv.ParseInt(p.Get("type"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } pool, err := strconv.ParseInt(p.Get("pool"), 10, 64) if err != nil || (pool != 0 && pool != 1) { c.JSON(nil, ecode.RequestErr) return } dmids, err := xstr.SplitInts(p.Get("dmids")) if err != nil || len(dmids) == 0 { c.JSON(nil, ecode.RequestErr) return } adminID, err := strconv.ParseInt(p.Get("adminId"), 10, 64) if err != nil || adminID <= 0 { c.JSON(nil, ecode.RequestErr) return } err = dmSvc.EditDMPool(c, int32(tp), oid, int32(pool), dmids, adminID) c.JSON(nil, err) } // editDMAttr change attr func editDMAttr(c *bm.Context) { var ( p = c.Request.Form bit uint value int32 ) tp, err := strconv.ParseInt(p.Get("type"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } oid, err := strconv.ParseInt(p.Get("oid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } attr, err := strconv.ParseInt(p.Get("attr"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } switch attr { case 0: // unprotect dm bit = model.AttrProtect value = model.AttrNo case 1: // protect dm bit = model.AttrProtect value = model.AttrYes default: c.JSON(nil, ecode.RequestErr) return } dmids, err := xstr.SplitInts(p.Get("dmids")) if err != nil || len(dmids) == 0 { c.JSON(nil, ecode.RequestErr) return } adminID, err := strconv.ParseInt(p.Get("adminId"), 10, 64) if err != nil || adminID <= 0 { c.JSON(nil, ecode.RequestErr) return } err = dmSvc.EditDMAttr(c, int32(tp), oid, dmids, bit, value, adminID) c.JSON(nil, err) } // dmIndexInfo get dm_index info func dmIndexInfo(c *bm.Context) { p := c.Request.Form cid, err := strconv.ParseInt(p.Get("cid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } info, err := dmSvc.DMIndexInfo(c, cid) c.JSON(info, err) } func fixDMCount(c *bm.Context) { p := c.Request.Form aid, err := strconv.ParseInt(p.Get("aid"), 10, 64) if err != nil { c.JSON(nil, ecode.RequestErr) return } err = dmSvc.FixDMCount(c, aid) c.JSON(nil, err) }
apache-2.0
torrances/swtk-commons
commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p1/p1/WordnetNounIndexIdInstance1179.java
14874
package org.swtk.commons.dict.wordnet.indexbyid.instance.p1.p1; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance1179 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("11790090", "{\"term\":\"allamanda\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790090\"]}"); add("11790272", "{\"term\":\"allamanda cathartica\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790272\"]}"); add("11790272", "{\"term\":\"common allamanda\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790272\"]}"); add("11790272", "{\"term\":\"golden trumpet\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790272\"]}"); add("11790482", "{\"term\":\"alstonia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790482\"]}"); add("11790482", "{\"term\":\"genus alstonia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790482\"]}"); add("11790725", "{\"term\":\"alstonia scholaris\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790725\"]}"); add("11790725", "{\"term\":\"devil tree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790725\"]}"); add("11790725", "{\"term\":\"dita\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790725\"]}"); add("11790725", "{\"term\":\"dita bark\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790725\"]}"); add("11790995", "{\"term\":\"amsonia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790995\"]}"); add("11790995", "{\"term\":\"genus amsonia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11790995\"]}"); add("11791222", "{\"term\":\"amsonia tabernaemontana\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791222\"]}"); add("11791222", "{\"term\":\"blue star\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791222\"]}"); add("11791438", "{\"term\":\"beaumontia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791438\"]}"); add("11791438", "{\"term\":\"genus beaumontia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791438\"]}"); add("11791616", "{\"term\":\"beaumontia grandiflora\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791616\"]}"); add("11791616", "{\"term\":\"easter lily vine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791616\"]}"); add("11791616", "{\"term\":\"nepal trumpet flower\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791616\"]}"); add("11791852", "{\"term\":\"genus carissa\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11791852\"]}"); add("11792008", "{\"term\":\"carissa\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792008\"]}"); add("11792215", "{\"term\":\"carissa bispinosa\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792215\"]}"); add("11792215", "{\"term\":\"hedge thorn\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792215\"]}"); add("11792215", "{\"term\":\"natal plum\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07762886\", \"11792215\", \"11792393\"]}"); add("11792393", "{\"term\":\"amatungulu\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792393\"]}"); add("11792393", "{\"term\":\"carissa grandiflora\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792393\"]}"); add("11792393", "{\"term\":\"carissa macrocarpa\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792393\"]}"); add("11792393", "{\"term\":\"natal plum\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"07762886\", \"11792215\", \"11792393\"]}"); add("11792623", "{\"term\":\"catharanthus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792623\"]}"); add("11792623", "{\"term\":\"genus catharanthus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792623\"]}"); add("11792877", "{\"term\":\"cape periwinkle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11792877", "{\"term\":\"catharanthus roseus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11792877", "{\"term\":\"cayenne jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11792877", "{\"term\":\"madagascar periwinkle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11792877", "{\"term\":\"old maid\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"00494869\", \"10293049\", \"11792877\", \"12054610\", \"10655886\"]}"); add("11792877", "{\"term\":\"periwinkle\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01951087\", \"07798644\", \"11792877\", \"11798398\"]}"); add("11792877", "{\"term\":\"red periwinkle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11792877", "{\"term\":\"rose periwinkle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11792877", "{\"term\":\"vinca rosea\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11792877\"]}"); add("11793171", "{\"term\":\"genus holarrhena\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793171\"]}"); add("11793171", "{\"term\":\"holarrhena\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793171\"]}"); add("11793348", "{\"term\":\"conessi\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793348\"]}"); add("11793348", "{\"term\":\"holarrhena antidysenterica\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793348\"]}"); add("11793348", "{\"term\":\"holarrhena pubescens\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793348\"]}"); add("11793348", "{\"term\":\"ivory tree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793348\"]}"); add("11793348", "{\"term\":\"kurchee\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793348\"]}"); add("11793348", "{\"term\":\"kurchi\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793348\"]}"); add("11793607", "{\"term\":\"dipladenia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793607\"]}"); add("11793607", "{\"term\":\"genus dipladenia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793607\"]}"); add("11793607", "{\"term\":\"genus mandevilla\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793607\"]}"); add("11793607", "{\"term\":\"mandevilla\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793607\"]}"); add("11793877", "{\"term\":\"dipladenia boliviensis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793877\"]}"); add("11793877", "{\"term\":\"mandevilla boliviensis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793877\"]}"); add("11793877", "{\"term\":\"white dipladenia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11793877\"]}"); add("11794097", "{\"term\":\"chilean jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794097\"]}"); add("11794097", "{\"term\":\"mandevilla laxa\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794097\"]}"); add("11794329", "{\"term\":\"genus nerium\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794329\"]}"); add("11794329", "{\"term\":\"nerium\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794329\"]}"); add("11794456", "{\"term\":\"nerium oleander\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794456\"]}"); add("11794456", "{\"term\":\"oleander\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794456\"]}"); add("11794456", "{\"term\":\"rose bay\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794456\"]}"); add("11794748", "{\"term\":\"genus plumeria\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794748\"]}"); add("11794748", "{\"term\":\"plumeria\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794748\"]}"); add("11794748", "{\"term\":\"plumiera\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794748\"]}"); add("11794982", "{\"term\":\"frangipani\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794982\"]}"); add("11794982", "{\"term\":\"frangipanni\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11794982\"]}"); add("11795264", "{\"term\":\"pagoda tree\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11795264\", \"11795441\"]}"); add("11795264", "{\"term\":\"plumeria acutifolia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795264\"]}"); add("11795264", "{\"term\":\"temple tree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795264\"]}"); add("11795441", "{\"term\":\"pagoda tree\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11795264\", \"11795441\"]}"); add("11795441", "{\"term\":\"plumeria alba\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795441\"]}"); add("11795441", "{\"term\":\"west indian jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795441\"]}"); add("11795629", "{\"term\":\"genus rauvolfia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795629\"]}"); add("11795629", "{\"term\":\"genus rauwolfia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795629\"]}"); add("11795809", "{\"term\":\"rauvolfia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11795809\"]}"); add("11795809", "{\"term\":\"rauwolfia\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11795809\", \"15027381\"]}"); add("11796095", "{\"term\":\"rauwolfia serpentina\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796095\"]}"); add("11796095", "{\"term\":\"snakewood\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796095\"]}"); add("11796249", "{\"term\":\"genus strophanthus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796249\"]}"); add("11796428", "{\"term\":\"strophanthus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796428\"]}"); add("11796703", "{\"term\":\"strophanthus kombe\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796703\"]}"); add("11796806", "{\"term\":\"genus tabernaemontana\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796806\"]}"); add("11796806", "{\"term\":\"tabernaemontana\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796806\"]}"); add("11796980", "{\"term\":\"adam\u0027s apple\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05537929\", \"11796980\"]}"); add("11796980", "{\"term\":\"coffee rose\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"crape jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"crepe gardenia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"crepe jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"east indian rosebay\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"nero\u0027s crown\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"pinwheel flower\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11796980", "{\"term\":\"tabernaemontana divaricate\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11796980\"]}"); add("11797330", "{\"term\":\"genus thevetia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797330\"]}"); add("11797330", "{\"term\":\"thevetia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797330\"]}"); add("11797549", "{\"term\":\"thevetia neriifolia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797549\"]}"); add("11797549", "{\"term\":\"thevetia peruviana\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797549\"]}"); add("11797549", "{\"term\":\"yellow oleander\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797549\"]}"); add("11797834", "{\"term\":\"genus trachelospermum\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797834\"]}"); add("11797834", "{\"term\":\"trachelospermum\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11797834\"]}"); add("11798021", "{\"term\":\"confederate jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798021\"]}"); add("11798021", "{\"term\":\"star jasmine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798021\"]}"); add("11798021", "{\"term\":\"trachelospermum jasminoides\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798021\"]}"); add("11798248", "{\"term\":\"genus vinca\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798248\"]}"); add("11798248", "{\"term\":\"vinca\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798248\"]}"); add("11798398", "{\"term\":\"periwinkle\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01951087\", \"07798644\", \"11792877\", \"11798398\"]}"); add("11798561", "{\"term\":\"myrtle\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"12350986\", \"11798561\"]}"); add("11798561", "{\"term\":\"vinca minor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798561\"]}"); add("11798726", "{\"term\":\"large periwinkle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798726\"]}"); add("11798726", "{\"term\":\"vinca major\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798726\"]}"); add("11798860", "{\"term\":\"arales\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798860\"]}"); add("11798860", "{\"term\":\"order arales\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11798860\"]}"); add("11799003", "{\"term\":\"araceae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11799003\"]}"); add("11799003", "{\"term\":\"arum family\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11799003\"]}"); add("11799003", "{\"term\":\"family araceae\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11799003\"]}"); add("11799769", "{\"term\":\"aroid\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11799769\"]}"); add("11799769", "{\"term\":\"arum\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11799769\", \"11800487\"]}"); } private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } }
apache-2.0
estatio/estatio
estatioapp/app/src/main/java/org/estatio/module/base/dom/apptenancy/ApplicationTenancyInvariantsService.java
3740
/* * * Copyright 2012-2014 Eurocommercial Properties NV * * * 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.estatio.module.base.dom.apptenancy; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; import org.estatio.module.base.dom.UdoDomainObject2; import org.estatio.module.base.dom.UdoDomainService; /** * Centralizes rules governing the moving of {@link org.isisaddons.module.security.dom.tenancy.ApplicationTenancy}. */ @DomainService(nature = NatureOfService.DOMAIN) public class ApplicationTenancyInvariantsService extends UdoDomainService<ApplicationTenancyInvariantsService> { // ////////////////////////////////////// private ApplicationTenancySubscriberAlgorithmRegistry algorithmRegistry; public ApplicationTenancyInvariantsService() { super(ApplicationTenancyInvariantsService.class); } // ////////////////////////////////////// @PostConstruct public void init(final Map<String, String> properties) { super.init(properties); algorithmRegistry = new ApplicationTenancySubscriberAlgorithmRegistry(); algorithmRegistry.addAlgorithms(); } // ////////////////////////////////////// @Programmatic @com.google.common.eventbus.Subscribe @org.axonframework.eventhandling.annotation.EventHandler public void on(final ApplicationTenancyEventChanged ev) { on(ev, ApplicationTenancyEventChanged.class); } @Programmatic @com.google.common.eventbus.Subscribe @org.axonframework.eventhandling.annotation.EventHandler public void on(final ApplicationTenancyEventMovedDown ev) { on(ev, ApplicationTenancyEventMovedDown.class); } @Programmatic @com.google.common.eventbus.Subscribe @org.axonframework.eventhandling.annotation.EventHandler public void on(final ApplicationTenancyEventMovedUp ev) { on(ev, ApplicationTenancyEventMovedUp.class); } private void on( final ApplicationTenancyEventChanged ev, final Class<? extends ApplicationTenancyEventChanged> eventClass) { final UdoDomainObject2 source = ev.getSource(); final List<ApplicationTenancySubscriberAlgorithm> algorithms = algorithmRegistry.lookup(source, eventClass); for (final ApplicationTenancySubscriberAlgorithm algorithm : algorithms) { getContainer().injectServicesInto(algorithm); switch (ev.getEventPhase()) { case HIDE: algorithm.hide(ev, source); break; case DISABLE: algorithm.disable(ev, source); break; case VALIDATE: algorithm.validate(ev, source); break; case EXECUTING: algorithm.executing(ev, source); break; case EXECUTED: algorithm.executed(ev, source); break; } } } }
apache-2.0
orientechnologies/orientdb
tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphDatabaseTest.java
14380
/* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.test.database.auto; import com.orientechnologies.common.util.OCallable; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OCommandExecutionException; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientEdge; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientVertex; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @Test public class GraphDatabaseTest extends DocumentDBBaseTest { private OrientGraph database; @Parameters(value = "url") public GraphDatabaseTest(@Optional String url) { super(url); } @BeforeMethod public void init() { database = new OrientGraph(url); database.setUseLightweightEdges(false); } @AfterMethod public void deinit() { database.shutdown(); } @Test public void populate() { OClass vehicleClass = database.createVertexType("GraphVehicle"); database.createVertexType("GraphCar", vehicleClass); database.createVertexType("GraphMotocycle", "GraphVehicle"); ODocument carNode = database .addVertex("class:GraphCar", "brand", "Hyundai", "model", "Coupe", "year", 2003) .getRecord(); ODocument motoNode = database .addVertex( "class:GraphMotocycle", "brand", "Yamaha", "model", "X-City 250", "year", 2009) .getRecord(); database.commit(); database.addEdge(null, database.getVertex(carNode), database.getVertex(motoNode), "E").save(); List<ODocument> result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>("select from GraphVehicle")); Assert.assertEquals(result.size(), 2); for (ODocument v : result) { Assert.assertTrue(v.getSchemaClass().isSubClassOf(vehicleClass)); } database.commit(); database.shutdown(); database = new OrientGraph(url); database.setUseLightweightEdges(false); database.getRawGraph().getMetadata().getSchema().reload(); result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>("select from GraphVehicle")); Assert.assertEquals(result.size(), 2); Edge edge1 = null; Edge edge2 = null; for (ODocument v : result) { Assert.assertTrue(v.getSchemaClass().isSubClassOf("GraphVehicle")); if (v.getClassName().equals("GraphCar")) { Assert.assertEquals(database.getVertex(v).countEdges(Direction.OUT), 1); edge1 = database.getVertex(v).getEdges(Direction.OUT).iterator().next(); } else { Assert.assertEquals(database.getVertex(v).countEdges(Direction.IN), 1); edge2 = database.getVertex(v).getEdges(Direction.IN).iterator().next(); } } database.commit(); Assert.assertEquals(edge1, edge2); } @Test(dependsOnMethods = "populate") public void testSQLAgainstGraph() { Vertex tom = database.addVertex(null, "name", "Tom"); Vertex ferrari = database.addVertex("class:GraphCar", "brand", "Ferrari"); Vertex maserati = database.addVertex("class:GraphCar", "brand", "Maserati"); Vertex porsche = database.addVertex("class:GraphCar", "brand", "Porsche"); database.addEdge(null, tom, ferrari, "drives"); database.addEdge(null, tom, maserati, "drives"); database.addEdge(null, tom, porsche, "owns"); database.commit(); Assert.assertNotNull(database.getVertex(tom).getEdges(Direction.OUT, "drives")); Assert.assertEquals(database.getVertex(tom).countEdges(Direction.OUT, "drives"), 2); List<ODocument> result = database .getRawGraph() .query( new OSQLSynchQuery<ODocument>( "select out_[in.@class = 'GraphCar'].in_ from V where name = 'Tom'")); Assert.assertEquals(result.size(), 1); result = database .getRawGraph() .query( new OSQLSynchQuery<ODocument>( "select out_[label='drives'][in.brand = 'Ferrari'].in_ from V where name = 'Tom'")); Assert.assertEquals(result.size(), 1); result = database .getRawGraph() .query( new OSQLSynchQuery<ODocument>( "select out_[in.brand = 'Ferrari'].in_ from V where name = 'Tom'")); Assert.assertEquals(result.size(), 1); } public void testNotDuplicatedIndexTxChanges() throws IOException { database.setAutoStartTx(false); database.commit(); OClass oc = database.getVertexType("vertexA"); if (oc == null) oc = database.createVertexType("vertexA"); if (!oc.existsProperty("name")) oc.createProperty("name", OType.STRING); if (oc.getClassIndex("vertexA_name_idx") == null) oc.createIndex("vertexA_name_idx", OClass.INDEX_TYPE.UNIQUE, "name"); database.setAutoStartTx(true); // FIRST: create a couple of records Vertex vertexA = database.addVertex("class:vertexA", "name", "myKey"); Vertex vertexB = database.addVertex("class:vertexA", "name", "anotherKey"); database.commit(); database.removeVertex(vertexB); database.removeVertex(vertexA); database.addVertex("class:vertexA", "name", "myKey"); database.commit(); } public void testNewVertexAndEdgesWithFieldsInOneShoot() throws IOException { OrientVertex vertexA = database.addVertex(null, "field1", "value1", "field2", "value2"); Map<String, Object> map = new HashMap<String, Object>(); map.put("field1", "value1"); map.put("field2", "value2"); OrientVertex vertexB = database.addVertex(null, map); OrientEdge edgeC = database.addEdge(null, vertexA, vertexB, "E"); edgeC.setProperty("edgeF1", "edgeV2"); database.commit(); Assert.assertEquals(vertexA.getProperty("field1"), "value1"); Assert.assertEquals(vertexA.getProperty("field2"), "value2"); Assert.assertEquals(vertexB.getProperty("field1"), "value1"); Assert.assertEquals(vertexB.getProperty("field2"), "value2"); Assert.assertEquals(edgeC.getProperty("edgeF1"), "edgeV2"); } @Test public void sqlNestedQueries() { Vertex vertex1 = database.addVertex(null, "driver", "John"); Vertex vertex2 = database.addVertex(null, "car", "ford"); Vertex targetVertex = database.addVertex(null, "car", "audi"); Edge edge = database.addEdge(null, vertex1, vertex2, "E"); edge.setProperty("color", "red"); edge.setProperty("action", "owns"); edge = database.addEdge(null, vertex1, targetVertex, "E"); edge.setProperty("color", "red"); edge.setProperty("action", "wants"); database.commit(); String query1 = "select driver from V where out().car contains 'ford'"; List<ODocument> result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(query1)); Assert.assertEquals(result.size(), 1); String query2 = "select driver from V where outE()[color='red'].inV().car contains 'ford'"; result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(query2)); Assert.assertEquals(result.size(), 1); // TODO these tests are broken, they should test "contains" instead of "=" String query3 = "select driver from V where outE()[action='owns'].inV().car = 'ford'"; result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(query3)); Assert.assertEquals(result.size(), 1); String query4 = "select driver from V where outE()[color='red'][action='owns'].inV().car = 'ford'"; result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(query4)); Assert.assertEquals(result.size(), 1); } @SuppressWarnings("unchecked") public void nestedQuery() { Vertex countryVertex1 = database.addVertex(null, "name", "UK", "area", "Europe", "code", "2"); Vertex cityVertex1 = database.addVertex(null, "name", "leicester", "lat", "52.64640", "long", "-1.13159"); Vertex cityVertex2 = database.addVertex(null, "name", "manchester", "lat", "53.47497", "long", "-2.25769"); database.addEdge(null, countryVertex1, cityVertex1, "owns"); database.addEdge(null, countryVertex1, cityVertex2, "owns"); database.commit(); String subquery = "select out('owns') from V where name = 'UK'"; List<OIdentifiable> result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(subquery)); Assert.assertEquals(result.size(), 1); Assert.assertEquals(((Collection) ((ODocument) result.get(0)).field("out")).size(), 2); subquery = "select expand(out('owns')) from V where name = 'UK'"; result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(subquery)); Assert.assertEquals(result.size(), 2); for (int i = 0; i < result.size(); i++) { // System.out.println("uno: " + result.get(i)); Assert.assertTrue(((ODocument) result.get(i).getRecord()).containsField("lat")); } String query = "select name, lat, long, distance(lat,long,51.5,0.08) as distance from (select expand(out('owns')) from V where name = 'UK') order by distance"; result = database.getRawGraph().query(new OSQLSynchQuery<ODocument>(query)); Assert.assertEquals(result.size(), 2); for (int i = 0; i < result.size(); i++) { // System.out.println("dos: " + result.get(i)); Assert.assertTrue(((ODocument) result.get(i).getRecord()).containsField("lat")); Assert.assertTrue(((ODocument) result.get(i).getRecord()).containsField("distance")); } } public void testDeleteOfVerticesWithDeleteCommandMustFail() { try { database.command(new OCommandSQL("delete from GraphVehicle")).execute(); Assert.assertTrue(false); } catch (OCommandExecutionException e) { Assert.assertTrue(true); } } public void testDeleteOfEdgesWithDeleteCommandMustFail() { try { database.command(new OCommandSQL("delete from E")).execute(); Assert.assertTrue(false); } catch (OCommandExecutionException e) { Assert.assertTrue(true); } } public void testDeleteOfVerticesAndEdgesWithDeleteCommandAndUnsafe() { Iterable<OIdentifiable> deletedVertices = database .command(new OCommandSQL("delete from GraphVehicle return before limit 1 unsafe")) .execute(); Assert.assertTrue(deletedVertices.iterator().hasNext()); OrientVertex v = (OrientVertex) deletedVertices.iterator().next(); Integer confirmDeleted = database.command(new OCommandSQL("delete from " + v.getIdentity() + " unsafe")).execute(); Assert.assertFalse(deletedVertices.iterator().hasNext()); Assert.assertEquals(confirmDeleted.intValue(), 0); Iterable<Edge> edges = v.getEdges(Direction.BOTH); for (Edge e : edges) { Integer deletedEdges = database .command(new OCommandSQL("delete from " + ((OrientEdge) e).getIdentity() + " unsafe")) .execute(); Assert.assertEquals(deletedEdges.intValue(), 1); } } public void testInsertOfEdgeWithInsertCommand() { try { database.command(new OCommandSQL("insert into E set a = 33")).execute(); Assert.assertTrue(false); } catch (OCommandExecutionException e) { Assert.assertTrue(true); } } public void testInsertOfEdgeWithInsertCommandUnsafe() { OrientEdge insertedEdge = database .command(new OCommandSQL("insert into E set in = #9:0, out = #9:1, a = 33 unsafe")) .execute(); Assert.assertNotNull(insertedEdge); Integer confirmDeleted = database .command(new OCommandSQL("delete from " + insertedEdge.getIdentity() + " unsafe")) .execute(); Assert.assertEquals(confirmDeleted.intValue(), 1); } public void testEmbeddedDoc() { database.executeOutsideTx( new OCallable<Object, OrientBaseGraph>() { @Override public Object call(OrientBaseGraph iArgument) { return iArgument.getRawGraph().getMetadata().getSchema().createClass("NonVertex"); } }); Vertex vertex = database.addVertex("class:V", "name", "vertexWithEmbedded"); ODocument doc = new ODocument(); doc.field("foo", "bar"); doc.save( database.getRawGraph().getClusterNameById(database.getRawGraph().getDefaultClusterId())); vertex.setProperty("emb1", doc); ODocument doc2 = new ODocument("V"); doc2.field("foo", "bar1"); vertex.setProperty("emb2", doc2); ODocument doc3 = new ODocument("NonVertex"); doc3.field("foo", "bar2"); vertex.setProperty("emb3", doc3); Object res1 = vertex.getProperty("emb1"); Assert.assertNotNull(res1); Assert.assertTrue(res1 instanceof ODocument); Object res2 = vertex.getProperty("emb2"); Assert.assertNotNull(res2); Assert.assertFalse(res2 instanceof ODocument); Object res3 = vertex.getProperty("emb3"); Assert.assertNotNull(res3); Assert.assertTrue(res3 instanceof ODocument); database.commit(); } }
apache-2.0
tensorflow/java
tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/proto/framework/AttrValue.java
160841
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/attr_value.proto package org.tensorflow.proto.framework; /** * <pre> * Protocol buffer representing the value for an attr used to configure an Op. * Comment indicates the corresponding attr type. Only the field matching the * attr type may be filled. * </pre> * * Protobuf type {@code tensorflow.AttrValue} */ public final class AttrValue extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tensorflow.AttrValue) AttrValueOrBuilder { private static final long serialVersionUID = 0L; // Use AttrValue.newBuilder() to construct. private AttrValue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AttrValue() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new AttrValue(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AttrValue( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { org.tensorflow.proto.framework.AttrValue.ListValue.Builder subBuilder = null; if (valueCase_ == 1) { subBuilder = ((org.tensorflow.proto.framework.AttrValue.ListValue) value_).toBuilder(); } value_ = input.readMessage(org.tensorflow.proto.framework.AttrValue.ListValue.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((org.tensorflow.proto.framework.AttrValue.ListValue) value_); value_ = subBuilder.buildPartial(); } valueCase_ = 1; break; } case 18: { valueCase_ = 2; value_ = input.readBytes(); break; } case 24: { valueCase_ = 3; value_ = input.readInt64(); break; } case 37: { valueCase_ = 4; value_ = input.readFloat(); break; } case 40: { valueCase_ = 5; value_ = input.readBool(); break; } case 48: { int rawValue = input.readEnum(); valueCase_ = 6; value_ = rawValue; break; } case 58: { org.tensorflow.proto.framework.TensorShapeProto.Builder subBuilder = null; if (valueCase_ == 7) { subBuilder = ((org.tensorflow.proto.framework.TensorShapeProto) value_).toBuilder(); } value_ = input.readMessage(org.tensorflow.proto.framework.TensorShapeProto.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((org.tensorflow.proto.framework.TensorShapeProto) value_); value_ = subBuilder.buildPartial(); } valueCase_ = 7; break; } case 66: { org.tensorflow.proto.framework.TensorProto.Builder subBuilder = null; if (valueCase_ == 8) { subBuilder = ((org.tensorflow.proto.framework.TensorProto) value_).toBuilder(); } value_ = input.readMessage(org.tensorflow.proto.framework.TensorProto.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((org.tensorflow.proto.framework.TensorProto) value_); value_ = subBuilder.buildPartial(); } valueCase_ = 8; break; } case 74: { java.lang.String s = input.readStringRequireUtf8(); valueCase_ = 9; value_ = s; break; } case 82: { org.tensorflow.proto.framework.NameAttrList.Builder subBuilder = null; if (valueCase_ == 10) { subBuilder = ((org.tensorflow.proto.framework.NameAttrList) value_).toBuilder(); } value_ = input.readMessage(org.tensorflow.proto.framework.NameAttrList.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((org.tensorflow.proto.framework.NameAttrList) value_); value_ = subBuilder.buildPartial(); } valueCase_ = 10; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.proto.framework.AttrValue.class, org.tensorflow.proto.framework.AttrValue.Builder.class); } public interface ListValueOrBuilder extends // @@protoc_insertion_point(interface_extends:tensorflow.AttrValue.ListValue) com.google.protobuf.MessageOrBuilder { /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ java.util.List<com.google.protobuf.ByteString> getSList(); /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ int getSCount(); /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ com.google.protobuf.ByteString getS(int index); /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ java.util.List<java.lang.Long> getIList(); /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ int getICount(); /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ long getI(int index); /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ java.util.List<java.lang.Float> getFList(); /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ int getFCount(); /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ float getF(int index); /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ java.util.List<java.lang.Boolean> getBList(); /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ int getBCount(); /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ boolean getB(int index); /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ java.util.List<org.tensorflow.proto.framework.DataType> getTypeList(); /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ int getTypeCount(); /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ org.tensorflow.proto.framework.DataType getType(int index); /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ java.util.List<java.lang.Integer> getTypeValueList(); /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ int getTypeValue(int index); /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ java.util.List<org.tensorflow.proto.framework.TensorShapeProto> getShapeList(); /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ org.tensorflow.proto.framework.TensorShapeProto getShape(int index); /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ int getShapeCount(); /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ java.util.List<? extends org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> getShapeOrBuilderList(); /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ org.tensorflow.proto.framework.TensorShapeProtoOrBuilder getShapeOrBuilder( int index); /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ java.util.List<org.tensorflow.proto.framework.TensorProto> getTensorList(); /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ org.tensorflow.proto.framework.TensorProto getTensor(int index); /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ int getTensorCount(); /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ java.util.List<? extends org.tensorflow.proto.framework.TensorProtoOrBuilder> getTensorOrBuilderList(); /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ org.tensorflow.proto.framework.TensorProtoOrBuilder getTensorOrBuilder( int index); /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ java.util.List<org.tensorflow.proto.framework.NameAttrList> getFuncList(); /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ org.tensorflow.proto.framework.NameAttrList getFunc(int index); /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ int getFuncCount(); /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ java.util.List<? extends org.tensorflow.proto.framework.NameAttrListOrBuilder> getFuncOrBuilderList(); /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ org.tensorflow.proto.framework.NameAttrListOrBuilder getFuncOrBuilder( int index); } /** * <pre> * LINT.IfChange * </pre> * * Protobuf type {@code tensorflow.AttrValue.ListValue} */ public static final class ListValue extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tensorflow.AttrValue.ListValue) ListValueOrBuilder { private static final long serialVersionUID = 0L; // Use ListValue.newBuilder() to construct. private ListValue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListValue() { s_ = java.util.Collections.emptyList(); i_ = emptyLongList(); f_ = emptyFloatList(); b_ = emptyBooleanList(); type_ = java.util.Collections.emptyList(); shape_ = java.util.Collections.emptyList(); tensor_ = java.util.Collections.emptyList(); func_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ListValue(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListValue( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 18: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { s_ = new java.util.ArrayList<com.google.protobuf.ByteString>(); mutable_bitField0_ |= 0x00000001; } s_.add(input.readBytes()); break; } case 24: { if (!((mutable_bitField0_ & 0x00000002) != 0)) { i_ = newLongList(); mutable_bitField0_ |= 0x00000002; } i_.addLong(input.readInt64()); break; } case 26: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); if (!((mutable_bitField0_ & 0x00000002) != 0) && input.getBytesUntilLimit() > 0) { i_ = newLongList(); mutable_bitField0_ |= 0x00000002; } while (input.getBytesUntilLimit() > 0) { i_.addLong(input.readInt64()); } input.popLimit(limit); break; } case 37: { if (!((mutable_bitField0_ & 0x00000004) != 0)) { f_ = newFloatList(); mutable_bitField0_ |= 0x00000004; } f_.addFloat(input.readFloat()); break; } case 34: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); if (!((mutable_bitField0_ & 0x00000004) != 0) && input.getBytesUntilLimit() > 0) { f_ = newFloatList(); mutable_bitField0_ |= 0x00000004; } while (input.getBytesUntilLimit() > 0) { f_.addFloat(input.readFloat()); } input.popLimit(limit); break; } case 40: { if (!((mutable_bitField0_ & 0x00000008) != 0)) { b_ = newBooleanList(); mutable_bitField0_ |= 0x00000008; } b_.addBoolean(input.readBool()); break; } case 42: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); if (!((mutable_bitField0_ & 0x00000008) != 0) && input.getBytesUntilLimit() > 0) { b_ = newBooleanList(); mutable_bitField0_ |= 0x00000008; } while (input.getBytesUntilLimit() > 0) { b_.addBoolean(input.readBool()); } input.popLimit(limit); break; } case 48: { int rawValue = input.readEnum(); if (!((mutable_bitField0_ & 0x00000010) != 0)) { type_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000010; } type_.add(rawValue); break; } case 50: { int length = input.readRawVarint32(); int oldLimit = input.pushLimit(length); while(input.getBytesUntilLimit() > 0) { int rawValue = input.readEnum(); if (!((mutable_bitField0_ & 0x00000010) != 0)) { type_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000010; } type_.add(rawValue); } input.popLimit(oldLimit); break; } case 58: { if (!((mutable_bitField0_ & 0x00000020) != 0)) { shape_ = new java.util.ArrayList<org.tensorflow.proto.framework.TensorShapeProto>(); mutable_bitField0_ |= 0x00000020; } shape_.add( input.readMessage(org.tensorflow.proto.framework.TensorShapeProto.parser(), extensionRegistry)); break; } case 66: { if (!((mutable_bitField0_ & 0x00000040) != 0)) { tensor_ = new java.util.ArrayList<org.tensorflow.proto.framework.TensorProto>(); mutable_bitField0_ |= 0x00000040; } tensor_.add( input.readMessage(org.tensorflow.proto.framework.TensorProto.parser(), extensionRegistry)); break; } case 74: { if (!((mutable_bitField0_ & 0x00000080) != 0)) { func_ = new java.util.ArrayList<org.tensorflow.proto.framework.NameAttrList>(); mutable_bitField0_ |= 0x00000080; } func_.add( input.readMessage(org.tensorflow.proto.framework.NameAttrList.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { s_ = java.util.Collections.unmodifiableList(s_); // C } if (((mutable_bitField0_ & 0x00000002) != 0)) { i_.makeImmutable(); // C } if (((mutable_bitField0_ & 0x00000004) != 0)) { f_.makeImmutable(); // C } if (((mutable_bitField0_ & 0x00000008) != 0)) { b_.makeImmutable(); // C } if (((mutable_bitField0_ & 0x00000010) != 0)) { type_ = java.util.Collections.unmodifiableList(type_); } if (((mutable_bitField0_ & 0x00000020) != 0)) { shape_ = java.util.Collections.unmodifiableList(shape_); } if (((mutable_bitField0_ & 0x00000040) != 0)) { tensor_ = java.util.Collections.unmodifiableList(tensor_); } if (((mutable_bitField0_ & 0x00000080) != 0)) { func_ = java.util.Collections.unmodifiableList(func_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_ListValue_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_ListValue_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.proto.framework.AttrValue.ListValue.class, org.tensorflow.proto.framework.AttrValue.ListValue.Builder.class); } public static final int S_FIELD_NUMBER = 2; private java.util.List<com.google.protobuf.ByteString> s_; /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public java.util.List<com.google.protobuf.ByteString> getSList() { return s_; } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public int getSCount() { return s_.size(); } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public com.google.protobuf.ByteString getS(int index) { return s_.get(index); } public static final int I_FIELD_NUMBER = 3; private com.google.protobuf.Internal.LongList i_; /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public java.util.List<java.lang.Long> getIList() { return i_; } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public int getICount() { return i_.size(); } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public long getI(int index) { return i_.getLong(index); } private int iMemoizedSerializedSize = -1; public static final int F_FIELD_NUMBER = 4; private com.google.protobuf.Internal.FloatList f_; /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public java.util.List<java.lang.Float> getFList() { return f_; } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public int getFCount() { return f_.size(); } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public float getF(int index) { return f_.getFloat(index); } private int fMemoizedSerializedSize = -1; public static final int B_FIELD_NUMBER = 5; private com.google.protobuf.Internal.BooleanList b_; /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public java.util.List<java.lang.Boolean> getBList() { return b_; } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public int getBCount() { return b_.size(); } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public boolean getB(int index) { return b_.getBoolean(index); } private int bMemoizedSerializedSize = -1; public static final int TYPE_FIELD_NUMBER = 6; private java.util.List<java.lang.Integer> type_; private static final com.google.protobuf.Internal.ListAdapter.Converter< java.lang.Integer, org.tensorflow.proto.framework.DataType> type_converter_ = new com.google.protobuf.Internal.ListAdapter.Converter< java.lang.Integer, org.tensorflow.proto.framework.DataType>() { public org.tensorflow.proto.framework.DataType convert(java.lang.Integer from) { @SuppressWarnings("deprecation") org.tensorflow.proto.framework.DataType result = org.tensorflow.proto.framework.DataType.valueOf(from); return result == null ? org.tensorflow.proto.framework.DataType.UNRECOGNIZED : result; } }; /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public java.util.List<org.tensorflow.proto.framework.DataType> getTypeList() { return new com.google.protobuf.Internal.ListAdapter< java.lang.Integer, org.tensorflow.proto.framework.DataType>(type_, type_converter_); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public int getTypeCount() { return type_.size(); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public org.tensorflow.proto.framework.DataType getType(int index) { return type_converter_.convert(type_.get(index)); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public java.util.List<java.lang.Integer> getTypeValueList() { return type_; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public int getTypeValue(int index) { return type_.get(index); } private int typeMemoizedSerializedSize; public static final int SHAPE_FIELD_NUMBER = 7; private java.util.List<org.tensorflow.proto.framework.TensorShapeProto> shape_; /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public java.util.List<org.tensorflow.proto.framework.TensorShapeProto> getShapeList() { return shape_; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public java.util.List<? extends org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> getShapeOrBuilderList() { return shape_; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public int getShapeCount() { return shape_.size(); } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto getShape(int index) { return shape_.get(index); } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProtoOrBuilder getShapeOrBuilder( int index) { return shape_.get(index); } public static final int TENSOR_FIELD_NUMBER = 8; private java.util.List<org.tensorflow.proto.framework.TensorProto> tensor_; /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public java.util.List<org.tensorflow.proto.framework.TensorProto> getTensorList() { return tensor_; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public java.util.List<? extends org.tensorflow.proto.framework.TensorProtoOrBuilder> getTensorOrBuilderList() { return tensor_; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public int getTensorCount() { return tensor_.size(); } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto getTensor(int index) { return tensor_.get(index); } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProtoOrBuilder getTensorOrBuilder( int index) { return tensor_.get(index); } public static final int FUNC_FIELD_NUMBER = 9; private java.util.List<org.tensorflow.proto.framework.NameAttrList> func_; /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public java.util.List<org.tensorflow.proto.framework.NameAttrList> getFuncList() { return func_; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public java.util.List<? extends org.tensorflow.proto.framework.NameAttrListOrBuilder> getFuncOrBuilderList() { return func_; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public int getFuncCount() { return func_.size(); } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrList getFunc(int index) { return func_.get(index); } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrListOrBuilder getFuncOrBuilder( int index) { return func_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (int i = 0; i < s_.size(); i++) { output.writeBytes(2, s_.get(i)); } if (getIList().size() > 0) { output.writeUInt32NoTag(26); output.writeUInt32NoTag(iMemoizedSerializedSize); } for (int i = 0; i < i_.size(); i++) { output.writeInt64NoTag(i_.getLong(i)); } if (getFList().size() > 0) { output.writeUInt32NoTag(34); output.writeUInt32NoTag(fMemoizedSerializedSize); } for (int i = 0; i < f_.size(); i++) { output.writeFloatNoTag(f_.getFloat(i)); } if (getBList().size() > 0) { output.writeUInt32NoTag(42); output.writeUInt32NoTag(bMemoizedSerializedSize); } for (int i = 0; i < b_.size(); i++) { output.writeBoolNoTag(b_.getBoolean(i)); } if (getTypeList().size() > 0) { output.writeUInt32NoTag(50); output.writeUInt32NoTag(typeMemoizedSerializedSize); } for (int i = 0; i < type_.size(); i++) { output.writeEnumNoTag(type_.get(i)); } for (int i = 0; i < shape_.size(); i++) { output.writeMessage(7, shape_.get(i)); } for (int i = 0; i < tensor_.size(); i++) { output.writeMessage(8, tensor_.get(i)); } for (int i = 0; i < func_.size(); i++) { output.writeMessage(9, func_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < s_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(s_.get(i)); } size += dataSize; size += 1 * getSList().size(); } { int dataSize = 0; for (int i = 0; i < i_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeInt64SizeNoTag(i_.getLong(i)); } size += dataSize; if (!getIList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(dataSize); } iMemoizedSerializedSize = dataSize; } { int dataSize = 0; dataSize = 4 * getFList().size(); size += dataSize; if (!getFList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(dataSize); } fMemoizedSerializedSize = dataSize; } { int dataSize = 0; dataSize = 1 * getBList().size(); size += dataSize; if (!getBList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(dataSize); } bMemoizedSerializedSize = dataSize; } { int dataSize = 0; for (int i = 0; i < type_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeEnumSizeNoTag(type_.get(i)); } size += dataSize; if (!getTypeList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream .computeUInt32SizeNoTag(dataSize); }typeMemoizedSerializedSize = dataSize; } for (int i = 0; i < shape_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, shape_.get(i)); } for (int i = 0; i < tensor_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, tensor_.get(i)); } for (int i = 0; i < func_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(9, func_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.tensorflow.proto.framework.AttrValue.ListValue)) { return super.equals(obj); } org.tensorflow.proto.framework.AttrValue.ListValue other = (org.tensorflow.proto.framework.AttrValue.ListValue) obj; if (!getSList() .equals(other.getSList())) return false; if (!getIList() .equals(other.getIList())) return false; if (!getFList() .equals(other.getFList())) return false; if (!getBList() .equals(other.getBList())) return false; if (!type_.equals(other.type_)) return false; if (!getShapeList() .equals(other.getShapeList())) return false; if (!getTensorList() .equals(other.getTensorList())) return false; if (!getFuncList() .equals(other.getFuncList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getSCount() > 0) { hash = (37 * hash) + S_FIELD_NUMBER; hash = (53 * hash) + getSList().hashCode(); } if (getICount() > 0) { hash = (37 * hash) + I_FIELD_NUMBER; hash = (53 * hash) + getIList().hashCode(); } if (getFCount() > 0) { hash = (37 * hash) + F_FIELD_NUMBER; hash = (53 * hash) + getFList().hashCode(); } if (getBCount() > 0) { hash = (37 * hash) + B_FIELD_NUMBER; hash = (53 * hash) + getBList().hashCode(); } if (getTypeCount() > 0) { hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_.hashCode(); } if (getShapeCount() > 0) { hash = (37 * hash) + SHAPE_FIELD_NUMBER; hash = (53 * hash) + getShapeList().hashCode(); } if (getTensorCount() > 0) { hash = (37 * hash) + TENSOR_FIELD_NUMBER; hash = (53 * hash) + getTensorList().hashCode(); } if (getFuncCount() > 0) { hash = (37 * hash) + FUNC_FIELD_NUMBER; hash = (53 * hash) + getFuncList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.proto.framework.AttrValue.ListValue parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(org.tensorflow.proto.framework.AttrValue.ListValue prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * LINT.IfChange * </pre> * * Protobuf type {@code tensorflow.AttrValue.ListValue} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tensorflow.AttrValue.ListValue) org.tensorflow.proto.framework.AttrValue.ListValueOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_ListValue_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_ListValue_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.proto.framework.AttrValue.ListValue.class, org.tensorflow.proto.framework.AttrValue.ListValue.Builder.class); } // Construct using org.tensorflow.proto.framework.AttrValue.ListValue.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getShapeFieldBuilder(); getTensorFieldBuilder(); getFuncFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); s_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); i_ = emptyLongList(); bitField0_ = (bitField0_ & ~0x00000002); f_ = emptyFloatList(); bitField0_ = (bitField0_ & ~0x00000004); b_ = emptyBooleanList(); bitField0_ = (bitField0_ & ~0x00000008); type_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); if (shapeBuilder_ == null) { shape_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { shapeBuilder_.clear(); } if (tensorBuilder_ == null) { tensor_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); } else { tensorBuilder_.clear(); } if (funcBuilder_ == null) { func_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); } else { funcBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_ListValue_descriptor; } @java.lang.Override public org.tensorflow.proto.framework.AttrValue.ListValue getDefaultInstanceForType() { return org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } @java.lang.Override public org.tensorflow.proto.framework.AttrValue.ListValue build() { org.tensorflow.proto.framework.AttrValue.ListValue result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public org.tensorflow.proto.framework.AttrValue.ListValue buildPartial() { org.tensorflow.proto.framework.AttrValue.ListValue result = new org.tensorflow.proto.framework.AttrValue.ListValue(this); int from_bitField0_ = bitField0_; if (((bitField0_ & 0x00000001) != 0)) { s_ = java.util.Collections.unmodifiableList(s_); bitField0_ = (bitField0_ & ~0x00000001); } result.s_ = s_; if (((bitField0_ & 0x00000002) != 0)) { i_.makeImmutable(); bitField0_ = (bitField0_ & ~0x00000002); } result.i_ = i_; if (((bitField0_ & 0x00000004) != 0)) { f_.makeImmutable(); bitField0_ = (bitField0_ & ~0x00000004); } result.f_ = f_; if (((bitField0_ & 0x00000008) != 0)) { b_.makeImmutable(); bitField0_ = (bitField0_ & ~0x00000008); } result.b_ = b_; if (((bitField0_ & 0x00000010) != 0)) { type_ = java.util.Collections.unmodifiableList(type_); bitField0_ = (bitField0_ & ~0x00000010); } result.type_ = type_; if (shapeBuilder_ == null) { if (((bitField0_ & 0x00000020) != 0)) { shape_ = java.util.Collections.unmodifiableList(shape_); bitField0_ = (bitField0_ & ~0x00000020); } result.shape_ = shape_; } else { result.shape_ = shapeBuilder_.build(); } if (tensorBuilder_ == null) { if (((bitField0_ & 0x00000040) != 0)) { tensor_ = java.util.Collections.unmodifiableList(tensor_); bitField0_ = (bitField0_ & ~0x00000040); } result.tensor_ = tensor_; } else { result.tensor_ = tensorBuilder_.build(); } if (funcBuilder_ == null) { if (((bitField0_ & 0x00000080) != 0)) { func_ = java.util.Collections.unmodifiableList(func_); bitField0_ = (bitField0_ & ~0x00000080); } result.func_ = func_; } else { result.func_ = funcBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.tensorflow.proto.framework.AttrValue.ListValue) { return mergeFrom((org.tensorflow.proto.framework.AttrValue.ListValue)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.tensorflow.proto.framework.AttrValue.ListValue other) { if (other == org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance()) return this; if (!other.s_.isEmpty()) { if (s_.isEmpty()) { s_ = other.s_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSIsMutable(); s_.addAll(other.s_); } onChanged(); } if (!other.i_.isEmpty()) { if (i_.isEmpty()) { i_ = other.i_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureIIsMutable(); i_.addAll(other.i_); } onChanged(); } if (!other.f_.isEmpty()) { if (f_.isEmpty()) { f_ = other.f_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureFIsMutable(); f_.addAll(other.f_); } onChanged(); } if (!other.b_.isEmpty()) { if (b_.isEmpty()) { b_ = other.b_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureBIsMutable(); b_.addAll(other.b_); } onChanged(); } if (!other.type_.isEmpty()) { if (type_.isEmpty()) { type_ = other.type_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureTypeIsMutable(); type_.addAll(other.type_); } onChanged(); } if (shapeBuilder_ == null) { if (!other.shape_.isEmpty()) { if (shape_.isEmpty()) { shape_ = other.shape_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensureShapeIsMutable(); shape_.addAll(other.shape_); } onChanged(); } } else { if (!other.shape_.isEmpty()) { if (shapeBuilder_.isEmpty()) { shapeBuilder_.dispose(); shapeBuilder_ = null; shape_ = other.shape_; bitField0_ = (bitField0_ & ~0x00000020); shapeBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getShapeFieldBuilder() : null; } else { shapeBuilder_.addAllMessages(other.shape_); } } } if (tensorBuilder_ == null) { if (!other.tensor_.isEmpty()) { if (tensor_.isEmpty()) { tensor_ = other.tensor_; bitField0_ = (bitField0_ & ~0x00000040); } else { ensureTensorIsMutable(); tensor_.addAll(other.tensor_); } onChanged(); } } else { if (!other.tensor_.isEmpty()) { if (tensorBuilder_.isEmpty()) { tensorBuilder_.dispose(); tensorBuilder_ = null; tensor_ = other.tensor_; bitField0_ = (bitField0_ & ~0x00000040); tensorBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTensorFieldBuilder() : null; } else { tensorBuilder_.addAllMessages(other.tensor_); } } } if (funcBuilder_ == null) { if (!other.func_.isEmpty()) { if (func_.isEmpty()) { func_ = other.func_; bitField0_ = (bitField0_ & ~0x00000080); } else { ensureFuncIsMutable(); func_.addAll(other.func_); } onChanged(); } } else { if (!other.func_.isEmpty()) { if (funcBuilder_.isEmpty()) { funcBuilder_.dispose(); funcBuilder_ = null; func_ = other.func_; bitField0_ = (bitField0_ & ~0x00000080); funcBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getFuncFieldBuilder() : null; } else { funcBuilder_.addAllMessages(other.func_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.tensorflow.proto.framework.AttrValue.ListValue parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.tensorflow.proto.framework.AttrValue.ListValue) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.protobuf.ByteString> s_ = java.util.Collections.emptyList(); private void ensureSIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { s_ = new java.util.ArrayList<com.google.protobuf.ByteString>(s_); bitField0_ |= 0x00000001; } } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public java.util.List<com.google.protobuf.ByteString> getSList() { return ((bitField0_ & 0x00000001) != 0) ? java.util.Collections.unmodifiableList(s_) : s_; } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public int getSCount() { return s_.size(); } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public com.google.protobuf.ByteString getS(int index) { return s_.get(index); } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public Builder setS( int index, com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureSIsMutable(); s_.set(index, value); onChanged(); return this; } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public Builder addS(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureSIsMutable(); s_.add(value); onChanged(); return this; } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public Builder addAllS( java.lang.Iterable<? extends com.google.protobuf.ByteString> values) { ensureSIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, s_); onChanged(); return this; } /** * <pre> * "list(string)" * </pre> * * <code>repeated bytes s = 2;</code> */ public Builder clearS() { s_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } private com.google.protobuf.Internal.LongList i_ = emptyLongList(); private void ensureIIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { i_ = mutableCopy(i_); bitField0_ |= 0x00000002; } } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public java.util.List<java.lang.Long> getIList() { return ((bitField0_ & 0x00000002) != 0) ? java.util.Collections.unmodifiableList(i_) : i_; } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public int getICount() { return i_.size(); } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public long getI(int index) { return i_.getLong(index); } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public Builder setI( int index, long value) { ensureIIsMutable(); i_.setLong(index, value); onChanged(); return this; } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public Builder addI(long value) { ensureIIsMutable(); i_.addLong(value); onChanged(); return this; } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public Builder addAllI( java.lang.Iterable<? extends java.lang.Long> values) { ensureIIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, i_); onChanged(); return this; } /** * <pre> * "list(int)" * </pre> * * <code>repeated int64 i = 3 [packed = true];</code> */ public Builder clearI() { i_ = emptyLongList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } private com.google.protobuf.Internal.FloatList f_ = emptyFloatList(); private void ensureFIsMutable() { if (!((bitField0_ & 0x00000004) != 0)) { f_ = mutableCopy(f_); bitField0_ |= 0x00000004; } } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public java.util.List<java.lang.Float> getFList() { return ((bitField0_ & 0x00000004) != 0) ? java.util.Collections.unmodifiableList(f_) : f_; } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public int getFCount() { return f_.size(); } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public float getF(int index) { return f_.getFloat(index); } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public Builder setF( int index, float value) { ensureFIsMutable(); f_.setFloat(index, value); onChanged(); return this; } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public Builder addF(float value) { ensureFIsMutable(); f_.addFloat(value); onChanged(); return this; } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public Builder addAllF( java.lang.Iterable<? extends java.lang.Float> values) { ensureFIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, f_); onChanged(); return this; } /** * <pre> * "list(float)" * </pre> * * <code>repeated float f = 4 [packed = true];</code> */ public Builder clearF() { f_ = emptyFloatList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } private com.google.protobuf.Internal.BooleanList b_ = emptyBooleanList(); private void ensureBIsMutable() { if (!((bitField0_ & 0x00000008) != 0)) { b_ = mutableCopy(b_); bitField0_ |= 0x00000008; } } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public java.util.List<java.lang.Boolean> getBList() { return ((bitField0_ & 0x00000008) != 0) ? java.util.Collections.unmodifiableList(b_) : b_; } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public int getBCount() { return b_.size(); } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public boolean getB(int index) { return b_.getBoolean(index); } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public Builder setB( int index, boolean value) { ensureBIsMutable(); b_.setBoolean(index, value); onChanged(); return this; } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public Builder addB(boolean value) { ensureBIsMutable(); b_.addBoolean(value); onChanged(); return this; } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public Builder addAllB( java.lang.Iterable<? extends java.lang.Boolean> values) { ensureBIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, b_); onChanged(); return this; } /** * <pre> * "list(bool)" * </pre> * * <code>repeated bool b = 5 [packed = true];</code> */ public Builder clearB() { b_ = emptyBooleanList(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } private java.util.List<java.lang.Integer> type_ = java.util.Collections.emptyList(); private void ensureTypeIsMutable() { if (!((bitField0_ & 0x00000010) != 0)) { type_ = new java.util.ArrayList<java.lang.Integer>(type_); bitField0_ |= 0x00000010; } } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public java.util.List<org.tensorflow.proto.framework.DataType> getTypeList() { return new com.google.protobuf.Internal.ListAdapter< java.lang.Integer, org.tensorflow.proto.framework.DataType>(type_, type_converter_); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public int getTypeCount() { return type_.size(); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public org.tensorflow.proto.framework.DataType getType(int index) { return type_converter_.convert(type_.get(index)); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder setType( int index, org.tensorflow.proto.framework.DataType value) { if (value == null) { throw new NullPointerException(); } ensureTypeIsMutable(); type_.set(index, value.getNumber()); onChanged(); return this; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder addType(org.tensorflow.proto.framework.DataType value) { if (value == null) { throw new NullPointerException(); } ensureTypeIsMutable(); type_.add(value.getNumber()); onChanged(); return this; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder addAllType( java.lang.Iterable<? extends org.tensorflow.proto.framework.DataType> values) { ensureTypeIsMutable(); for (org.tensorflow.proto.framework.DataType value : values) { type_.add(value.getNumber()); } onChanged(); return this; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder clearType() { type_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public java.util.List<java.lang.Integer> getTypeValueList() { return java.util.Collections.unmodifiableList(type_); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public int getTypeValue(int index) { return type_.get(index); } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder setTypeValue( int index, int value) { ensureTypeIsMutable(); type_.set(index, value); onChanged(); return this; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder addTypeValue(int value) { ensureTypeIsMutable(); type_.add(value); onChanged(); return this; } /** * <pre> * "list(type)" * </pre> * * <code>repeated .tensorflow.DataType type = 6 [packed = true];</code> */ public Builder addAllTypeValue( java.lang.Iterable<java.lang.Integer> values) { ensureTypeIsMutable(); for (int value : values) { type_.add(value); } onChanged(); return this; } private java.util.List<org.tensorflow.proto.framework.TensorShapeProto> shape_ = java.util.Collections.emptyList(); private void ensureShapeIsMutable() { if (!((bitField0_ & 0x00000020) != 0)) { shape_ = new java.util.ArrayList<org.tensorflow.proto.framework.TensorShapeProto>(shape_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.TensorShapeProto, org.tensorflow.proto.framework.TensorShapeProto.Builder, org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> shapeBuilder_; /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public java.util.List<org.tensorflow.proto.framework.TensorShapeProto> getShapeList() { if (shapeBuilder_ == null) { return java.util.Collections.unmodifiableList(shape_); } else { return shapeBuilder_.getMessageList(); } } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public int getShapeCount() { if (shapeBuilder_ == null) { return shape_.size(); } else { return shapeBuilder_.getCount(); } } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto getShape(int index) { if (shapeBuilder_ == null) { return shape_.get(index); } else { return shapeBuilder_.getMessage(index); } } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder setShape( int index, org.tensorflow.proto.framework.TensorShapeProto value) { if (shapeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureShapeIsMutable(); shape_.set(index, value); onChanged(); } else { shapeBuilder_.setMessage(index, value); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder setShape( int index, org.tensorflow.proto.framework.TensorShapeProto.Builder builderForValue) { if (shapeBuilder_ == null) { ensureShapeIsMutable(); shape_.set(index, builderForValue.build()); onChanged(); } else { shapeBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder addShape(org.tensorflow.proto.framework.TensorShapeProto value) { if (shapeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureShapeIsMutable(); shape_.add(value); onChanged(); } else { shapeBuilder_.addMessage(value); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder addShape( int index, org.tensorflow.proto.framework.TensorShapeProto value) { if (shapeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureShapeIsMutable(); shape_.add(index, value); onChanged(); } else { shapeBuilder_.addMessage(index, value); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder addShape( org.tensorflow.proto.framework.TensorShapeProto.Builder builderForValue) { if (shapeBuilder_ == null) { ensureShapeIsMutable(); shape_.add(builderForValue.build()); onChanged(); } else { shapeBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder addShape( int index, org.tensorflow.proto.framework.TensorShapeProto.Builder builderForValue) { if (shapeBuilder_ == null) { ensureShapeIsMutable(); shape_.add(index, builderForValue.build()); onChanged(); } else { shapeBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder addAllShape( java.lang.Iterable<? extends org.tensorflow.proto.framework.TensorShapeProto> values) { if (shapeBuilder_ == null) { ensureShapeIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, shape_); onChanged(); } else { shapeBuilder_.addAllMessages(values); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder clearShape() { if (shapeBuilder_ == null) { shape_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { shapeBuilder_.clear(); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public Builder removeShape(int index) { if (shapeBuilder_ == null) { ensureShapeIsMutable(); shape_.remove(index); onChanged(); } else { shapeBuilder_.remove(index); } return this; } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto.Builder getShapeBuilder( int index) { return getShapeFieldBuilder().getBuilder(index); } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProtoOrBuilder getShapeOrBuilder( int index) { if (shapeBuilder_ == null) { return shape_.get(index); } else { return shapeBuilder_.getMessageOrBuilder(index); } } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public java.util.List<? extends org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> getShapeOrBuilderList() { if (shapeBuilder_ != null) { return shapeBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(shape_); } } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto.Builder addShapeBuilder() { return getShapeFieldBuilder().addBuilder( org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance()); } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto.Builder addShapeBuilder( int index) { return getShapeFieldBuilder().addBuilder( index, org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance()); } /** * <pre> * "list(shape)" * </pre> * * <code>repeated .tensorflow.TensorShapeProto shape = 7;</code> */ public java.util.List<org.tensorflow.proto.framework.TensorShapeProto.Builder> getShapeBuilderList() { return getShapeFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.TensorShapeProto, org.tensorflow.proto.framework.TensorShapeProto.Builder, org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> getShapeFieldBuilder() { if (shapeBuilder_ == null) { shapeBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.TensorShapeProto, org.tensorflow.proto.framework.TensorShapeProto.Builder, org.tensorflow.proto.framework.TensorShapeProtoOrBuilder>( shape_, ((bitField0_ & 0x00000020) != 0), getParentForChildren(), isClean()); shape_ = null; } return shapeBuilder_; } private java.util.List<org.tensorflow.proto.framework.TensorProto> tensor_ = java.util.Collections.emptyList(); private void ensureTensorIsMutable() { if (!((bitField0_ & 0x00000040) != 0)) { tensor_ = new java.util.ArrayList<org.tensorflow.proto.framework.TensorProto>(tensor_); bitField0_ |= 0x00000040; } } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.TensorProto, org.tensorflow.proto.framework.TensorProto.Builder, org.tensorflow.proto.framework.TensorProtoOrBuilder> tensorBuilder_; /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public java.util.List<org.tensorflow.proto.framework.TensorProto> getTensorList() { if (tensorBuilder_ == null) { return java.util.Collections.unmodifiableList(tensor_); } else { return tensorBuilder_.getMessageList(); } } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public int getTensorCount() { if (tensorBuilder_ == null) { return tensor_.size(); } else { return tensorBuilder_.getCount(); } } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto getTensor(int index) { if (tensorBuilder_ == null) { return tensor_.get(index); } else { return tensorBuilder_.getMessage(index); } } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder setTensor( int index, org.tensorflow.proto.framework.TensorProto value) { if (tensorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTensorIsMutable(); tensor_.set(index, value); onChanged(); } else { tensorBuilder_.setMessage(index, value); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder setTensor( int index, org.tensorflow.proto.framework.TensorProto.Builder builderForValue) { if (tensorBuilder_ == null) { ensureTensorIsMutable(); tensor_.set(index, builderForValue.build()); onChanged(); } else { tensorBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder addTensor(org.tensorflow.proto.framework.TensorProto value) { if (tensorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTensorIsMutable(); tensor_.add(value); onChanged(); } else { tensorBuilder_.addMessage(value); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder addTensor( int index, org.tensorflow.proto.framework.TensorProto value) { if (tensorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTensorIsMutable(); tensor_.add(index, value); onChanged(); } else { tensorBuilder_.addMessage(index, value); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder addTensor( org.tensorflow.proto.framework.TensorProto.Builder builderForValue) { if (tensorBuilder_ == null) { ensureTensorIsMutable(); tensor_.add(builderForValue.build()); onChanged(); } else { tensorBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder addTensor( int index, org.tensorflow.proto.framework.TensorProto.Builder builderForValue) { if (tensorBuilder_ == null) { ensureTensorIsMutable(); tensor_.add(index, builderForValue.build()); onChanged(); } else { tensorBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder addAllTensor( java.lang.Iterable<? extends org.tensorflow.proto.framework.TensorProto> values) { if (tensorBuilder_ == null) { ensureTensorIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, tensor_); onChanged(); } else { tensorBuilder_.addAllMessages(values); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder clearTensor() { if (tensorBuilder_ == null) { tensor_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); onChanged(); } else { tensorBuilder_.clear(); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public Builder removeTensor(int index) { if (tensorBuilder_ == null) { ensureTensorIsMutable(); tensor_.remove(index); onChanged(); } else { tensorBuilder_.remove(index); } return this; } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto.Builder getTensorBuilder( int index) { return getTensorFieldBuilder().getBuilder(index); } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProtoOrBuilder getTensorOrBuilder( int index) { if (tensorBuilder_ == null) { return tensor_.get(index); } else { return tensorBuilder_.getMessageOrBuilder(index); } } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public java.util.List<? extends org.tensorflow.proto.framework.TensorProtoOrBuilder> getTensorOrBuilderList() { if (tensorBuilder_ != null) { return tensorBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(tensor_); } } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto.Builder addTensorBuilder() { return getTensorFieldBuilder().addBuilder( org.tensorflow.proto.framework.TensorProto.getDefaultInstance()); } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto.Builder addTensorBuilder( int index) { return getTensorFieldBuilder().addBuilder( index, org.tensorflow.proto.framework.TensorProto.getDefaultInstance()); } /** * <pre> * "list(tensor)" * </pre> * * <code>repeated .tensorflow.TensorProto tensor = 8;</code> */ public java.util.List<org.tensorflow.proto.framework.TensorProto.Builder> getTensorBuilderList() { return getTensorFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.TensorProto, org.tensorflow.proto.framework.TensorProto.Builder, org.tensorflow.proto.framework.TensorProtoOrBuilder> getTensorFieldBuilder() { if (tensorBuilder_ == null) { tensorBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.TensorProto, org.tensorflow.proto.framework.TensorProto.Builder, org.tensorflow.proto.framework.TensorProtoOrBuilder>( tensor_, ((bitField0_ & 0x00000040) != 0), getParentForChildren(), isClean()); tensor_ = null; } return tensorBuilder_; } private java.util.List<org.tensorflow.proto.framework.NameAttrList> func_ = java.util.Collections.emptyList(); private void ensureFuncIsMutable() { if (!((bitField0_ & 0x00000080) != 0)) { func_ = new java.util.ArrayList<org.tensorflow.proto.framework.NameAttrList>(func_); bitField0_ |= 0x00000080; } } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.NameAttrList, org.tensorflow.proto.framework.NameAttrList.Builder, org.tensorflow.proto.framework.NameAttrListOrBuilder> funcBuilder_; /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public java.util.List<org.tensorflow.proto.framework.NameAttrList> getFuncList() { if (funcBuilder_ == null) { return java.util.Collections.unmodifiableList(func_); } else { return funcBuilder_.getMessageList(); } } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public int getFuncCount() { if (funcBuilder_ == null) { return func_.size(); } else { return funcBuilder_.getCount(); } } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrList getFunc(int index) { if (funcBuilder_ == null) { return func_.get(index); } else { return funcBuilder_.getMessage(index); } } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder setFunc( int index, org.tensorflow.proto.framework.NameAttrList value) { if (funcBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFuncIsMutable(); func_.set(index, value); onChanged(); } else { funcBuilder_.setMessage(index, value); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder setFunc( int index, org.tensorflow.proto.framework.NameAttrList.Builder builderForValue) { if (funcBuilder_ == null) { ensureFuncIsMutable(); func_.set(index, builderForValue.build()); onChanged(); } else { funcBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder addFunc(org.tensorflow.proto.framework.NameAttrList value) { if (funcBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFuncIsMutable(); func_.add(value); onChanged(); } else { funcBuilder_.addMessage(value); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder addFunc( int index, org.tensorflow.proto.framework.NameAttrList value) { if (funcBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFuncIsMutable(); func_.add(index, value); onChanged(); } else { funcBuilder_.addMessage(index, value); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder addFunc( org.tensorflow.proto.framework.NameAttrList.Builder builderForValue) { if (funcBuilder_ == null) { ensureFuncIsMutable(); func_.add(builderForValue.build()); onChanged(); } else { funcBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder addFunc( int index, org.tensorflow.proto.framework.NameAttrList.Builder builderForValue) { if (funcBuilder_ == null) { ensureFuncIsMutable(); func_.add(index, builderForValue.build()); onChanged(); } else { funcBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder addAllFunc( java.lang.Iterable<? extends org.tensorflow.proto.framework.NameAttrList> values) { if (funcBuilder_ == null) { ensureFuncIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, func_); onChanged(); } else { funcBuilder_.addAllMessages(values); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder clearFunc() { if (funcBuilder_ == null) { func_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); onChanged(); } else { funcBuilder_.clear(); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public Builder removeFunc(int index) { if (funcBuilder_ == null) { ensureFuncIsMutable(); func_.remove(index); onChanged(); } else { funcBuilder_.remove(index); } return this; } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrList.Builder getFuncBuilder( int index) { return getFuncFieldBuilder().getBuilder(index); } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrListOrBuilder getFuncOrBuilder( int index) { if (funcBuilder_ == null) { return func_.get(index); } else { return funcBuilder_.getMessageOrBuilder(index); } } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public java.util.List<? extends org.tensorflow.proto.framework.NameAttrListOrBuilder> getFuncOrBuilderList() { if (funcBuilder_ != null) { return funcBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(func_); } } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrList.Builder addFuncBuilder() { return getFuncFieldBuilder().addBuilder( org.tensorflow.proto.framework.NameAttrList.getDefaultInstance()); } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public org.tensorflow.proto.framework.NameAttrList.Builder addFuncBuilder( int index) { return getFuncFieldBuilder().addBuilder( index, org.tensorflow.proto.framework.NameAttrList.getDefaultInstance()); } /** * <pre> * "list(attr)" * </pre> * * <code>repeated .tensorflow.NameAttrList func = 9;</code> */ public java.util.List<org.tensorflow.proto.framework.NameAttrList.Builder> getFuncBuilderList() { return getFuncFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.NameAttrList, org.tensorflow.proto.framework.NameAttrList.Builder, org.tensorflow.proto.framework.NameAttrListOrBuilder> getFuncFieldBuilder() { if (funcBuilder_ == null) { funcBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< org.tensorflow.proto.framework.NameAttrList, org.tensorflow.proto.framework.NameAttrList.Builder, org.tensorflow.proto.framework.NameAttrListOrBuilder>( func_, ((bitField0_ & 0x00000080) != 0), getParentForChildren(), isClean()); func_ = null; } return funcBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:tensorflow.AttrValue.ListValue) } // @@protoc_insertion_point(class_scope:tensorflow.AttrValue.ListValue) private static final org.tensorflow.proto.framework.AttrValue.ListValue DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.tensorflow.proto.framework.AttrValue.ListValue(); } public static org.tensorflow.proto.framework.AttrValue.ListValue getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListValue> PARSER = new com.google.protobuf.AbstractParser<ListValue>() { @java.lang.Override public ListValue parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListValue(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListValue> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListValue> getParserForType() { return PARSER; } @java.lang.Override public org.tensorflow.proto.framework.AttrValue.ListValue getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private int valueCase_ = 0; private java.lang.Object value_; public enum ValueCase implements com.google.protobuf.Internal.EnumLite { S(2), I(3), F(4), B(5), TYPE(6), SHAPE(7), TENSOR(8), LIST(1), FUNC(10), PLACEHOLDER(9), VALUE_NOT_SET(0); private final int value; private ValueCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ValueCase valueOf(int value) { return forNumber(value); } public static ValueCase forNumber(int value) { switch (value) { case 2: return S; case 3: return I; case 4: return F; case 5: return B; case 6: return TYPE; case 7: return SHAPE; case 8: return TENSOR; case 1: return LIST; case 10: return FUNC; case 9: return PLACEHOLDER; case 0: return VALUE_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ValueCase getValueCase() { return ValueCase.forNumber( valueCase_); } public static final int S_FIELD_NUMBER = 2; /** * <pre> * "string" * </pre> * * <code>bytes s = 2;</code> */ public com.google.protobuf.ByteString getS() { if (valueCase_ == 2) { return (com.google.protobuf.ByteString) value_; } return com.google.protobuf.ByteString.EMPTY; } public static final int I_FIELD_NUMBER = 3; /** * <pre> * "int" * </pre> * * <code>int64 i = 3;</code> */ public long getI() { if (valueCase_ == 3) { return (java.lang.Long) value_; } return 0L; } public static final int F_FIELD_NUMBER = 4; /** * <pre> * "float" * </pre> * * <code>float f = 4;</code> */ public float getF() { if (valueCase_ == 4) { return (java.lang.Float) value_; } return 0F; } public static final int B_FIELD_NUMBER = 5; /** * <pre> * "bool" * </pre> * * <code>bool b = 5;</code> */ public boolean getB() { if (valueCase_ == 5) { return (java.lang.Boolean) value_; } return false; } public static final int TYPE_FIELD_NUMBER = 6; /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public int getTypeValue() { if (valueCase_ == 6) { return (java.lang.Integer) value_; } return 0; } /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public org.tensorflow.proto.framework.DataType getType() { if (valueCase_ == 6) { @SuppressWarnings("deprecation") org.tensorflow.proto.framework.DataType result = org.tensorflow.proto.framework.DataType.valueOf( (java.lang.Integer) value_); return result == null ? org.tensorflow.proto.framework.DataType.UNRECOGNIZED : result; } return org.tensorflow.proto.framework.DataType.DT_INVALID; } public static final int SHAPE_FIELD_NUMBER = 7; /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public boolean hasShape() { return valueCase_ == 7; } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto getShape() { if (valueCase_ == 7) { return (org.tensorflow.proto.framework.TensorShapeProto) value_; } return org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance(); } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProtoOrBuilder getShapeOrBuilder() { if (valueCase_ == 7) { return (org.tensorflow.proto.framework.TensorShapeProto) value_; } return org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance(); } public static final int TENSOR_FIELD_NUMBER = 8; /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public boolean hasTensor() { return valueCase_ == 8; } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto getTensor() { if (valueCase_ == 8) { return (org.tensorflow.proto.framework.TensorProto) value_; } return org.tensorflow.proto.framework.TensorProto.getDefaultInstance(); } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProtoOrBuilder getTensorOrBuilder() { if (valueCase_ == 8) { return (org.tensorflow.proto.framework.TensorProto) value_; } return org.tensorflow.proto.framework.TensorProto.getDefaultInstance(); } public static final int LIST_FIELD_NUMBER = 1; /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public boolean hasList() { return valueCase_ == 1; } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public org.tensorflow.proto.framework.AttrValue.ListValue getList() { if (valueCase_ == 1) { return (org.tensorflow.proto.framework.AttrValue.ListValue) value_; } return org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public org.tensorflow.proto.framework.AttrValue.ListValueOrBuilder getListOrBuilder() { if (valueCase_ == 1) { return (org.tensorflow.proto.framework.AttrValue.ListValue) value_; } return org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } public static final int FUNC_FIELD_NUMBER = 10; /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public boolean hasFunc() { return valueCase_ == 10; } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public org.tensorflow.proto.framework.NameAttrList getFunc() { if (valueCase_ == 10) { return (org.tensorflow.proto.framework.NameAttrList) value_; } return org.tensorflow.proto.framework.NameAttrList.getDefaultInstance(); } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public org.tensorflow.proto.framework.NameAttrListOrBuilder getFuncOrBuilder() { if (valueCase_ == 10) { return (org.tensorflow.proto.framework.NameAttrList) value_; } return org.tensorflow.proto.framework.NameAttrList.getDefaultInstance(); } public static final int PLACEHOLDER_FIELD_NUMBER = 9; /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public java.lang.String getPlaceholder() { java.lang.Object ref = ""; if (valueCase_ == 9) { ref = value_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (valueCase_ == 9) { value_ = s; } return s; } } /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public com.google.protobuf.ByteString getPlaceholderBytes() { java.lang.Object ref = ""; if (valueCase_ == 9) { ref = value_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (valueCase_ == 9) { value_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (valueCase_ == 1) { output.writeMessage(1, (org.tensorflow.proto.framework.AttrValue.ListValue) value_); } if (valueCase_ == 2) { output.writeBytes( 2, (com.google.protobuf.ByteString) value_); } if (valueCase_ == 3) { output.writeInt64( 3, (long)((java.lang.Long) value_)); } if (valueCase_ == 4) { output.writeFloat( 4, (float)((java.lang.Float) value_)); } if (valueCase_ == 5) { output.writeBool( 5, (boolean)((java.lang.Boolean) value_)); } if (valueCase_ == 6) { output.writeEnum(6, ((java.lang.Integer) value_)); } if (valueCase_ == 7) { output.writeMessage(7, (org.tensorflow.proto.framework.TensorShapeProto) value_); } if (valueCase_ == 8) { output.writeMessage(8, (org.tensorflow.proto.framework.TensorProto) value_); } if (valueCase_ == 9) { com.google.protobuf.GeneratedMessageV3.writeString(output, 9, value_); } if (valueCase_ == 10) { output.writeMessage(10, (org.tensorflow.proto.framework.NameAttrList) value_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (valueCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (org.tensorflow.proto.framework.AttrValue.ListValue) value_); } if (valueCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeBytesSize( 2, (com.google.protobuf.ByteString) value_); } if (valueCase_ == 3) { size += com.google.protobuf.CodedOutputStream .computeInt64Size( 3, (long)((java.lang.Long) value_)); } if (valueCase_ == 4) { size += com.google.protobuf.CodedOutputStream .computeFloatSize( 4, (float)((java.lang.Float) value_)); } if (valueCase_ == 5) { size += com.google.protobuf.CodedOutputStream .computeBoolSize( 5, (boolean)((java.lang.Boolean) value_)); } if (valueCase_ == 6) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(6, ((java.lang.Integer) value_)); } if (valueCase_ == 7) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, (org.tensorflow.proto.framework.TensorShapeProto) value_); } if (valueCase_ == 8) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, (org.tensorflow.proto.framework.TensorProto) value_); } if (valueCase_ == 9) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(9, value_); } if (valueCase_ == 10) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(10, (org.tensorflow.proto.framework.NameAttrList) value_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.tensorflow.proto.framework.AttrValue)) { return super.equals(obj); } org.tensorflow.proto.framework.AttrValue other = (org.tensorflow.proto.framework.AttrValue) obj; if (!getValueCase().equals(other.getValueCase())) return false; switch (valueCase_) { case 2: if (!getS() .equals(other.getS())) return false; break; case 3: if (getI() != other.getI()) return false; break; case 4: if (java.lang.Float.floatToIntBits(getF()) != java.lang.Float.floatToIntBits( other.getF())) return false; break; case 5: if (getB() != other.getB()) return false; break; case 6: if (getTypeValue() != other.getTypeValue()) return false; break; case 7: if (!getShape() .equals(other.getShape())) return false; break; case 8: if (!getTensor() .equals(other.getTensor())) return false; break; case 1: if (!getList() .equals(other.getList())) return false; break; case 10: if (!getFunc() .equals(other.getFunc())) return false; break; case 9: if (!getPlaceholder() .equals(other.getPlaceholder())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (valueCase_) { case 2: hash = (37 * hash) + S_FIELD_NUMBER; hash = (53 * hash) + getS().hashCode(); break; case 3: hash = (37 * hash) + I_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getI()); break; case 4: hash = (37 * hash) + F_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits( getF()); break; case 5: hash = (37 * hash) + B_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getB()); break; case 6: hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + getTypeValue(); break; case 7: hash = (37 * hash) + SHAPE_FIELD_NUMBER; hash = (53 * hash) + getShape().hashCode(); break; case 8: hash = (37 * hash) + TENSOR_FIELD_NUMBER; hash = (53 * hash) + getTensor().hashCode(); break; case 1: hash = (37 * hash) + LIST_FIELD_NUMBER; hash = (53 * hash) + getList().hashCode(); break; case 10: hash = (37 * hash) + FUNC_FIELD_NUMBER; hash = (53 * hash) + getFunc().hashCode(); break; case 9: hash = (37 * hash) + PLACEHOLDER_FIELD_NUMBER; hash = (53 * hash) + getPlaceholder().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static org.tensorflow.proto.framework.AttrValue parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.proto.framework.AttrValue parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.proto.framework.AttrValue parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tensorflow.proto.framework.AttrValue parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.proto.framework.AttrValue parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static org.tensorflow.proto.framework.AttrValue parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static org.tensorflow.proto.framework.AttrValue parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tensorflow.proto.framework.AttrValue parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(org.tensorflow.proto.framework.AttrValue prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Protocol buffer representing the value for an attr used to configure an Op. * Comment indicates the corresponding attr type. Only the field matching the * attr type may be filled. * </pre> * * Protobuf type {@code tensorflow.AttrValue} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tensorflow.AttrValue) org.tensorflow.proto.framework.AttrValueOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tensorflow.proto.framework.AttrValue.class, org.tensorflow.proto.framework.AttrValue.Builder.class); } // Construct using org.tensorflow.proto.framework.AttrValue.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); valueCase_ = 0; value_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.tensorflow.proto.framework.AttrValueProtos.internal_static_tensorflow_AttrValue_descriptor; } @java.lang.Override public org.tensorflow.proto.framework.AttrValue getDefaultInstanceForType() { return org.tensorflow.proto.framework.AttrValue.getDefaultInstance(); } @java.lang.Override public org.tensorflow.proto.framework.AttrValue build() { org.tensorflow.proto.framework.AttrValue result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public org.tensorflow.proto.framework.AttrValue buildPartial() { org.tensorflow.proto.framework.AttrValue result = new org.tensorflow.proto.framework.AttrValue(this); if (valueCase_ == 2) { result.value_ = value_; } if (valueCase_ == 3) { result.value_ = value_; } if (valueCase_ == 4) { result.value_ = value_; } if (valueCase_ == 5) { result.value_ = value_; } if (valueCase_ == 6) { result.value_ = value_; } if (valueCase_ == 7) { if (shapeBuilder_ == null) { result.value_ = value_; } else { result.value_ = shapeBuilder_.build(); } } if (valueCase_ == 8) { if (tensorBuilder_ == null) { result.value_ = value_; } else { result.value_ = tensorBuilder_.build(); } } if (valueCase_ == 1) { if (listBuilder_ == null) { result.value_ = value_; } else { result.value_ = listBuilder_.build(); } } if (valueCase_ == 10) { if (funcBuilder_ == null) { result.value_ = value_; } else { result.value_ = funcBuilder_.build(); } } if (valueCase_ == 9) { result.value_ = value_; } result.valueCase_ = valueCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.tensorflow.proto.framework.AttrValue) { return mergeFrom((org.tensorflow.proto.framework.AttrValue)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.tensorflow.proto.framework.AttrValue other) { if (other == org.tensorflow.proto.framework.AttrValue.getDefaultInstance()) return this; switch (other.getValueCase()) { case S: { setS(other.getS()); break; } case I: { setI(other.getI()); break; } case F: { setF(other.getF()); break; } case B: { setB(other.getB()); break; } case TYPE: { setTypeValue(other.getTypeValue()); break; } case SHAPE: { mergeShape(other.getShape()); break; } case TENSOR: { mergeTensor(other.getTensor()); break; } case LIST: { mergeList(other.getList()); break; } case FUNC: { mergeFunc(other.getFunc()); break; } case PLACEHOLDER: { valueCase_ = 9; value_ = other.value_; onChanged(); break; } case VALUE_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.tensorflow.proto.framework.AttrValue parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.tensorflow.proto.framework.AttrValue) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int valueCase_ = 0; private java.lang.Object value_; public ValueCase getValueCase() { return ValueCase.forNumber( valueCase_); } public Builder clearValue() { valueCase_ = 0; value_ = null; onChanged(); return this; } /** * <pre> * "string" * </pre> * * <code>bytes s = 2;</code> */ public com.google.protobuf.ByteString getS() { if (valueCase_ == 2) { return (com.google.protobuf.ByteString) value_; } return com.google.protobuf.ByteString.EMPTY; } /** * <pre> * "string" * </pre> * * <code>bytes s = 2;</code> */ public Builder setS(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } valueCase_ = 2; value_ = value; onChanged(); return this; } /** * <pre> * "string" * </pre> * * <code>bytes s = 2;</code> */ public Builder clearS() { if (valueCase_ == 2) { valueCase_ = 0; value_ = null; onChanged(); } return this; } /** * <pre> * "int" * </pre> * * <code>int64 i = 3;</code> */ public long getI() { if (valueCase_ == 3) { return (java.lang.Long) value_; } return 0L; } /** * <pre> * "int" * </pre> * * <code>int64 i = 3;</code> */ public Builder setI(long value) { valueCase_ = 3; value_ = value; onChanged(); return this; } /** * <pre> * "int" * </pre> * * <code>int64 i = 3;</code> */ public Builder clearI() { if (valueCase_ == 3) { valueCase_ = 0; value_ = null; onChanged(); } return this; } /** * <pre> * "float" * </pre> * * <code>float f = 4;</code> */ public float getF() { if (valueCase_ == 4) { return (java.lang.Float) value_; } return 0F; } /** * <pre> * "float" * </pre> * * <code>float f = 4;</code> */ public Builder setF(float value) { valueCase_ = 4; value_ = value; onChanged(); return this; } /** * <pre> * "float" * </pre> * * <code>float f = 4;</code> */ public Builder clearF() { if (valueCase_ == 4) { valueCase_ = 0; value_ = null; onChanged(); } return this; } /** * <pre> * "bool" * </pre> * * <code>bool b = 5;</code> */ public boolean getB() { if (valueCase_ == 5) { return (java.lang.Boolean) value_; } return false; } /** * <pre> * "bool" * </pre> * * <code>bool b = 5;</code> */ public Builder setB(boolean value) { valueCase_ = 5; value_ = value; onChanged(); return this; } /** * <pre> * "bool" * </pre> * * <code>bool b = 5;</code> */ public Builder clearB() { if (valueCase_ == 5) { valueCase_ = 0; value_ = null; onChanged(); } return this; } /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public int getTypeValue() { if (valueCase_ == 6) { return ((java.lang.Integer) value_).intValue(); } return 0; } /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public Builder setTypeValue(int value) { valueCase_ = 6; value_ = value; onChanged(); return this; } /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public org.tensorflow.proto.framework.DataType getType() { if (valueCase_ == 6) { @SuppressWarnings("deprecation") org.tensorflow.proto.framework.DataType result = org.tensorflow.proto.framework.DataType.valueOf( (java.lang.Integer) value_); return result == null ? org.tensorflow.proto.framework.DataType.UNRECOGNIZED : result; } return org.tensorflow.proto.framework.DataType.DT_INVALID; } /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public Builder setType(org.tensorflow.proto.framework.DataType value) { if (value == null) { throw new NullPointerException(); } valueCase_ = 6; value_ = value.getNumber(); onChanged(); return this; } /** * <pre> * "type" * </pre> * * <code>.tensorflow.DataType type = 6;</code> */ public Builder clearType() { if (valueCase_ == 6) { valueCase_ = 0; value_ = null; onChanged(); } return this; } private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.TensorShapeProto, org.tensorflow.proto.framework.TensorShapeProto.Builder, org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> shapeBuilder_; /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public boolean hasShape() { return valueCase_ == 7; } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto getShape() { if (shapeBuilder_ == null) { if (valueCase_ == 7) { return (org.tensorflow.proto.framework.TensorShapeProto) value_; } return org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance(); } else { if (valueCase_ == 7) { return shapeBuilder_.getMessage(); } return org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance(); } } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public Builder setShape(org.tensorflow.proto.framework.TensorShapeProto value) { if (shapeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } value_ = value; onChanged(); } else { shapeBuilder_.setMessage(value); } valueCase_ = 7; return this; } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public Builder setShape( org.tensorflow.proto.framework.TensorShapeProto.Builder builderForValue) { if (shapeBuilder_ == null) { value_ = builderForValue.build(); onChanged(); } else { shapeBuilder_.setMessage(builderForValue.build()); } valueCase_ = 7; return this; } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public Builder mergeShape(org.tensorflow.proto.framework.TensorShapeProto value) { if (shapeBuilder_ == null) { if (valueCase_ == 7 && value_ != org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance()) { value_ = org.tensorflow.proto.framework.TensorShapeProto.newBuilder((org.tensorflow.proto.framework.TensorShapeProto) value_) .mergeFrom(value).buildPartial(); } else { value_ = value; } onChanged(); } else { if (valueCase_ == 7) { shapeBuilder_.mergeFrom(value); } shapeBuilder_.setMessage(value); } valueCase_ = 7; return this; } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public Builder clearShape() { if (shapeBuilder_ == null) { if (valueCase_ == 7) { valueCase_ = 0; value_ = null; onChanged(); } } else { if (valueCase_ == 7) { valueCase_ = 0; value_ = null; } shapeBuilder_.clear(); } return this; } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProto.Builder getShapeBuilder() { return getShapeFieldBuilder().getBuilder(); } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ public org.tensorflow.proto.framework.TensorShapeProtoOrBuilder getShapeOrBuilder() { if ((valueCase_ == 7) && (shapeBuilder_ != null)) { return shapeBuilder_.getMessageOrBuilder(); } else { if (valueCase_ == 7) { return (org.tensorflow.proto.framework.TensorShapeProto) value_; } return org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance(); } } /** * <pre> * "shape" * </pre> * * <code>.tensorflow.TensorShapeProto shape = 7;</code> */ private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.TensorShapeProto, org.tensorflow.proto.framework.TensorShapeProto.Builder, org.tensorflow.proto.framework.TensorShapeProtoOrBuilder> getShapeFieldBuilder() { if (shapeBuilder_ == null) { if (!(valueCase_ == 7)) { value_ = org.tensorflow.proto.framework.TensorShapeProto.getDefaultInstance(); } shapeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.TensorShapeProto, org.tensorflow.proto.framework.TensorShapeProto.Builder, org.tensorflow.proto.framework.TensorShapeProtoOrBuilder>( (org.tensorflow.proto.framework.TensorShapeProto) value_, getParentForChildren(), isClean()); value_ = null; } valueCase_ = 7; onChanged();; return shapeBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.TensorProto, org.tensorflow.proto.framework.TensorProto.Builder, org.tensorflow.proto.framework.TensorProtoOrBuilder> tensorBuilder_; /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public boolean hasTensor() { return valueCase_ == 8; } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto getTensor() { if (tensorBuilder_ == null) { if (valueCase_ == 8) { return (org.tensorflow.proto.framework.TensorProto) value_; } return org.tensorflow.proto.framework.TensorProto.getDefaultInstance(); } else { if (valueCase_ == 8) { return tensorBuilder_.getMessage(); } return org.tensorflow.proto.framework.TensorProto.getDefaultInstance(); } } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public Builder setTensor(org.tensorflow.proto.framework.TensorProto value) { if (tensorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } value_ = value; onChanged(); } else { tensorBuilder_.setMessage(value); } valueCase_ = 8; return this; } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public Builder setTensor( org.tensorflow.proto.framework.TensorProto.Builder builderForValue) { if (tensorBuilder_ == null) { value_ = builderForValue.build(); onChanged(); } else { tensorBuilder_.setMessage(builderForValue.build()); } valueCase_ = 8; return this; } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public Builder mergeTensor(org.tensorflow.proto.framework.TensorProto value) { if (tensorBuilder_ == null) { if (valueCase_ == 8 && value_ != org.tensorflow.proto.framework.TensorProto.getDefaultInstance()) { value_ = org.tensorflow.proto.framework.TensorProto.newBuilder((org.tensorflow.proto.framework.TensorProto) value_) .mergeFrom(value).buildPartial(); } else { value_ = value; } onChanged(); } else { if (valueCase_ == 8) { tensorBuilder_.mergeFrom(value); } tensorBuilder_.setMessage(value); } valueCase_ = 8; return this; } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public Builder clearTensor() { if (tensorBuilder_ == null) { if (valueCase_ == 8) { valueCase_ = 0; value_ = null; onChanged(); } } else { if (valueCase_ == 8) { valueCase_ = 0; value_ = null; } tensorBuilder_.clear(); } return this; } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProto.Builder getTensorBuilder() { return getTensorFieldBuilder().getBuilder(); } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ public org.tensorflow.proto.framework.TensorProtoOrBuilder getTensorOrBuilder() { if ((valueCase_ == 8) && (tensorBuilder_ != null)) { return tensorBuilder_.getMessageOrBuilder(); } else { if (valueCase_ == 8) { return (org.tensorflow.proto.framework.TensorProto) value_; } return org.tensorflow.proto.framework.TensorProto.getDefaultInstance(); } } /** * <pre> * "tensor" * </pre> * * <code>.tensorflow.TensorProto tensor = 8;</code> */ private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.TensorProto, org.tensorflow.proto.framework.TensorProto.Builder, org.tensorflow.proto.framework.TensorProtoOrBuilder> getTensorFieldBuilder() { if (tensorBuilder_ == null) { if (!(valueCase_ == 8)) { value_ = org.tensorflow.proto.framework.TensorProto.getDefaultInstance(); } tensorBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.TensorProto, org.tensorflow.proto.framework.TensorProto.Builder, org.tensorflow.proto.framework.TensorProtoOrBuilder>( (org.tensorflow.proto.framework.TensorProto) value_, getParentForChildren(), isClean()); value_ = null; } valueCase_ = 8; onChanged();; return tensorBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.AttrValue.ListValue, org.tensorflow.proto.framework.AttrValue.ListValue.Builder, org.tensorflow.proto.framework.AttrValue.ListValueOrBuilder> listBuilder_; /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public boolean hasList() { return valueCase_ == 1; } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public org.tensorflow.proto.framework.AttrValue.ListValue getList() { if (listBuilder_ == null) { if (valueCase_ == 1) { return (org.tensorflow.proto.framework.AttrValue.ListValue) value_; } return org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } else { if (valueCase_ == 1) { return listBuilder_.getMessage(); } return org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public Builder setList(org.tensorflow.proto.framework.AttrValue.ListValue value) { if (listBuilder_ == null) { if (value == null) { throw new NullPointerException(); } value_ = value; onChanged(); } else { listBuilder_.setMessage(value); } valueCase_ = 1; return this; } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public Builder setList( org.tensorflow.proto.framework.AttrValue.ListValue.Builder builderForValue) { if (listBuilder_ == null) { value_ = builderForValue.build(); onChanged(); } else { listBuilder_.setMessage(builderForValue.build()); } valueCase_ = 1; return this; } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public Builder mergeList(org.tensorflow.proto.framework.AttrValue.ListValue value) { if (listBuilder_ == null) { if (valueCase_ == 1 && value_ != org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance()) { value_ = org.tensorflow.proto.framework.AttrValue.ListValue.newBuilder((org.tensorflow.proto.framework.AttrValue.ListValue) value_) .mergeFrom(value).buildPartial(); } else { value_ = value; } onChanged(); } else { if (valueCase_ == 1) { listBuilder_.mergeFrom(value); } listBuilder_.setMessage(value); } valueCase_ = 1; return this; } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public Builder clearList() { if (listBuilder_ == null) { if (valueCase_ == 1) { valueCase_ = 0; value_ = null; onChanged(); } } else { if (valueCase_ == 1) { valueCase_ = 0; value_ = null; } listBuilder_.clear(); } return this; } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public org.tensorflow.proto.framework.AttrValue.ListValue.Builder getListBuilder() { return getListFieldBuilder().getBuilder(); } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ public org.tensorflow.proto.framework.AttrValue.ListValueOrBuilder getListOrBuilder() { if ((valueCase_ == 1) && (listBuilder_ != null)) { return listBuilder_.getMessageOrBuilder(); } else { if (valueCase_ == 1) { return (org.tensorflow.proto.framework.AttrValue.ListValue) value_; } return org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } } /** * <pre> * any "list(...)" * </pre> * * <code>.tensorflow.AttrValue.ListValue list = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.AttrValue.ListValue, org.tensorflow.proto.framework.AttrValue.ListValue.Builder, org.tensorflow.proto.framework.AttrValue.ListValueOrBuilder> getListFieldBuilder() { if (listBuilder_ == null) { if (!(valueCase_ == 1)) { value_ = org.tensorflow.proto.framework.AttrValue.ListValue.getDefaultInstance(); } listBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.AttrValue.ListValue, org.tensorflow.proto.framework.AttrValue.ListValue.Builder, org.tensorflow.proto.framework.AttrValue.ListValueOrBuilder>( (org.tensorflow.proto.framework.AttrValue.ListValue) value_, getParentForChildren(), isClean()); value_ = null; } valueCase_ = 1; onChanged();; return listBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.NameAttrList, org.tensorflow.proto.framework.NameAttrList.Builder, org.tensorflow.proto.framework.NameAttrListOrBuilder> funcBuilder_; /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public boolean hasFunc() { return valueCase_ == 10; } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public org.tensorflow.proto.framework.NameAttrList getFunc() { if (funcBuilder_ == null) { if (valueCase_ == 10) { return (org.tensorflow.proto.framework.NameAttrList) value_; } return org.tensorflow.proto.framework.NameAttrList.getDefaultInstance(); } else { if (valueCase_ == 10) { return funcBuilder_.getMessage(); } return org.tensorflow.proto.framework.NameAttrList.getDefaultInstance(); } } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public Builder setFunc(org.tensorflow.proto.framework.NameAttrList value) { if (funcBuilder_ == null) { if (value == null) { throw new NullPointerException(); } value_ = value; onChanged(); } else { funcBuilder_.setMessage(value); } valueCase_ = 10; return this; } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public Builder setFunc( org.tensorflow.proto.framework.NameAttrList.Builder builderForValue) { if (funcBuilder_ == null) { value_ = builderForValue.build(); onChanged(); } else { funcBuilder_.setMessage(builderForValue.build()); } valueCase_ = 10; return this; } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public Builder mergeFunc(org.tensorflow.proto.framework.NameAttrList value) { if (funcBuilder_ == null) { if (valueCase_ == 10 && value_ != org.tensorflow.proto.framework.NameAttrList.getDefaultInstance()) { value_ = org.tensorflow.proto.framework.NameAttrList.newBuilder((org.tensorflow.proto.framework.NameAttrList) value_) .mergeFrom(value).buildPartial(); } else { value_ = value; } onChanged(); } else { if (valueCase_ == 10) { funcBuilder_.mergeFrom(value); } funcBuilder_.setMessage(value); } valueCase_ = 10; return this; } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public Builder clearFunc() { if (funcBuilder_ == null) { if (valueCase_ == 10) { valueCase_ = 0; value_ = null; onChanged(); } } else { if (valueCase_ == 10) { valueCase_ = 0; value_ = null; } funcBuilder_.clear(); } return this; } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public org.tensorflow.proto.framework.NameAttrList.Builder getFuncBuilder() { return getFuncFieldBuilder().getBuilder(); } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ public org.tensorflow.proto.framework.NameAttrListOrBuilder getFuncOrBuilder() { if ((valueCase_ == 10) && (funcBuilder_ != null)) { return funcBuilder_.getMessageOrBuilder(); } else { if (valueCase_ == 10) { return (org.tensorflow.proto.framework.NameAttrList) value_; } return org.tensorflow.proto.framework.NameAttrList.getDefaultInstance(); } } /** * <pre> * "func" represents a function. func.name is a function's name or * a primitive op's name. func.attr.first is the name of an attr * defined for that function. func.attr.second is the value for * that attr in the instantiation. * </pre> * * <code>.tensorflow.NameAttrList func = 10;</code> */ private com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.NameAttrList, org.tensorflow.proto.framework.NameAttrList.Builder, org.tensorflow.proto.framework.NameAttrListOrBuilder> getFuncFieldBuilder() { if (funcBuilder_ == null) { if (!(valueCase_ == 10)) { value_ = org.tensorflow.proto.framework.NameAttrList.getDefaultInstance(); } funcBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< org.tensorflow.proto.framework.NameAttrList, org.tensorflow.proto.framework.NameAttrList.Builder, org.tensorflow.proto.framework.NameAttrListOrBuilder>( (org.tensorflow.proto.framework.NameAttrList) value_, getParentForChildren(), isClean()); value_ = null; } valueCase_ = 10; onChanged();; return funcBuilder_; } /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public java.lang.String getPlaceholder() { java.lang.Object ref = ""; if (valueCase_ == 9) { ref = value_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (valueCase_ == 9) { value_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public com.google.protobuf.ByteString getPlaceholderBytes() { java.lang.Object ref = ""; if (valueCase_ == 9) { ref = value_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (valueCase_ == 9) { value_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public Builder setPlaceholder( java.lang.String value) { if (value == null) { throw new NullPointerException(); } valueCase_ = 9; value_ = value; onChanged(); return this; } /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public Builder clearPlaceholder() { if (valueCase_ == 9) { valueCase_ = 0; value_ = null; onChanged(); } return this; } /** * <pre> * This is a placeholder only used in nodes defined inside a * function. It indicates the attr value will be supplied when * the function is instantiated. For example, let us suppose a * node "N" in function "FN". "N" has an attr "A" with value * placeholder = "foo". When FN is instantiated with attr "foo" * set to "bar", the instantiated node N's attr A will have been * given the value "bar". * </pre> * * <code>string placeholder = 9;</code> */ public Builder setPlaceholderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); valueCase_ = 9; value_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:tensorflow.AttrValue) } // @@protoc_insertion_point(class_scope:tensorflow.AttrValue) private static final org.tensorflow.proto.framework.AttrValue DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.tensorflow.proto.framework.AttrValue(); } public static org.tensorflow.proto.framework.AttrValue getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AttrValue> PARSER = new com.google.protobuf.AbstractParser<AttrValue>() { @java.lang.Override public AttrValue parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AttrValue(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AttrValue> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AttrValue> getParserForType() { return PARSER; } @java.lang.Override public org.tensorflow.proto.framework.AttrValue getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
baiqiantao/CashLoan
app/src/main/java/com/bcb/cashloan/activity/DWXXActivity.java
939
package com.bcb.cashloan.activity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import com.bcb.cashloan.R; import com.bcb.cashloan.baseAF.BaseSwipeBackTitleActivity; import butterknife.BindView; import butterknife.OnClick; public class DWXXActivity extends BaseSwipeBackTitleActivity { @BindView(R.id.et_name) EditText etName; @BindView(R.id.et_phone) EditText etPhone; @BindView(R.id.et_dz) EditText etDz; @BindView(R.id.et_time) EditText etTime; @BindView(R.id.et_sr) EditText etSr; @BindView(R.id.button_confirm) Button buttonConfirm; @BindView(R.id.activity_sfrz) RelativeLayout activitySfrz; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setMyContentView(R.layout.activity_dwxx); tv_title.setText("单位信息"); } @OnClick(R.id.button_confirm) public void onClick() { } }
apache-2.0
jbAdyoulike/Prebid.js
modules/gumgumBidAdapter.js
5687
const bidfactory = require('src/bidfactory'); const bidmanager = require('src/bidmanager'); const utils = require('src/utils'); const adloader = require('src/adloader'); var adaptermanager = require('src/adaptermanager'); const BIDDER_CODE = 'gumgum'; const CALLBACKS = {}; const GumgumAdapter = function GumgumAdapter() { const bidEndpoint = `https://g2.gumgum.com/hbid/imp`; let topWindow; let topScreen; let pageViewId; const requestCache = {}; const throttleTable = {}; const defaultThrottle = 3e4; const dtCredentials = { member: 'YcXr87z2lpbB' }; try { topWindow = global.top; topScreen = topWindow.screen; } catch (error) { return utils.logError(error); } function _getTimeStamp() { return new Date().getTime(); } function _getDigiTrustQueryParams() { function getDigiTrustId () { var digiTrustUser = (window.DigiTrust && window.DigiTrust.getUser) ? window.DigiTrust.getUser(dtCredentials) : {}; return (digiTrustUser && digiTrustUser.success && digiTrustUser.identity) || ''; }; let digiTrustId = getDigiTrustId(); // Verify there is an ID and this user has not opted out if (!digiTrustId || (digiTrustId.privacy && digiTrustId.privacy.optout)) { return {}; } return { 'dt': digiTrustId.id }; } function _callBids({ bids }) { const browserParams = { vw: topWindow.innerWidth, vh: topWindow.innerHeight, sw: topScreen.width, sh: topScreen.height, pu: topWindow.location.href, ce: navigator.cookieEnabled, dpr: topWindow.devicePixelRatio || 1 }; utils._each(bids, bidRequest => { const { bidId , params = {} , placementCode } = bidRequest; const timestamp = _getTimeStamp(); const trackingId = params.inScreen; const nativeId = params.native; const slotId = params.inSlot; const bid = { tmax: $$PREBID_GLOBAL$$.cbTimeout }; /* slot/native ads need the placement id */ switch (true) { case !!(params.inImage): bid.pi = 1; break; case !!(params.inScreen): bid.pi = 2; break; case !!(params.inSlot): bid.pi = 3; break; case !!(params.native): bid.pi = 5; break; default: return utils.logWarn( `[GumGum] No product selected for the placement ${placementCode}` + ', please check your implementation.' ); } /* throttle based on the latest request for this product */ const productId = bid.pi; const requestKey = productId + '|' + placementCode; const throttle = throttleTable[productId]; const latestRequest = requestCache[requestKey]; if (latestRequest && throttle && (timestamp - latestRequest) < throttle) { return utils.logWarn( `[GumGum] The refreshes for "${placementCode}" with the params ` + `${JSON.stringify(params)} should be at least ${throttle / 1e3}s apart.` ); } /* update the last request */ requestCache[requestKey] = timestamp; /* tracking id is required for in-image and in-screen */ if (trackingId) bid.t = trackingId; /* native ads require a native placement id */ if (nativeId) bid.ni = nativeId; /* slot ads require a slot id */ if (slotId) bid.si = slotId; /* include the pageViewId, if any */ if (pageViewId) bid.pv = pageViewId; const cachedBid = Object.assign({ placementCode, id: bidId }, bid); const callback = { jsonp: `$$PREBID_GLOBAL$$.handleGumGumCB['${bidId}']` }; CALLBACKS[bidId] = _handleGumGumResponse(cachedBid); const query = Object.assign(callback, browserParams, bid, _getDigiTrustQueryParams()); const bidCall = `${bidEndpoint}?${utils.parseQueryStringParameters(query)}`; adloader.loadScript(bidCall); }); } const _handleGumGumResponse = cachedBidRequest => (bidResponse = {}) => { const { pi: productId } = cachedBidRequest; const { ad = {} , pag = {} , thms: throttle } = bidResponse; /* cache the pageViewId */ if (pag && pag.pvid) pageViewId = pag.pvid; if (ad && ad.id) { /* set the new throttle */ throttleTable[productId] = throttle || defaultThrottle; /* create the bid */ const bid = bidfactory.createBid(1); const { t: trackingId } = pag; bidResponse.request = cachedBidRequest; const encodedResponse = encodeURIComponent(JSON.stringify(bidResponse)); const gumgumAdLoader = `<script> (function (context, topWindow, d, s, G) { G = topWindow.GUMGUM; d = topWindow.document; function loadAd() { topWindow.GUMGUM.pbjs("${trackingId}", ${productId}, "${encodedResponse}" , context); } if (G) { loadAd(); } else { topWindow.$$PREBID_GLOBAL$$.loadScript("https://js.gumgum.com/services.js", loadAd); } }(window, top)); </script>`; Object.assign(bid, { cpm: ad.price, ad: gumgumAdLoader, width: ad.width, height: ad.height, bidderCode: BIDDER_CODE }); bidmanager.addBidResponse(cachedBidRequest.placementCode, bid); } else { const noBid = bidfactory.createBid(2); noBid.bidderCode = BIDDER_CODE; bidmanager.addBidResponse(cachedBidRequest.placementCode, noBid); } delete CALLBACKS[cachedBidRequest.id]; }; window.$$PREBID_GLOBAL$$.handleGumGumCB = CALLBACKS; return { callBids: _callBids }; }; adaptermanager.registerBidAdapter(new GumgumAdapter(), 'gumgum'); module.exports = GumgumAdapter;
apache-2.0
chadstolper/glo
js/namespace.js
37
//GLO Namespace var GLO = GLO || {};
apache-2.0
baitouwei/ASwipeRefresh
app/src/main/java/com/baitouwei/aswiperefresh/sample/ui/SwipeRefreshViewPagerFragment.java
4055
/* * Copyright (C) 2015 baitouwei. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baitouwei.aswiperefresh.sample.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.baiouwei.example.R; import com.baitouwei.aswiperefresh.sample.BaseFragment; /** * @author baitouwei */ public class SwipeRefreshViewPagerFragment extends BaseFragment { private static final String TAG = SwipeRefreshViewPagerFragment.class.getSimpleName(); private ViewPager viewPager; private ViewPagerAdapter viewPagerAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager()); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.swipe_view_pager_fragment, container, false); viewPager = (ViewPager) v.findViewById(R.id.view_pager); return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); viewPager.setAdapter(viewPagerAdapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); } private void findSwipeRefreshLayout() { Fragment f = getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":" + viewPager.getCurrentItem()); if (f != null && f instanceof BaseFragment) { swipeRefreshLayout = ((BaseFragment) f).getSwipeRefreshLayout(); } } private class ViewPagerAdapter extends FragmentPagerAdapter { public ViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { Fragment f; switch (position) { case 0: f = new SwipeRefreshListFragment(); break; case 1: f = new SwipeRefreshRecycleViewFragment(); break; case 2: f = new SwipeRefreshScrollViewFragment(); break; case 3: f = new SwipeRefreshWebViewFragment(); break; default: f = new SwipeRefreshListFragment(); break; } return f; } @Override public CharSequence getPageTitle(int position) { return getItem(position).getClass().getSimpleName(); } @Override public int getCount() { return 4; } @Override public void finishUpdate(ViewGroup container) { super.finishUpdate(container); } } }
apache-2.0
russbishop/swift
lib/Sema/DerivedConformanceRawRepresentable.cpp
15918
//===--- DerivedConformanceRawRepresentable.cpp - Derived RawRepresentable ===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements implicit derivation of the RawRepresentable protocol // for an enum. // //===----------------------------------------------------------------------===// #include "TypeChecker.h" #include "swift/AST/ArchetypeBuilder.h" #include "swift/AST/Decl.h" #include "swift/AST/Stmt.h" #include "swift/AST/Expr.h" #include "swift/AST/Pattern.h" #include "swift/AST/Types.h" #include "DerivedConformances.h" using namespace swift; using namespace DerivedConformance; static LiteralExpr *cloneRawLiteralExpr(ASTContext &C, LiteralExpr *expr) { LiteralExpr *clone; if (auto intLit = dyn_cast<IntegerLiteralExpr>(expr)) { clone = new (C) IntegerLiteralExpr(intLit->getDigitsText(), expr->getLoc(), /*implicit*/ true); if (intLit->isNegative()) cast<IntegerLiteralExpr>(clone)->setNegative(expr->getLoc()); } else if (isa<NilLiteralExpr>(expr)) { clone = new (C) NilLiteralExpr(expr->getLoc()); } else if (auto stringLit = dyn_cast<StringLiteralExpr>(expr)) { clone = new (C) StringLiteralExpr(stringLit->getValue(), expr->getLoc()); } else if (auto floatLit = dyn_cast<FloatLiteralExpr>(expr)) { clone = new (C) FloatLiteralExpr(floatLit->getDigitsText(), expr->getLoc(), /*implicit*/ true); if (floatLit->isNegative()) cast<FloatLiteralExpr>(clone)->setNegative(expr->getLoc()); } else { llvm_unreachable("invalid raw literal expr"); } clone->setImplicit(); return clone; } static Type deriveRawRepresentable_Raw(TypeChecker &tc, Decl *parentDecl, EnumDecl *enumDecl) { // enum SomeEnum : SomeType { // @derived // typealias Raw = SomeType // } auto rawInterfaceType = enumDecl->getRawType(); return ArchetypeBuilder::mapTypeIntoContext(cast<DeclContext>(parentDecl), rawInterfaceType); } static void deriveBodyRawRepresentable_raw(AbstractFunctionDecl *toRawDecl) { // enum SomeEnum : SomeType { // case A = 111, B = 222 // @derived // var raw: SomeType { // switch self { // case A: // return 111 // case B: // return 222 // } // } // } auto parentDC = toRawDecl->getDeclContext(); ASTContext &C = parentDC->getASTContext(); auto enumDecl = parentDC->getAsEnumOrEnumExtensionContext(); Type rawTy = enumDecl->getRawType(); assert(rawTy); for (auto elt : enumDecl->getAllElements()) { if (!elt->getTypeCheckedRawValueExpr() || !elt->getTypeCheckedRawValueExpr()->getType()->isEqual(rawTy)) { return; } } Type enumType = parentDC->getDeclaredTypeInContext(); SmallVector<CaseStmt*, 4> cases; for (auto elt : enumDecl->getAllElements()) { auto pat = new (C) EnumElementPattern(TypeLoc::withoutLoc(enumType), SourceLoc(), SourceLoc(), Identifier(), elt, nullptr); pat->setImplicit(); auto labelItem = CaseLabelItem(/*IsDefault=*/false, pat, SourceLoc(), nullptr); auto returnExpr = cloneRawLiteralExpr(C, elt->getRawValueExpr()); auto returnStmt = new (C) ReturnStmt(SourceLoc(), returnExpr); auto body = BraceStmt::create(C, SourceLoc(), ASTNode(returnStmt), SourceLoc()); cases.push_back(CaseStmt::create(C, SourceLoc(), labelItem, /*HasBoundDecls=*/false, SourceLoc(), body)); } auto selfRef = createSelfDeclRef(toRawDecl); auto switchStmt = SwitchStmt::create(LabeledStmtInfo(), SourceLoc(), selfRef, SourceLoc(), cases, SourceLoc(), C); auto body = BraceStmt::create(C, SourceLoc(), ASTNode(switchStmt), SourceLoc()); toRawDecl->setBody(body); } static VarDecl *deriveRawRepresentable_raw(TypeChecker &tc, Decl *parentDecl, EnumDecl *enumDecl) { ASTContext &C = tc.Context; auto parentDC = cast<DeclContext>(parentDecl); auto rawInterfaceType = enumDecl->getRawType(); auto rawType = ArchetypeBuilder::mapTypeIntoContext(parentDC, rawInterfaceType); // Define the getter. auto getterDecl = declareDerivedPropertyGetter(tc, parentDecl, enumDecl, rawInterfaceType, rawType); getterDecl->setBodySynthesizer(&deriveBodyRawRepresentable_raw); // Define the property. VarDecl *propDecl; PatternBindingDecl *pbDecl; std::tie(propDecl, pbDecl) = declareDerivedReadOnlyProperty(tc, parentDecl, enumDecl, C.Id_rawValue, rawInterfaceType, rawType, getterDecl); auto dc = cast<IterableDeclContext>(parentDecl); dc->addMember(getterDecl); dc->addMember(propDecl); dc->addMember(pbDecl); return propDecl; } static void deriveBodyRawRepresentable_init(AbstractFunctionDecl *initDecl) { // enum SomeEnum : SomeType { // case A = 111, B = 222 // @derived // init?(rawValue: SomeType) { // switch rawValue { // case 111: // self = .A // case 222: // self = .B // default: // return nil // } // } // } auto parentDC = initDecl->getDeclContext(); ASTContext &C = parentDC->getASTContext(); auto nominalTypeDecl = parentDC->getAsNominalTypeOrNominalTypeExtensionContext(); auto enumDecl = cast<EnumDecl>(nominalTypeDecl); Type rawTy = enumDecl->getRawType(); assert(rawTy); rawTy = ArchetypeBuilder::mapTypeIntoContext(initDecl, rawTy); for (auto elt : enumDecl->getAllElements()) { if (!elt->getTypeCheckedRawValueExpr() || !elt->getTypeCheckedRawValueExpr()->getType()->isEqual(rawTy)) { return; } } Type enumType = parentDC->getDeclaredTypeInContext(); auto selfDecl = cast<ConstructorDecl>(initDecl)->getImplicitSelfDecl(); SmallVector<CaseStmt*, 4> cases; for (auto elt : enumDecl->getAllElements()) { auto litExpr = cloneRawLiteralExpr(C, elt->getRawValueExpr()); auto litPat = new (C) ExprPattern(litExpr, /*isResolved*/ true, nullptr, nullptr); litPat->setImplicit(); auto labelItem = CaseLabelItem(/*IsDefault=*/false, litPat, SourceLoc(), nullptr); auto eltRef = new (C) DeclRefExpr(elt, DeclNameLoc(), /*implicit*/true); auto metaTyRef = TypeExpr::createImplicit(enumType, C); auto valueExpr = new (C) DotSyntaxCallExpr(eltRef, SourceLoc(), metaTyRef); auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*implicit*/true, AccessSemantics::DirectToStorage); auto assignment = new (C) AssignExpr(selfRef, SourceLoc(), valueExpr, /*implicit*/ true); auto body = BraceStmt::create(C, SourceLoc(), ASTNode(assignment), SourceLoc()); cases.push_back(CaseStmt::create(C, SourceLoc(), labelItem, /*HasBoundDecls=*/false, SourceLoc(), body)); } auto anyPat = new (C) AnyPattern(SourceLoc()); anyPat->setImplicit(); auto dfltLabelItem = CaseLabelItem(/*IsDefault=*/true, anyPat, SourceLoc(), nullptr); auto dfltReturnStmt = new (C) FailStmt(SourceLoc(), SourceLoc()); auto dfltBody = BraceStmt::create(C, SourceLoc(), ASTNode(dfltReturnStmt), SourceLoc()); cases.push_back(CaseStmt::create(C, SourceLoc(), dfltLabelItem, /*HasBoundDecls=*/false, SourceLoc(), dfltBody)); auto rawDecl = initDecl->getParameterList(1)->get(0); auto rawRef = new (C) DeclRefExpr(rawDecl, DeclNameLoc(), /*implicit*/true); auto switchStmt = SwitchStmt::create(LabeledStmtInfo(), SourceLoc(), rawRef, SourceLoc(), cases, SourceLoc(), C); auto body = BraceStmt::create(C, SourceLoc(), ASTNode(switchStmt), SourceLoc()); initDecl->setBody(body); } static ConstructorDecl *deriveRawRepresentable_init(TypeChecker &tc, Decl *parentDecl, EnumDecl *enumDecl) { ASTContext &C = tc.Context; auto parentDC = cast<DeclContext>(parentDecl); auto rawInterfaceType = enumDecl->getRawType(); auto rawType = ArchetypeBuilder::mapTypeIntoContext(parentDC, rawInterfaceType); // Make sure that the raw type is Equatable. We need it to ensure that we have // a suitable ~= for the switch. auto equatableProto = tc.getProtocol(enumDecl->getLoc(), KnownProtocolKind::Equatable); if (!equatableProto) return nullptr; if (!tc.conformsToProtocol(rawType, equatableProto, enumDecl, None)) { SourceLoc loc = enumDecl->getInherited()[0].getSourceRange().Start; tc.diagnose(loc, diag::enum_raw_type_not_equatable, rawType); return nullptr; } Type enumType = parentDC->getDeclaredTypeInContext(); auto *selfDecl = ParamDecl::createUnboundSelf(SourceLoc(), parentDC, /*static*/false, /*inout*/true); auto *rawDecl = new (C) ParamDecl(/*IsLet*/true, SourceLoc(), SourceLoc(), C.Id_rawValue, SourceLoc(), C.Id_rawValue, rawType, parentDC); rawDecl->setImplicit(); auto paramList = ParameterList::createWithoutLoc(rawDecl); auto retTy = OptionalType::get(enumType); DeclName name(C, C.Id_init, paramList); auto initDecl = new (C) ConstructorDecl(name, SourceLoc(), /*Failability=*/ OTK_Optional, /*FailabilityLoc=*/SourceLoc(), /*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), selfDecl, paramList, /*GenericParams=*/nullptr, parentDC); initDecl->setImplicit(); initDecl->setBodySynthesizer(&deriveBodyRawRepresentable_init); // Compute the type of the initializer. GenericParamList *genericParams = initDecl->getGenericParamsOfContext(); TupleTypeElt element(rawType, C.Id_rawValue); auto argType = TupleType::get(element, C); TupleTypeElt interfaceElement(rawInterfaceType, C.Id_rawValue); auto interfaceArgType = TupleType::get(interfaceElement, C); Type type = FunctionType::get(argType, retTy); Type selfType = initDecl->computeSelfType(); selfDecl->overwriteType(selfType); Type selfMetatype = MetatypeType::get(selfType->getInOutObjectType()); Type allocType; if (genericParams) allocType = PolymorphicFunctionType::get(selfMetatype, type, genericParams); else allocType = FunctionType::get(selfMetatype, type); initDecl->setType(allocType); // Compute the interface type of the initializer. Type retInterfaceType = OptionalType::get(parentDC->getDeclaredInterfaceType()); Type interfaceType = FunctionType::get(interfaceArgType, retInterfaceType); Type selfInterfaceType = initDecl->computeInterfaceSelfType(/*init*/ false); Type selfInitializerInterfaceType = initDecl->computeInterfaceSelfType(/*init*/ true); Type allocIfaceType; Type initIfaceType; if (auto sig = parentDC->getGenericSignatureOfContext()) { initDecl->setGenericSignature(sig); allocIfaceType = GenericFunctionType::get(sig, selfInterfaceType, interfaceType, FunctionType::ExtInfo()); initIfaceType = GenericFunctionType::get(sig, selfInitializerInterfaceType, interfaceType, FunctionType::ExtInfo()); } else { allocIfaceType = FunctionType::get(selfMetatype, type); initIfaceType = FunctionType::get(selfType, type); } initDecl->setInterfaceType(allocIfaceType); initDecl->setInitializerInterfaceType(initIfaceType); initDecl->setAccessibility(enumDecl->getFormalAccess()); // If the enum was not imported, the derived conformance is either from the // enum itself or an extension, in which case we will emit the declaration // normally. if (enumDecl->hasClangNode()) tc.Context.addExternalDecl(initDecl); cast<IterableDeclContext>(parentDecl)->addMember(initDecl); return initDecl; } ValueDecl *DerivedConformance::deriveRawRepresentable(TypeChecker &tc, Decl *parentDecl, NominalTypeDecl *type, ValueDecl *requirement) { // Check preconditions. These should already have been diagnosed by // type-checking but we may still get here after recovery. // The type must be an enum. auto enumDecl = dyn_cast<EnumDecl>(type); if (!enumDecl) return nullptr; // It must have a valid raw type. if (!enumDecl->hasRawType()) return nullptr; if (!enumDecl->getInherited().empty() && enumDecl->getInherited().front().isError()) return nullptr; // There must be enum elements. if (enumDecl->getAllElements().empty()) return nullptr; for (auto elt : enumDecl->getAllElements()) tc.validateDecl(elt); if (requirement->getName() == tc.Context.Id_rawValue) return deriveRawRepresentable_raw(tc, parentDecl, enumDecl); if (requirement->getName() == tc.Context.Id_init) return deriveRawRepresentable_init(tc, parentDecl, enumDecl); tc.diagnose(requirement->getLoc(), diag::broken_raw_representable_requirement); return nullptr; } Type DerivedConformance::deriveRawRepresentable(TypeChecker &tc, Decl *parentDecl, NominalTypeDecl *type, AssociatedTypeDecl *assocType) { // Check preconditions. These should already have been diagnosed by // type-checking but we may still get here after recovery. // The type must be an enum. auto enumDecl = dyn_cast<EnumDecl>(type); if (!enumDecl) return nullptr; // It must have a valid raw type. if (!enumDecl->hasRawType()) return nullptr; if (!enumDecl->getInherited().empty() && enumDecl->getInherited().front().isError()) return nullptr; // There must be enum elements. if (enumDecl->getAllElements().empty()) return nullptr; for (auto elt : enumDecl->getAllElements()) tc.validateDecl(elt); if (assocType->getName() == tc.Context.Id_RawValue) { return deriveRawRepresentable_Raw(tc, parentDecl, enumDecl); } tc.diagnose(assocType->getLoc(), diag::broken_raw_representable_requirement); return nullptr; }
apache-2.0
marcosni1108/TCC_Kairos
js/highdataIndireta.js
1870
$(function () { var chart; var options = { chart: { renderTo: 'chart', type: 'column' }, title: { text: 'Paradas Indiretas' }, xAxis: { type: 'category', labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { min: 0, title: { text: 'Parada por hora' } }, legend: { enabled: false }, tooltip: { pointFormat: 'Total em horas: <b>{point.y:.1f} </b>' }, credits: { enabled: false }, colors: [ '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92' ], plotOptions: { column: { colorByPoint: true } }, series: [{ name: 'Produtividade', dataLabels: { enabled: true, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] } $.getJSON("../../js/dataGrafico/paradaTipoParada.json", function (json) { options.xAxis.categories = json[1]['data'];//xAxis: {categories: []} options.series[0] = json[0]; chart = new Highcharts.Chart(options); }); //fim script });
apache-2.0
wenanguo/anguosoft
code/anguo-core/src/main/java/com/anguo/app/db/mapper/CommonSysMemberMapper.java
476
package com.anguo.app.db.mapper; import com.anguo.app.db.domain.CommonSysMember; import com.anguo.mybatis.db.mapper.BaseMapper; public interface CommonSysMemberMapper extends BaseMapper<CommonSysMember> { /** * 根据用户名单条数据 * @param obj * @return */ public CommonSysMember getDataByUserName(CommonSysMember obj); /** * 根据uuid获取当前登录用户 * @param obj * @return */ public CommonSysMember getDataByUUID(String obj); }
apache-2.0
aholake/hiringviet
src/main/java/vn/com/hiringviet/util/TimeUtil.java
328
package vn.com.hiringviet.util; // TODO: Auto-generated Javadoc /** * The Class TimeUtil. */ public class TimeUtil { /** * Convert minute to second. * * @param minute the minute * @return the int */ public static final int convertMinuteToSecond(int minute) { return minute * 60 * 1000; } }
apache-2.0
barryvdh/less.php
test/FixturesTest.php
2763
<?php class FixturesTest extends PHPUnit_Framework_TestCase{ public $fixtures_dir; public $cache_dir; function setUp(){ print_r("\nSet-Up"); require_once( dirname(__FILE__) . '/../lib/Less/Autoloader.php' ); Less_Autoloader::register(); $this->fixtures_dir = dirname(__FILE__).'/Fixtures'; print_r("\n fixtures_dir: ".$this->fixtures_dir); Less_Cache::$cache_dir = $this->CacheDirectory(); print_r("\n cache_dir: ".Less_Cache::$cache_dir); print_r("\n\n"); } /** * Test the contents of the files in /test/Fixtures/less.js/expected * */ function testLessJs(){ print_r("\nBegin Tests"); $css_dir = $this->fixtures_dir.'/less.js/expected'; $files = scandir($css_dir); foreach($files as $file){ if( $file == '.' || $file == '..' ){ continue; } $expected_file = $css_dir.'/'.$file; if( is_dir($expected_file) ){ continue; } $this->CompareFile( $expected_file ); } print_r("\n\nTests Complete!!"); } /** * Return the path of the cache directory if it's writable * */ function CacheDirectory(){ $cache_dir = dirname(__FILE__).'/_cache'; if( !file_exists($cache_dir) && !mkdir($cache_dir) ){ return false; } if( !is_writable($cache_dir) ){ return false; } return $cache_dir; } /** * Change a css file name to a less file name * * eg: /Fixtures/less.js/css/filename.css -> /Fixtures/less.js/less/filename.less * */ function TranslateFile( $file_css, $dir = 'less', $type = 'less' ){ $filename = basename($file_css); $filename = substr($filename,0,-4); return dirname( dirname($file_css) ).'/'.$dir.'/'.$filename.'.'.$type; } /** * Compare the parser results with the expected css * */ function CompareFile( $expected_file ){ $less_file = $this->TranslateFile( $expected_file ); $expected_css = trim(file_get_contents($expected_file)); // Check with standard parser print_r("\n ".basename($expected_file)); print_r("\n - Standard Compiler"); $parser = new Less_Parser(); $parser->parseFile($less_file); $css = $parser->getCss(); $css = trim($css); $this->assertEquals( $expected_css, $css ); // Check with cache if( Less_Cache::$cache_dir ){ print_r("\n - Regenerating Cache"); $files = array( $less_file => '' ); $css_file_name = Less_Cache::Regen( $files ); $css = file_get_contents(Less_Cache::$cache_dir.'/'.$css_file_name); $css = trim($css); $this->assertEquals( $expected_css, $css ); // Check using the cached data print_r("\n - Using Cache"); $css_file_name = Less_Cache::Get( $files ); $css = file_get_contents(Less_Cache::$cache_dir.'/'.$css_file_name); $css = trim($css); $this->assertEquals( $expected_css, $css ); } } }
apache-2.0
andrew749/Muzik
aFileDialog/src/main/java/ar/com/daidalos/afiledialog/FileChooserCore.java
19926
/* * Copyright 2013 Jose F. Maldonado * * This file is part of aFileDialog. * * aFileDialog is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * aFileDialog is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with aFileDialog. If not, see <http://www.gnu.org/licenses/>. */ package ar.com.daidalos.afiledialog; import java.io.*; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Environment; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import ar.com.daidalos.afiledialog.view.FileItem; /** * This class implements the common features of a file chooser. */ class FileChooserCore { // ----- Attributes ----- // /** * The file chooser in which all the operations are performed. */ private FileChooser chooser; /** * The listeners for the event of select a file. */ private List<OnFileSelectedListener> listeners; /** * A regular expression for filter the files. */ private String filter; /** * A boolean indicating if only the files that can be selected (they pass the filter) must be show. */ private boolean showOnlySelectable; /** * A boolean indicating if the user can create files. */ private boolean canCreateFiles; /** * A boolean indicating if the chooser is going to be used to select folders. */ private boolean folderMode; /** * A file that indicates the folder that is currently being displayed. */ private File currentFolder; /** * This attribut allows to override the default value of the labels. */ private FileChooserLabels labels; /** * A boolean that indicates if a confirmation dialog must be displaying when selecting a file. */ private boolean showConfirmationOnSelect; /** * A boolean that indicates if a confirmation dialog must be displaying when creating a file. */ private boolean showConfirmationOnCreate; /** * A boolean indicating if the folder's full path must be show in the title. */ private boolean showFullPathInTitle; // ---- Static attributes ----- // /** * Static attribute for save the folder displayed by default. */ private static File defaultFolder; /** * Static constructor. */ static { defaultFolder = null; } // ----- Constructor ----- // /** * Creates an instance of this class. * * @param fileChooser The graphical file chooser. */ public FileChooserCore(FileChooser fileChooser) { // Initialize attributes. this.chooser = fileChooser; this.listeners = new LinkedList<OnFileSelectedListener>(); this.filter = null; this.showOnlySelectable = false; this.setCanCreateFiles(false); this.setFolderMode(false); this.currentFolder = null; this.labels = null; this.showConfirmationOnCreate = false; this.showConfirmationOnSelect = false; this.showFullPathInTitle = false; // Add listener for the buttons. LinearLayout root = this.chooser.getRootLayout(); Button addButton = (Button) root.findViewById(R.id.buttonAdd); addButton.setOnClickListener(addButtonClickListener); Button okButton = (Button) root.findViewById(R.id.buttonOk); okButton.setOnClickListener(okButtonClickListener); } // ----- Events methods ----- // /** * Implementation of the click listener for when the add button is clicked. */ private View.OnClickListener addButtonClickListener = new View.OnClickListener() { public void onClick(View v) { // Get the current context. Context context = v.getContext(); // Create an alert dialog. AlertDialog.Builder alert = new AlertDialog.Builder(context); // Define the dialog's labels. String title = context.getString(FileChooserCore.this.folderMode? R.string.daidalos_create_folder : R.string.daidalos_create_file); if(FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogTitle != null) title = FileChooserCore.this.labels.createFileDialogTitle; String message = context.getString(FileChooserCore.this.folderMode? R.string.daidalos_enter_folder_name : R.string.daidalos_enter_file_name); if(FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogMessage != null) message = FileChooserCore.this.labels.createFileDialogMessage; String posButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogAcceptButton != null)? FileChooserCore.this.labels.createFileDialogAcceptButton : context.getString(R.string.daidalos_accept); String negButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.createFileDialogCancelButton != null)? FileChooserCore.this.labels.createFileDialogCancelButton : context.getString(R.string.daidalos_cancel); // Set the title and the message. alert.setTitle( title ); alert.setMessage( message ); // Set an EditText view to get the file's name. final EditText input = new EditText(context); alert.setView(input); // Set the 'ok' and 'cancel' buttons. alert.setPositiveButton(posButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String fileName = input.getText().toString(); // Verify if a value has been entered. if(fileName != null && fileName.length() > 0) { // Notify the listeners. FileChooserCore.this.notifyListeners(FileChooserCore.this.currentFolder, fileName); } } }); alert.setNegativeButton(negButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing, automatically the dialog is going to be closed. } }); // Show the dialog. alert.show(); } }; /** * Implementation of the click listener for when the ok button is clicked. */ private View.OnClickListener okButtonClickListener = new View.OnClickListener() { public void onClick(View v) { // Notify the listeners. FileChooserCore.this.notifyListeners(FileChooserCore.this.currentFolder, null); } }; /** * Implementation of the click listener for when a file item is clicked. */ private FileItem.OnFileClickListener fileItemClickListener = new FileItem.OnFileClickListener() { public void onClick(FileItem source) { // Verify if the item is a folder. File file = source.getFile(); if(file.isDirectory()) { // Open the folder. FileChooserCore.this.loadFolder(file); } else { // Notify the listeners. FileChooserCore.this.notifyListeners(file, null); } } }; /** * Add a listener for the event of a file selected. * * @param listener The listener to add. */ public void addListener(OnFileSelectedListener listener) { this.listeners.add(listener); } /** * Removes a listener for the event of a file selected. * * @param listener The listener to remove. */ public void removeListener(OnFileSelectedListener listener) { this.listeners.remove(listener); } /** * Removes all the listeners for the event of a file selected. */ public void removeAllListeners() { this.listeners.clear(); } /** * Interface definition for a callback to be invoked when a file is selected. */ public interface OnFileSelectedListener { /** * Called when a file has been selected. * * @param file The file selected. */ void onFileSelected(File file); /** * Called when an user wants to be create a file. * * @param folder The file's parent folder. * @param name The file's name. */ void onFileSelected(File folder, String name); } /** * Notify to all listeners that a file has been selected or created. * * @param file The file or folder selected or the folder in which the file must be created. * @param name The name of the file that must be created or 'null' if a file was selected (instead of being created). */ private void notifyListeners(final File file, final String name) { // Determine if a file has been selected or created. final boolean creation = name != null && name.length() > 0; // Verify if a confirmation dialog must be show. if((creation && this.showConfirmationOnCreate || !creation && this.showConfirmationOnSelect)) { // Create an alert dialog. Context context = this.chooser.getContext(); AlertDialog.Builder alert = new AlertDialog.Builder(context); // Define the dialog's labels. String message = null; if(FileChooserCore.this.labels != null && ((creation && FileChooserCore.this.labels.messageConfirmCreation != null) || (!creation && FileChooserCore.this.labels.messageConfirmSelection != null))) { message = creation? FileChooserCore.this.labels.messageConfirmCreation : FileChooserCore.this.labels.messageConfirmSelection; } else { if(FileChooserCore.this.folderMode) { message = context.getString(creation? R.string.daidalos_confirm_create_folder : R.string.daidalos_confirm_select_folder); } else { message = context.getString(creation? R.string.daidalos_confirm_create_file : R.string.daidalos_confirm_select_file); } } if(message != null) message = message.replace("$file_name", name!=null? name : file.getName()); String posButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.labelConfirmYesButton != null)? FileChooserCore.this.labels.labelConfirmYesButton : context.getString(R.string.daidalos_yes); String negButton = (FileChooserCore.this.labels != null && FileChooserCore.this.labels.labelConfirmNoButton != null)? FileChooserCore.this.labels.labelConfirmNoButton : context.getString(R.string.daidalos_no); // Set the message and the 'yes' and 'no' buttons. alert.setMessage( message ); alert.setPositiveButton(posButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Notify to listeners. for(int i=0; i<FileChooserCore.this.listeners.size(); i++) { if(creation) { FileChooserCore.this.listeners.get(i).onFileSelected(file, name); } else { FileChooserCore.this.listeners.get(i).onFileSelected(file); } } } }); alert.setNegativeButton(negButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing, automatically the dialog is going to be closed. } }); // Show the dialog. alert.show(); } else { // Notify to listeners. for(int i=0; i<FileChooserCore.this.listeners.size(); i++) { if(creation) { FileChooserCore.this.listeners.get(i).onFileSelected(file, name); } else { FileChooserCore.this.listeners.get(i).onFileSelected(file); } } } } // ----- Get and set methods ----- // /** * Allows to define if a confirmation dialog must be show when selecting a file. * * @param show 'true' for show the confirmation dialog, 'false' for not show the dialog. */ public void setShowConfirmationOnSelect(boolean show) { this.showConfirmationOnSelect = show; } /** * Allows to define if a confirmation dialog must be show when creating a file. * * @param show 'true' for show the confirmation dialog, 'false' for not show the dialog. */ public void setShowConfirmationOnCreate(boolean show) { this.showConfirmationOnCreate = show; } /** * Allows to define if, in the title, must be show only the current folder's name or the full file's path.. * * @param show 'true' for show the full path, 'false' for show only the name. */ public void setShowFullPathInTitle(boolean show) { this.showFullPathInTitle = show; } /** * Defines the value of the labels. * * @param label The labels. */ public void setLabels(FileChooserLabels labels) { this.labels = labels; // Verify if the buttons for add a file or select a folder has been modified. if(labels != null) { LinearLayout root = this.chooser.getRootLayout(); if(labels.labelAddButton != null) { Button addButton = (Button) root.findViewById(R.id.buttonAdd); addButton.setText(labels.labelAddButton); } if(labels.labelSelectButton != null) { Button okButton = (Button) root.findViewById(R.id.buttonOk); okButton.setText(labels.labelSelectButton); } } } /** * Set a regular expression to filter the files that can be selected. * * @param filter A regular expression. */ public void setFilter(String filter) { if(filter == null || filter.length() == 0 ) { this.filter = null; } else { this.filter = filter; } // Reload the list of files. this.loadFolder(this.currentFolder); } /** * Defines if the chooser is going to be used to select folders, instead of files. * * @param folderMode 'true' for select folders or 'false' for select files. */ public void setFolderMode(boolean folderMode) { this.folderMode = folderMode; // Show or hide the 'Ok' button. updateButtonsLayout(); // Reload the list of files. this.loadFolder(this.currentFolder); } /** * Defines if the user can create files, instead of only select files. * * @param canCreate 'true' if the user can create files or 'false' if it can only select them. */ public void setCanCreateFiles(boolean canCreate) { this.canCreateFiles = canCreate; // Show or hide the 'Add' button. updateButtonsLayout(); } /** * Defines if only the files that can be selected (they pass the filter) must be show. * * @param show 'true' if only the files that can be selected must be show or 'false' if all the files must be show. */ public void setShowOnlySelectable(boolean show) { this.showOnlySelectable = show; // Reload the list of files. this.loadFolder(this.currentFolder); } /** * Returns the current folder. * * @return The current folder. */ public File getCurrentFolder() { return this.currentFolder; } // ----- Miscellaneous methods ----- // /** * Changes the height of the layout for the buttons, according if the buttons are visible or not. */ private void updateButtonsLayout() { // Get the buttons layout. LinearLayout root = this.chooser.getRootLayout(); LinearLayout buttonsLayout = (LinearLayout) root.findViewById(R.id.linearLayoutButtons); // Verify if the 'Add' button is visible or not. View addButton = root.findViewById(R.id.buttonAdd); addButton.setVisibility(this.canCreateFiles? View.VISIBLE : View.INVISIBLE); addButton.getLayoutParams().width = this.canCreateFiles? ViewGroup.LayoutParams.MATCH_PARENT : 0; // Verify if the 'Ok' button is visible or not. View okButton = root.findViewById(R.id.buttonOk); okButton.setVisibility(this.folderMode? View.VISIBLE : View.INVISIBLE); okButton.getLayoutParams().width = this.folderMode? ViewGroup.LayoutParams.MATCH_PARENT : 0; // If both buttons are invisible, hide the layout. ViewGroup.LayoutParams params = buttonsLayout.getLayoutParams(); if(this.canCreateFiles || this.folderMode) { // Show the layout. params.height = ViewGroup.LayoutParams.WRAP_CONTENT; // If only the 'Ok' button is visible, put him first. Otherwise, put 'Add' first. buttonsLayout.removeAllViews(); if(this.folderMode && !this.canCreateFiles) { buttonsLayout.addView(okButton); buttonsLayout.addView(addButton); } else { buttonsLayout.addView(addButton); buttonsLayout.addView(okButton); } } else { // Hide the layout. params.height = 0; } } /** * Loads all the files of the SD card root. */ public void loadFolder() { this.loadFolder(defaultFolder); } /** * Loads all the files of a folder in the file chooser. * * If no path is specified ('folderPath' is null) the root folder of the SD card is going to be used. * * @param folderPath The folder's path. */ public void loadFolder(String folderPath) { // Get the file path. File path = null; if(folderPath != null && folderPath.length() > 0) { path = new File(folderPath); } this.loadFolder(path); } /** * Loads all the files of a folder in the file chooser. * * If no path is specified ('folder' is null) the root folder of the SD card is going to be used. * * @param folder The folder. */ public void loadFolder(File folder) { // Remove previous files. LinearLayout root = this.chooser.getRootLayout(); LinearLayout layout = (LinearLayout) root.findViewById(R.id.linearLayoutFiles); layout.removeAllViews(); // Get the file path. if(folder == null || !folder.exists()) { if(defaultFolder != null) { this.currentFolder = defaultFolder; } else { this.currentFolder = Environment.getExternalStorageDirectory(); } } else { this.currentFolder = folder; } // Verify if the path exists. if(this.currentFolder.exists() && layout != null) { List<FileItem> fileItems = new LinkedList<FileItem>(); // Add the parent folder. if(this.currentFolder.getParent() != null) { File parent = new File(this.currentFolder.getParent()); if(parent.exists()) { fileItems.add(new FileItem(this.chooser.getContext(), parent, "..")); } } // Verify if the file is a directory. if(this.currentFolder.isDirectory()) { // Get the folder's files. File[] fileList = this.currentFolder.listFiles(); if(fileList != null) { // Order the files alphabetically and separating folders from files. Arrays.sort(fileList, new Comparator<File>() { public int compare(File file1, File file2) { if(file1 != null && file2 != null) { if(file1.isDirectory() && (!file2.isDirectory())) return -1; if(file2.isDirectory() && (!file1.isDirectory())) return 1; return file1.getName().compareTo(file2.getName()); } return 0; } }); // Iterate all the files in the folder. for(int i=0; i<fileList.length; i++) { // Verify if file can be selected (is a directory or folder mode is not activated and the file pass the filter, if defined). boolean selectable = true; if(!fileList[i].isDirectory()) { selectable = !this.folderMode && (this.filter == null || fileList[i].getName().matches(this.filter)); } // Verify if the file must be show. if(selectable || !this.showOnlySelectable) { // Create the file item and add it to the list. FileItem fileItem = new FileItem(this.chooser.getContext(), fileList[i]); fileItem.setSelectable(selectable); fileItems.add(fileItem); } } } // Set the name of the current folder. String currentFolderName = this.showFullPathInTitle? this.currentFolder.getPath() : this.currentFolder.getName(); this.chooser.setCurrentFolderName(currentFolderName); } else { // The file is not a folder, add only this file. fileItems.add(new FileItem(this.chooser.getContext(), this.currentFolder)); } // Add click listener and add the FileItem objects to the layout. for(int i=0; i<fileItems.size(); i++) { fileItems.get(i).addListener(this.fileItemClickListener); layout.addView(fileItems.get(i)); } // Refresh default folder. defaultFolder = this.currentFolder; } } }
apache-2.0
lessthanoptimal/BoofProcessing
src/boofcv/processing/SimpleTemplateMatching.java
2448
package boofcv.processing; import boofcv.alg.feature.detect.template.TemplateMatching; import boofcv.struct.feature.Match; import boofcv.struct.image.GrayU8; import georegression.struct.point.Point2D_I32; import processing.core.PImage; import java.util.ArrayList; import java.util.List; /** * Simplified interface for performing template matching on an image * * @author Peter Abeles */ public class SimpleTemplateMatching { TemplateMatching<GrayU8> matcher; GrayU8 ginput = new GrayU8(1,1); GrayU8 gtemplate = new GrayU8(1,1); public SimpleTemplateMatching(TemplateMatching<GrayU8> matcher) { this.matcher = matcher; } public void setInput( PImage input ) { ConvertProcessing.convertFromRGB(input,ginput); matcher.setImage(ginput); } public List<Match> detect( PImage template , int maxMatches ) { ConvertProcessing.convertFromRGB(template,gtemplate); // System.out.println("width="+ginput.width+"x"+ginput.height+" width="+gtemplate.width+"x"+gtemplate.height); // // System.out.println("sum="+ ImageStatistics.sum(ginput)); // System.out.println("sum="+ ImageStatistics.sum(gtemplate)); matcher.setTemplate(gtemplate,null, maxMatches); return extractResults(); } public List<Match> detect(PImage template , SimpleBinary mask , int maxMatches ) { ConvertProcessing.convert_RGB_U8(template,gtemplate); matcher.setTemplate(gtemplate,mask.image, maxMatches); // System.out.println("width="+ginput.width+"x"+ginput.height+" width="+gtemplate.width+"x"+gtemplate.height+ // " width="+mask.image.width+"x"+mask.image.height); // // System.out.println("sum="+ ImageStatistics.sum(ginput)); // System.out.println("sum="+ ImageStatistics.sum(gtemplate)); // System.out.println("sum="+ ImageStatistics.sum(mask.image)); return extractResults(); } private List<Match> extractResults() { matcher.process(); List<Match> matches = matcher.getResults().toList(); // System.out.println("total found "+matches.size()); List<Match> output = new ArrayList<>(); for (int i = 0; i < matches.size(); i++) { Match orig = matches.get(i); Match copy = new Match(); copy.set(orig); copy.score = orig.score; output.add(copy); } return output; } }
apache-2.0
nielsbasjes/logparser
parser-core/src/test/java/nl/basjes/parse/core/test/UltimateDummyDissector.java
2078
/* * Apache HTTPD & NGINX Access log parsing made easy * Copyright (C) 2011-2021 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.parse.core.test; import nl.basjes.parse.core.Casts; import nl.basjes.parse.core.SimpleDissector; import java.util.EnumSet; import java.util.HashMap; import static nl.basjes.parse.core.Casts.STRING_ONLY; import static nl.basjes.parse.core.Casts.STRING_OR_DOUBLE; import static nl.basjes.parse.core.Casts.STRING_OR_LONG; import static nl.basjes.parse.core.Casts.STRING_OR_LONG_OR_DOUBLE; /** * A dummy dissector to ensure retrieving all types works in the various wrappers */ public abstract class UltimateDummyDissector extends SimpleDissector { private static final HashMap<String, EnumSet<Casts>> DISSECTOR_CONFIG = new HashMap<>(); static { DISSECTOR_CONFIG.put("ANY:any", STRING_OR_LONG_OR_DOUBLE); DISSECTOR_CONFIG.put("STRING:string", STRING_ONLY); DISSECTOR_CONFIG.put("INT:int", STRING_OR_LONG); DISSECTOR_CONFIG.put("LONG:long", STRING_OR_LONG); DISSECTOR_CONFIG.put("FLOAT:float", STRING_OR_DOUBLE); DISSECTOR_CONFIG.put("DOUBLE:double", STRING_OR_DOUBLE); } public UltimateDummyDissector() { super("INPUT", DISSECTOR_CONFIG); } public UltimateDummyDissector(String inputType) { super(inputType, DISSECTOR_CONFIG); } @Override public boolean initializeFromSettingsParameter(String settings) { setInputType(settings); return true; } }
apache-2.0
lt669/lt669.github.io
code/javascript/wrapper.js
355
/*////////////////////////////////////////////////////// Description Keeps the input value between 0 - 360 Author: Lewis Thresh */////////////////////////////////////////////////////// inlets = 1; outlets = 1; function msg_float(input){ if(input >360){ input = input - 360; }else if(input < 0){ input = input + 360; } outlet(0,input); }
apache-2.0
lsmaira/gradle
subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/ivyservice/resolveengine/graph/conflicts/PotentialConflictFactory.java
2234
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.conflicts; import org.gradle.api.Action; import org.gradle.api.artifacts.ModuleIdentifier; import org.gradle.api.internal.artifacts.ivyservice.resolveengine.ComponentResolutionState; import java.util.Set; class PotentialConflictFactory { private static final PotentialConflict NO_CONFLICT = new NoConflict(); static PotentialConflict potentialConflict(final ConflictContainer<ModuleIdentifier, ? extends ComponentResolutionState>.Conflict conflict) { if (conflict == null) { return NO_CONFLICT; } return new HasConflict(conflict.participants); } static PotentialConflict noConflict() { return NO_CONFLICT; } private static class HasConflict implements PotentialConflict { private final Set<ModuleIdentifier> participants; private HasConflict(Set<ModuleIdentifier> participants) { this.participants = participants; } @Override public void withParticipatingModules(Action<ModuleIdentifier> action) { for (ModuleIdentifier participant : participants) { action.execute(participant); } } @Override public boolean conflictExists() { return true; } } private static class NoConflict implements PotentialConflict { @Override public void withParticipatingModules(Action<ModuleIdentifier> action) { } @Override public boolean conflictExists() { return false; } } }
apache-2.0
lgoldstein/communitychest
apps/tools/xmlstruct/src/main/java/net/community/apps/tools/xmlstruct/DocStructPanel.java
814
/* * */ package net.community.apps.tools.xmlstruct; import net.community.chest.CoVariantReturn; import net.community.chest.ui.components.tree.document.BaseDocumentPanel; /** * <P>Copyright 2008 as per GPLv2</P> * * @author Lyor G. * @since Jan 6, 2009 4:30:57 PM */ public class DocStructPanel extends BaseDocumentPanel { /** * */ private static final long serialVersionUID = -5033348104749825219L; public DocStructPanel (boolean autoLayout) { super(autoLayout); } public DocStructPanel () { this(true); } /* * @see net.community.chest.ui.components.tree.BaseDocumentPanel#createDocumentTree() */ @Override @CoVariantReturn protected DocStructTree createDocumentTree () { return new DocStructTree(); } }
apache-2.0
brskasimova/java_pft
sandbox/src/main/java/ru/stqa/pft/sandbox/Equality.java
435
package ru.stqa.pft.sandbox; import java.util.Objects; public class Equality { public static void main(String[] args) { String s1 = "firefox"; String s2 = new String(s1); System.out.println(s1 == s2); // сравнение ссылок - физтческое System.out.println(Objects.equals(s1, s2)); // сравнение содержимого объектов - логическое } }
apache-2.0
zIPjahoda/LogicalCircuitDesigner
LogCirDes/LogCirDes/Logics/LogicComponent.cs
1559
using LogCirDes.Logics; using System; using System.Collections.Generic; using System.Linq; using System.Net.Configuration; using System.Text; namespace LogCirDes { public abstract class LogicComponent { public event EventHandler StateChanged; public LogicInput[] Inputs { get { return Inputs; } set { if(value.Length < MinInputs) throw new Exception("You cannot have less than " + MinInputs + " inputs."); else if(value.Length > MaxInputs) throw new Exception("You cannot have more than " + MaxInputs + " inputs."); Inputs = value; } } public LogicOutput Output { get { return Output; } set { if(value == null) throw new Exception("Each component must have an output and " + "thus you cannot assign null to an output."); Output = value; } } public int MaxInputs { get { return MaxInputs; } set { MaxInputs = value; } } public int MinInputs { get; set; } public bool Value { get { Value = CalculateValue(); return Value; } private set { } } public bool ForcedValue { get; set; } protected abstract bool CalculateValue(); } }
apache-2.0
kyleolivo/gocd
server/test/unit/com/thoughtworks/go/server/service/GoConfigServiceTest.java
74104
/* * Copyright 2017 ThoughtWorks, 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 com.thoughtworks.go.server.service; import com.thoughtworks.go.config.*; import com.thoughtworks.go.config.exceptions.ConfigFileHasChangedException; import com.thoughtworks.go.config.exceptions.GoConfigInvalidException; import com.thoughtworks.go.config.exceptions.PipelineGroupNotFoundException; import com.thoughtworks.go.config.materials.MaterialConfigs; import com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig; import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig; import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig; import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry; import com.thoughtworks.go.config.remote.RepoConfigOrigin; import com.thoughtworks.go.config.server.security.ldap.BaseConfig; import com.thoughtworks.go.config.server.security.ldap.BasesConfig; import com.thoughtworks.go.config.update.ConfigUpdateResponse; import com.thoughtworks.go.config.update.FullConfigUpdateCommand; import com.thoughtworks.go.config.update.UiBasedConfigUpdateCommand; import com.thoughtworks.go.config.update.UpdateConfigFromUI; import com.thoughtworks.go.config.validation.GoConfigValidity; import com.thoughtworks.go.domain.*; import com.thoughtworks.go.domain.materials.MaterialConfig; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.helper.MaterialConfigsMother; import com.thoughtworks.go.helper.PipelineConfigMother; import com.thoughtworks.go.helper.StageConfigMother; import com.thoughtworks.go.i18n.Localizer; import com.thoughtworks.go.listener.BaseUrlChangeListener; import com.thoughtworks.go.listener.ConfigChangedListener; import com.thoughtworks.go.security.GoCipher; import com.thoughtworks.go.server.cache.GoCache; import com.thoughtworks.go.server.dao.UserDao; import com.thoughtworks.go.server.domain.PipelineConfigDependencyGraph; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.domain.user.PipelineSelections; import com.thoughtworks.go.server.persistence.PipelineRepository; import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult; import com.thoughtworks.go.service.ConfigRepository; import com.thoughtworks.go.util.*; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.core.IsInstanceOf; import org.jdom2.input.JDOMParseException; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.File; import java.util.*; import static com.thoughtworks.go.helper.ConfigFileFixture.configWith; import static com.thoughtworks.go.helper.PipelineConfigMother.createGroup; import static com.thoughtworks.go.helper.PipelineConfigMother.pipelineConfig; import static com.thoughtworks.go.helper.PipelineTemplateConfigMother.createTemplate; import static java.lang.String.format; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.nullValue; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class GoConfigServiceTest { private GoConfigDao goConfigDao; private GoConfigService goConfigService; private PipelineRepository pipelineRepository; private static final String PIPELINE = "pipeline1"; private static final String STAGE = "stage1"; private static final String JOB = "Job1"; private CruiseConfig cruiseConfig; private Clock clock; private GoCache goCache; private ConfigRepository configRepo; private UserDao userDao; public PipelinePauseService pipelinePauseService; private InstanceFactory instanceFactory; private SystemEnvironment systemEnvironment; @Before public void setup() throws Exception { new SystemEnvironment().setProperty(SystemEnvironment.ENFORCE_SERVERID_MUTABILITY, "N"); configRepo = mock(ConfigRepository.class); goConfigDao = mock(GoConfigDao.class); pipelineRepository = mock(PipelineRepository.class); pipelinePauseService = mock(PipelinePauseService.class); systemEnvironment = mock(SystemEnvironment.class); cruiseConfig = unchangedConfig(); expectLoad(cruiseConfig); this.clock = mock(Clock.class); goCache = mock(GoCache.class); instanceFactory = mock(InstanceFactory.class); userDao = mock(UserDao.class); stub(systemEnvironment.optimizeFullConfigSave()).toReturn(false); ConfigElementImplementationRegistry registry = ConfigElementImplementationRegistryMother.withNoPlugins(); goConfigService = new GoConfigService(goConfigDao, pipelineRepository, this.clock, new GoConfigMigration(configRepo, new TimeProvider(), new ConfigCache(), registry), goCache, configRepo, registry, instanceFactory, mock(CachedGoPartials.class), systemEnvironment); } @Test public void shouldUnderstandIfAnEnvironmentVariableIsConfiguredForAPipeline() throws Exception { final PipelineConfigs newPipeline = new BasicPipelineConfigs(); PipelineConfig otherPipeline = createPipelineConfig("pipeline_other", "stage_other", "plan_other"); otherPipeline.setVariables(GoConfigFileHelper.env("OTHER_PIPELINE_LEVEL", "other pipeline")); otherPipeline.first().setVariables(GoConfigFileHelper.env("OTHER_STAGE_LEVEL", "other stage")); otherPipeline.first().jobConfigByConfigName(new CaseInsensitiveString("plan_other")).setVariables(GoConfigFileHelper.env("OTHER_JOB_LEVEL", "other job")); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); pipelineConfig.setVariables(GoConfigFileHelper.env("PIPELINE_LEVEL", "pipeline value")); StageConfig stageConfig = pipelineConfig.first(); stageConfig.setVariables(GoConfigFileHelper.env("STAGE_LEVEL", "stage value")); stageConfig.jobConfigByConfigName(new CaseInsensitiveString("plan")).setVariables(GoConfigFileHelper.env("JOB_LEVEL", "job value")); newPipeline.add(pipelineConfig); newPipeline.add(otherPipeline); CruiseConfig cruiseConfig = new BasicCruiseConfig(newPipeline); EnvironmentConfig environmentConfig = cruiseConfig.addEnvironment("uat"); environmentConfig.addPipeline(new CaseInsensitiveString("pipeline")); environmentConfig.addEnvironmentVariable("ENV_LEVEL", "env value"); expectLoad(cruiseConfig); assertThat(goConfigService.hasVariableInScope("pipeline", "NOT_IN_SCOPE"), is(false)); assertThat(goConfigService.hasVariableInScope("pipeline", "ENV_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline", "PIPELINE_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline", "STAGE_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline", "JOB_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline", "OTHER_PIPELINE_LEVEL"), is(false)); assertThat(goConfigService.hasVariableInScope("pipeline", "OTHER_STAGE_LEVEL"), is(false)); assertThat(goConfigService.hasVariableInScope("pipeline", "OTHER_JOB_LEVEL"), is(false)); assertThat(goConfigService.hasVariableInScope("pipeline_other", "ENV_LEVEL"), is(false)); assertThat(goConfigService.hasVariableInScope("pipeline_other", "OTHER_PIPELINE_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline_other", "OTHER_STAGE_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline_other", "OTHER_JOB_LEVEL"), is(true)); assertThat(goConfigService.hasVariableInScope("pipeline_other", "NOT_IN_SCOPE"), is(false)); } @Test public void shouldUnderstandIfAStageHasFetchMaterialsConfigured() throws Exception { PipelineConfig pipeline = createPipelineConfig("cruise", "dev", "test"); StageConfig stage = pipeline.first(); stage.setFetchMaterials(false); CruiseConfig cruiseConfig = new BasicCruiseConfig(new BasicPipelineConfigs(pipeline)); expectLoad(cruiseConfig); assertThat(goConfigService.shouldFetchMaterials("cruise", "dev"), is(false)); } private void expectLoad(final CruiseConfig result) throws Exception { when(goConfigDao.load()).thenReturn(result); } private void expectLoadForEditing(final CruiseConfig result) throws Exception { when(goConfigDao.loadForEditing()).thenReturn(result); } private CruiseConfig unchangedConfig() { return configWith(createPipelineConfig(PIPELINE, STAGE, JOB)); } @Test public void shouldGetAllStagesWithOne() throws Exception { final PipelineConfigs newPipeline = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); newPipeline.add(pipelineConfig); expectLoad(new BasicCruiseConfig(newPipeline)); assertThat(goConfigService.stageConfigNamed("pipeline", "name"), is(pipelineConfig.findBy(new CaseInsensitiveString("name")))); } @Test public void shouldTellIfAnUSerIsGroupAdministrator() throws Exception { final PipelineConfigs newPipeline = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); newPipeline.add(pipelineConfig); newPipeline.setAuthorization(new Authorization(new AdminsConfig(new AdminUser(new CaseInsensitiveString("dawg"))))); expectLoad(new BasicCruiseConfig(newPipeline)); final Username dawg = new Username(new CaseInsensitiveString("dawg")); assertThat(goConfigService.isGroupAdministrator(dawg.getUsername()), is(true)); } @Test public void shouldTellIfAnEnvironmentExists() throws Exception { BasicEnvironmentConfig first = new BasicEnvironmentConfig(new CaseInsensitiveString("first")); BasicEnvironmentConfig second = new BasicEnvironmentConfig(new CaseInsensitiveString("second")); CruiseConfig config = new BasicCruiseConfig(); config.addEnvironment(first); config.addEnvironment(second); expectLoad(config); assertThat(goConfigService.hasEnvironmentNamed(new CaseInsensitiveString("first")), is(true)); assertThat(goConfigService.hasEnvironmentNamed(new CaseInsensitiveString("second")), is(true)); assertThat(goConfigService.hasEnvironmentNamed(new CaseInsensitiveString("SECOND")), is(true)); assertThat(goConfigService.hasEnvironmentNamed(new CaseInsensitiveString("fourth")), is(false)); } @Test public void shouldTellIfOnlyKnownUsersAreAllowedToLogin() throws Exception { CruiseConfig config = new BasicCruiseConfig(); config.server().security().setAllowOnlyKnownUsersToLogin(true); expectLoad(config); assertThat(goConfigService.isOnlyKnownUserAllowedToLogin(), is(true)); } @Test public void shouldTellIfAnAgentExists() throws Exception { CruiseConfig config = new BasicCruiseConfig(); config.agents().add(new AgentConfig("uuid")); expectLoad(config); assertThat(goConfigService.hasAgent("uuid"), is(true)); assertThat(goConfigService.hasAgent("doesnt-exist"), is(false)); } @Test public void shouldReturnTrueIfStageHasTestsAndFalseIfItDoesnt() throws Exception { PipelineConfigs newPipelines = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); pipelineConfig.add(StageConfigMother.stageConfigWithArtifact("stage1", "job1", ArtifactType.unit)); pipelineConfig.add(StageConfigMother.stageConfigWithArtifact("stage2", "job2", ArtifactType.file)); newPipelines.add(pipelineConfig); expectLoad(new BasicCruiseConfig(newPipelines)); assertThat(goConfigService.stageHasTests("pipeline", "stage1"), is(true)); assertThat(goConfigService.stageHasTests("pipeline", "stage2"), is(false)); } @Test public void shouldGetCommentRenderer() throws Exception { PipelineConfigs newPipeline = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); pipelineConfig.setTrackingTool(new TrackingTool("link", "regex")); newPipeline.add(pipelineConfig); expectLoad(new BasicCruiseConfig(newPipeline)); assertEquals(goConfigService.getCommentRendererFor("pipeline"), new TrackingTool("link", "regex")); pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); pipelineConfig.setMingleConfig(new MingleConfig("baseUrl", "projIdentifier", "mql")); newPipeline = new BasicPipelineConfigs(); newPipeline.add(pipelineConfig); expectLoad(new BasicCruiseConfig(newPipeline)); assertEquals(goConfigService.getCommentRendererFor("pipeline"), new MingleConfig("baseUrl", "projIdentifier", "mql")); pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); newPipeline = new BasicPipelineConfigs(); newPipeline.add(pipelineConfig); expectLoad(new BasicCruiseConfig(newPipeline)); assertEquals(goConfigService.getCommentRendererFor("pipeline"), new TrackingTool()); } @Test public void shouldUnderstandIfAPipelineIsLockable() throws Exception { PipelineConfigs group = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); group.add(pipelineConfig); expectLoad(new BasicCruiseConfig(group)); assertThat(goConfigService.isLockable("pipeline"), is(false)); pipelineConfig.lockExplicitly(); expectLoad(new BasicCruiseConfig(group)); assertThat(goConfigService.isLockable("pipeline"), is(true)); } @Test public void shouldUnderstandIfLdapIsConfigured() throws Exception { CruiseConfig config = new BasicCruiseConfig(); config.setServerConfig(new ServerConfig(null, new SecurityConfig(new LdapConfig("test", "test", "test", null, true, new BasesConfig(new BaseConfig("test")), "test"), null, true, null))); expectLoad(config); assertThat("Ldap is configured", goConfigService.isLdapConfigured(), is(true)); } @Test public void shouldRememberValidityWhenCruiseConfigLoaderHasInvalidConfigFile() throws Exception { GoConfigService service = goConfigServiceWithInvalidStatus(); assertThat(service.checkConfigFileValid().isValid(), is(false)); assertThat(service.checkConfigFileValid().errorMessage(), is("JDom exception")); } @Test public void shouldNotHaveErrorMessageWhenConfigFileValid() throws Exception { when(goConfigDao.checkConfigFileValid()).thenReturn(GoConfigValidity.valid()); GoConfigValidity configValidity = goConfigService.checkConfigFileValid(); assertThat(configValidity.isValid(), is(true)); assertThat(configValidity.errorMessage(), is("")); } private CruiseConfig configWithPipeline() { PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "stage", "first"); pipelineConfig.addMaterialConfig(MaterialConfigsMother.hgMaterialConfig()); CruiseConfig config = configWith(pipelineConfig); config.server().setArtifactsDir("/var/logs"); return config; } @Test public void shouldReturnInvalidWhenWholeConfigIsInvalidAndShouldUpgrade() throws Exception { CruiseConfig config = configWithPipeline(); when(goConfigDao.loadForEditing()).thenReturn(config); String configContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<cruise xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"cruise-config.xsd\" schemaVersion=\"14\">\n" + "<server artifactsdir='artifactsDir'/><unknown/></cruise>"; GoConfigValidity validity = goConfigService.fileSaver(true).saveXml(configContent, "md5"); assertThat(validity.errorMessage(), is("Cruise config file with version 14 is invalid. Unable to upgrade.")); } @Test public void shouldReturnInvalidWhenWholeConfigIsInvalid() throws Exception { CruiseConfig config = configWithPipeline(); when(goConfigDao.loadForEditing()).thenReturn(config); String configContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<cruise xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"cruise-config.xsd\" schemaVersion=\"" + GoConstants.CONFIG_SCHEMA_VERSION + "\">\n" + "<server artifactsdir='artifactsDir'/><unknown/></cruise>"; GoConfigValidity validity = goConfigService.fileSaver(false).saveXml(configContent, "md5"); assertThat(validity.errorMessage(), containsString("Invalid content was found starting with element 'unknown'")); } @Test public void shouldReturnvariablesForAPipeline() { EnvironmentConfig env = cruiseConfig.addEnvironment("environment"); env.addEnvironmentVariable("foo", "env-fooValue"); env.addEnvironmentVariable("bar", "env-barValue"); env.addPipeline(new CaseInsensitiveString(PIPELINE)); PipelineConfig pipeline = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString(PIPELINE)); pipeline.addEnvironmentVariable("foo", "pipeline-fooValue"); pipeline.addEnvironmentVariable("blah", "pipeline-blahValue"); EnvironmentVariablesConfig variables = goConfigService.variablesFor(PIPELINE); assertThat(variables.size(), is(3)); assertThat(variables, hasItems( new EnvironmentVariableConfig("foo", "pipeline-fooValue"), new EnvironmentVariableConfig("bar", "env-barValue"), new EnvironmentVariableConfig("blah", "pipeline-blahValue"))); } @Test public void shouldReturnvariablesForAPipelineNotInAnEnvironment() { PipelineConfig pipeline = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString(PIPELINE)); pipeline.addEnvironmentVariable("foo", "pipeline-fooValue"); pipeline.addEnvironmentVariable("blah", "pipeline-blahValue"); EnvironmentVariablesConfig variables = goConfigService.variablesFor(PIPELINE); assertThat(variables.size(), is(2)); assertThat(variables, hasItems( new EnvironmentVariableConfig("foo", "pipeline-fooValue"), new EnvironmentVariableConfig("blah", "pipeline-blahValue"))); } private PipelineConfig pipelineWithTemplate() { PipelineConfig pipeline = PipelineConfigMother.pipelineConfig("pipeline"); pipeline.clear(); pipeline.setTemplateName(new CaseInsensitiveString("foo")); PipelineTemplateConfig template = new PipelineTemplateConfig(new CaseInsensitiveString("foo"), StageConfigMother.custom("stage", "job")); pipeline.usingTemplate(template); return pipeline; } @Test public void shouldNotThrowExceptionWhenUpgradeFailsForConfigFileUpdate() throws Exception { expectLoadForEditing(configWith(createPipelineConfig("pipeline", "stage", "build"))); GoConfigService.XmlPartialSaver saver = goConfigService.fileSaver(true); GoConfigValidity validity = saver.saveXml("some_junk", "junk_md5"); assertThat(validity.isValid(), is(false)); assertThat(validity.errorMessage(), is("Error on line 1: Content is not allowed in prolog.")); } @Test public void shouldProvideDetailsWhenXmlConfigDomIsInvalid() throws Exception { expectLoadForEditing(configWith(createPipelineConfig("pipeline", "stage", "build"))); GoConfigService.XmlPartialSaver saver = goConfigService.fileSaver(false); String configContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<cruise xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"cruise-config.xsd\" schemaVersion=\"" + GoConstants.CONFIG_SCHEMA_VERSION + "\">\n" + "<server artifactsdir='artifactsDir></cruise>"; GoConfigValidity validity = saver.saveXml(configContent, "junk_md5"); assertThat(validity.isValid(), is(false)); assertThat(validity.errorMessage(), is("Invalid Configuration - Error on line 3: The value of attribute \"artifactsdir\" associated with an element type \"server\" must not contain the '<' character.")); } @Test public void xmlPartialSaverShouldReturnTheRightXMLThroughAsXml() throws Exception { expectLoadForEditing(new GoConfigMother().defaultCruiseConfig()); GoConfigService.XmlPartialSaver saver = goConfigService.fileSaver(true); assertThat(saver.asXml(), containsString(String.format("schemaVersion=\"%s\"", GoConstants.CONFIG_SCHEMA_VERSION))); assertThat(saver.asXml(), containsString("xsi:noNamespaceSchemaLocation=\"cruise-config.xsd\"")); } @Test public void shouldRegisterListenerWithTheConfigDAO() throws Exception { final ConfigChangedListener listener = mock(ConfigChangedListener.class); goConfigService.register(listener); verify(goConfigDao).registerListener(listener); } private CruiseConfig configWithAgents(AgentConfig... agentConfigs) { CruiseConfig cruiseConfig = unchangedConfig(); cruiseConfig.agents().addAll(Arrays.asList(agentConfigs)); return cruiseConfig; } @Test public void shouldFixJobNameCase() throws Exception { expectLoad(unchangedConfig()); JobConfigIdentifier translated = goConfigService.translateToActualCase( new JobConfigIdentifier(PIPELINE.toUpperCase(), STAGE.toUpperCase(), JOB.toUpperCase())); assertThat(translated, is(new JobConfigIdentifier(PIPELINE, STAGE, JOB))); } @Test public void shouldNotLoseUUIDWhenRunOnAllAgents() throws Exception { expectLoad(unchangedConfigWithRunOnAllAgents()); JobConfigIdentifier translated = goConfigService.translateToActualCase( new JobConfigIdentifier(PIPELINE.toUpperCase(), STAGE.toUpperCase(), RunOnAllAgents.CounterBasedJobNameGenerator.appendMarker(JOB.toUpperCase(), 2))); assertThat(translated, is(new JobConfigIdentifier(PIPELINE, STAGE, RunOnAllAgents.CounterBasedJobNameGenerator.appendMarker(JOB, 2)))); } @Test public void shouldNotBeInstanceOfWhenRunOnAllAgentsWithMissingAgent() throws Exception { expectLoad(unchangedConfigWithRunOnAllAgents()); String missingJobName = JOB + "-missing"; try { goConfigService.translateToActualCase(new JobConfigIdentifier(PIPELINE, STAGE, missingJobName)); fail("Should not be able to find job with missing agent"); } catch (JobNotFoundException expected) { assertThat(expected.getMessage(), is(format("Job '%s' not found in pipeline '%s' stage '%s'", missingJobName, PIPELINE, STAGE))); } } private CruiseConfig unchangedConfigWithRunOnAllAgents() { PipelineConfig pipelineConfig = createPipelineConfig(PIPELINE, STAGE, JOB); pipelineConfig.get(0).jobConfigByConfigName(new CaseInsensitiveString(JOB)).setRunOnAllAgents(true); return configWith(pipelineConfig); } @Test public void shouldThrowJobNotFoundExceptionWhenJobDoesNotExist() throws Exception { expectLoad(unchangedConfig()); try { goConfigService.translateToActualCase(new JobConfigIdentifier(PIPELINE, STAGE, "invalid-job")); fail("should throw exception if job does not exist"); } catch (Exception e) { assertThat(e, instanceOf(JobNotFoundException.class)); assertThat(e.getMessage(), containsString("invalid-job")); } } @Test public void shouldThrowStageNotFoundExceptionWhenStageDoesNotExist() throws Exception { expectLoad(unchangedConfig()); try { goConfigService.translateToActualCase(new JobConfigIdentifier(PIPELINE, "invalid-stage", JOB)); fail("should throw exception if stage does not exist"); } catch (Exception e) { assertThat(e, instanceOf(StageNotFoundException.class)); assertThat(e.getMessage(), containsString("invalid-stage")); } } @Test public void shouldThrowPipelineNotFoundExceptionWhenStageDoesNotExist() throws Exception { expectLoad(unchangedConfig()); try { goConfigService.translateToActualCase(new JobConfigIdentifier("invalid-pipeline", STAGE, JOB)); fail("should throw exception if pipeline does not exist"); } catch (Exception e) { assertThat(e, instanceOf(PipelineNotFoundException.class)); assertThat(e.getMessage(), containsString("invalid-pipeline")); } } @Test public void shouldThrowIfCruiseHasNoReadPermissionOnArtifactsDir() throws Exception { if (SystemUtil.isWindows()) { return; } File artifactsDir = FileUtil.createTempFolder(); artifactsDir.setReadable(false, false); cruiseConfig.setServerConfig(new ServerConfig(artifactsDir.getAbsolutePath(), new SecurityConfig())); expectLoad(cruiseConfig); try { goConfigService.initialize(); fail("should throw when cruise has no read permission on artifacts dir " + artifactsDir.getAbsolutePath()); } catch (Exception e) { assertThat(e.getMessage(), is("Cruise does not have read permission on " + artifactsDir.getAbsolutePath())); } finally { FileUtil.deleteFolder(artifactsDir); } } @Test public void shouldThrowIfCruiseHasNoWritePermissionOnArtifactsDir() throws Exception { if (SystemUtil.isWindows()) { return; } File artifactsDir = FileUtil.createTempFolder(); artifactsDir.setWritable(false, false); cruiseConfig.setServerConfig(new ServerConfig(artifactsDir.getAbsolutePath(), new SecurityConfig())); expectLoad(cruiseConfig); try { goConfigService.initialize(); fail("should throw when cruise has no write permission on artifacts dir " + artifactsDir.getAbsolutePath()); } catch (Exception e) { assertThat(e.getMessage(), is("Cruise does not have write permission on " + artifactsDir.getAbsolutePath())); } finally { FileUtil.deleteFolder(artifactsDir); } } @Test public void shouldFindMaterialByPipelineUniqueFingerprint() throws Exception { SvnMaterialConfig svnMaterialConfig = new SvnMaterialConfig("repo", null, null, false); svnMaterialConfig.setName(new CaseInsensitiveString("foo")); cruiseConfig = configWith(GoConfigMother.createPipelineConfigWithMaterialConfig(svnMaterialConfig)); when(goConfigDao.load()).thenReturn(cruiseConfig); assertThat(goConfigService.findMaterial(new CaseInsensitiveString("pipeline"), svnMaterialConfig.getPipelineUniqueFingerprint()), is(svnMaterialConfig)); assertThat(goConfigService.findMaterial(new CaseInsensitiveString("piPelIne"), svnMaterialConfig.getPipelineUniqueFingerprint()), is(svnMaterialConfig)); } @Test public void shouldReturnNullIfNoMaterialMatches() throws Exception { DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(new CaseInsensitiveString("upstream-pipeline"), new CaseInsensitiveString("upstream-stage")); cruiseConfig = configWith(GoConfigMother.createPipelineConfigWithMaterialConfig(dependencyMaterialConfig)); when(goConfigDao.load()).thenReturn(cruiseConfig); assertThat(goConfigService.findMaterial(new CaseInsensitiveString("pipeline"), "missing"), is(nullValue())); } @Test public void shouldFindMaterialConfigBasedOnFingerprint() throws Exception { SvnMaterialConfig expected = new SvnMaterialConfig("repo", null, null, false); cruiseConfig = configWith(GoConfigMother.createPipelineConfigWithMaterialConfig(expected)); when(goConfigDao.load()).thenReturn(cruiseConfig); MaterialConfig actual = goConfigService.materialForPipelineWithFingerprint("pipeline", expected.getFingerprint()); assertThat(actual, is(expected)); } @Test public void shouldThrowExceptionWhenUnableToFindMaterialBasedOnFingerprint() throws Exception { SvnMaterialConfig svnMaterialConfig = new SvnMaterialConfig("repo", null, null, false); cruiseConfig = configWith(GoConfigMother.createPipelineConfigWithMaterialConfig(svnMaterialConfig)); when(goConfigDao.load()).thenReturn(cruiseConfig); try { goConfigService.materialForPipelineWithFingerprint("pipeline", "bad-fingerprint"); fail("Shouldn't be able to find material with incorrect fingerprint"); } catch (Exception expected) { assertThat(expected.getMessage(), is("Pipeline [pipeline] does not have a material with fingerprint [bad-fingerprint]")); } } @Test public void shouldReturnDependentPiplinesForAGivenPipeline() throws Exception { PipelineConfig up = createPipelineConfig("blahPipeline", "blahStage"); up.addMaterialConfig(MaterialConfigsMother.hgMaterialConfig()); PipelineConfig down1 = GoConfigMother.createPipelineConfigWithMaterialConfig("down1", new DependencyMaterialConfig(new CaseInsensitiveString("blahPipeline"), new CaseInsensitiveString("blahStage"))); PipelineConfig down2 = GoConfigMother.createPipelineConfigWithMaterialConfig("down2", new DependencyMaterialConfig(new CaseInsensitiveString("blahPipeline"), new CaseInsensitiveString("blahStage"))); when(goConfigDao.load()).thenReturn(configWith( up, down1, down2, GoConfigMother.createPipelineConfigWithMaterialConfig("otherPipeline", new DependencyMaterialConfig(new CaseInsensitiveString("someotherpipeline"), new CaseInsensitiveString("blahStage"))) )); assertThat(goConfigService.downstreamPipelinesOf("blahPipeline"), is(Arrays.asList(down1, down2))); } @Test public void shouldReturnUpstreamDependencyGraphForAGivenPipeline() throws Exception { PipelineConfig current = GoConfigMother.createPipelineConfigWithMaterialConfig("current", new DependencyMaterialConfig(new CaseInsensitiveString("up1"), new CaseInsensitiveString("first")), new DependencyMaterialConfig(new CaseInsensitiveString("up2"), new CaseInsensitiveString("first"))); PipelineConfig up1 = GoConfigMother.createPipelineConfigWithMaterialConfig("up1", new DependencyMaterialConfig(new CaseInsensitiveString("uppest"), new CaseInsensitiveString("first"))); PipelineConfig up2 = GoConfigMother.createPipelineConfigWithMaterialConfig("up2", new DependencyMaterialConfig(new CaseInsensitiveString("uppest"), new CaseInsensitiveString("first"))); PipelineConfig uppest = GoConfigMother.createPipelineConfigWithMaterialConfig("uppest", MaterialConfigsMother.hgMaterialConfig()); when(goConfigDao.load()).thenReturn(configWith(current, up1, up2, uppest)); assertThat(goConfigService.upstreamDependencyGraphOf("current"), is( new PipelineConfigDependencyGraph(current, new PipelineConfigDependencyGraph(up1, new PipelineConfigDependencyGraph(uppest)), new PipelineConfigDependencyGraph(up2, new PipelineConfigDependencyGraph(uppest)) ))); /* uppest / \ up1 up2 \ / current */ } @Test public void shouldDetermineIfStageExistsInCurrentConfig() throws Exception { PipelineConfigs pipelineConfigs = new BasicPipelineConfigs(); pipelineConfigs.add(createPipelineConfig("pipeline", "stage", "job")); expectLoad(new BasicCruiseConfig(pipelineConfigs)); assertThat(goConfigService.stageExists("pipeline", "randomstage"), is(false)); assertThat(goConfigService.stageExists("pipeline", "stage"), is(true)); } @Test public void shouldPersistPipelineSelections_WhenSecurityIsDisabled() { Date date = new DateTime(2000, 1, 1, 1, 1, 1, 1).toDate(); when(clock.currentTime()).thenReturn(date); mockConfig(); Matcher<PipelineSelections> pipelineSelectionsMatcher = hasValues(Arrays.asList("pipelineX", "pipeline3"), Arrays.asList("pipeline1", "pipeline2"), date, null); when(pipelineRepository.saveSelectedPipelines(argThat(pipelineSelectionsMatcher))).thenReturn(2L); assertThat(goConfigService.persistSelectedPipelines(null, null, Arrays.asList("pipelineX", "pipeline3"), true), is(2l)); verify(pipelineRepository).saveSelectedPipelines(argThat(pipelineSelectionsMatcher)); } @Test public void shouldPersistPipelineSelectionsAgainstUser_AlreadyHavingSelections() { Date date = new DateTime(2000, 1, 1, 1, 1, 1, 1).toDate(); when(clock.currentTime()).thenReturn(date); mockConfigWithSecurity(); User user = getUser("badger", 10L); PipelineSelections pipelineSelections = new PipelineSelections(Arrays.asList("pipeline2"), new Date(), user.getId(), true); when(pipelineRepository.findPipelineSelectionsByUserId(user.getId())).thenReturn(pipelineSelections); when(pipelineRepository.saveSelectedPipelines(pipelineSelections)).thenReturn(2L); long pipelineSelectionId = goConfigService.persistSelectedPipelines("1", user.getId(), Arrays.asList("pipelineX", "pipeline3"), true); assertThat(pipelineSelections.getSelections(), is("pipeline1,pipeline2")); assertThat(pipelineSelectionId, is(2l)); verify(pipelineRepository).saveSelectedPipelines(pipelineSelections); verify(pipelineRepository).findPipelineSelectionsByUserId(user.getId()); verify(pipelineRepository, never()).findPipelineSelectionsById("1"); } @Test public void shouldPersistPipelineSelectionsAgainstUser_WhenUserHasNoSelections() { Date date = new DateTime(2000, 1, 1, 1, 1, 1, 1).toDate(); when(clock.currentTime()).thenReturn(date); mockConfigWithSecurity(); User user = getUser("badger", 10L); Matcher<PipelineSelections> pipelineSelectionsMatcher = hasValues(Arrays.asList("pipelineX", "pipeline3"), Arrays.asList("pipeline1", "pipeline2"), date, user.getId()); when(pipelineRepository.findPipelineSelectionsByUserId(user.getId())).thenReturn(null); when(pipelineRepository.saveSelectedPipelines(argThat(pipelineSelectionsMatcher))).thenReturn(2L); long pipelineSelectionsId = goConfigService.persistSelectedPipelines("1", user.getId(), Arrays.asList("pipelineX", "pipeline3"), true); assertThat(pipelineSelectionsId, is(2l)); verify(pipelineRepository).saveSelectedPipelines(argThat(pipelineSelectionsMatcher)); verify(pipelineRepository).findPipelineSelectionsByUserId(user.getId()); verify(pipelineRepository, never()).findPipelineSelectionsById("1"); } @Test public void shouldPersistPipelineSelectionsShouldRemovePipelinesFromSelectedGroups() { CruiseConfig config = configWith( createGroup("group1", pipelineConfig("pipeline1"), pipelineConfig("pipeline2")), createGroup("group2", pipelineConfig("pipelineX")), createGroup("group3", pipelineConfig("pipeline3"), pipelineConfig("pipeline4"))); when(goConfigDao.load()).thenReturn(config); goConfigService.persistSelectedPipelines(null, null, Arrays.asList("pipeline1", "pipeline2", "pipeline3"), true); verify(pipelineRepository).saveSelectedPipelines(argThat(hasValues(Arrays.asList("pipeline1", "pipeline2", "pipeline3"), Arrays.asList("pipelineX", "pipeline4"), clock.currentTime(), null))); } @Test public void shouldPersistInvertedListOfPipelineSelections_WhenBlacklistIsSelected() { Date date = new DateTime(2000, 1, 1, 1, 1, 1, 1).toDate(); when(clock.currentTime()).thenReturn(date); mockConfigWithSecurity(); User user = getUser("badger", 10L); PipelineSelections blacklistPipelineSelections = new PipelineSelections(new ArrayList<>(), date, user.getId(), false); when(pipelineRepository.findPipelineSelectionsByUserId(user.getId())).thenReturn(blacklistPipelineSelections); goConfigService.persistSelectedPipelines(null, user.getId(), Arrays.asList("pipelineX", "pipeline3"), true); verify(pipelineRepository).saveSelectedPipelines(argThat(isAPipelineSelectionsInstanceWith(true, "pipeline1", "pipeline2"))); } @Test public void shouldPersistNonInvertedListOfPipelineSelections_WhenWhitelistIsSelected() { Date date = new DateTime(2000, 1, 1, 1, 1, 1, 1).toDate(); when(clock.currentTime()).thenReturn(date); mockConfigWithSecurity(); User user = getUser("badger", 10L); PipelineSelections whitelistPipelineSelections = new PipelineSelections(new ArrayList<>(), date, user.getId(), true); when(pipelineRepository.findPipelineSelectionsByUserId(user.getId())).thenReturn(whitelistPipelineSelections); goConfigService.persistSelectedPipelines(null, user.getId(), Arrays.asList("pipelineX", "pipeline3"), false); verify(pipelineRepository).saveSelectedPipelines(argThat(isAPipelineSelectionsInstanceWith(false, "pipelineX", "pipeline3"))); } @Test public void shouldUpdateAlreadyPersistedSelection_WhenSecurityIsDisabled() { Date date = new DateTime(2000, 1, 1, 1, 1, 1, 1).toDate(); when(clock.currentTime()).thenReturn(date); mockConfig(); PipelineSelections pipelineSelections = new PipelineSelections(Arrays.asList("pip1")); when(pipelineRepository.findPipelineSelectionsById("123")).thenReturn(pipelineSelections); List<String> newPipelines = Arrays.asList("pipeline1", "pipeline2"); goConfigService.persistSelectedPipelines("123", null, newPipelines, true); assertHasSelected(pipelineSelections, newPipelines); assertThat(pipelineSelections.lastUpdated(), is(date)); verify(pipelineRepository).findPipelineSelectionsById("123"); verify(pipelineRepository).saveSelectedPipelines(argThat(hasValues(Arrays.asList("pipeline1", "pipeline2"), Arrays.asList("pipelineX", "pipeline3"), clock.currentTime(), null))); } @Test public void shouldReturnPersistedPipelineSelectionsAgainstCookieId_WhenSecurityisDisabled() { PipelineSelections pipelineSelections = new PipelineSelections(Arrays.asList("pip1")); when(pipelineRepository.findPipelineSelectionsById("123")).thenReturn(pipelineSelections); assertThat(goConfigService.getSelectedPipelines("123", null), is(pipelineSelections)); assertThat(goConfigService.getSelectedPipelines("", null), is(PipelineSelections.ALL)); assertThat(goConfigService.getSelectedPipelines("345", null), is(PipelineSelections.ALL)); } @Test public void shouldReturnPersistedPipelineSelectionsAgainstUser_WhenSecurityIsEnabled() { User loser = getUser("loser", 10L); User newUser = getUser("new user", 20L); when(userDao.findUser("new user")).thenReturn(newUser); mockConfigWithSecurity(); PipelineSelections pipelineSelections = new PipelineSelections(Arrays.asList("pip1")); when(pipelineRepository.findPipelineSelectionsByUserId(loser.getId())).thenReturn(pipelineSelections); assertThat(goConfigService.getSelectedPipelines("1", loser.getId()), is(pipelineSelections)); assertThat(goConfigService.getSelectedPipelines("1", newUser.getId()), is(PipelineSelections.ALL)); } @Test public void shouldReturnAllPipelineSelections_WhenSecurityIsEnabled_AndNoPersistedSelections() { User user = getUser("loser", 10L); User newUser = getUser("new user", 20L); when(userDao.findUser("new user")).thenReturn(newUser); mockConfigWithSecurity(); when(pipelineRepository.findPipelineSelectionsByUserId(user.getId())).thenReturn(null); when(pipelineRepository.findPipelineSelectionsById("1")).thenReturn(null); assertThat(goConfigService.getSelectedPipelines("1", newUser.getId()), is(PipelineSelections.ALL)); } @Test public void shouldReturnPersistedPipelineSelectionsAgainstCookieId_WhenSecurityIsEnabled_AndUserSelectionsDoesNotExist() { User user = getUser("loser", 10L); mockConfigWithSecurity(); PipelineSelections pipelineSelections = new PipelineSelections(Arrays.asList("pip1")); when(pipelineRepository.findPipelineSelectionsByUserId(user.getId())).thenReturn(null); when(pipelineRepository.findPipelineSelectionsById("1")).thenReturn(pipelineSelections); assertThat(goConfigService.getSelectedPipelines("1", user.getId()), is(pipelineSelections)); } @Test public void shouldRegisterBaseUrlChangeListener() throws Exception { CruiseConfig cruiseConfig = new GoConfigMother().cruiseConfigWithOnePipelineGroup(); stub(goConfigDao.load()).toReturn(cruiseConfig); goConfigService.initialize(); verify(goConfigDao).registerListener(any(BaseUrlChangeListener.class)); } @Test public void getConfigAtVersion_shouldFetchRequiredVersion() throws Exception { GoConfigRevision revision = new GoConfigRevision("v1", "md5-1", "loser", "100.3.9.1", new TimeProvider()); when(configRepo.getRevision("md5-1")).thenReturn(revision); assertThat(goConfigService.getConfigAtVersion("md5-1"), is(revision)); } @Test public void getNotThrowUpWhenRevisionIsNotFound() throws Exception { when(configRepo.getRevision("md5-1")).thenThrow(new IllegalArgumentException("did not find the revision")); try { assertThat(goConfigService.getConfigAtVersion("md5-1"), is(nullValue())); } catch (Exception e) { fail("should not have thrown up"); } } @Test public void shouldReturnListOfUpstreamPipelineConfigValidForFetchArtifact() { PipelineConfig unrelatedPipeline = PipelineConfigMother.pipelineConfig("some.random.pipeline"); PipelineConfig upstream = PipelineConfigMother.createPipelineConfig("upstream", "upstream.stage", "upstream.job"); upstream.add(StageConfigMother.stageConfig("upstream.stage.2")); upstream.add(StageConfigMother.stageConfig("upstream.stage.3")); PipelineConfig downstream = PipelineConfigMother.createPipelineConfig("pipeline", "stage.1", "jobs"); downstream.add(StageConfigMother.stageConfig("stage.2")); downstream.add(StageConfigMother.stageConfig("current.stage")); downstream.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("upstream"), new CaseInsensitiveString("upstream.stage.2"))); CruiseConfig cruiseConfig = configWith(upstream, downstream, unrelatedPipeline); when(goConfigDao.load()).thenReturn(cruiseConfig); List<PipelineConfig> fetchablePipelines = goConfigService.pipelinesForFetchArtifacts("pipeline"); assertThat(fetchablePipelines.size(), is(2)); assertThat(fetchablePipelines, hasItem(upstream)); assertThat(fetchablePipelines, hasItem(downstream)); } @Test public void uiBasedUpdateCommandShouldReturnTheConfigPassedByUpdateOperation() { UiBasedConfigUpdateCommand command = new UiBasedConfigUpdateCommand("md5", null, null, null) { public boolean canContinue(CruiseConfig cruiseConfig) { return true; } }; CruiseConfig after = new BasicCruiseConfig(); command.afterUpdate(after); assertThat(command.configAfter(), sameInstance(after)); } @Test public void shouldUseInstanceFactoryToCreateAStageInstanceForTheSpecifiedPipelineStageCombination() throws Exception { PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("foo-pipeline", "foo-stage", "foo-job"); DefaultSchedulingContext schedulingContext = new DefaultSchedulingContext("loser"); String md5 = "foo-md5"; CruiseConfig config = mock(BasicCruiseConfig.class); when(config.pipelineConfigByName(new CaseInsensitiveString("foo-pipeline"))).thenReturn(pipelineConfig); when(config.getMd5()).thenReturn(md5); when(goConfigDao.load()).thenReturn(config); goConfigService.scheduleStage("foo-pipeline", "foo-stage", schedulingContext); verify(instanceFactory).createStageInstance(pipelineConfig, new CaseInsensitiveString("foo-stage"), schedulingContext, md5, clock); } @Test public void shouldReturnFalseIfMD5DoesNotMatch() { String staleMd5 = "oldmd5"; when(goConfigDao.md5OfConfigFile()).thenReturn("newmd5"); assertThat(goConfigService.doesMd5Match(staleMd5), is(false)); } @Test public void shouldReturnTrueifMd5Matches() { String staleMd5 = "md5"; when(goConfigDao.md5OfConfigFile()).thenReturn("md5"); assertThat(goConfigService.doesMd5Match(staleMd5), is(true)); } @Test public void shouldThrowExceptionIfGroupDoesNotExist_WhenUserIsAdmin() { CaseInsensitiveString adminName = new CaseInsensitiveString("admin"); GoConfigMother mother = new GoConfigMother(); mother.enableSecurityWithPasswordFile(cruiseConfig); cruiseConfig.server().security().adminsConfig().add(new AdminUser(adminName)); String groupName = String.format("group_%s", UUID.randomUUID()); try { goConfigService.isUserAdminOfGroup(adminName, groupName); fail("Should fail since group does not exist"); } catch (Exception e) { assertThat(e, is(instanceOf(PipelineGroupNotFoundException.class))); } } @Test public void shouldThrowExceptionIfGroupDoesNotExist_WhenUserIsNonAdmin() { CaseInsensitiveString adminName = new CaseInsensitiveString("admin"); String groupName = String.format("group_%s", UUID.randomUUID()); GoConfigMother mother = new GoConfigMother(); mother.enableSecurityWithPasswordFile(cruiseConfig); cruiseConfig.server().security().adminsConfig().add(new AdminUser(adminName)); try { goConfigService.isUserAdminOfGroup(new CaseInsensitiveString("foo"), groupName); fail("Should fail since group does not exist"); } catch (Exception e) { assertThat(e, is(instanceOf(PipelineGroupNotFoundException.class))); } } @Test public void shouldReturnTrueIfUserIsTheAdminForGroup() { CaseInsensitiveString adminName = new CaseInsensitiveString("admin"); String groupName = String.format("group_%s", UUID.randomUUID()); GoConfigMother mother = new GoConfigMother(); mother.enableSecurityWithPasswordFile(cruiseConfig); cruiseConfig.server().security().adminsConfig().add(new AdminUser(adminName)); mother.addPipelineWithGroup(cruiseConfig, groupName, "pipeline", "stage"); mother.addAdminUserForPipelineGroup(cruiseConfig, "user", groupName); assertThat(goConfigService.isUserAdminOfGroup(new CaseInsensitiveString("user"), groupName), is(true)); } @Test public void shouldReturnValidOnUpdateXml() throws Exception { String groupName = "group_name"; String md5 = "md5"; cruiseConfig = new BasicCruiseConfig(); expectLoad(cruiseConfig); new GoConfigMother().addPipelineWithGroup(cruiseConfig, groupName, "pipeline_name", "stage_name", "job_name"); expectLoadForEditing(cruiseConfig); when(goConfigDao.md5OfConfigFile()).thenReturn(md5); GoConfigService.XmlPartialSaver partialSaver = goConfigService.groupSaver(groupName); String renamedGroupName = "renamed_group_name"; GoConfigValidity validity = partialSaver.saveXml(groupXml(renamedGroupName), md5); assertThat(validity.isValid(), Matchers.is(true)); assertThat(validity.errorMessage(), Matchers.is("")); verify(goConfigDao).updateConfig(argThat(cruiseConfigIsUpdatedWith(renamedGroupName, "new_name", "${COUNT}-#{foo}"))); } @Test public void shouldUpdateXmlUsingNewFlowIfEnabled() throws Exception { String groupName = "group_name"; String md5 = "md5"; cruiseConfig = new BasicCruiseConfig(); ArgumentCaptor<FullConfigUpdateCommand> commandArgumentCaptor = ArgumentCaptor.forClass(FullConfigUpdateCommand.class); expectLoad(cruiseConfig); new GoConfigMother().addPipelineWithGroup(cruiseConfig, groupName, "pipeline_name", "stage_name", "job_name"); expectLoadForEditing(cruiseConfig); when(goConfigDao.md5OfConfigFile()).thenReturn(md5); when(systemEnvironment.optimizeFullConfigSave()).thenReturn(true); when(goConfigDao.updateFullConfig(commandArgumentCaptor.capture())).thenReturn(null); GoConfigService.XmlPartialSaver partialSaver = goConfigService.groupSaver(groupName); String renamedGroupName = "renamed_group_name"; GoConfigValidity validity = partialSaver.saveXml(groupXml(renamedGroupName), md5); assertThat(validity.isValid(), Matchers.is(true)); assertThat(validity.errorMessage(), Matchers.is("")); CruiseConfig updatedConfig = commandArgumentCaptor.getValue().configForEdit(); PipelineConfigs group = updatedConfig.findGroup(renamedGroupName); PipelineConfig pipeline = group.findBy(new CaseInsensitiveString("new_name")); assertThat(pipeline.name(), is(new CaseInsensitiveString("new_name"))); assertThat(pipeline.getLabelTemplate(), is("${COUNT}-#{foo}")); assertThat(pipeline.materialConfigs().first(), is(IsInstanceOf.instanceOf(SvnMaterialConfig.class))); assertThat(pipeline.materialConfigs().first().getUriForDisplay(), is("file:///tmp/foo")); } @Test public void shouldReturnInvalidWhenPipelineGroupPartialIsInvalid() throws Exception { String groupName = "group_name"; String md5 = "md5"; cruiseConfig = new BasicCruiseConfig(); expectLoad(cruiseConfig); new GoConfigMother().addPipelineWithGroup(cruiseConfig, groupName, "pipeline_name", "stage_name", "job_name"); expectLoadForEditing(cruiseConfig); when(goConfigDao.md5OfConfigFile()).thenReturn(md5); String pipelineGroupContent = groupXmlWithInvalidElement(groupName); GoConfigValidity validity = goConfigService.groupSaver(groupName).saveXml(pipelineGroupContent, "md5"); assertThat(validity.isValid(), Matchers.is(false)); assertThat(validity.errorMessage(), containsString("Invalid content was found starting with element 'unknown'")); verify(goConfigDao, never()).updateConfig(any(UpdateConfigCommand.class)); } @Test public void shouldReturnInvalidWhenPipelineGroupPartialHasInvalidAttributeValue() throws Exception { String groupName = "group_name"; String md5 = "md5"; cruiseConfig = new BasicCruiseConfig(); expectLoad(cruiseConfig); new GoConfigMother().addPipelineWithGroup(cruiseConfig, groupName, "pipeline_name", "stage_name", "job_name"); expectLoadForEditing(cruiseConfig); when(goConfigDao.md5OfConfigFile()).thenReturn(md5); String pipelineGroupContent = groupXmlWithInvalidAttributeValue(groupName); GoConfigValidity validity = goConfigService.groupSaver(groupName).saveXml(pipelineGroupContent, "md5"); assertThat(validity.isValid(), Matchers.is(false)); assertThat(validity.errorMessage(), containsString("Name is invalid. \"pipeline@$^\"")); verify(goConfigDao, never()).updateConfig(any(UpdateConfigCommand.class)); } @Test public void shouldReturnInvalidWhenPipelineGroupPartialXmlIsInvalid() throws Exception { String groupName = "group_name"; String md5 = "md5"; cruiseConfig = new BasicCruiseConfig(); expectLoad(cruiseConfig); new GoConfigMother().addPipelineWithGroup(cruiseConfig, groupName, "pipeline_name", "stage_name", "job_name"); expectLoadForEditing(cruiseConfig); when(goConfigDao.md5OfConfigFile()).thenReturn(md5); GoConfigValidity validity = goConfigService.groupSaver(groupName).saveXml("<foobar>", "md5"); assertThat(validity.isValid(), Matchers.is(false)); assertThat(validity.errorMessage(), containsString("XML document structures must start and end within the same entity")); verify(goConfigDao, never()).updateConfig(any(UpdateConfigCommand.class)); } @Test public void shouldFindConfigChangesForGivenConfigMd5() throws Exception { goConfigService.configChangesFor("md5-5", "md5-4", new HttpLocalizedOperationResult()); verify(configRepo).configChangesFor("md5-5", "md5-4"); } @Test public void shouldUpdateResultAsConfigRevisionNotFoundWhenConfigChangeIsNotFound() throws Exception { HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); Localizer localizer = mock(Localizer.class); when(configRepo.configChangesFor("md5-5", "md5-4")).thenThrow(new IllegalArgumentException("something")); goConfigService.configChangesFor("md5-5", "md5-4", result); assertThat(result.isSuccessful(), is(false)); assertThat(result.httpCode(), is(SC_BAD_REQUEST)); result.message(localizer); verify(localizer).localize("CONFIG_VERSION_NOT_FOUND", new Object[]{}); } @Test public void shouldUpdateResultAsCouldNotRetrieveConfigDiffWhenGenericExceptionOccurs() throws Exception { HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); Localizer localizer = mock(Localizer.class); when(configRepo.configChangesFor("md5-5", "md5-4")).thenThrow(new RuntimeException("something")); goConfigService.configChangesFor("md5-5", "md5-4", result); assertThat(result.isSuccessful(), is(false)); assertThat(result.httpCode(), is(SC_INTERNAL_SERVER_ERROR)); result.message(localizer); verify(localizer).localize("COULD_NOT_RETRIEVE_CONFIG_DIFF", new Object[]{}); } @Test public void shouldReturnWasMergedInConfigUpdateResponse_WhenConfigIsMerged() { when(goConfigDao.updateConfig(org.mockito.Matchers.<UpdateConfigCommand>any())).thenReturn(ConfigSaveState.MERGED); ConfigUpdateResponse configUpdateResponse = goConfigService.updateConfigFromUI(mock(UpdateConfigFromUI.class), "md5", new Username(new CaseInsensitiveString("user")), new HttpLocalizedOperationResult()); assertThat(configUpdateResponse.wasMerged(), is(true)); } @Test public void shouldReturnNotMergedInConfigUpdateResponse_WhenConfigIsUpdated() { when(goConfigDao.updateConfig(org.mockito.Matchers.<UpdateConfigCommand>any())).thenReturn(ConfigSaveState.UPDATED); ConfigUpdateResponse configUpdateResponse = goConfigService.updateConfigFromUI(mock(UpdateConfigFromUI.class), "md5", new Username(new CaseInsensitiveString("user")), new HttpLocalizedOperationResult()); assertThat(configUpdateResponse.wasMerged(), is(false)); } @Test public void shouldReturnNotMergedInConfigUpdateResponse_WhenConfigUpdateFailed() throws Exception { when(goConfigDao.updateConfig(org.mockito.Matchers.<UpdateConfigCommand>any())).thenThrow(new ConfigFileHasChangedException()); expectLoadForEditing(cruiseConfig); ConfigUpdateResponse configUpdateResponse = goConfigService.updateConfigFromUI(mock(UpdateConfigFromUI.class), "md5", new Username(new CaseInsensitiveString("user")), new HttpLocalizedOperationResult()); assertThat(configUpdateResponse.wasMerged(), is(false)); } @Test public void badConfigShouldContainOldMD5_WhenConfigUpdateFailed(){ when(goConfigDao.updateConfig(org.mockito.Matchers.<UpdateConfigCommand>any())).thenThrow(new RuntimeException(getGoConfigInvalidException())); ConfigUpdateResponse configUpdateResponse = goConfigService.updateConfigFromUI(mock(UpdateConfigFromUI.class), "old-md5", new Username(new CaseInsensitiveString("user")), new HttpLocalizedOperationResult()); assertThat(configUpdateResponse.wasMerged(), is(false)); assertThat(configUpdateResponse.getCruiseConfig().getMd5(), is("old-md5")); } @Test public void configShouldContainOldMD5_WhenConfigMergeFailed(){ when(goConfigDao.loadForEditing()).thenReturn(new BasicCruiseConfig()); when(goConfigDao.updateConfig(org.mockito.Matchers.<UpdateConfigCommand>any())).thenThrow(new ConfigFileHasChangedException()); ConfigUpdateResponse configUpdateResponse = goConfigService.updateConfigFromUI(mock(UpdateConfigFromUI.class), "old-md5", new Username(new CaseInsensitiveString("user")), new HttpLocalizedOperationResult()); assertThat(configUpdateResponse.wasMerged(), is(false)); assertThat(configUpdateResponse.getCruiseConfig().getMd5(), is("old-md5")); } @Test public void shouldReturnConfigStateFromDaoLayer_WhenUpdatingServerConfig() { ConfigSaveState expectedSaveState = ConfigSaveState.MERGED; when(goConfigDao.updateConfig(org.mockito.Matchers.<UpdateConfigCommand>any())).thenReturn(expectedSaveState); ConfigSaveState configSaveState = goConfigService.updateServerConfig(new MailHost(new GoCipher()), null, null, true, "md5", null, null, null, null, "http://site", "https://site", "location"); assertThat(configSaveState, is(expectedSaveState)); } @Test public void shouldDelegateToConfig_getAllPipelinesInGroup() throws Exception { CruiseConfig cruiseConfig = mock(BasicCruiseConfig.class); expectLoad(cruiseConfig); goConfigService.getAllPipelinesInGroup("group"); verify(cruiseConfig).pipelines("group"); } @Test public void shouldNotUpdatePipelineSelectionsWhenTheUserIsAnonymousAndHasNeverSelectedPipelines() { goConfigService.updateUserPipelineSelections(null, null, new CaseInsensitiveString("pipelineNew")); verify(pipelineRepository, times(0)).saveSelectedPipelines(argThat(Matchers.any(PipelineSelections.class))); } @Test public void shouldNotUpdatePipelineSelectionsWhenTheUserIsAnonymousAndHasSelectedPipelines_WithBlacklist() { when(pipelineRepository.findPipelineSelectionsById("1")).thenReturn(new PipelineSelections(Arrays.asList("pipeline1", "pipeline2"), null, null, true)); goConfigService.updateUserPipelineSelections("1", null, new CaseInsensitiveString("pipelineNew")); verify(pipelineRepository).findPipelineSelectionsById("1"); verify(pipelineRepository, times(0)).saveSelectedPipelines(argThat(Matchers.any(PipelineSelections.class))); } @Test public void shouldUpdatePipelineSelectionsWhenTheUserIsAnonymousAndHasSelectedPipelines_WithWhitelist() { when(pipelineRepository.findPipelineSelectionsById("1")).thenReturn(new PipelineSelections(Arrays.asList("pipeline1", "pipeline2"), null, null, false)); goConfigService.updateUserPipelineSelections("1", null, new CaseInsensitiveString("pipelineNew")); verify(pipelineRepository).findPipelineSelectionsById("1"); verify(pipelineRepository, times(1)).saveSelectedPipelines(argThat(isAPipelineSelectionsInstanceWith(false, "pipeline1", "pipeline2", "pipelineNew"))); } @Test public void shouldNotUpdatePipelineSelectionsWhenTheUserIsLoggedIn_WithBlacklist() { mockConfigWithSecurity(); when(pipelineRepository.findPipelineSelectionsByUserId(1L)).thenReturn(new PipelineSelections(Arrays.asList("pipeline1", "pipeline2"), null, null, true)); goConfigService.updateUserPipelineSelections(null, 1L, new CaseInsensitiveString("pipelineNew")); verify(pipelineRepository).findPipelineSelectionsByUserId(1L); verify(pipelineRepository, times(0)).saveSelectedPipelines(argThat(Matchers.any(PipelineSelections.class))); } @Test public void shouldUpdatePipelineSelectionsWhenTheUserIsLoggedIn_WithWhitelist() { mockConfigWithSecurity(); when(pipelineRepository.findPipelineSelectionsByUserId(1L)).thenReturn(new PipelineSelections(Arrays.asList("pipeline1", "pipeline2"), null, null, false)); goConfigService.updateUserPipelineSelections(null, 1L, new CaseInsensitiveString("pipelineNew")); verify(pipelineRepository).findPipelineSelectionsByUserId(1L); verify(pipelineRepository, times(1)).saveSelectedPipelines(argThat(isAPipelineSelectionsInstanceWith(false, "pipeline1", "pipeline2", "pipelineNew"))); } @Test public void pipelineEditableViaUI_shouldReturnFalseWhenPipelineIsRemote() throws Exception { PipelineConfigs group = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); pipelineConfig.setOrigin(new RepoConfigOrigin()); group.add(pipelineConfig); expectLoad(new BasicCruiseConfig(group)); assertThat(goConfigService.isPipelineEditableViaUI("pipeline"), is(false)); } @Test public void pipelineEditableViaUI_shouldReturnTrueWhenPipelineIsLocal() throws Exception { PipelineConfigs group = new BasicPipelineConfigs(); PipelineConfig pipelineConfig = createPipelineConfig("pipeline", "name", "plan"); group.add(pipelineConfig); expectLoad(new BasicCruiseConfig(group)); assertThat(goConfigService.isPipelineEditableViaUI("pipeline"), is(true)); } @Test public void shouldTellIfAnUserIsAdministrator() throws Exception { final Username user = new Username(new CaseInsensitiveString("user")); expectLoad(mock(BasicCruiseConfig.class)); goConfigService.isAdministrator(user.getUsername()); verify(goConfigDao.load()).isAdministrator(user.getUsername().toString()); } @Test public void shouldBeAbleToListAllDependencyMaterialConfigs() { BasicCruiseConfig config = mock(BasicCruiseConfig.class); DependencyMaterialConfig dependencyMaterialConfig = MaterialConfigsMother.dependencyMaterialConfig(); SvnMaterialConfig svnMaterialConfig = MaterialConfigsMother.svnMaterialConfig(); PluggableSCMMaterialConfig pluggableSCMMaterialConfig = MaterialConfigsMother.pluggableSCMMaterialConfig(); HashSet<MaterialConfig> materialConfigs = new HashSet<>(Arrays.asList(dependencyMaterialConfig, svnMaterialConfig, pluggableSCMMaterialConfig)); when(goConfigService.getCurrentConfig()).thenReturn(config); when(config.getAllUniqueMaterialsBelongingToAutoPipelinesAndConfigRepos()).thenReturn(materialConfigs); Set<DependencyMaterialConfig> schedulableDependencyMaterials = goConfigService.getSchedulableDependencyMaterials(); assertThat(schedulableDependencyMaterials.size(), is(1)); assertTrue(schedulableDependencyMaterials.contains(dependencyMaterialConfig)); } @Test public void shouldBeAbleToListAllSCMMaterialConfigs() { BasicCruiseConfig config = mock(BasicCruiseConfig.class); DependencyMaterialConfig dependencyMaterialConfig = MaterialConfigsMother.dependencyMaterialConfig(); SvnMaterialConfig svnMaterialConfig = MaterialConfigsMother.svnMaterialConfig(); PluggableSCMMaterialConfig pluggableSCMMaterialConfig = MaterialConfigsMother.pluggableSCMMaterialConfig(); HashSet<MaterialConfig> materialConfigs = new HashSet<>(Arrays.asList(dependencyMaterialConfig, svnMaterialConfig, pluggableSCMMaterialConfig)); when(goConfigService.getCurrentConfig()).thenReturn(config); when(config.getAllUniqueMaterialsBelongingToAutoPipelinesAndConfigRepos()).thenReturn(materialConfigs); Set<MaterialConfig> schedulableDependencyMaterials = goConfigService.getSchedulableSCMMaterials(); assertThat(schedulableDependencyMaterials.size(), is(2)); assertTrue(schedulableDependencyMaterials.contains(svnMaterialConfig)); assertTrue(schedulableDependencyMaterials.contains(pluggableSCMMaterialConfig)); } private PipelineConfig createPipelineConfig(String pipelineName, String stageName, String... buildNames) { PipelineConfig pipeline = new PipelineConfig(new CaseInsensitiveString(pipelineName), new MaterialConfigs()); pipeline.add(new StageConfig(new CaseInsensitiveString(stageName), jobConfigs(buildNames))); return pipeline; } private JobConfigs jobConfigs(String... buildNames) { JobConfigs jobConfigs = new JobConfigs(); for (String buildName : buildNames) { jobConfigs.add(new JobConfig(buildName)); } return jobConfigs; } private GoConfigService goConfigServiceWithInvalidStatus() throws Exception { goConfigDao = mock(GoConfigDao.class, "badCruiseConfigManager"); when(goConfigDao.checkConfigFileValid()).thenReturn(GoConfigValidity.invalid(new JDOMParseException("JDom exception", new RuntimeException()))); return new GoConfigService(goConfigDao, pipelineRepository, new SystemTimeClock(), mock(GoConfigMigration.class), goCache, null, ConfigElementImplementationRegistryMother.withNoPlugins(), instanceFactory, null, null); } private CruiseConfig mockConfig() { CruiseConfig config = configWith( createGroup("group0", pipelineConfig("pipeline1"), pipelineConfig("pipeline2")), createGroup("group1", pipelineConfig("pipelineX")), createGroup("group2", pipelineConfig("pipeline3"))); when(goConfigDao.load()).thenReturn(config); return config; } private CruiseConfig mockConfigWithSecurity() { CruiseConfig config = mockConfig(); config.server().useSecurity(new SecurityConfig(null, new PasswordFileConfig("path"), true)); return config; } private GoConfigInvalidException getGoConfigInvalidException() { ConfigErrors configErrors = new ConfigErrors(); configErrors.add("command", "command cannot be empty"); AllConfigErrors list = new AllConfigErrors(); list.add(configErrors); return new GoConfigInvalidException(new BasicCruiseConfig(), list.asString()); } private Matcher<UpdateConfigCommand> cruiseConfigIsUpdatedWith(final String groupName, final String newPipelineName, final String labelTemplate) { return new Matcher<UpdateConfigCommand>() { @Override public boolean matches(Object item) { UpdateConfigCommand configCommand = (UpdateConfigCommand) item; CruiseConfig updatedConfig = null; try { updatedConfig = configCommand.update(new BasicCruiseConfig()); } catch (Exception e) { Assert.fail(String.format("Updating config through exception : %s", e)); } PipelineConfigs group = updatedConfig.findGroup(groupName); PipelineConfig pipeline = group.findBy(new CaseInsensitiveString(newPipelineName)); assertThat(pipeline.name(), is(new CaseInsensitiveString(newPipelineName))); assertThat(pipeline.getLabelTemplate(), is(labelTemplate)); assertThat(pipeline.materialConfigs().first(), is(IsInstanceOf.instanceOf(SvnMaterialConfig.class))); assertThat(pipeline.materialConfigs().first().getUriForDisplay(), is("file:///tmp/foo")); return true; } @Override public void describeMismatch(Object o, Description description) { description.appendText("There was a mismatch!"); } @Override public void _dont_implement_Matcher___instead_extend_BaseMatcher_() { } @Override public void describeTo(Description description) { } }; } private User getUser(final String userName, long id) { long userId = id; User user = new User(userName); user.setId(userId); when(userDao.findUser(userName)).thenReturn(user); return user; } private Matcher<PipelineSelections> hasValues(final List<String> isVisible, final List<String> isNotVisible, final Date today, final Long userId) { return new BaseMatcher<PipelineSelections>() { public boolean matches(Object o) { PipelineSelections pipelineSelections = (PipelineSelections) o; assertHasSelected(pipelineSelections, isVisible); assertHasSelected(pipelineSelections, isNotVisible, false); assertThat(pipelineSelections.lastUpdated(), is(today)); assertThat(pipelineSelections.userId(), is(userId)); return true; } public void describeTo(Description description) { } }; } private Matcher<PipelineSelections> isAPipelineSelectionsInstanceWith(final boolean isBlacklist, final String... pipelineSelectionsInInstance) { return new BaseMatcher<PipelineSelections>() { public boolean matches(Object o) { PipelineSelections pipelineSelections = (PipelineSelections) o; assertThat(pipelineSelections.isBlacklist(), is(isBlacklist)); List<String> expectedSelectionsAsList = Arrays.asList(pipelineSelectionsInInstance); assertEquals(pipelineSelections.getSelections(), ListUtil.join(expectedSelectionsAsList, ",")); return true; } public void describeTo(Description description) { } }; } private void assertHasSelected(PipelineSelections pipelineSelections, List<String> pipelines) { assertHasSelected(pipelineSelections, pipelines, true); } private void assertHasSelected(PipelineSelections pipelineSelections, List<String> pipelines, boolean has) { String message = "Expected: " + pipelines + " to include " + pipelineSelections + ": (" + has + ")."; for (String pipeline : pipelines) { assertThat(message + ". Failed to find: " + pipeline, pipelineSelections.includesPipeline(pipelineConfig(pipeline)), is(has)); } } private String groupXml(final String groupName) { return "<pipelines group=\"" + groupName + "\">\n" + " <pipeline name=\"new_name\" labeltemplate=\"${COUNT}-#{foo}\">\n" + " <params>\n" + " <param name=\"foo\">test</param>\n" + " </params>" + " <materials>\n" + " <svn url=\"file:///tmp/foo\" />\n" + " </materials>\n" + " <stage name=\"stage_name\">\n" + " <jobs>\n" + " <job name=\"job_name\" />\n" + " </jobs>\n" + " </stage>\n" + " </pipeline>\n" + "</pipelines>"; } private String groupXmlWithInvalidElement(final String groupName) { return "<pipelines group='" + groupName + "'>" + " <unknown/>" + "<pipeline name='pipeline'>\n" + " <materials>\n" + " <svn url ='svnurl' dest='a'/>\n" + " </materials>\n" + " <stage name='firstStage'>" + " <jobs>" + " <job name='jobName'/>" + " </jobs>" + " </stage>" + "</pipeline>" + "</pipelines>"; } private String groupXmlWithInvalidAttributeValue(final String groupName) { return "<pipelines group='" + groupName + "'>" + "<pipeline name='pipeline@$^'>\n" + " <materials>\n" + " <svn url ='svnurl' dest='a'/>\n" + " </materials>\n" + " <stage name='firstStage'>" + " <jobs>" + " <job name='jobName'/>" + " </jobs>" + " </stage>" + "</pipeline>" + "</pipelines>"; } }
apache-2.0
jnr/jnr-unixsocket
src/main/java/jnr/unixsocket/impl/Common.java
3617
/* * Copyright (C) 2016 Fritz Elfert * * This file is part of the JNR project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jnr.unixsocket.impl; import java.io.IOException; import java.nio.ByteBuffer; import jnr.constants.platform.Errno; import jnr.enxio.channels.Native; import jnr.enxio.channels.NativeException; /** * Helper class, providing common methods. */ final class Common { private int _fd = -1; Common(int fd) { _fd = fd; } void setFD(int fd) { _fd = fd; } int getFD() { return _fd; } int read(ByteBuffer dst) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(dst.remaining()); int n = Native.read(_fd, buffer); buffer.flip(); dst.put(buffer); switch (n) { case 0: return -1; case -1: Errno lastError = Native.getLastError(); switch (lastError) { case EAGAIN: case EWOULDBLOCK: return 0; default: throw new NativeException(Native.getLastErrorString(), lastError); } default: { return n; } } } long read(ByteBuffer[] dsts, int offset, int length) throws IOException { long total = 0; for (int i = 0; i < length; i++) { ByteBuffer dst = dsts[offset + i]; long read = read(dst); if (read == -1) { return read; } total += read; } return total; } int write(ByteBuffer src) throws IOException { int r = src.remaining(); ByteBuffer buffer = ByteBuffer.allocate(r); buffer.put(src); buffer.position(0); int n = Native.write(_fd, buffer); if (n >=0 ) { if (n < r) { src.position(src.position()-(r-n)); } } else { Errno lastError = Native.getLastError(); switch (lastError) { case EAGAIN: case EWOULDBLOCK: src.position(src.position()-r); return 0; default: throw new NativeException(Native.getLastErrorString(), lastError); } } return n; } long write(ByteBuffer[] srcs, int offset, int length) throws IOException { long result = 0; for (int index = offset; index < length; ++index) { ByteBuffer buffer = srcs[index]; int remaining = buffer.remaining(); int written = 0; while (true) { int w = write(buffer); written += w; if (w == 0 || written == remaining) { break; } } result += written; if (written < remaining) { break; } } return result; } }
apache-2.0
brson/cargo
src/cargo/sources/config.rs
6902
//! Implementation of configuration for various sources //! //! This module will parse the various `source.*` TOML configuration keys into a //! structure usable by Cargo itself. Currently this is primarily used to map //! sources to one another via the `replace-with` key in `.cargo/config`. use std::collections::HashMap; use std::path::{Path, PathBuf}; use url::Url; use core::{Source, SourceId}; use sources::ReplacedSource; use util::{CargoResult, Config, ChainError, human, ToUrl}; use util::config::ConfigValue; pub struct SourceConfigMap<'cfg> { cfgs: HashMap<String, SourceConfig>, id2name: HashMap<SourceId, String>, config: &'cfg Config, } /// Configuration for a particular source, found in TOML looking like: /// /// ```toml /// [source.crates-io] /// registry = 'https://github.com/rust-lang/crates.io-index' /// replace-with = 'foo' # optional /// ``` struct SourceConfig { // id this source corresponds to, inferred from the various defined keys in // the configuration id: SourceId, // Name of the source that this source should be replaced with. This field // is a tuple of (name, path) where path is where this configuration key was // defined (the literal `.cargo/config` file). replace_with: Option<(String, PathBuf)>, } impl<'cfg> SourceConfigMap<'cfg> { pub fn new(config: &'cfg Config) -> CargoResult<SourceConfigMap<'cfg>> { let mut base = try!(SourceConfigMap::empty(config)); if let Some(table) = try!(config.get_table("source")) { for (key, value) in table.val.iter() { try!(base.add_config(key, value)); } } Ok(base) } pub fn empty(config: &'cfg Config) -> CargoResult<SourceConfigMap<'cfg>> { let mut base = SourceConfigMap { cfgs: HashMap::new(), id2name: HashMap::new(), config: config, }; base.add("crates-io", SourceConfig { id: try!(SourceId::crates_io(config)), replace_with: None, }); Ok(base) } pub fn load(&self, id: &SourceId) -> CargoResult<Box<Source + 'cfg>> { debug!("loading: {}", id); let mut name = match self.id2name.get(id) { Some(name) => name, None => return Ok(id.load(self.config)), }; let mut path = Path::new("/"); let orig_name = name; let new_id; loop { let cfg = match self.cfgs.get(name) { Some(cfg) => cfg, None => bail!("could not find a configured source with the \ name `{}` when attempting to lookup `{}` \ (configuration in `{}`)", name, orig_name, path.display()), }; match cfg.replace_with { Some((ref s, ref p)) => { name = s; path = p; } None if *id == cfg.id => return Ok(id.load(self.config)), None => { new_id = cfg.id.with_precise(id.precise() .map(|s| s.to_string())); break } } debug!("following pointer to {}", name); if name == orig_name { bail!("detected a cycle of `replace-with` sources, the source \ `{}` is eventually replaced with itself \ (configuration in `{}`)", name, path.display()) } } let new_src = new_id.load(self.config); let old_src = id.load(self.config); if new_src.supports_checksums() != old_src.supports_checksums() { let (supports, no_support) = if new_src.supports_checksums() { (name, orig_name) } else { (orig_name, name) }; bail!("\ cannot replace `{orig}` with `{name}`, the source `{supports}` supports \ checksums, but `{no_support}` does not a lock file compatible with `{orig}` cannot be generated in this situation ", orig = orig_name, name = name, supports = supports, no_support = no_support); } Ok(Box::new(ReplacedSource::new(id, &new_id, new_src))) } fn add(&mut self, name: &str, cfg: SourceConfig) { self.id2name.insert(cfg.id.clone(), name.to_string()); self.cfgs.insert(name.to_string(), cfg); } fn add_config(&mut self, name: &str, cfg: &ConfigValue) -> CargoResult<()> { let (table, _path) = try!(cfg.table(&format!("source.{}", name))); let mut srcs = Vec::new(); if let Some(val) = table.get("registry") { let url = try!(url(val, &format!("source.{}.registry", name))); srcs.push(SourceId::for_registry(&url)); } if let Some(val) = table.get("local-registry") { let (s, path) = try!(val.string(&format!("source.{}.local-registry", name))); let mut path = path.to_path_buf(); path.pop(); path.pop(); path.push(s); srcs.push(try!(SourceId::for_local_registry(&path))); } if let Some(val) = table.get("directory") { let (s, path) = try!(val.string(&format!("source.{}.directory", name))); let mut path = path.to_path_buf(); path.pop(); path.pop(); path.push(s); srcs.push(try!(SourceId::for_directory(&path))); } let mut srcs = srcs.into_iter(); let src = try!(srcs.next().chain_error(|| { human(format!("no source URL specified for `source.{}`, need \ either `registry` or `local-registry` defined", name)) })); if srcs.next().is_some() { return Err(human(format!("more than one source URL specified for \ `source.{}`", name))) } let mut replace_with = None; if let Some(val) = table.get("replace-with") { let (s, path) = try!(val.string(&format!("source.{}.replace-with", name))); replace_with = Some((s.to_string(), path.to_path_buf())); } self.add(name, SourceConfig { id: src, replace_with: replace_with, }); return Ok(()); fn url(cfg: &ConfigValue, key: &str) -> CargoResult<Url> { let (url, path) = try!(cfg.string(key)); url.to_url().chain_error(|| { human(format!("configuration key `{}` specified an invalid \ URL (in {})", key, path.display())) }) } } }
apache-2.0
halentest/solr
lucene/facet/src/java/org/apache/lucene/facet/taxonomy/directory/TaxonomyIndexArrays.java
7928
package org.apache.lucene.facet.taxonomy.directory; import java.io.IOException; import org.apache.lucene.facet.taxonomy.ParallelTaxonomyArrays; import org.apache.lucene.facet.taxonomy.TaxonomyReader; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DocsAndPositionsEnum; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.util.ArrayUtil; /* * 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. */ /** * A {@link ParallelTaxonomyArrays} that are initialized from the taxonomy * index. * * @lucene.experimental */ class TaxonomyIndexArrays extends ParallelTaxonomyArrays { private final int[] parents; // the following two arrays are lazily intialized. note that we only keep a // single boolean member as volatile, instead of declaring the arrays // volatile. the code guarantees that only after the boolean is set to true, // the arrays are returned. private volatile boolean initializedChildren = false; private int[] children, siblings; /** Used by {@link #add(int, int)} after the array grew. */ private TaxonomyIndexArrays(int[] parents) { this.parents = parents; } public TaxonomyIndexArrays(IndexReader reader) throws IOException { parents = new int[reader.maxDoc()]; if (parents.length > 0) { initParents(reader, 0); // Starting Lucene 2.9, following the change LUCENE-1542, we can // no longer reliably read the parent "-1" (see comment in // LuceneTaxonomyWriter.SinglePositionTokenStream). We have no way // to fix this in indexing without breaking backward-compatibility // with existing indexes, so what we'll do instead is just // hard-code the parent of ordinal 0 to be -1, and assume (as is // indeed the case) that no other parent can be -1. parents[0] = TaxonomyReader.INVALID_ORDINAL; } } public TaxonomyIndexArrays(IndexReader reader, TaxonomyIndexArrays copyFrom) throws IOException { assert copyFrom != null; // note that copyParents.length may be equal to reader.maxDoc(). this is not a bug // it may be caused if e.g. the taxonomy segments were merged, and so an updated // NRT reader was obtained, even though nothing was changed. this is not very likely // to happen. int[] copyParents = copyFrom.parents(); this.parents = new int[reader.maxDoc()]; System.arraycopy(copyParents, 0, parents, 0, copyParents.length); initParents(reader, copyParents.length); if (copyFrom.initializedChildren) { initChildrenSiblings(copyFrom); } } private final synchronized void initChildrenSiblings(TaxonomyIndexArrays copyFrom) { if (!initializedChildren) { // must do this check ! children = new int[parents.length]; siblings = new int[parents.length]; if (copyFrom != null) { // called from the ctor, after we know copyFrom has initialized children/siblings System.arraycopy(copyFrom.children(), 0, children, 0, copyFrom.children().length); System.arraycopy(copyFrom.siblings(), 0, siblings, 0, copyFrom.siblings().length); } computeChildrenSiblings(parents, 0); initializedChildren = true; } } private void computeChildrenSiblings(int[] parents, int first) { // reset the youngest child of all ordinals. while this should be done only // for the leaves, we don't know up front which are the leaves, so we reset // all of them. for (int i = first; i < parents.length; i++) { children[i] = TaxonomyReader.INVALID_ORDINAL; } // the root category has no parent, and therefore no siblings if (first == 0) { first = 1; siblings[0] = TaxonomyReader.INVALID_ORDINAL; } for (int i = first; i < parents.length; i++) { // note that parents[i] is always < i, so the right-hand-side of // the following line is already set when we get here siblings[i] = children[parents[i]]; children[parents[i]] = i; } } // Read the parents of the new categories private void initParents(IndexReader reader, int first) throws IOException { if (reader.maxDoc() == first) { return; } // it's ok to use MultiFields because we only iterate on one posting list. // breaking it to loop over the leaves() only complicates code for no // apparent gain. DocsAndPositionsEnum positions = MultiFields.getTermPositionsEnum(reader, null, Consts.FIELD_PAYLOADS, Consts.PAYLOAD_PARENT_BYTES_REF, DocsAndPositionsEnum.FLAG_PAYLOADS); // shouldn't really happen, if it does, something's wrong if (positions == null || positions.advance(first) == DocIdSetIterator.NO_MORE_DOCS) { throw new CorruptIndexException("Missing parent data for category " + first); } int num = reader.maxDoc(); for (int i = first; i < num; i++) { if (positions.docID() == i) { if (positions.freq() == 0) { // shouldn't happen throw new CorruptIndexException("Missing parent data for category " + i); } parents[i] = positions.nextPosition(); if (positions.nextDoc() == DocIdSetIterator.NO_MORE_DOCS) { if (i + 1 < num) { throw new CorruptIndexException("Missing parent data for category "+ (i + 1)); } break; } } else { // this shouldn't happen throw new CorruptIndexException("Missing parent data for category " + i); } } } /** * Adds the given ordinal/parent info and returns either a new instance if the * underlying array had to grow, or this instance otherwise. * <p> * <b>NOTE:</b> you should call this method from a thread-safe code. */ TaxonomyIndexArrays add(int ordinal, int parentOrdinal) { if (ordinal >= parents.length) { int[] newarray = ArrayUtil.grow(parents, ordinal + 1); newarray[ordinal] = parentOrdinal; return new TaxonomyIndexArrays(newarray); } parents[ordinal] = parentOrdinal; return this; } /** * Returns the parents array, where {@code parents[i]} denotes the parent of * category ordinal {@code i}. */ @Override public int[] parents() { return parents; } /** * Returns the children array, where {@code children[i]} denotes the youngest * child of category ordinal {@code i}. The youngest child is defined as the * category that was added last to the taxonomy as an immediate child of * {@code i}. */ @Override public int[] children() { if (!initializedChildren) { initChildrenSiblings(null); } // the array is guaranteed to be populated return children; } /** * Returns the siblings array, where {@code siblings[i]} denotes the sibling * of category ordinal {@code i}. The sibling is defined as the previous * youngest child of {@code parents[i]}. */ @Override public int[] siblings() { if (!initializedChildren) { initChildrenSiblings(null); } // the array is guaranteed to be populated return siblings; } }
apache-2.0
MarkAufdencamp/stomp-client-daemon
google_service_processor/google_compute_engine_controller.py
2797
from stomp_message_controller import StompMessageController from stomp_message import StompMessage # https://developers.google.com/api-client-library/python/ # google-api-python-client class GoogleComputeEngineController(StompMessageController): stomp_tasks = ["CreateComputeEngineInstance", "DeleteComputeEngineInstance", "StartComputeEngineInstance", "StopComputeEngineInstance"] def run(self): print("GoogleComputeEngineController") def create_compute_engine_instance(self, stomp_message): print("CreateComputeEngineInstance - google_compute_engine_controller.create_compute_engine_instance()") stomp_message.print_message() successfulProvisioning = True acknowledgementMessageDict = stomp_message.parsed_body if successfulProvisioning: self.acknowledge_success(acknowledgementMessageDict) else: self.acknowledge_failure(acknowledgementMessageDict) def delete_compute_engine_instance(self, stomp_message): print("DeleteComputeEngineInstance - google_compute_engine_controller.delete_compute_engine_instance()") stomp_message.print_message() successfulProvisioning = True acknowledgementMessageDict = stomp_message.parsed_body if successfulProvisioning: self.acknowledge_success(acknowledgementMessageDict) else: self.acknowledge_failure(acknowledgementMessageDict) def start_compute_engine_instance(self, stomp_message): print("StartComputeEngineInstance - google_compute_engine_controller.start_compute_engine_instance()") stomp_message.print_message() successfulProvisioning = True acknowledgementMessageDict = stomp_message.parsed_body if successfulProvisioning: self.acknowledge_success(acknowledgementMessageDict) else: self.acknowledge_failure(acknowledgementMessageDict) def stop_compute_engine_instance(self, stomp_message): print("StopComputeEngineInstance - google_compute_engine_controller.stop_compute_engine_instance()") stomp_message.print_message() successfulProvisioning = True acknowledgementMessageDict = stomp_message.parsed_body if successfulProvisioning: self.acknowledge_success(acknowledgementMessageDict) else: self.acknowledge_failure(acknowledgementMessageDict) def acknowledge_success(self, acknowledgementMessageDict): print("== Acknowledge Message Success ==") acknowledgementQueue = acknowledgementMessageDict["service"] acknowledgementMessageDict["taskResult"] = "Success" self.send_message(acknowledgementQueue, acknowledgementMessageDict) def acknowledge_failure(self, acknowledgementMessageDict): print("== Acknowledge Message Failure ==") acknowledgementQueue = acknowledgementMessageDict["service"] acknowledgementMessageDict["taskResult"] = "Failure" self.send_message(acknowledgementQueue, acknowledgementMessageDict)
apache-2.0
hwangfantasy/spring-sample
spring-boot-sample/src/main/java/com/hwangfantasy/config/mybatis/MyBatisMapperScannerConfig.java
1058
package com.hwangfantasy.config.mybatis; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import tk.mybatis.spring.mapper.MapperScannerConfigurer; import java.util.Properties; /** * @author hwangfantasy * @创建时间: 2017/3/7 17:22 <br/> * @方法描述: MyBatisMapperScannerConfig. <br/> */ @Configuration @AutoConfigureAfter(MyBatisConfig.class) public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage("com.hwangfantasy.dao"); Properties properties = new Properties(); properties.setProperty("dialect", "mysql"); mapperScannerConfigurer.setProperties(properties); return mapperScannerConfigurer; } }
apache-2.0
darkpsy3934/community-plugins
ofsocial/src/wp-content/plugins/wp-helpers/parts/settings/discussion-trackbacks.php
307
<?php /* Title: Trackbacks / Pingbacks Setting: piklist_wp_helpers Tab: Discussion Order: 410 Flow: WP Helpers Settings Flow */ piklist('field', array( 'type' => 'checkbox' ,'field' => 'disable_self_ping' ,'label' => 'Self Pings' ,'choices' => array( 'true' => 'Disable' ) ));
apache-2.0
supercocoa/HelloAndroid
app/src/main/java/com/helloandroid/image/VectorCompatActivity.java
1391
package com.helloandroid.image; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import android.widget.ImageView; import com.helloandroid.app.R; /** * Created by scott on 15/11/14. */ public class VectorCompatActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); imageView = new ImageView(this); imageView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); setContentView(imageView); Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { makeSvg(); } }, 50); } private void makeSvg() { imageView.setImageDrawable(getResources().getDrawable(R.drawable.homer_simpson)); // imageView.setBackground(ResourcesCompat.getDrawable(this, R.drawable.homer_simpson)); //Drawable vectorDrawable = ResourcesCompat.getDrawable(this, R.drawable.homer_simpson); //vectorDrawable.setAlpha(50); //imageView.setImageDrawable(vectorDrawable); } }
apache-2.0
sponiro/deep-uncompress
src/test/java/de/fanero/uncompress/stream/OneEntryArchiveInputStreamTest.java
2744
/* * Copyright (C) 2014 Robert Kühne * * 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 de.fanero.uncompress.stream; import de.fanero.uncompress.stream.EmtpyArchiveEntry; import de.fanero.uncompress.stream.OneEntryArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.junit.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author Robert Kühne */ public class OneEntryArchiveInputStreamTest { @Test public void testGetNextEntryFirstCall() throws Exception { ArchiveEntry archiveEntry = EmtpyArchiveEntry.getInstance(); OneEntryArchiveInputStream stream = new OneEntryArchiveInputStream(new ByteArrayInputStream(new byte[3]), archiveEntry); assertThat(stream.getNextEntry(), is(archiveEntry)); } @Test public void testGetNextEntrySecondCall() throws Exception { ArchiveEntry archiveEntry = EmtpyArchiveEntry.getInstance(); OneEntryArchiveInputStream stream = new OneEntryArchiveInputStream(new ByteArrayInputStream(new byte[3]), archiveEntry); assertThat(stream.getNextEntry(), is(archiveEntry)); assertThat(stream.getNextEntry(), is(nullValue())); } @Test public void testCloseOfInputStream() throws Exception { ArchiveEntry archiveEntry = EmtpyArchiveEntry.getInstance(); InputStream inputStream = Mockito.mock(InputStream.class); OneEntryArchiveInputStream stream = new OneEntryArchiveInputStream(inputStream, archiveEntry); stream.getNextEntry(); verify(inputStream, times(1)).close(); } @Test public void testReadDelegation() throws Exception { ArchiveEntry archiveEntry = EmtpyArchiveEntry.getInstance(); InputStream inputStream = Mockito.mock(InputStream.class); OneEntryArchiveInputStream stream = new OneEntryArchiveInputStream(inputStream, archiveEntry); stream.read(); verify(inputStream, times(1)).read(); } }
apache-2.0
OpenNTF/org.openntf.domino
domino/core/src/main/java/org/openntf/domino/design/SharedActions.java
771
/** * Copyright © 2013-2021 The OpenNTF Domino API Team * * 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.openntf.domino.design; /** * @author Roland Praml * */ public interface SharedActions extends DesignBase { }
apache-2.0
FITeagle/adapters
motor/src/main/java/org/fiteagle/adapters/motor/dm/MotorApp.java
447
package org.fiteagle.adapters.motor.dm; import java.util.HashSet; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * Created by dne on 24.06.15. */ @ApplicationPath("/motor") public class MotorApp extends Application { @Override public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(MotorAdapterREST.class); return classes; } }
apache-2.0
phraktle/lmdbjava
src/main/java/org/lmdbjava/Txn.java
9088
/*- * #%L * LmdbJava * %% * Copyright (C) 2016 - 2017 The LmdbJava Open Source Project * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.lmdbjava; import static jnr.ffi.Memory.allocateDirect; import static jnr.ffi.NativeType.ADDRESS; import jnr.ffi.Pointer; import static org.lmdbjava.Library.LIB; import static org.lmdbjava.Library.RUNTIME; import static org.lmdbjava.MaskedFlag.isSet; import static org.lmdbjava.MaskedFlag.mask; import static org.lmdbjava.ResultCodeMapper.checkRc; import static org.lmdbjava.Txn.State.DONE; import static org.lmdbjava.Txn.State.READY; import static org.lmdbjava.Txn.State.RELEASED; import static org.lmdbjava.Txn.State.RESET; import static org.lmdbjava.TxnFlags.MDB_RDONLY_TXN; /** * LMDB transaction. * * @param <T> buffer type */ public final class Txn<T> implements AutoCloseable { private final KeyVal<T> keyVal; private final Txn<T> parent; private final BufferProxy<T> proxy; private final Pointer ptr; private final boolean readOnly; private State state; Txn(final Env<T> env, final Txn<T> parent, final BufferProxy<T> proxy, final TxnFlags... flags) { this.proxy = proxy; this.keyVal = proxy.keyVal(); final int flagsMask = mask(flags); this.readOnly = isSet(flagsMask, MDB_RDONLY_TXN); if (env.isReadOnly() && !this.readOnly) { throw new EnvIsReadOnly(); } this.parent = parent; if (parent != null && parent.isReadOnly() != this.readOnly) { throw new IncompatibleParent(); } final Pointer txnPtr = allocateDirect(RUNTIME, ADDRESS); final Pointer txnParentPtr = parent == null ? null : parent.ptr; checkRc(LIB.mdb_txn_begin(env.pointer(), txnParentPtr, flagsMask, txnPtr)); ptr = txnPtr.getPointer(0); state = READY; } /** * Aborts this transaction. */ public void abort() { checkReady(); state = DONE; LIB.mdb_txn_abort(ptr); } /** * Closes this transaction by aborting if not already committed. * * <p> * Closing the transaction will invoke * {@link BufferProxy#deallocate(java.lang.Object)} for each read-only buffer * (ie the key and value). */ @Override public void close() { if (state == RELEASED) { return; } if (state == READY) { LIB.mdb_txn_abort(ptr); } keyVal.close(); state = RELEASED; } /** * Commits this transaction. */ public void commit() { checkReady(); state = DONE; checkRc(LIB.mdb_txn_commit(ptr)); } /** * Return the transaction's ID. * * @return A transaction ID, valid if input is an active transaction */ public long getId() { return LIB.mdb_txn_id(ptr); } /** * Obtains this transaction's parent. * * @return the parent transaction (may be null) */ public Txn<T> getParent() { return parent; } /** * Whether this transaction is read-only. * * @return if read-only */ public boolean isReadOnly() { return readOnly; } /** * Fetch the buffer which holds a read-only view of the LMDI allocated memory. * Any use of this buffer must comply with the standard LMDB C "mdb_get" * contract (ie do not modify, do not attempt to release the memory, do not * use once the transaction or cursor closes, do not use after a write etc). * * @return the key buffer (never null) */ public T key() { return keyVal.key(); } /** * Renews a read-only transaction previously released by {@link #reset()}. */ public void renew() { if (state != RESET) { throw new NotResetException(); } state = DONE; checkRc(LIB.mdb_txn_renew(ptr)); state = READY; } /** * Aborts this read-only transaction and resets the transaction handle so it * can be reused upon calling {@link #renew()}. */ public void reset() { checkReadOnly(); if (state != READY && state != DONE) { throw new ResetException(); } state = RESET; LIB.mdb_txn_reset(ptr); } /** * Fetch the buffer which holds a read-only view of the LMDI allocated memory. * Any use of this buffer must comply with the standard LMDB C "mdb_get" * contract (ie do not modify, do not attempt to release the memory, do not * use once the transaction or cursor closes, do not use after a write etc). * * @return the value buffer (never null) */ public T val() { return keyVal.val(); } void checkReadOnly() throws ReadOnlyRequiredException { if (!readOnly) { throw new ReadOnlyRequiredException(); } } void checkReady() throws NotReadyException { if (state != READY) { throw new NotReadyException(); } } void checkWritesAllowed() throws ReadWriteRequiredException { if (readOnly) { throw new ReadWriteRequiredException(); } } /** * Return the state of the transaction. * * @return the state */ State getState() { return state; } KeyVal<T> kv() { return keyVal; } KeyVal<T> newKeyVal() { return proxy.keyVal(); } Pointer pointer() { return ptr; } /** * Transaction must abort, has a child, or is invalid. */ public static final class BadException extends LmdbNativeException { static final int MDB_BAD_TXN = -30_782; private static final long serialVersionUID = 1L; BadException() { super(MDB_BAD_TXN, "Transaction must abort, has a child, or is invalid"); } } /** * Invalid reuse of reader locktable slot. */ public static final class BadReaderLockException extends LmdbNativeException { static final int MDB_BAD_RSLOT = -30_783; private static final long serialVersionUID = 1L; BadReaderLockException() { super(MDB_BAD_RSLOT, "Invalid reuse of reader locktable slot"); } } /** * The proposed R-W transaction is incompatible with a R-O Env. */ public static class EnvIsReadOnly extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public EnvIsReadOnly() { super("Read-write Txn incompatible with read-only Env"); } } /** * The proposed transaction is incompatible with its parent transaction. */ public static class IncompatibleParent extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public IncompatibleParent() { super("Transaction incompatible with its parent transaction"); } } /** * Transaction is not in a READY state. */ public static final class NotReadyException extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public NotReadyException() { super("Transaction is not in ready state"); } } /** * The current transaction has not been reset. */ public static class NotResetException extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public NotResetException() { super("Transaction has not been reset"); } } /** * The current transaction is not a read-only transaction. */ public static class ReadOnlyRequiredException extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public ReadOnlyRequiredException() { super("Not a read-only transaction"); } } /** * The current transaction is not a read-write transaction. */ public static class ReadWriteRequiredException extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public ReadWriteRequiredException() { super("Not a read-write transaction"); } } /** * The current transaction has already been reset. */ public static class ResetException extends LmdbException { private static final long serialVersionUID = 1L; /** * Creates a new instance. */ public ResetException() { super("Transaction has already been reset"); } } /** * Transaction has too many dirty pages. */ public static final class TxFullException extends LmdbNativeException { static final int MDB_TXN_FULL = -30_788; private static final long serialVersionUID = 1L; TxFullException() { super(MDB_TXN_FULL, "Transaction has too many dirty pages"); } } /** * Transaction states. */ enum State { READY, DONE, RESET, RELEASED } }
apache-2.0
imay/palo
fe/src/main/java/org/apache/doris/rewrite/ExprRewriter.java
3842
// 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.rewrite; import java.util.List; import org.apache.doris.analysis.Analyzer; import org.apache.doris.analysis.Expr; import org.apache.doris.common.AnalysisException; import com.google.common.collect.Lists; /** * Helper class that drives the transformation of Exprs according to a given list of * ExprRewriteRules. The rules are applied as follows: * - a single rule is applied repeatedly to the Expr and all its children in a bottom-up * fashion until there are no more changes * - the rule list is applied repeatedly until no rule has made any changes * - the rules are applied in the order they appear in the rule list * Keeps track of how many transformations were applied. */ public class ExprRewriter { private int numChanges_ = 0; private final List<ExprRewriteRule> rules_; public ExprRewriter(List<ExprRewriteRule> rules) { rules_ = rules; } public ExprRewriter(ExprRewriteRule rule) { rules_ = Lists.newArrayList(rule); } public Expr rewrite(Expr expr, Analyzer analyzer) throws AnalysisException { // Keep applying the rule list until no rule has made any changes. int oldNumChanges; Expr rewrittenExpr = expr; do { oldNumChanges = numChanges_; for (ExprRewriteRule rule: rules_) { rewrittenExpr = applyRuleRepeatedly(rewrittenExpr, rule, analyzer); } } while (oldNumChanges != numChanges_); return rewrittenExpr; } /** * Applies 'rule' on the Expr tree rooted at 'expr' until there are no more changes. * Returns the transformed Expr or 'expr' if there were no changes. */ private Expr applyRuleRepeatedly(Expr expr, ExprRewriteRule rule, Analyzer analyzer) throws AnalysisException { int oldNumChanges; Expr rewrittenExpr = expr; do { oldNumChanges = numChanges_; rewrittenExpr = applyRuleBottomUp(rewrittenExpr, rule, analyzer); } while (oldNumChanges != numChanges_); return rewrittenExpr; } /** * Applies 'rule' on 'expr' and all its children in a bottom-up fashion. * Returns the transformed Expr or 'expr' if there were no changes. */ private Expr applyRuleBottomUp(Expr expr, ExprRewriteRule rule, Analyzer analyzer) throws AnalysisException { for (int i = 0; i < expr.getChildren().size(); ++i) { expr.setChild(i, applyRuleBottomUp(expr.getChild(i), rule, analyzer)); } Expr rewrittenExpr = rule.apply(expr, analyzer); if (rewrittenExpr != expr) ++numChanges_; return rewrittenExpr; } public void rewriteList(List<Expr> exprs, Analyzer analyzer) throws AnalysisException { for (int i = 0; i < exprs.size(); ++i) exprs.set(i, rewrite(exprs.get(i), analyzer)); } public void reset() { numChanges_ = 0; } public boolean changed() { return numChanges_ > 0; } public int getNumChanges() { return numChanges_; } }
apache-2.0
openpne/OpenPNE3
lib/vendor/symfony/lib/response/sfWebResponse.class.php
23766
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfWebResponse class. * * This class manages web reponses. It supports cookies and headers management. * * @package symfony * @subpackage response * @author Fabien Potencier <[email protected]> * @version SVN: $Id$ */ class sfWebResponse extends sfResponse { const FIRST = 'first', MIDDLE = '', LAST = 'last', ALL = 'ALL', RAW = 'RAW'; protected $cookies = array(), $statusCode = 200, $statusText = 'OK', $headerOnly = false, $headers = array(), $metas = array(), $httpMetas = array(), $positions = array('first', '', 'last'), $stylesheets = array(), $javascripts = array(), $slots = array(); static protected $statusTexts = array( '100' => 'Continue', '101' => 'Switching Protocols', '200' => 'OK', '201' => 'Created', '202' => 'Accepted', '203' => 'Non-Authoritative Information', '204' => 'No Content', '205' => 'Reset Content', '206' => 'Partial Content', '300' => 'Multiple Choices', '301' => 'Moved Permanently', '302' => 'Found', '303' => 'See Other', '304' => 'Not Modified', '305' => 'Use Proxy', '306' => '(Unused)', '307' => 'Temporary Redirect', '400' => 'Bad Request', '401' => 'Unauthorized', '402' => 'Payment Required', '403' => 'Forbidden', '404' => 'Not Found', '405' => 'Method Not Allowed', '406' => 'Not Acceptable', '407' => 'Proxy Authentication Required', '408' => 'Request Timeout', '409' => 'Conflict', '410' => 'Gone', '411' => 'Length Required', '412' => 'Precondition Failed', '413' => 'Request Entity Too Large', '414' => 'Request-URI Too Long', '415' => 'Unsupported Media Type', '416' => 'Requested Range Not Satisfiable', '417' => 'Expectation Failed', '500' => 'Internal Server Error', '501' => 'Not Implemented', '502' => 'Bad Gateway', '503' => 'Service Unavailable', '504' => 'Gateway Timeout', '505' => 'HTTP Version Not Supported', ); /** * Initializes this sfWebResponse. * * Available options: * * * charset: The charset to use (utf-8 by default) * * content_type: The content type (text/html by default) * * send_http_headers: Whether to send HTTP headers or not (true by default) * * http_protocol: The HTTP protocol to use for the response (HTTP/1.0 by default) * * @param sfEventDispatcher $dispatcher An sfEventDispatcher instance * @param array $options An array of options * * @return bool true, if initialization completes successfully, otherwise false * * @throws <b>sfInitializationException</b> If an error occurs while initializing this sfResponse * * @see sfResponse */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { parent::initialize($dispatcher, $options); $this->javascripts = array_combine($this->positions, array_fill(0, count($this->positions), array())); $this->stylesheets = array_combine($this->positions, array_fill(0, count($this->positions), array())); if (!isset($this->options['charset'])) { $this->options['charset'] = 'utf-8'; } if (!isset($this->options['send_http_headers'])) { $this->options['send_http_headers'] = true; } if (!isset($this->options['http_protocol'])) { $this->options['http_protocol'] = 'HTTP/1.0'; } $this->options['content_type'] = $this->fixContentType(isset($this->options['content_type']) ? $this->options['content_type'] : 'text/html'); } /** * Sets if the response consist of just HTTP headers. * * @param bool $value */ public function setHeaderOnly($value = true) { $this->headerOnly = (boolean) $value; } /** * Returns if the response must only consist of HTTP headers. * * @return bool returns true if, false otherwise */ public function isHeaderOnly() { return $this->headerOnly; } /** * Sets a cookie. * * @param string $name HTTP header name * @param string $value Value for the cookie * @param string $expire Cookie expiration period * @param string $path Path * @param string $domain Domain name * @param bool $secure If secure * @param bool $httpOnly If uses only HTTP * * @throws <b>sfException</b> If fails to set the cookie */ public function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false) { if ($expire !== null) { if (is_numeric($expire)) { $expire = (int) $expire; } else { $expire = strtotime($expire); if ($expire === false || $expire == -1) { throw new sfException('Your expire parameter is not valid.'); } } } $this->cookies[$name] = array( 'name' => $name, 'value' => $value, 'expire' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => $secure ? true : false, 'httpOnly' => $httpOnly, ); } /** * Sets response status code. * * @param string $code HTTP status code * @param string $name HTTP status text * */ public function setStatusCode($code, $name = null) { $this->statusCode = $code; $this->statusText = null !== $name ? $name : self::$statusTexts[$code]; } /** * Retrieves status text for the current web response. * * @return string Status text */ public function getStatusText() { return $this->statusText; } /** * Retrieves status code for the current web response. * * @return integer Status code */ public function getStatusCode() { return $this->statusCode; } /** * Sets a HTTP header. * * @param string $name HTTP header name * @param string $value Value (if null, remove the HTTP header) * @param bool $replace Replace for the value * */ public function setHttpHeader($name, $value, $replace = true) { $name = $this->normalizeHeaderName($name); if (null === $value) { unset($this->headers[$name]); return; } if ('Content-Type' == $name) { if ($replace || !$this->getHttpHeader('Content-Type', null)) { $this->setContentType($value); } return; } if (!$replace) { $current = isset($this->headers[$name]) ? $this->headers[$name] : ''; $value = ($current ? $current.', ' : '').$value; } $this->headers[$name] = $value; } /** * Gets HTTP header current value. * * @param string $name HTTP header name * @param string $default Default value returned if named HTTP header is not found * * @return string */ public function getHttpHeader($name, $default = null) { $name = $this->normalizeHeaderName($name); return isset($this->headers[$name]) ? $this->headers[$name] : $default; } /** * Checks if response has given HTTP header. * * @param string $name HTTP header name * * @return bool */ public function hasHttpHeader($name) { return array_key_exists($this->normalizeHeaderName($name), $this->headers); } /** * Sets response content type. * * @param string $value Content type * */ public function setContentType($value) { $this->headers['Content-Type'] = $this->fixContentType($value); } /** * Gets the current charset as defined by the content type. * * @return string The current charset */ public function getCharset() { return $this->options['charset']; } /** * Gets response content type. * * @return array */ public function getContentType() { return $this->getHttpHeader('Content-Type', $this->options['content_type']); } /** * Sends HTTP headers and cookies. Only the first invocation of this method will send the headers. * Subsequent invocations will silently do nothing. This allows certain actions to send headers early, * while still using the standard controller. */ public function sendHttpHeaders() { if (!$this->options['send_http_headers']) { return; } // status $status = $this->options['http_protocol'].' '.$this->statusCode.' '.$this->statusText; header($status); if (substr(php_sapi_name(), 0, 3) == 'cgi') { // fastcgi servers cannot send this status information because it was sent by them already due to the HTT/1.0 line // so we can safely unset them. see ticket #3191 unset($this->headers['Status']); } if ($this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Send status "%s"', $status)))); } // headers if (!$this->getHttpHeader('Content-Type')) { $this->setContentType($this->options['content_type']); } foreach ($this->headers as $name => $value) { header($name.': '.$value); if ($value != '' && $this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Send header "%s: %s"', $name, $value)))); } } // cookies foreach ($this->cookies as $cookie) { setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']); if ($this->options['logging']) { $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Send cookie "%s": "%s"', $cookie['name'], $cookie['value'])))); } } // prevent resending the headers $this->options['send_http_headers'] = false; } /** * Send content for the current web response. * */ public function sendContent() { if (!$this->headerOnly) { parent::sendContent(); } } /** * Sends the HTTP headers and the content. */ public function send() { $this->sendHttpHeaders(); $this->sendContent(); if (function_exists('fastcgi_finish_request')) { $this->dispatcher->notify(new sfEvent($this, 'response.fastcgi_finish_request')); fastcgi_finish_request(); } } /** * Retrieves a normalized Header. * * @param string $name Header name * * @return string Normalized header */ protected function normalizeHeaderName($name) { return strtr(ucwords(strtr(strtolower($name), array('_' => ' ', '-' => ' '))), array(' ' => '-')); } /** * Retrieves a formated date. * * @param string $timestamp Timestamp * @param string $type Format type * * @return string Formatted date */ static public function getDate($timestamp, $type = 'rfc1123') { $type = strtolower($type); if ($type == 'rfc1123') { return substr(gmdate('r', $timestamp), 0, -5).'GMT'; } else if ($type == 'rfc1036') { return gmdate('l, d-M-y H:i:s ', $timestamp).'GMT'; } else if ($type == 'asctime') { return gmdate('D M j H:i:s', $timestamp); } else { throw new InvalidArgumentException('The second getDate() method parameter must be one of: rfc1123, rfc1036 or asctime.'); } } /** * Adds vary to a http header. * * @param string $header HTTP header */ public function addVaryHttpHeader($header) { $vary = $this->getHttpHeader('Vary'); $currentHeaders = array(); if ($vary) { $currentHeaders = preg_split('/\s*,\s*/', $vary); } $header = $this->normalizeHeaderName($header); if (!in_array($header, $currentHeaders)) { $currentHeaders[] = $header; $this->setHttpHeader('Vary', implode(', ', $currentHeaders)); } } /** * Adds an control cache http header. * * @param string $name HTTP header * @param string $value Value for the http header */ public function addCacheControlHttpHeader($name, $value = null) { $cacheControl = $this->getHttpHeader('Cache-Control'); $currentHeaders = array(); if ($cacheControl) { foreach (preg_split('/\s*,\s*/', $cacheControl) as $tmp) { $tmp = explode('=', $tmp); $currentHeaders[$tmp[0]] = isset($tmp[1]) ? $tmp[1] : null; } } $currentHeaders[str_replace('_', '-', strtolower($name))] = $value; $headers = array(); foreach ($currentHeaders as $key => $value) { $headers[] = $key.(null !== $value ? '='.$value : ''); } $this->setHttpHeader('Cache-Control', implode(', ', $headers)); } /** * Retrieves meta headers for the current web response. * * @return string Meta headers */ public function getHttpMetas() { return $this->httpMetas; } /** * Adds a HTTP meta header. * * @param string $key Key to replace * @param string $value HTTP meta header value (if null, remove the HTTP meta) * @param bool $replace Replace or not */ public function addHttpMeta($key, $value, $replace = true) { $key = $this->normalizeHeaderName($key); // set HTTP header $this->setHttpHeader($key, $value, $replace); if (null === $value) { unset($this->httpMetas[$key]); return; } if ('Content-Type' == $key) { $value = $this->getContentType(); } elseif (!$replace) { $current = isset($this->httpMetas[$key]) ? $this->httpMetas[$key] : ''; $value = ($current ? $current.', ' : '').$value; } $this->httpMetas[$key] = $value; } /** * Retrieves all meta headers. * * @return array List of meta headers */ public function getMetas() { return $this->metas; } /** * Adds a meta header. * * @param string $key Name of the header * @param string $value Meta header value (if null, remove the meta) * @param bool $replace true if it's replaceable * @param bool $escape true for escaping the header */ public function addMeta($key, $value, $replace = true, $escape = true) { $key = strtolower($key); if (null === $value) { unset($this->metas[$key]); return; } // FIXME: If you use the i18n layer and escape the data here, it won't work // see include_metas() in AssetHelper if ($escape) { $value = htmlspecialchars($value, ENT_QUOTES, $this->options['charset']); } $current = isset($this->metas[$key]) ? $this->metas[$key] : null; if ($replace || !$current) { $this->metas[$key] = $value; } } /** * Retrieves title for the current web response. * * @return string Title */ public function getTitle() { return isset($this->metas['title']) ? $this->metas['title'] : ''; } /** * Preprend title * * @param string $title Title name * @param string $separator Separator string (default: " - ") * @param boolean $escape true, for escaping the title */ public function prependTitle($title, $separator = ' - ', $escape = true) { if (!isset($this->metas['title'])) { $this->setTitle($title); return; } // FIXME: If you use the i18n layer and escape the data here, it won't work // see include_metas() in AssetHelper if ($escape) { $title = htmlspecialchars($title, ENT_QUOTES, $this->options['charset']); } $this->metas['title'] = $title.$separator.$this->metas['title']; } /** * Sets title for the current web response. * * @param string $title Title name * @param bool $escape true, for escaping the title */ public function setTitle($title, $escape = true) { $this->addMeta('title', $title, true, $escape); } /** * Returns the available position names for stylesheets and javascripts in order. * * @return array An array of position names */ public function getPositions() { return $this->positions; } /** * Retrieves stylesheets for the current web response. * * By default, the position is sfWebResponse::ALL, * and the method returns all stylesheets ordered by position. * * @param string $position The position * * @return array An associative array of stylesheet files as keys and options as values */ public function getStylesheets($position = self::ALL) { if (self::ALL === $position) { $stylesheets = array(); foreach ($this->getPositions() as $position) { foreach ($this->stylesheets[$position] as $file => $options) { $stylesheets[$file] = $options; } } return $stylesheets; } else if (self::RAW === $position) { return $this->stylesheets; } $this->validatePosition($position); return $this->stylesheets[$position]; } /** * Adds a stylesheet to the current web response. * * @param string $file The stylesheet file * @param string $position Position * @param string $options Stylesheet options */ public function addStylesheet($file, $position = '', $options = array()) { $this->validatePosition($position); $this->stylesheets[$position][$file] = $options; } /** * Removes a stylesheet from the current web response. * * @param string $file The stylesheet file to remove */ public function removeStylesheet($file) { foreach ($this->getPositions() as $position) { unset($this->stylesheets[$position][$file]); } } /** * Clear all previously added stylesheets */ public function clearStylesheets() { foreach (array_keys($this->getStylesheets()) as $file) { $this->removeStylesheet($file); } } /** * Retrieves javascript files from the current web response. * * By default, the position is sfWebResponse::ALL, * and the method returns all javascripts ordered by position. * * @param string $position The position * * @return array An associative array of javascript files as keys and options as values */ public function getJavascripts($position = self::ALL) { if (self::ALL === $position) { $javascripts = array(); foreach ($this->getPositions() as $position) { foreach ($this->javascripts[$position] as $file => $options) { $javascripts[$file] = $options; } } return $javascripts; } else if (self::RAW === $position) { return $this->javascripts; } $this->validatePosition($position); return $this->javascripts[$position]; } /** * Adds javascript code to the current web response. * * @param string $file The JavaScript file * @param string $position Position * @param string $options Javascript options */ public function addJavascript($file, $position = '', $options = array()) { $this->validatePosition($position); $this->javascripts[$position][$file] = $options; } /** * Removes a JavaScript file from the current web response. * * @param string $file The Javascript file to remove */ public function removeJavascript($file) { foreach ($this->getPositions() as $position) { unset($this->javascripts[$position][$file]); } } /** * Clear all previously added javascripts */ public function clearJavascripts() { foreach (array_keys($this->getJavascripts()) as $file) { $this->removeJavascript($file); } } /** * Retrieves slots from the current web response. * * @return string Javascript code */ public function getSlots() { return $this->slots; } /** * Sets a slot content. * * @param string $name Slot name * @param string $content Content */ public function setSlot($name, $content) { $this->slots[$name] = $content; } /** * Retrieves cookies from the current web response. * * @return array Cookies */ public function getCookies() { return $this->cookies; } /** * Retrieves HTTP headers from the current web response. * * @return string HTTP headers */ public function getHttpHeaders() { return $this->headers; } /** * Cleans HTTP headers from the current web response. */ public function clearHttpHeaders() { $this->headers = array(); } /** * Copies all properties from a given sfWebResponse object to the current one. * * @param sfWebResponse $response An sfWebResponse instance */ public function copyProperties(sfWebResponse $response) { $this->options = $response->getOptions(); $this->headers = $response->getHttpHeaders(); $this->metas = $response->getMetas(); $this->httpMetas = $response->getHttpMetas(); $this->stylesheets = $response->getStylesheets(self::RAW); $this->javascripts = $response->getJavascripts(self::RAW); $this->slots = $response->getSlots(); $this->options['http_protocol'] = 'HTTP/1.1'; } /** * Merges all properties from a given sfWebResponse object to the current one. * * @param sfWebResponse $response An sfWebResponse instance */ public function merge(sfWebResponse $response) { foreach ($this->getPositions() as $position) { $this->javascripts[$position] = array_merge($this->getJavascripts($position), $response->getJavascripts($position)); $this->stylesheets[$position] = array_merge($this->getStylesheets($position), $response->getStylesheets($position)); } $this->slots = array_merge($this->getSlots(), $response->getSlots()); } /** * @see sfResponse */ public function serialize() { return serialize(array($this->content, $this->statusCode, $this->statusText, $this->options, $this->headerOnly, $this->headers, $this->metas, $this->httpMetas, $this->stylesheets, $this->javascripts, $this->slots)); } /** * @see sfResponse */ public function unserialize($serialized) { list($this->content, $this->statusCode, $this->statusText, $this->options, $this->headerOnly, $this->headers, $this->metas, $this->httpMetas, $this->stylesheets, $this->javascripts, $this->slots) = unserialize($serialized); } /** * Validate a position name. * * @param string $position * * @throws InvalidArgumentException if the position is not available */ protected function validatePosition($position) { if (!in_array($position, $this->positions, true)) { throw new InvalidArgumentException(sprintf('The position "%s" does not exist (available positions: %s).', $position, implode(', ', $this->positions))); } } /** * Fixes the content type by adding the charset for text content types. * * @param string $contentType The content type * * @return string The content type with the charset if needed */ protected function fixContentType($contentType) { // add charset if needed (only on text content) if (false === stripos($contentType, 'charset') && (0 === stripos($contentType, 'text/') || strlen($contentType) - 3 === strripos($contentType, 'xml'))) { $contentType .= '; charset='.$this->options['charset']; } // change the charset for the response if (preg_match('/charset\s*=\s*(.+)\s*$/', $contentType, $match)) { $this->options['charset'] = $match[1]; } return $contentType; } }
apache-2.0