answer
stringlengths
15
1.25M
#include "audioloader.h" using namespace djaudio; AudioLoader::AudioLoader(DB * db, QObject * parent) : QObject(parent), mDB(db) { qRegisterMetaType<djaudio::AudioBufferPtr>("djaudio::AudioBufferPtr"); qRegisterMetaType<djaudio::BeatBufferPtr>("djaudio::BeatBufferPtr"); } void AudioLoader::playerTrigger(int player, QString name) { if (player < 0 || name != "load") return; //build up loaders for (int p = mLoaders.size(); p <= player; p++) { djaudio::LoaderThread * loader = new djaudio::LoaderThread(p, this); mLoaders.push_back(loader); connect(loader, SIGNAL(<API key>(int, QString, int)), SIGNAL(<API key>(int,QString, int))); connect(loader, SIGNAL(<API key>(int, QString, QString)), SIGNAL(<API key>(int,QString, QString))); connect(loader, SIGNAL(loadComplete(int, djaudio::AudioBufferPtr, djaudio::BeatBufferPtr)), SIGNAL(<API key>(int, djaudio::AudioBufferPtr, djaudio::BeatBufferPtr))); } try { QString audio_file_location; QString <API key>; if (mDB-><API key>(mWorkID, audio_file_location, <API key>)) { QString songinfo("$title\n$artist"); mDB->format_string_by_id(mWorkID, songinfo); emit(<API key>(player, "loading_work", songinfo)); emit(<API key>(player, "loading_work", mWorkID)); mLoaders[player]->load(audio_file_location, <API key>, songinfo); } } catch (std::exception& e) { emit(playerLoadError(player, QString(e.what()))); } } void AudioLoader::selectWork(int id) { mWorkID = id; }
<?php Class DaoTodo { private static function getConn(){ try{ $pdo = new PDO('sqlite:'.dirname(__FILE__).'/../db/todolist.db'); $pdo->setAttribute(PDO::<API key>, PDO::FETCH_ASSOC); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } catch(Exception $e) { echo "Impossible d'accéder à la base de données SQLite : ".$e->getMessage(); die(); } } public static function getLists(){ $pdo = DaoTodo::getConn(); $stmt = $pdo->query("SELECT * FROM mtt_lists ORDER BY ow"); $result = $stmt->fetchAll(); return $result; } public static function getListById($listId){ $pdo = DaoTodo::getConn(); $stmt = $pdo->query("SELECT * FROM mtt_lists WHERE id=$listId"); $result = $stmt->fetchAll(); return $result[0]; } public static function getTodosByListId($listId){ $pdo = DaoTodo::getConn(); $stmt = $pdo->query("SELECT * FROM mtt_lists WHERE id=$listId"); $liste = $stmt->fetchAll(); $sorting = intval($liste[0]["sorting"]); //0 > sort by hand //3 > sort by date created 103 //1 > sort by priority //2 > sort by due date //4 > sort by date modified switch($sorting) { case 0: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY ow"); break; case 1: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY prio DESC"); break; case 101: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY prio"); break; case 2: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY duedate DESC"); break; case 102: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY duedate"); break; case 3: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY d_created"); break; case 103: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY d_created DESC"); break; case 4: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY d_edited"); break; case 104: $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE compl=0 AND list_id=$listId ORDER BY d_edited DESC"); break; } $result = $stmt->fetchAll(); return $result; } public static function getTodoById($todoId){ $pdo = DaoTodo::getConn(); $stmt = $pdo->query("SELECT * FROM mtt_todolist WHERE id=$todoId"); $result = $stmt->fetchAll(); return $result[0]; } public static function isListEmpty($listId){ $todos = DaoTodo::getTodosByListId($listId); if(count($todos)==0) {$vide = true;} else {$vide = false;} return $vide; } public static function setTodoDone($todoId){ $pdo = DaoTodo::getConn(); $stmt = $pdo->exec("UPDATE mtt_todolist SET compl=1 WHERE id=$todoId"); $todo = DaoTodo::getTodoById($todoId); return $todo; } public static function insertFastTodo($todo){ $pdo = DaoTodo::getConn(); $uid=generateUUID(); $time=time(); $stmt = $pdo->prepare("INSERT INTO mtt_todolist (uuid,list_id,title,note,d_created,d_edited) VALUES (:uid,:list_id,:title,:note,:time,:timeb)"); $stmt->bindParam(':uid',$uid); $stmt->bindParam(':title',$todo["title"]); $stmt->bindParam(':note',$todo["note"]); $stmt->bindParam(':list_id',$todo["list"]); $stmt->bindParam(':time',$time); $stmt->bindParam(':timeb',$time); $stmt->execute(); } public static function editTodo($todo) { $pdo = DaoTodo::getConn(); $stmt = $pdo->prepare('UPDATE mtt_todolist SET note=:note WHERE id=:id'); $stmt->bindParam(':note',$todo["note"]); $stmt->bindParam(':id',$todo["id"]); $stmt->execute(); } } ?>
CStudioAdminConsole.Tool.ContentTypes.PropertyType.String = CStudioAdminConsole.Tool.ContentTypes.PropertyType.String || function(fieldName, containerEl) { this.fieldName = fieldName; this.containerEl = containerEl; return this; } YAHOO.extend(CStudioAdminConsole.Tool.ContentTypes.PropertyType.String, CStudioAdminConsole.Tool.ContentTypes.PropertyType, { render: function(value, updateFn) { var containerEl = this.containerEl; var valueEl = document.createElement("input"); containerEl.appendChild(valueEl); valueEl.value = value; valueEl.fieldName = this.fieldName; if(updateFn) { var updateFieldFn = function(event, el) { updateFn(event, el); CStudioAdminConsole.Tool.ContentTypes.visualization.render(); }; YAHOO.util.Event.on(valueEl, 'keyup', updateFieldFn, valueEl); } this.valueEl = valueEl; }, getValue: function() { return this.valueEl.value; } }); CStudioAuthoring.Module.moduleLoaded("<API key>", CStudioAdminConsole.Tool.ContentTypes.PropertyType.String);
CREATE TABLE `USArrests` ( `Murder` FLOAT NOT NULL, `Assault` INTEGER NOT NULL, `UrbanPop` INTEGER NOT NULL, `Rape` FLOAT NOT NULL );
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.8 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .<API key> # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/spacecat/AutonomousFlight/simulation/simulation_ws/src # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/spacecat/AutonomousFlight/simulation/simulation_ws/build # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..." /usr/bin/cmake -i . .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -<API key>=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: install/local .PHONY : install/local/fast # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -<API key>=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: install/strip .PHONY : install/strip/fast # Special rule for the target <API key> <API key>: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : <API key> # Special rule for the target <API key> <API key>/fast: <API key> .PHONY : <API key>/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target test test: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..." /usr/bin/ctest --<API key> $(ARGS) .PHONY : test # Special rule for the target test test/fast: test .PHONY : test/fast # The main all target all: <API key> cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(CMAKE_COMMAND) -E <API key> /home/spacecat/AutonomousFlight/simulation/simulation_ws/build/CMakeFiles /home/spacecat/AutonomousFlight/simulation/simulation_ws/build/gflags_catkin/CMakeFiles/progress.marks cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/all $(CMAKE_COMMAND) -E <API key> /home/spacecat/AutonomousFlight/simulation/simulation_ws/build/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. gflags_catkin/CMakeFiles/gflags_catkin.dir/rule: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/CMakeFiles/gflags_catkin.dir/rule .PHONY : gflags_catkin/CMakeFiles/gflags_catkin.dir/rule # Convenience name for target. gflags_catkin: gflags_catkin/CMakeFiles/gflags_catkin.dir/rule .PHONY : gflags_catkin # fast build rule for target. gflags_catkin/fast: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f gflags_catkin/CMakeFiles/gflags_catkin.dir/build.make gflags_catkin/CMakeFiles/gflags_catkin.dir/build .PHONY : gflags_catkin/fast # Convenience name for target. gflags_catkin/CMakeFiles/<API key>.dir/rule: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/CMakeFiles/<API key>.dir/rule .PHONY : gflags_catkin/CMakeFiles/<API key>.dir/rule # Convenience name for target. <API key>: gflags_catkin/CMakeFiles/<API key>.dir/rule .PHONY : <API key> # fast build rule for target. <API key>/fast: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f gflags_catkin/CMakeFiles/<API key>.dir/build.make gflags_catkin/CMakeFiles/<API key>.dir/build .PHONY : <API key>/fast # Convenience name for target. gflags_catkin/CMakeFiles/gflags_src.dir/rule: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f CMakeFiles/Makefile2 gflags_catkin/CMakeFiles/gflags_src.dir/rule .PHONY : gflags_catkin/CMakeFiles/gflags_src.dir/rule # Convenience name for target. gflags_src: gflags_catkin/CMakeFiles/gflags_src.dir/rule .PHONY : gflags_src # fast build rule for target. gflags_src/fast: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f gflags_catkin/CMakeFiles/gflags_src.dir/build.make gflags_catkin/CMakeFiles/gflags_src.dir/build .PHONY : gflags_src/fast src/dependency_tracker.o: src/dependency_tracker.cc.o .PHONY : src/dependency_tracker.o # target to build an object file src/dependency_tracker.cc.o: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f gflags_catkin/CMakeFiles/gflags_catkin.dir/build.make gflags_catkin/CMakeFiles/gflags_catkin.dir/src/dependency_tracker.cc.o .PHONY : src/dependency_tracker.cc.o src/dependency_tracker.i: src/dependency_tracker.cc.i .PHONY : src/dependency_tracker.i # target to preprocess a source file src/dependency_tracker.cc.i: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f gflags_catkin/CMakeFiles/gflags_catkin.dir/build.make gflags_catkin/CMakeFiles/gflags_catkin.dir/src/dependency_tracker.cc.i .PHONY : src/dependency_tracker.cc.i src/dependency_tracker.s: src/dependency_tracker.cc.s .PHONY : src/dependency_tracker.s # target to generate assembly for a file src/dependency_tracker.cc.s: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(MAKE) -f gflags_catkin/CMakeFiles/gflags_catkin.dir/build.make gflags_catkin/CMakeFiles/gflags_catkin.dir/src/dependency_tracker.cc.s .PHONY : src/dependency_tracker.cc.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... gflags_catkin" @echo "... <API key>" @echo "... gflags_src" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... <API key>" @echo "... rebuild_cache" @echo "... test" @echo "... src/dependency_tracker.o" @echo "... src/dependency_tracker.i" @echo "... src/dependency_tracker.s" .PHONY : help # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. <API key>: cd /home/spacecat/AutonomousFlight/simulation/simulation_ws/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : <API key>
package org.esa.snap.productlibrary.rcp.toolviews.extensions; import com.bc.ceres.core.Assert; import org.esa.snap.productlibrary.rcp.toolviews.<API key>; /** * Provides a standard implementation for <API key>. */ public class <API key> { private String id; private Class<? extends <API key>> actionExtClass; private int position; <API key>(final String id, final Class<? extends <API key>> actionExtClass, final int position) { this.id = id; this.actionExtClass = actionExtClass; this.position = position; } public String getId() { return id; } public int getPosition() { return position; } public boolean isSeperator() { return actionExtClass == null; } public <API key> createActionExt(final <API key> actionHandler) { if(isSeperator()) { return null; } Object object; try { object = actionExtClass.newInstance(); ((<API key>) object).setActionHandler(actionHandler); } catch (Throwable e) { throw new <API key>("actionExtClass.newInstance()", e); } Assert.state(object instanceof <API key>, "object instanceof <API key>"); return (<API key>) object; } }
package com.rabbitmq.client.test; import java.io.File; import java.io.IOException; import java.net.Socket; import java.util.Properties; import junit.framework.Test; import junit.framework.TestResult; import junit.framework.TestSuite; import com.rabbitmq.tools.Host; public abstract class <API key> extends TestSuite { private static final String <API key> = "localhost"; private static final int DEFAULT_SSL_PORT = 5671; private static boolean <API key> = false; static { Properties TESTS_PROPS = new Properties(System.getProperties()); TESTS_PROPS.setProperty("make.bin", System.getenv("MAKE") == null ? "make" : System.getenv("MAKE")); try { TESTS_PROPS.load(Host.class.getClassLoader().getResourceAsStream("build.properties")); TESTS_PROPS.load(Host.class.getClassLoader().getResourceAsStream("config.properties")); } catch (Exception e) { System.out.println( "\"build.properties\" or \"config.properties\" not found" + " in classpath. Please copy \"build.properties\" and" + " \"config.properties\" into src/test/resources. Ignore" + " this message if running with ant."); } finally { System.setProperties(TESTS_PROPS); } } public static boolean requiredProperties() { /* GNU Make. */ String make = Host.makeCommand(); boolean isGNUMake = false; if (make != null) { try { Process makeProc = Host.<API key>(make + " --version"); String makeVersion = Host.capture(makeProc.getInputStream()); isGNUMake = makeVersion.startsWith("GNU Make"); } catch (IOException e) {} } if (!isGNUMake) { System.err.println( "GNU Make required; please set \"make.bin\" system property" + " or \"$MAKE\" environment variable"); return false; } /* Path to rabbitmq_test. */ String rabbitmq_test = Host.rabbitmqTestDir(); if (rabbitmq_test == null || !new File(rabbitmq_test).isDirectory()) { System.err.println( "rabbitmq_test required; please set \"sibling.rabbitmq_test.dir\" system" + " property"); return false; } /* Path to rabbitmqctl. */ String rabbitmqctl = Host.rabbitmqctlCommand(); if (rabbitmqctl == null || !new File(rabbitmqctl).isFile()) { System.err.println( "rabbitmqctl required; please set \"rabbitmqctl.bin\" system" + " property"); return false; } return true; } public static boolean isUnderUmbrella() { return new File("../../UMBRELLA.md").isFile(); } public static boolean isSSLAvailable() { String SSL_CERTS_DIR = System.getenv("SSL_CERTS_DIR"); String hostname = System.getProperty("broker.hostname"); String port = System.getProperty("broker.sslport"); if (SSL_CERTS_DIR == null || hostname == null || port == null) return false; String sslClientCertsDir = SSL_CERTS_DIR + File.separator + "client"; // If certificate is present and some server is listening on port 5671 if (new File(sslClientCertsDir).exists() && <API key>(hostname, Integer.parseInt(port))) { return true; } else return false; } private static boolean <API key>(String host, int port) { Socket s = null; try { s = new Socket(host, port); return true; } catch (Exception e) { return false; } finally { if (s != null) try { s.close(); } catch (Exception e) { } } } }
#include "fdraii.h" namespace range { namespace util { ::range::<API key> LockFdRAIILogModule { "util.LockFdRAII" }; } /* namespace util */ } /* namespace range */
# <API key>: true require 'rails_helper' RSpec.shared_examples 'sluggable' do let(:model_sym) { subject.class.name.underscore.to_sym } let(:instance) { FactoryGirl.create model_sym } it 'has callback for set_slug' do expect(subject.class.<API key>.select { |cb| cb.kind.eql?(:before) } .map(&:raw_filter).include?(:set_slug)).to be_truthy end describe 'slugify' do it 'slugifies the thing we want' do expect(subject.class.slugify('Universal Health Care ')).to eq('<API key>') end it 'strips special characters' do expect(subject.class.slugify("party-palaces' hause")).to eq('party_palaces_hause') end it 'handles dashed things' do expect(subject.class.slugify('Cool -- A sweet change')).to eq('cool_a_sweet_change') end it "removes parentheses and what's inside them" do expect(subject.class.slugify('As Soon As Possible Party (ASAPP) ')).to eq('<API key>') end it 'returns nil if given nil' do expect(subject.class.slugify(nil)).to be_nil end end it 'to_param returns slug' do subject.slug = 'cool slug' expect(subject.to_param).to eq 'cool slug' end describe 'friendly_find' do context 'integer_slug' do it 'finds integers' do n = rand(0..15) expect(subject.class).to receive(:find).with(n) subject.class.friendly_find(n) end end context 'not integer slug' do it 'finds by the slug' do n = 'foo' allow(subject.class).to receive(:slugify) { 'bar' } expect(subject.class).to receive(:find_by_slug).with('bar') subject.class.friendly_find(n) end end end end
package com.jw.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; public class SQLUtils { private static final Logger LOGGER = Logger.getLogger(SQLUtils.class); private static final Pattern <API key> = Pattern.compile(":([A-Za-z0-9_]+)"); public static int update(String dbName, String sql, Map<String, Object> params) { DB db = DbManagerFactory.getManager().getDB(dbName); return update(db, sql, params); } public static int update(String dbName, String sql, Object[] params) { DB db = DbManagerFactory.getManager().getDB(dbName); return update(db, sql, params); } public static int update(String sql, Map<String, Object> params) { DB db = DbManagerFactory.getManager().getDefaultDB(); return update(db, sql, params); } public static int update(String sql, Object[] params) { DB db = DbManagerFactory.getManager().getDefaultDB(); return update(db, sql, params); } public static int update(DB db, String sql, Map<String, Object> params) { Connection conn = db.getConnection(); int result = update(conn, sql, params); db.releaseConnection(conn); return result; } public static int update(DB db, String sql, Object[] params) { Connection conn = db.getConnection(); int result = update(conn, sql, params); db.releaseConnection(conn); return result; } public static int update(Connection conn, String sql, Map<String, Object> params) { List<Object> list = new LinkedList<Object>(); Matcher m = <API key>.matcher(sql); if (m.find()) { StringBuilder sb = new StringBuilder(sql); int start = 0, end = 0, offset = 0; while (m.find(start)) { start = m.start(); end = m.end(); sb.replace(start + offset, end + offset, "?"); list.add(params.get(m.group(1))); offset = 1 - (end - start); start = end; } return update(conn, sb.toString(), list.toArray()); } return update(conn, sql, (Object[]) null); } public static int update(Connection conn, String sql, Object[] params) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); } catch (SQLException e) { LOGGER.error("Prepare statement failed", e); return 0; } if (params != null) { int len = params.length; for (int i = 1; i <= len; i++) { try { ps.setObject(i, params[i - 1]); } catch (SQLException e) { LOGGER.error("Error raised when set value in PreparedStatement", e); return 0; } } } log(ps); int i = 0; try { i = ps.executeUpdate(); } catch (SQLException e) { LOGGER.error("Error raised when execute sql : " + sql, e); } return i; } public static ResultSet query(String dbName, String sql, Map<String, Object> params) { DB db = DbManagerFactory.getManager().getDB(dbName); return query(db, sql, params); } public static ResultSet query(String dbName, String sql, Object[] params) { DB db = DbManagerFactory.getManager().getDB(dbName); return query(db, sql, params); } public static ResultSet query(String sql, Map<String, Object> params) { DB db = DbManagerFactory.getManager().getDefaultDB(); return query(db, sql, params); } public static ResultSet query(String sql, Object[] params) { DB db = DbManagerFactory.getManager().getDefaultDB(); return query(db, sql, params); } public static ResultSet query(DB db, String sql, Map<String, Object> params) { Connection conn = db.getConnection(); ResultSet rs = query(conn, sql, params); db.releaseConnection(conn); return rs; } public static ResultSet query(DB db, String sql, Object[] params) { Connection conn = db.getConnection(); ResultSet rs = query(conn, sql, params); db.releaseConnection(conn); return rs; } public static ResultSet query(Connection conn, String sql, Map<String, Object> params) { List<Object> list = new LinkedList<Object>(); Matcher m = <API key>.matcher(sql); if (m.find()) { StringBuilder sb = new StringBuilder(sql); int start = 0, end = 0, offset = 0; while (m.find(start)) { start = m.start(); end = m.end(); sb.replace(start + offset, end + offset, "?"); list.add(params.get(m.group(1))); offset = 1 - (end - start); start = end; } return query(conn, sb.toString(), list.toArray()); } return query(conn, sql, (Object[]) null); } public static ResultSet query(Connection conn, String sql, Object[] params) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); } catch (Exception e) { LOGGER.error("Prepare statement failed", e); return null; } if (params != null) { int len = params.length; for (int i = 1; i <= len; i++) { try { ps.setObject(i, params[i - 1]); } catch (SQLException e) { LOGGER.error("Error raised when set value in PreparedStatement", e); return null; } } } log(ps); ResultSet rs = null; try { rs = ps.executeQuery(); } catch (SQLException e) { LOGGER.error("Error raised when querying with sql : " + sql, e); return null; } return rs; } private static void log(PreparedStatement ps) { String msg = ps.toString(); int index = msg.indexOf(":"); if (index > -1 && index != msg.length() - 1) { msg = msg.substring(msg.indexOf(":") + 1); } LOGGER.info("The sql is " + msg); } public static void release(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOGGER.error("Error raised when close rs."); return; } } } }
#ifndef Vectortypes_H #define Vectortypes_H #include <vector> #include <iterator> using namespace std; typedef vector<int> vint; typedef vector<vint> vvint; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<vvd> vvvd; typedef istream_iterator<double> iidouble; typedef vector<string> vstring; typedef string::iterator istring; typedef vint::iterator ivint; typedef vector<ivint> vivint; typedef vvint::iterator ivvint; typedef vd::iterator ivd; typedef vvd::iterator ivvd; typedef vint::const_iterator civint; typedef vvint::const_iterator civvint; typedef vd::const_iterator civd; typedef vvd::const_iterator civvd; ostream & operator <<(ostream & os, const vvd & matrice); ostream & operator <<(ostream & os, const vint & bs); ostream & operator <<(ostream & os, const vvint & vbs); ostream & operator <<(ostream & os, const vd & vect); typedef vstring::iterator ivstring; typedef istream_iterator<string> iisstring; vd operator+(const vd & vec1, const vd & vec2); vvd operator +(const vvd & mat1, const vvd & mat2); vd operator -(const vd & col1, const vd & col2); vvd operator -(const vvd & mat1, const vvd & mat2); vd abs(const vd & col1); vvd abs(const vvd & mat1); double sum(const vd & col1); double sum(const vvd & mat1); istream & operator >>(istream & is, vvd & matrice); istream & operator >>(istream & is, int * distmot); int min(int n1, int n2); #endif // Vectortypes_H
// Count denormals to check if denormal prevention works // TODO: include into unit tests? #include <map> #include <string> #include <iostream> #include "apf/biquad.h" #define <API key>(Name, Prevention) \ template<typename T> \ struct Name : Prevention<T> { \ void prevent_denormals(T& val) { \ this->Prevention<T>::prevent_denormals(val); \ if (std::abs(val) < std::numeric_limits<T>::min() && (val != 0)) \ denormal_counter[#Name].first++; \ denormal_counter[#Name].second++; } }; #define <API key>(coeffs, cascade, name, prevention) \ std::vector<decltype(coeffs)> \ temp##coeffs(cascade.number_of_sections(), coeffs); \ cascade.set(temp##coeffs.begin(), temp##coeffs.end()); \ denormal_counter[#name] = std::make_pair(0, 0); \ input[0] = 1; \ for (int n = 0; n < <API key>; ++n) { \ cascade.execute(input.begin(), input.end() , output.begin()); \ input[0] = 0; } \ std::cout << std::string(#cascade) << " (" << #prevention << ") created " \ << denormal_counter[#name].first << " denormal numbers (" \ << static_cast<float>(denormal_counter[#name].first) / static_cast<float>(denormal_counter[#name].second) * 100.0f \ << "%)." << std::endl; #define COUNT_DENORMALS(coeffs_flt, coeffs_dbl, name, prevention) { \ apf::Cascade<apf::BiQuad<float, name>> \ cascade_flt(<API key>); \ apf::Cascade<apf::BiQuad<double, name>> \ cascade_dbl(<API key>); \ <API key>(coeffs_flt, cascade_flt, name, prevention) \ <API key>(coeffs_dbl, cascade_dbl, name, prevention) \ std::cout << std::endl; } size_t block_size = 1024; int <API key> = 200; size_t <API key> = 10; // denormal counter map std::map<std::string, std::pair<int, int>> denormal_counter; // create denormal counter classes <API key>(count_dc, apf::dp::dc) <API key>(count_ac, apf::dp::ac) <API key>(count_quant, apf::dp::quantization) <API key>(count_set_zero_1, apf::dp::set_zero_2) // TODO: remove apf::dp::set_zero_1 <API key>(count_set_zero_2, apf::dp::set_zero_3) <API key>(count_ftz_on, apf::dp::none) <API key>(count_daz_on, apf::dp::none) <API key>(<API key>, apf::dp::none) <API key>(count_none, apf::dp::none) int main() { // We're only interested in single precision audio data std::vector<float> input(block_size); std::vector<float> output(block_size); apf::SosCoefficients<float> benign_flt, malignant_flt; apf::SosCoefficients<double> benign_dbl, malignant_dbl; // simple LPF benign_flt.b0 = 0.2f; benign_dbl.b0 = 0.2; benign_flt.b1 = 0.5f; benign_dbl.b1 = 0.5; benign_flt.b2 = 0.2f; benign_dbl.b2 = 0.2; benign_flt.a1 = 0.5f; benign_dbl.a1 = 0.5; benign_flt.a2 = 0.2f; benign_dbl.a2 = 0.2; // HPF similar to the one used in HOA algorithm malignant_flt.b0 = 0.98f; malignant_dbl.b0 = 0.98; malignant_flt.b1 = -1.9f; malignant_dbl.b1 = -1.9; malignant_flt.b2 = 0.93f; malignant_dbl.b2 = 0.93; malignant_flt.a1 = -1.85f; malignant_dbl.a1 = -1.85; malignant_flt.a2 = 0.9f; malignant_dbl.a2 = 0.9; std::cout << "\n==> First the benign coefficients:\n" << std::endl; COUNT_DENORMALS(benign_flt, benign_dbl, count_ac, apf::dp::ac) COUNT_DENORMALS(benign_flt, benign_dbl, count_dc, apf::dp::dc) COUNT_DENORMALS(benign_flt, benign_dbl, count_quant, apf::dp::quantization) COUNT_DENORMALS(benign_flt, benign_dbl, count_set_zero_1, apf::dp::set_zero_2) COUNT_DENORMALS(benign_flt, benign_dbl, count_set_zero_2, apf::dp::set_zero_3) #ifdef __SSE__ std::cout << "FTZ on" << std::endl; apf::dp::ftz_on(); COUNT_DENORMALS(benign_flt, benign_dbl, count_ftz_on, apf::dp::none) #ifdef __SSE3__ std::cout << "DAZ on" << std::endl; apf::dp::daz_on(); COUNT_DENORMALS(benign_flt, benign_dbl, count_daz_on, apf::dp::none) #endif std::cout << "FTZ off" << std::endl; apf::dp::ftz_off(); #ifdef __SSE3__ COUNT_DENORMALS(benign_flt, benign_dbl, <API key>, apf::dp::none) std::cout << "DAZ off" << std::endl; apf::dp::daz_off(); #endif #endif COUNT_DENORMALS(benign_flt, benign_dbl, count_none, apf::dp::none) std::cout << "\n==> Now the malignant coefficients:" << std::endl; std::cout << std::endl; COUNT_DENORMALS(malignant_flt, malignant_dbl, count_ac, apf::dp::ac) COUNT_DENORMALS(malignant_flt, malignant_dbl, count_dc, apf::dp::dc) COUNT_DENORMALS(malignant_flt, malignant_dbl, count_quant, apf::dp::quantization) COUNT_DENORMALS(malignant_flt, malignant_dbl, count_set_zero_1, apf::dp::set_zero_2) COUNT_DENORMALS(malignant_flt, malignant_dbl, count_set_zero_2, apf::dp::set_zero_3) #ifdef __SSE__ std::cout << "FTZ on" << std::endl; apf::dp::ftz_on(); COUNT_DENORMALS(malignant_flt, malignant_dbl, count_ftz_on, apf::dp::none) #ifdef __SSE3__ std::cout << "DAZ on" << std::endl; apf::dp::daz_on(); COUNT_DENORMALS(malignant_flt, malignant_dbl, count_daz_on, apf::dp::none) #endif std::cout << "FTZ off" << std::endl; apf::dp::ftz_off(); #ifdef __SSE3__ COUNT_DENORMALS(malignant_flt, malignant_dbl, <API key>, apf::dp::none) std::cout << "DAZ off" << std::endl; apf::dp::daz_off(); #endif #endif std::cout << "The following can take quite a while ... abort with Ctrl+C\n\n"; COUNT_DENORMALS(malignant_flt, malignant_dbl, count_none, apf::dp::none) }
#ifndef <API key> #define <API key> #include <asn_application.h> #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif /* <API key> */ #include <asn_internal.h>
package net.sf.jeppers.grid; /** * @author <a href="grom@capsicumcorp.com">Cameron Zemek</a> */ public interface <API key> extends java.util.EventListener{ public void selectionChanged(SelectionModelEvent e); }
#include "Watchdog.h" void Watchdog::Begin(byte pin, uint interval) { m_pin = pin; m_interval = interval * 500; m_lastToggle = 0; pinMode(m_pin, OUTPUT); digitalWrite(m_pin, HIGH); delay(50); digitalWrite(m_pin, LOW); m_state = true; } void Watchdog::Handle() { if (millis() < m_lastToggle) { m_lastToggle = 0; } if (millis() > m_lastToggle + m_interval) { m_state = !m_state; digitalWrite(m_pin, m_state); m_lastToggle = millis(); } }
package visGrid.tests; import junit.textui.TestRunner; import visGrid.Clotheswasher; import visGrid.VisGridFactory; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Clotheswasher</b></em>'. * <!-- end-user-doc --> * @generated */ public class ClotheswasherTest extends ConnectionTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(ClotheswasherTest.class); } /** * Constructs a new Clotheswasher test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ClotheswasherTest(String name) { super(name); } /** * Returns the fixture for this Clotheswasher test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected Clotheswasher getFixture() { return (Clotheswasher)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(VisGridFactory.eINSTANCE.createClotheswasher()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //ClotheswasherTest
package com.shuttler67.demonomancy.proxy; public interface IProxy { public abstract void registerKeyBindings(); public abstract void <API key>(); public abstract void <API key>(); public abstract void <API key>(); }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_33) on Fri Aug 03 11:42:05 PDT 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class com.hp.hpl.jena.reasoner.rulesys.builtins.GE (Apache Jena) </TITLE> <META NAME="date" CONTENT="2012-08-03"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hp.hpl.jena.reasoner.rulesys.builtins.GE (Apache Jena)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../com/hp/hpl/jena/reasoner/rulesys/builtins/GE.html" title="class in com.hp.hpl.jena.reasoner.rulesys.builtins"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?com/hp/hpl/jena/reasoner/rulesys/builtins//class-useGE.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="GE.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>com.hp.hpl.jena.reasoner.rulesys.builtins.GE</B></H2> </CENTER> No usage of com.hp.hpl.jena.reasoner.rulesys.builtins.GE <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../com/hp/hpl/jena/reasoner/rulesys/builtins/GE.html" title="class in com.hp.hpl.jena.reasoner.rulesys.builtins"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?com/hp/hpl/jena/reasoner/rulesys/builtins//class-useGE.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="GE.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Licenced under the Apache License, Version 2.0 </BODY> </HTML>
// CHistory: // implements undo and redo. class CHistoryTrack { public: CHistoryTrack( }; typedef CTypedPtrList<CPtrList, CHistoryTrack*> CHistoryTrackList; class CHistory { public: CHistory(); ~CHistory(); // mark undo position: void MarkUndoPosition(); // keep this object so we can undo changes to it: void Keep(CMapClass *pObject); // keep the relationship between objects: void Keep(CMapClass *pParent, CMapClass *pChild); // store this pointer for destruction if unused during undo lifetime: void KeepForDestruction(CMapClass *pObject); CHistoryTrackList *CurTrack; CTypedPtrList<CPtrList, CHistoryTrackList*> Tracks; };
/* * @lc app=leetcode id=1203 lang=csharp * * [1203] Sort Items by Groups Respecting Dependencies */ using System.Collections.Generic; using System.Linq; // @lc code=start public class Solution { private static bool SortItemsRecurse(IList<int> sorted, int[] added, HashSet<int>[] deps, int curr) { if (added[curr] == 1) { return false; } if (added[curr] == 2) { return true; } added[curr] = 1; foreach (var next in deps[curr]) { if (!SortItemsRecurse(sorted, added, deps, next)) { return false; } } sorted.Add(curr); added[curr] = 2; return true; } public int[] SortItems(int n, int m, int[] group, IList<IList<int>> beforeItems) { int t = n + 2 * m; var deps = new HashSet<int>[t]; var added = new int[t]; var sorted = new List<int>(t); for (int i = 0; i < t; ++i) { deps[i] = new HashSet<int>(); } for (int i = 0; i < n; ++i) { if (group[i] != -1) { deps[i].Add(n + m + group[i]); deps[n + group[i]].Add(i); } foreach (var before in beforeItems[i]) { if (group[i] != -1 && group[i] == group[before]) { deps[before].Add(i); } else { int gi = group[i] == -1 ? i : (n + group[i]); int gb = group[before] == -1 ? before : (n + m + group[before]); deps[gb].Add(gi); } } } for (int i = t - 1; i >= 0; --i) { if (!SortItemsRecurse(sorted, added, deps, i)) { return new int[0]; } } return sorted.Where(i => i < n).Reverse().ToArray(); } } // @lc code=end
# -*- coding: utf-8 -*- __all__ = ["inet_aton", "record_by_ip", "record_by_request", "get_ip", "<API key>", "<API key>"] import struct import socket from geoip.defaults import BACKEND, REDIS_TYPE from geoip.redis_wrapper import RedisClient from geoip.models import Range _RECORDS_KEYS = ('country', 'area', 'city', 'isp', 'provider') def _from_redis(ip): r = RedisClient() data = r.zrangebyscore("geoip", ip, 'inf', 0, 1, withscores=True) if not data: return res, score = data[0] geo_id, junk, prefix = res.decode().split(":", 2) if prefix == "s" and score > ip: return info = r.get("geoip:%s" % junk) if info is not None: return info.decode('utf-8', 'ignore').split(':') def _from_db(ip): obj = Range.objects.select_related().filter( start_ip__lte=ip, end_ip__gte=ip ).order_by('end_ip', '-start_ip')[:1][0] if REDIS_TYPE == 'pk': return map(lambda k: str(getattr(obj, k).pk), _RECORDS_KEYS) return map(lambda k: str(getattr(obj, k)), _RECORDS_KEYS) def inet_aton(ip): return struct.unpack('!L', socket.inet_aton(ip))[0] def get_ip(request): ip = request.META['REMOTE_ADDR'] if '<API key>' in request.META: ip = request.META['<API key>'].split(',')[0] return ip def record_by_ip(ip): return (_from_redis if BACKEND == 'redis' else _from_db)(inet_aton(ip)) def record_by_request(request): return record_by_ip(get_ip(request)) def <API key>(ip): return dict(zip(_RECORDS_KEYS, record_by_ip(ip))) def <API key>(request): return dict(zip(_RECORDS_KEYS, record_by_ip(get_ip(request))))
<?php /* @var $this <API key> */ /* @var $model SettingsSound */ /* @var $form bootstrap.widgets.TbActiveForm */ $this->widget('bootstrap.widgets.TbBreadcrumb', array( 'links' => array( Yii::t('app','Modules') => 'indexModules', Yii::t('app','Sound'), ), )); $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'settings-sound-form', 'layout' => TbHtml::<API key>, )); ?> <legend>Sound</legend> <fieldset> <?php echo $form-><API key>($model,'enabled', array('value'=>-1)); ?> <?php echo $form-><API key>($model,'volume', array('append' => '%')); ?> <?php echo $form-><API key>($model,'debug', array('value'=>-1)); ?> </fieldset> <?php echo TbHtml::formActions(array( TbHtml::submitButton(Yii::t('app','Submit'), array('color' => TbHtml::<API key>)), TbHtml::resetButton(Yii::t('app','Reset')), )); ?> <?php $this->endWidget(); ?>
package com.websimple.springmvc.configuracion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.<API key>; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.<API key>; import org.springframework.security.core.userdetails.UserDetailsService; @Configuration @EnableWebSecurity public class <API key> extends <API key> { @Autowired @Qualifier("<API key>") UserDetailsService userDetailsService; @Autowired public void <API key>(<API key> auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/principal").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-22 16:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('teklif', '<API key>'), ] operations = [ migrations.CreateModel( name='Odeme', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('odeme_basligi', models.CharField(blank=True, max_length=40, null=True)), ('ucret', models.IntegerField(blank=True, null=True)), ('odemeTuru', models.CharField(choices=[('H', 'Havale'), ('N', 'Nakit'), ('O', 'Online Ödeme')], default='N', max_length=3)), ('tamamlanma_durumu', models.BooleanField(default=False)), ('teklif', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='odeme_teklifi', to='teklif.Teklif')), ], options={ 'verbose_name_plural': 'Ödemeler', 'verbose_name': 'Ödeme', }, ), ]
<?php abstract class OneTrickAbstract { /** @var mixed */ public $storeHere; /** * * * @param mixed $whatever */ abstract public function trick($whatever); }
// This file is part of multidupehack. #include "MaxArea.h" unsigned int MaxArea::threshold; MaxArea::MaxArea(const unsigned int nbOfDimensions, const unsigned int thresholdParam): <API key>(nbOfDimensions), maxArea(0) { threshold = thresholdParam; } MaxArea* MaxArea::clone() const { return new MaxArea(*this); } const bool MaxArea::<API key>(const unsigned int <API key>, const vector<unsigned int>& elementsSetPresent) { maxArea = 1; unsigned int dimensionId = 0; for (unsigned int& <API key> : <API key>) { if (dimensionId++ == <API key>) { <API key> += elementsSetPresent.size(); } maxArea *= <API key>; } #ifdef DEBUG if (maxArea > threshold) { cout << threshold << "-maximal area constraint cannot be satisfied -> Prune!" << endl; } #endif return maxArea > threshold; } const float MaxArea::optimisticValue() const { return static_cast<float>(maxArea); }
package org.chemicalmozart.view.implementations; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.border.EmptyBorder; public class SecondView extends JDialog { /** * Launch the application. */ public static void main(String[] args) { try { SecondView dialog = new SecondView(); dialog.<API key>(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public SecondView() { setBounds(100, 100, 450, 300); getContentPane().setLayout(new GridLayout(0, 2, 0, 0)); JPanel leftPanel = new JPanel(); getContentPane().add(leftPanel); leftPanel.setLayout(new GridLayout(2, 1, 0, 0)); JPanel progressBarPanel = new JPanel(); progressBarPanel.setBorder(new EmptyBorder(40, 10, 40, 10)); leftPanel.add(progressBarPanel); progressBarPanel.setLayout(new GridLayout(0, 1, 0, 0)); JProgressBar progressBar = new JProgressBar(); progressBarPanel.add(progressBar); JPanel btnPlayPanel = new JPanel(); btnPlayPanel.setBorder(new EmptyBorder(30, 10, 30, 10)); leftPanel.add(btnPlayPanel); btnPlayPanel.setLayout(new GridLayout(0, 1, 0, 0)); JButton btnPlay = new JButton("Play"); btnPlayPanel.add(btnPlay); JPanel rightPanel = new JPanel(); getContentPane().add(rightPanel); rightPanel.setLayout(new GridLayout(2, 0, 0, 0)); JPanel btnSavePanel = new JPanel(); btnSavePanel.setBorder(new EmptyBorder(30, 10, 30, 10)); rightPanel.add(btnSavePanel); btnSavePanel.setLayout(new GridLayout(0, 1, 0, 0)); JButton btnSave = new JButton("Save"); btnSavePanel.add(btnSave); JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(30, 10, 30, 10)); rightPanel.add(panel); panel.setLayout(new GridLayout(0, 1, 0, 0)); JButton btnClose = new JButton("Close"); panel.add(btnClose); } }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0" /> <style type="text/css"> </style> </head> <body> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> <span class="hello">hello</span> <span class="world">world</span> </body> </html>
module.exports = [ [ [ / 'sh_comment', 1 ], [ /\b[+-]?(?:(?:0x[A-Fa-f0-9]+)|(?:(?:[\d]*\.)?[\d]+(?:[eE][+-]?[\d]+)?))u?(?:(?:int(?:8|16|32|64))|L)?\b/g, 'sh_number', -1 ], [ /"/g, 'sh_string', 2 ], [ /'/g, 'sh_string', 3 ], [ /~|!|%|\^|\*|\(|\)|-|\+|=|\[|\]|\\|:|;|,|\.|\/|\?|&|<|>|\|/g, 'sh_symbol', -1 ], [ /\{|\}/g, 'sh_cbracket', -1 ], [ /\b(?:proc|global|upvar|if|then|else|elseif|for|foreach|break|continue|while|set|eval|case|in|switch|default|exit|error|proc|return|uplevel|loop|for_array_keys|for_recursive_glob|for_file|unwind_protect|expr|catch|namespace|rename|variable|method|itcl_class|public|protected|append|binary|format|re_syntax|regexp|regsub|scan|string|subst|concat|join|lappend|lindex|list|llength|lrange|lreplace|lsearch|lset|lsort|split|expr|incr|close|eof|fblocked|fconfigure|fcopy|file|fileevent|flush|gets|open|puts|read|seek|socket|tell|load|loadTk|package|pgk::create|pgk_mkIndex|source|bgerror|history|info|interp|memory|unknown|enconding|http|msgcat|cd|clock|exec|exit|glob|pid|pwd|time|dde|registry|resource)\b/g, 'sh_keyword', -1 ], [ /\$[A-Za-z0-9_]+/g, 'sh_variable', -1 ] ], [ [ /$/g, null, -2 ] ], [ [ /"/g, 'sh_string', -2 ], [ /\\./g, 'sh_specialchar', -1 ] ], [ [ /'/g, 'sh_string', -2 ], [ /\\./g, 'sh_specialchar', -1 ] ] ];
#ifndef TileCache_h #define TileCache_h #include "IntPointHash.h" #include "IntRect.h" #include "TiledBacking.h" #include "Timer.h" #include <wtf/HashMap.h> #include <wtf/Noncopyable.h> #include <wtf/PassOwnPtr.h> #include <wtf/RetainPtr.h> OBJC_CLASS CALayer; OBJC_CLASS WebTileCacheLayer; OBJC_CLASS WebTileLayer; namespace WebCore { class FloatRect; class IntPoint; class IntRect; class TileCache : public TiledBacking { <API key>(TileCache); public: static PassOwnPtr<TileCache> create(WebTileCacheLayer*, const IntSize& tileSize); ~TileCache(); void <API key>(); void setNeedsDisplay(); void <API key>(const IntRect&); void drawLayer(WebTileLayer*, CGContextRef); void setScale(CGFloat); bool acceleratesDrawing() const { return <API key>; } void <API key>(bool); CALayer *tileContainerLayer() const { return <API key>.get(); } void <API key>(float); void <API key>(CGColorRef); private: TileCache(WebTileCacheLayer*, const IntSize& tileSize); // TiledBacking member functions. virtual void visibleRectChanged(const IntRect&) OVERRIDE; virtual void setIsInWindow(bool) OVERRIDE; virtual void <API key>(bool) OVERRIDE; IntRect bounds() const; typedef IntPoint TileIndex; IntRect rectForTileIndex(const TileIndex&) const; void <API key>(const IntRect&, TileIndex& topLeft, TileIndex& bottomRight); IntRect tileCoverageRect() const; void <API key>(double interval); void <API key>(Timer<TileCache>*); void revalidateTiles(); WebTileLayer* tileLayerAtIndex(const TileIndex&) const; RetainPtr<WebTileLayer> createTileLayer(const IntRect&); bool <API key>() const; WebTileCacheLayer* m_tileCacheLayer; RetainPtr<CALayer> <API key>; const IntSize m_tileSize; IntRect m_visibleRect; typedef HashMap<TileIndex, RetainPtr<WebTileLayer> > TileMap; TileMap m_tiles; Timer<TileCache> <API key>; IntRect m_tileCoverageRect; CGFloat m_scale; CGFloat m_deviceScaleFactor; bool m_isInWindow; bool m_canHaveScrollbars; bool <API key>; RetainPtr<CGColorRef> <API key>; float <API key>; }; } // namespace WebCore #endif // TileCache_h
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns:v="urn:<API key>:vml" xmlns:o="urn:<API key>:office:office" xmlns:w="urn:<API key>:office:word" xmlns="http: <! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http: * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <head> <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 10"> <meta name=Originator content="Microsoft Word 10"> <link rel=File-List href="header_files/filelist.xml"> <link rel=Edit-Time-Data href="header_files/editdata.mso"> <!--[if !mso]> <style> v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif] <title>Main Page</title> <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Author>Randy Ribler</o:Author> <o:Template>Normal</o:Template> <o:LastAuthor>Randy Ribler</o:LastAuthor> <o:Revision>6</o:Revision> <o:TotalTime>16</o:TotalTime> <o:Created>2004-07-23T05:34:00Z</o:Created> <o:LastSaved>2004-07-23T06:03:00Z</o:LastSaved> <o:Pages>1</o:Pages> <o:Words>5</o:Words> <o:Characters>32</o:Characters> <o:Company>LC</o:Company> <o:Lines>1</o:Lines> <o:Paragraphs>1</o:Paragraphs> <o:<API key>>36</o:<API key>> <o:Version>10.2625</o:Version> </o:DocumentProperties> </xml><![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:SpellingState>Clean</w:SpellingState> <w:GrammarState>Clean</w:GrammarState> <w:BrowserLevel><API key></w:BrowserLevel> </w:WordDocument> </xml><![endif] <link rel=Stylesheet type="text/css" media=all href=RM_stylesheet.css> <style> <! /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman"; <API key>:yes;} h1 {mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; text-align:center; mso-pagination:widow-orphan; mso-outline-level:1; font-size:24.0pt; font-family:"Times New Roman"; font-weight:bold;} h2 {mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; mso-pagination:widow-orphan; mso-outline-level:2; font-size:18.0pt; font-family:"Times New Roman"; font-weight:bold;} a:link, span.MsoHyperlink {color:#252E78; text-decoration:underline; text-underline:single;} a:visited, span.<API key> {color:#3D2185; text-decoration:underline; text-underline:single;} p {mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman";} address {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; font-style:italic;} pre {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt; font-size:10.0pt; font-family:"Courier New"; <API key>:"Times New Roman";} p.formuladsp, li.formuladsp, div.formuladsp {mso-style-name:formuladsp; mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; text-align:center; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman";} p.mdtable, li.mdtable, div.mdtable {mso-style-name:mdtable; mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; mso-pagination:widow-orphan; background:#F4F4FB; border:none; mso-border-alt:solid #868686 .75pt; padding:0in; mso-padding-alt:0in 0in 0in 0in; font-size:12.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman";} p.mdrow, li.mdrow, div.mdrow {mso-style-name:mdrow; mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman";} p.mdescleft, li.mdescleft, div.mdescleft {mso-style-name:mdescleft; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; background:#FAFAFA; font-size:10.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman"; font-style:italic;} p.mdescright, li.mdescright, div.mdescright {mso-style-name:mdescright; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; background:#FAFAFA; font-size:10.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman"; font-style:italic;} p.memitemleft, li.memitemleft, div.memitemleft {mso-style-name:memitemleft; margin:3.0pt; mso-pagination:widow-orphan; background:#FAFAFA; border:none; mso-border-top-alt:solid #E0E0E0 .75pt; padding:0in; mso-padding-alt:1.0pt 0in 0in 0in; font-size:9.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman";} p.memitemright, li.memitemright, div.memitemright {mso-style-name:memitemright; margin:3.0pt; mso-pagination:widow-orphan; background:#FAFAFA; border:none; mso-border-top-alt:solid #E0E0E0 .75pt; padding:0in; mso-padding-alt:1.0pt 0in 0in 0in; font-size:10.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman";} p.search, li.search, div.search {mso-style-name:search; mso-margin-top-alt:auto; margin-right:0in; <API key>:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; <API key>:"Times New Roman"; font-weight:bold;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; <API key>:0; <API key>:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; <API key>:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman";} table.MsoTableGrid {mso-style-name:"Table Grid"; <API key>:0; <API key>:0; border:solid windowtext 1.0pt; mso-border-alt:solid windowtext .5pt; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-border-insideh:.5pt solid windowtext; mso-border-insidev:.5pt solid windowtext; mso-para-margin:0in; <API key>:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman";} </style> <![endif]--><![if mso 9]> <style> p.MsoNormal {margin-left:15.0pt;} </style> <![endif]><!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="4098"> <o:colormru v:ext="edit" colors="#060"/> <o:colormenu v:ext="edit" strokecolor="#060"/> </o:shapedefaults></xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1"/> </o:shapelayout></xml><![endif] </head> <body bgcolor=white lang=EN-US link="#252E78" vlink="#3D2185" style='tab-interval: .5in;margin-left:15.0pt;margin-right:15.0pt'> <div class=Section1> <p class=MsoNormal style='margin-top:0in;margin-right:15.0pt;margin-bottom: 0in;margin-left:15.0pt;margin-bottom:.0001pt'><!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="_x0000_s1026" type="#_x0000_t75" style='position:absolute; left:0;text-align:left;margin-left:30pt;margin-top:9pt;width:72.75pt;height:57.75pt; z-index:1'> <v:imagedata src="header_files/image001.jpg" o:title="NCSAlogo"/> </v:shape><![endif]--><![if !vml]><span style='mso-ignore:vglayout;position: absolute;z-index:1;left:0px;margin-left:40px;margin-top:12px;width:97px; height:77px'><img width=97 height=77 src="header_files/image002.jpg" v:shapes="_x0000_s1026"></span><![endif]><span style='mso-spacerun:yes'> </span><b style='<API key>:normal'><span style='font-size:22.0pt'><o:p></o:p></span></b></p> <div align=center> <table class=MsoTableGrid border=1 cellspacing=0 cellpadding=0 style='margin-left:103.45pt;border-collapse:collapse;border:none;<API key>: solid #006600 2.25pt;mso-yfti-tbllook:480;mso-padding-alt:0in 5.4pt 0in 5.4pt'> <tr style='mso-yfti-irow:0;mso-yfti-lastrow:yes;height:29.25pt'> <td width=443 valign=top style='width:332.6pt;border:none;border-bottom:solid #006600 2.25pt; padding:0in 5.4pt 0in 5.4pt;height:29.25pt'> <p class=MsoNormal><b style='<API key>:normal'><span style='font-size:22.0pt'>HDF5 C++ API Reference Manual</span></b></p> </td> </tr> </table> </div> <p class=MsoNormal><o:p>&nbsp;</o:p></p> <p class=MsoNormal><o:p>&nbsp;</o:p></p> <p class=MsoNormal><o:p>&nbsp;</o:p></p> </div> </body> </html> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li id="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> </ul></div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul></div> <div class="nav"> <a class="el" href="namespaceH5.html">H5</a>::<a class="el" href="classH5_1_1H5File.html">H5File</a></div> <h1>H5::H5File Class Reference</h1><!-- doxytag: class="H5::H5File" --><!-- doxytag: inherits="H5::IdComponent,H5::CommonFG" --><code>#include &lt;<a class="el" href="H5File_8h-source.html">H5File.h</a>&gt;</code> <p> <p>Inheritance diagram for H5::H5File: <p><center><img src="classH5_1_1H5File.png" usemap="#H5::H5File_map" border="0" alt=""></center> <map name="H5::H5File_map"> <area href="<API key>.html" alt="H5::IdComponent" shape="rect" coords="0,0,107,24"> <area href="classH5_1_1CommonFG.html" alt="H5::CommonFG" shape="rect" coords="117,0,224,24"> </map> <a href="<API key>.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">H5File</a> (const char *name, unsigned int flags, const <a class="el" href="<API key>.html">FileCreatPropList</a> &amp;create_plist=<a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a>, const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;access_plist=<a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a>)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Creates or opens an HDF5 file depending on the parameter flags. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">H5File</a> (const H5std_string &amp;name, unsigned int flags, const <a class="el" href="<API key>.html">FileCreatPropList</a> &amp;create_plist=<a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a>, const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;access_plist=<a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a>)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is another overloaded constructor. It differs from the above constructor only in the type of the <em>name</em> argument. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">openFile</a> (const H5std_string &amp;name, unsigned int flags, const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;access_plist=<a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a>)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is an overloaded member function, provided for convenience. It takes an <code>H5std_string</code> for <em>name</em>. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">openFile</a> (const char *name, unsigned int flags, const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;access_plist=<a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a>)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Opens an HDF5 file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">close</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Closes this HDF5 file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">flush</a> (H5F_scope_t scope) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Flushes all buffers associated with a file to disk. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="<API key>.html">FileAccPropList</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getAccessPlist</a> () const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Returns the access property list of this file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="<API key>.html">FileCreatPropList</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getCreatePlist</a> () const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Returns the creation property list of this file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">H5std_string&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getFileName</a> () const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Gets the name of this file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">hsize_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getFileSize</a> () const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Returns the file size of the HDF5 file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">hssize_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getFreeSpace</a> () const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Returns the amount of free space in the file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">ssize_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getObjCount</a> (unsigned types) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Returns the number of opened object IDs (files, datasets, groups and datatypes) in the same file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">ssize_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getObjCount</a> () const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is an overloaded member function, provided for convenience. It takes no parameter and returns the object count of all object types. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getObjIDs</a> (unsigned types, size_t max_objs, hid_t *oid_list) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Retrieves a list of opened object IDs (files, datasets, groups and datatypes) in the same file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">H5G_obj_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getRefObjType</a> (void *ref, H5R_type_t ref_type=H5R_OBJECT) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Retrieves the type of object that an object reference points to. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">H5G_obj_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getObjType</a> (void *ref, H5R_type_t ref_type=H5R_OBJECT) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This function was misnamed and will be deprecated in favor of <a class="el" href="classH5_1_1H5File.html#<API key>">H5File::getRefObjType</a>; please use getRefObjType instead. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="<API key>.html">DataSpace</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getRegion</a> (void *ref, H5R_type_t ref_type=H5R_DATASET_REGION) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Retrieves a dataspace with the region pointed to selected. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getVFDHandle</a> (<a class="el" href="<API key>.html">FileAccPropList</a> &amp;fapl, void **file_handle) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Returns the pointer to the file handle of the low-level file driver. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getVFDHandle</a> (void **file_handle) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is an overloaded member function, provided for convenience. It differs from the above function only in what arguments it accepts. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">reOpen</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Reopens this file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">reopen</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Reopens this file. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">reference</a> (void *ref, const char *name, const <a class="el" href="<API key>.html">DataSpace</a> &amp;dataspace, H5R_type_t ref_type=H5R_DATASET_REGION) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Creates a reference to an HDF5 object or a dataset region. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">reference</a> (void *ref, const char *name) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is an overloaded function, provided for your convenience. It differs from the above function in that it only creates a reference to an HDF5 object, not to a dataset region. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">reference</a> (void *ref, const H5std_string &amp;name) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is an overloaded function, provided for your convenience. It differs from the above function in that it takes an <code>H5std_string</code> for the object's name. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual H5std_string&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">fromClass</a> () const </td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">throwException</a> (const H5std_string &amp;func_name, const H5std_string &amp;msg) const </td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Throws file exception - initially implemented for <a class="el" href="classH5_1_1CommonFG.html">CommonFG</a>. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual hid_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getLocId</a> () const </td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">H5File</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Default constructor: creates a stub <a class="el" href="classH5_1_1H5File.html">H5File</a> object. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">H5File</a> (const <a class="el" href="classH5_1_1H5File.html">H5File</a> &amp;original)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Copy constructor: makes a copy of the original <a class="el" href="classH5_1_1H5File.html">H5File</a> object. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual hid_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">getId</a> () const </td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">~H5File</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Properly terminates access to this file. <a href="#<API key>"></a><br></td></tr> <tr><td colspan="2"><br><h2>Static Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">static bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">isHdf5</a> (const char *name)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Determines whether a file in HDF5 format. <a href="#<API key>"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">static bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">isHdf5</a> (const H5std_string &amp;name)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This is an overloaded member function, provided for convenience. It takes an <code>H5std_string</code> for <em>name</em>. <a href="#<API key>"></a><br></td></tr> <tr><td colspan="2"><br><h2>Protected Member Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classH5_1_1H5File.html#<API key>">p_setId</a> (const hid_t new_id)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Sets the identifier of this HDF5 file to a new value. <a href="#<API key>"></a><br></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <dl compact><dt><b>Examples: </b></dt><dd> <p> <a class="el" href="chunks_8cpp-example.html#_a1">chunks.cpp</a>, <a class="el" href="<API key>.html#_a19">compound.cpp</a>, <a class="el" href="create_8cpp-example.html#_a35">create.cpp</a>, <a class="el" href="<API key>.html#_a48">extend_ds.cpp</a>, <a class="el" href="<API key>.html#_a65">h5group.cpp</a>, <a class="el" href="<API key>.html#_a86">readdata.cpp</a>, and <a class="el" href="<API key>.html#_a106">writedata.cpp</a>.</dl> <p> <hr><h2>Constructor &amp; Destructor Documentation</h2> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::H5File" ref="<API key>" args="(const char *name, unsigned int flags, const FileCreatPropList &amp;create_plist=FileCreatPropList::DEFAULT, const FileAccPropList &amp;access_plist=FileAccPropList::DEFAULT)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5::H5File::H5File </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>flags</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">FileCreatPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>create_plist</em> = <code><a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a></code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>access_plist</em> = <code><a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a></code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> Creates or opens an HDF5 file depending on the parameter flags. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the file </td></tr> <tr><td valign="top"></td><td valign="top"><em>flags</em>&nbsp;</td><td>- IN: File access flags </td></tr> <tr><td valign="top"></td><td valign="top"><em>create_plist</em>&nbsp;</td><td>- IN: File creation property list, used when modifying default file meta-data. Default to <a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a> </td></tr> <tr><td valign="top"></td><td valign="top"><em>access_plist</em>&nbsp;</td><td>- IN: File access property list. Default to <a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a> </td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>Valid values of <em>flags</em> include: <ul> <li><code>H5F_ACC_TRUNC</code> - Truncate file, if it already exists, erasing all data previously stored in the file. </li> <li><code>H5F_ACC_EXCL</code> - Fail if file already exists. <code>H5F_ACC_TRUNC</code> and <code>H5F_ACC_EXCL</code> are mutually exclusive </li> <li><code>H5F_ACC_DEBUG</code> - print debug information. This flag is used only by HDF5 library developers; it is neither tested nor supported for use in applications. </li> </ul> </dd></dl> <dl compact><dt><b></b></dt><dd>For info on file creation in the case of an already-open file, please refer to the <b>Special</b> <b>case</b> section in the C layer Reference Manual at: <a href="../RM_H5F.html#File-Create">../RM_H5F.html::File-Create</a> </dd></dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::H5File" ref="<API key>" args="(const H5std_string &amp;name, unsigned int flags, const FileCreatPropList &amp;create_plist=FileCreatPropList::DEFAULT, const FileAccPropList &amp;access_plist=FileAccPropList::DEFAULT)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5::H5File::H5File </td> <td>(</td> <td class="paramtype">const H5std_string &amp;&nbsp;</td> <td class="paramname"> <em>name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>flags</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">FileCreatPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>create_plist</em> = <code><a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a></code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>access_plist</em> = <code><a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a></code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> This is another overloaded constructor. It differs from the above constructor only in the type of the <em>name</em> argument. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the file - <code>H5std_string</code> </td></tr> <tr><td valign="top"></td><td valign="top"><em>flags</em>&nbsp;</td><td>- IN: File access flags </td></tr> <tr><td valign="top"></td><td valign="top"><em>create_plist</em>&nbsp;</td><td>- IN: File creation property list, used when modifying default file meta-data. Default to <a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a> </td></tr> <tr><td valign="top"></td><td valign="top"><em>access_plist</em>&nbsp;</td><td>- IN: File access property list. Default to <a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a> </td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::H5File" ref="<API key>" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5::H5File::H5File </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> Default constructor: creates a stub <a class="el" href="classH5_1_1H5File.html">H5File</a> object. <p> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::H5File" ref="<API key>" args="(const H5File &amp;original)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5::H5File::H5File </td> <td>(</td> <td class="paramtype">const <a class="el" href="classH5_1_1H5File.html">H5File</a> &amp;&nbsp;</td> <td class="paramname"> <em>original</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> Copy constructor: makes a copy of the original <a class="el" href="classH5_1_1H5File.html">H5File</a> object. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>original</em>&nbsp;</td><td>- IN: <a class="el" href="classH5_1_1H5File.html">H5File</a> instance to copy </td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::~H5File" ref="<API key>" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5::H5File::~H5File </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"><code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Properly terminates access to this file. <p> </div> </div><p> <hr><h2>Member Function Documentation</h2> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::openFile" ref="<API key>" args="(const H5std_string &amp;name, unsigned int flags, const FileAccPropList &amp;access_plist=FileAccPropList::DEFAULT)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::openFile </td> <td>(</td> <td class="paramtype">const H5std_string &amp;&nbsp;</td> <td class="paramname"> <em>name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>flags</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>access_plist</em> = <code><a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a></code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> This is an overloaded member function, provided for convenience. It takes an <code>H5std_string</code> for <em>name</em>. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the file - <code>H5std_string</code> </td></tr> <tr><td valign="top"></td><td valign="top"><em>flags</em>&nbsp;</td><td>- IN: File access flags </td></tr> <tr><td valign="top"></td><td valign="top"><em>access_plist</em>&nbsp;</td><td>- IN: File access property list. Default to <a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a> </td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::openFile" ref="<API key>" args="(const char *name, unsigned int flags, const FileAccPropList &amp;access_plist=FileAccPropList::DEFAULT)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::openFile </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>flags</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">FileAccPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>access_plist</em> = <code><a class="el" href="<API key>.html#<API key>">FileAccPropList::DEFAULT</a></code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> Opens an HDF5 file. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the file </td></tr> <tr><td valign="top"></td><td valign="top"><em>flags</em>&nbsp;</td><td>- IN: File access flags </td></tr> <tr><td valign="top"></td><td valign="top"><em>access_plist</em>&nbsp;</td><td>- IN: File access property list. Default to <a class="el" href="<API key>.html#<API key>">FileCreatPropList::DEFAULT</a> </td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>Valid values of <em>flags</em> include: H5F_ACC_RDWR: Open with read/write access. If the file is currently open for read-only access then it will be reopened. Absence of this flag implies read-only access.</dd></dl> H5F_ACC_RDONLY: Open with read only access. - default </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::close" ref="<API key>" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::close </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"><code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Closes this HDF5 file. <p> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::flush" ref="<API key>" args="(H5F_scope_t scope) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::flush </td> <td>(</td> <td class="paramtype">H5F_scope_t&nbsp;</td> <td class="paramname"> <em>scope</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Flushes all buffers associated with a file to disk. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>scope</em>&nbsp;</td><td>- IN: Specifies the scope of the flushing action, which can be either of these values: <ul> <li><code>H5F_SCOPE_GLOBAL</code> - Flushes the entire virtual file </li> <li><code>H5F_SCOPE_LOCAL</code> - Flushes only the specified file </li> </ul> </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getAccessPlist" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="<API key>.html">FileAccPropList</a> H5::H5File::getAccessPlist </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Returns the access property list of this file. <p> <dl compact><dt><b>Returns:</b></dt><dd><a class="el" href="<API key>.html">FileAccPropList</a> object </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getCreatePlist" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="<API key>.html">FileCreatPropList</a> H5::H5File::getCreatePlist </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Returns the creation property list of this file. <p> <dl compact><dt><b>Returns:</b></dt><dd><a class="el" href="<API key>.html">FileCreatPropList</a> object </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getFileName" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5std_string H5::H5File::getFileName </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Gets the name of this file. <p> <dl compact><dt><b>Returns:</b></dt><dd>File name </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getFileSize" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">hsize_t H5::H5File::getFileSize </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Returns the file size of the HDF5 file. <p> <dl compact><dt><b>Returns:</b></dt><dd>File size </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>This function is called after an existing file is opened in order to learn the true size of the underlying file. </dd></dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getFreeSpace" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">hssize_t H5::H5File::getFreeSpace </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Returns the amount of free space in the file. <p> <dl compact><dt><b>Returns:</b></dt><dd>Amount of free space </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getObjCount" ref="<API key>" args="(unsigned types) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ssize_t H5::H5File::getObjCount </td> <td>(</td> <td class="paramtype">unsigned&nbsp;</td> <td class="paramname"> <em>types</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Returns the number of opened object IDs (files, datasets, groups and datatypes) in the same file. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>types</em>&nbsp;</td><td>- Type of object to retrieve the count </td></tr> </table> </dl> <dl compact><dt><b>Returns:</b></dt><dd>Number of opened object IDs </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>The valid values for <em>types</em> include: <ul> <li><code>H5F_OBJ_FILE</code> - Files only </li> <li><code>H5F_OBJ_DATASET</code> - Datasets only </li> <li><code>H5F_OBJ_GROUP</code> - Groups only </li> <li><code>H5F_OBJ_DATATYPE</code> - Named datatypes only </li> <li><code>H5F_OBJ_ATTR</code> - Attributes only </li> <li><code>H5F_OBJ_ALL</code> - All of the above, i.e., <code>H5F_OBJ_FILE</code> | <code>H5F_OBJ_DATASET</code> | <code>H5F_OBJ_GROUP</code> | <code>H5F_OBJ_DATATYPE</code> | <code>H5F_OBJ_ATTR</code> </li> </ul> </dd></dl> <dl compact><dt><b></b></dt><dd>Multiple object types can be combined with the logical OR operator (|). </dd></dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getObjCount" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ssize_t H5::H5File::getObjCount </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> This is an overloaded member function, provided for convenience. It takes no parameter and returns the object count of all object types. <p> <dl compact><dt><b>Returns:</b></dt><dd>Number of opened object IDs </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getObjIDs" ref="<API key>" args="(unsigned types, size_t max_objs, hid_t *oid_list) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::getObjIDs </td> <td>(</td> <td class="paramtype">unsigned&nbsp;</td> <td class="paramname"> <em>types</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">size_t&nbsp;</td> <td class="paramname"> <em>max_objs</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">hid_t *&nbsp;</td> <td class="paramname"> <em>oid_list</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Retrieves a list of opened object IDs (files, datasets, groups and datatypes) in the same file. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>types</em>&nbsp;</td><td>- Type of object to retrieve the count </td></tr> <tr><td valign="top"></td><td valign="top"><em>max_objs</em>&nbsp;</td><td>- Maximum number of object identifiers to place into obj_id_list. </td></tr> <tr><td valign="top"></td><td valign="top"><em>oid_list</em>&nbsp;</td><td>- List of open object identifiers </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>The valid values for <em>types</em> include: <ul> <li><code>H5F_OBJ_FILE</code> - Files only </li> <li><code>H5F_OBJ_DATASET</code> - Datasets only </li> <li><code>H5F_OBJ_GROUP</code> - Groups only </li> <li><code>H5F_OBJ_DATATYPE</code> - Named datatypes only </li> <li><code>H5F_OBJ_ATTR</code> - Attributes only </li> <li><code>H5F_OBJ_ALL</code> - All of the above, i.e., <code>H5F_OBJ_FILE</code> | <code>H5F_OBJ_DATASET</code> | <code>H5F_OBJ_GROUP</code> | <code>H5F_OBJ_DATATYPE</code> | <code>H5F_OBJ_ATTR</code> </li> </ul> </dd></dl> <dl compact><dt><b></b></dt><dd>Multiple object types can be combined with the logical OR operator (|). </dd></dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getRefObjType" ref="<API key>" args="(void *ref, H5R_type_t ref_type=H5R_OBJECT) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5G_obj_t H5::H5File::getRefObjType </td> <td>(</td> <td class="paramtype">void *&nbsp;</td> <td class="paramname"> <em>ref</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">H5R_type_t&nbsp;</td> <td class="paramname"> <em>ref_type</em> = <code>H5R_OBJECT</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Retrieves the type of object that an object reference points to. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>ref</em>&nbsp;</td><td>- IN: Reference to query </td></tr> <tr><td valign="top"></td><td valign="top"><em>ref_type</em>&nbsp;</td><td>- IN: Type of reference, valid values are: <ul> <li><code>H5R_OBJECT</code> is an object reference. </li> <li><code>H5R_DATASET_REGION</code> is a dataset region reference. </li> </ul> </td></tr> </table> </dl> <dl compact><dt><b>Returns:</b></dt><dd>Object type, which can be one of the following: <ul> <li><code>H5G_LINK</code> - Object is a symbolic link. </li> <li><code>H5G_GROUP</code> - Object is a group. </li> <li><code>H5G_DATASET</code> - Object is a dataset. </li> <li><code>H5G_TYPE</code> - Object is a named datatype </li> </ul> </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getObjType" ref="<API key>" args="(void *ref, H5R_type_t ref_type=H5R_OBJECT) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">H5G_obj_t H5::H5File::getObjType </td> <td>(</td> <td class="paramtype">void *&nbsp;</td> <td class="paramname"> <em>ref</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">H5R_type_t&nbsp;</td> <td class="paramname"> <em>ref_type</em> = <code>H5R_OBJECT</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> This function was misnamed and will be deprecated in favor of <a class="el" href="classH5_1_1H5File.html#<API key>">H5File::getRefObjType</a>; please use getRefObjType instead. <p> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getRegion" ref="<API key>" args="(void *ref, H5R_type_t ref_type=H5R_DATASET_REGION) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="<API key>.html">DataSpace</a> H5::H5File::getRegion </td> <td>(</td> <td class="paramtype">void *&nbsp;</td> <td class="paramname"> <em>ref</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">H5R_type_t&nbsp;</td> <td class="paramname"> <em>ref_type</em> = <code>H5R_DATASET_REGION</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Retrieves a dataspace with the region pointed to selected. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>ref</em>&nbsp;</td><td>- IN: Reference to get region of </td></tr> <tr><td valign="top"></td><td valign="top"><em>ref_type</em>&nbsp;</td><td>- IN: Type of reference to get region of - default </td></tr> </table> </dl> <dl compact><dt><b>Returns:</b></dt><dd><a class="el" href="<API key>.html">DataSpace</a> instance </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getVFDHandle" ref="<API key>" args="(FileAccPropList &amp;fapl, void **file_handle) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::getVFDHandle </td> <td>(</td> <td class="paramtype"><a class="el" href="<API key>.html">FileAccPropList</a> &amp;&nbsp;</td> <td class="paramname"> <em>fapl</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">void **&nbsp;</td> <td class="paramname"> <em>file_handle</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Returns the pointer to the file handle of the low-level file driver. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>fapl</em>&nbsp;</td><td>- File access property list </td></tr> <tr><td valign="top"></td><td valign="top"><em>file_handle</em>&nbsp;</td><td>- Pointer to the file handle being used by the low-level virtual file driver </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>For the <code>FAMILY</code> or <code>MULTI</code> drivers, <em>fapl</em> should be defined through the property list functions: <code><a class="el" href="<API key>.html#<API key>">FileAccPropList::setFamilyOffset</a></code> for the <code>FAMILY</code> driver and <code><a class="el" href="<API key>.html#<API key>">FileAccPropList::setMultiType</a></code> for the <code>MULTI</code> driver.</dd></dl> The obtained file handle is dynamic and is valid only while the file remains open; it will be invalid if the file is closed and reopened or opened during a subsequent session. </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getVFDHandle" ref="<API key>" args="(void **file_handle) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::getVFDHandle </td> <td>(</td> <td class="paramtype">void **&nbsp;</td> <td class="paramname"> <em>file_handle</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> This is an overloaded member function, provided for convenience. It differs from the above function only in what arguments it accepts. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>file_handle</em>&nbsp;</td><td>- Pointer to the file handle being used by the low-level virtual file driver </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::isHdf5" ref="<API key>" args="(const char *name)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool H5::H5File::isHdf5 </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>name</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"><code> [static]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Determines whether a file in HDF5 format. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the file </td></tr> </table> </dl> <dl compact><dt><b>Returns:</b></dt><dd>true if the file is in HDF5 format, and false, otherwise </dd></dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::isHdf5" ref="<API key>" args="(const H5std_string &amp;name)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool H5::H5File::isHdf5 </td> <td>(</td> <td class="paramtype">const H5std_string &amp;&nbsp;</td> <td class="paramname"> <em>name</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"><code> [static]</code></td> </tr> </table> </div> <div class="memdoc"> <p> This is an overloaded member function, provided for convenience. It takes an <code>H5std_string</code> for <em>name</em>. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the file - <code>H5std_string</code> </td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::reOpen" ref="<API key>" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::reOpen </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> Reopens this file. <p> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::reopen" ref="<API key>" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::reopen </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"></td> </tr> </table> </div> <div class="memdoc"> <p> Reopens this file. <p> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd>This function will be replaced by the above function <code>reOpen</code> in future releases. </dd></dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::reference" ref="<API key>" args="(void *ref, const char *name, const DataSpace &amp;dataspace, H5R_type_t ref_type=H5R_DATASET_REGION) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::reference </td> <td>(</td> <td class="paramtype">void *&nbsp;</td> <td class="paramname"> <em>ref</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="<API key>.html">DataSpace</a> &amp;&nbsp;</td> <td class="paramname"> <em>dataspace</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">H5R_type_t&nbsp;</td> <td class="paramname"> <em>ref_type</em> = <code>H5R_DATASET_REGION</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> Creates a reference to an HDF5 object or a dataset region. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>ref</em>&nbsp;</td><td>- IN: Reference pointer </td></tr> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the object to be referenced </td></tr> <tr><td valign="top"></td><td valign="top"><em>dataspace</em>&nbsp;</td><td>- IN: Dataspace with selection </td></tr> <tr><td valign="top"></td><td valign="top"><em>ref_type</em>&nbsp;</td><td>- IN: Type of reference to query, valid values are: <ul> <li><code>H5R_OBJECT</code> is an object reference. </li> <li><code>H5R_DATASET_REGION</code> is a dataset region reference. - this is the default </li> </ul> </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::<API key></a></em>&nbsp;</td><td></td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::reference" ref="<API key>" args="(void *ref, const char *name) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::reference </td> <td>(</td> <td class="paramtype">void *&nbsp;</td> <td class="paramname"> <em>ref</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>name</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> This is an overloaded function, provided for your convenience. It differs from the above function in that it only creates a reference to an HDF5 object, not to a dataset region. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>ref</em>&nbsp;</td><td>- IN: Reference pointer </td></tr> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the object to be referenced - <code>char</code> pointer </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::<API key></a></em>&nbsp;</td><td></td></tr> </table> </dl> <dl compact><dt><b>Description</b></dt><dd></dd></dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::reference" ref="<API key>" args="(void *ref, const H5std_string &amp;name) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::reference </td> <td>(</td> <td class="paramtype">void *&nbsp;</td> <td class="paramname"> <em>ref</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const H5std_string &amp;&nbsp;</td> <td class="paramname"> <em>name</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const</td> </tr> </table> </div> <div class="memdoc"> <p> This is an overloaded function, provided for your convenience. It differs from the above function in that it takes an <code>H5std_string</code> for the object's name. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>ref</em>&nbsp;</td><td>- IN: Reference pointer </td></tr> <tr><td valign="top"></td><td valign="top"><em>name</em>&nbsp;</td><td>- IN: Name of the object to be referenced - <code>H5std_string</code> </td></tr> </table> </dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::fromClass" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual H5std_string H5::H5File::fromClass </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [inline, virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::throwException" ref="<API key>" args="(const H5std_string &amp;func_name, const H5std_string &amp;msg) const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::throwException </td> <td>(</td> <td class="paramtype">const H5std_string &amp;&nbsp;</td> <td class="paramname"> <em>func_name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const H5std_string &amp;&nbsp;</td> <td class="paramname"> <em>msg</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td width="100%"> const<code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Throws file exception - initially implemented for <a class="el" href="classH5_1_1CommonFG.html">CommonFG</a>. <p> <dl compact><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>func_name</em>&nbsp;</td><td>- Name of the function where failure occurs </td></tr> <tr><td valign="top"></td><td valign="top"><em>msg</em>&nbsp;</td><td>- Message describing the failure </td></tr> </table> </dl> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::FileIException</a></em>&nbsp;</td><td></td></tr> </table> </dl> <p> Implements <a class="el" href="classH5_1_1CommonFG.html#<API key>">H5::CommonFG</a>. </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getLocId" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">hid_t H5::H5File::getLocId </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::getId" ref="<API key>" args="() const " --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">hid_t H5::H5File::getId </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> <p> Implements <a class="el" href="<API key>.html#<API key>">H5::IdComponent</a>.<dl compact><dt><b>Examples: </b></dt><dd> <a class="el" href="<API key>.html#a79">h5group.cpp</a>.</dl> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="H5::H5File::p_setId" ref="<API key>" args="(const hid_t new_id)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void H5::H5File::p_setId </td> <td>(</td> <td class="paramtype">const hid_t&nbsp;</td> <td class="paramname"> <em>new_id</em> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"><code> [protected, virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Sets the identifier of this HDF5 file to a new value. <p> <dl compact><dt><b>Exceptions:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em><a class="el" href="<API key>.html">H5::<API key></a></em>&nbsp;</td><td>when the attempt to close the HDF5 object fails </td></tr> </table> </dl> </div> </div><p> <hr size="1"><address style="align: right;"><small>Generated on Wed Nov 4 14:13:07 2009 by&nbsp; <a href="http: <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.7 </small></address> </body> </html>
package org.jevis.commons.driver; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.SftpException; import java.io.IOException; import java.security.SecureRandom; import java.security.Security; import java.security.cert.<API key>; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.lang3.StringUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.jevis.api.JEVisException; import org.jevis.api.JEVisObject; import org.jevis.api.JEVisSample; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.<API key>; /** * * @author Broder */ public class DataSourceHelper { public static void test() { } static public void <API key>() throws Exception { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws <API key> { return; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws <API key> { return; } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.<API key>(sc.getSocketFactory()); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) { System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'."); } return true; } }; HttpsURLConnection.<API key>(hv); } public static List<String> <API key>(FTPClient fc, DateTime lastReadout, String filePath) { filePath = filePath.replace("\\", "/"); String[] pathStream = getPathTokens(filePath); String startPath = ""; if (filePath.startsWith("/")) { startPath = "/"; } List<String> folderPathes = getMatchingPathes(startPath, pathStream, new ArrayList<String>(), fc, lastReadout, new <API key>()); // System.out.println("foldersize,"+folderPathes.size()); List<String> fileNames = new ArrayList<String>(); if (folderPathes.isEmpty()) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Cant find suitable folder on the device"); return fileNames; } // String fileName = null; String fileNameScheme = pathStream[pathStream.length - 1]; String currentfolder = null; try { for (String folder : folderPathes) { // fc.<API key>(folder); // System.out.println("currentFolder,"+folder); currentfolder = folder; // for (FTPFile file : fc.listFiles(folder)) { // System.out.println(file.getName()); fc.<API key>(folder); for (FTPFile file : fc.listFiles()) { // org.apache.log4j.Logger.getLogger(Launcher.class.getName()).log(org.apache.log4j.Level.ALL, "CurrentFileName: " + fileName); // fileName = removeFoler(fileName, folder); if (file.getTimestamp().compareTo(lastReadout.toGregorianCalendar()) < 0) { continue; } boolean match = false; System.out.println(file.getName()); if (DataSourceHelper.containsTokens(fileNameScheme)) { boolean matchDate = matchDateString(file.getName(), fileNameScheme); DateTime folderTime = getFileTime(folder + file.getName(), pathStream); boolean isLater = folderTime.isAfter(lastReadout); if (matchDate && isLater) { match = true; } } else { Pattern p = Pattern.compile(fileNameScheme); Matcher m = p.matcher(file.getName()); match = m.matches(); } if (match) { fileNames.add(folder + file.getName()); } } } } catch (IOException ex) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, ex.getMessage()); } catch (Exception ex) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Error while searching a matching file"); org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Folder: " + currentfolder); org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "FileName: " + fileNameScheme); org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, ex.getMessage()); } if (folderPathes.isEmpty()) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Cant find suitable files on the device"); } // System.out.println("filenamesize"+fileNames.size()); return fileNames; } private static DateTime getFileTime(String name, String[] pathStream) { String compactDateString = <API key>(name, pathStream); String <API key> = <API key>(name, pathStream); DateTimeFormatter dtf = DateTimeFormat.forPattern(<API key>); DateTime parseDateTime = dtf.parseDateTime(compactDateString); return parseDateTime; } private static String <API key>(String name, String[] pathStream) { String[] realTokens = StringUtils.split(name, "/"); String compactDateString = null; for (int i = 0; i < realTokens.length; i++) { String currentString = pathStream[i]; if (currentString.contains("${D:")) { int startindex = currentString.indexOf("${D:"); int endindex = currentString.indexOf("}"); if (compactDateString == null) { compactDateString = realTokens[i].substring(startindex, endindex - 4); } else { compactDateString += " " + realTokens[i].substring(startindex, endindex - 4); } } } return compactDateString; } private static String <API key>(String name, String[] pathStream) { String[] realTokens = StringUtils.split(name, "/"); String compactDateString = null; //contains more than one date token? for (int i = 0; i < realTokens.length; i++) { String currentString = pathStream[i]; if (currentString.contains("${")) { int startindex = currentString.indexOf("${"); int endindex = currentString.indexOf("}"); if (compactDateString == null) { compactDateString = currentString.substring(startindex + 4, endindex); } else { compactDateString += " " + currentString.substring(startindex + 4, endindex); } } } return compactDateString; } private static String removeFoler(String fileName, String folder) { if (fileName.startsWith(folder)) { return fileName.substring(folder.length(), fileName.length()); } return fileName; } private static boolean matchDateString(String currentFolder, String nextToken) { String[] substringsBetween = StringUtils.substringsBetween(nextToken, "${D:", "}"); for (int i = 0; i < substringsBetween.length; i++) { nextToken = nextToken.replace("${D:" + substringsBetween[i] + "}", ".{" + substringsBetween[i].length() + "}"); } Pattern p = Pattern.compile(nextToken); Matcher m = p.matcher(currentFolder); return m.matches(); } private static List<String> getMatchingPathes(String path, String[] pathStream, ArrayList<String> arrayList, FTPClient fc, DateTime lastReadout, <API key> dtfbuilder) { int nextTokenPos = getPathTokens(path).length; if (nextTokenPos == pathStream.length - 1) { arrayList.add(path); return arrayList; } String nextToken = pathStream[nextTokenPos]; String nextFolder = null; try { if (containsDateToken(nextToken)) { FTPFile[] listDirectories = fc.listFiles(path); // DateTimeFormatter ftmTemp = getDateFormatter(nextToken); for (FTPFile folder : listDirectories) { if (!matchDateString(folder.getName(), nextToken)) { continue; } // System.out.println("listdir," + folder.getName()); // if (containsDate(folder.getName(), ftmTemp)) { DateTime folderTime = getFolderTime(path + folder.getName() + "/", pathStream); if (folderTime.isAfter(lastReadout)) { nextFolder = folder.getName(); // System.out.println("dateFolder," + nextFolder); getMatchingPathes(path + nextFolder + "/", pathStream, arrayList, fc, lastReadout, dtfbuilder); } } } else { nextFolder = nextToken; // System.out.println("normalFolder," + nextFolder); getMatchingPathes(path + nextFolder + "/", pathStream, arrayList, fc, lastReadout, dtfbuilder); } } catch (IOException ex) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, ex.getMessage()); } return arrayList; } private static boolean containsDateToken(String string) { if (string.contains("${D:")) { return true; } else { return false; } } public static String[] getPathTokens(String filePath) { // List<String> tokens = new ArrayList<String>(); // filePath.substring("\\$\\{","\\}"); String[] tokens = StringUtils.split(filePath, "/"); // String[] tokens = filePath.trim().split("\\%"); for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } return tokens; } public static String replaceDateFrom(String template, DateTime date) { DateTimeFormatter dtf = getFromDateFormat(template); int startindex = template.indexOf("${DF:"); int endindex = template.indexOf("}") + 1; String first = template.substring(0, startindex); String last = template.substring(endindex, template.length()); return first + date.toString(dtf) + last; } public static String replaceDateUntil(String template, DateTime date) { DateTimeFormatter dtf = getUntilDateFormat(template); int startindex = template.indexOf("${DU:"); int endindex = template.indexOf("}") + 1; String first = template.substring(0, startindex); String last = template.substring(endindex, template.length()); return first + date.toString(dtf) + last; } public static String <API key>(DateTime from, DateTime until, String filePath) { // String replacedString = null; while (filePath.indexOf("${DF:") != -1 || filePath.indexOf("${DF:") != -1) { int fromstartindex = filePath.indexOf("${DF:"); int untilstartindex = filePath.indexOf("${DU:"); if (fromstartindex < untilstartindex) { filePath = replaceDateFrom(filePath, from); filePath = replaceDateUntil(filePath, until); } else { filePath = replaceDateUntil(filePath, until); filePath = replaceDateFrom(filePath, from); } } return filePath; } private static DateTime getFolderTime(String name, String[] pathStream) { String compactDateString = <API key>(name, pathStream); String <API key> = <API key>(name, pathStream); DateTimeFormatter dtf = DateTimeFormat.forPattern(<API key>); DateTime parseDateTime = dtf.parseDateTime(compactDateString); if (parseDateTime.year().get() == parseDateTime.year().getMinimumValue()) { parseDateTime = parseDateTime.year().withMaximumValue(); } if (parseDateTime.monthOfYear().get() == parseDateTime.monthOfYear().getMinimumValue()) { parseDateTime = parseDateTime.monthOfYear().withMaximumValue(); } if (parseDateTime.dayOfMonth().get() == parseDateTime.dayOfMonth().getMinimumValue()) { parseDateTime = parseDateTime.dayOfMonth().withMaximumValue(); } if (parseDateTime.hourOfDay().get() == parseDateTime.hourOfDay().getMinimumValue()) { parseDateTime = parseDateTime.hourOfDay().withMaximumValue(); } if (parseDateTime.minuteOfHour().get() == parseDateTime.minuteOfHour().getMinimumValue()) { parseDateTime = parseDateTime.minuteOfHour().withMaximumValue(); } if (parseDateTime.secondOfMinute().get() == parseDateTime.secondOfMinute().getMinimumValue()) { parseDateTime = parseDateTime.secondOfMinute().withMaximumValue(); } if (parseDateTime.millisOfSecond().get() == parseDateTime.millisOfSecond().getMinimumValue()) { parseDateTime = parseDateTime.millisOfSecond().withMaximumValue(); } return parseDateTime; } public static DateTimeFormatter getFromDateFormat(String stringWithDate) { int startindex = stringWithDate.indexOf("${DF:"); int endindex = stringWithDate.indexOf("}"); String date = stringWithDate.substring(startindex + 5, endindex); DateTimeFormatter dtf = DateTimeFormat.forPattern(date); return dtf; } public static DateTimeFormatter getUntilDateFormat(String stringWithDate) { int startindex = stringWithDate.indexOf("${DU:"); int endindex = stringWithDate.indexOf("}"); String date = stringWithDate.substring(startindex + 5, endindex); DateTimeFormatter dtf = DateTimeFormat.forPattern(date); return dtf; } public static Boolean containsTokens(String path) { if (path.contains("${")) { return true; } else { return false; } } public static List<String> <API key>(ChannelSftp _channel, DateTime lastReadout, String filePath) { filePath = filePath.replace("\\", "/"); String[] pathStream = getPathTokens(filePath); String startPath = ""; if (filePath.startsWith("/")) { startPath = "/"; } List<String> folderPathes = <API key>(startPath, pathStream, new ArrayList<String>(), _channel, lastReadout, new <API key>()); // System.out.println("foldersize,"+folderPathes.size()); List<String> fileNames = new ArrayList<String>(); if (folderPathes.isEmpty()) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Cant find suitable folder on the device"); return fileNames; } if (folderPathes.isEmpty()) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Cant find suitable folder on the device"); return fileNames; } String fileNameScheme = pathStream[pathStream.length - 1]; String currentfolder = null; try { for (String folder : folderPathes) { // fc.<API key>(folder); // System.out.println("currentFolder,"+folder); currentfolder = folder; // for (FTPFile file : fc.listFiles(folder)) { // System.out.println(file.getName()); // Vector ls = _channel.ls(folder); for (Object fileName : _channel.ls(folder)) { LsEntry currentFile = (LsEntry) fileName; String currentFileName = currentFile.getFilename(); currentFileName = removeFoler(currentFileName, folder); boolean match = false; System.out.println(currentFileName); if (DataSourceHelper.containsTokens(fileNameScheme)) { boolean matchDate = matchDateString(currentFileName, fileNameScheme); DateTime folderTime = getFileTime(folder + currentFileName, pathStream); boolean isLater = folderTime.isAfter(lastReadout); if (matchDate && isLater) { match = true; } } else { Pattern p = Pattern.compile(fileNameScheme); Matcher m = p.matcher(currentFileName); match = m.matches(); } if (match) { fileNames.add(folder + currentFileName); } } } } catch (Exception ex) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Error while searching a matching file"); org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Folder: " + currentfolder); org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "FileName: " + fileNameScheme); org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, ex.getMessage()); } if (folderPathes.isEmpty()) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Cant find suitable files on the device"); } // System.out.println("filenamesize"+fileNames.size()); return fileNames; } private static List<String> <API key>(String path, String[] pathStream, ArrayList<String> arrayList, ChannelSftp fc, DateTime lastReadout, <API key> dtfbuilder) { int nextTokenPos = getPathTokens(path).length; if (nextTokenPos == pathStream.length - 1) { arrayList.add(path); return arrayList; } String nextToken = pathStream[nextTokenPos]; String nextFolder = null; try { if (containsDateToken(nextToken)) { Vector listDirectories = fc.ls(path); for (Object folder : listDirectories) { LsEntry currentFolder = (LsEntry) folder; if (!matchDateString(currentFolder.getFilename(), nextToken)) { continue; } DateTime folderTime = getFolderTime(path + currentFolder.getFilename() + "/", pathStream); if (folderTime.isAfter(lastReadout)) { nextFolder = currentFolder.getFilename(); <API key>(path + nextFolder + "/", pathStream, arrayList, fc, lastReadout, dtfbuilder); } } } else { nextFolder = nextToken; <API key>(path + nextFolder + "/", pathStream, arrayList, fc, lastReadout, dtfbuilder); } } catch (SftpException ex) { org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR, "Cant find suitable files on the device"); } return arrayList; } }
var structRREQ = [ [ "RREQ", "structRREQ.html#<API key>", null ], [ "RREQ", "structRREQ.html#<API key>", null ], [ "copy", "structRREQ.html#<API key>", null ], [ "detailedInfo", "structRREQ.html#<API key>", null ], [ "dup", "structRREQ.html#<API key>", null ], [ "getCost", "structRREQ.html#<API key>", null ], [ "getD", "structRREQ.html#<API key>", null ], [ "getDest_addr", "structRREQ.html#<API key>", null ], [ "getDest_seqno", "structRREQ.html#<API key>", null ], [ "getG", "structRREQ.html#<API key>", null ], [ "getHcnt", "structRREQ.html#<API key>", null ], [ "getHopfix", "structRREQ.html#<API key>", null ], [ "getJ", "structRREQ.html#<API key>", null ], [ "getOrig_addr", "structRREQ.html#<API key>", null ], [ "getOrig_seqno", "structRREQ.html#<API key>", null ], [ "getR", "structRREQ.html#<API key>", null ], [ "getRes1", "structRREQ.html#<API key>", null ], [ "getRes2", "structRREQ.html#<API key>", null ], [ "getRreq_id", "structRREQ.html#<API key>", null ], [ "operator=", "structRREQ.html#<API key>", null ], [ "cost", "structRREQ.html#<API key>", null ], [ "d", "structRREQ.html#<API key>", null ], [ "dest_addr", "structRREQ.html#<API key>", null ], [ "dest_addr", "structRREQ.html#<API key>", null ], [ "dest_seqno", "structRREQ.html#<API key>", null ], [ "g", "structRREQ.html#<API key>", null ], [ "hcnt", "structRREQ.html#<API key>", null ], [ "hopfix", "structRREQ.html#<API key>", null ], [ "j", "structRREQ.html#<API key>", null ], [ "orig_addr", "structRREQ.html#<API key>", null ], [ "orig_addr", "structRREQ.html#<API key>", null ], [ "orig_seqno", "structRREQ.html#<API key>", null ], [ "r", "structRREQ.html#<API key>", null ], [ "res1", "structRREQ.html#<API key>", null ], [ "res2", "structRREQ.html#<API key>", null ], [ "rreq_id", "structRREQ.html#<API key>", null ], [ "type", "structRREQ.html#<API key>", null ] ];
function send_msg(chat_id, text, use_markdown, reply_to_message_id) local url = send_api .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. url.escape(text) if reply_to_message_id then url = url .. '&reply_to_message_id=' .. reply_to_message_id end if use_markdown then url = url .. '&parse_mode=Markdown' end return send_req(url) end function send_document(chat_id, name) local send = send_api.."/sendDocument" local curl_command = 'curl -s "'..send..'" -F "chat_id='..chat_id..'" -F "document=@'..name..'"' return io.popen(curl_command):read("*all") end function forwardMessage(chat_id, from_chat_id, message_id) local url = send_api .. '/forwardMessage?chat_id=' .. chat_id .. '&from_chat_id=' .. from_chat_id .. '&message_id=' .. message_id return send_req(url) end function send_key(chat_id, text, keyboard, inline, resize, mark) local response = {} response.keyboard = keyboard response.inline_keyboard = inline response.resize_keyboard = resize response.one_time_keyboard = false response.selective = false local responseString = JSON.encode(response) if mark then sended = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&<API key>=true&reply_markup="..url.escape(responseString) else sended = send_api.."/sendMessage?chat_id="..chat_id.."&text="..url.escape(text).."&parse_mode=Markdown&<API key>=true&reply_markup="..url.escape(responseString) end return send_req(sended) end function edit_key( chat_id, message_id, text, keyboard, inline, resize, mark) local response = {} response.keyboard = keyboard response.inline_keyboard = inline response.resize_keyboard = resize response.one_time_keyboard = false response.selective = false local responseString = JSON.encode(response) local Rep = send_api.. '/editMessageText?&chat_id='..chat_id..'&message_id='..message_id..'&text=' .. url.escape(text) Rep=Rep .. '&parse_mode=Markdown' if keyboard or inline then Rep=Rep..'&reply_markup='..url.escape(responseString) end return send_req(Rep) end function alert(callback_query_id, text, show_alert) local Rep = send_api .. '/answerCallbackQuery?callback_query_id=' .. callback_query_id .. '&text=' .. url.escape(text) if show_alert then Rep = Rep..'&show_alert=true' end return send_req(Rep) end function string:input() if not self:find(' ') then return false end return self:sub(self:find(' ')+1) end function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end if sudo_id == msg.from.id then var = true end return var end function is_sudo1(sudoo) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == sudoo then var = true end end if sudo_id == sudoo then var = true end return var end function check_markdown(text) --markdown escape ( when you need to escape markdown , use it like : check_markdown('your text') str = text if str:match('_') then output = str:gsub('_',[[\_]]) elseif str:match('*') then output = str:gsub('*','\\*') elseif str:match('`') then output = str:gsub('`','\\`') else output = str end return output end function getChatMember(chat_id, user_id) local url = send_api .. '/getChatMember?chat_id=' .. chat_id .. '&user_id=' .. user_id return send_req(url) end function LeaveGroup(chat_id) local url = send_api .. '/leaveChat?chat_id=' .. chat_id return send_req(url) end
#!/usr/bin/perl #./scripts/<API key>.pl structured 13 # Computes and plots structure distance among alien benchmark sets and versus Rfam # 1. Computes the normalized distance changes over iterations # 3. Computes the average normalized distance changes over iterations # 2. Computes the distance between updated structure and normal structure over iterations # 4. Computes the average distance between updated structure and normal structure over iterations # 5. Compute the normalized distance between iteration and Rfam consensus # 6. Compute the average normalized distance between iteration and Rfam consensus use warnings; use strict; use diagnostics; use Data::Dumper; use Cwd; $|=1; #decideds which benchmark data to process my $type = $ARGV[0]; #result iteration my $currentresultnumber = $ARGV[1]; #contains all RNAlien result folders for sRNA tagged families my $<API key>; #contains all Rfam Families names by family name with extension .cm my $rfammodel_basename; #contains all full seed alignment sequences as RfamID .fa fasta files my $rfamfasta_basename; #contains seed alignments as RfamID .fa fasta files my $<API key>; my $RNAFamilyIdFile; my $familyNumber; my $resulttempdir; if($type eq "structured"){ $<API key>="/scr/coridan/egg/<API key>" . "$currentresultnumber" . "/"; $<API key> = "/scr/coridan/egg/<API key>/"; $rfamfasta_basename = "/scr/coridan/egg/rfamfamilyseedfasta/"; $RNAFamilyIdFile = "/scr/coridan/egg/<API key>"; $familyNumber = 56; $resulttempdir = "/scr/coridan/egg/temp/<API key>". "$currentresultnumber" . "/"; }else{ #sRNA $<API key>="/scr/kronos/egg/<API key>" . "$currentresultnumber" . "/"; $rfammodel_basename = "/scr/kronos/egg/AlienTest/sRNAFamilies/all_models/"; $RNAFamilyIdFile = "/scr/kronos/egg/<API key>.csv"; $familyNumber = 374; $resulttempdir = "/scr/kronos/egg/temp/<API key>" . "$currentresultnumber" . "/"; } #Distance comparison between first stockholms of constructions with and without structureupdate #<API key>($familyNumber,$<API key>,$rfammodel_basename,$rfamfasta_basename,$RNAFamilyIdFile,$resulttempdir,"/scratch/egg/"); unless(-d "/scr/kronos/egg/iterationdistance$currentresultnumber/"){ mkdir "/scr/kronos/egg/iterationdistance$currentresultnumber/"; } <API key>($familyNumber,$<API key>,$<API key>,$rfamfasta_basename,$RNAFamilyIdFile,$resulttempdir,"/scr/kronos/egg/iterationdistance$currentresultnumber/"); #<API key>($familyNumber,$<API key>,$rfammodel_basename,$rfamfasta_basename,$RNAFamilyIdFile,$resulttempdir,"/scr/kronos/egg/iterationdistance$currentresultnumber/"); sub <API key>{ #retrieve common sequence identifier #compare stockholmstructre and parse result back my $familyNumber = shift; my $<API key> = shift; my $<API key> = shift; my $rfamfasta_basename = shift; my $RNAFamilyIdFile = shift; my $resulttempdir = shift; my $resultfolderpath = shift; my $outputfilePath= $resultfolderpath . "<API key>.dist"; my $output; for(my $counter=1; $counter <= $familyNumber; $counter++){ my $<API key>= $<API key>.$counter."/"; if(-e $<API key>.$counter."/done"){ #print "$<API key>$counter\n"; my $fstStockholmPath = "$<API key>/$counter.stockholm"; my $sndStockholmPath = "$<API key>"."$counter"."/result.stockholm"; my $inputFastaPath = "$<API key>"."$counter"."/result.fa"; if(-e $inputFastaPath){ my @fastacontent; open(my $fastafh, "<", $inputFastaPath) or die "Failed to open file: $!\n"; while(<$fastafh>) { chomp; push @fastacontent, $_; } close $fastafh; my $fasta_identifier = $fastacontent[0]; $fasta_identifier =~ s/> #$fasta_identifier =~ s/\\K.+$//; if(-e $fstStockholmPath){ $output = $output . `~egg/current/Projects/Haskell/StockholmTools/dist/build/<API key>/<API key> -i $fasta_identifier -a $fstStockholmPath -r $sndStockholmPath -d P -o $resultfolderpath`; }else{ $output = $output . "no stockholm found\n"; } } }else{ $output = $output . "no inputfasta found\n"; } } open(my $outputfh, ">", $outputfilePath) or die "Failed to open file: $!\n"; print $outputfh $output; close $outputfh; return 1; } sub <API key>{ #retrieve common sequence identifier #compare stockholmstructre and parse result back my $familyNumber = shift; my $<API key> = shift; my $rfammodel_basename = shift; my $rfamfasta_basename = shift; my $RNAFamilyIdFile = shift; my $resulttempdir = shift; my $resultfolderpath = shift; my $outputfilePath= $resultfolderpath . "<API key>.dist"; my $output; for(my $counter=1; $counter <= $familyNumber; $counter++){ my $<API key>= $<API key>.$counter."/"; if(-e $<API key>.$counter."/done"){ #print "$<API key>$counter\n"; my $fstStockholmPath = findStockholm("/scratch/egg/<API key>/$counter/"); my $sndStockholmPath = findStockholm("/scratch/egg/<API key>/$counter/"); my $inputFastaPath = findInputFasta($<API key>); if(-e $inputFastaPath){ my @fastacontent; open(my $fastafh, "<", $inputFastaPath) or die "Failed to open file: $!\n"; while(<$fastafh>) { chomp; push @fastacontent, $_; } close $fastafh; my $fasta_identifier = $fastacontent[0]; $fasta_identifier =~ s/> $fasta_identifier =~ s/\\K.+$ if(-e $fstStockholmPath){ $output = $output . `~egg/current/Projects/Haskell/StockholmTools/dist/build/<API key>/<API key> -i $fasta_identifier -a $fstStockholmPath -r $sndStockholmPath -o /scratch/egg/temp/`; }else{ $output = $output . "no stockholm found\n"; } } }else{ $output = $output . "no inputfasta found\n"; } } open(my $outputfh, ">", $outputfilePath) or die "Failed to open file: $!\n"; print $outputfh $output; close $outputfh; return 1; } sub <API key>{ #retrieve common sequence identifier #compare stockholmstructre and parse result back my $familyNumber = shift; my $<API key> = shift; my $rfammodel_basename = shift; my $rfamfasta_basename = shift; my $RNAFamilyIdFile = shift; my $resulttempdir = shift; my $resultfolderpath = shift; for(my $counter=1; $counter <= $familyNumber; $counter++){ my $output = ""; my $<API key>= $<API key>.$counter."/"; if(-e $<API key> . $counter."/done"){ #print "$<API key>$counter\n"; my $<API key> = findStockholm("/scratch/egg/<API key>/$counter/"); my $inputFastaPath = findInputFasta($<API key>); my $iterationNumber = findIterationNumber($<API key>); if(-e $inputFastaPath){ my @fastacontent; open(my $fastafh, "<", $inputFastaPath) or die "Failed to open file: $!\n"; while(<$fastafh>) { chomp; push @fastacontent, $_; } close $fastafh; my $fasta_identifier = $fastacontent[0]; $fasta_identifier =~ s/> $fasta_identifier =~ s/\\K.+$ if(-e $<API key>){ for(my $iteration = 0; $iteration <= $iterationNumber; $iteration++){ my $<API key> = $<API key> . $iteration . "/model.stockholm"; if(-e $<API key>){ $output = $output . "$iteration\t" . `~egg/current/Projects/Haskell/StockholmTools/dist/build/<API key>/<API key> -i $fasta_identifier -a $<API key> -r $<API key> -o /scratch/egg/temp/`; }else{ #print "$<API key>\n"; $output = $output . "$iteration\tNA\n" } } }else{ $output = $output . "no stockholm found\n"; } } }else{ $output = $output . "no inputfasta found\n"; } my $outputfilePath = $resultfolderpath . $counter . "_iterationstructure.dist"; open(my $outputfh, ">", $outputfilePath) or die "Failed to open file: $!\n"; print $outputfh $output; close $outputfh; } return 1; } sub findIterationNumber{ my $<API key> = shift; my $continue = 1; my $iteration = 0; while($continue){ my $currentpath = $<API key>."/".$iteration; #print $currentfastapath; unless(-d $currentpath){ $continue = 0; return $iteration; }else{ $iteration++; } if($iteration>50){ $continue = 0; } } } sub findInputFasta{ my $<API key> = shift; my $continue = 1; my $iteration = 0; while($continue){ my $currentfastapath = $<API key>."/".$iteration."/input.fa"; #print $currentfastapath; if(-e $currentfastapath){ $continue = 0; return $currentfastapath; }else{ $iteration++; } if($iteration>50){ $continue = 0; } } } sub findStockholm{ my $<API key> = shift; my $continue = 1; my $iteration = 0; while($continue){ my $<API key> = $<API key>."/".$iteration."/model.stockholm"; if(-e $<API key>){ $continue = 0; return $<API key>; }else{ $iteration++; } if($iteration>50){ $continue = 0; } } } # sub <API key>{ # #retrieve common sequence identifier # #compare stockholmstructre and parse result back # my $familyNumber = shift; # my $<API key> = shift; # my $rfammodel_basename = shift; # my $rfamfasta_basename = shift; # my $RNAFamilyIdFile = shift; # my $resulttempdir = shift; # my $<API key> = shift; # my $<API key> = shift; # my $outputfilePath = shift; # my $output; # for(my $counter=1; $counter <= $familyNumber; $counter++){ # my $<API key>= $<API key>.$counter."/"; # if(-e $<API key>.$counter."/done"){ # my $alienModelPath = $<API key>."result.cm"; # my $alienFastaPath = $<API key>."result.fa"; # my @rfamModelNameId = split(/\s+/,$RNAfamilies[($counter - 1)]); # my $rfamModelName = $rfamModelNameId[0]; # my $rfamModelId = $rfamModelNameId[1]; # my $rfamModelPath = $rfammodel_basename . $rfamModelId . ".cm"; # my $rfamFastaPath =$rfamfasta_basename . $rfamModelId . ".fa"; # if(! -e $rfamModelPath){ # print "Does not exist: $rfamModelPath "; # if(! -e $rfamFastaPath){ # print "Does not exist: $rfamFastaPath "; # if(! -e $alienModelPath){ # print "Does not exist: $alienModelPath "; # if(! -e $alienFastaPath){ # print "Does not exist: $alienFastaPath"; # $output = $output . `RNAlienStatistics -c 20 -n $rfamModelName -d $rfamModelId -b $counter -i $alienModelPath -r $rfamModelPath -a $alienFastaPath -g $rfamFastaPath -t $rfamThreshold -x $rfamThreshold -o $resulttempdir`; # #~egg/current/Projects/Haskell/StockholmTools/dist/build/<API key>/<API key> -i AB001721.1 -a /scratch/egg/<API key>/1/1/model.stockholm -r /scratch/egg/<API key>/1/9/model.stockholm -o /scratch/egg/temp/ # open(my $outputfh, ">", $outputfilePath) # or die "Failed to open file: $!\n"; # print $outputfh $output; # close $outputfh; # return 1; # sub <API key>{ # #summarize familywise results of <API key> # return 1; # sub <API key>{ # return 1; # sub <API key>{ # return 1; # sub <API key>{ # return 1; # sub <API key>{ # return 1;
\begin{tikzpicture} [very thick, color=black,->] \node (n0) at (0,0) {000}; \node (n1) at (1.2,1) {001}; \node (n2) at (0,1) {010}; \node (n3) at (1.2,2) {011}; \node (n4) at (-1.2,1) {100}; \node (n5) at (0,2) {101}; \node (n6) at (-1.2,2) {110}; \node (n7) at (0,3) {111}; \draw (n0) \draw (n0) \draw (n0) \draw (n1) \draw (n1) \draw (n2) \draw (n2) \draw (n4) \draw (n4) \draw (n7) \draw (n7) \draw (n7) \end{tikzpicture}
package com.autentia.wuija.widget.query; import java.util.ArrayList; import java.util.List; import javax.faces.model.SelectItem; import org.springframework.util.Assert; import com.autentia.wuija.persistence.criteria.Criteria; import com.autentia.wuija.persistence.criteria.Criterion; import com.autentia.wuija.persistence.criteria.EntityCriteria; import com.autentia.wuija.persistence.criteria.SimpleExpression; import com.autentia.wuija.persistence.criteria.MatchMode; import com.autentia.wuija.web.jsf.I18NSelectItemList; import com.autentia.wuija.widget.property.Property; public class AdvancedQuery extends Query { private static final List<SelectItem> <API key> = new I18NSelectItemList(MatchMode.values()); private static final int <API key> = 1; protected final Criteria criteria; private final Criteria originalCriteria; private final Property[] properties; /** Lista de widgets para la entrada de criterios */ private final List<<API key>> <API key> = new ArrayList<<API key>>(); public AdvancedQuery(Property[] properties, Criteria criteria) { try { this.originalCriteria = (Criteria)criteria.clone(); } catch (<API key> e) { final String msg = criteria.getClass().getName() + " or deeper object, doesn't supports clone()"; throw new <API key>(msg, e); } this.criteria = criteria; this.properties = properties; prepareUserInterfaz(); } public void <API key>() { final SimpleExpression simpleExpression = <API key>(); if (simpleExpression == null) { return; } criteria.add(simpleExpression); <API key>(simpleExpression); } private void <API key>(SimpleExpression simpleExpression) { final <API key> <API key> = new <API key>(simpleExpression, properties); <API key>.add(<API key>); } protected SimpleExpression <API key>() { return new SimpleExpression(); } public List<SelectItem> getMatchModes() { return <API key>; } /** * @see JsfWidget#getRendererPath() */ @Override public String getRendererPath() { return RENDERER_PATH + "advancedQuery.jspx"; } public MatchMode <API key>() { return criteria.getMatchMode(); } public List<<API key>> <API key>() { return <API key>; } public boolean <API key>() { return <API key>.size() == <API key>; } @Override protected void prepareUserInterfaz() { <API key>.clear(); final List<Criterion> criterions = criteria.getCriterions(); for (int i = 0; i < criterions.size(); i++) { final Criterion criterion = criterions.get(i); Assert.isInstanceOf(SimpleExpression.class, criterion, "Type " + criterion.getClass().getName() + "not supported."); final SimpleExpression simpleExpression = (SimpleExpression)criterion; <API key>(simpleExpression); } <API key>(); } public String <API key>() { if (!<API key>()) { <API key>.remove(<API key>.size() - 1); criteria.removeCriterion(); } return null; } @Override protected void <API key>() { criteria.setCriteria(originalCriteria); } public void <API key>(MatchMode matchMode) { criteria.setMatchMode(matchMode); } public List<Criterion> getCriterions() { return criteria.getCriterions(); } }
/** @file * * Contains definitions of the SSAOPlugin Renderer that require qt headers * which are incompatible with glew.h. */ #include "SSAO.hh" #include <QGLFormat> QString SSAOPlugin::checkOpenGL() { // Get version and check QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags(); if ( !flags.testFlag(QGLFormat::OpenGL_Version_3_2) ) return QString("Insufficient OpenGL Version! OpenGL 3.2 or higher required"); // Check extensions QString glExtensions = QString((const char*)glGetString(GL_EXTENSIONS)); QString missing(""); if ( !glExtensions.contains("<API key>") ) missing += "<API key> extension missing\n"; #ifndef __APPLE__ if ( !glExtensions.contains("<API key>") ) missing += "<API key> extension missing\n"; #endif if ( !glExtensions.contains("<API key>") ) missing += "<API key> extension missing\n"; if ( !glExtensions.contains("<API key>") ) missing += "<API key> extension missing\n"; return missing; }
// main.cpp // ArenaBasic #include <iostream> #include <fstream> #include <string> #include <math.h> using namespace std; /* warrior class could have arrays of attributes, eg, war_prowess[]={max,current} to allow easy access and consolidated storage. warrior classes could also include the functions necessary for fights that would be realistic as their actions are a function of themselves only the fight results would be in the fight class The "fight" would be just passing of variables back and forth between instances of the warrior class */ class warrior { public: string war_name; int war_prowess[2]; int war_agility[2]; int war_intel[2]; int war_pers[2]; int war_health[2]; int war_disability[6]; // 0=fatigue,1=stun,2=fall,3=disarm, 4=fatigue/rd; 5=health/rd; higher numbers indicate more severe injury bool attacking () { // whether or not the fighter is attacking int check_atk = rand()%100+1-war_pers; float war_dis_total = war_disability[1] + war_disability[2] + war_disability[3]; // type match? check_atk = check_atk + pow(.5, war_dis_total); // pow called properly? can't use ^? check_atk > 0 ? return true : return false; // why is this incorrect? } int action () { // the quality of the fighter's attack float actionvalue; actionvalue = (war_prowess[1] * 3 + war_agility[1] + war_intel[1]) * (100-war_disability[0])/100; return actionvalue; } } warrior1, warrior2; /* cout << "Enter warrior name:" cin >> war_name; etc... hardcoding two warriors initially; use form-filler later Warrior creation will also be separate; with <API key> selecting from available warriors. */ // for both, other attributes should be initialized to zero. obviously won't work as listed. // however the current attributes should be initialized to the max before new fights (until an alternate recovery system is in place.) warrior1 = {"John",80,50,50,80,50}; // not sure how to assign values to the members of the class. warrior2 = {"Jack",50,80,80,50,50}; // this initializes each fighter in this fight to the values listed above for each warrior, or 0. // this will need to change to choose the selected warrior instead of the hardcoded 2 objects int ftr_main () { ft_startoffight: if (!warrior1.attacking && !warrior2.attacking) { // neither attacking scenario; reduce fatigue, minimum 0. warrior1.disability[0]>=3 ? warrior1.disability[0]-=3 : warrior1.disability[0]=0; warrior2.disability[0]>=3 ? warrior2.disability[0]-=3 : warrior2.disability[0]=0; goto ft_nextround; } if (warrior1.attacking || warrior2.attacking) { // either attacking scenario // assigns a winner/loser in the immediate attack session new void hit_success; // not sure how to declare this variable; intended to point to a warrior class object warrior1.action>warrior2.action ? hit_success == warrior1 : hit_success = warrior2; // prefers 1 in tie. hit_success == warrior1 ? hit_fail == warrior2 : hit_fail == warrior1; new int ft_res=abs(warrior1.action-warrior2.action); // fight resolution, severity of hit, confirm abs library is available warrior1.attacking && warrior2.attacking ? ft_res+=25; // increase severity if both are attacking. switch (ft_res) { case <50: warrior1.attacking && warrior2.attacking ? cout<< "weapons clash.\n"; cout << hit_success.war_name << " dodges.\n"; goto ft_nextround; case <75: if (!hit_success.attacking) { hit_fail.disability[0]+=10; // a dodge creating a fatiguing miss cout << hit_success.war_name << " dodges deftly, while " << hit_fail.war_name << " flails wildly.\n"; else { hit_fail.disability[4]+=3; cout << hit_fail.war_name << " suffers a glancing blow.\n"; } } goto ft_nextround; case <100: if (!hit_success.attacking) { hit_fail.disability[0]+=10; // fatiguing miss just like <75 cout << hit_success.war_name << " dodges deftly, while " << hit_fail.war_name << " flails wildly.\n"; else { hit_fail.disability[4]+=5; hit_fail.disability[5]+=5; cout << hit_success.war_name << " scores a solid hit.\n"; } } goto ft_nextround; case >=100: if (!hit_success.attacking) { hit_fail.disability[0]+=10; // dodge with riposte hit_fail.disability[4]+=3; cout << hit_success.war_name << " dodges deftly, scoring a hit in response.\n"; else { hit_fail.disability[4]+=20; hit_fail.disability[5]+=20; cout << hit_fail.war_name << " suffers a grievous wound.\n"; rand()%100+1 > hit_fail.war_intel[1] ? hit_fail.war_disability[1]++; // stun check rand()%100+1 > hit_fail.war_agility[1] ? hit_fail.war_disability[2]++; // fall check rand()%100+1 > hit_fail.war_agility[1] ? hit_fail.war_disability[3]++; // disarm check war_disability[1]==1 ? cout<<hit_fail.war_name<<" is stunned. "; war_disability[2]==1 ? cout<<hit_fail.war_name<<" falls to the ground. "; war_disability[3]==1 ? cout<<hit_fail.war_name<<" loses hold of his weapon. "; } } goto ft_nextround; } } ft_nextround: new int warrior1status; new int warrior2status; warrior1.war_health[1]>0&&warrior1.war_disability[0]>0 ? warrior1status==1 : warrior1status==0; warrior2.war_health[1]>0&&warrior2.war_disability[0]>0 ? warrior2status==1 : warrior2status==0; if warrior1status <1 || warrior2status <1 { warrior1status==1&&warrior2status==0 ? cout<<warrior1.war_name<<" wins!"; warrior2status==1&&warrior1status==0 ? cout<<warrior2.war_name<<" wins!"; goto ft_endoffight; } // if warriors are alive, fight continues with fighters affected by their fatigue. warrior1.war_prowess[1]=warrior1.war_prowess[1]*(100-warrior1.war_disability[0])/100; warrior1.war_agility[1]=warrior1.war_ability[1]*(100-warrior1.war_disability[0])/100; warrior1.war_intel[1]=warrior1.war_intel[1]*(100-warrior1.war_disability[0])/100; warrior1.war_pers[1]=warrior1.war_pers[1]*(100-warrior1.war_disability[0])/100; warrior2.war_prowess[1]=warrior2.war_prowess[1]*(100-warrior2.war_disability[0])/100; warrior2.war_agility[1]=warrior2.war_ability[1]*(100-warrior2.war_disability[0])/100; warrior2.war_intel[1]=warrior2.war_intel[1]*(100-warrior2.war_disability[0])/100; warrior2.war_pers[1]=warrior2.war_pers[1]*(100-warrior2.war_disability[0])/100; // apply effects of low health or high fatigue warrior1.health[1]<warrior1.health[1]*.25 ? warrior1.disability[1]++; warrior1.health[1]<warrior1.health[1]*.1 ? warrior1.disability[2]++; warrior1.disability[1]==1; cout<<warrior1.war_name<<" is stunned from wounds."; warrior1.disability[2]==1; cout<<warrior1.war_name<<" stumbles to the ground from wounds."; // recover from disabilities, could be easier if I could loop warrior1/2 if warrior1.disability[1]>0 { int stat_check=rand()%100+1)-50; warrior1.war_intel[1]>stat_check ? warrior1.disability[1] warrior1.disability[1]==0 ? cout<<warrior1.war_name<<" clears his head."; } if warrior1.disability[2]>0 { int stat_check=rand()%100+1)-50; warrior1.war_agility[1]>stat_check ? warrior1.disability[2] warrior1.disability[2]==0 ? cout<<warrior1.war_name<<" rises to his feet."; } if warrior1.disability[3]>0 { int stat_check=rand()%100+1)-50; warrior1.war_agility[1]>stat_check ? warrior1.disability[3] warrior1.disability[3]==0 ? cout<<warrior1.war_name<<" recovers his weapon."; } if warrior2.disability[1]>0 { int stat_check=rand()%100+1)-50; warrior2.war_intel[1]>stat_check ? warrior2.disability[1] warrior2.disability[1]==0 ? cout<<warrior2.war_name<<" clears his head."; } if warrior2.disability[2]>0 { int stat_check=rand()%100+1)-50; warrior2.war_agility[1]>stat_check ? warrior2.disability[2] warrior2.disability[2]==0 ? cout<<warrior2.war_name<<" rises to his feet."; } if warrior2.disability[3]>0 { int stat_check=rand()%100+1)-50; warrior2.war_agility[1]>stat_check ? warrior2.disability[3] warrior2.disability[3]==0 ? cout<<warrior2.war_name<<" recovers his weapon."; } goto ft_startoffight; ft_endoffight: cout<<"\n The crowd roars."; }; int main(int argc, const char * argv[]) { // running fighter main is the only function so far. ftr_damage(); // standard hello world below. int p_input; string uname; cin >> p_input; cout<< "Hello, World!\n" << p_input << ": prowess a new line.\n"; cout<< "input name here: "; cin >> uname; cout<<"Name: " << uname << "\n"; return 0; }
#define BOOST_TEST_MODULE "ParticleSpace_test" #ifdef <API key> # include <boost/test/unit_test.hpp> #else # define BOOST_TEST_NO_LIB # include <boost/test/included/unit_test.hpp> #endif #include <boost/test/tools/<API key>.hpp> #include <ecell4/core/<API key>.hpp> #include <ecell4/core/SerialIDGenerator.hpp> using namespace ecell4; struct Fixture { typedef <API key> particle_space_type; const Real3 edge_lengths; const Integer3 matrix_sizes; const Real radius; Fixture() : edge_lengths(1, 1, 1), matrix_sizes(5, 5, 5), radius(0.005) {} }; <API key>(suite, Fixture) <API key>(<API key>) { std::unique_ptr<ParticleSpace> space(new particle_space_type(edge_lengths, matrix_sizes)); BOOST_CHECK_EQUAL((*space).list_species().size(), 0); BOOST_CHECK_EQUAL((*space).num_particles(), 0); BOOST_CHECK_EQUAL((*space).edge_lengths(), edge_lengths); BOOST_CHECK_EQUAL((*space).volume(), 1.0); BOOST_CHECK_EQUAL((*space).t(), 0.0); } <API key>(<API key>) { std::unique_ptr<ParticleSpace> space(new particle_space_type(edge_lengths, matrix_sizes)); SerialIDGenerator<ParticleID> pidgen; const ParticleID pid1 = pidgen(); const Species sp1 = Species("A"); const Species sp2 = Species("B"); BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.5, radius, 0))); BOOST_CHECK_EQUAL((*space).num_particles(), 1); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); BOOST_CHECK(!(*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.25, radius, 0))); BOOST_CHECK_EQUAL((*space).num_particles(), 1); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); BOOST_CHECK(!(*space).update_particle(pid1, Particle(sp2, edge_lengths * 0.1, radius, 0))); BOOST_CHECK_EQUAL((*space).num_particles(), 1); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); BOOST_CHECK_EQUAL((*space).num_particles(sp2), 1); (*space).remove_particle(pid1); BOOST_CHECK_EQUAL((*space).num_particles(), 0); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); } <API key>(<API key>) { std::unique_ptr<ParticleSpace> space(new particle_space_type(edge_lengths, matrix_sizes)); SerialIDGenerator<ParticleID> pidgen; const ParticleID pid1 = pidgen(); const ParticleID pid2 = pidgen(); const ParticleID pid3 = pidgen(); const Species sp1 = Species("A"); BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.5, radius, 0))); BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, edge_lengths * 0.25, radius, 0))); BOOST_CHECK((*space).update_particle(pid3, Particle(sp1, edge_lengths * 0.75, radius, 0))); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 3); (*space).remove_particle(pid2); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); (*space).remove_particle(pid3); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); (*space).remove_particle(pid1); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); } <API key>(<API key>) { std::unique_ptr<ParticleSpace> space(new particle_space_type(edge_lengths, matrix_sizes)); SerialIDGenerator<ParticleID> pidgen; const ParticleID pid1 = pidgen(); BOOST_CHECK_THROW((*space).remove_particle(pid1), NotFound); } <API key>(<API key>) { std::unique_ptr<ParticleSpace> space(new particle_space_type(edge_lengths, matrix_sizes)); SerialIDGenerator<ParticleID> pidgen; const ParticleID pid1 = pidgen(); const ParticleID pid2 = pidgen(); const Species sp1 = Species("A"); BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, Real3(0.5, 0.5, 0.5), radius, 0))); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); { const std::vector<std::pair<std::pair<ParticleID, Particle>, Real> > retval = (*space).<API key>(Real3(0.509, 0.5, 0.5), radius); BOOST_CHECK_EQUAL(retval.size(), 1); BOOST_CHECK_EQUAL(retval[0].first.first, pid1); BOOST_CHECK_CLOSE(retval[0].second, 0.009 - radius, 1e-6); } BOOST_CHECK_EQUAL((*space).<API key>(Real3(0.509, 0.5, 0.5), radius, pid1).size(), 0); BOOST_CHECK_EQUAL((*space).<API key>(Real3(0.511, 0.5, 0.5), radius).size(), 0); BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, Real3(0.511, 0.5, 0.5), radius, 0))); BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); BOOST_CHECK_EQUAL((*space).<API key>(Real3(0.509, 0.5, 0.5), radius).size(), 2); (*space).remove_particle(pid1); { const std::vector<std::pair<std::pair<ParticleID, Particle>, Real> > retval = (*space).<API key>(Real3(0.509, 0.5, 0.5), radius); BOOST_CHECK_EQUAL(retval.size(), 1); BOOST_CHECK_EQUAL(retval[0].first.first, pid2); BOOST_CHECK_CLOSE(retval[0].second, 0.002 - radius, 1e-6); } } <API key>(<API key>) { std::unique_ptr<<API key>> space(new <API key>(edge_lengths, matrix_sizes)); BOOST_CHECK_EQUAL((*space).matrix_sizes(), matrix_sizes); } <API key>()
<?php require_once( LIB_PATH.DS."class.database.php"); require_once( LIB_PATH.DS."class.paymentmodules.php"); require_once( LIB_PATH.DS."class.paymentconfig.php"); class paypal { public $module_key = 'paypal'; public function button(){ global $smarty; $paymentconfig = PaymentConfig::find_by_module_key( $this->module_key ); foreach( $paymentconfig as $confitem ) { $paymod_data[ $confitem->config_key ] = $confitem->config_value; } unset($confdata); $smarty->assign( 'email', $paymod_data['<API key>'] ); $smarty->assign('run_mode', $paymod_data['<API key>']) ; $smarty->assign('rendered_page', $smarty->fetch('employer/paypal_checkout.tpl') ); } public function install(){ global $db, $database; $paymentmodules = PaymentModules::find_by_module_key( $this->module_key ); $paymentmodules->enabled = 'Y'; $payment_module_id = $paymentmodules->id; $paymentmodules->save(); $paymentconfig = new PaymentConfig(); $paymentconfig->payment_module_id = $payment_module_id; $paymentconfig->module_key = 'paypal'; $paymentconfig->config_title = 'E-Mail Address'; $paymentconfig->config_key = '<API key>'; $paymentconfig->config_value = 'yourname@yourdomain.com'; $paymentconfig->config_description = 'The e-mail address to use for the PayPal service'; //$paymentconfig->data_type; $paymentconfig->input_type = 'text'; //$paymentconfig->input_options; $paymentconfig->date_added = date("Y-m-d H:i:s", time()); $paymentconfig->save(); unset($paymentconfig->id); //$paymentconfig->payment_module_id = $payment_module_id; //$paymentconfig->module_key = 'paypal'; $paymentconfig->config_title = 'Transaction Mode'; $paymentconfig->config_key = '<API key>'; $paymentconfig->config_value = 'test'; $paymentconfig->config_description = 'The transaction is in test mode or not'; //$paymentconfig->data_type; $paymentconfig->input_type = 'radio'; $paymentconfig->input_options = 'test|live'; //$paymentconfig->date_added = 'NOW()'; $paymentconfig->save(); } public function remove(){ $paymentmodules = PaymentModules::find_by_module_key( $this->module_key ); $paymentmodules->enabled = 'N'; $payment_module_id = $paymentmodules->id; $paymentmodules->save(); PaymentConfig::<API key>( $this->module_key ); } } ?>
Info<< "Reading incremental displacement field DU\n" << endl; volVectorField DU ( IOobject ( "DU", runTime.timeName(), stressMesh, IOobject::MUST_READ, IOobject::AUTO_WRITE ), stressMesh ); volTensorField gradDU = fvc::grad(DU); volVectorField Usolid ( IOobject ( "Usolid", runTime.timeName(), stressMesh, IOobject::READ_IF_PRESENT, IOobject::AUTO_WRITE ), DU ); Info<< "Reading incremental displacement field DV\n" << endl; volVectorField DV ( IOobject ( "DV", runTime.timeName(), stressMesh, IOobject::READ_IF_PRESENT, IOobject::AUTO_WRITE ), fvc::ddt(DU) ); Info<< "Reading accumulated velocity field V\n" << endl; volVectorField Vs ( IOobject ( "Vs", runTime.timeName(), stressMesh, IOobject::READ_IF_PRESENT, IOobject::AUTO_WRITE ), stressMesh, dimensionedVector("zero", dimVelocity, vector::zero) ); Info << "Reading accumulated stress field sigma\n" << endl; volSymmTensorField sigma ( IOobject ( "sigma", runTime.timeName(), stressMesh, IOobject::READ_IF_PRESENT, IOobject::AUTO_WRITE ), stressMesh, <API key>("zero", dimForce/dimArea, symmTensor::zero) ); Info << "Reading incremental stress field DSigma\n" << endl; volSymmTensorField DSigma ( IOobject ( "DSigma", runTime.timeName(), stressMesh, IOobject::READ_IF_PRESENT, IOobject::AUTO_WRITE ), stressMesh, <API key>("zero", dimForce/dimArea, symmTensor::zero) ); constitutiveModel rheology(sigma, DU); volScalarField rho = rheology.rho(); volScalarField mu = rheology.mu(); volScalarField lambda = rheology.lambda(); volTensorField F = I + gradDU.T(); volTensorField DF = F - I; volScalarField J = det(F); word solidDdtScheme ( stressMesh.schemesDict().ddtScheme("ddt(" + DU.name() +')') ); // solidDdtScheme != fv::<API key><vector>::typeName // && solidDdtScheme != fv::<API key><vector>::typeName // FatalErrorIn(args.executable()) // << "Selected temporal differencing scheme: " << solidDdtScheme // << ", instead: " // << fv::<API key><vector>::typeName // << fv::<API key><vector>::typeName // << exit(FatalError); // IOdictionary rheologyProp // IOobject // "rheologyProperties", // runTime.constant(), // stressMesh, // IOobject::MUST_READ, // IOobject::NO_WRITE // dimensionedVector fb(rheologyProp.lookup("bodyForce"));
layout: post title: "D3.js tour 7" date: 2017-04-21 01:27:13 +0000 img: docker-jekyll.jpg description: D3.js tour 7 tags: [js, d3] author: Alan Wang js const axis = d3.axisTop(linear) js svg.append('g') .attr('transform', 'translate(0,30)') .call(axis) css .axis path, .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 11px; } ![]({{ site.baseurl }}/assets/demos/d3tour/tour07.png) END
<?php ob_start(); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Global Character Manager</title> <style type="text/css"> * { font-family: sans-serif, sans; text-align: left; } th { font-weight: bold; background-color: #ddd; } </style> <script type="text/javascript"> function gx(w) { return document.getElementById(w); } function toggleall() { for (var i=1;;i++) { var b = gx('c'+i); if (!b) { break; } b.checked = !b.checked; } } function selectall() { for (var i=1;;i++) { var b = gx('c'+i); if (!b) { break; } b.checked = true; } } function unselectall() { for (var i=1;;i++) { var b = gx('c'+i); if (!b) { break; } b.checked = false; } } </script> </head> <body bgcolor="white" color="black"> <form action="/characters.php" method="post"> <?php $chars = array(); if (!empty($_REQUEST['email']) && !empty($_REQUEST['password'])) { require_once __DIR__.'/mysql.php'; $_REQUEST['email'] = <API key>($handler, $_REQUEST['email']); $_REQUEST['org_password'] = $_REQUEST['password']; $_REQUEST['password'] = md5($_REQUEST['password']); $update = array(); if (!empty($_REQUEST['newemail'])) { $new = <API key>($handler, trim($_REQUEST['newemail'])); $update[] = "email='".$new."'"; } if (!empty($_REQUEST['newpassword'])) { $new = md5(trim($_REQUEST['newpassword'])); $update[] = "password='".$new."'"; } if (!empty($_REQUEST['newicq'])) { $new = intval(trim($_REQUEST['newicq'])); $update[] = "icq='".$new."'"; } if (!empty($_REQUEST['newcolor'])) { $new = <API key>($handler, trim($_REQUEST['newcolor'])); $update[] = "pcolor='".$new."'"; } if (!empty($_REQUEST['newimage'])) { $new = <API key>($handler, trim($_REQUEST['newimage'])); $update[] = "pimage='".$new."'"; } if (!empty($_REQUEST['newlink'])) { $new = <API key>($handler, trim($_REQUEST['newlink'])); $update[] = "plink='".$new."'"; } if (!empty($_REQUEST['newprefs'])) { $new = <API key>($handler, preg_replace('@[^A-Za-z0-9]@', '', trim($_REQUEST['newprefs']))); $update[] = "prefs='".$new."'"; } if (!empty($_REQUEST['newaim'])) { $new = <API key>($handler, preg_replace('@[^A-Za-z0-9]@', '', trim($_REQUEST['newaim']))); $update[] = "aim='".$new."'"; } if (!empty($_REQUEST['newym'])) { $new = <API key>($handler, trim($_REQUEST['newym'])); $update[] = "ym='".$new."'"; } if (!empty($_REQUEST['newmsn'])) { $new = <API key>($handler, trim($_REQUEST['newmsn'])); $update[] = "msn='".$new."'"; } if (!empty($_REQUEST['newskype'])) { $new = <API key>($handler, trim($_REQUEST['newskype'])); $update[] = "skype='".$new."'"; } if (!empty($_REQUEST['newsite'])) { $new = <API key>($handler, trim($_REQUEST['newsite'])); $update[] = "site='".$new."'"; } if (!empty($_REQUEST['newlastfm'])) { $new = <API key>($handler, trim($_REQUEST['newlastfm'])); $update[] = "lastfm='".$new."'"; } if (!empty($_REQUEST['newflickr'])) { $new = <API key>($handler, trim($_REQUEST['newflickr'])); $update[] = "flickr='".$new."'"; } if (!empty($_REQUEST['newfacebook'])) { $new = <API key>($handler, trim($_REQUEST['newfacebook'])); $update[] = "facebook='".$new."'"; } if (!empty($_REQUEST['newgplus'])) { $new = <API key>($handler, trim($_REQUEST['newgplus'])); $update[] = "gplus='".$new."'"; } if (!empty($_REQUEST['newdisplayname'])) { $new = <API key>($handler, trim($_REQUEST['newdisplayname'])); $update[] = "displayname='".$new."'"; } if (empty($_REQUEST['export']) && !empty($update)) { $update = implode(', ', $update); $query = "UPDATE uo_chat_database SET {$update} WHERE email='".$_REQUEST['email']."' AND password='".$_REQUEST['password']."' AND chat LIKE 'chat%'"; foreach ($_REQUEST['uids'] as $key => $uid) { if (!empty($uid)) { $key = intval($key); mysqli_query($handler, "$query AND uid=$key"); } } } $query = "SELECT uid, chat, username, displayname, prefs, pimage, plink, pcolor, icq, aim, ym, msn, site, skype, lastfm, flickr, facebook, gplus FROM uo_chat_database WHERE email='".$_REQUEST['email']."' AND password='".$_REQUEST['password']."' AND chat LIKE 'chat%' AND dtime IS NULL ORDER BY chat ASC, username ASC"; $rez = mysqli_query($handler, $query); while ($row = mysqli_fetch_assoc($rez)) { $chars[] = $row; } mysqli_free_result($rez); if (!empty($_REQUEST['export']) && !empty($chars)) { ob_end_clean(); header('Content-Type: text/<API key>; charset=UTF-8'); header('Content-Disposition: attachment; filename="characters.tsv"'); echo implode("\t", array_keys($chars[0]))."\n"; foreach ($chars as $c) { echo implode("\t", $c)."\n"; } exit(); } } if (!empty($chars)) { echo <<<OUTPUT <blockquote> Found the following characters matching those credentials... </blockquote> <table cellspacing="1" cellpadding="3" border="0"> <tr valign="top"> <th>&nbsp;</th> <th>ID</th> <th>Chat</th> <th>Username</th> <th>Color</th> <th>Image</th> <th>Link</th> <th>Prefs</th> </tr> <tr valign="top"> <th>&nbsp;</th> <th>ICQ</th> <th>AIM</th> <th>Yahoo</th> <th>MSN</th> <th>Skype</th> <th>Website</th> <th>Last.fm</th> </tr> <tr valign="top"> <th>&nbsp;</th> <th>Flickr</th> <th>Facebook</th> <th>Google+</th> <th>Display Name</th> </tr> <tr valign="top"> <th colspan="8"> <input type="button" onclick="toggleall();" value="Toggle All"> <input type="button" onclick="selectall();" value="Select All"> <input type="button" onclick="unselectall();" value="Unselect All"> </th> </tr> OUTPUT; $cl = '#ffffff'; $cn = 0; foreach ($chars as $char) { $cn++; $chat = mb_substr($char['chat'], 4); $char['username'] = htmlentities($char['username']); $char['pcolor'] = htmlentities($char['pcolor']); $char['pimage'] = htmlentities($char['pimage']); $char['plink'] = htmlentities($char['plink']); $char['prefs'] = htmlentities($char['prefs']); $char['icq'] = htmlentities($char['icq']); $char['aim'] = htmlentities($char['aim']); $char['ym'] = htmlentities($char['ym']); $char['msn'] = htmlentities($char['msn']); $char['skype'] = htmlentities($char['skype']); $char['site'] = htmlentities($char['site']); $char['lastfm'] = htmlentities($char['lastfm']); $char['flickr'] = htmlentities($char['flickr']); $char['facebook'] = htmlentities($char['facebook']); $char['gplus'] = htmlentities($char['gplus']); $char['displayname'] = htmlentities($char['displayname']); $ck = ''; if (!empty($_REQUEST['uids'][$char['uid']])) { $ck = ' checked'; } echo <<<OUTPUT <tr valign="top" bgcolor="{$cl}"> <td><input type="checkbox" name="uids[{$char['uid']}]" value="c{$char['uid']}" id="c{$cn}"$ck></td> <td>{$char['uid']}</td> <td><a href="/{$chat}/">{$chat}</a></td> <td>{$char['username']}</td> <td>{$char['pcolor']}</td> <td>{$char['pimage']}</td> <td>{$char['plink']}</td> <td>{$char['prefs']}</td> </tr> <tr valign="top" bgcolor="{$cl}"> <td>&nbsp;</td> <td>{$char['icq']}</td> <td>{$char['aim']}</td> <td>{$char['ym']}</td> <td>{$char['msn']}</td> <td>{$char['skype']}</td> <td>{$char['site']}</td> <td>{$char['lastfm']}</td> </tr> <tr valign="top" bgcolor="{$cl}"> <td>&nbsp;</td> <td>{$char['flickr']}</td> <td>{$char['facebook']}</td> <td>{$char['gplus']}</td> <td>{$char['displayname']}</td> </tr> OUTPUT; if ($cl == '#ffffff') { $cl = '#eeeeee'; } else { $cl = '#ffffff'; } } echo <<<OUTPUT <tr valign="top"> <th colspan="8"> <input type="button" onclick="toggleall();" value="Toggle All"> <input type="button" onclick="selectall();" value="Select All"> <input type="button" onclick="unselectall();" value="Unselect All"> <input type="submit" name="export" value="Export All as TSV"> </th> </tr> </table> OUTPUT; ?> <blockquote> For the selected characters, set the following fields... Empty means it won't change that field. If you want it zeroed, put in a space. </blockquote> <table cellspacing="1" cellpadding="3" border="0"> <tr valign="top"> <th>Email</th> <th>Password</th> <th>Color</th> <th>Image</th> <th>Link</th> <th>Prefs</th> </tr> <tr valign="top"> <th>ICQ</th> <th>AIM</th> <th>Yahoo</th> <th>MSN</th> <th>Skype</th> <th>Website</th> <th>Last.fm</th> </tr> <tr valign="top"> <th>Flickr</th> <th>Facebook</th> <th>Google+</th> <th>Display Name</th> </tr> <tr valign="top"> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newemail']);?>" name="newemail"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newpassword']);?>" name="newpassword"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newcolor']);?>" name="newcolor"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newimage']);?>" name="newimage"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newlink']);?>" name="newlink"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newprefs']);?>" name="newprefs"></td> </tr> <tr valign="top"> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newicq']);?>" name="newicq"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newaim']);?>" name="newaim"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newym']);?>" name="newym"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newmsn']);?>" name="newmsn"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newskype']);?>" name="newskype"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newsite']);?>" name="newsite"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newlastfm']);?>" name="newlastfm"></td> </tr> <tr valign="top"> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newflickr']);?>" name="newflickr"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newfacebook']);?>" name="newfacebook"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newgplus']);?>" name="newgplus"></td> <td><input type="text" size="10" value="<?=htmlentities($_REQUEST['newdisplayname']);?>" name="newdisplayname"></td> </tr> </table> <?php } ?> <blockquote> Fill in email and password. </blockquote> <table cellspacing="1" cellpadding="3" border="0"> <tr valign="top"> <th>Email</th> <th>Password</th> <th>&nbsp;</th> </tr> <tr valign="top"> <td><input type="text" size="20" value="<?=htmlentities($_REQUEST['email']);?>" name="email"></td> <td><input type="password" size="10" value="<?=htmlentities($_REQUEST['org_password']);?>" name="password"></td> <td><input type="submit" value="Submit"></td> </tr> </table> </form> <blockquote> This can be used to manage various aspects of all your characters across pJJ, if they all have the same email and password. Any questions should be directed to <a href="http://tinodidriksen.com/convoke/">Tino Didriksen</a>. </blockquote> </body> </html>
<?php namespace Alchemy\Phrasea\TaskManager\Editor; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\<API key>; use Alchemy\Phrasea\Core\Configuration\PropertyAccess; class SubdefsEditor extends AbstractEditor { /** * {@inheritdoc} */ public function getTemplatePath() { return 'admin/task-manager/task-editor/subdefs.html.twig'; } /** * {@inheritdoc} */ public function getDefaultPeriod() { return 10; } /** * {@inheritdoc} */ public function getDefaultSettings(PropertyAccess $config = null) { return <<<EOF <?xml version="1.0" encoding="UTF-8"?> <tasksettings> <embedded>1</embedded> <sbas/> <type_image>1</type_image> <type_video>1</type_video> <type_audio>1</type_audio> <type_document>1</type_document> <type_flash>1</type_flash> <type_unknown>1</type_unknown> <flush>5</flush> <maxrecs>20</maxrecs> <maxmegs>256</maxmegs> <maxduration>3600</maxduration> </tasksettings> EOF; } /** * {@inheritdoc} */ protected function getFormProperties() { return [ 'sbas[]' => static::FORM_TYPE_INTEGER, 'type_image' => static::FORM_TYPE_BOOLEAN, 'type_video' => static::FORM_TYPE_BOOLEAN, 'type_audio' => static::FORM_TYPE_BOOLEAN, 'type_document' => static::FORM_TYPE_BOOLEAN, 'type_flash' => static::FORM_TYPE_BOOLEAN, 'type_unknown' => static::FORM_TYPE_BOOLEAN, 'flush' => static::FORM_TYPE_INTEGER, 'maxrecs' => static::FORM_TYPE_INTEGER, 'maxmegs' => static::FORM_TYPE_INTEGER, 'embedded' => static::FORM_TYPE_BOOLEAN, ]; } /** * {@inheritdoc} */ public function <API key>(Request $request) { $dom = $this->createBlankDom(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; if (false === @$dom->loadXML($request->request->get('xml'))) { throw new <API key>('Invalid XML data.'); } // delete empty /text-nodes so the output can be better formatted $nodesToDel = array(); for($node = $dom->documentElement->firstChild; $node; $node=$node->nextSibling) { if($node->nodeType == XML_TEXT_NODE && trim($node->data)=="") { $nodesToDel[] = $node; } } foreach($nodesToDel as $node) { $dom->documentElement->removeChild($node); } $dom->normalizeDocument(); foreach ($this->getFormProperties() as $name => $type) { $multi = false; if(substr($name, -2)== "[]") { $multi = true; $name = substr($name, 0, strlen($name)-2); } $values = $request->request->get($name); if($values === null && !$multi) { switch($type) { case static::FORM_TYPE_INTEGER: case static::FORM_TYPE_BOOLEAN: $values = "0"; break; case static::FORM_TYPE_STRING: $values = ""; break; } } // erase the former setting but keep the node in place. // in case on multi-valued, keep only the first node (except if no value at all: erase all) $nodesToDel = array(); foreach($dom-><API key>($name) as $i=>$node) { // empty while ($child = $node->firstChild) { $node->removeChild($child); } // keep the first for multi, only if there is something to write if($i > 0 || ($multi && $values===null) ) { $nodesToDel[] = $node; } } foreach($nodesToDel as $node) { $dom->documentElement->removeChild($node); } // if no multiple-setting to write, no reason to create an empty node if($values === null) { continue; } if(!is_array($values)) { $values = array($values); } // in case the node did not exist at all, create one if ( ($node = $dom-><API key>($name)->item(0)) === null) { $node = $dom->documentElement->appendChild($dom->createElement($name)); } // because dom::insertBefore is used, reverse allows to respect order while serializing. $values = array_reverse($values); // write foreach($values as $i=>$value) { if($i>0) { // multi-valued ? add an entry $node = $dom->documentElement->insertBefore($dom->createElement($name), $node); } $node->appendChild($dom->createTextNode($this->toXMLValue($type, $value))); } } $dom->normalizeDocument(); return new Response($dom->saveXML(), 200, ['Content-type' => 'text/xml']); } private function toXMLValue($type, $value) { switch ($type) { case static::FORM_TYPE_BOOLEAN: $value = (!$value ? '0' : '1'); break; case static::FORM_TYPE_INTEGER: $value = ($value !== null ? (string)((int) $value) : ''); break; } return $value; } }
import { Component } from '@angular/core'; import { NavController, NavParams, ToastController, ModalController, AlertController, LoadingController, <API key> } from 'ionic-angular'; import { AbstractPage } from '../abstract-page'; import { AssetsPage } from '../assets/assets'; import { EventPage } from '../event/event'; import { OutagePage } from '../outage/outage'; import { ResourcesPage } from '../resources/resources'; import { SetLocationPage } from '../set-location/set-location'; import { OnmsNode } from '../../models/onms-node'; import { OnmsEvent } from '../../models/onms-event'; import { OnmsOutage } from '../../models/onms-outage'; import { <API key> } from '../../models/<API key>'; import { OnmsApiFilter } from '../../models/onms-api-filter'; import { OnmsUIService } from '../../services/onms-ui'; import { OnmsNodesService } from '../../services/onms-nodes'; import { OnmsEventsService } from '../../services/onms-events'; import { OnmsOutagesService } from '../../services/onms-outages'; import { <API key> } from '../../services/onms-availability'; import { OnmsServersService, OnmsFeatures } from '../../services/onms-servers'; @Component({ selector: 'page-node', templateUrl: 'node.html' }) export class NodePage extends AbstractPage { mode: string = 'info'; inScheduledOutage: boolean = false; node: OnmsNode; availability: <API key> = <API key>.create(); events: OnmsEvent[] = []; outages: OnmsOutage[] = []; constructor( loadingCtrl: LoadingController, alertCtrl: AlertController, toastCtrl: ToastController, private navCtrl: NavController, private navParams: NavParams, private modalCtrl: ModalController, private actionSheetCtrl: <API key>, private uiService: OnmsUIService, private nodesService: OnmsNodesService, private eventsService: OnmsEventsService, private outagesService: OnmsOutagesService, private serversService: OnmsServersService, private availabilityService: <API key> ) { super(loadingCtrl, alertCtrl, toastCtrl); } ionViewWillLoad() { this.node = this.navParams.get('node'); } ionViewDidLoad() { this.updateDependencies(); } onShowOptions() { const actionSheet = this.actionSheetCtrl.create({ title: 'Node Commands', buttons: [ { text: 'Refresh Content', handler: () => { this.onRefresh() } }, { text: 'Show Assets', handler: () => this.onShowAssets() }, { text: 'Show Resources', handler: () => this.onShowResources() }, { text: 'Force Rescan', handler: () => this.onForceRescan() }, { text: 'Cancel', role: 'cancel' } ] }); actionSheet.present(); } async onRefresh() { const loading = this.loading('Refreshing node ...'); try { this.node = await this.nodesService.getNode(this.node.id); this.updateDependencies(); } catch (error) { this.alert('Refresh Node', error); } finally { loading.dismiss(); } } onShowEvent(event: OnmsEvent) { this.navCtrl.push(EventPage, {event: event}); } onShowOutage(outage: OnmsOutage) { this.navCtrl.push(OutagePage, {outage: outage}); } onShowResources() { if (this.serversService.supports(OnmsFeatures.Measurements)) { this.navCtrl.push(ResourcesPage, {node: this.node}); } else { this.alert('Warning', 'Feature not supported on this version.'); } } onShowAssets() { this.navCtrl.push(AssetsPage, {node: this.node}); } async onForceRescan() { const loading = this.loading('Sending force rescan...'); try { const event = { uei: 'uei.opennms.org/internal/capsd/forceRescan', nodeid: this.node.id }; await this.eventsService.sendEvent(event); this.toast('Force rescan event has been sent!'); } catch (error) { this.alert('Force Rescan Error', error); } finally { loading.dismiss(); } } onSelectOnMap() { const modal = this.modalCtrl.create(SetLocationPage, { node: this.node }); modal.onDidDismiss(data => { if (data) this.saveCoordinates(data); }); modal.present(); } formatUei(uei: string) : string { return this.uiService.getFormattedUei(uei); } getOutageColor(outage: OnmsOutage) : string { return this.uiService.getOutageIconColor(outage); } private async updateDependencies() { try { const labelFilter = new OnmsApiFilter('node.label', this.node.label); const outstanding = new OnmsApiFilter('ifRegainedService', 'null'); let promises = []; promises.push(this.nodesService.getIpInterfaces(this.node.id)); promises.push(this.nodesService.getSnmpInterfaces(this.node.id)); promises.push(this.availabilityService.<API key>(this.node.id)); promises.push(this.eventsService.getEvents(0, [labelFilter], 5)); promises.push(this.outagesService.getOutages(0, [labelFilter, outstanding], 5)); promises.push(this.nodesService.<API key>(this.node.id)); [ this.node.ipInterfaces, this.node.snmpInterfaces, this.availability, this.events, this.outages, this.inScheduledOutage ] = await Promise.all(promises); } catch (error) { this.alert('Error', `Cannot update dependencies: ${error}`); } } private async saveCoordinates(coords: {latitude: number, longitude: number}) { this.node.assetRecord.latitude = coords.latitude; this.node.assetRecord.longitude = coords.longitude; const loading = this.loading('Updating node assets...'); try { await this.nodesService.updateAssets(this.node.id, coords); this.toast('Coordinates updated!'); } catch (error) { this.alert('Update Assets Error', error); } finally { loading.dismiss(); } } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Tue Jul 07 13:45:10 BST 2015 --> <title>interactor Class Hierarchy</title> <meta name="date" content="2015-07-07"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="interactor Class Hierarchy"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../input/package-tree.html">Prev</a></li> <li><a href="../output/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../index.html?interactor/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h1 class="title">Hierarchy For Package interactor</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">interactor.<a href="../interactor/InteractorUDP.html" title="class in interactor"><span class="strong">InteractorUDP</span></a> (implements java.lang.Runnable) <ul> <li type="circle">interactor.<a href="../interactor/ConsoleInteractor.html" title="class in interactor"><span class="strong">ConsoleInteractor</span></a></li> </ul> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../input/package-tree.html">Prev</a></li> <li><a href="../output/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../index.html?interactor/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
# <API key> VB.Net Cryptsy APIv2 Class This class can be used in a Visual Studio dotNet Project to query www.Cryptsy.com. Trading crypto currencies can be high risk and you can lose money. This code is supplied without warranty. The Class is capable of most of the Cryptsy functions like place and cancel an order, get trading fees etc. If you find it useful donations to the following Crytpo wallets will be gratefully recieved: BitCoin: <API key> DashCoin: <API key> DiamondCoin: <API key> DOGECoin: <API key> EarthCoin: <API key> LiteCoin: <API key> LottoCoin: <API key> NobleCoin: <API key>
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Fire here. * * @author ink * @version (a version number or a date) */ public class Fire extends Bullet { /** * Constructor de la clase */ public Fire(double x ,double y, Vector move) { super(x,y,5,move,new Vector(),"fire_bullet.png",8); } /** *calls the super class act method. */ public void act() { super.act(); } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; namespace zComp.Core.Helpers { public static class SerializationHelper { <summary>Renvoie la sérialisation d'un objet DataContract</summary> <param name="item">Objet à sérialiser</param> <returns>La sérialisation de l'objet sous forme de chaine de caractères</returns> public static string <API key>(object item, Type[] knowedTypes, Encoding encoding) { if (encoding == null) encoding = Encoding.Default; var type = item == null ? typeof(object) : item.GetType(); var xs = new XmlSerializer(type, knowedTypes); using (var ms = new MemoryStream()) using (StreamWriter wr = new StreamWriter(ms)) { xs.Serialize(wr, item); wr.Flush(); return encoding.GetString(ms.ToArray()); } } <summary>Renvoie la sérialisation d'un objet DataContract</summary> <param name="item">Objet à sérialiser</param> <returns>La sérialisation de l'objet sous forme d'un buffer</returns> public static byte[] <API key>(object item, Type[] knowedTypes) { var type = item == null ? typeof(object) : item.GetType(); var xs = new XmlSerializer(type, knowedTypes); using (var ms = new MemoryStream()) using (StreamWriter wr = new StreamWriter(ms)) { xs.Serialize(wr, item); wr.Flush(); return ms.ToArray(); } } <summary>Déserialise un objet à partir d'une chaine de caractères</summary> <param name="serialization">Sérialisation xml de l'objet</param> <param name="type">Type de l'objet à désérialiser</param> <param name="knowedTypes">Types connus</param> <returns>L'objet désérialisé</returns> public static object <API key>(string serialization, Type type, Type[] knowedTypes, Encoding encoding) { if (string.IsNullOrEmpty(serialization)) return null; if (encoding == null) encoding = Encoding.Default; using (var memStream = new MemoryStream(encoding.GetBytes(serialization))) { memStream.Position = 0; using (var textReader = new XmlTextReader(memStream)) { var serializer = new System.Xml.Serialization.XmlSerializer(type, knowedTypes); return serializer.Deserialize(textReader); } } } public static string <API key>(object item, Type[] knowedTypes, Encoding encoding) { if (encoding == null) encoding = Encoding.Default; var type = item == null ? typeof(object) : item.GetType(); var serializer = new <API key>(type, knowedTypes); using (var ms = new MemoryStream()) { serializer.WriteObject(ms, item); return encoding.GetString(ms.ToArray()); } } public static byte [] <API key>(object item, Type[] knowedTypes) { var type = item == null ? typeof(object) : item.GetType(); var serializer = new <API key>(type, knowedTypes); using (var ms = new MemoryStream()) { serializer.WriteObject(ms, item); return ms.ToArray(); } } <summary>Déserialise un objet à partir d'un buffer</summary> <param name="serialization">Sérialisation xml de l'objet dans un buffer</param> <param name="type">Type de l'objet à désérialiser</param> <param name="knowedTypes">Types connus</param> <returns>L'objet désérialisé</returns> public static object <API key>(string serialization, Type type, Type[] knowedTypes, Encoding encoding) { if (encoding == null) encoding = Encoding.Default; if (type == null) throw new <API key>("Le type de l'objet à désérialiser"); var serializer = new <API key>(type, knowedTypes); using (var ms = new MemoryStream(encoding.GetBytes(serialization))) return serializer.ReadObject(ms); } <summary>Déserialise un objet à partir d'un buffer</summary> <param name="serialization">Sérialisation xml de l'objet dans un buffer</param> <param name="type">Type de l'objet à désérialiser</param> <param name="knowedTypes">Types connus</param> <returns>L'objet désérialisé</returns> public static object <API key>(byte[] serialization, Type type, Type[] knowedTypes) { if (type == null) throw new <API key>("Le type de l'objet à désérialiser"); var serializer = new <API key>(type, knowedTypes); using (var ms = new MemoryStream(serialization)) return serializer.ReadObject(ms); } <summary>Clone un objet</summary> <param name="item">L'objet à cloner</param> <param name="type">Le type de l'objet à cloner (si item = null)</param> <param name="knowedTypes">Une liste de types connus</param> <returns>Un clone de l'objet d'origine</returns> public static object <API key>(object item, Type[] knowedTypes) { if (item == null) return null; else return item == null ? null : <API key>(<API key>(item, knowedTypes, Encoding.Default), item.GetType(), knowedTypes, Encoding.Default); } public static object <API key>(object item, Type[] knowedTypes) { if (item == null) return null; else return item == null ? null : <API key>(<API key>(item, knowedTypes, Encoding.Default), item.GetType(), knowedTypes, Encoding.Default); } public static object <API key>(object item, Type[] knowedTypes) { object result = null; if (item != null) { var type = item.GetType(); if (type.IsGenericType) type = type.GetGenericArguments().First(); if (type.GetCustomAttributes(true).Any(attr => attr is <API key>)) result = SerializationHelper.<API key>(item, knowedTypes); else result = SerializationHelper.<API key>(item, knowedTypes); } return result; } public static bool <API key>(object item1, object item2, Type[] knowedTypes, bool <API key>) { var result = false; if (item1 == null && item2 == null) result = true; else if (item1 != null && item2 != null) result = <API key> ? <API key>(item1, knowedTypes, Encoding.Default) == <API key>(item2, knowedTypes, Encoding.Default) : SerializeToString(item1, knowedTypes, Encoding.Default) == SerializeToString(item2, knowedTypes, Encoding.Default); return result; } public static string SerializeToString(object item, Type[] knowedTypes, Encoding encoding) { string result; var type = item.GetType(); if (type.IsGenericType) type = type.GetGenericArguments().First(); if (type.GetCustomAttributes(true).Any(attr => attr is <API key>)) result = <API key>(item, knowedTypes, encoding); else result = <API key>(item, knowedTypes, encoding); return result; } public static bool IsDataContractType(Type type) { return type.GetCustomAttributes(true).Any(attr => attr is <API key>); } public static string Serialize(object item) { var sb = new StringBuilder(); <API key>(item, null, 0, sb); return sb.ToString().Trim(); } public static object Unserialize(string serialization, IEnumerable<Type> knowedTypes) { //CreateKnowedTypes(); var knowedTypesDict = knowedTypes.ToDictionary(x => GetTypeName(x)); using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(serialization))) { var root = XElement.Load(memStream); return ReadXmlRecursive(root, knowedTypesDict); } } public static TItem Clone<TItem>(TItem item, IEnumerable<Type> knowedTypes) { return (TItem)Clone((object)item, knowedTypes); } public static object Clone(object item, IEnumerable<Type> knowedTypes) { var s = Serialize(item); var result = Unserialize(s, knowedTypes); return result; } //private static Dictionary<string, Type> knowedTypes = null; public static bool IsSimpleType(Type type) { return type.IsEnum || type.Namespace == "System"; } /* private static void <API key>(Assembly assembly) { var typesList = assembly .GetExportedTypes() .Where(t => t.GetCustomAttributes(true).Any(attr => attr is <API key>)) .Where(t => !t.IsGenericType) .Distinct() .ToList(); var arraysTypes = typesList .Where(t => t.IsEnum) .Select(t => Array.CreateInstance(t, 0).GetType()) .ToList(); typesList.AddRange(arraysTypes); foreach (var type in typesList) { var typeName = <API key>(type); if (!_knowedTypes.ContainsKey(typeName)) _knowedTypes.Add(typeName, type); } }*/ /* private static void CreateKnowedTypes() { if (_knowedTypes == null) { _knowedTypes = new Dictionary<string, Type>(); <API key>(typeof(SerializationHelper).Assembly); } }*/ private static void Indent(StringBuilder sb, int indentation) { for (int i = 0; i < indentation; i++) sb.Append(" "); } private static string <API key>(Type type) { var dataContractAttr = (<API key>)type.GetCustomAttributes(typeof(<API key>), true).FirstOrDefault(); string typeName; if (dataContractAttr != null && !string.IsNullOrWhiteSpace(dataContractAttr.Name)) { typeName = dataContractAttr.Name; } else typeName = type.Name; return typeName; } private static string GetTypeName(Type type) { string result; var genericArgs = type.GetGenericArguments(); if (genericArgs.Length == 0) result = type.Name; else { result = type.Name; var i = result.IndexOf("`"); result = result.Substring(0, i) + "_" + genericArgs.Select(t => t.Name).Aggregate((s1, s2) => s1 + "_" + s2); } return result; } private static void <API key>(object element, string propName, int indentation, StringBuilder sb) { if (element != null) { var indent = new String(' ', indentation * 3); var elementType = element.GetType(); var hasPropName = !string.IsNullOrWhiteSpace(propName); if (hasPropName) { sb.AppendLine(); Indent(sb, indentation); sb.Append(string.Format("<{0}>", propName)); } if (typeof(IList).IsAssignableFrom(elementType)) { bool root = sb.Length == 0; if (root) { sb.AppendLine("<" + GetTypeName(element.GetType()) + ">"); indentation++; } var children = (IList)element; foreach (var child in children) { if (child != null) { if (IsSimpleType(child.GetType())) { sb.AppendLine(); Indent(sb, indentation + 1); sb.Append(child.ToString()); } else <API key>(child, null, indentation + 1, sb); } } if (root) { indentation sb.AppendLine(""); sb.AppendLine("</" + GetTypeName(element.GetType()) + ">"); } } else { var typeName = <API key>(elementType); if (hasPropName) indentation++; sb.AppendLine(); Indent(sb, indentation); sb.Append(string.Format("<{0}", typeName)); var dataMembers = elementType.GetProperties() .Select(p => new { Prop = p, Attribute = p.GetCustomAttributes(typeof(DataMemberAttribute), true).FirstOrDefault() }) .Where(x => x.Attribute != null) .ToList(); var simpleDataMembers = dataMembers.Where(x => IsSimpleType(x.Prop.PropertyType)).ToList(); foreach (var member in simpleDataMembers) { var memberValue = member.Prop.GetValue(element, null); if (memberValue != null && !(member.Prop.PropertyType.IsValueType && memberValue.Equals(Activator.CreateInstance(member.Prop.PropertyType)))) { sb.Append(string.Format(" {0}=\"{1}\"", member.Prop.Name, memberValue.ToString())); } dataMembers.Remove(member); } if (dataMembers.Count == 0) sb.Append(string.Format(" />", typeName)); else { sb.Append(string.Format(">", typeName)); foreach (var member in dataMembers) <API key>(member.Prop.GetValue(element, null), member.Prop.Name, indentation + 1, sb); sb.AppendLine(); Indent(sb, indentation); sb.Append(string.Format("</{0}>", typeName)); } if (hasPropName) indentation } if (hasPropName) { sb.AppendLine(); Indent(sb, indentation); sb.Append(string.Format("</{0}>", propName)); } } } public static object ChangeType(string value, Type conversionType) { object result; if (conversionType.IsEnum) result = Enum.Parse(conversionType, value); else result = Convert.ChangeType(value, conversionType); return result; } private static object ReadXmlRecursive(XElement element, Dictionary<string, Type> knowedTypes) { object result = null; Type type; if (element.Name.LocalName.StartsWith("<API key>")) { var generics = element.Name.LocalName.Split('_'); var genType = knowedTypes[generics[1]]; type = typeof(<API key><>).MakeGenericType(new Type[] { genType }); } else type = knowedTypes.ContainsKey(element.Name.LocalName) ? knowedTypes[element.Name.LocalName] : null; if (type != null) { //var type = ; result = Activator.CreateInstance(type); foreach (var attribute in element.Attributes()) { var prop = type.GetProperty(attribute.Name.LocalName); if (prop != null && prop.CanWrite) { var value = string.IsNullOrWhiteSpace(attribute.Value) ? null : ChangeType(attribute.Value, ReflectionHelper.GetNullableType(prop.PropertyType) ?? prop.PropertyType); prop.SetValue(result, value, null); } } foreach (var childNode in element.Elements()) { var prop = type.GetProperty(childNode.Name.LocalName); if (prop != null && prop.CanWrite) { if (typeof(IList).IsAssignableFrom(prop.PropertyType)) { IList list = null; var listElementType = prop.PropertyType.IsGenericType ? prop.PropertyType.GetGenericArguments()[0] : typeof(string); if (IsSimpleType(listElementType)) { list = (IList)Activator.CreateInstance(prop.PropertyType); var rows = childNode.Value.Split('\n').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToList(); rows.ForEach(x => list.Add(ChangeType(x, listElementType))); } else { foreach (var itemElement in childNode.Elements()) { if (list == null) { list = (IList)Activator.CreateInstance(prop.PropertyType); } var item = ReadXmlRecursive(itemElement, knowedTypes); if (item != null) list.Add(item); } } prop.SetValue(result, list, null); } else { var firstChild = childNode.Elements().FirstOrDefault(); if (firstChild != null) { var value = ReadXmlRecursive(firstChild, knowedTypes); prop.SetValue(result, value, null); } } } } } return result; } } }
package eu.siacs.conversations.entities; import android.annotation.SuppressLint; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Field; import eu.siacs.conversations.xmpp.jid.InvalidJidException; import eu.siacs.conversations.xmpp.jid.Jid; import eu.siacs.conversations.xmpp.pep.Avatar; @SuppressLint("DefaultLocale") public class MucOptions { private boolean <API key> = true; public Account getAccount() { return this.conversation.getAccount(); } public void setSelf(User user) { this.self = user; } public void changeAffiliation(Jid jid, Affiliation affiliation) { User user = findUserByRealJid(jid); synchronized (users) { if (user != null && user.getRole() == Role.NONE) { users.remove(user); if (affiliation.ranks(Affiliation.MEMBER)) { user.affiliation = affiliation; users.add(user); } } } } public void <API key>() { <API key> = false; } public boolean <API key>() { return <API key>; } public boolean isSelf(Jid counterpart) { return counterpart.getResourcepart().equals(getActualNick()); } public void resetChatState() { synchronized (users) { for(User user : users) { user.chatState = Config.DEFAULT_CHATSTATE; } } } public enum Affiliation { OWNER("owner", 4, R.string.owner), ADMIN("admin", 3, R.string.admin), MEMBER("member", 2, R.string.member), OUTCAST("outcast", 0, R.string.outcast), NONE("none", 1, R.string.no_affiliation); Affiliation(String string, int rank, int resId) { this.string = string; this.resId = resId; this.rank = rank; } private String string; private int resId; private int rank; public int getResId() { return resId; } @Override public String toString() { return this.string; } public boolean outranks(Affiliation affiliation) { return rank > affiliation.rank; } public boolean ranks(Affiliation affiliation) { return rank >= affiliation.rank; } } public enum Role { MODERATOR("moderator", R.string.moderator,3), VISITOR("visitor", R.string.visitor,1), PARTICIPANT("participant", R.string.participant,2), NONE("none", R.string.no_role,0); Role(String string, int resId, int rank) { this.string = string; this.resId = resId; this.rank = rank; } private String string; private int resId; private int rank; public int getResId() { return resId; } @Override public String toString() { return this.string; } public boolean ranks(Role role) { return rank >= role.rank; } } public enum Error { NO_RESPONSE, SERVER_NOT_FOUND, NONE, NICK_IN_USE, PASSWORD_REQUIRED, BANNED, MEMBERS_ONLY, KICKED, SHUTDOWN, UNKNOWN } public static final String <API key> = "110"; public static final String <API key> = "201"; public static final String STATUS_CODE_BANNED = "301"; public static final String <API key> = "303"; public static final String STATUS_CODE_KICKED = "307"; public static final String <API key> = "321"; public static final String <API key> = "322"; public static final String <API key> = "332"; private interface OnEventListener { void onSuccess(); void onFailure(); } public interface OnRenameListener extends OnEventListener { } public static class User implements Comparable<User> { private Role role = Role.NONE; private Affiliation affiliation = Affiliation.NONE; private Jid realJid; private Jid fullJid; private long pgpKeyId = 0; private Avatar avatar; private MucOptions options; private ChatState chatState = Config.DEFAULT_CHATSTATE; public User(MucOptions options, Jid from) { this.options = options; this.fullJid = from; } public String getName() { return fullJid == null ? null : fullJid.getResourcepart(); } public void setRealJid(Jid jid) { this.realJid = jid != null ? jid.toBareJid() : null; } public Role getRole() { return this.role; } public void setRole(String role) { if (role == null) { this.role = Role.NONE; return; } role = role.toLowerCase(); switch (role) { case "moderator": this.role = Role.MODERATOR; break; case "participant": this.role = Role.PARTICIPANT; break; case "visitor": this.role = Role.VISITOR; break; default: this.role = Role.NONE; break; } } public Affiliation getAffiliation() { return this.affiliation; } public void setAffiliation(String affiliation) { if (affiliation == null) { this.affiliation = Affiliation.NONE; return; } affiliation = affiliation.toLowerCase(); switch (affiliation) { case "admin": this.affiliation = Affiliation.ADMIN; break; case "owner": this.affiliation = Affiliation.OWNER; break; case "member": this.affiliation = Affiliation.MEMBER; break; case "outcast": this.affiliation = Affiliation.OUTCAST; break; default: this.affiliation = Affiliation.NONE; } } public void setPgpKeyId(long id) { this.pgpKeyId = id; } public long getPgpKeyId() { if (this.pgpKeyId != 0) { return this.pgpKeyId; } else if (realJid != null) { return getAccount().getRoster().getContact(realJid).getPgpKeyId(); } else { return 0; } } public Contact getContact() { if (fullJid != null) { return getAccount().getRoster().<API key>(realJid); } else if (realJid != null){ return getAccount().getRoster().getContact(realJid); } else { return null; } } public boolean setAvatar(Avatar avatar) { if (this.avatar != null && this.avatar.equals(avatar)) { return false; } else { this.avatar = avatar; return true; } } public String getAvatar() { return avatar == null ? null : avatar.getFilename(); } public Account getAccount() { return options.getAccount(); } public Jid getFullJid() { return fullJid; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (role != user.role) return false; if (affiliation != user.affiliation) return false; if (realJid != null ? !realJid.equals(user.realJid) : user.realJid != null) return false; return fullJid != null ? fullJid.equals(user.fullJid) : user.fullJid == null; } @Override public int hashCode() { int result = role != null ? role.hashCode() : 0; result = 31 * result + (affiliation != null ? affiliation.hashCode() : 0); result = 31 * result + (realJid != null ? realJid.hashCode() : 0); result = 31 * result + (fullJid != null ? fullJid.hashCode() : 0); return result; } @Override public String toString() { return "[fulljid:"+String.valueOf(fullJid)+",realjid:"+String.valueOf(realJid)+",affiliation"+affiliation.toString()+"]"; } public boolean <API key>() { return realJid != null && realJid.equals(options.account.getJid().toBareJid()); } @Override public int compareTo(User another) { if (another.getAffiliation().outranks(getAffiliation())) { return 1; } else if (getAffiliation().outranks(another.getAffiliation())) { return -1; } else { return getComparableName().compareToIgnoreCase(another.getComparableName()); } } private String getComparableName() { Contact contact = getContact(); if (contact != null) { return contact.getDisplayName(); } else { String name = getName(); return name == null ? "" : name; } } public Jid getRealJid() { return realJid; } public boolean setChatState(ChatState chatState) { if (this.chatState == chatState) { return false; } this.chatState = chatState; return true; } } private Account account; private final Set<User> users = new HashSet<>(); private final List<String> features = new ArrayList<>(); private Data form = new Data(); private Conversation conversation; private boolean isOnline = false; private Error error = Error.NONE; public OnRenameListener onRenameListener = null; private User self; private String subject = null; private String password = null; public MucOptions(Conversation conversation) { this.account = conversation.getAccount(); this.conversation = conversation; this.self = new User(this,createJoinJid(getProposedNick())); } public void updateFeatures(ArrayList<String> features) { this.features.clear(); this.features.addAll(features); } public void updateFormData(Data form) { this.form = form; } public boolean hasFeature(String feature) { return this.features.contains(feature); } public boolean canInvite() { Field field = this.form.getFieldByName("muc#<API key>"); return !membersOnly() || self.getRole().ranks(Role.MODERATOR) || (field != null && "1".equals(field.getValue())); } public boolean canChangeSubject() { Field field = this.form.getFieldByName("muc#<API key>"); return self.getRole().ranks(Role.MODERATOR) || (field != null && "1".equals(field.getValue())); } public boolean participating() { return !online() || self.getRole().ranks(Role.PARTICIPANT) || hasFeature("muc_unmoderated"); } public boolean membersOnly() { return hasFeature("muc_membersonly"); } public boolean mamSupport() { return hasFeature(Namespace.MAM) || hasFeature(Namespace.MAM_LEGACY); } public boolean mamLegacy() { return hasFeature(Namespace.MAM_LEGACY) && !hasFeature(Namespace.MAM); } public boolean nonanonymous() { return hasFeature("muc_nonanonymous"); } public boolean persistent() { return hasFeature("muc_persistent"); } public boolean moderated() { return hasFeature("muc_moderated"); } public User deleteUser(Jid jid) { User user = findUserByFullJid(jid); if (user != null) { synchronized (users) { users.remove(user); boolean realJidInMuc = false; for (User u : users) { if (user.realJid != null && user.realJid.equals(u.realJid)) { realJidInMuc = true; break; } } boolean self = user.realJid != null && user.realJid.equals(account.getJid().toBareJid()); if (membersOnly() && nonanonymous() && user.affiliation.ranks(Affiliation.MEMBER) && user.realJid != null && !realJidInMuc && !self) { user.role = Role.NONE; user.avatar = null; user.fullJid = null; users.add(user); } } } return user; } //returns true if real jid was new; public boolean updateUser(User user) { User old; boolean realJidFound = false; if (user.fullJid == null && user.realJid != null) { old = findUserByRealJid(user.realJid); realJidFound = old != null; if (old != null) { if (old.fullJid != null) { return false; //don't add. user already exists } else { synchronized (users) { users.remove(old); } } } } else if (user.realJid != null) { old = findUserByRealJid(user.realJid); realJidFound = old != null; synchronized (users) { if (old != null && old.fullJid == null) { users.remove(old); } } } old = findUserByFullJid(user.getFullJid()); synchronized (this.users) { if (old != null) { users.remove(old); } boolean fullJidIsSelf = isOnline && user.getFullJid() != null && user.getFullJid().equals(self.getFullJid()); if ((!membersOnly() || user.getAffiliation().ranks(Affiliation.MEMBER)) && user.getAffiliation().outranks(Affiliation.OUTCAST) && !fullJidIsSelf){ this.users.add(user); return !realJidFound && user.realJid != null; } } return false; } public User findUserByFullJid(Jid jid) { if (jid == null) { return null; } synchronized (users) { for (User user : users) { if (jid.equals(user.getFullJid())) { return user; } } } return null; } private User findUserByRealJid(Jid jid) { if (jid == null) { return null; } synchronized (users) { for (User user : users) { if (jid.equals(user.realJid)) { return user; } } } return null; } public boolean isContactInRoom(Contact contact) { return findUserByRealJid(contact.getJid().toBareJid()) != null; } public boolean isUserInRoom(Jid jid) { return findUserByFullJid(jid) != null; } public void setError(Error error) { this.isOnline = isOnline && error == Error.NONE; this.error = error; } public void setOnline() { this.isOnline = true; } public ArrayList<User> getUsers() { return getUsers(true); } public ArrayList<User> getUsers(boolean includeOffline) { synchronized (users) { if (includeOffline) { return new ArrayList<>(users); } else { ArrayList<User> onlineUsers = new ArrayList<>(); for (User user : users) { if (user.getRole().ranks(Role.PARTICIPANT)) { onlineUsers.add(user); } } return onlineUsers; } } } public ArrayList<User> <API key>(ChatState state, int max) { synchronized (users) { ArrayList<User> list = new ArrayList<>(); for(User user : users) { if (user.chatState == state) { list.add(user); if (list.size() >= max) { break; } } } return list; } } public List<User> getUsers(int max) { ArrayList<User> subset = new ArrayList<>(); HashSet<Jid> jids = new HashSet<>(); jids.add(account.getJid().toBareJid()); synchronized (users) { for(User user : users) { if (user.getRealJid() == null || jids.add(user.getRealJid())) { subset.add(user); } if (subset.size() >= max) { break; } } } return subset; } public int getUserCount() { synchronized (users) { return users.size(); } } public String getProposedNick() { if (conversation.getBookmark() != null && conversation.getBookmark().getNick() != null && !conversation.getBookmark().getNick().trim().isEmpty()) { return conversation.getBookmark().getNick().trim(); } else if (!conversation.getJid().isBareJid()) { return conversation.getJid().getResourcepart(); } else { return account.getUsername(); } } public String getActualNick() { if (this.self.getName() != null) { return this.self.getName(); } else { return this.getProposedNick(); } } public boolean online() { return this.isOnline; } public Error getError() { return this.error; } public void setOnRenameListener(OnRenameListener listener) { this.onRenameListener = listener; } public void setOffline() { synchronized (users) { this.users.clear(); } this.error = Error.NO_RESPONSE; this.isOnline = false; } public User getSelf() { return self; } public void setSubject(String content) { this.subject = content; } public String getSubject() { return this.subject; } public String <API key>() { if (getUserCount() >= 2) { StringBuilder builder = new StringBuilder(); for (User user : getUsers(5)) { if (builder.length() != 0) { builder.append(", "); } Contact contact = user.getContact(); if (contact != null && !contact.getDisplayName().isEmpty()) { builder.append(contact.getDisplayName().split("\\s+")[0]); } else { final String name = user.getName(); final Jid jid = user.getRealJid(); if (name != null){ builder.append(name.split("\\s+")[0]); } else if (jid != null) { builder.append(jid.getLocalpart()); } } } return builder.toString(); } else { return null; } } public long[] getPgpKeyIds() { List<Long> ids = new ArrayList<>(); for (User user : this.users) { if (user.getPgpKeyId() != 0) { ids.add(user.getPgpKeyId()); } } ids.add(account.getPgpId()); long[] primitiveLongArray = new long[ids.size()]; for (int i = 0; i < ids.size(); ++i) { primitiveLongArray[i] = ids.get(i); } return primitiveLongArray; } public boolean pgpKeysInUse() { synchronized (users) { for (User user : users) { if (user.getPgpKeyId() != 0) { return true; } } } return false; } public boolean everybodyHasKeys() { synchronized (users) { for (User user : users) { if (user.getPgpKeyId() == 0) { return false; } } } return true; } public Jid createJoinJid(String nick) { try { return Jid.fromString(this.conversation.getJid().toBareJid().toString() + "/" + nick); } catch (final InvalidJidException e) { return null; } } public Jid getTrueCounterpart(Jid jid) { if (jid.equals(getSelf().getFullJid())) { return account.getJid().toBareJid(); } User user = findUserByFullJid(jid); return user == null ? null : user.realJid; } public String getPassword() { this.password = conversation.getAttribute(Conversation.<API key>); if (this.password == null && conversation.getBookmark() != null && conversation.getBookmark().getPassword() != null) { return conversation.getBookmark().getPassword(); } else { return this.password; } } public void setPassword(String password) { if (conversation.getBookmark() != null) { conversation.getBookmark().setPassword(password); } else { this.password = password; } conversation.setAttribute(Conversation.<API key>, password); } public Conversation getConversation() { return this.conversation; } public List<Jid> getMembers() { ArrayList<Jid> members = new ArrayList<>(); synchronized (users) { for (User user : users) { if (user.affiliation.ranks(Affiliation.MEMBER) && user.realJid != null) { members.add(user.realJid); } } } return members; } }
#ifndef writePatchGraph_H #define writePatchGraph_H #include "volFieldsFwd.H" namespace Foam { void writePatchGraph ( const volScalarField& vsf, const label patchLabel, const direction d, const word& graphFormat ); } // End namespace Foam #endif
using System; using System.Linq; using System.Xml; using System.Xml.Linq; using SatIp.DiscoverySample.Logging; namespace SatIp.DiscoverySample.Upnp { <summary> </summary> public class SatIpDevice { #region Private Fields private Uri _baseUrl; private string _deviceType = ""; private string _friendlyName = ""; private string _manufacturer = ""; private string _manufacturerUrl = ""; private string _modelDescription = ""; private string _modelName = ""; private string _modelNumber = ""; private string _modelUrl = ""; private string _serialNumber = ""; private string _uniqueDeviceName = ""; private string _presentationUrl = ""; private string _deviceDescription; private SatIpDeviceIcon[] _iconList = new SatIpDeviceIcon[4]; private string _capabilities = ""; private string _m3u = ""; private bool _supportsDVBC; private bool _supportsDVBS; private bool _supportsDVBT; #endregion #region Constructor <summary> Default constructor. </summary> <param name="url">Device URL.</param> internal SatIpDevice(string url) { if (url == null) { throw new <API key>("url"); } Init(new Uri(url)); } #endregion #region Methods <summary> </summary> <param name="index"></param> <returns></returns> public string GetImage(int index) { var icon = (SatIpDeviceIcon)_iconList.GetValue(index); return icon.Url; } <summary> </summary> <param name="locationUri"></param> private void Init(Uri locationUri) { try { Logger.Info("the Description Url is {0}", locationUri); BaseUrl = locationUri; var document = XDocument.Load(locationUri.AbsoluteUri); var xnm= new XmlNamespaceManager(new NameTable()); XNamespace n1 = "urn:ses-com:satip"; XNamespace n0 = "urn:schemas-upnp-org:device-1-0"; xnm.AddNamespace("root", n0.NamespaceName); xnm.AddNamespace("satip:",n1.NamespaceName); if (document.Root != null) { var deviceElement = document.Root.Element(n0 + "device"); _deviceDescription = document.Declaration + document.ToString(); Logger.Info("The Description has this Content \r\n{0}",_deviceDescription); if (deviceElement != null) { var devicetypeElement = deviceElement.Element(n0 + "deviceType"); if (devicetypeElement != null) _deviceType = devicetypeElement.Value; var friendlynameElement = deviceElement.Element(n0 + "friendlyName"); if (friendlynameElement != null) _friendlyName = friendlynameElement.Value; var manufactureElement = deviceElement.Element(n0 + "manufacturer"); if (manufactureElement != null) _manufacturer = manufactureElement.Value; var <API key> = deviceElement.Element(n0 + "manufacturerURL"); if (<API key> != null) _manufacturerUrl = <API key>.Value; var <API key> = deviceElement.Element(n0 + "modelDescription"); if (<API key> != null) _modelDescription = <API key>.Value; var modelnameElement = deviceElement.Element(n0 + "modelName"); if (modelnameElement != null) _modelName = modelnameElement.Value; var modelnumberElement = deviceElement.Element(n0 + "modelNumber"); if (modelnumberElement != null) _modelNumber = modelnumberElement.Value; var modelurlElement = deviceElement.Element(n0 + "modelURL"); if (modelurlElement != null) _modelUrl = modelurlElement.Value; var serialnumberElement = deviceElement.Element(n0 + "serialNumber"); if (serialnumberElement != null) _serialNumber = serialnumberElement.Value; var <API key> = deviceElement.Element(n0 + "UDN"); if (<API key> != null) _uniqueDeviceName = <API key>.Value; var iconList = deviceElement.Element(n0 + "iconList"); if (iconList != null) { var icons = from query in iconList.Descendants(n0 + "icon") select new SatIpDeviceIcon { // Needed to change mimeType to mimetype. XML is case sensitive MimeType = (string) query.Element(n0 + "mimetype"), Url = (string) query.Element(n0 + "url"), Height = (int) query.Element(n0 + "height"), Width = (int) query.Element(n0 + "width"), Depth = (int) query.Element(n0 + "depth"), }; _iconList = icons.ToArray(); } var <API key> = deviceElement.Element(n0 + "presentationURL"); if (<API key> != null) { if(<API key>.Value.StartsWith("Http; _presentationUrl=<API key>.Value; _presentationUrl = locationUri.Scheme + "://" + locationUri.Host; } if (<API key>==null) { _presentationUrl = locationUri.Scheme + "://" + locationUri.Host; } var capabilitiesElement = deviceElement.Element(n1 + "X_SATIPCAP"); if (capabilitiesElement != null) { _capabilities = capabilitiesElement.Value; if (capabilitiesElement.Value.Contains(',')) { string[] capabilities = capabilitiesElement.Value.Split(','); foreach (var capability in capabilities) { ReadCapability(capability); } } else { ReadCapability(capabilitiesElement.Value); } } else { _supportsDVBS = true; //ToDo Create only one Digital Recorder / Capture Instance here } var m3uElement = deviceElement.Element(n1 + "X_SATIPM3U"); if (m3uElement != null) _m3u = locationUri.Scheme + "://" + locationUri.Host + ":" + locationUri.Port + m3uElement.Value; } } } catch (Exception exception) { Logger.Error("It give a Problem with the Description {0}", exception); } } <summary> </summary> <param name="capability"></param> private void ReadCapability(string capability) { string[] cap = capability.Split('-'); switch (cap[0].ToLower()) { case "dvbs": case "dvbs2": { // Optional that you know what an device Supports can you add an flag _supportsDVBS = true; for (int i = 0; i < int.Parse(cap[1]); i++) { //ToDo Create Digital Recorder / Capture Instance here } break; } case "dvbc": case "dvbc2": { // Optional that you know what an device Supports can you add an flag _supportsDVBC = true; for (int i = 0; i < int.Parse(cap[1]); i++) { //ToDo Create Digital Recorder / Capture Instance here } break; } case "dvbt": case "dvbt2": { // Optional that you know what an device Supports can you add an flag _supportsDVBT = true; for (int i = 0; i < int.Parse(cap[1]); i++) { //ToDo Create Digital Recorder / Capture Instance here } break; } } } #endregion #region Proeprties <summary> Gets device type. </summary> public string DeviceType { get{ return _deviceType; } } <summary> Gets device short name. </summary> public string FriendlyName { get{ return _friendlyName; } } <summary> Gets manufacturer's name. </summary> public string Manufacturer { get{ return _manufacturer; } } <summary> Gets web site for Manufacturer. </summary> public string ManufacturerUrl { get{ return _manufacturerUrl; } } <summary> Gets device long description. </summary> public string ModelDescription { get{ return _modelDescription; } } <summary> Gets model name. </summary> public string ModelName { get{ return _modelName; } } <summary> Gets model number. </summary> public string ModelNumber { get{ return _modelNumber; } } <summary> Gets web site for model. </summary> public string ModelUrl { get{ return _modelUrl; } } <summary> Gets serial number. </summary> public string SerialNumber { get{ return _serialNumber; } } <summary> Gets unique device name. </summary> public string UniqueDeviceName { get{ return _uniqueDeviceName; } } <summary> Gets device UI url. </summary> public string PresentationUrl { get{ return _presentationUrl; } } <summary> Gets UPnP device XML description. </summary> public string DeviceDescription { get{ return _deviceDescription; } } <summary> </summary> public Uri BaseUrl { get { return _baseUrl; } set { _baseUrl = value; } } <summary> </summary> public string M3U { get { return _m3u; } set { _m3u = value; } } <summary> </summary> public string Capabilities { get { return _capabilities; } set { _capabilities = value; } } <summary> </summary> public bool SupportsDVBC { get { return _supportsDVBC; } set { _supportsDVBC = value; } } <summary> </summary> public bool SupportsDVBS { get { return _supportsDVBS; } set { _supportsDVBS = value; } } <summary> </summary> public bool SupportsDVBT { get { return _supportsDVBT; } set { _supportsDVBT = value; } } #endregion } <summary> </summary> public class SatIpDeviceIcon { <summary> </summary> public SatIpDeviceIcon() { Url = ""; MimeType = ""; } <summary> </summary> public int Depth { get; set; } <summary> </summary> public int Height { get; set; } <summary> </summary> public int Width { get; set; } <summary> </summary> public string MimeType { get; set; } <summary> </summary> public string Url { get; set; } } }
package br.com.fiap.excecoes; public class Excecoes extends Exception { private static final long serialVersionUID = 1L; public Excecoes(String message, Exception e) { super(message, e); if (e.getClass().toString().equals("class java.lang.<API key>")) { System.out.println("Número inválido."); } else if (e.getClass().toString().equals("class java.lang.ArithmeticException")) { System.out.println("Divisão por 0"); } else { System.out.println(e.getClass().toString()); } this.print(); e.printStackTrace(); } public Excecoes(String message) { System.out.println(message); } public void print() { System.out.println(getMessage()); System.out.println("PrintStackTrace: "); } }
<?php /*%%SmartyHeaderCode:<API key>%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '<SHA1-like>' => array ( 0 => '/Users/Evergreen/Documents/workspace/licpresta/themes/default-bootstrap/modules/blockwishlist/blockwishlist-ajax.tpl', 1 => 1452095428, 2 => 'file', ), ), 'nocache_hash' => '<API key>', 'function' => array ( ), 'variables' => array ( 'products' => 0, 'product' => 0, 'link' => 0, 'error' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.19', 'unifunc' => '<API key>', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('<API key>')) {function <API key>($_smarty_tpl) {?> <?php if ($_smarty_tpl->tpl_vars['products']->value) {?> <dl class="products"> <?php $_smarty_tpl->tpl_vars['product'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['product']->_loop = false; $_from = $_smarty_tpl->tpl_vars['products']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} $_smarty_tpl->tpl_vars['product']->total= $_smarty_tpl->_count($_from); $_smarty_tpl->tpl_vars['product']->iteration=0; $_smarty_tpl->tpl_vars['product']->index=-1; foreach ($_from as $_smarty_tpl->tpl_vars['product']->key => $_smarty_tpl->tpl_vars['product']->value) { $_smarty_tpl->tpl_vars['product']->_loop = true; $_smarty_tpl->tpl_vars['product']->iteration++; $_smarty_tpl->tpl_vars['product']->index++; $_smarty_tpl->tpl_vars['product']->first = $_smarty_tpl->tpl_vars['product']->index === 0; $_smarty_tpl->tpl_vars['product']->last = $_smarty_tpl->tpl_vars['product']->iteration === $_smarty_tpl->tpl_vars['product']->total; $_smarty_tpl->tpl_vars['smarty']->value['foreach']['i']['first'] = $_smarty_tpl->tpl_vars['product']->first; $_smarty_tpl->tpl_vars['smarty']->value['foreach']['i']['last'] = $_smarty_tpl->tpl_vars['product']->last; ?> <dt class="<?php if ($_smarty_tpl->getVariable('smarty')->value['foreach']['i']['first']) {?>first_item<?php } elseif ($_smarty_tpl->getVariable('smarty')->value['foreach']['i']['last']) {?>last_item<?php } else { ?>item<?php }?>"> <span class="quantity-formated"> <span class="quantity"><?php echo intval($_smarty_tpl->tpl_vars['product']->value['quantity']);?> </span>x </span> <a class="<API key>" href="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getProductLink($_smarty_tpl->tpl_vars['product']->value['id_product'],$_smarty_tpl->tpl_vars['product']->value['link_rewrite'],$_smarty_tpl->tpl_vars['product']->value['category_rewrite']), ENT_QUOTES, 'UTF-8', true);?> " title="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['product']->value['name'], ENT_QUOTES, 'UTF-8', true);?> "> <?php echo htmlspecialchars($_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['truncate'][0][0]-><API key>($_smarty_tpl->tpl_vars['product']->value['name'],13,'...'), ENT_QUOTES, 'UTF-8', true);?> </a> <a class="<API key>" href="javascript:;" onclick="javascript:WishlistCart('wishlist_block_list', 'delete', '<?php echo $_smarty_tpl->tpl_vars['product']->value['id_product'];?> ', <?php echo $_smarty_tpl->tpl_vars['product']->value['<API key>'];?> , '0');" rel="nofollow" title="<?php echo smartyTranslate(array('s'=>'remove this product from my wishlist','mod'=>'blockwishlist'),$_smarty_tpl);?> "> <i class="icon-remove-sign"></i> </a> </dt> <?php if (isset($_smarty_tpl->tpl_vars['product']->value['attributes_small'])) {?> <dd class="<?php if ($_smarty_tpl->getVariable('smarty')->value['foreach']['i']['first']) {?>first_item<?php } elseif ($_smarty_tpl->getVariable('smarty')->value['foreach']['i']['last']) {?>last_item<?php } else { ?>item<?php }?>"> <a href="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getProductLink($_smarty_tpl->tpl_vars['product']->value['id_product'],$_smarty_tpl->tpl_vars['product']->value['link_rewrite']), ENT_QUOTES, 'UTF-8', true);?> " title="<?php echo smartyTranslate(array('s'=>'Product detail','mod'=>'blockwishlist'),$_smarty_tpl);?> "> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['product']->value['attributes_small'], ENT_QUOTES, 'UTF-8', true);?> </a> </dd> <?php }?> <?php } ?> </dl> <?php } else { ?> <dl class="products no-products"> <?php if (isset($_smarty_tpl->tpl_vars['error']->value)&&$_smarty_tpl->tpl_vars['error']->value) {?> <dt><?php echo smartyTranslate(array('s'=>'You must create a wishlist before adding products','mod'=>'blockwishlist'),$_smarty_tpl);?> </dt> <?php } else { ?> <dt><?php echo smartyTranslate(array('s'=>'No products','mod'=>'blockwishlist'),$_smarty_tpl);?> </dt> <?php }?> </dl> <?php }?><?php }} ?>
#!/usr/bin/env bash # Changing to working directory cd $(dirname "$0") source ../config.sh # Temp paths and files VERSION="stable" export SRC_PKG="http://${VERSION}.release.core-os.net/amd64-usr/current/<API key>.vmlinuz" export SRC_PKG2="http://${VERSION}.release.core-os.net/amd64-usr/current/<API key>.cpio.gz" export TRG_NME="coreos-stable" # FIXME export TRG_PKG="vmlinuz" export TRG_PKG2="cpio.gz" # Download syslinux and deploy it . ./common/download.sh TRG_PATH=$TFTP_PATH/boot/$TRG_NME [ ! -d $TRG_PATH ] && mkdir $TRG_PATH -p cp -r $TMP/$TRG_PKG $TFTP_PATH/boot/$TRG_NME cp -r $TMP/$TRG_PKG2 $TFTP_PATH/boot/$TRG_NME # Clean . ./common/clean.sh
#!/bin/bash #script for scripts to covertly get the mysql root password source ~/setup_aws.conf.sh echo "$MYSQL_ROOT_PW" exit 0
package org.jboss.pressgang.ccms.provider; import org.jboss.pressgang.ccms.rest.v1.collections.<API key>; import org.jboss.pressgang.ccms.rest.v1.entities.RESTBlobConstantV1; import org.jboss.pressgang.ccms.wrapper.BlobConstantWrapper; import org.jboss.pressgang.ccms.wrapper.<API key>; import org.jboss.pressgang.ccms.wrapper.collection.CollectionWrapper; import org.jboss.pressgang.ccms.wrapper.collection.<API key>; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class <API key> extends RESTDataProvider implements <API key> { private static Logger log = LoggerFactory.getLogger(<API key>.class); public <API key>(final RESTProviderFactory providerFactory) { super(providerFactory); } protected RESTBlobConstantV1 loadBlobConstant(Integer id, Integer revision, final String expandString) { if (revision == null) { return getRESTClient().getJSONBlobConstant(id, expandString); } else { return getRESTClient().<API key>(id, revision, expandString); } } public RESTBlobConstantV1 getRESTBlobConstant(int id) { return getRESTBlobConstant(id, null); } @Override public BlobConstantWrapper getBlobConstant(int id) { return getBlobConstant(id, null); } public RESTBlobConstantV1 getRESTBlobConstant(int id, Integer revision) { try { final RESTBlobConstantV1 blobConstant; if (getRESTEntityCache().containsKeyValue(RESTBlobConstantV1.class, id, revision)) { blobConstant = getRESTEntityCache().get(RESTBlobConstantV1.class, id, revision); } else { blobConstant = loadBlobConstant(id, revision, ""); getRESTEntityCache().add(blobConstant, revision); } return blobConstant; } catch (Exception e) { log.debug("Failed to retrieve Blob Constant " + id + (revision == null ? "" : (", Revision " + revision)), e); throw handleException(e); } } @Override public BlobConstantWrapper getBlobConstant(int id, Integer revision) { return <API key>.newBuilder() .providerFactory(getProviderFactory()) .entity(getRESTBlobConstant(id, revision)) .isRevision(revision != null) .build(); } public byte[] <API key>(int id, Integer revision) { try { RESTBlobConstantV1 blobConstant = null; if (getRESTEntityCache().containsKeyValue(RESTBlobConstantV1.class, id, revision)) { blobConstant = getRESTEntityCache().get(RESTBlobConstantV1.class, id, revision); // check if the cached copy has the value if (blobConstant.getValue() != null) { return blobConstant.getValue(); } } // We need to expand the value in the blobconstant final String expandString = getExpansionString(RESTBlobConstantV1.VALUE_NAME); // Load the blob constant from the REST Interface final RESTBlobConstantV1 tempBlobConstant = loadBlobConstant(id, revision, expandString); // If the Blob Constant has been saved, or has been evicted then re-add it to the cache. if (blobConstant == null) { blobConstant = tempBlobConstant; getRESTEntityCache().add(blobConstant, revision); } else { blobConstant.setValue(tempBlobConstant.getValue()); } return blobConstant.getValue(); } catch (Exception e) { log.debug("Failed to retrieve Blob Constant " + id + (revision == null ? "" : (", Revision " + revision)), e); throw handleException(e); } } public <API key> <API key>(int id, Integer revision) { try { RESTBlobConstantV1 blobConstant = null; // Check the cache first if (getRESTEntityCache().containsKeyValue(RESTBlobConstantV1.class, id, revision)) { blobConstant = getRESTEntityCache().get(RESTBlobConstantV1.class, id, revision); if (blobConstant.getRevisions() != null) { return blobConstant.getRevisions(); } } // We need to expand the revisions in the blob constant collection final String expandString = getExpansionString(RESTBlobConstantV1.REVISIONS_NAME); // Load the blob constant from the REST Interface final RESTBlobConstantV1 tempBlobConstant = loadBlobConstant(id, revision, expandString); if (blobConstant == null) { blobConstant = tempBlobConstant; getRESTEntityCache().add(blobConstant, revision); } else { blobConstant.setRevisions(tempBlobConstant.getRevisions()); } return blobConstant.getRevisions(); } catch (Exception e) { log.debug("Failed to retrieve the Revisions for Blob Constant " + id + (revision == null ? "" : (", Revision " + revision)), e); throw handleException(e); } } @Override public CollectionWrapper<BlobConstantWrapper> <API key>(int id, Integer revision) { return <API key>.<BlobConstantWrapper>newBuilder() .providerFactory(getProviderFactory()) .collection(<API key>(id, revision)) .<API key>() .build(); } }
#include "Item.h" std::string GetItemTitleForType(ItemType type) { switch (type) { case ItemType::None: { return "None"; } // Dropped item in the world case ItemType::DroppedItem: { return "Dropped Item"; } // Hearts and coins dropped from killing enemies case ItemType::Coin: { return "Coin"; } case ItemType::Heart: { return "Heart"; } // Zombie gib case ItemType::Gib: { return "Gib"; } // Interact items case ItemType::Tombstone: { return "Tombstone"; } case ItemType::Chest: { return "Chest"; } case ItemType::Torch: { return "Torch"; } case ItemType::Furnace: { return "Furnace"; } case ItemType::Anvil: { return "Anvil"; } case ItemType::QuestBoard: { return "Quest Board"; } case ItemType::CampFire: { return "Camp Fire"; } case ItemType::Mannequin: { return "Mannequin"; } // Ingredients case ItemType::SlimeJelly: { return "Slime Jelly"; } case ItemType::BeeWing: { return "Bee Wing"; } case ItemType::Bone: { return "Bone"; } // Ore and mining case ItemType::CopperVein: { return "Copper Vein"; } case ItemType::CopperOre: { return "Copper Ore"; } case ItemType::CopperBar: { return "Copper Bar"; } case ItemType::IronVein: { return "Iron Vein"; } case ItemType::IronOre: { return "Iron Ore"; } case ItemType::IronBar: { return "Iron Bar"; } case ItemType::SilverVein: { return "Silver Vein"; } case ItemType::SilverOre: { return "Silver Ore"; } case ItemType::SilverBar: { return "Silver Bar"; } case ItemType::GoldVein: { return "Gold Vein"; } case ItemType::GoldOre: { return "Gold Ore"; } case ItemType::GoldBar: { return "Gold Bar"; } // World blocks case ItemType::BlockGrass: { return "Grass Block"; } case ItemType::BlockDirt: { return "Dirt Block"; } case ItemType::BlockStone: { return "Stone Block"; } case ItemType::BlockWood: { return "Wood Block"; } case ItemType::BlockLeaf: { return "Leaf Block"; } case ItemType::BlockSand: { return "Sand Block"; } case ItemType::BlockCactus: { return "Cactus Block"; } case ItemType::BlockRock: { return "Rock Block"; } case ItemType::BlockSnow: { return "Snow Block"; } case ItemType::NUM_ITEMS: throw std::logic_error("Invalid ItemType!"); default: throw std::logic_error("Invalid ItemType!"); } } std::string <API key>(ItemType type) { switch (type) { case ItemType::None: { return "None"; } // Dropped item in the world case ItemType::DroppedItem: { return "Dropped Item"; } // Hearts and coins dropped from killing enemies case ItemType::Coin: { return "Coin"; } case ItemType::Heart: { return "Heart"; } // Zombie gib case ItemType::Gib: { return "Gib"; } // Interact items case ItemType::Tombstone: { return "Tombstone"; } case ItemType::Chest: { return "Chest"; } case ItemType::Torch: { return "Torch"; } case ItemType::Furnace: { return "Furnace"; } case ItemType::Anvil: { return "Anvil"; } case ItemType::QuestBoard: { return "Quest Board"; } case ItemType::CampFire: { return "Camp Fire"; } case ItemType::Mannequin: { return "A wooden mannequin, used for storing armor sets."; } // Ingredients case ItemType::SlimeJelly: { return "Jelly from a slime monster."; } case ItemType::BeeWing: { return "A wing from a bee."; } case ItemType::Bone: { return "A raw bone from a skeleton."; } // Ore and mining case ItemType::CopperVein: { return "Copper Vein"; } case ItemType::CopperOre: { return "A nugget of copper ore. Can be smelted down at a furnace to create copper bars."; } case ItemType::CopperBar: { return "A solid bar of copper, used for crafting items made out of copper."; } case ItemType::IronVein: { return "Iron Vein"; } case ItemType::IronOre: { return "A nugget of iron ore. Can be smelted down at a furnace to create iron bars."; } case ItemType::IronBar: { return "A solid bar of iron, used for crafting items made out of iron."; } case ItemType::SilverVein: { return "Silver Vein"; } case ItemType::SilverOre: { return "A nugget of silver ore. Can be smelted down at a furnace to create silver bars."; } case ItemType::SilverBar: { return "A solid bar of silver, used for crafting items made out of silver."; } case ItemType::GoldVein: { return "Gold Vein"; } case ItemType::GoldOre: { return "A nugget of gold ore. Can be smelted down at a furnace to create gold bars."; } case ItemType::GoldBar: { return "A solid bar of gold, used for crafting items made out of gold."; } // World blocks case ItemType::BlockGrass: { return "Grass block for world building."; } case ItemType::BlockDirt: { return "Dirt block for world building."; } case ItemType::BlockStone: { return "Stone block for world building."; } case ItemType::BlockWood: { return "Wood block for world building."; } case ItemType::BlockLeaf: { return "Leaf block for world building."; } case ItemType::BlockSand: { return "Sand block for world building."; } case ItemType::BlockCactus: { return "Cactus block for world building."; } case ItemType::BlockRock: { return "Rock block for world building."; } case ItemType::BlockSnow: { return "Snow block for world building."; } case ItemType::NUM_ITEMS: throw std::logic_error("Invalid ItemType!"); default: throw std::logic_error("Invalid ItemType!"); } } std::string <API key>(ItemType type) { switch (type) { case ItemType::None: { return ""; } // Dropped item in the world case ItemType::DroppedItem: { return ""; } // Hearts and coins dropped from killing enemies case ItemType::Coin: { return "Resources/gamedata/items/Coin/Coin.item"; } case ItemType::Heart: { return "Resources/gamedata/items/Heart/Heart.item"; } // Zombie gib case ItemType::Gib: { return "Resources/gamedata/items/Hand1Gib.item"; } // Interact items case ItemType::Tombstone: { return "Resources/gamedata/items/Tombstone/Tombstone1.item"; } case ItemType::Chest: { return "Resources/gamedata/items/Chest/Chest.item"; } case ItemType::Torch: { return "Resources/gamedata/items/Torch/Torch.item"; } case ItemType::Furnace: { return "Resources/gamedata/items/Furnace/Furnace.item"; } case ItemType::Anvil: { return "Resources/gamedata/items/Anvil/Anvil.item"; } case ItemType::QuestBoard: { return "Resources/gamedata/items/QuestBoard/QuestBoard.item"; } case ItemType::CampFire: { return "Resources/gamedata/items/CampFire/CampFire.item"; } case ItemType::Mannequin: { return "Resources/gamedata/items/Mannequin/Mannequin.item"; } // Ingredients case ItemType::SlimeJelly: { return "Resources/gamedata/items/SlimeJelly/SlimeJelly.item"; } case ItemType::BeeWing: { return "Resources/gamedata/items/BeeWing/BeeWing.item"; } case ItemType::Bone: { return "Resources/gamedata/items/Bone/Bone.item"; } // Ore and mining case ItemType::CopperVein: { return "Resources/gamedata/items/CopperVein/CopperVein0.item"; } case ItemType::CopperOre: { return "Resources/gamedata/items/CopperOre/CopperOre.item"; } case ItemType::CopperBar: { return "Resources/gamedata/items/CopperBar/CopperBar.item"; } case ItemType::IronVein: { return "Resources/gamedata/items/IronVein/IronVein0.item"; } case ItemType::IronOre: { return "Resources/gamedata/items/IronOre/IronOre.item"; } case ItemType::IronBar: { return "Resources/gamedata/items/IronBar/IronBar.item"; } case ItemType::SilverVein: { return "Resources/gamedata/items/SilverVein/SilverVein0.item"; } case ItemType::SilverOre: { return "Resources/gamedata/items/SilverOre/SilverOre.item"; } case ItemType::SilverBar: { return "Resources/gamedata/items/SilverBar/SilverBar.item"; } case ItemType::GoldVein: { return "Resources/gamedata/items/GoldVein/GoldVein0.item"; } case ItemType::GoldOre: { return "Resources/gamedata/items/GoldOre/GoldOre.item"; } case ItemType::GoldBar: { return "Resources/gamedata/items/GoldBar/GoldBar.item"; } // World blocks case ItemType::BlockGrass: { return "Resources/gamedata/items/Block_Grass/Block_Grass.item"; } case ItemType::BlockDirt: { return "Resources/gamedata/items/Block_Dirt/Block_Dirt.item"; } case ItemType::BlockStone: { return "Resources/gamedata/items/Block_Stone/Block_Stone.item"; } case ItemType::BlockWood: { return "Resources/gamedata/items/Block_Wood/Block_Wood.item"; } case ItemType::BlockLeaf: { return "Resources/gamedata/items/Block_Leaf/Block_Leaf.item"; } case ItemType::BlockSand: { return "Resources/gamedata/items/Block_Sand/Block_Sand.item"; } case ItemType::BlockCactus: { return "Resources/gamedata/items/Block_Cactus/Block_Cactus.item"; } case ItemType::BlockRock: { return "Resources/gamedata/items/Block_Rock/Block_Rock.item"; } case ItemType::BlockSnow: { return "Resources/gamedata/items/Block_Snow/Block_Snow.item"; } case ItemType::NUM_ITEMS: throw std::logic_error("Invalid ItemType!"); default: throw std::logic_error("Invalid ItemType!"); } } std::string <API key>(ItemType type) { switch (type) { case ItemType::None: { return ""; } // Dropped item in the world case ItemType::DroppedItem: { return ""; } // Hearts and coins dropped from killing enemies case ItemType::Coin: { return "Resources/textures/items/coin.tga"; } case ItemType::Heart: { return "Resources/textures/items/heart.tga"; } // Zombie gib case ItemType::Gib: { return "Resources/textures/items/question_mark.tga"; } // Interact items case ItemType::Tombstone: { return "Resources/textures/items/tombstone.tga"; } case ItemType::Chest: { return "Resources/textures/items/chest.tga"; } case ItemType::Torch: { return "Resources/textures/items/torch.tga"; } case ItemType::Furnace: { return "Resources/textures/items/furnace.tga"; } case ItemType::Anvil: { return "Resources/textures/items/anvil.tga"; } case ItemType::QuestBoard: { return "Resources/textures/items/quest_board.tga"; } case ItemType::CampFire: { return "Resources/textures/items/camp_fire.tga"; } case ItemType::Mannequin: { return "Resources/textures/items/mannequin.tga"; } // Ingredients case ItemType::SlimeJelly: { return "Resources/textures/items/slime_jelly.tga"; } case ItemType::BeeWing: { return "Resources/textures/items/bee_wing.tga"; } case ItemType::Bone: { return "Resources/textures/items/bone.tga"; } // Ore and mining case ItemType::CopperVein: { return "Resources/textures/items/question_mark.tga"; } case ItemType::CopperOre: { return "Resources/textures/items/copper_ore.tga"; } case ItemType::CopperBar: { return "Resources/textures/items/copper_bar.tga"; } case ItemType::IronVein: { return "Resources/textures/items/question_mark.tga"; } case ItemType::IronOre: { return "Resources/textures/items/iron_ore.tga"; } case ItemType::IronBar: { return "Resources/textures/items/iron_bar.tga"; } case ItemType::SilverVein: { return "Resources/textures/items/question_mark.tga"; } case ItemType::SilverOre: { return "Resources/textures/items/silver_ore.tga"; } case ItemType::SilverBar: { return "Resources/textures/items/silver_bar.tga"; } case ItemType::GoldVein: { return "Resources/textures/items/question_mark.tga"; } case ItemType::GoldOre: { return "Resources/textures/items/gold_ore.tga"; } case ItemType::GoldBar: { return "Resources/textures/items/gold_bar.tga"; } // World blocks case ItemType::BlockGrass: { return "Resources/textures/items/block_grass.tga"; } case ItemType::BlockDirt: { return "Resources/textures/items/block_dirt.tga"; } case ItemType::BlockStone: { return "Resources/textures/items/block_stone.tga"; } case ItemType::BlockWood: { return "Resources/textures/items/block_wood.tga"; } case ItemType::BlockLeaf: { return "Resources/textures/items/block_leaf.tga"; } case ItemType::BlockSand: { return "Resources/textures/items/block_sand.tga"; } case ItemType::BlockCactus: { return "Resources/textures/items/block_cactus.tga"; } case ItemType::BlockRock: { return "Resources/textures/items/block_rock.tga"; } case ItemType::BlockSnow: { return "Resources/textures/items/block_snow.tga"; } case ItemType::NUM_ITEMS: throw std::logic_error("Invalid ItemType!"); default: throw std::logic_error("Invalid ItemType!"); } } float <API key>(ItemType type) { switch (type) { case ItemType::None: { return 1.00f; } // Dropped item in the world case ItemType::DroppedItem: { return 0.50f; } // Hearts and coins dropped from killing enemies case ItemType::Coin: { return 0.25f; } case ItemType::Heart: { return 0.25f; } // Zombie gib case ItemType::Gib: { return 0.125f; } // Interact items case ItemType::Tombstone: { return 0.50f; } case ItemType::Chest: { return 0.50f; } case ItemType::Torch: { return 1.00f; } case ItemType::Furnace: { return 0.50f; } case ItemType::Anvil: { return 0.50f; } case ItemType::QuestBoard: { return 1.00f; } case ItemType::CampFire: { return 0.50f; } case ItemType::Mannequin: { return 1.00f; } // Ingredients case ItemType::SlimeJelly: { return 0.25f; } case ItemType::BeeWing: { return 0.25f; } case ItemType::Bone: { return 0.25f; } // Ore and mining case ItemType::CopperVein: { return 0.50f; } case ItemType::CopperOre: { return 0.25f; } case ItemType::CopperBar: { return 0.25f; } case ItemType::IronVein: { return 0.50f; } case ItemType::IronOre: { return 0.25f; } case ItemType::IronBar: { return 0.25f; } case ItemType::SilverVein: { return 0.50f; } case ItemType::SilverOre: { return 0.25f; } case ItemType::SilverBar: { return 0.25f; } case ItemType::GoldVein: { return 0.5f; } case ItemType::GoldOre: { return 0.25f; } case ItemType::GoldBar: { return 0.25f; } // World blocks case ItemType::BlockGrass: { return 0.25f; } case ItemType::BlockDirt: { return 0.25f; } case ItemType::BlockStone: { return 0.25f; } case ItemType::BlockWood: { return 0.25f; } case ItemType::BlockLeaf: { return 0.25f; } case ItemType::BlockSand: { return 0.25f; } case ItemType::BlockCactus: { return 0.25f; } case ItemType::BlockRock: { return 0.25f; } case ItemType::BlockSnow: { return 0.25f; } case ItemType::NUM_ITEMS: throw std::logic_error("Invalid ItemType!"); default: throw std::logic_error("Invalid ItemType!"); } }
#include <iomanip> #include <sigc++/slot.h> #include "tonecurve.h" #include "adjuster.h" #include "eventmapper.h" #include "ppversion.h" #include "../rtengine/procparams.h" #include "editcallbacks.h" using namespace rtengine; using namespace rtengine::procparams; ToneCurve::ToneCurve () : FoldableToolPanel(this, "tonecurve", M("TP_EXPOSURE_LABEL")) { auto m = ProcEventMapper::getInstance(); EvHistMatching = m->newEvent(AUTOEXP, "<API key>"); EvHistMatchingBatch = m->newEvent(M_VOID, "<API key>"); EvClampOOG = m->newEvent(DARKFRAME, "<API key>"); CurveListener::setMulti(true); std::vector<GradientMilestone> bottomMilestones; bottomMilestones.push_back( GradientMilestone(0., 0., 0., 0.) ); bottomMilestones.push_back( GradientMilestone(1., 1., 1., 1.) ); clampOOG = Gtk::manage(new Gtk::CheckButton(M("<API key>"))); pack_start(*clampOOG); pack_start (*Gtk::manage (new Gtk::HSeparator())); clampOOG->signal_toggled().connect(sigc::mem_fun(*this, &ToneCurve::clampOOGChanged)); abox = Gtk::manage (new Gtk::HBox ()); abox->set_spacing (4); autolevels = Gtk::manage (new Gtk::ToggleButton (M("<API key>"))); autolevels->set_tooltip_markup (M("<API key>")); autoconn = autolevels->signal_toggled().connect( sigc::mem_fun(*this, &ToneCurve::autolevels_toggled) ); lclip = Gtk::manage (new Gtk::Label (M("TP_EXPOSURE_CLIP"))); lclip->set_tooltip_text (M("<API key>")); sclip = Gtk::manage (new MySpinButton ()); sclip->set_range (0.0, 0.99); sclip->set_increments (0.01, 0.10); sclip->set_value (0.02); sclip->set_digits (2); sclip->set_width_chars(4); sclip->set_max_width_chars(4); sclip-><API key>().connect( sigc::mem_fun(*this, &ToneCurve::clip_changed) ); neutral = Gtk::manage (new Gtk::Button (M("TP_NEUTRAL"))); neutral->set_tooltip_text (M("TP_NEUTRAL_TIP")); neutralconn = neutral->signal_pressed().connect( sigc::mem_fun(*this, &ToneCurve::neutral_pressed) ); neutral->show(); abox->pack_start (*autolevels, true, true, 0); // pack_end is used for these controls as autolevels is replaceable using pack_start in batchmode abox->pack_end (*neutral, true, true, 0); abox->pack_end (*sclip, false, false, 0); abox->pack_end (*lclip, false, false, 0); pack_start (*abox); pack_start (*Gtk::manage (new Gtk::HSeparator())); hrenabled = Gtk::manage (new Gtk::CheckButton (M("TP_HLREC_LABEL"))); hrenabled->set_active (false); hrenabled->set_tooltip_markup (M("<API key>")); pack_start (*hrenabled); method = Gtk::manage (new MyComboBoxText ()); method->append (M("TP_HLREC_LUMINANCE")); method->append (M("TP_HLREC_CIELAB")); method->append (M("TP_HLREC_COLOR")); method->append (M("TP_HLREC_BLEND")); method->set_active (0); hlrbox = Gtk::manage (new Gtk::HBox ()); Gtk::Label* lab = Gtk::manage (new Gtk::Label (M("TP_HLREC_METHOD"))); hlrbox->pack_start (*lab, Gtk::PACK_SHRINK, 4); hlrbox->pack_start (*method); pack_start (*hlrbox); enaconn = hrenabled->signal_toggled().connect( sigc::mem_fun(*this, &ToneCurve::hrenabledChanged) ); methconn = method->signal_changed().connect ( sigc::mem_fun(*this, &ToneCurve::methodChanged) ); pack_start (*Gtk::manage (new Gtk::HSeparator())); expcomp = Gtk::manage (new Adjuster (M("TP_EXPOSURE_EXPCOMP"), -5, 12, 0.05, 0)); expcomp->setLogScale(2, 0, true); pack_start (*expcomp); hlcompr = Gtk::manage (new Adjuster (M("<API key>"), 0, 500, 1, 0)); pack_start (*hlcompr); hlcomprthresh = Gtk::manage (new Adjuster (M("<API key>"), 0, 100, 1, 0)); pack_start (*hlcomprthresh); black = Gtk::manage (new Adjuster (M("<API key>"), -16384, 32768, 50, 0)); black->setLogScale(10, 0, true); pack_start (*black); shcompr = Gtk::manage (new Adjuster (M("<API key>"), 0, 100, 1, 50)); pack_start (*shcompr); pack_start (*Gtk::manage (new Gtk::HSeparator())); brightness = Gtk::manage (new Adjuster (M("<API key>"), -100, 100, 1, 0)); pack_start (*brightness); contrast = Gtk::manage (new Adjuster (M("<API key>"), -100, 100, 1, 0)); pack_start (*contrast); saturation = Gtk::manage (new Adjuster (M("<API key>"), -100, 100, 1, 0)); pack_start (*saturation); brightness->setLogScale(2, 0, true); contrast->setLogScale(2, 0, true); saturation->setLogScale(2, 0, true); pack_start (*Gtk::manage (new Gtk::HSeparator())); histmatching = Gtk::manage(new Gtk::ToggleButton(M("<API key>"))); histmatching->set_tooltip_markup(M("<API key>")); histmatchconn = histmatching->signal_toggled().connect(sigc::mem_fun(*this, &ToneCurve::histmatchingToggled)); pack_start(*histmatching, true, true, 2); toneCurveMode = Gtk::manage (new MyComboBoxText ()); toneCurveMode->append (M("<API key>")); toneCurveMode->append (M("<API key>")); toneCurveMode->append (M("<API key>")); toneCurveMode->append (M("<API key>")); toneCurveMode->append (M("<API key>")); toneCurveMode->append (M("<API key>")); toneCurveMode->set_active (0); toneCurveMode->set_tooltip_text(M("<API key>")); curveEditorG = new CurveEditorGroup (options.lastToneCurvesDir, M("<API key>")); curveEditorG->setCurveListener (this); shape = static_cast<DiagonalCurveEditor*>(curveEditorG->addCurve(CT_Diagonal, "", toneCurveMode)); shape->setEditID(EUID_ToneCurve1, BT_IMAGEFLOAT); shape-><API key>(bottomMilestones); shape-><API key>(bottomMilestones); // This will add the reset button at the end of the curveType buttons curveEditorG->curveListComplete(); pack_start( *curveEditorG, Gtk::PACK_SHRINK, 2); tcmodeconn = toneCurveMode->signal_changed().connect( sigc::mem_fun(*this, &ToneCurve::curveMode1Changed), true ); toneCurveMode2 = Gtk::manage (new MyComboBoxText ()); toneCurveMode2->append (M("<API key>")); toneCurveMode2->append (M("<API key>")); toneCurveMode2->append (M("<API key>")); toneCurveMode2->append (M("<API key>")); toneCurveMode2->append (M("<API key>")); toneCurveMode2->append (M("<API key>")); toneCurveMode2->set_active (0); toneCurveMode2->set_tooltip_text(M("<API key>")); curveEditorG2 = new CurveEditorGroup (options.lastToneCurvesDir, M("<API key>")); curveEditorG2->setCurveListener (this); shape2 = static_cast<DiagonalCurveEditor*>(curveEditorG2->addCurve(CT_Diagonal, "", toneCurveMode2)); shape2->setEditID(EUID_ToneCurve2, BT_IMAGEFLOAT); shape2-><API key>(bottomMilestones); shape2-><API key>(bottomMilestones); // This will add the reset button at the end of the curveType buttons curveEditorG2->curveListComplete(); curveEditorG2->setTooltip(M("<API key>")); pack_start( *curveEditorG2, Gtk::PACK_SHRINK, 2); tcmode2conn = toneCurveMode2->signal_changed().connect( sigc::mem_fun(*this, &ToneCurve::curveMode2Changed), true ); expcomp->setAdjusterListener (this); brightness->setAdjusterListener (this); black->setAdjusterListener (this); hlcompr->setAdjusterListener (this); hlcomprthresh->setAdjusterListener (this); shcompr->setAdjusterListener (this); contrast->setAdjusterListener (this); saturation->setAdjusterListener (this); } ToneCurve::~ToneCurve () { idle_register.destroy(); delete curveEditorG; delete curveEditorG2; } void ToneCurve::read (const ProcParams* pp, const ParamsEdited* pedited) { disableListener (); tcmodeconn.block(true); tcmode2conn.block(true); autoconn.block (true); autolevels->set_active (pp->toneCurve.autoexp); lastAuto = pp->toneCurve.autoexp; sclip->set_value (pp->toneCurve.clip); expcomp->setValue (pp->toneCurve.expcomp); black->setValue (pp->toneCurve.black); hlcompr->setValue (pp->toneCurve.hlcompr); hlcomprthresh->setValue (pp->toneCurve.hlcomprthresh); shcompr->setValue (pp->toneCurve.shcompr); if (!black->getAddMode() && !batchMode) { shcompr->set_sensitive(!((int)black->getValue () == 0)); //at black=0 shcompr value has no effect } if (!hlcompr->getAddMode() && !batchMode) { hlcomprthresh->set_sensitive(!((int)hlcompr->getValue () == 0)); //at hlcompr=0 hlcomprthresh value has no effect } brightness->setValue (pp->toneCurve.brightness); contrast->setValue (pp->toneCurve.contrast); saturation->setValue (pp->toneCurve.saturation); shape->setCurve (pp->toneCurve.curve); shape2->setCurve (pp->toneCurve.curve2); toneCurveMode->set_active(rtengine::toUnderlying(pp->toneCurve.curveMode)); toneCurveMode2->set_active(rtengine::toUnderlying(pp->toneCurve.curveMode2)); histmatching->set_active(pp->toneCurve.histmatching); fromHistMatching = pp->toneCurve.fromHistMatching; clampOOG->set_active(pp->toneCurve.clampOOG); if (pedited) { expcomp->setEditedState (pedited->toneCurve.expcomp ? Edited : UnEdited); black->setEditedState (pedited->toneCurve.black ? Edited : UnEdited); hlcompr->setEditedState (pedited->toneCurve.hlcompr ? Edited : UnEdited); hlcomprthresh->setEditedState (pedited->toneCurve.hlcomprthresh ? Edited : UnEdited); shcompr->setEditedState (pedited->toneCurve.shcompr ? Edited : UnEdited); brightness->setEditedState (pedited->toneCurve.brightness ? Edited : UnEdited); contrast->setEditedState (pedited->toneCurve.contrast ? Edited : UnEdited); saturation->setEditedState (pedited->toneCurve.saturation ? Edited : UnEdited); autolevels->set_inconsistent (!pedited->toneCurve.autoexp); clipDirty = pedited->toneCurve.clip; shape->setUnChanged (!pedited->toneCurve.curve); shape2->setUnChanged (!pedited->toneCurve.curve2); hrenabled->set_inconsistent (!pedited->toneCurve.hrenabled); if (!pedited->toneCurve.curveMode) { toneCurveMode->set_active(6); } if (!pedited->toneCurve.curveMode2) { toneCurveMode2->set_active(6); } histmatching->set_inconsistent(!pedited->toneCurve.histmatching); clampOOG->set_inconsistent(!pedited->toneCurve.clampOOG); } enaconn.block (true); hrenabled->set_active (pp->toneCurve.hrenabled); enaconn.block (false); if (pedited && !pedited->toneCurve.method) { method->set_active (4); } else if (pp->toneCurve.method == "Luminance") { method->set_active (0); } else if (pp->toneCurve.method == "CIELab blending") { method->set_active (1); } else if (pp->toneCurve.method == "Color") { method->set_active (2); } else if (pp->toneCurve.method == "Blend") { method->set_active (3); } if (!batchMode) { if (hrenabled->get_active()) { hlrbox->show(); } else { hlrbox->hide(); } } lasthrEnabled = pp->toneCurve.hrenabled; autoconn.block (false); tcmode2conn.block(false); tcmodeconn.block(false); enableListener (); } void ToneCurve::autoOpenCurve () { shape->openIfNonlinear(); shape2->openIfNonlinear(); } void ToneCurve::setEditProvider (EditDataProvider *provider) { shape->setEditProvider(provider); shape2->setEditProvider(provider); } void ToneCurve::write (ProcParams* pp, ParamsEdited* pedited) { pp->toneCurve.autoexp = autolevels->get_active(); pp->toneCurve.clip = sclip->get_value (); pp->toneCurve.expcomp = expcomp->getValue (); pp->toneCurve.black = (int)black->getValue (); pp->toneCurve.hlcompr = (int)hlcompr->getValue (); pp->toneCurve.hlcomprthresh = (int)hlcomprthresh->getValue (); pp->toneCurve.shcompr = (int)shcompr->getValue (); pp->toneCurve.brightness = (int)brightness->getValue (); pp->toneCurve.contrast = (int)contrast->getValue (); pp->toneCurve.saturation = (int)saturation->getValue (); pp->toneCurve.curve = shape->getCurve (); pp->toneCurve.curve2 = shape2->getCurve (); int tcMode = toneCurveMode-><API key>(); if (tcMode == 0) { pp->toneCurve.curveMode = ToneCurveMode::STD; } else if (tcMode == 1) { pp->toneCurve.curveMode = ToneCurveMode::WEIGHTEDSTD; } else if (tcMode == 2) { pp->toneCurve.curveMode = ToneCurveMode::FILMLIKE; } else if (tcMode == 3) { pp->toneCurve.curveMode = ToneCurveMode::SATANDVALBLENDING; } else if (tcMode == 4) { pp->toneCurve.curveMode = ToneCurveMode::LUMINANCE; } else if (tcMode == 5) { pp->toneCurve.curveMode = ToneCurveMode::PERCEPTUAL; } tcMode = toneCurveMode2-><API key>(); if (tcMode == 0) { pp->toneCurve.curveMode2 = ToneCurveMode::STD; } else if (tcMode == 1) { pp->toneCurve.curveMode2 = ToneCurveMode::WEIGHTEDSTD; } else if (tcMode == 2) { pp->toneCurve.curveMode2 = ToneCurveMode::FILMLIKE; } else if (tcMode == 3) { pp->toneCurve.curveMode2 = ToneCurveMode::SATANDVALBLENDING; } else if (tcMode == 4) { pp->toneCurve.curveMode2 = ToneCurveMode::LUMINANCE; } else if (tcMode == 5) { pp->toneCurve.curveMode2 = ToneCurveMode::PERCEPTUAL; } pp->toneCurve.histmatching = histmatching->get_active(); pp->toneCurve.fromHistMatching = fromHistMatching; pp->toneCurve.clampOOG = clampOOG->get_active(); if (pedited) { pedited->toneCurve.expcomp = expcomp->getEditedState (); pedited->toneCurve.black = black->getEditedState (); pedited->toneCurve.hlcompr = hlcompr->getEditedState (); pedited->toneCurve.hlcomprthresh = hlcomprthresh->getEditedState (); pedited->toneCurve.shcompr = shcompr->getEditedState (); pedited->toneCurve.brightness = brightness->getEditedState (); pedited->toneCurve.contrast = contrast->getEditedState (); pedited->toneCurve.saturation = saturation->getEditedState (); pedited->toneCurve.autoexp = !autolevels->get_inconsistent(); pedited->toneCurve.clip = clipDirty; pedited->toneCurve.curve = !shape->isUnChanged (); pedited->toneCurve.curve2 = !shape2->isUnChanged (); pedited->toneCurve.curveMode = toneCurveMode-><API key>() != 6; pedited->toneCurve.curveMode2 = toneCurveMode2-><API key>() != 6; pedited->toneCurve.method = method-><API key>() != 4; pedited->toneCurve.hrenabled = !hrenabled->get_inconsistent(); pedited->toneCurve.histmatching = !histmatching->get_inconsistent(); pedited->toneCurve.fromHistMatching = true; pedited->toneCurve.clampOOG = !clampOOG->get_inconsistent(); } pp->toneCurve.hrenabled = hrenabled->get_active(); if (method-><API key>() == 0) { pp->toneCurve.method = "Luminance"; } else if (method-><API key>() == 1) { pp->toneCurve.method = "CIELab blending"; } else if (method-><API key>() == 2) { pp->toneCurve.method = "Color"; } else if (method-><API key>() == 3) { pp->toneCurve.method = "Blend"; } } void ToneCurve::hrenabledChanged () { if (multiImage) { if (hrenabled->get_inconsistent()) { hrenabled->set_inconsistent (false); enaconn.block (true); hrenabled->set_active (false); enaconn.block (false); } else if (lasthrEnabled) { hrenabled->set_inconsistent (true); } lasthrEnabled = hrenabled->get_active (); } if (!batchMode) { if (hrenabled->get_active()) { hlrbox->show(); } else { hlrbox->hide(); } } if (listener) { // Switch off auto exposure if user changes enabled manually if (autolevels->get_active() ) { autoconn.block(true); autolevels->set_active (false); autoconn.block(false); autolevels->set_inconsistent (false); } setHistmatching(false); if (hrenabled->get_active ()) { listener->panelChanged (EvHREnabled, M("GENERAL_ENABLED")); } else { listener->panelChanged (EvHREnabled, M("GENERAL_DISABLED")); } } } void ToneCurve::methodChanged () { if (listener) { setHistmatching(false); if (hrenabled->get_active ()) { listener->panelChanged (EvHRMethod, method->get_active_text ()); } } } void ToneCurve::clampOOGChanged() { if (listener) { listener->panelChanged(EvClampOOG, clampOOG->get_active() ? M("GENERAL_ENABLED") : M("GENERAL_DISABLED")); } } void ToneCurve::setRaw (bool raw) { disableListener (); method->set_sensitive (raw); hrenabled->set_sensitive (raw); histmatching->set_sensitive(raw); enableListener (); } void ToneCurve::setDefaults (const ProcParams* defParams, const ParamsEdited* pedited) { expcomp->setDefault (defParams->toneCurve.expcomp); brightness->setDefault (defParams->toneCurve.brightness); black->setDefault (defParams->toneCurve.black); hlcompr->setDefault (defParams->toneCurve.hlcompr); hlcomprthresh->setDefault (defParams->toneCurve.hlcomprthresh); shcompr->setDefault (defParams->toneCurve.shcompr); contrast->setDefault (defParams->toneCurve.contrast); saturation->setDefault (defParams->toneCurve.saturation); if (pedited) { expcomp-><API key> (pedited->toneCurve.expcomp ? Edited : UnEdited); black-><API key> (pedited->toneCurve.black ? Edited : UnEdited); hlcompr-><API key> (pedited->toneCurve.hlcompr ? Edited : UnEdited); hlcomprthresh-><API key> (pedited->toneCurve.hlcomprthresh ? Edited : UnEdited); shcompr-><API key> (pedited->toneCurve.shcompr ? Edited : UnEdited); brightness-><API key> (pedited->toneCurve.brightness ? Edited : UnEdited); contrast-><API key> (pedited->toneCurve.contrast ? Edited : UnEdited); saturation-><API key> (pedited->toneCurve.saturation ? Edited : UnEdited); } else { expcomp-><API key> (Irrelevant); black-><API key> (Irrelevant); hlcompr-><API key> (Irrelevant); hlcomprthresh-><API key> (Irrelevant); shcompr-><API key> (Irrelevant); brightness-><API key> (Irrelevant); contrast-><API key> (Irrelevant); saturation-><API key> (Irrelevant); } } void ToneCurve::curveChanged (CurveEditor* ce) { if (listener) { setHistmatching(false); if (ce == shape) { listener->panelChanged (EvToneCurve1, M("HISTORY_CUSTOMCURVE")); } else if (ce == shape2) { listener->panelChanged (EvToneCurve2, M("HISTORY_CUSTOMCURVE")); } } } void ToneCurve::curveMode1Changed () { //if (listener) listener->panelChanged (EvToneCurveMode, toneCurveMode->get_active_text()); if (listener) { setHistmatching(false); Glib::signal_idle().connect (sigc::mem_fun(*this, &ToneCurve::curveMode1Changed_)); } } bool ToneCurve::curveMode1Changed_ () { if (listener) { listener->panelChanged (EvToneCurveMode1, toneCurveMode->get_active_text()); } return false; } void ToneCurve::curveMode2Changed () { //if (listener) listener->panelChanged (EvToneCurveMode, toneCurveMode->get_active_text()); if (listener) { setHistmatching(false); Glib::signal_idle().connect (sigc::mem_fun(*this, &ToneCurve::curveMode2Changed_)); } } bool ToneCurve::curveMode2Changed_ () { if (listener) { listener->panelChanged (EvToneCurveMode2, toneCurveMode2->get_active_text()); } return false; } float ToneCurve::blendPipetteValues(CurveEditor *ce, float chan1, float chan2, float chan3) { // assuming that all the channels are used... if (ce == shape) { if (toneCurveMode-><API key>() == 4) { return chan1 * 0.2126729f + chan2 * 0.7151521f + chan3 * 0.0721750f; } } else if (ce == shape2) { if (toneCurveMode2-><API key>() == 4) { return chan1 * 0.2126729f + chan2 * 0.7151521f + chan3 * 0.0721750f; } } return CurveListener::blendPipetteValues(ce, chan1, chan2, chan3); } void ToneCurve::adjusterChanged(Adjuster* a, double newval) { // Switch off auto exposure if user changes sliders manually if (autolevels->get_active() && (a == expcomp || a == brightness || a == contrast || a == black || a == hlcompr || a == hlcomprthresh)) { autoconn.block(true); autolevels->set_active (false); autoconn.block(false); autolevels->set_inconsistent (false); } if (!listener) { return; } if (a != expcomp && a != hlcompr && a != hlcomprthresh) { setHistmatching(false); } Glib::ustring costr; if (a == expcomp) { costr = Glib::ustring::format (std::setw(3), std::fixed, std::setprecision(2), a->getValue()); } else { costr = Glib::ustring::format ((int)a->getValue()); } if (a == expcomp) { listener->panelChanged (EvExpComp, costr); } else if (a == brightness) { listener->panelChanged (EvBrightness, costr); } else if (a == black) { listener->panelChanged (EvBlack, costr); if (!black->getAddMode() && !batchMode) { shcompr->set_sensitive(!((int)black->getValue () == 0)); //at black=0 shcompr value has no effect } } else if (a == contrast) { listener->panelChanged (EvContrast, costr); } else if (a == saturation) { listener->panelChanged (EvSaturation, costr); } else if (a == hlcompr) { listener->panelChanged (EvHLCompr, costr); if (!hlcompr->getAddMode() && !batchMode) { hlcomprthresh->set_sensitive(!((int)hlcompr->getValue () == 0)); //at hlcompr=0 hlcomprthresh value has no effect } } else if (a == hlcomprthresh) { listener->panelChanged (EvHLComprThreshold, costr); } else if (a == shcompr) { listener->panelChanged (EvSHCompr, costr); } } void ToneCurve::adjusterAutoToggled(Adjuster* a, bool newval) { } void ToneCurve::neutral_pressed () { // This method deselects auto levels and HL reconstruction auto // and sets neutral values to params in exposure panel setHistmatching(false); if (batchMode) { autolevels->set_inconsistent (false); autoconn.block (true); autolevels->set_active (false); autoconn.block (false); lastAuto = autolevels->get_active (); } else { //!batchMode autolevels->set_active (false); autolevels->set_inconsistent (false); } expcomp->setValue(0); hlcompr->setValue(0); hlcomprthresh->setValue(0); brightness->setValue(0); black->setValue(0); shcompr->setValue(50); enaconn.block (true); hrenabled->set_active (false); enaconn.block (false); if (!batchMode) { hlrbox->hide(); } if (!black->getAddMode() && !batchMode) { shcompr->set_sensitive(!((int)black->getValue () == 0)); //at black=0 shcompr value has no effect } if (!hlcompr->getAddMode() && !batchMode) { hlcomprthresh->set_sensitive(!((int)hlcompr->getValue () == 0)); //at hlcompr=0 hlcomprthresh value has no effect } contrast->setValue(0); //saturation->setValue(0); listener->panelChanged (EvNeutralExp, M("GENERAL_ENABLED")); } void ToneCurve::autolevels_toggled () { setHistmatching(false); if (batchMode) { if (autolevels->get_inconsistent()) { autolevels->set_inconsistent (false); autoconn.block (true); autolevels->set_active (false); autoconn.block (false); } else if (lastAuto) { autolevels->set_inconsistent (true); } lastAuto = autolevels->get_active (); expcomp->setEditedState (UnEdited); brightness->setEditedState (UnEdited); contrast->setEditedState (UnEdited); black->setEditedState (UnEdited); hlcompr->setEditedState (UnEdited); hlcomprthresh->setEditedState (UnEdited); if (expcomp->getAddMode()) { expcomp->setValue (0); } if (brightness->getAddMode()) { brightness->setValue (0); } if (contrast->getAddMode()) { contrast->setValue (0); } if (black->getAddMode()) { black->setValue (0); } if (hlcompr->getAddMode()) { hlcompr->setValue (0); } if (hlcomprthresh->getAddMode()) { hlcomprthresh->setValue (0); } if (listener) { if (!autolevels->get_inconsistent()) { if (autolevels->get_active ()) { listener->panelChanged (EvAutoExp, M("GENERAL_ENABLED")); } else { listener->panelChanged (EvFixedExp, M("GENERAL_DISABLED")); } } } } else if (/* !batchMode && */ listener) { if (autolevels->get_active()) { listener->panelChanged (EvAutoExp, M("GENERAL_ENABLED")); waitForAutoExp (); if (!black->getAddMode()) { shcompr->set_sensitive(!((int)black->getValue () == 0)); //at black=0 shcompr value has no effect } if (!hlcompr->getAddMode() && !batchMode) { hlcomprthresh->set_sensitive(!((int)hlcompr->getValue () == 0)); //at hlcompr=0 hlcomprthresh value has no effect } } else { listener->panelChanged (EvFixedExp, M("GENERAL_DISABLED")); } } } void ToneCurve::clip_changed () { clipDirty = true; if (autolevels->get_active() && listener) { Glib::signal_idle().connect (sigc::mem_fun(*this, &ToneCurve::clip_changed_)); } } bool ToneCurve::clip_changed_ () { if (listener) { listener->panelChanged (EvClip, Glib::ustring::format (std::setprecision(5), sclip->get_value())); if (!batchMode) { waitForAutoExp (); } } return false; } void ToneCurve::waitForAutoExp () { sclip->set_sensitive (false); expcomp->setEnabled (false); brightness->setEnabled (false); contrast->setEnabled (false); black->setEnabled (false); hlcompr->setEnabled (false); hlcomprthresh->setEnabled (false); shcompr->setEnabled (false); contrast->setEnabled (false); saturation->setEnabled (false); curveEditorG->set_sensitive (false); toneCurveMode->set_sensitive (false); curveEditorG2->set_sensitive (false); toneCurveMode2->set_sensitive (false); hrenabled->set_sensitive(false); method->set_sensitive(false); histmatching->set_sensitive(false); } void ToneCurve::enableAll () { sclip->set_sensitive (true); expcomp->setEnabled (true); brightness->setEnabled (true); black->setEnabled (true); hlcompr->setEnabled (true); hlcomprthresh->setEnabled (true); shcompr->setEnabled (true); contrast->setEnabled (true); saturation->setEnabled (true); curveEditorG->set_sensitive (true); toneCurveMode->set_sensitive (true); curveEditorG2->set_sensitive (true); toneCurveMode2->set_sensitive (true); hrenabled->set_sensitive(true); method->set_sensitive(true); histmatching->set_sensitive(true); } void ToneCurve::setBatchMode (bool batchMode) { ToolPanel::setBatchMode (batchMode); method->append (M("GENERAL_UNCHANGED")); removeIfThere (abox, autolevels, false); autolevels = Gtk::manage (new Gtk::CheckButton (M("<API key>"))); autolevels->set_tooltip_markup (M("<API key>")); autoconn = autolevels->signal_toggled().connect( sigc::mem_fun(*this, &ToneCurve::autolevels_toggled) ); abox->pack_start (*autolevels); ToolPanel::setBatchMode (batchMode); expcomp->showEditedCB (); black->showEditedCB (); hlcompr->showEditedCB (); hlcomprthresh->showEditedCB (); shcompr->showEditedCB (); brightness->showEditedCB (); contrast->showEditedCB (); saturation->showEditedCB (); toneCurveMode->append (M("GENERAL_UNCHANGED")); toneCurveMode2->append (M("GENERAL_UNCHANGED")); curveEditorG->setBatchMode (batchMode); curveEditorG2->setBatchMode (batchMode); } void ToneCurve::setAdjusterBehavior (bool expadd, bool hlcompadd, bool hlcompthreshadd, bool bradd, bool blackadd, bool shcompadd, bool contradd, bool satadd) { expcomp->setAddMode(expadd); hlcompr->setAddMode(hlcompadd); hlcomprthresh->setAddMode(hlcompthreshadd); brightness->setAddMode(bradd); black->setAddMode(blackadd); shcompr->setAddMode(shcompadd); contrast->setAddMode(contradd); saturation->setAddMode(satadd); } void ToneCurve::trimValues (rtengine::procparams::ProcParams* pp) { expcomp->trimValue(pp->toneCurve.expcomp); hlcompr->trimValue(pp->toneCurve.hlcompr); hlcomprthresh->trimValue(pp->toneCurve.hlcomprthresh); brightness->trimValue(pp->toneCurve.brightness); black->trimValue(pp->toneCurve.black); shcompr->trimValue(pp->toneCurve.shcompr); contrast->trimValue(pp->toneCurve.contrast); saturation->trimValue(pp->toneCurve.saturation); } void ToneCurve::<API key>( const LUTu& histToneCurve, const LUTu& histLCurve, const LUTu& histCCurve, const LUTu& histLCAM, const LUTu& histCCAM, const LUTu& histRed, const LUTu& histGreen, const LUTu& histBlue, const LUTu& histLuma, const LUTu& histLRETI ) { shape-><API key>(histToneCurve); } void ToneCurve::setHistmatching(bool enabled) { fromHistMatching = enabled; if (histmatching->get_active()) { histmatchconn.block(true); histmatching->set_active(enabled); histmatchconn.block(false); histmatching->set_inconsistent(false); } } void ToneCurve::histmatchingToggled() { if (listener) { if (!batchMode) { if (histmatching->get_active()) { fromHistMatching = false; listener->panelChanged(EvHistMatching, M("GENERAL_ENABLED")); waitForAutoExp(); } else { listener->panelChanged(EvHistMatching, M("GENERAL_DISABLED")); } } else { listener->panelChanged(EvHistMatchingBatch, histmatching->get_active() ? M("GENERAL_ENABLED") : M("GENERAL_DISABLED")); } } } void ToneCurve::autoExpChanged(double expcomp, int bright, int contr, int black, int hlcompr, int hlcomprthresh, bool hlrecons) { nextBlack = black; nextExpcomp = expcomp; nextBrightness = bright; nextContrast = contr; nextHlcompr = hlcompr; nextHlcomprthresh = hlcomprthresh; nextHLRecons = hlrecons; idle_register.add( [this]() -> bool { GThreadLock lock; // All GUI access from idle_add callbacks or separate thread HAVE to be protected // FIXME: We don't need the GThreadLock, don't we? disableListener(); enableAll(); this->expcomp->setValue(nextExpcomp); brightness->setValue(nextBrightness); contrast->setValue(nextContrast); this->black->setValue(nextBlack); this->hlcompr->setValue(nextHlcompr); this->hlcomprthresh->setValue(nextHlcomprthresh); enaconn.block(true); hrenabled->set_active(nextHLRecons); enaconn.block(false); if (nextHLRecons) { hlrbox->show(); } else if (!batchMode) { hlrbox->hide(); } if (!this->black->getAddMode() && !batchMode) { shcompr->set_sensitive(static_cast<int>(this->black->getValue())); //at black=0 shcompr value has no effect } if (!this->hlcompr->getAddMode() && !batchMode) { this->hlcomprthresh->set_sensitive(static_cast<int>(this->hlcompr->getValue())); //at hlcompr=0 hlcomprthresh value has no effect } enableListener(); return false; } ); } void ToneCurve::<API key>(rtengine::procparams::ToneCurveMode curveMode, const std::vector<double>& curve) { nextToneCurveMode = curveMode; nextToneCurve = curve; idle_register.add( [this]() -> bool { GThreadLock lock; // FIXME: Obsolete disableListener(); enableAll(); brightness->setValue(0); contrast->setValue(0); black->setValue(0); if (!black->getAddMode() && !batchMode) { shcompr->set_sensitive(static_cast<int>(black->getValue())); } if (!hlcompr->getAddMode() && !batchMode) { hlcomprthresh->set_sensitive(static_cast<int>(hlcompr->getValue())); //at hlcompr=0 hlcomprthresh value has no effect } if (autolevels->get_active() ) { expcomp->setValue(0); autoconn.block(true); autolevels->set_active(false); autoconn.block(false); autolevels->set_inconsistent(false); } toneCurveMode->set_active(rtengine::toUnderlying(nextToneCurveMode)); shape->setCurve(nextToneCurve); shape2->setCurve({DCT_Linear}); shape->openIfNonlinear(); enableListener(); fromHistMatching = true; return false; } ); }
# NewTab An newtab page with a simple python response server ## First setup Place the html folder and the server.py file in the folder _/var/www_ Open you browsers' settings and change the default newtab page. For Firefox users Install this [addon](https://addons.mozilla.org/en-US/firefox/addon/new-tab-override/) and set the default page to localhost (or if you don't setup the server.py just the path to the index.html file). For Chrome users Install this [addon](https://chrome.google.com/webstore/detail/new-tab-redirect/<API key>) and set the default page to localhost (or if you don't setup the server.py just the path to the index.html file). ## Start server If you want the searchbar of your browser to be clean, you can run the following code in the working directory.<br/> You have to install Python 3 though. sudo python3 server.py If you choose not to, it's no problem. All paths in the code are relative. ## How to edit the page? The page itself is easily edited in the [setting.json](html/js/settings.json) file. User object In here only the users' name is set and a background if that's wanted.<br/> If the users' name is not set, there will be a different message: Hello there! Searchengines object The Searchengines object is the content of the dropdown menu.<br/> These are the searchengines you can do an instant seach on. Categories object The Categories object is a tiny bit different.<br/> This one has an (optional) icon from FontAwesome. You only have to set the icons' CSS class.<br/> There is the title of the category.<br/> And last but not least there is the list with URLs within the category. Each list item has an url and text option.
var App = Ember.Application.create(); // var App is a namespace to write all of our application code // namespace can be anything you like - but App is common // this single line boots ember, set up all controllers, views, and template rendering that is needed // to see this, we'll actually need to render something - which we'll do in the HTML file // note that this single line of code also generates the index route and controller, and renders it templates // Router - define a bunch of resources, each of which handle different actions in the application // each resource is a part of a URL, and optionally followed by some additional information about what to do at that URL // this additional information is optional only because ember generates sensible defaults when they are not present //we define each of the resources that we are interested in //each resource maps to a single route object //routes can have sub routes (called nested routes) //NOTE App.Router - not App.Route App.Router.map(function() { // '/'' => 'index' this mapping is always generated by default - no need to specify //now we wish to add a resource that is mapped from the URL hash: '/tables/:table_id' this.resource('tables', function() { this.resource('table', { //if path is not specified, it will be implied to be the name of the resource //since this resource is nested, its full path would be parent path + own path: // 'tables' + '/' + ':table_id' path: ':table_id' }); }); // this will take us to the tables route - which we'll add to HTML //visiting an ember route goes through a sequence of objects when rendering objects //to the screen, one of them is the route object (singular) }); //but if we want some data to be available across all controllers in the app.. //we can use a special route - the application route. it has been generated implicitly all this while //- since we haven't needed to use it thus far, we have not needed to write it App.ApplicationRoute = Ember.Route.extend({ //the setup controller method is useful for setting up cross controller activity //(when we need to work with multiple controllers) setupController: function() { //we can load data for any of the routes in this application in this method //the data we want to set for the food controller is obtained using: App.Food.find() //the food controller can be accessed using: this.controllerFor('food') //TODO find out why it is this.controllerFor instead of App.controllerFor - //the latter seems more intuitive, and using this seems more like an artefact of implementation detail this.controllerFor('food').set('model', App.Food.find()); } }); App.IndexRoute = Ember.Route.extend({ redirect: function() { this.transitionTo('tables'); } }); //name of route must correspond to the name of the resource above //custom objects in ember use extend as a means of inheritance App.TablesRoute = Ember.Route.extend({ //in the route, implement the model method to return the data that is required //to be displayed - that should be used by the matching controller (tables controller) model: function() { //the return value is used to set the model property of the corresponding controller //at this stage, if you refresh the page, the page will not display anything, //as there will be an error - TableModel has yet to be defined return App.Table.find(); } }); //ember actually generates this route automatically in memory when it is not specified //only really need to write this code if you want to do anything special //you get this for free just by following the naming conventions //We temporarily uncoimment this route to insert a debugger statement to inspect the value of params //App.TableRoute = Ember.Route.extend({ // //since this route has a path with a variable, we can access it using the params object // model: function(params) { // console.log('TableRoute#model params', params); // return App.Table.find(params.table_id); // //you can override setup controller if you wish. // // the model created in the model function will be passed in here, along with the current controller // setupController: function(controller, model) { // //call to _super is likely to be deprecated in future version of ember // this._super(controller, model); // //this.controllerFor(...); // //however, this should not be done most of the time - let ember assign the model for you //an array controller expects its model to be a list of object models App.TablesController = Ember.ArrayController.extend({ //specify sort properties which define the order in which models will be presented to the templates sortProperties: ['id'] }); //ember actually generates this controller automatically in memory when not specified //write this code only if you wish to override the default behaviour App.TableController = Ember.ObjectController.extend({ addFood: function(food) { //in order to add food, we need to get a hold of the tab model that we are adding it to //controller for table will return the controller with the model set to the currently //selected/ active table var table = this.get('model'); //note - no need to do table.get('tab').get('tabItems') here var tabItems = table.get('tab.tabItems'); tabItems.createRecord({ food: food, cents: food.get('cents') }); } }); //this is our custom controller //array controller because it manages a list of objects //but how do we load the data for this controller? //- we cannot load the data in controllers //- there is no route object that corresponds to this controller to load the data into its model property //nested resources are one way to load resources from another controller App.FoodController = Ember.ArrayController.extend({ //we decide to shift the addFood action to the parent controller, and let ember bubble the action // //we add the implementation for the action here in the food controller // addFood: function(food) { // //in order to add food, we need to get a hold of the tab model that we are adding it to // //controller for table will return the controller with the model set to the currently // //selected/ active table // var table = this.controllerFor('table').get('model'); // //note - no need to do table.get('tab').get('tabItems') here // var tabItems = table.get('tab.tabItems'); // tabItems.createRecord({ // food: food, // cents: food.get('cents') }); //Deleted as ember will automatically generate this anyway //App.TabController = Ember.ObjectController.extend(); //we define the handlebars helpers that we wish to use here Ember.Handlebars.registerBoundHelper('money', function(value) { return '$' + parseFloat(value/100).toFixed(2); }); App.Store = DS.Store.extend({ revision: 11, adapter: 'DS.FixtureAdapter' }); //models backed by a fixture adapter data store will be defined in a POJSO //the only requirement is that each of them has an id attribute - which may be //either a number or a string //copied from models.js // Models //create a simple data model //ember expects the name of the data store object to be store //this is the object it will look in when you used .find(), etc, to get any models App.Store = DS.Store.extend({ //ember data is still ina state of flux - so specifying a revision number is //similar to specifying a API version revision: 11, //DS.FixtureAdapter is an object, but we use a string instead because that lets //ember load/ initialise this object when it wants to later on, //instead of forcing it to do so now, when this store is specified adapter: 'DS.FixtureAdapter' }); //define the model to be bound to this data store we have just created App.Table = DS.Model.extend({ //we define the relationship between the table model adn the table model: table belongs to a tab //the tab model is referred to here as a string, for the same reason that DS fixture adapter is above: //to allow ember to load/ init this object when it want to later on, instead of forcing it to do so right now //exception to the rule: you should never use 'App' or 'App.' in a string anywhere else //belongs to really means has one tab: DS.belongsTo('App.Tab') }); App.Tab = DS.Model.extend({ //relationship between tab model: tab has many tab items tabItems: DS.hasMany('App.TabItem'), cents: function() { //within this function we have access to the other properties of this objects - tab items //this is basically a map-reduce pattern (getEach is a type of map) return this.get('tabItems').getEach('cents').reduce(function(acc, itemCents) { return acc + itemCents; }, 0); }.property('tabItems.@each.cents') //we should also optimise this calculation by caching it so that it is only computed once //in addition, it should be recomputed any time the tab items change, and notify ember of this change //in ember we do this by calling .property after the closing squiggly brace of the function //we should pass in a description of the circumstances under which this property should be recomputed //this will often be the name of a simple property //in this case however, we are going for something more complex, and ember provides a expression language for this }); App.TabItem = DS.Model.extend({ //we define the the tab item model to contain an attribute //this means that objects saved into this model should have a cents attribute of type number //allowed attribute types are string, number, and boolean cents: DS.attr('number'), //relationship between tab item model and food model: tab item belongs to food food: DS.belongsTo('App.Food') }); App.Food = DS.Model.extend({ //food does not define any new relationships of its own name: DS.attr('string'), imageUrl: DS.attr('string'), cents: DS.attr('number') }); //once the models have been defines, we populate them with data //full featured ember data can retrieve data from a server, //or you can do this manually by using AJAX to fetch JSON and populate the record manually from here //we'll use fixtures here so that we do not need to rely on having a functional server while develop this app (the client) //note that ember defines an id attribute for all models automatically, but we will need to specify this in the fixtures //parent objects need to keep track of the keys of their child objects App.Table.FIXTURES = [{ id: 1, tab: 1 //belongs to }, { id: 2, tab: 2 }, { id: 3, tab: 3 }, { id: 4, tab: 4 }, { id: 5, tab: 5 }, { id: 6, tab: 6 }]; App.Tab.FIXTURES = [{ id: 1, tabItems: [] //has many }, { id: 2, tabItems: [] }, { id: 3, tabItems: [] }, { id: 4, tabItems: [400, 401, 402, 403, 404] }, { id: 5, tabItems: [] }, { id: 6, tabItems: [] }]; //ids do not need to start with 1 - use larger number for different classes for ease of debugging App.TabItem.FIXTURES = [{ id: 400, cents: 1500, food: 1 }, { id: 401, cents: 300, food: 2 }, { id: 402, cents: 700, food: 3 }, { id: 403, cents: 950, food: 4 }, { id: 404, cents: 2000, food: 5 }]; App.Food.FIXTURES = [{ id: 1, name: 'Pizza', imageUrl: 'img/pizza.png', cents: 1500 }, { id: 2, name: 'Pancakes', imageUrl: 'img/pancakes.png', cents: 300 }, { id: 3, name: 'Fries', imageUrl: 'img/fries.png', cents: 700 }, { id: 4, name: 'Hot Dog', imageUrl: 'img/hotdog.png', cents: 950 }, { id: 5, name: 'Birthday Cake', imageUrl: 'img/birthdaycake.png', cents: 2000 }];
#ifndef DEF_VERSION_H #define DEF_VERSION_H #define CLIENT_GUID "{<API key>}" #define <API key> "Rambler" #define CLIENT_NAME "Contacts" #define CLIENT_VERSION "0.7.0" #define <API key> "beta" #define CLIENT_HOME_PAGE "http://contacts.rambler.ru" #endif // DEF_VERSION_H
<?php /** * Games Collector Game Attributes Taxonomy * * @package GC\GamesCollector\Attributes * @since 0.1 */ namespace GC\GamesCollector\Attributes; /** * Register the taxonomies. * * @since 0.1 */ function register_taxonomy() { <API key>( 'gc_attribute', 'gc_game', [ 'dashboard_glance' => true, // Show this taxonomy in the 'At a Glance' widget. 'hierarchical' => false, 'show_in_rest' => true, 'rest_base' => 'attributes', ], [ 'singular' => __( 'Game Attribute', 'games-collector' ), 'plural' => __( 'Game Attributes', 'games-collector' ), 'slug' => 'attribute', ] ); } /** * Remove the default taxonomy metabox and add a new one using Chosen. * * @since 0.1 */ function metabox() { remove_meta_box( '<API key>', 'gc_game', 'side' ); add_meta_box( '<API key>', __( 'Game Attributes', 'games-collector' ), __NAMESPACE__ . '\\meta_box_display', 'gc_game', 'side', 'default' ); } /** * Enqueue the Chosen CSS and JS. * * @since 0.1 */ function enqueue_scripts() { $screen = get_current_screen(); if ( 'post' !== $screen->base || 'gc_game' !== $screen->post_type ) { return; } wp_enqueue_script( 'chosen', plugin_dir_url( dirname( dirname( __FILE__ ) ) ) . 'vendor/harvesthq/chosen/chosen.jquery.min.js', [ 'jquery' ], '1.8', true ); wp_enqueue_style( 'chosen', plugin_dir_url( dirname( dirname( __FILE__ ) ) ) . 'vendor/harvesthq/chosen/chosen.min.css', [], '1.8' ); } function meta_box_display() { wp_nonce_field( '<API key>', '<API key>' ); $tax = 'gc_attribute'; ?> <script type="text/javascript"> jQuery(document).ready(function($){ $( '.chzn-select' ).chosen(); }); </script> <?php if ( current_user_can( 'edit_posts' ) ) { $terms = get_terms( $tax, [ 'hide_empty' => 0 ] ); $current_terms = wp_get_post_terms( get_the_ID(), $tax, [ 'fields' => 'ids' ] ); $name = "tax_input[$tax]"; ?> <p><select name="<?php echo esc_html( $name ); ?>[]" class="chzn-select widefat" data-placeholder="<?php esc_html_e( 'Select one or more attributes', 'games-collector' ); ?>" multiple="multiple"> <?php foreach ( $terms as $term ) { $value = $term->slug; ?> <option value="<?php echo esc_html( $value ); ?>"<?php selected( in_array( $term->term_id, $current_terms ) ); ?>><?php echo esc_html( $term->name ); ?></option> <?php } ?> </select> </p> <?php } } /** * Create some default game attributes. * * @since 0.1 */ function <API key>() { if ( ! term_exists( 'Solo Play', 'gc_attribute' ) ) { wp_insert_term( 'Solo Play', 'gc_attribute', [ 'slug' => 'solo' ] ); } if ( ! term_exists( 'Cooperative', 'gc_attribute' ) ) { wp_insert_term( 'Cooperative', 'gc_attribute', [ 'slug' => 'coop' ] ); } if ( ! term_exists( 'Party Game', 'gc_attribute' ) ) { wp_insert_term( 'Party Game', 'gc_attribute', [ 'slug' => 'party' ] ); } if ( ! term_exists( 'Easy-to-learn', 'gc_attribute' ) ) { wp_insert_term( 'Easy-to-learn', 'gc_attribute', [ 'slug' => 'easy-to-learn' ] ); } if ( ! term_exists( 'Heavy Strategy', 'gc_attribute' ) ) { wp_insert_term( 'Heavy Strategy', 'gc_attribute', [ 'slug' => 'strategy' ] ); } if ( ! term_exists( 'Expansion', 'gc_attribute' ) ) { wp_insert_term( 'Expansion', 'gc_attribute', [ 'slug' => 'expansion' ] ); } if ( ! term_exists( 'City/Empire Building', 'gc_attribute' ) ) { wp_insert_term( 'City/Empire Building', 'gc_attribute', [ 'slug' => 'city-building' ] ); } if ( ! term_exists( 'Fast-paced', 'gc_attribute' ) ) { wp_insert_term( 'Fast-paced', 'gc_attribute', [ 'slug' => 'fast-paced' ] ); } if ( ! term_exists( 'Card Game', 'gc_attribute' ) ) { wp_insert_term( 'Card Game', 'gc_attribute', [ 'slug' => 'card' ] ); } if ( ! term_exists( 'Deck Building', 'gc_attribute' ) ) { wp_insert_term( 'Deck Building', 'gc_attribute', [ 'slug' => 'deck-building' ] ); } if ( ! term_exists( 'Dice Game', 'gc_attribute' ) ) { wp_insert_term( 'Dice Game', 'gc_attribute', [ 'slug' => 'dice' ] ); } if ( ! term_exists( 'Role-Playing Game', 'gc_attribute' ) ) { wp_insert_term( 'Role-Playing Game', 'gc_attribute', [ 'slug' => 'rpg' ] ); } if ( ! term_exists( 'Sci-Fi', 'gc_attribute' ) || ! term_exists( 'Science Fiction', 'gc_attribute' ) ) { wp_insert_term( 'Sci-Fi', 'gc_attribute', [ 'slug' => 'sci-fi' ] ); } if ( ! term_exists( 'Horror', 'gc_attribute' ) ) { wp_insert_term( 'Horror', 'gc_attribute', [ 'slug' => 'horror' ] ); } if ( ! term_exists( 'Fantasy', 'gc_attribute' ) ) { wp_insert_term( 'Fantasy', 'gc_attribute', [ 'slug' => 'fantasy' ] ); } if ( ! term_exists( 'Based on a Film/TV Show', 'gc_attribute' ) ) { wp_insert_term( 'Based on a Film/TV Show', 'gc_attribute', [ 'slug' => 'based-on-film-tv' ] ); } if ( ! term_exists( 'Mystery', 'gc_attribute' ) ) { wp_insert_term( 'Mystery', 'gc_attribute', [ 'slug' => 'mystery' ] ); } if ( ! term_exists( 'Historical', 'gc_attribute' ) ) { wp_insert_term( 'Historical', 'gc_attribute', [ 'slug' => 'historical' ] ); } if ( ! term_exists( 'Legacy', 'gc_attribute' ) ) { wp_insert_term( 'Legacy', 'gc_attribute', [ 'slug' => 'legacy' ] ); } } function save_post( $post_id ) { // Verify nonce. if ( ! isset( $_POST['<API key>'] ) || ! wp_verify_nonce( $_POST['<API key>'], '<API key>' ) ) { return; } // Check autosave. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } $input = isset( $_POST['tax_input']['gc_attribute'] ) ? $_POST['tax_input']['gc_attribute'] : ''; if ( empty( $input ) ) { $taxonomy = get_taxonomy( 'gc_attribute' ); if ( $taxonomy && current_user_can( $taxonomy->cap->assign_terms ) ) { wp_set_object_terms( $post_id, '', 'gc_attribute' ); } } } /** * Get a list of attributes for the given post. Use instead of get_term_list. * * @since 1.0.0 * @param integer $post_id The post ID. If none is given, will attempt to grab one from the WP_Post object. * @param string $before Anything before the list of attributes. * @param string $seperator Seperator between attributes (default is ", "). * @param string $after Anything after the list of attributes. * @return string The sanitized list of attributes. */ function <API key>( $post_id = 0, $before = '', $seperator = ', ', $after = '' ) { if ( 0 === $post_id ) { global $post; if ( isset( $post->ID ) ) { $post_id = $post->ID; } else { return new WP_Error( '<API key>', esc_html__( 'No post ID given for game. Cannot get attributes.', 'games-collector' ) ); } } $terms = ''; $attributes = get_the_terms( $post_id, 'gc_attribute' ); if ( ! is_wp_error( $attributes ) ) { $count = count( $attributes ); $iterator = 1; foreach ( $attributes as $term ) { $seperator = ( $iterator < $count ) ? $seperator : ''; $terms .= '<span class="gc-attribute attribute-' . $term->slug . '">' . $term->name . '</span>' . $seperator; $iterator++; } } // Allow the terms to be filtered. $terms = apply_filters( 'gc_filter_the_terms', $terms ); return apply_filters( '<API key>', gc_kses( $before ) . $terms . gc_kses( $after ) ); } /** * Internal wp_kses which allows SVG tags. * * @since 1.1.0 * @param string $string The string to be sanitized. * @return string The sanitized string. */ function gc_kses( $string = '' ) { $allowed_html = array_merge( <API key>( 'post' ), [ 'svg' => [ 'class' => [], 'aria-labelledby' => [], 'role' => [], 'version' => [], 'xmlns' => [], 'xmlns:xlink' => [], 'height' => [], 'width' => [], 'viewbox' => [], ], 'title' => [], 'path' => [ 'd' => [], ], ] ); return wp_kses( $string, $allowed_html ); }
/** * The Editor class is used to provide inline editing for elements on the page. The editor * is backed by a {@link Ext.form.field.Field} that will be displayed to edit the underlying content. * The editor is a floating Component, when the editor is shown it is automatically aligned to * display over the top of the bound element it is editing. The Editor contains several options * for how to handle key presses: * * - {@link #completeOnEnter} * - {@link #cancelOnEsc} * - {@link #swallowKeys} * * It also has options for how to use the value once the editor has been activated: * * - {@link #revertInvalid} * - {@link #ignoreNoChange} * - {@link #updateEl} * * Sample usage: * * var editor = new Ext.Editor({ * updateEl: true, // update the innerHTML of the bound element when editing completes * field: { * xtype: 'textfield' * } * }); * var el = Ext.get('my-text'); // The element to 'edit' * editor.startEdit(el); // The value of the field will be taken as the innerHTML of the element. * * {@img Ext.Editor/Ext.Editor.png Ext.Editor component} * */ Ext.define('Ext.Editor', { /* Begin Definitions */ extend: 'Ext.container.Container', alias: 'widget.editor', requires: ['Ext.layout.container.Editor'], /* End Definitions */ layout: 'editor', /** * @cfg {Ext.form.field.Field} field * The Field object (or descendant) or config object for field */ /** * @cfg {Boolean} allowBlur * True to {@link #completeEdit complete the editing process} if in edit mode when the * field is blurred. */ allowBlur: true, /** * @cfg {Boolean/Object} autoSize * True for the editor to automatically adopt the size of the underlying field. Otherwise, an object * can be passed to indicate where to get each dimension. The available properties are 'boundEl' and * 'field'. If a dimension is not specified, it will use the underlying height/width specified on * the editor object. * Examples: * * autoSize: true // The editor will be sized to the height/width of the field * * height: 21, * autoSize: { * width: 'boundEl' // The width will be determined by the width of the boundEl, the height from the editor (21) * } * * autoSize: { * width: 'field', // Width from the field * height: 'boundEl' // Height from the boundEl * } */ /** * @cfg {Boolean} revertInvalid * True to automatically revert the field value and cancel the edit when the user completes an edit and the field * validation fails */ revertInvalid: true, /** * @cfg {Boolean} [ignoreNoChange=false] * True to skip the edit completion process (no save, no events fired) if the user completes an edit and * the value has not changed. Applies only to string values - edits for other data types * will never be ignored. */ /** * @cfg {Boolean} [hideEl=true] * False to keep the bound element visible while the editor is displayed */ /** * @cfg {Object} value * The data value of the underlying field */ value : '', /** * @cfg {String} alignment * The position to align to (see {@link Ext.Element#alignTo} for more details). */ alignment: 'c-c?', /** * @cfg {Number[]} offsets * The offsets to use when aligning (see {@link Ext.Element#alignTo} for more details. */ offsets: [0, 0], /** * @cfg {Boolean/String} shadow * "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop" for bottom-right shadow. */ shadow : 'frame', /** * @cfg {Boolean} constrain * True to constrain the editor to the viewport */ constrain : false, /** * @cfg {Boolean} swallowKeys * Handle the keydown/keypress events so they don't propagate */ swallowKeys : true, /** * @cfg {Boolean} completeOnEnter * True to complete the edit when the enter key is pressed. */ completeOnEnter : true, /** * @cfg {Boolean} cancelOnEsc * True to cancel the edit when the escape key is pressed. */ cancelOnEsc : true, /** * @cfg {Boolean} updateEl * True to update the innerHTML of the bound element when the update completes */ updateEl : false, /** * @cfg {String/HTMLElement/Ext.Element} [parentEl=document.body] * An element to render to. */ // private overrides hidden: true, baseCls: Ext.baseCSSPrefix + 'editor', initComponent : function() { var me = this, field = me.field = Ext.ComponentManager.create(me.field, 'textfield'); Ext.apply(field, { inEditor: true, msgTarget: field.msgTarget == 'title' ? 'title' : 'qtip' }); me.mon(field, { scope: me, blur: { fn: me.onFieldBlur, // slight delay to avoid race condition with startEdits (e.g. grid view refresh) delay: 1 }, specialkey: me.onSpecialKey }); if (field.grow) { me.mon(field, 'autosize', me.onFieldAutosize, me, {delay: 1}); } me.floating = { constrain: me.constrain }; me.items = field; me.callParent(arguments); me.addEvents( /** * @event beforestartedit * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning * false from the handler of this event. * @param {Ext.Editor} this * @param {Ext.Element} boundEl The underlying element bound to this editor * @param {Object} value The field value being set */ 'beforestartedit', /** * @event startedit * Fires when this editor is displayed * @param {Ext.Editor} this * @param {Ext.Element} boundEl The underlying element bound to this editor * @param {Object} value The starting field value */ 'startedit', /** * @event beforecomplete * Fires after a change has been made to the field, but before the change is reflected in the underlying * field. Saving the change to the field can be canceled by returning false from the handler of this event. * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this * event will not fire since no edit actually occurred. * @param {Ext.Editor} this * @param {Object} value The current field value * @param {Object} startValue The original field value */ 'beforecomplete', /** * @event complete * Fires after editing is complete and any changed value has been written to the underlying field. * @param {Ext.Editor} this * @param {Object} value The current field value * @param {Object} startValue The original field value */ 'complete', /** * @event canceledit * Fires after editing has been canceled and the editor's value has been reset. * @param {Ext.Editor} this * @param {Object} value The user-entered field value that was discarded * @param {Object} startValue The original field value that was set back into the editor after cancel */ 'canceledit', /** * @event specialkey * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check * {@link Ext.EventObject#getKey} to determine which key was pressed. * @param {Ext.Editor} this * @param {Ext.form.field.Field} The field attached to this editor * @param {Ext.EventObject} event The event object */ 'specialkey' ); }, // private onFieldAutosize: function(){ this.updateLayout(); }, // private afterRender : function(ct, position) { var me = this, field = me.field, inputEl = field.inputEl; me.callParent(arguments); // Ensure the field doesn't get submitted as part of any form if (inputEl) { inputEl.dom.name = ''; if (me.swallowKeys) { inputEl.swallowEvent([ 'keypress', 'keydown' ]); } } }, // private onSpecialKey : function(field, event) { var me = this, key = event.getKey(), complete = me.completeOnEnter && key == event.ENTER, cancel = me.cancelOnEsc && key == event.ESC; if (complete || cancel) { event.stopEvent(); // Must defer this slightly to prevent exiting edit mode before the field's own // key nav can handle the enter key, e.g. selecting an item in a combobox list Ext.defer(function() { if (complete) { me.completeEdit(); } else { me.cancelEdit(); } if (field.triggerBlur) { field.triggerBlur(); } }, 10); } me.fireEvent('specialkey', me, field, event); }, /** * Starts the editing process and shows the editor. * @param {String/HTMLElement/Ext.Element} el The element to edit * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults * to the innerHTML of el. */ startEdit : function(el, value) { var me = this, field = me.field; me.completeEdit(); me.boundEl = Ext.get(el); value = Ext.isDefined(value) ? value : (me.boundEl.dom.innerText || me.boundEl.dom.innerHTML).trim(); if (!me.rendered) { me.render(me.parentEl || document.body); } if (me.fireEvent('beforestartedit', me, me.boundEl, value) !== false) { me.startValue = value; me.show(); // temporarily suspend events on field to prevent the "change" event from firing when reset() and setValue() are called field.suspendEvents(); field.reset(); field.setValue(value); field.resumeEvents(); me.realign(true); field.focus(false, 10); if (field.autoSize) { field.autoSize(); } me.editing = true; } }, /** * Realigns the editor to the bound field based on the current alignment config value. * @param {Boolean} autoSize (optional) True to size the field to the dimensions of the bound element. */ realign : function(autoSize) { var me = this; if (autoSize === true) { me.updateLayout(); } me.alignTo(me.boundEl, me.alignment, me.offsets); }, /** * Ends the editing process, persists the changed value to the underlying field, and hides the editor. * @param {Boolean} [remainVisible=false] Override the default behavior and keep the editor visible after edit */ completeEdit : function(remainVisible) { var me = this, field = me.field, value; if (!me.editing) { return; } // Assert combo values first if (field.assertValue) { field.assertValue(); } value = me.getValue(); if (!field.isValid()) { if (me.revertInvalid !== false) { me.cancelEdit(remainVisible); } return; } if (String(value) === String(me.startValue) && me.ignoreNoChange) { me.hideEdit(remainVisible); return; } if (me.fireEvent('beforecomplete', me, value, me.startValue) !== false) { // Grab the value again, may have changed in beforecomplete value = me.getValue(); if (me.updateEl && me.boundEl) { me.boundEl.update(value); } me.hideEdit(remainVisible); me.fireEvent('complete', me, value, me.startValue); } }, // private onShow : function() { var me = this; me.callParent(arguments); if (me.hideEl !== false) { me.boundEl.hide(); } me.fireEvent("startedit", me.boundEl, me.startValue); }, /** * Cancels the editing process and hides the editor without persisting any changes. The field value will be * reverted to the original starting value. * @param {Boolean} [remainVisible=false] Override the default behavior and keep the editor visible after cancel */ cancelEdit : function(remainVisible) { var me = this, startValue = me.startValue, field = me.field, value; if (me.editing) { value = me.getValue(); // temporarily suspend events on field to prevent the "change" event from firing when setValue() is called field.suspendEvents(); me.setValue(startValue); field.resumeEvents(); me.hideEdit(remainVisible); me.fireEvent('canceledit', me, value, startValue); } }, // private hideEdit: function(remainVisible) { if (remainVisible !== true) { this.editing = false; this.hide(); } }, // private onFieldBlur : function() { var me = this; // selectSameEditor flag allows the same editor to be started without onFieldBlur firing on itself if(me.allowBlur === true && me.editing && me.selectSameEditor !== true) { me.completeEdit(); } }, // private onHide : function() { var me = this, field = me.field; if (me.editing) { me.completeEdit(); return; } if (field.hasFocus) { field.blur(); } if (field.collapse) { field.collapse(); } //field.hide(); if (me.hideEl !== false) { me.boundEl.show(); } me.callParent(arguments); }, /** * Sets the data value of the editor * @param {Object} value Any valid value supported by the underlying field */ setValue : function(value) { this.field.setValue(value); }, /** * Gets the data value of the editor * @return {Object} The data value */ getValue : function() { return this.field.getValue(); }, beforeDestroy : function() { var me = this; Ext.destroy(me.field); delete me.field; delete me.parentEl; delete me.boundEl; me.callParent(arguments); } });
package net.freerouting.datastructures; import net.freerouting.geometry.planar.RegularTileShape; import net.freerouting.geometry.planar.<API key>; import java.util.Set; import java.util.TreeSet; /** * Binary search tree for shapes in the plane. * The shapes are stored in the leafs of the tree. * The algorithm for storing a new shape is as following. * Starting from the root go to the child, so that the increase of the bounding shape of that child * is minimal after adding the new shape, until you reach a leaf. * The use of ShapeDirections to calculate the bounding shape is for historical reasons (coming from a Kd-Tree). * Instead any algorithm to calculate a bounding shape of two input shapes can be used. * The algorithm would of course also work for higher dimensions. * * @author Alfons Wirtz */ public class MinAreaTree extends ShapeTree { protected ArrayStack<TreeNode> node_stack = new ArrayStack<TreeNode>(10000); /** * Constructor with a fixed set of directions defining the keys and and * the surrounding shapes */ public MinAreaTree(<API key> p_directions) { super(p_directions); } /** * Calculates the objects in this tree, which overlap with p_shape */ public Set<Leaf> overlaps(RegularTileShape p_shape) { Set<Leaf> found_overlaps = new TreeSet<Leaf>(); if (this.root == null) { return found_overlaps; } this.node_stack.reset(); this.node_stack.push(this.root); TreeNode curr_node; for (; ; ) { curr_node = this.node_stack.pop(); if (curr_node == null) { break; } if (curr_node.bounding_shape.intersects(p_shape)) { if (curr_node instanceof Leaf) { found_overlaps.add((Leaf) curr_node); } else { this.node_stack.push(((InnerNode) curr_node).first_child); this.node_stack.push(((InnerNode) curr_node).second_child); } } } return found_overlaps; } void insert(Leaf p_leaf) { ++this.leaf_count; // Tree is empty - just insert the new leaf if (root == null) { root = p_leaf; return; } // Non-empty tree - do a recursive location for leaf replacement Leaf leaf_to_replace = position_locate(root, p_leaf); // Construct a new node - whenever a leaf is added so is a new node RegularTileShape new_bounds = p_leaf.bounding_shape.union(leaf_to_replace.bounding_shape); InnerNode curr_parent = leaf_to_replace.parent; InnerNode new_node = new InnerNode(new_bounds, curr_parent); if (leaf_to_replace.parent != null) { // Replace the pointer from the parent to the leaf with our new node if (leaf_to_replace == curr_parent.first_child) { curr_parent.first_child = new_node; } else { curr_parent.second_child = new_node; } } // Update the parent pointers of the old leaf and new leaf to point to new node leaf_to_replace.parent = new_node; p_leaf.parent = new_node; // Insert the children in any order. new_node.first_child = leaf_to_replace; new_node.second_child = p_leaf; if (root == leaf_to_replace) { root = new_node; } } private final Leaf position_locate(TreeNode p_curr_node, Leaf p_leaf_to_insert) { TreeNode curr_node = p_curr_node; while (!(curr_node instanceof Leaf)) { InnerNode curr_inner_node = (InnerNode) curr_node; curr_inner_node.bounding_shape = p_leaf_to_insert.bounding_shape.union(curr_inner_node.bounding_shape); // Choose the the child, so that the area increase of that child after taking the union // with the shape of p_leaf_to_insert is minimal. RegularTileShape first_child_shape = curr_inner_node.first_child.bounding_shape; RegularTileShape <API key> = p_leaf_to_insert.bounding_shape.union(first_child_shape); double first_area_increase = <API key>.area() - first_child_shape.area(); RegularTileShape second_child_shape = curr_inner_node.second_child.bounding_shape; RegularTileShape <API key> = p_leaf_to_insert.bounding_shape.union(second_child_shape); double <API key> = <API key>.area() - second_child_shape.area(); if (first_area_increase <= <API key>) { curr_node = curr_inner_node.first_child; } else { curr_node = curr_inner_node.second_child; } } return (Leaf) curr_node; } /** * removes an entry from this tree */ public void remove_leaf(Leaf p_leaf) { if (p_leaf == null) { return; } // remove the leaf node InnerNode parent = p_leaf.parent; p_leaf.bounding_shape = null; p_leaf.parent = null; p_leaf.object = null; --this.leaf_count; if (parent == null) { // tree gets empty root = null; return; } // find the other leaf of the parent TreeNode other_leaf; if (parent.second_child == p_leaf) { other_leaf = parent.first_child; } else if (parent.first_child == p_leaf) { other_leaf = parent.second_child; } else { System.out.println("MinAreaTree.remove_leaf: parent inconsistent"); other_leaf = null; } // link the other leaf to the grand_parent and remove the parent node InnerNode grand_parent = parent.parent; other_leaf.parent = grand_parent; if (grand_parent == null) { // only one leaf left in the tree root = other_leaf; } else { if (grand_parent.second_child == parent) { grand_parent.second_child = other_leaf; } else if (grand_parent.first_child == parent) { grand_parent.first_child = other_leaf; } else { System.out.println("MinAreaTree.remove_leaf: grand_parent inconsistent"); } } parent.parent = null; parent.first_child = null; parent.second_child = null; parent.bounding_shape = null; // recalculate the bounding shapes of the ancestors // as long as it gets smaller after removing p_leaf InnerNode node_to_recalculate = grand_parent; while (node_to_recalculate != null) { RegularTileShape new_bounds = node_to_recalculate.second_child.bounding_shape.union(node_to_recalculate.first_child.bounding_shape); if (new_bounds.contains(node_to_recalculate.bounding_shape)) { // the new bounds are not smaller, no further recalculate nessesary break; } node_to_recalculate.bounding_shape = new_bounds; node_to_recalculate = node_to_recalculate.parent; } } }
#!/usr/bin/env python from __future__ import print_function from setuptools import setup, find_packages import yowsup_ext.commandserver deps = ['yowsup2==2.4.48', '<API key>'] setup( name='<API key>', version=yowsup_ext.commandserver.__version__, tests_require=[], install_requires = deps, scripts = ['<API key>'], dependency_links = [ 'https://github.com/tgalal/yowsup/archive/develop.zip#egg=yowsup2-2.4.48', ], packages= find_packages(), <API key>=True, platforms='any', namespace_packages = ['yowsup_ext', 'yowsup_ext.commandserver', 'yowsup_ext.layers'], classifiers = [ 'Programming Language :: Python', 'Development Status :: 4 - Beta', 'Natural Language :: English', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
<?php class <API key> extends CDbMigration { public function up() { // Add missing create/edited columns on drug tables foreach (array('drug_duration','<API key>','drug_form','drug_frequency','drug_route','drug_type') as $table) { $this->addColumn($table, '<API key>', 'int(10) unsigned NOT NULL DEFAULT 1'); $this->addColumn($table, 'created_user_id', 'int(10) unsigned NOT NULL DEFAULT 1'); $this->addColumn($table, 'last_modified_date', 'datetime NOT NULL DEFAULT \'1900-01-01 00:00:00\''); $this->addColumn($table, 'created_date', 'datetime NOT NULL DEFAULT \'1900-01-01 00:00:00\''); $this->addForeignKey($table.'_lmui_fk', $table, '<API key>', 'user', 'id'); $this->addForeignKey($table.'_cui_fk', $table, 'created_user_id', 'user', 'id'); } $this->addColumn('drug_duration','display_order','int(10) unsigned NOT NULL DEFAULT 1'); foreach (array('24 hours','48 hours','1 day','3 days','4 days','6 weeks') as $name) { if (!DrugDuration::model()->find('name=?',array($name))) { $dd = new DrugDuration; $dd->name = $name; $dd->save(); } } $ids = array( 'hours' => array(), 'days' => array(), 'weeks' => array(), 'months' => array(), 'other' => array(), ); foreach (DrugDuration::model()->findAll() as $drug_duration) { if (preg_match('/^([0-9]+) hour/',$drug_duration->name,$m)) { $ids['hours'][$m[1]] = $drug_duration->id; } elseif (preg_match('/^([0-9]+) day/',$drug_duration->name,$m)) { $ids['days'][$m[1]] = $drug_duration->id; } elseif (preg_match('/^([0-9]+) week/',$drug_duration->name,$m)) { $ids['weeks'][$m[1]] = $drug_duration->id; } elseif (preg_match('/^([0-9]+) month/',$drug_duration->name,$m)) { $ids['months'][$m[1]] = $drug_duration->id; } else { $ids['other'][] = $drug_duration->id; } } ksort($ids['hours']); ksort($ids['days']); ksort($ids['weeks']); ksort($ids['months']); ksort($ids['other']); $i = 1; foreach ($ids as $list => $items) { foreach ($items as $item) { $this->update('drug_duration',array('display_order'=>$i),'id='.$item); $i++; } } } public function down() { $this->dropColumn('drug_duration','display_order'); } }
public class HelloWorld{ public static void main(String[]args){ System.out.println("hello world"); } }
package scripting.portal; import client.MapleClient; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.<API key>; import java.util.HashMap; import java.util.Map; import javax.script.Compilable; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import server.MaplePortal; import tools.FilePrinter; public class PortalScriptManager { private static PortalScriptManager instance = new PortalScriptManager(); private Map<String, PortalScript> scripts = new HashMap<>(); private ScriptEngineFactory sef; private PortalScriptManager() { ScriptEngineManager sem = new ScriptEngineManager(); sef = sem.getEngineByName("javascript").getFactory(); } public static PortalScriptManager getInstance() { return instance; } private PortalScript getPortalScript(String scriptName) { if (scripts.containsKey(scriptName)) { return scripts.get(scriptName); } File scriptFile = new File("scripts/portal/" + scriptName + ".js"); if (!scriptFile.exists()) { scripts.put(scriptName, null); return null; } FileReader fr = null; ScriptEngine portal = sef.getScriptEngine(); try { fr = new FileReader(scriptFile); ((Compilable) portal).compile(fr).eval(); } catch (ScriptException | IOException | <API key> e) { FilePrinter.printError(FilePrinter.PORTAL + scriptName + ".txt", e); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { System.out.println("ERROR CLOSING " + e); } } } PortalScript script = ((Invocable) portal).getInterface(PortalScript.class); scripts.put(scriptName, script); return script; } public boolean executePortalScript(MaplePortal portal, MapleClient c) { try { PortalScript script = getPortalScript(portal.getScriptName()); if (script != null) { return script.enter(new <API key>(c, portal)); } } catch (<API key> ute) { FilePrinter.printError(FilePrinter.PORTAL + portal.getScriptName() + ".txt", ute); } catch (final Exception e) { FilePrinter.printError(FilePrinter.PORTAL + portal.getScriptName() + ".txt", e); } return false; } public void reloadPortalScripts() { scripts.clear(); } }
package de.sudoq.model.solverGenerator; import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Before; import org.junit.Test; import de.sudoq.model.solverGenerator.Generator; import de.sudoq.model.solverGenerator.GeneratorCallback; import de.sudoq.model.solverGenerator.solver.ComplexityRelation; import de.sudoq.model.solverGenerator.solver.Solver; import de.sudoq.model.solverGenerator.transformations.Transformer; import de.sudoq.model.sudoku.Sudoku; import de.sudoq.model.sudoku.complexity.Complexity; import de.sudoq.model.sudoku.sudokuTypes.SudokuTypes; import de.sudoq.model.sudoku.sudokuTypes.TypeBuilder; public class GeneratorTests implements GeneratorCallback { private Generator generator; @Before public void beforeTest() { TypeBuilder.get99(); generator = new Generator(); } @Override public synchronized void generationFinished(Sudoku sudoku) { assertEquals(new Solver(sudoku).validate(null, false), ComplexityRelation.<API key>); this.notifyAll(); } // Empirischer Test durch mehrfaches Generieren @Test public void testGeneration() { Random rnd = new Random(0); generator.setRandom(rnd); Transformer.setRandom(rnd); generator.generate(SudokuTypes.standard16x16, Complexity.infernal, this); synchronized (this) { try { wait(); } catch (<API key> e) { e.printStackTrace(); } } System.out.println("16 done"); generator.setRandom(rnd); Transformer.setRandom(rnd); generator.generate(SudokuTypes.standard9x9, Complexity.infernal, this); synchronized (this) { try { wait(); } catch (<API key> e) { e.printStackTrace(); } } System.out.println("9 done"); generator.setRandom(rnd); Transformer.setRandom(rnd); generator.generate(SudokuTypes.Xsudoku, Complexity.medium, this); synchronized (this) { try { wait(); } catch (<API key> e) { e.printStackTrace(); } } System.out.println("X done"); generator.setRandom(rnd); Transformer.setRandom(rnd); generator.generate(SudokuTypes.squigglya, Complexity.infernal, this); synchronized (this) { try { wait(); } catch (<API key> e) { e.printStackTrace(); } } System.out.println("sqA done"); //TODO fix this /*generator.setRandom(rnd); Transformer.setRandom(rnd); generator.generate(SudokuTypes.samurai, Complexity.easy, this); synchronized (this) { try { wait(); } catch (<API key> e) { e.printStackTrace(); } }*/ System.out.println("samurai done"); } }
module EnvTests (runTests) where import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Syntax import Env import Test.HUnit -- printing tests testEnv1 = initEnv [Static "a", Static "b", Static "c"] envTest1 = TestCase $ assertEqual "envEqualize1" "Just Env{a=b,b=b,c=c}" (show (equalizeNames (Static "a") (Static "b") testEnv1)) envTest2 = TestCase $ assertEqual "envEqualize2" "Just Env{a=a,b=b,c=c}" (show (equalizeNames (Static "a") (Static "a") testEnv1)) envTest3 = TestCase $ assertEqual "envDistinguish1" "Just Env{a=a,b=b,c=c,a<>b}" (show (distinguishNames (Static "a") (Static "b") testEnv1)) testEnv2 = fromJust $ equalizeNames (Static "a") (Static "b") testEnv1 envTest4 = TestCase $ assertEqual "envDistinguish2" "Nothing" (show (distinguishNames (Static "a") (Static "b") testEnv2)) envTests = TestList [TestLabel "envTest1" envTest1 , TestLabel "envTest2" envTest2 , TestLabel "envTest3" envTest3 , TestLabel "envTest4" envTest4 ] runTests = runTestTT envTests
#include "cornerAxis.h" #include <qapplication.h> int main(int argc, char** argv) { QApplication application(argc,argv); Viewer viewer; #if QT_VERSION < 0x040000 application.setMainWidget(&viewer); #else viewer.setWindowTitle("cornerAxis"); #endif viewer.show(); return application.exec(); }
<?php declare(strict_types=1); namespace Breeze\Entity; abstract class BaseEntity { public const ALIAS_ID = '%1$s.%2$s AS %2$s'; public const WRONG_VALUES = 'error_wrong_values'; abstract public static function getTableName(): string; abstract public static function getColumns(): array; }
title: Wurst 5.2 - Bugfixes and Improvements category: Wurst Update Wurst-version: v5.2 minecraft-version: 1.11.X image: https://lh3.googleusercontent.com/LtrwXUBpB9f4-JbF_jHRZaQl9PFV8kKQIcQWaDk0aS2ra5ZBy85IJFIlDYBxhJ1XpcMYaQEiAlY3dB6NBhADOnsfYcT3aBA4S7AHZGxtOxEIYNNnnR9YxLcXjjy1O7vKp1ZnCsL1chgY20q3DRfKc_cEnmesqsLHTrs8HwTpn8WVdWjCG8jd4dnps_RmV8J59fUamUv2kvb44Fm7HJu7VQ6WC04oGIYK<API key><API key>AMF6_bawp_yVGJRYm80N4ZJDdL7ukiubcKs7bNrDzW_a1rQuFEpKzJlmnlNV4o7Wv46u_BlBPrLp0Vm4fnJ1y_k1QkYjz_aSjDBE2BhG2IBUha8<API key><API key><API key>=w1280-h720-no ## Changelog - Improved reliability and performance of AntiSpam. - It will now run in the same thread as the chat itself, meaning that every new message will now be checked by AntiSpam _before_ being added to the chat. - It can now reliably keep up with any new messages, regardless of how quickly they are added to the chat. - Rather than cleaning up the entire chat every time a new message is added, it will now only clean up duplicates of that message. - Improved AutoArmor. - It will now work in both survival and creative mode. - It will now update once per second rather than once every 3 seconds. - Renamed KillerPotion to KillPotion. - Renamed CrashItem to CrashTag. - Improved CrashTag, KillPotion and TrollPotion. - Fixed some settings not loading correctly. - Fixed AutoFish not catching anything. - Fixed Tracers disabling the view bobbing completely. - Fixed CMD-Block, `.copyitem`, CrashChest and `.give` not giving items. - Fixed Clean Up keeping 1.10 servers and removing the 1.11 ones. - Fixed KillPotion and TrollPotion not giving potions. - Removed ArenaBrawl.
#ifndef <API key> #define <API key> #include "jit/mips-shared/<API key>.h" namespace js { namespace jit { class LIRGeneratorMIPS64 : public <API key> { protected: LIRGeneratorMIPS64(MIRGenerator* gen, MIRGraph& graph, LIRGraph& lirGraph) : <API key>(gen, graph, lirGraph) { } protected: // Returns a box allocation. reg2 is ignored on 64-bit platforms. LBoxAllocation useBoxFixed(MDefinition* mir, Register reg1, Register reg2, bool useAtStart = false); inline LDefinition tempToUnbox() { return temp(); } void <API key>(MPhi* phi, uint32_t inputPosition, LBlock* block, size_t lirIndex); void defineUntypedPhi(MPhi* phi, size_t lirIndex); void <API key>(MTruncateToInt32* ins); void <API key>(MTruncateToInt32* ins); public: void visitBox(MBox* box); void visitUnbox(MUnbox* unbox); void visitReturn(MReturn* ret); void visitRandom(MRandom* ins); }; typedef LIRGeneratorMIPS64 <API key>; } // namespace jit } // namespace js #endif /* <API key> */
<!DOCTYPE HTML> <html> <! https://bugzilla.mozilla.org/show_bug.cgi?id=1062406 <head> <title>Test for Bug 1062406</title> <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> </head> <body> <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1062406">Mozilla Bug 1062406</a> <div id="content" style="display: none"> </div> <div style="width:10000px; height:10000px"></div> <pre id="test"> <script type="application/javascript"> /** Test for Bug 1062406 **/ window.scroll(100, 100); window.scroll(NaN, NaN); is(window.scrollX, 0, "window.scroll x parameter must treat NaN as 0."); is(window.scrollY, 0, "window.scroll y parameter must treat NaN as 0."); window.scroll(100, 100); window.scroll(Infinity, Infinity); is(window.scrollX, 0, "window.scroll x parameter must treat Infinity as 0."); is(window.scrollY, 0, "window.scroll y parameter must treat Infinity as 0."); window.scroll(100, 100); window.scroll(-Infinity, -Infinity); is(window.scrollX, 0, "window.scroll x parameter must treat -Infinity as 0."); is(window.scrollY, 0, "window.scroll y parameter must treat -Infinity as 0."); </script> </pre> </body> </html>
<?php # This Source Code Form is subject to the terms of the Mozilla Public define ('NO_HOUSE_KEEPING', true); require ("config.php"); if (JB_TAF_ENABLED != 'YES') { die('Feature disabled'); } echo $JBMarkup->get_doctype(); $JBMarkup->markup_open(); $JBMarkup->head_open(); $JBMarkup->stylesheet_link(JB_get_maincss_url());// <link> to main.css $JBMarkup->charset_meta_tag(); // character set $JBMarkup->no_robots_meta_tag(); // do not follow, do not index $JBMarkup->head_close(); $JBMarkup->body_open('style="background-color:white"'); $submit = JB_clean_str($_REQUEST['submit']); $post_id = (int) $_REQUEST['post_id']; $url = JB_clean_str($_REQUEST['url']); // Assume quotes is always On, we need to strip slashes. $subject = JB_clean_str(stripslashes($_REQUEST['subject'])); $message = JB_clean_str(stripslashes($_REQUEST['message'])); $your_name = JB_clean_str(stripslashes($_REQUEST['your_name'])); $your_email = JB_clean_str(stripslashes($_REQUEST['your_email'])); $to_email = JB_clean_str(stripslashes($_REQUEST['to_email'])); $to_name = JB_clean_str(stripslashes($_REQUEST['to_name'])); if (strlen(trim($to_name))==0) { $to_name = $to_email; } if (strlen(trim($your_name))==0) { $your_name = <API key>($_SESSION['JB_FirstName'], $_SESSION['JB_LastName']); } if (strlen(trim($your_email))==0) { //$your_email = $sql = "SELECT Email from users WHERE ID='".jb_escape_sql($_SESSION['JB_ID'])."'"; $result = jb_mysql_query($sql); if (mysql_num_rows($result)) { $your_email = array_pop(mysql_fetch_row($result)); } } if ($submit != '') { if ($your_email == '') { $error .= $label['taf_email_blank']." <br>"; } elseif (!JB_validate_mail($your_email)) { $error .= $label['taf_email_invalid']."<br>"; } if ($your_name == '') { $error .= $label['taf_name_blank']."<br>"; } if ($to_email == '') { $error .= $label['taf_f_email_blank']."<br>"; } elseif (!JB_validate_mail($to_email)) { $error .= $label['taf_f_email_invalid']."<br>"; } if ($subject == '') { $error .= $label['taf_subject_blank']."<br>"; } // new checks to discourage spam if (!empty($message) && (strlen($message)>140)) { // that's about a paragraph, 3 lines $error .= $label['taf_msg_too_long']."<br>"; } if (!empty($subject) && (strlen($subject)>35)) { $error .= $label['taf_subj_too_long']."<br>"; } if (strpos($message, '://')!==false) { // no URLs allowed $error .= $label['taf_no_url']."<br>"; } if ($error == '') { // send the sucker. $to = $to_email; //$users[$i]; $from = $your_email; // Enter your email adress here $msg = "". $label['taf_msg_to']." $to_name <$to_email>\r\n". $label['taf_msg_from']." $your_name <$your_email>\r\n\r\n". //$label['taf_msg_line']." ".JB_SITE_NAME ."\r\n\r\n". str_replace('%SITE_NAME%', JB_SITE_NAME, $label['taf_msg_line'])."\r\n\r\n". $label['taf_msg_link']."\r\n". "$url\r\n\r\n". $label['taf_msg_comments']."\r\n". $message; // to discourage spam, include IP of sender: $ip = $_SERVER['REMOTE_ADDR']; if (!empty($_SERVER['X-FORWARDED-FOR'])) { $ip = $_SERVER['REMOTE_ADDR']; } $msg .= "---\nX-Sender-IP: ".$ip; echo $label['taf_sending_email']; // anti-spam, we check the email queue, find the last 10 emails in the last 5 minutes // then we silently discard if matches our basic checks $discard = false; $sql = "SELECT * FROM `mail_queue` WHERE `template_id` =46 AND mail_date > DATE_SUB( NOW( ) , INTERVAL 5 MINUTE ) LIMIT 10 "; $result = jb_mysql_query($sql); if (mysql_num_rows($result)>0) { $score = 0; $max_score = 40; // adjust this when adjusting the score rules below while ($row = mysql_fetch_array($result)) { if ($row['subject']===$subject) { // repeat subject $score += 2; } if (strpos($row['message'], $your_name)!==false) { // re-used name $score++; } if (strpos($row['message'], $your_email)!==false) { // re-used email $score++; } } $score = $score / $max_score; if ($score >= 0.5) { $discard = true; // silently discard this message } } if (!$discard) { $email_id = JB_queue_mail($to, $to_name, <API key>, JB_SITE_NAME, $subject, $msg, '', 46); <API key>(1, $email_id); } ?> <hr><?php echo $label['taf_email_sent']; ?> <?php echo jb_escape_html($to_email); ?><b/><br> <p style="text-align:center;"><input onclick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF'])."?post_id=$post_id";?>'" type='button' value='<?php echo $label['<API key>'];?>'><input onclick='window.close(); return false' type="button" value="<?php echo $label['<API key>'];?>"></p> <?php } else { $success = false; $JBMarkup->error_msg($label['taf_error']); echo $error; } } if (($submit == '') || ($error!='') ) { <API key>(); } JBPLUG_do_callback('taf_before_body_end', $A = false); $JBMarkup->body_close(); // </body> $JBMarkup->markup_close(); // </html> ?>
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ #include "nsPrintSettingsImpl.h" #include "nsReadableUtils.h" #include "nsIPrintSession.h" #include "mozilla/RefPtr.h" #define <API key> 0.5 NS_IMPL_ISUPPORTS(nsPrintSettings, nsIPrintSettings) nsPrintSettings::nsPrintSettings() : mPrintOptions(0L), mPrintRange(kRangeAllPages), mStartPageNum(1), mEndPageNum(1), mScaling(1.0), mPrintBGColors(false), mPrintBGImages(false), <API key>(kUseInternalDefault), mPrintFrameType(kFramesAsIs), mHowToEnableFrameUI(kFrameEnableNone), mIsCancelled(false), mPrintSilent(false), mPrintPreview(false), mShrinkToFit(true), mShowPrintProgress(true), mPrintPageDelay(50), mPaperData(0), mPaperWidth(8.5), mPaperHeight(11.0), mPaperSizeUnit(kPaperSizeInches), mPrintReversed(false), mPrintInColor(true), mOrientation(<API key>), mNumCopies(1), mPrintToFile(false), mOutputFormat(kOutputFormatNative), <API key>(false), mIsInitedFromPrefs(false) { /* member initializers and constructor code */ int32_t marginWidth = <API key>(<API key>); mMargin.SizeTo(marginWidth, marginWidth, marginWidth, marginWidth); mEdge.SizeTo(0, 0, 0, 0); mUnwriteableMargin.SizeTo(0,0,0,0); mPrintOptions = kPrintOddPages | kPrintEvenPages; mHeaderStrs[0].AssignLiteral("&T"); mHeaderStrs[2].AssignLiteral("&U"); mFooterStrs[0].AssignLiteral("&PT"); // Use &P (Page Num Only) or &PT (Page Num of Page Total) mFooterStrs[2].AssignLiteral("&D"); } nsPrintSettings::nsPrintSettings(const nsPrintSettings& aPS) { *this = aPS; } nsPrintSettings::~nsPrintSettings() { } NS_IMETHODIMP nsPrintSettings::GetPrintSession(nsIPrintSession **aPrintSession) { <API key>(aPrintSession); *aPrintSession = nullptr; nsCOMPtr<nsIPrintSession> session = do_QueryReferent(mSession); if (!session) return <API key>; *aPrintSession = session; NS_ADDREF(*aPrintSession); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintSession(nsIPrintSession *aPrintSession) { // Clearing it by passing nullptr is not allowed. That's why we // use a weak ref so that it doesn't have to be cleared. NS_ENSURE_ARG(aPrintSession); mSession = do_GetWeakReference(aPrintSession); if (!mSession) { // This may happen if the implementation of this object does // not support weak references - programmer error. NS_ERROR("Could not get a weak reference from aPrintSession"); return NS_ERROR_FAILURE; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetStartPageRange(int32_t *aStartPageRange) { //<API key>(aStartPageRange); *aStartPageRange = mStartPageNum; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetStartPageRange(int32_t aStartPageRange) { mStartPageNum = aStartPageRange; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetEndPageRange(int32_t *aEndPageRange) { //<API key>(aEndPageRange); *aEndPageRange = mEndPageNum; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetEndPageRange(int32_t aEndPageRange) { mEndPageNum = aEndPageRange; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintReversed(bool *aPrintReversed) { //<API key>(aPrintReversed); *aPrintReversed = mPrintReversed; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintReversed(bool aPrintReversed) { mPrintReversed = aPrintReversed; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintInColor(bool *aPrintInColor) { //<API key>(aPrintInColor); *aPrintInColor = mPrintInColor; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintInColor(bool aPrintInColor) { mPrintInColor = aPrintInColor; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetOrientation(int32_t *aOrientation) { <API key>(aOrientation); *aOrientation = mOrientation; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetOrientation(int32_t aOrientation) { mOrientation = aOrientation; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetResolution(int32_t *aResolution) { <API key>(aResolution); *aResolution = mResolution; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetResolution(const int32_t aResolution) { mResolution = aResolution; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetDuplex(int32_t *aDuplex) { <API key>(aDuplex); *aDuplex = mDuplex; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetDuplex(const int32_t aDuplex) { mDuplex = aDuplex; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrinterName(char16_t * *aPrinter) { <API key>(aPrinter); *aPrinter = ToNewUnicode(mPrinter); NS_ENSURE_TRUE(*aPrinter, <API key>); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrinterName(const char16_t * aPrinter) { if (!aPrinter || !mPrinter.Equals(aPrinter)) { <API key> = false; mIsInitedFromPrefs = false; } mPrinter.Assign(aPrinter); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetNumCopies(int32_t *aNumCopies) { <API key>(aNumCopies); *aNumCopies = mNumCopies; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetNumCopies(int32_t aNumCopies) { mNumCopies = aNumCopies; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintToFile(bool *aPrintToFile) { //<API key>(aPrintToFile); *aPrintToFile = mPrintToFile; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintToFile(bool aPrintToFile) { mPrintToFile = aPrintToFile; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetToFileName(char16_t * *aToFileName) { //<API key>(aToFileName); *aToFileName = ToNewUnicode(mToFileName); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetToFileName(const char16_t * aToFileName) { if (aToFileName) { mToFileName = aToFileName; } else { mToFileName.SetLength(0); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetOutputFormat(int16_t *aOutputFormat) { <API key>(aOutputFormat); *aOutputFormat = mOutputFormat; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetOutputFormat(int16_t aOutputFormat) { mOutputFormat = aOutputFormat; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintPageDelay(int32_t *aPrintPageDelay) { *aPrintPageDelay = mPrintPageDelay; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintPageDelay(int32_t aPrintPageDelay) { mPrintPageDelay = aPrintPageDelay; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(bool *<API key>) { <API key>(<API key>); *<API key> = (bool)<API key>; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(bool <API key>) { <API key> = (bool)<API key>; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(bool *<API key>) { <API key>(<API key>); *<API key> = (bool)mIsInitedFromPrefs; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(bool <API key>) { mIsInitedFromPrefs = (bool)<API key>; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetMarginTop(double *aMarginTop) { <API key>(aMarginTop); *aMarginTop = NS_TWIPS_TO_INCHES(mMargin.top); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetMarginTop(double aMarginTop) { mMargin.top = <API key>(float(aMarginTop)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetMarginLeft(double *aMarginLeft) { <API key>(aMarginLeft); *aMarginLeft = NS_TWIPS_TO_INCHES(mMargin.left); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetMarginLeft(double aMarginLeft) { mMargin.left = <API key>(float(aMarginLeft)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetMarginBottom(double *aMarginBottom) { <API key>(aMarginBottom); *aMarginBottom = NS_TWIPS_TO_INCHES(mMargin.bottom); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetMarginBottom(double aMarginBottom) { mMargin.bottom = <API key>(float(aMarginBottom)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetMarginRight(double *aMarginRight) { <API key>(aMarginRight); *aMarginRight = NS_TWIPS_TO_INCHES(mMargin.right); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetMarginRight(double aMarginRight) { mMargin.right = <API key>(float(aMarginRight)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetEdgeTop(double *aEdgeTop) { <API key>(aEdgeTop); *aEdgeTop = NS_TWIPS_TO_INCHES(mEdge.top); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetEdgeTop(double aEdgeTop) { mEdge.top = <API key>(float(aEdgeTop)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetEdgeLeft(double *aEdgeLeft) { <API key>(aEdgeLeft); *aEdgeLeft = NS_TWIPS_TO_INCHES(mEdge.left); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetEdgeLeft(double aEdgeLeft) { mEdge.left = <API key>(float(aEdgeLeft)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetEdgeBottom(double *aEdgeBottom) { <API key>(aEdgeBottom); *aEdgeBottom = NS_TWIPS_TO_INCHES(mEdge.bottom); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetEdgeBottom(double aEdgeBottom) { mEdge.bottom = <API key>(float(aEdgeBottom)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetEdgeRight(double *aEdgeRight) { <API key>(aEdgeRight); *aEdgeRight = NS_TWIPS_TO_INCHES(mEdge.right); return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetEdgeRight(double aEdgeRight) { mEdge.right = <API key>(float(aEdgeRight)); return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double *<API key>) { <API key>(<API key>); *<API key> = NS_TWIPS_TO_INCHES(mUnwriteableMargin.top); return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double <API key>) { if (<API key> >= 0.0) { mUnwriteableMargin.top = <API key>(<API key>); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double *<API key>) { <API key>(<API key>); *<API key> = NS_TWIPS_TO_INCHES(mUnwriteableMargin.left); return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double <API key>) { if (<API key> >= 0.0) { mUnwriteableMargin.left = <API key>(<API key>); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double *<API key>) { <API key>(<API key>); *<API key> = NS_TWIPS_TO_INCHES(mUnwriteableMargin.bottom); return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double <API key>) { if (<API key> >= 0.0) { mUnwriteableMargin.bottom = <API key>(<API key>); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double *<API key>) { <API key>(<API key>); *<API key> = NS_TWIPS_TO_INCHES(mUnwriteableMargin.right); return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double <API key>) { if (<API key> >= 0.0) { mUnwriteableMargin.right = <API key>(<API key>); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetScaling(double *aScaling) { <API key>(aScaling); *aScaling = mScaling; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetScaling(double aScaling) { mScaling = aScaling; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintBGColors(bool *aPrintBGColors) { <API key>(aPrintBGColors); *aPrintBGColors = mPrintBGColors; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintBGColors(bool aPrintBGColors) { mPrintBGColors = aPrintBGColors; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintBGImages(bool *aPrintBGImages) { <API key>(aPrintBGImages); *aPrintBGImages = mPrintBGImages; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintBGImages(bool aPrintBGImages) { mPrintBGImages = aPrintBGImages; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintRange(int16_t *aPrintRange) { <API key>(aPrintRange); *aPrintRange = mPrintRange; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintRange(int16_t aPrintRange) { mPrintRange = aPrintRange; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetTitle(char16_t * *aTitle) { <API key>(aTitle); if (!mTitle.IsEmpty()) { *aTitle = ToNewUnicode(mTitle); } else { *aTitle = nullptr; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetTitle(const char16_t * aTitle) { if (aTitle) { mTitle = aTitle; } else { mTitle.SetLength(0); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetDocURL(char16_t * *aDocURL) { <API key>(aDocURL); if (!mURL.IsEmpty()) { *aDocURL = ToNewUnicode(mURL); } else { *aDocURL = nullptr; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetDocURL(const char16_t * aDocURL) { if (aDocURL) { mURL = aDocURL; } else { mURL.SetLength(0); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintOptions(int32_t aType, bool *aTurnOnOff) { <API key>(aTurnOnOff); *aTurnOnOff = mPrintOptions & aType ? true : false; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintOptions(int32_t aType, bool aTurnOnOff) { if (aTurnOnOff) { mPrintOptions |= aType; } else { mPrintOptions &= ~aType; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintOptionsBits(int32_t *aBits) { <API key>(aBits); *aBits = mPrintOptions; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintOptionsBits(int32_t aBits) { mPrintOptions = aBits; return NS_OK; } nsresult nsPrintSettings::GetMarginStrs(char16_t * *aTitle, nsHeaderFooterEnum aType, int16_t aJust) { <API key>(aTitle); *aTitle = nullptr; if (aType == eHeader) { switch (aJust) { case kJustLeft: *aTitle = ToNewUnicode(mHeaderStrs[0]);break; case kJustCenter: *aTitle = ToNewUnicode(mHeaderStrs[1]);break; case kJustRight: *aTitle = ToNewUnicode(mHeaderStrs[2]);break; } //switch } else { switch (aJust) { case kJustLeft: *aTitle = ToNewUnicode(mFooterStrs[0]);break; case kJustCenter: *aTitle = ToNewUnicode(mFooterStrs[1]);break; case kJustRight: *aTitle = ToNewUnicode(mFooterStrs[2]);break; } //switch } return NS_OK; } nsresult nsPrintSettings::SetMarginStrs(const char16_t * aTitle, nsHeaderFooterEnum aType, int16_t aJust) { <API key>(aTitle); if (aType == eHeader) { switch (aJust) { case kJustLeft: mHeaderStrs[0] = aTitle;break; case kJustCenter: mHeaderStrs[1] = aTitle;break; case kJustRight: mHeaderStrs[2] = aTitle;break; } //switch } else { switch (aJust) { case kJustLeft: mFooterStrs[0] = aTitle;break; case kJustCenter: mFooterStrs[1] = aTitle;break; case kJustRight: mFooterStrs[2] = aTitle;break; } //switch } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetHeaderStrLeft(char16_t * *aTitle) { return GetMarginStrs(aTitle, eHeader, kJustLeft); } NS_IMETHODIMP nsPrintSettings::SetHeaderStrLeft(const char16_t * aTitle) { return SetMarginStrs(aTitle, eHeader, kJustLeft); } NS_IMETHODIMP nsPrintSettings::GetHeaderStrCenter(char16_t * *aTitle) { return GetMarginStrs(aTitle, eHeader, kJustCenter); } NS_IMETHODIMP nsPrintSettings::SetHeaderStrCenter(const char16_t * aTitle) { return SetMarginStrs(aTitle, eHeader, kJustCenter); } NS_IMETHODIMP nsPrintSettings::GetHeaderStrRight(char16_t * *aTitle) { return GetMarginStrs(aTitle, eHeader, kJustRight); } NS_IMETHODIMP nsPrintSettings::SetHeaderStrRight(const char16_t * aTitle) { return SetMarginStrs(aTitle, eHeader, kJustRight); } NS_IMETHODIMP nsPrintSettings::GetFooterStrLeft(char16_t * *aTitle) { return GetMarginStrs(aTitle, eFooter, kJustLeft); } NS_IMETHODIMP nsPrintSettings::SetFooterStrLeft(const char16_t * aTitle) { return SetMarginStrs(aTitle, eFooter, kJustLeft); } NS_IMETHODIMP nsPrintSettings::GetFooterStrCenter(char16_t * *aTitle) { return GetMarginStrs(aTitle, eFooter, kJustCenter); } NS_IMETHODIMP nsPrintSettings::SetFooterStrCenter(const char16_t * aTitle) { return SetMarginStrs(aTitle, eFooter, kJustCenter); } NS_IMETHODIMP nsPrintSettings::GetFooterStrRight(char16_t * *aTitle) { return GetMarginStrs(aTitle, eFooter, kJustRight); } NS_IMETHODIMP nsPrintSettings::SetFooterStrRight(const char16_t * aTitle) { return SetMarginStrs(aTitle, eFooter, kJustRight); } NS_IMETHODIMP nsPrintSettings::<API key>(int16_t *<API key>) { <API key>(<API key>); *<API key> = <API key>; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(int16_t <API key>) { <API key> = <API key>; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintFrameType(int16_t *aPrintFrameType) { <API key>(aPrintFrameType); *aPrintFrameType = (int32_t)mPrintFrameType; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintFrameType(int16_t aPrintFrameType) { mPrintFrameType = aPrintFrameType; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPrintSilent(bool *aPrintSilent) { <API key>(aPrintSilent); *aPrintSilent = mPrintSilent; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPrintSilent(bool aPrintSilent) { mPrintSilent = aPrintSilent; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetShrinkToFit(bool *aShrinkToFit) { <API key>(aShrinkToFit); *aShrinkToFit = mShrinkToFit; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetShrinkToFit(bool aShrinkToFit) { mShrinkToFit = aShrinkToFit; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(bool *aShowPrintProgress) { <API key>(aShowPrintProgress); *aShowPrintProgress = mShowPrintProgress; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(bool aShowPrintProgress) { mShowPrintProgress = aShowPrintProgress; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPaperName(char16_t * *aPaperName) { <API key>(aPaperName); if (!mPaperName.IsEmpty()) { *aPaperName = ToNewUnicode(mPaperName); } else { *aPaperName = nullptr; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPaperName(const char16_t * aPaperName) { if (aPaperName) { mPaperName = aPaperName; } else { mPaperName.SetLength(0); } return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(int16_t *aHowToEnableFrameUI) { <API key>(aHowToEnableFrameUI); *aHowToEnableFrameUI = mHowToEnableFrameUI; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(int16_t aHowToEnableFrameUI) { mHowToEnableFrameUI = aHowToEnableFrameUI; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetIsCancelled(bool *aIsCancelled) { <API key>(aIsCancelled); *aIsCancelled = mIsCancelled; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetIsCancelled(bool aIsCancelled) { mIsCancelled = aIsCancelled; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPaperWidth(double *aPaperWidth) { <API key>(aPaperWidth); *aPaperWidth = mPaperWidth; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPaperWidth(double aPaperWidth) { mPaperWidth = aPaperWidth; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPaperHeight(double *aPaperHeight) { <API key>(aPaperHeight); *aPaperHeight = mPaperHeight; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPaperHeight(double aPaperHeight) { mPaperHeight = aPaperHeight; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPaperSizeUnit(int16_t *aPaperSizeUnit) { <API key>(aPaperSizeUnit); *aPaperSizeUnit = mPaperSizeUnit; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPaperSizeUnit(int16_t aPaperSizeUnit) { mPaperSizeUnit = aPaperSizeUnit; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPaperData(int16_t *aPaperData) { <API key>(aPaperData); *aPaperData = mPaperData; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetPaperData(int16_t aPaperData) { mPaperData = aPaperData; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetMarginInTwips(nsIntMargin& aMargin) { mMargin = aMargin; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetEdgeInTwips(nsIntMargin& aEdge) { mEdge = aEdge; return NS_OK; } // NOTE: Any subclass implementation of this function should make sure // to check for negative margin values in aUnwriteableMargin (which // would indicate that we should use the system default unwriteable margin.) NS_IMETHODIMP nsPrintSettings::<API key>(nsIntMargin& aUnwriteableMargin) { if (aUnwriteableMargin.top >= 0) { mUnwriteableMargin.top = aUnwriteableMargin.top; } if (aUnwriteableMargin.left >= 0) { mUnwriteableMargin.left = aUnwriteableMargin.left; } if (aUnwriteableMargin.bottom >= 0) { mUnwriteableMargin.bottom = aUnwriteableMargin.bottom; } if (aUnwriteableMargin.right >= 0) { mUnwriteableMargin.right = aUnwriteableMargin.right; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetMarginInTwips(nsIntMargin& aMargin) { aMargin = mMargin; return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetEdgeInTwips(nsIntMargin& aEdge) { aEdge = mEdge; return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(nsIntMargin& aUnwriteableMargin) { aUnwriteableMargin = mUnwriteableMargin; return NS_OK; } NS_IMETHODIMP nsPrintSettings::SetupSilentPrinting() { return NS_OK; } NS_IMETHODIMP nsPrintSettings::<API key>(double *aWidth, double *aHeight) { if (mPaperSizeUnit == kPaperSizeInches) { *aWidth = NS_INCHES_TO_TWIPS(float(mPaperWidth)); *aHeight = NS_INCHES_TO_TWIPS(float(mPaperHeight)); } else { *aWidth = <API key>(float(mPaperWidth)); *aHeight = <API key>(float(mPaperHeight)); } if (<API key> == mOrientation) { double temp = *aWidth; *aWidth = *aHeight; *aHeight = temp; } return NS_OK; } NS_IMETHODIMP nsPrintSettings::GetPageRanges(nsTArray<int32_t> &aPages) { aPages.Clear(); return NS_OK; } nsresult nsPrintSettings::_Clone(nsIPrintSettings **_retval) { RefPtr<nsPrintSettings> printSettings = new nsPrintSettings(*this); printSettings.forget(_retval); return NS_OK; } NS_IMETHODIMP nsPrintSettings::Clone(nsIPrintSettings **_retval) { <API key>(_retval); return _Clone(_retval); } nsresult nsPrintSettings::_Assign(nsIPrintSettings *aPS) { nsPrintSettings *ps = static_cast<nsPrintSettings*>(aPS); *this = *ps; return NS_OK; } NS_IMETHODIMP nsPrintSettings::Assign(nsIPrintSettings *aPS) { NS_ENSURE_ARG(aPS); return _Assign(aPS); } nsPrintSettings& nsPrintSettings::operator=(const nsPrintSettings& rhs) { if (this == &rhs) { return *this; } mStartPageNum = rhs.mStartPageNum; mEndPageNum = rhs.mEndPageNum; mMargin = rhs.mMargin; mEdge = rhs.mEdge; mUnwriteableMargin = rhs.mUnwriteableMargin; mScaling = rhs.mScaling; mPrintBGColors = rhs.mPrintBGColors; mPrintBGImages = rhs.mPrintBGImages; mPrintRange = rhs.mPrintRange; mTitle = rhs.mTitle; mURL = rhs.mURL; mHowToEnableFrameUI = rhs.mHowToEnableFrameUI; mIsCancelled = rhs.mIsCancelled; <API key> = rhs.<API key>; mPrintFrameType = rhs.mPrintFrameType; mPrintSilent = rhs.mPrintSilent; mShrinkToFit = rhs.mShrinkToFit; mShowPrintProgress = rhs.mShowPrintProgress; mPaperName = rhs.mPaperName; mPaperData = rhs.mPaperData; mPaperWidth = rhs.mPaperWidth; mPaperHeight = rhs.mPaperHeight; mPaperSizeUnit = rhs.mPaperSizeUnit; mPrintReversed = rhs.mPrintReversed; mPrintInColor = rhs.mPrintInColor; mOrientation = rhs.mOrientation; mNumCopies = rhs.mNumCopies; mPrinter = rhs.mPrinter; mPrintToFile = rhs.mPrintToFile; mToFileName = rhs.mToFileName; mOutputFormat = rhs.mOutputFormat; mPrintPageDelay = rhs.mPrintPageDelay; for (int32_t i=0;i<NUM_HEAD_FOOT;i++) { mHeaderStrs[i] = rhs.mHeaderStrs[i]; mFooterStrs[i] = rhs.mFooterStrs[i]; } return *this; }
const mocha = require('mocha'); const assert = require('chai').assert; const RSI = require('../../../libs/indicators/RSI'); describe('Indicators - RSI', () => { it('should calculate a RSI', function () { let values1 = [0.03942905, 0.04392796, 0.04765162, 0.04517327, 0.045491, 0.05476803, 0.0541574, 0.057, 0.05122999, 0.05158624, 0.0571, 0.06036029, 0.06543595, 0.0864442, 0.08650966, 0.08177442, 0.08258693, 0.08133237, 0.08057352, 0.07530004, 0.07389911, 0.07659014, 0.0760925, 0.07619996, 0.07320906, 0.07645593, 0.07904786, 0.07453816, 0.07330022, 0.06330002, 0.0673268, 0.07140002, 0.0718, 0.0767741, 0.07438594, 0.0745, 0.0756822, 0.07692296, 0.07296102, 0.06884297, 0.06667, 0.07133, 0.0737991, 0.07298951, 0.07240001, 0.07111035, 0.06988019, 0.06968897, 0.06901015, 0.07102435, 0.07010544, 0.06805265, 0.06898778, 0.06837669]; let expected1 = [25.6]; let opts1 = { period: 14, values: values1 } let rsi1 = new RSI(opts1); let output1 = rsi1.calculate(); assert.deepEqual(output1, expected1) }); });
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Page' db.create_table('api_page', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('html', self.gf('django.db.models.fields.TextField')(max_length=10000)), ('original_url', self.gf('django.db.models.fields.URLField')(default='', max_length=200, blank=True)), )) db.send_create_signal('api', ['Page']) def backwards(self, orm): # Deleting model 'Page' db.delete_table('api_page') models = { 'api.page': { 'Meta': {'object_name': 'Page'}, 'html': ('django.db.models.fields.TextField', [], {'max_length': '10000'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'original_url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}) } } complete_apps = ['api']
package private import "testing" func TestGetFreePort(t *testing.T) { p, _ := GetFreePort() if p <= 0 { t.Fatal("expecting > 0 port, got:", p) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `GetProtoObject` fn in crate `script`."> <meta name="keywords" content="rust, rustlang, rust-lang, GetProtoObject"> <title>script::dom::bindings::codegen::Bindings::<API key>::GetProtoObject - Rust</title> <link rel="stylesheet" type="text/css" href="../../../../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../../../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif] <nav class="sidebar"> <p class='location'><a href='../../../../../index.html'>script</a>::<wbr><a href='../../../../index.html'>dom</a>::<wbr><a href='../../../index.html'>bindings</a>::<wbr><a href='../../index.html'>codegen</a>::<wbr><a href='../index.html'>Bindings</a>::<wbr><a href='index.html'><API key></a></p><script>window.sidebarCurrent = {name: 'GetProtoObject', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../../../../../index.html'>script</a>::<wbr><a href='../../../../index.html'>dom</a>::<wbr><a href='../../../index.html'>bindings</a>::<wbr><a href='../../index.html'>codegen</a>::<wbr><a href='../index.html'>Bindings</a>::<wbr><a href='index.html'><API key></a>::<wbr><a class='fn' href=''>GetProtoObject</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-36955' class='srclink' href='../../../../../../src/script/home/servo/buildbot/slave/doc/build/target/debug/build/<API key>/out/Bindings/<API key>.rs.html#101-119' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>fn GetProtoObject(cx: <a class='primitive' href='../../../../../../std/primitive.pointer.html'>*mut </a><a class='enum' href='../../../../../../js/jsapi/enum.JSContext.html' title='js::jsapi::JSContext'>JSContext</a>, global: <a class='type' href='../../../../../../js/jsapi/type.HandleObject.html' title='js::jsapi::HandleObject'>HandleObject</a>, rval: <a class='type' href='../../../../../../js/jsapi/type.MutableHandleObject.html' title='js::jsapi::MutableHandleObject'>MutableHandleObject</a>)</pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../../../../"; window.currentCrate = "script"; window.playgroundUrl = ""; </script> <script src="../../../../../../jquery.js"></script> <script src="../../../../../../main.js"></script> <script defer src="../../../../../../search-index.js"></script> </body> </html>
// Aspia Project // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #include "base/audio/audio_output.h" #include "base/logging.h" #include "build/build_config.h" #if defined(OS_WIN) #include "base/audio/audio_output_win.h" #elif defined(OS_MAC) #include "base/audio/audio_output_mac.h" #elif defined(OS_LINUX) #include "base/audio/audio_output_pulse.h" #endif #include <cstring> namespace base { AudioOutput::AudioOutput(const NeedMoreDataCB& need_more_data_cb) : need_more_data_cb_(need_more_data_cb) { // Nothing } // static std::unique_ptr<AudioOutput> AudioOutput::create(const NeedMoreDataCB& need_more_data_cb) { #if defined(OS_WIN) return std::make_unique<AudioOutputWin>(need_more_data_cb); #elif defined(OS_MAC) return std::make_unique<AudioOutputMac>(need_more_data_cb); #elif defined(OS_LINUX) return std::make_unique<AudioOutputPulse>(need_more_data_cb); #else NOTIMPLEMENTED(); return nullptr; #endif } void AudioOutput::onDataRequest(int16_t* audio_samples, size_t audio_samples_count) { static const size_t <API key> = kSampleRate * 10 / 1000; static const size_t kSamplesPer10ms = kChannels * <API key>; static const size_t kBytesPer10ms = kSamplesPer10ms * sizeof(int16_t); const size_t rounds = audio_samples_count / kSamplesPer10ms; for (size_t i = 0; i < rounds; ++i) { // Get 10ms decoded audio. size_t num_bytes = need_more_data_cb_(audio_samples + (i * kSamplesPer10ms), kBytesPer10ms); if (!num_bytes) { memset(audio_samples, 0, audio_samples_count * sizeof(int16_t)); return; } } } } // namespace base
package cli import ( "os" auditFile "github.com/hashicorp/vault/builtin/audit/file" auditSocket "github.com/hashicorp/vault/builtin/audit/socket" auditSyslog "github.com/hashicorp/vault/builtin/audit/syslog" "github.com/hashicorp/vault/version" credAppId "github.com/hashicorp/vault/builtin/credential/app-id" credAppRole "github.com/hashicorp/vault/builtin/credential/approle" credAwsEc2 "github.com/hashicorp/vault/builtin/credential/aws-ec2" credCert "github.com/hashicorp/vault/builtin/credential/cert" credGitHub "github.com/hashicorp/vault/builtin/credential/github" credLdap "github.com/hashicorp/vault/builtin/credential/ldap" credOkta "github.com/hashicorp/vault/builtin/credential/okta" credRadius "github.com/hashicorp/vault/builtin/credential/radius" credMarathon "github.com/hashicorp/vault/builtin/credential/marathon" credUserpass "github.com/hashicorp/vault/builtin/credential/userpass" "github.com/hashicorp/vault/builtin/logical/aws" "github.com/hashicorp/vault/builtin/logical/cassandra" "github.com/hashicorp/vault/builtin/logical/consul" "github.com/hashicorp/vault/builtin/logical/mongodb" "github.com/hashicorp/vault/builtin/logical/mssql" "github.com/hashicorp/vault/builtin/logical/mysql" "github.com/hashicorp/vault/builtin/logical/pki" "github.com/hashicorp/vault/builtin/logical/postgresql" "github.com/hashicorp/vault/builtin/logical/rabbitmq" "github.com/hashicorp/vault/builtin/logical/ssh" "github.com/hashicorp/vault/builtin/logical/transit" "github.com/hashicorp/vault/audit" "github.com/hashicorp/vault/command" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/meta" "github.com/mitchellh/cli" ) // Commands returns the mapping of CLI commands for Vault. The meta // parameter lets you set meta options for all commands. func Commands(metaPtr *meta.Meta) map[string]cli.CommandFactory { if metaPtr == nil { metaPtr = &meta.Meta{ TokenHelper: command.DefaultTokenHelper, } } if metaPtr.Ui == nil { metaPtr.Ui = &cli.BasicUi{ Writer: os.Stdout, ErrorWriter: os.Stderr, } } return map[string]cli.CommandFactory{ "init": func() (cli.Command, error) { return &command.InitCommand{ Meta: *metaPtr, }, nil }, "server": func() (cli.Command, error) { return &command.ServerCommand{ Meta: *metaPtr, AuditBackends: map[string]audit.Factory{ "file": auditFile.Factory, "syslog": auditSyslog.Factory, "socket": auditSocket.Factory, }, CredentialBackends: map[string]logical.Factory{ "approle": credAppRole.Factory, "cert": credCert.Factory, "aws-ec2": credAwsEc2.Factory, "app-id": credAppId.Factory, "github": credGitHub.Factory, "userpass": credUserpass.Factory, "ldap": credLdap.Factory, "okta": credOkta.Factory, "radius": credRadius.Factory, "marathon": credMarathon.Factory, }, LogicalBackends: map[string]logical.Factory{ "aws": aws.Factory, "consul": consul.Factory, "postgresql": postgresql.Factory, "cassandra": cassandra.Factory, "pki": pki.Factory, "transit": transit.Factory, "mongodb": mongodb.Factory, "mssql": mssql.Factory, "mysql": mysql.Factory, "ssh": ssh.Factory, "rabbitmq": rabbitmq.Factory, }, ShutdownCh: command.MakeShutdownCh(), SighupCh: command.MakeSighupCh(), }, nil }, "ssh": func() (cli.Command, error) { return &command.SSHCommand{ Meta: *metaPtr, }, nil }, "path-help": func() (cli.Command, error) { return &command.PathHelpCommand{ Meta: *metaPtr, }, nil }, "auth": func() (cli.Command, error) { return &command.AuthCommand{ Meta: *metaPtr, Handlers: map[string]command.AuthHandler{ "github": &credGitHub.CLIHandler{}, "userpass": &credUserpass.CLIHandler{DefaultMount: "userpass"}, "ldap": &credLdap.CLIHandler{}, "okta": &credOkta.CLIHandler{}, "cert": &credCert.CLIHandler{}, "radius": &credUserpass.CLIHandler{DefaultMount: "radius"}, "marathon": &credMarathon.CLIHandler{}, }, }, nil }, "auth-enable": func() (cli.Command, error) { return &command.AuthEnableCommand{ Meta: *metaPtr, }, nil }, "auth-disable": func() (cli.Command, error) { return &command.AuthDisableCommand{ Meta: *metaPtr, }, nil }, "audit-list": func() (cli.Command, error) { return &command.AuditListCommand{ Meta: *metaPtr, }, nil }, "audit-disable": func() (cli.Command, error) { return &command.AuditDisableCommand{ Meta: *metaPtr, }, nil }, "audit-enable": func() (cli.Command, error) { return &command.AuditEnableCommand{ Meta: *metaPtr, }, nil }, "key-status": func() (cli.Command, error) { return &command.KeyStatusCommand{ Meta: *metaPtr, }, nil }, "policies": func() (cli.Command, error) { return &command.PolicyListCommand{ Meta: *metaPtr, }, nil }, "policy-delete": func() (cli.Command, error) { return &command.PolicyDeleteCommand{ Meta: *metaPtr, }, nil }, "policy-write": func() (cli.Command, error) { return &command.PolicyWriteCommand{ Meta: *metaPtr, }, nil }, "read": func() (cli.Command, error) { return &command.ReadCommand{ Meta: *metaPtr, }, nil }, "unwrap": func() (cli.Command, error) { return &command.UnwrapCommand{ Meta: *metaPtr, }, nil }, "list": func() (cli.Command, error) { return &command.ListCommand{ Meta: *metaPtr, }, nil }, "write": func() (cli.Command, error) { return &command.WriteCommand{ Meta: *metaPtr, }, nil }, "delete": func() (cli.Command, error) { return &command.DeleteCommand{ Meta: *metaPtr, }, nil }, "rekey": func() (cli.Command, error) { return &command.RekeyCommand{ Meta: *metaPtr, }, nil }, "generate-root": func() (cli.Command, error) { return &command.GenerateRootCommand{ Meta: *metaPtr, }, nil }, "renew": func() (cli.Command, error) { return &command.RenewCommand{ Meta: *metaPtr, }, nil }, "revoke": func() (cli.Command, error) { return &command.RevokeCommand{ Meta: *metaPtr, }, nil }, "seal": func() (cli.Command, error) { return &command.SealCommand{ Meta: *metaPtr, }, nil }, "status": func() (cli.Command, error) { return &command.StatusCommand{ Meta: *metaPtr, }, nil }, "unseal": func() (cli.Command, error) { return &command.UnsealCommand{ Meta: *metaPtr, }, nil }, "step-down": func() (cli.Command, error) { return &command.StepDownCommand{ Meta: *metaPtr, }, nil }, "mount": func() (cli.Command, error) { return &command.MountCommand{ Meta: *metaPtr, }, nil }, "mounts": func() (cli.Command, error) { return &command.MountsCommand{ Meta: *metaPtr, }, nil }, "mount-tune": func() (cli.Command, error) { return &command.MountTuneCommand{ Meta: *metaPtr, }, nil }, "remount": func() (cli.Command, error) { return &command.RemountCommand{ Meta: *metaPtr, }, nil }, "rotate": func() (cli.Command, error) { return &command.RotateCommand{ Meta: *metaPtr, }, nil }, "unmount": func() (cli.Command, error) { return &command.UnmountCommand{ Meta: *metaPtr, }, nil }, "token-create": func() (cli.Command, error) { return &command.TokenCreateCommand{ Meta: *metaPtr, }, nil }, "token-lookup": func() (cli.Command, error) { return &command.TokenLookupCommand{ Meta: *metaPtr, }, nil }, "token-renew": func() (cli.Command, error) { return &command.TokenRenewCommand{ Meta: *metaPtr, }, nil }, "token-revoke": func() (cli.Command, error) { return &command.TokenRevokeCommand{ Meta: *metaPtr, }, nil }, "capabilities": func() (cli.Command, error) { return &command.CapabilitiesCommand{ Meta: *metaPtr, }, nil }, "version": func() (cli.Command, error) { versionInfo := version.GetVersion() return &command.VersionCommand{ VersionInfo: versionInfo, Ui: metaPtr.Ui, }, nil }, } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `load_with` fn in crate `gleam`."> <meta name="keywords" content="rust, rustlang, rust-lang, load_with"> <title>gleam::gl::GetString::load_with - Rust</title> <link rel="stylesheet" type="text/css" href="../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif] <nav class="sidebar"> <p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a href='index.html'>GetString</a></p><script>window.sidebarCurrent = {name: 'load_with', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a href='index.html'>GetString</a>::<wbr><a class='fn' href=''>load_with</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-7364' class='srclink' href='../../../src/gleam/home/servo/buildbot/slave/doc/build/target/debug/build/<API key>/out/gl_bindings.rs.html#10913-10917' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub fn load_with&lt;F&gt;(loadfn: F) <span class='where'>where F: <a class='trait' href='../../../core/ops/trait.FnMut.html' title='core::ops::FnMut'>FnMut</a>(&amp;<a class='primitive' href='../../../std/primitive.str.html'>str</a>) -&gt; <a class='primitive' href='../../../std/primitive.pointer.html'>*const </a><a class='enum' href='../../../gleam/ffi/__gl_imports/raw/enum.c_void.html' title='gleam::ffi::__gl_imports::raw::c_void'>c_void</a></span></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../"; window.currentCrate = "gleam"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script defer src="../../../search-index.js"></script> </body> </html>
SUBROUTINE SLAROT( LROWS, LLEFT, LRIGHT, NL, C, S, A, LDA, XLEFT, $ XRIGHT ) * * -- LAPACK auxiliary test routine (version 3.1) -- * Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. * November 2006 * * .. Scalar Arguments .. LOGICAL LLEFT, LRIGHT, LROWS INTEGER LDA, NL REAL C, S, XLEFT, XRIGHT * .. * .. Array Arguments .. REAL A( * ) * .. * * Purpose * ======= * * SLAROT applies a (Givens) rotation to two adjacent rows or * columns, where one element of the first and/or last column/row * November 2006 * for use on matrices stored in some format other than GE, so * that elements of the matrix may be used or modified for which * no array element is provided. * * One example is a symmetric matrix in SB format (bandwidth=4), for * which UPLO='L': Two adjacent rows will have the format: * * row j: * * * * * . . . . * row j+1: * * * * * . . . . * * '*' indicates elements for which storage is provided, * '.' indicates elements for which no storage is provided, but * are not necessarily zero; their values are determined by * symmetry. ' ' indicates elements which are necessarily zero, * and have no storage provided. * * Those columns which have two '*'s can be handled by SROT. * Those columns which have no '*'s can be ignored, since as long * as the Givens rotations are carefully applied to preserve * symmetry, their values are determined. * Those columns which have one '*' have to be handled separately, * by using separate variables "p" and "q": * * row j: * * * * * p . . . * row j+1: q * * * * * . . . . * * The element p would have to be set correctly, then that column * is rotated, setting p to its new value. The next call to * SLAROT would rotate columns j and j+1, using p, and restore * symmetry. The element q would start out being zero, and be * made non-zero by the rotation. Later, rotations would presumably * be chosen to zero q out. * * Typical Calling Sequences: rotating the i-th and (i+1)-st rows. * * * General dense matrix: * * CALL SLAROT(.TRUE.,.FALSE.,.FALSE., N, C,S, * A(i,1),LDA, DUMMY, DUMMY) * * General banded matrix in GB format: * * j = MAX(1, i-KL ) * NL = MIN( N, i+KU+1 ) + 1-j * CALL SLAROT( .TRUE., i-KL.GE.1, i+KU.LT.N, NL, C,S, * A(KU+i+1-j,j),LDA-1, XLEFT, XRIGHT ) * * [ note that i+1-j is just MIN(i,KL+1) ] * * Symmetric banded matrix in SY format, bandwidth K, * lower triangle only: * * j = MAX(1, i-K ) * NL = MIN( K+1, i ) + 1 * CALL SLAROT( .TRUE., i-K.GE.1, .TRUE., NL, C,S, * A(i,j), LDA, XLEFT, XRIGHT ) * * Same, but upper triangle only: * * NL = MIN( K+1, N-i ) + 1 * CALL SLAROT( .TRUE., .TRUE., i+K.LT.N, NL, C,S, * A(i,i), LDA, XLEFT, XRIGHT ) * * Symmetric banded matrix in SB format, bandwidth K, * lower triangle only: * * [ same as for SY, except:] * . . . . * A(i+1-j,j), LDA-1, XLEFT, XRIGHT ) * * [ note that i+1-j is just MIN(i,K+1) ] * * Same, but upper triangle only: * . . . * A(K+1,i), LDA-1, XLEFT, XRIGHT ) * * Rotating columns is just the transpose of rotating rows, except * for GB and SB: (rotating columns i and i+1) * * GB: * j = MAX(1, i-KU ) * NL = MIN( N, i+KL+1 ) + 1-j * CALL SLAROT( .TRUE., i-KU.GE.1, i+KL.LT.N, NL, C,S, * A(KU+j+1-i,i),LDA-1, XTOP, XBOTTM ) * * [note that KU+j+1-i is just MAX(1,KU+2-i)] * * SB: (upper triangle) * * . . . . . . * A(K+j+1-i,i),LDA-1, XTOP, XBOTTM ) * * SB: (lower triangle) * * . . . . . . * A(1,i),LDA-1, XTOP, XBOTTM ) * * Arguments * ========= * * LROWS - LOGICAL * If .TRUE., then SLAROT will rotate two rows. If .FALSE., * then it will rotate two columns. * Not modified. * * LLEFT - LOGICAL * If .TRUE., then XLEFT will be used instead of the * corresponding element of A for the first element in the * second row (if LROWS=.FALSE.) or column (if LROWS=.TRUE.) * If .FALSE., then the corresponding element of A will be * used. * Not modified. * * LRIGHT - LOGICAL * If .TRUE., then XRIGHT will be used instead of the * corresponding element of A for the last element in the * first row (if LROWS=.FALSE.) or column (if LROWS=.TRUE.) If * .FALSE., then the corresponding element of A will be used. * Not modified. * * NL - INTEGER * The length of the rows (if LROWS=.TRUE.) or columns (if * LROWS=.FALSE.) to be rotated. If XLEFT and/or XRIGHT are * used, the columns/rows they are in should be included in * NL, e.g., if LLEFT = LRIGHT = .TRUE., then NL must be at * least 2. The number of rows/columns to be rotated * exclusive of those involving XLEFT and/or XRIGHT may * not be negative, i.e., NL minus how many of LLEFT and * LRIGHT are .TRUE. must be at least zero; if not, XERBLA * will be called. * Not modified. * * C, S - REAL * Specify the Givens rotation to be applied. If LROWS is * true, then the matrix ( c s ) * (-s c ) is applied from the left; * if false, then the transpose thereof is applied from the * right. For a Givens rotation, C**2 + S**2 should be 1, * but this is not checked. * Not modified. * * A - REAL array. * The array containing the rows/columns to be rotated. The * first element of A should be the upper left element to * be rotated. * Read and modified. * * LDA - INTEGER * The "effective" leading dimension of A. If A contains * a matrix stored in GE or SY format, then this is just * the leading dimension of A as dimensioned in the calling * routine. If A contains a matrix stored in band (GB or SB) * format, then this should be *one less* than the leading * dimension used in the calling routine. Thus, if * A were dimensioned A(LDA,*) in SLAROT, then A(1,j) would * be the j-th element in the first of the two rows * to be rotated, and A(2,j) would be the j-th in the second, * regardless of how the array may be stored in the calling * routine. [A cannot, however, actually be dimensioned thus, * since for band format, the row number may exceed LDA, which * is not legal FORTRAN.] * If LROWS=.TRUE., then LDA must be at least 1, otherwise * it must be at least NL minus the number of .TRUE. values * in XLEFT and XRIGHT. * Not modified. * * XLEFT - REAL * If LLEFT is .TRUE., then XLEFT will be used and modified * instead of A(2,1) (if LROWS=.TRUE.) or A(1,2) * (if LROWS=.FALSE.). * Read and modified. * * XRIGHT - REAL * If LRIGHT is .TRUE., then XRIGHT will be used and modified * instead of A(1,NL) (if LROWS=.TRUE.) or A(NL,1) * (if LROWS=.FALSE.). * Read and modified. * * ===================================================================== * * .. Local Scalars .. INTEGER IINC, INEXT, IX, IY, IYT, NT * .. * .. Local Arrays .. REAL XT( 2 ), YT( 2 ) * .. * .. External Subroutines .. EXTERNAL SROT, XERBLA * .. * .. Executable Statements .. * * Set up indices, arrays for ends * IF( LROWS ) THEN IINC = LDA INEXT = 1 ELSE IINC = 1 INEXT = LDA END IF * IF( LLEFT ) THEN NT = 1 IX = 1 + IINC IY = 2 + LDA XT( 1 ) = A( 1 ) YT( 1 ) = XLEFT ELSE NT = 0 IX = 1 IY = 1 + INEXT END IF * IF( LRIGHT ) THEN IYT = 1 + INEXT + ( NL-1 )*IINC NT = NT + 1 XT( NT ) = XRIGHT YT( NT ) = A( IYT ) ELSE IYT = 1 END IF * * Check for errors * IF( NL.LT.NT ) THEN CALL XERBLA( 'SLAROT', 4 ) RETURN END IF IF( LDA.LE.0 .OR. ( .NOT.LROWS .AND. LDA.LT.NL-NT ) ) THEN CALL XERBLA( 'SLAROT', 8 ) RETURN END IF * * Rotate * CALL SROT( NL-NT, A( IX ), IINC, A( IY ), IINC, C, S ) CALL SROT( NT, XT, 1, YT, 1, C, S ) * * Stuff values back into XLEFT, XRIGHT, etc. * IF( LLEFT ) THEN A( 1 ) = XT( 1 ) XLEFT = YT( 1 ) END IF * IF( LRIGHT ) THEN XRIGHT = XT( NT ) A( IYT ) = YT( NT ) END IF * RETURN * * End of SLAROT * END
RailsApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.<API key> = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.<API key> = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use <API key> built into browsers config.action_dispatch.<API key> = :builtin end
//This file is part of Finjin Engine (finjin-engine). //Finjin Engine is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. //This Source Code Form is subject to the terms of the Mozilla Public #pragma once #include "finjin/common/Utf8String.hpp" namespace Finjin { namespace Engine { using namespace Finjin::Common; enum class VulkanShaderType { VERTEX, <API key>, <API key>, GEOMETRY, FRAGMENT, COMPUTE, COUNT }; struct <API key> { static const char* ToString(VulkanShaderType value) { switch (value) { case VulkanShaderType::VERTEX: return "vertex"; case VulkanShaderType::<API key>: return "tessellation control"; case VulkanShaderType::<API key>: return "tessellation evaluation"; case VulkanShaderType::GEOMETRY: return "geometry"; case VulkanShaderType::FRAGMENT: return "fragment"; case VulkanShaderType::COMPUTE: return "compute"; default: return <API key>; } } }; } }
layout: "aws" page_title: "AWS: <API key>" sidebar_current: "<API key>" description: |- Provides a resource to create a Service Catalog portfolio # Resource: <API key> Provides a resource to create a Service Catalog Portfolio. ## Example Usage hcl resource "<API key>" "portfolio" { name = "My App Portfolio" description = "List of my organizations apps" provider_name = "Brett" } ## Argument Reference The following arguments are supported: * `name` - (Required) The name of the portfolio. * `description` - (Required) Description of the portfolio * `provider_name` - (Required) Name of the person or organization who owns the portfolio. * `tags` - (Optional) Tags to apply to the connection. ## Attributes Reference In addition to all arguments above, the following attributes are exported: * `id` - The ID of the Service Catalog Portfolio. ## Import Service Catalog Portfolios can be imported using the `service catalog portfolio id`, e.g. $ terraform import <API key>.testfolio port-12344321
#pragma once #include <gsCore/gsTemplateTools.h> #ifdef __MINGW32__ //#include <malloc/malloc.h> //xcode #include <malloc.h> #endif #if __cplusplus < 201103 && defined( __GLIBCXX__ ) # if defined(__INTEL_COMPILER) # include <boost/shared_ptr.hpp> # include <boost/weak_ptr.hpp> # else # include <tr1/memory> # endif #else // libc++ or other # include <memory> #endif namespace gismo { /** @namespace gismo::memory @brief This namespace contains functions related to memory management. \ingroup Core */ namespace memory { /* \brief Adaptor for a shared pointer usage: \code memory::shared_ptr<int> B; \endcode */ #if __cplusplus < 201103 && defined( __GLIBCXX__ ) # if defined(__INTEL_COMPILER) using boost::shared_ptr; using boost::weak_ptr; # else using std::tr1::shared_ptr; using std::tr1::weak_ptr; # endif #else // libc++ or other using std::shared_ptr; using std::weak_ptr; #endif /* \brief Adaptor for a unique pointer usage: \code memory::unique_ptr<int> B; \endcode */ #if __cplusplus >= 201103 || _MSC_VER >= 1600 using std::unique_ptr; using std::nullptr_t; #else template <typename T> class unique_ptr : public std::auto_ptr<T> { typedef std::auto_ptr<T> Base; typedef std::auto_ptr_ref<T> unique_ptr_ref; //struct <API key>; public : explicit unique_ptr(T* p = 0) throw() : Base(p) { } unique_ptr(const unique_ptr& r) : Base( const_cast<unique_ptr&>(r) ) { } unique_ptr(unique_ptr_ref m) throw() : Base(m) { } template<typename U> unique_ptr(const unique_ptr<U> & r // unique_ptr<typename conditional<is_base_of<U,T>::value, U, // <API key> >::type> ) throw() : Base( const_cast<unique_ptr<U>&>(r) ) { } unique_ptr & operator=(const unique_ptr& other) throw() { Base::operator=(const_cast<unique_ptr&>(other)); return *this; } template<class U> unique_ptr & operator=(const unique_ptr<U> & other) throw() { Base::operator=(const_cast<unique_ptr<U>&>(other)); return *this; } //operator shared_ptr<T> () { return shared_ptr<T>(this->release()); } template<class U> operator shared_ptr<U>() // shared_ptr<typename conditional<is_base_of<U,T>::value, U, // <API key> >::type> () { return shared_ptr<U>(Base::release()); } bool operator!() const { return Base::get() == NULL; } private: struct SafeBool { SafeBool(int) {} void dummy() {} }; typedef void (SafeBool::*bool_cast_type)(); public: operator bool_cast_type() const { return !Base::get() ? 0 : &SafeBool::dummy; } }; template<class T> bool operator==(const unique_ptr<T> & p1, const unique_ptr<T> & p2) { return p1.get()==p2.get(); } template<class T> bool operator!=(const unique_ptr<T> & p1, const unique_ptr<T> & p2) { return p1.get()!=p2.get(); } template<class T> bool operator<(const unique_ptr<T> & p1, const unique_ptr<T> & p2) { return p1.get()<p2.get(); } template<class T> bool operator>(const unique_ptr<T> & p1, const unique_ptr<T> & p2) { return p1.get()>p2.get(); } template<class T> bool operator<=(const unique_ptr<T> & p1, const unique_ptr<T> & p2) { return p1.get()<=p2.get(); } template<class T> bool operator>=(const unique_ptr<T> & p1, const unique_ptr<T> & p2) { return p1.get()>=p2.get(); } class nullptr_t { public: /* Return 0 for any class pointer */ template<typename T> operator T*() const {return 0;} /* Return 0 for any member pointer */ template<typename T, typename U> operator T U::*() const {return 0;} /* Safe boolean conversion */ operator void*() const {return 0;} private: /* Not allowed to get the address */ void operator&() const; }; #endif \brief Deleter function that does not delete an object pointer template <typename T> void null_deleter(T *) {} Takes a T* and wraps it in a shared_ptr. Useful for avoiding memory leaks. This has a move semantics: the shared_ptr object takes the ownership. template <typename T> inline shared_ptr<T> make_shared(T *x) { return shared_ptr<T>(x); } \brief Creates a shared pointer which does not eventually delete the underlying raw pointer. Usefull to refer to objects which should not be destroyed. The caller keeps the ownership. template <typename T> inline shared_ptr<T> <API key>(const T *x) { return shared_ptr<T>(const_cast<T*>(x), null_deleter<T>); } Takes a T* and wraps it in an unique_ptr. Useful for one-off function return values to avoid memory leaks. This has a move semantics: the unique_ptr object takes the ownership. template <typename T> inline unique_ptr<T> make_unique(T * x) { return unique_ptr<T>(x); } \brief Converts an uPtr \a p to an uPtr of class \a toC and gives it back as return value. template<class toC, typename from> inline unique_ptr<toC> convert_ptr(from p) { return unique_ptr<toC>( dynamic_cast<toC*>(p.release()) ); } Takes a vector of smart pointers and returns the corresponding raw pointers. template <typename T> inline std::vector<T*> get_raw(const std::vector< unique_ptr<T> >& cont) { std::vector<T*> result; for (typename std::vector< unique_ptr<T> >::const_iterator it = cont.begin(); it != cont.end(); ++it) result.push_back(const_cast<T*>( (*it).get() )); return result; } Takes a vector of smart pointers and returns the corresponding raw pointers. template <typename T> inline std::vector<T*> get_raw(const std::vector< shared_ptr<T> >& cont) { std::vector<T*> result; for (typename std::vector< shared_ptr<T> >::const_iterator it = cont.begin(); it != cont.end(); ++it) result.push_back(const_cast<T*>( (*it).get() )); return result; } Takes a vector of smart pointers, releases them and returns the corresponding raw pointers. template <typename T> inline std::vector<T*> release(std::vector< unique_ptr<T> >& cont) { std::vector<T*> result; for (typename std::vector< unique_ptr<T> >::iterator it = cont.begin(); it != cont.end(); ++it) result.push_back( (*it).release() ); cont.clear(); return result; } } // namespace memory #if __cplusplus >= 201103 || _MSC_VER >= 1900 // fix MSVC 2013- (_MSC_VER < 1900) // MSVC < 1900 do not work probably. give makes a deep copy for return value, // losses left value. But the alternative code results in segmentation vaults // because a swap/give loop leads to a stack overflow. // From the adresses, it seams that Eigen do not support rvalue with MSVC < 1900 // Therefore disabled <API key> for MSVC < 1900 and use // alternative code. /** Alias for std::move, to be used instead of writing std::move for keeping backward c++98 compatibility */ template <class T> inline auto give(T&& t) -> decltype(std::move(std::forward<T>(t))) { #if defined(GISMO_EXTRA_DEBUG) && ! defined(_MSC_VER) // TODO: is there way that also MS can check this? static_assert( util::<API key><typename std::remove_reference<T>::type>::value, "There is no move constructor. Copy would be created." ); #endif return std::move(std::forward<T>(t)); } #else /** Alias for std::move, to be used instead of std::move for backward c++98 compatibility and MSVC before 2015 Based on swapping and copy elision. */ template <typename S> inline S give(S & x) { S t; t.swap(x); return t; } template <typename T> inline memory::unique_ptr<T> give(memory::unique_ptr<T> & x) { return memory::unique_ptr<T>(x.release()); } template <typename T> inline memory::shared_ptr<T> give(memory::shared_ptr<T> & x) { memory::shared_ptr<T> result = x; x.reset(); return result; } #endif // Small, dynamically sized arrays on the stack, for POD types. // Only use this if the size is guaranteed not to be more than a few // hundred bytes! Be warned: overflow occurs without any warning #if defined(GISMO_WITH_GMP) || defined(GISMO_WITH_MPFR) #define STACK_ARRAY( T, name, sz ) T name[sz]; #else // Note: VLAs(following line) can be buggy on some compilers/versions, // also not nececarily on the stack // #define STACK_ARRAY( T, name, sz ) T name[sz]; #define STACK_ARRAY( T, name, sz ) T * name = (T*) alloca ( (sz) * sizeof(T) ); #endif \brief Clones all pointers in the range [\a start \a end) and stores new raw pointers in iterator \a out. template <typename It, typename ItOut> void cloneAll(It start, It end, ItOut out) { for (It i = start; i != end; ++i) *out++ = dynamic_cast<typename std::iterator_traits<ItOut>::value_type>((*i)->clone().release()); } \brief Clones all pointers in the container \a in and stores them as raw pointers in container \a out template <typename ContIn, typename ContOut> void cloneAll(const ContIn& in, ContOut& out) { out.resize(in.size()); cloneAll(in.begin(), in.end(), out.begin()); } \brief Frees all pointers in the range [\a begin \a end) template <typename It> void freeAll(It begin, It end) { for (It it = begin; it != end; ++it) { delete (*it); *it = NULL; } } \brief Frees all pointers in the container \a Cont template <typename Cont> void freeAll(Cont& cont) { for (typename Cont::iterator it = cont.begin(); it != cont.end(); ++it) delete (*it); cont.clear(); } \brief Constructs a vector of pointers from a vector of objects template<typename obj> inline std::vector<obj*> asVectorPtr(const std::vector<obj> & matv) { std::vector<obj*> result; const size_t d = matv.size(); result.reserve(d); for ( size_t i = 0; i!=d; ++i) result.push_back( const_cast<obj*>(&matv[i]) ); return result; } \brief Casts a vector of pointers template <typename Base, typename Derived> std::vector<Base*> castVectorPtr(std::vector<Derived*> pVec) { std::vector<Base*> result(pVec.size()); std::copy(pVec.begin(), pVec.end(), result.begin() ); return result; } \brief Returns true if all instances of \a Base cast to \a Derived template <typename Derived, typename Base> bool checkVectorPtrCast(std::vector<Base*> pVec) { for (typename std::vector<Base*>::iterator it = pVec.begin(); it != pVec.end(); ++it) if ( ! dynamic_cast<Derived*>(*it) ) return false; return true; } /** \brief Small wrapper for std::copy mimicking memcpy (or std::copy_n) for a raw pointer destination, copies \a n positions starting from \a begin into \a result. The latter is expected to have been allocated in advance */ template <class T, class U> inline void copy_n(T begin, const size_t n, U* result) { std::copy(begin, begin+n, # ifdef _MSC_VER // Take care of C4996 warning //stdext::<API key><U*>(result,n)); stdext::<API key><U*>(result)); # else result); // Note: in C++11 there is: // std::copy_n(begin, n, result); # endif } namespace util { /** \brief Small wrapper for std::copy mimicking std::copy for a raw pointer destination, copies \a n positions starting from \a begin into \a result. The latter is expected to have been allocated in advance */ template <class T, class U> inline void copy(T begin, T end, U* result) { std::copy(begin, end, # ifdef _MSC_VER // Take care of C4996 warning //stdext::<API key><U*>(result,n)); stdext::<API key><U*>(result)); # else result); # endif } } } // namespace gismo #if __cplusplus < 201103L && _MSC_VER < 1600 && !defined(nullptr) // Define nullptr for compatibility with newer C++ static const gismo::memory::nullptr_t nullptr ={}; #endif
#pragma once #include <alpaka/atomic/Traits.hpp> #include <alpaka/core/Unused.hpp> namespace alpaka { //! The CPU fibers accelerator atomic ops. class AtomicNoOp { public: AtomicNoOp() = default; AtomicNoOp(AtomicNoOp const&) = delete; AtomicNoOp(AtomicNoOp&&) = delete; auto operator=(AtomicNoOp const&) -> AtomicNoOp& = delete; auto operator=(AtomicNoOp&&) -> AtomicNoOp& = delete; /*virtual*/ ~AtomicNoOp() = default; }; namespace traits { //! The CPU fibers accelerator atomic operation. template<typename TOp, typename T, typename THierarchy> struct AtomicOp<TOp, AtomicNoOp, T, THierarchy> { ALPAKA_FN_HOST static auto atomicOp(AtomicNoOp const& atomic, T* const addr, T const& value) -> T { alpaka::ignore_unused(atomic); return TOp()(addr, value); } ALPAKA_FN_HOST static auto atomicOp( AtomicNoOp const& atomic, T* const addr, T const& compare, T const& value) -> T { alpaka::ignore_unused(atomic); return TOp()(addr, compare, value); } }; } // namespace traits } // namespace alpaka
// Mathematics and Physics, Charles University in Prague, Czech Republic. // This Source Code Form is subject to the terms of the Mozilla Public #include <cstring> #include "options.h" namespace ufal { namespace nametag { namespace utils { const options::value options::value::none(NONE); const options::value options::value::any(ANY); bool options::parse(const unordered_map<string, value>& allowed, int& argc, char**& argv, map& options) { int args = 1; bool options_allowed = true; for (int argi = 1; argi < argc; argi++) if (argv[argi][0] == '-' && options_allowed) { if (argv[argi][1] == '-' && argv[argi][2] == '\0') { options_allowed = false; continue; } const char* option = argv[argi] + 1 + (argv[argi][1] == '-'); const char* equal_sign = strchr(option, '='); string key = equal_sign ? string(option, equal_sign - option) : string(option); auto option_info = allowed.find(key); if (option_info == allowed.end()) return cerr << "Unknown option '" << argv[argi] << "'." << endl, false; string value; if (option_info->second.allowed == value::NONE && equal_sign) return cerr << "Option '" << key << "' cannot have value." << endl, false; if (option_info->second.allowed != value::NONE) { if (equal_sign) { value.assign(equal_sign + 1); } else { if (argi + 1 == argc) return cerr << "Missing value for option '" << key << "'." << endl, false; value.assign(argv[++argi]); } if (!(option_info->second.allowed == value::ANY || (option_info->second.allowed == value::SET && option_info->second.set.count(value)))) return cerr << "Option '" << key << "' cannot have value '" << value << "'." << endl, false; } options[key] = value; } else { argv[args++] = argv[argi]; } argc = args; return true; } } // namespace utils } // namespace nametag } // namespace ufal
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ var gTestfile = 'regress-452703.js'; var BUGNUMBER = 452703; var summary = 'Do not assert with JIT: rmask(rr)&FpRegs'; var actual = 'No Crash'; var expect = 'No Crash'; printBugNumber(BUGNUMBER); printStatus (summary); jit(true); (function() { for(let y in [0,1,2,3,4]) y = NaN; })(); jit(false); reportCompare(expect, actual, summary);
package org.casual.civic.service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.casual.civic.data.PoliticianData; import org.casual.civic.exception.<API key>; import org.casual.civic.exception.<API key>; import org.casual.civic.utils.ProcessorHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.<API key>; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import retrofit.client.Response; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @Service public class <API key> { private JdbcTemplate jdbcTemplate; @Autowired private <API key>(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(); this.jdbcTemplate.setDataSource(dataSource); } public List<PoliticianData> retrieveAll() { final PoliticianMapper pm = new PoliticianMapper(); final String sql = "select " + pm.schema() + " order by p.name"; return this.jdbcTemplate.query(sql, pm, new Object[] {}); } public List<PoliticianData> retrieveByLatLong(final double latitude, final double longitude) { final PoliticianMapper pm = new PoliticianMapper(); final String sql = "select " + pm.schema() + " inner join c_assemblies cpo on cpo.objectid=cc.polygon_id " + " where cpo.objectid = (select cpoo.objectid from c_assemblies cpoo where st_contains(cpoo.`the_geom`, point(?, ?))) order by p.name"; return this.jdbcTemplate.query(sql, pm, new Object[] {longitude, latitude}); } public List<PoliticianData> retrieveByAddress(final String address) { try { final GeocodingService service = ProcessorHelper .<API key>("https://maps.googleapis.com/maps/api/geocode"); final Map<String, String> queryParams = new HashMap<String, String> (); queryParams.put("address", address); queryParams.put("bounds", "28.3247893,76.7824797|28.9184529,77.3331994"); String sql = "select `key` from c_api_keys limit 1"; final List<String> apiKeys = this.jdbcTemplate.queryForList(sql, String.class); final String geocodingApiKey = apiKeys.get(0); queryParams.put("key", geocodingApiKey); final Response response = service.<API key>(queryParams); final JsonObject location = new JsonParser().parse(ProcessorHelper.getResponse(response)).getAsJsonObject() .get("results").getAsJsonArray().get(0).getAsJsonObject().get("geometry") .getAsJsonObject().get("location").getAsJsonObject(); final double lat = location.get("lat").getAsDouble(); final double longitude = location.get("lng").getAsDouble(); final PoliticianMapper pm = new PoliticianMapper(); sql = "select " + pm.schema() + " inner join c_assemblies cpo on cpo.objectid=cc.polygon_id " + " where cpo.objectid = (select cpoo.objectid from c_assemblies cpoo where st_contains(cpoo.`the_geom`, point(?, ?))) order by p.name"; return this.jdbcTemplate.query(sql, pm, new Object[] {longitude, lat}); } catch (Exception e) { e.printStackTrace(); throw new <API key>(); } } public String retrieveApiKey(int index) { String sql = "select `key` from c_api_keys"; final List<String> apiKeys = this.jdbcTemplate.queryForList(sql, String.class); return apiKeys.get(index); } public PoliticianData retrieveOne(final Long politicianId) { try { final PoliticianMapper pm = new PoliticianMapper(); final String sql = "select " + pm.schema() + " where p.id=? order by p.name"; return this.jdbcTemplate.queryForObject(sql, pm, new Object[] {politicianId}); } catch (<API key> exception) { throw new <API key>(politicianId); } } private static final class PoliticianMapper implements RowMapper<PoliticianData> { public String schema() { return " p.id as id, p.name, cc.`name` as constituencyName, cp.`abbreviation` as partyName, p.`<API key>`, p.`education`, p.`totalAssets`, p.`liabilities`," + " p.address, p.email, p.contact, p.ipc from c_politician p inner join c_party cp on p.`party_id`=cp.`id`" + " inner join c_constituency cc on cc.`id`=p.`constituency_id` "; } @Override public PoliticianData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); final String constituencyName = rs.getString("constituencyName"); final String partyName = rs.getString("partyName"); final String education = rs.getString("education"); final Long <API key> = rs.getLong("<API key>"); final Long totalAssets = rs.getLong("totalAssets"); final Long liabilities = rs.getLong("liabilities"); final String address = rs.getString("address"); final String email = rs.getString("email"); final String contact = rs.getString("contact"); final String ipc = rs.getString("ipc"); return PoliticianData.instance(id, name, constituencyName, partyName, education, <API key>, totalAssets, liabilities, address, email, contact, ipc); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `<API key>` constant in crate `x11`."> <meta name="keywords" content="rust, rustlang, rust-lang, <API key>"> <title>x11::xlib::<API key> - Rust</title> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif] <nav class="sidebar"> <p class='location'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xlib</a></p><script>window.sidebarCurrent = {name: '<API key>', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xlib</a>::<wbr><a class='constant' href=''><API key></a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-13589' class='srclink' href='../../src/x11/xlib.rs.html#2473' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const <API key>: <a class='type' href='../../std/os/raw/type.c_int.html' title='std::os::raw::c_int'>c_int</a><code> = </code><code>0</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "x11"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `POLYGON_SMOOTH_HINT` constant in crate `servo`."> <meta name="keywords" content="rust, rustlang, rust-lang, POLYGON_SMOOTH_HINT"> <title>servo::gl::POLYGON_SMOOTH_HINT - Rust</title> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif] <nav class="sidebar"> <p class='location'><a href='../index.html'>servo</a>::<wbr><a href='index.html'>gl</a></p><script>window.sidebarCurrent = {name: 'POLYGON_SMOOTH_HINT', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>servo</a>::<wbr><a href='index.html'>gl</a>::<wbr><a class='constant' href=''>POLYGON_SMOOTH_HINT</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-794' class='srclink' href='../../gleam/ffi/constant.POLYGON_SMOOTH_HINT.html?gotosrc=794' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const POLYGON_SMOOTH_HINT: <a class='primitive' href='../../std/primitive.u32.html'>u32</a><code> = </code><code>3155</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "servo"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
fastlane documentation ============= # Installation sudo gem install -n /usr/local/bin fastlane Since Mac OS X 10.11 El Capitan it is necessary to install in /usr/local/bin instead of the default location (/usr/bin) # Available Actions ## iOS ios test fastlane ios test Runs all the tests ios dev_setup fastlane ios dev_setup Setup Development ios dis_setup fastlane ios dis_setup Setup Distribution ios beta fastlane ios beta Submit a new Beta Build to Apple TestFlight This will also make sure the profile is up to date ios appstore fastlane ios appstore Deploy a new version to the App Store - This README.md is auto-generated and will be re-generated every time to run [fastlane](https://fastlane.tools). More information about fastlane can be found on [https: The documentation of fastlane can be found on [GitHub](https://github.com/fastlane/fastlane).
package aws import ( "fmt" "log" "math/rand" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directconnect" "github.com/hashicorp/<API key>/helper/acctest" "github.com/hashicorp/<API key>/helper/resource" "github.com/hashicorp/<API key>/terraform" ) func init() { resource.AddTestSweepers("aws_dx_gateway", &resource.Sweeper{ Name: "aws_dx_gateway", F: <API key>, Dependencies: []string{ "<API key>", }, }) } func <API key>(region string) error { client, err := <API key>(region) if err != nil { return fmt.Errorf("error getting client: %s", err) } conn := client.(*AWSClient).dxconn input := &directconnect.<API key>{} for { output, err := conn.<API key>(input) if <API key>(err) { log.Printf("[WARN] Skipping Direct Connect Gateway sweep for %s: %s", region, err) return nil } if err != nil { return fmt.Errorf("error retrieving Direct Connect Gateways: %s", err) } for _, gateway := range output.<API key> { id := aws.StringValue(gateway.<API key>) if aws.StringValue(gateway.<API key>) != directconnect.<API key> { log.Printf("[INFO] Skipping Direct Connect Gateway in non-available (%s) state: %s", aws.StringValue(gateway.<API key>), id) continue } var associations bool associationInput := &directconnect.<API key>{ <API key>: gateway.<API key>, } for { associationOutput, err := conn.<API key>(associationInput) if err != nil { return fmt.Errorf("error retrieving Direct Connect Gateway (%s) Associations: %s", id, err) } // If associations still remain, its likely that our region is not the home // region of those associations and the previous sweepers skipped them. // When we hit this condition, we skip trying to delete the gateway as it // will go from deleting -> available after a few minutes and timeout. if len(associationOutput.<API key>) > 0 { associations = true break } if aws.StringValue(associationOutput.NextToken) == "" { break } associationInput.Next<API key>.NextToken } if associations { log.Printf("[INFO] Skipping Direct Connect Gateway with remaining associations: %s", id) continue } input := &directconnect.<API key>{ <API key>: aws.String(id), } log.Printf("[INFO] Deleting Direct Connect Gateway: %s", id) _, err := conn.<API key>(input) if isAWSErr(err, directconnect.<API key>, "does not exist") { continue } if err != nil { return fmt.Errorf("error deleting Direct Connect Gateway (%s): %s", id, err) } if err := <API key>(conn, id, 20*time.Minute); err != nil { return fmt.Errorf("error waiting for Direct Connect Gateway (%s) to be deleted: %s", id, err) } } if aws.StringValue(output.NextToken) == "" { break } input.NextToken = output.NextToken } return nil } func <API key>(t *testing.T) { resourceName := "aws_dx_gateway.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: <API key>, Steps: []resource.TestStep{ { Config: <API key>(acctest.RandString(5), randIntRange(64512, 65534)), Check: resource.<API key>( <API key>(resourceName), <API key>(resourceName, "owner_account_id"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func <API key>(t *testing.T) { checkFn := func(s []*terraform.InstanceState) error { if len(s) != 3 { return fmt.Errorf("Got %d resources, expected 3. State: %#v", len(s), s) } return nil } rName1 := fmt.Sprintf("<API key>-%d", acctest.RandInt()) rName2 := fmt.Sprintf("<API key>-%d", acctest.RandInt()) rBgpAsn := randIntRange(64512, 65534) resourceName := "aws_dx_gateway.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: <API key>, Steps: []resource.TestStep{ { Config: <API key>(rName1, rName2, rBgpAsn), Check: resource.<API key>( <API key>(resourceName), <API key>(resourceName, "owner_account_id"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateCheck: checkFn, ImportStateVerify: true, }, }, }) } func <API key>(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).dxconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_dx_gateway" { continue } input := &directconnect.<API key>{ <API key>: aws.String(rs.Primary.ID), } resp, err := conn.<API key>(input) if err != nil { return err } for _, v := range resp.<API key> { if *v.<API key> == rs.Primary.ID && !(*v.<API key> == directconnect.GatewayStateDeleted) { return fmt.Errorf("[DESTROY ERROR] DX Gateway (%s) not deleted", rs.Primary.ID) } } } return nil } func <API key>(name string) resource.TestCheckFunc { return func(s *terraform.State) error { _, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) } return nil } } func <API key>(rName string, rBgpAsn int) string { return fmt.Sprintf(` resource "aws_dx_gateway" "test" { name = "<API key>-%s" amazon_side_asn = "%d" } `, rName, rBgpAsn) } func randIntRange(min int, max int) int { rand.Seed(time.Now().UTC().UnixNano()) source := rand.New(rand.NewSource(time.Now().UnixNano())) rangeMax := max - min return int(source.Int31n(int32(rangeMax))) + min }
-- Strings. SELECT '""'::jsonb; SELECT $$''$$::jsonb; -- ERROR, single quotes are not allowed SELECT '"abc"'::jsonb; SELECT '"abc'::jsonb; -- ERROR, quotes not closed SELECT '"abc def"'::jsonb; -- ERROR, unescaped newline in string constant SELECT '"\n\"\\"'::jsonb; SELECT '"\v"'::jsonb; -- ERROR, not a valid JSON escape -- see json_encoding test for input with unicode escapes -- Numbers. SELECT '1'::jsonb; SELECT '0'::jsonb; SELECT '01'::jsonb; -- ERROR, not valid according to JSON spec SELECT '0.1'::jsonb; SELECT '9223372036854775808'::jsonb; -- OK, even though it's too large for int8 SELECT '1e100'::jsonb; SELECT '1.3e100'::jsonb; SELECT '1f2'::jsonb; -- ERROR SELECT '0.x1'::jsonb; -- ERROR SELECT '1.3ex100'::jsonb; -- ERROR -- Arrays. SELECT '[]'::jsonb; SELECT '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'::jsonb; SELECT '[1,2]'::jsonb; SELECT '[1,2,]'::jsonb; -- ERROR, trailing comma SELECT '[1,2'::jsonb; -- ERROR, no closing bracket SELECT '[1,[2]'::jsonb; -- ERROR, no closing bracket -- Objects. SELECT '{}'::jsonb; SELECT '{"abc"}'::jsonb; -- ERROR, no value SELECT '{"abc":1}'::jsonb; SELECT '{1:"abc"}'::jsonb; -- ERROR, keys must be strings SELECT '{"abc",1}'::jsonb; -- ERROR, wrong separator SELECT '{"abc"=1}'::jsonb; -- ERROR, totally wrong separator SELECT '{"abc"::1}'::jsonb; -- ERROR, another wrong separator SELECT '{"abc":1,"def":2,"ghi":[3,4],"hij":{"klm":5,"nop":[6]}}'::jsonb; SELECT '{"abc":1:2}'::jsonb; -- ERROR, colon in wrong spot SELECT '{"abc":1,3}'::jsonb; -- ERROR, no value -- Recursion. SET max_stack_depth = '100kB'; SELECT repeat('[', 10000)::jsonb; SELECT repeat('{"a":', 10000)::jsonb; RESET max_stack_depth; -- Miscellaneous stuff. SELECT 'true'::jsonb; SELECT 'false'::jsonb; SELECT 'null'::jsonb; SELECT ' true '::jsonb; -- OK, even with extra whitespace SELECT 'true false'::jsonb; -- ERROR, too many values SELECT 'true, false'::jsonb; -- ERROR, too many values SELECT 'truf'::jsonb; -- ERROR, not a keyword SELECT 'trues'::jsonb; -- ERROR, not a keyword SELECT ''::jsonb; -- ERROR, no value SELECT ' '::jsonb; -- ERROR, no value -- make sure jsonb is passed through json generators without being escaped SELECT array_to_json(ARRAY [jsonb '{"a":1}', jsonb '{"b":[2,3]}']); -- to_jsonb, timestamps select to_jsonb(timestamp '2014-05-28 12:22:35.614298'); BEGIN; SET LOCAL TIME ZONE 10.5; select to_jsonb(timestamptz '2014-05-28 12:22:35.614298-04'); SET LOCAL TIME ZONE -8; select to_jsonb(timestamptz '2014-05-28 12:22:35.614298-04'); COMMIT; select to_jsonb(date '2014-05-28'); select to_jsonb(date 'Infinity'); select to_jsonb(date '-Infinity'); select to_jsonb(timestamp 'Infinity'); select to_jsonb(timestamp '-Infinity'); select to_jsonb(timestamptz 'Infinity'); select to_jsonb(timestamptz '-Infinity'); --jsonb_agg CREATE TEMP TABLE rows AS SELECT x, 'txt' || x as y FROM generate_series(1,3) AS x; SELECT jsonb_agg(q) FROM ( SELECT $$a$$ || x AS b, y AS c, ARRAY[ROW(x.*,ARRAY[1,2,3]), ROW(y.*,ARRAY[4,5,6])] AS z FROM generate_series(1,2) x, generate_series(4,5) y) q; SELECT jsonb_agg(q ORDER BY x, y) FROM rows q; UPDATE rows SET x = NULL WHERE x = 1; SELECT jsonb_agg(q ORDER BY x NULLS FIRST, y) FROM rows q; -- jsonb extraction functions CREATE TEMP TABLE test_jsonb ( json_type text, test_json jsonb ); INSERT INTO test_jsonb VALUES ('scalar','"a scalar"'), ('array','["zero", "one","two",null,"four","five", [1,2,3],{"f1":9}]'), ('object','{"field1":"val1","field2":"val2","field3":null, "field4": 4, "field5": [1,2,3], "field6": {"f1":9}}'); SELECT test_json -> 'x' FROM test_jsonb WHERE json_type = 'scalar'; SELECT test_json -> 'x' FROM test_jsonb WHERE json_type = 'array'; SELECT test_json -> 'x' FROM test_jsonb WHERE json_type = 'object'; SELECT test_json -> 'field2' FROM test_jsonb WHERE json_type = 'object'; SELECT test_json ->> 'field2' FROM test_jsonb WHERE json_type = 'scalar'; SELECT test_json ->> 'field2' FROM test_jsonb WHERE json_type = 'array'; SELECT test_json ->> 'field2' FROM test_jsonb WHERE json_type = 'object'; SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'scalar'; SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'array'; SELECT test_json -> 9 FROM test_jsonb WHERE json_type = 'array'; SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'object'; SELECT test_json ->> 6 FROM test_jsonb WHERE json_type = 'array'; SELECT test_json ->> 7 FROM test_jsonb WHERE json_type = 'array'; SELECT test_json ->> 'field4' FROM test_jsonb WHERE json_type = 'object'; SELECT test_json ->> 'field5' FROM test_jsonb WHERE json_type = 'object'; SELECT test_json ->> 'field6' FROM test_jsonb WHERE json_type = 'object'; SELECT test_json ->> 2 FROM test_jsonb WHERE json_type = 'scalar'; SELECT test_json ->> 2 FROM test_jsonb WHERE json_type = 'array'; SELECT test_json ->> 2 FROM test_jsonb WHERE json_type = 'object'; SELECT jsonb_object_keys(test_json) FROM test_jsonb WHERE json_type = 'scalar'; SELECT jsonb_object_keys(test_json) FROM test_jsonb WHERE json_type = 'array'; SELECT jsonb_object_keys(test_json) FROM test_jsonb WHERE json_type = 'object'; -- nulls SELECT (test_json->'field3') IS NULL AS expect_false FROM test_jsonb WHERE json_type = 'object'; SELECT (test_json->>'field3') IS NULL AS expect_true FROM test_jsonb WHERE json_type = 'object'; SELECT (test_json->3) IS NULL AS expect_false FROM test_jsonb WHERE json_type = 'array'; SELECT (test_json->>3) IS NULL AS expect_true FROM test_jsonb WHERE json_type = 'array'; -- corner cases select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> null::text; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> null::int; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> 1; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> 'z'; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> ''; select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 1; select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 3; select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 'z'; select '{"a": "c", "b": null}'::jsonb -> 'b'; select '"foo"'::jsonb -> 1; select '"foo"'::jsonb -> 'z'; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> null::text; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> null::int; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> 1; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> 'z'; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> ''; select '[{"b": "c"}, {"b": "cc"}]'::jsonb ->> 1; select '[{"b": "c"}, {"b": "cc"}]'::jsonb ->> 3; select '[{"b": "c"}, {"b": "cc"}]'::jsonb ->> 'z'; select '{"a": "c", "b": null}'::jsonb ->> 'b'; select '"foo"'::jsonb ->> 1; select '"foo"'::jsonb ->> 'z'; -- equality and inequality SELECT '{"x":"y"}'::jsonb = '{"x":"y"}'::jsonb; SELECT '{"x":"y"}'::jsonb = '{"x":"z"}'::jsonb; SELECT '{"x":"y"}'::jsonb <> '{"x":"y"}'::jsonb; SELECT '{"x":"y"}'::jsonb <> '{"x":"z"}'::jsonb; -- containment SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b"}'); SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b", "c":null}'); SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b", "g":null}'); SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"g":null}'); SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"c"}'); SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b"}'); SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b", "c":"q"}'); SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b"}'; SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b", "c":null}'; SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b", "g":null}'; SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"g":null}'; SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"c"}'; SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b"}'; SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b", "c":"q"}'; SELECT '[1,2]'::jsonb @> '[1,2,2]'::jsonb; SELECT '[1,1,2]'::jsonb @> '[1,2,2]'::jsonb; SELECT '[[1,2]]'::jsonb @> '[[1,2,2]]'::jsonb; SELECT '[1,2,2]'::jsonb <@ '[1,2]'::jsonb; SELECT '[1,2,2]'::jsonb <@ '[1,1,2]'::jsonb; SELECT '[[1,2,2]]'::jsonb <@ '[[1,2]]'::jsonb; SELECT jsonb_contained('{"a":"b"}', '{"a":"b", "b":1, "c":null}'); SELECT jsonb_contained('{"a":"b", "c":null}', '{"a":"b", "b":1, "c":null}'); SELECT jsonb_contained('{"a":"b", "g":null}', '{"a":"b", "b":1, "c":null}'); SELECT jsonb_contained('{"g":null}', '{"a":"b", "b":1, "c":null}'); SELECT jsonb_contained('{"a":"c"}', '{"a":"b", "b":1, "c":null}'); SELECT jsonb_contained('{"a":"b"}', '{"a":"b", "b":1, "c":null}'); SELECT jsonb_contained('{"a":"b", "c":"q"}', '{"a":"b", "b":1, "c":null}'); SELECT '{"a":"b"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; SELECT '{"a":"b", "c":null}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; SELECT '{"a":"b", "g":null}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; SELECT '{"g":null}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; SELECT '{"a":"c"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; SELECT '{"a":"b"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; SELECT '{"a":"b", "c":"q"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -- Raw scalar may contain another raw scalar, array may contain a raw scalar SELECT '[5]'::jsonb @> '[5]'; SELECT '5'::jsonb @> '5'; SELECT '[5]'::jsonb @> '5'; -- But a raw scalar cannot contain an array SELECT '5'::jsonb @> '[5]'; -- In general, one thing should always contain itself. Test array containment: SELECT '["9", ["7", "3"], 1]'::jsonb @> '["9", ["7", "3"], 1]'::jsonb; SELECT '["9", ["7", "3"], ["1"]]'::jsonb @> '["9", ["7", "3"], ["1"]]'::jsonb; -- array containment string matching confusion bug SELECT '{ "name": "Bob", "tags": [ "enim", "qui"]}'::jsonb @> '{"tags":["qu"]}'; -- array length SELECT jsonb_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]'); SELECT jsonb_array_length('[]'); SELECT jsonb_array_length('{"f1":1,"f2":[5,6]}'); SELECT jsonb_array_length('4'); -- each SELECT jsonb_each('{"f1":[1,2,3],"f2":{"f3":1},"f4":null}'); SELECT jsonb_each('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; SELECT * FROM jsonb_each('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":99,"f6":"stringy"}') q; SELECT * FROM jsonb_each('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; SELECT jsonb_each_text('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":"null"}'); SELECT jsonb_each_text('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; SELECT * FROM jsonb_each_text('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":99,"f6":"stringy"}') q; SELECT * FROM jsonb_each_text('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; -- exists SELECT jsonb_exists('{"a":null, "b":"qq"}', 'a'); SELECT jsonb_exists('{"a":null, "b":"qq"}', 'b'); SELECT jsonb_exists('{"a":null, "b":"qq"}', 'c'); SELECT jsonb_exists('{"a":"null", "b":"qq"}', 'a'); SELECT jsonb '{"a":null, "b":"qq"}' ? 'a'; SELECT jsonb '{"a":null, "b":"qq"}' ? 'b'; SELECT jsonb '{"a":null, "b":"qq"}' ? 'c'; SELECT jsonb '{"a":"null", "b":"qq"}' ? 'a'; -- array exists - array elements should behave as keys SELECT count(*) from testjsonb WHERE j->'array' ? 'bar'; -- type sensitive array exists - should return no rows (since "exists" only -- matches strings that are either object keys or array elements) SELECT count(*) from testjsonb WHERE j->'array' ? '5'::text; -- However, a raw scalar is *contained* within the array SELECT count(*) from testjsonb WHERE j->'array' @> '5'::jsonb; SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['a','b']); SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['b','a']); SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['c','a']); SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['c','d']); SELECT jsonb_exists_any('{"a":null, "b":"qq"}', '{}'::text[]); SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['a','b']; SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['b','a']; SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['c','a']; SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['c','d']; SELECT jsonb '{"a":null, "b":"qq"}' ?| '{}'::text[]; SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['a','b']); SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['b','a']); SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['c','a']); SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['c','d']); SELECT jsonb_exists_all('{"a":null, "b":"qq"}', '{}'::text[]); SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['a','b']; SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['b','a']; SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['c','a']; SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['c','d']; SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['a','a', 'b', 'b', 'b']; SELECT jsonb '{"a":null, "b":"qq"}' ?& '{}'::text[]; -- typeof SELECT jsonb_typeof('{}') AS object; SELECT jsonb_typeof('{"c":3,"p":"o"}') AS object; SELECT jsonb_typeof('[]') AS array; SELECT jsonb_typeof('["a", 1]') AS array; SELECT jsonb_typeof('null') AS "null"; SELECT jsonb_typeof('1') AS number; SELECT jsonb_typeof('-1') AS number; SELECT jsonb_typeof('1.0') AS number; SELECT jsonb_typeof('1e2') AS number; SELECT jsonb_typeof('-1.0') AS number; SELECT jsonb_typeof('true') AS boolean; SELECT jsonb_typeof('false') AS boolean; SELECT jsonb_typeof('"hello"') AS string; SELECT jsonb_typeof('"true"') AS string; SELECT jsonb_typeof('"1.0"') AS string; -- jsonb_build_array, jsonb_build_object, jsonb_object_agg SELECT jsonb_build_array('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}'); SELECT jsonb_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}'); SELECT jsonb_build_object( 'a', jsonb_build_object('b',false,'c',99), 'd', jsonb_build_object('e',array[9,8,7]::int[], 'f', (select row_to_json(r) from ( select relkind, oid::regclass as name from pg_class where relname = 'pg_class') r))); -- empty objects/arrays SELECT jsonb_build_array(); SELECT jsonb_build_object(); -- make sure keys are quoted SELECT jsonb_build_object(1,2); -- keys must be scalar and not null SELECT jsonb_build_object(null,2); SELECT jsonb_build_object(r,2) FROM (SELECT 1 AS a, 2 AS b) r; SELECT jsonb_build_object(json '{"a":1,"b":2}', 3); SELECT jsonb_build_object('{1,2,3}'::int[], 3); -- handling of NULL values SELECT jsonb_object_agg(1, NULL::jsonb); SELECT jsonb_object_agg(NULL, '{"a":1}'); CREATE TEMP TABLE foo (serial_num int, name text, type text); INSERT INTO foo VALUES (847001,'t15','GE1043'); INSERT INTO foo VALUES (847002,'t16','GE1043'); INSERT INTO foo VALUES (847003,'sub-alpha','GESS90'); SELECT jsonb_build_object('turbines',jsonb_object_agg(serial_num,jsonb_build_object('name',name,'type',type))) FROM foo; SELECT jsonb_object_agg(name, type) FROM foo; INSERT INTO foo VALUES (999999, NULL, 'bar'); SELECT jsonb_object_agg(name, type) FROM foo; -- jsonb_object -- empty object, one dimension SELECT jsonb_object('{}'); -- empty object, two dimensions SELECT jsonb_object('{}', '{}'); -- one dimension SELECT jsonb_object('{a,1,b,2,3,NULL,"d e f","a b c"}'); -- same but with two dimensions SELECT jsonb_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}'); -- odd number error SELECT jsonb_object('{a,b,c}'); -- one column error SELECT jsonb_object('{{a},{b}}'); -- too many columns error SELECT jsonb_object('{{a,b,c},{b,c,d}}'); -- too many dimensions error SELECT jsonb_object('{{{a,b},{c,d}},{{b,c},{d,e}}}'); --two argument form of jsonb_object select jsonb_object('{a,b,c,"d e f"}','{1,2,3,"a b c"}'); -- too many dimensions SELECT jsonb_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}', '{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}'); -- mismatched dimensions select jsonb_object('{a,b,c,"d e f",g}','{1,2,3,"a b c"}'); select jsonb_object('{a,b,c,"d e f"}','{1,2,3,"a b c",g}'); -- null key error select jsonb_object('{a,b,NULL,"d e f"}','{1,2,3,"a b c"}'); -- empty key is allowed select jsonb_object('{a,b,"","d e f"}','{1,2,3,"a b c"}'); -- extract_path, <API key> SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f4','f6'); SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f2'); SELECT jsonb_extract_path('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',0::text); SELECT jsonb_extract_path('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',1::text); SELECT <API key>('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f4','f6'); SELECT <API key>('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f2'); SELECT <API key>('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',0::text); SELECT <API key>('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',1::text); -- extract_path nulls SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":{"f5":null,"f6":"stringy"}}','f4','f5') IS NULL AS expect_false; SELECT <API key>('{"f2":{"f3":1},"f4":{"f5":null,"f6":"stringy"}}','f4','f5') IS NULL AS expect_true; SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":[0,1,2,null]}','f4','3') IS NULL AS expect_false; SELECT <API key>('{"f2":{"f3":1},"f4":[0,1,2,null]}','f4','3') IS NULL AS expect_true; -- extract_path operators SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f4','f6']; SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f2']; SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f2','0']; SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f2','1']; SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f4','f6']; SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f2']; SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f2','0']; SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f2','1']; -- corner cases for same select '{"a": {"b":{"c": "foo"}}}'::jsonb select '[1,2,3]'::jsonb select '"foo"'::jsonb select '42'::jsonb select 'null'::jsonb select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a', null]; select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a', '']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','b']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','b','c']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','b','c','d']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','z','c']; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #> array['a','1','b']; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #> array['a','z','b']; select '[{"b": "c"}, {"b": "cc"}]'::jsonb #> array['1','b']; select '[{"b": "c"}, {"b": "cc"}]'::jsonb #> array['z','b']; select '[{"b": "c"}, {"b": null}]'::jsonb #> array['1','b']; select '"foo"'::jsonb #> array['z']; select '42'::jsonb #> array['f2']; select '42'::jsonb #> array['0']; select '{"a": {"b":{"c": "foo"}}}'::jsonb select '[1,2,3]'::jsonb select '"foo"'::jsonb select '42'::jsonb select 'null'::jsonb select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a', null]; select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a', '']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','b']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','b','c']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','b','c','d']; select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','z','c']; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #>> array['a','1','b']; select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #>> array['a','z','b']; select '[{"b": "c"}, {"b": "cc"}]'::jsonb #>> array['1','b']; select '[{"b": "c"}, {"b": "cc"}]'::jsonb #>> array['z','b']; select '[{"b": "c"}, {"b": null}]'::jsonb #>> array['1','b']; select '"foo"'::jsonb #>> array['z']; select '42'::jsonb #>> array['f2']; select '42'::jsonb #>> array['0']; -- array_elements SELECT <API key>('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false]'); SELECT * FROM <API key>('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false]') q; SELECT <API key>('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]'); SELECT * FROM <API key>('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]') q; -- populate_record CREATE TYPE jbpop AS (a text, b int, c timestamp); SELECT * FROM <API key>(NULL::jbpop,'{"a":"blurfl","x":43.2}') q; SELECT * FROM <API key>(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"a":"blurfl","x":43.2}') q; SELECT * FROM <API key>(NULL::jbpop,'{"a":"blurfl","x":43.2}') q; SELECT * FROM <API key>(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"a":"blurfl","x":43.2}') q; SELECT * FROM <API key>(NULL::jbpop,'{"a":[100,200,false],"x":43.2}') q; SELECT * FROM <API key>(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"a":[100,200,false],"x":43.2}') q; SELECT * FROM <API key>(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"c":[100,200,false],"x":43.2}') q; -- populate_recordset SELECT * FROM <API key>(NULL::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(row('def',99,NULL)::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(NULL::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(row('def',99,NULL)::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(row('def',99,NULL)::jbpop,'[{"a":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(row('def',99,NULL)::jbpop,'[{"c":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(NULL::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(row('def',99,NULL)::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; SELECT * FROM <API key>(row('def',99,NULL)::jbpop,'[{"a":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; -- jsonb_to_record and jsonb_to_recordset select * from jsonb_to_record('{"a":1,"b":"foo","c":"bar"}') as x(a int, b text, d text); select * from jsonb_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]') as x(a int, b text, c boolean); select *, c is null as c_is_null from jsonb_to_record('{"a":1, "b":{"c":16, "d":2}, "x":8}'::jsonb) as t(a int, b jsonb, c text, x int); select *, c is null as c_is_null from jsonb_to_recordset('[{"a":1, "b":{"c":16, "d":2}, "x":8}]'::jsonb) as t(a int, b jsonb, c text, x int); -- indexing SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}'; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC"}'; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC", "public":true}'; SELECT count(*) FROM testjsonb WHERE j @> '{"age":25}'; SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}'; SELECT count(*) FROM testjsonb WHERE j ? 'public'; SELECT count(*) FROM testjsonb WHERE j ? 'bar'; SELECT count(*) FROM testjsonb WHERE j ?| ARRAY['public','disabled']; SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled']; CREATE INDEX jidx ON testjsonb USING gin (j); SET enable_seqscan = off; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}'; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC"}'; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC", "public":true}'; SELECT count(*) FROM testjsonb WHERE j @> '{"age":25}'; SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}'; SELECT count(*) FROM testjsonb WHERE j @> '{"array":["foo"]}'; SELECT count(*) FROM testjsonb WHERE j @> '{"array":["bar"]}'; -- exercise GIN_SEARCH_MODE_ALL SELECT count(*) FROM testjsonb WHERE j @> '{}'; SELECT count(*) FROM testjsonb WHERE j ? 'public'; SELECT count(*) FROM testjsonb WHERE j ? 'bar'; SELECT count(*) FROM testjsonb WHERE j ?| ARRAY['public','disabled']; SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled']; -- array exists - array elements should behave as keys (for GIN index scans too) CREATE INDEX jidx_array ON testjsonb USING gin((j->'array')); SELECT count(*) from testjsonb WHERE j->'array' ? 'bar'; -- type sensitive array exists - should return no rows (since "exists" only -- matches strings that are either object keys or array elements) SELECT count(*) from testjsonb WHERE j->'array' ? '5'::text; -- However, a raw scalar is *contained* within the array SELECT count(*) from testjsonb WHERE j->'array' @> '5'::jsonb; RESET enable_seqscan; SELECT count(*) FROM (SELECT (jsonb_each(j)).key FROM testjsonb) AS wow; SELECT key, count(*) FROM (SELECT (jsonb_each(j)).key FROM testjsonb) AS wow GROUP BY key ORDER BY count DESC, key; -- sort/hash SELECT count(distinct j) FROM testjsonb; SET enable_hashagg = off; SELECT count(*) FROM (SELECT j FROM (SELECT * FROM testjsonb UNION ALL SELECT * FROM testjsonb) js GROUP BY j) js2; SET enable_hashagg = on; SET enable_sort = off; SELECT count(*) FROM (SELECT j FROM (SELECT * FROM testjsonb UNION ALL SELECT * FROM testjsonb) js GROUP BY j) js2; SELECT distinct * FROM (values (jsonb '{}' || ''::text),('{}')) v(j); SET enable_sort = on; RESET enable_hashagg; RESET enable_sort; DROP INDEX jidx; DROP INDEX jidx_array; -- btree CREATE INDEX jidx ON testjsonb USING btree (j); SET enable_seqscan = off; SELECT count(*) FROM testjsonb WHERE j > '{"p":1}'; SELECT count(*) FROM testjsonb WHERE j = '{"pos":98, "line":371, "node":"CBA", "indexed":true}'; --gin path opclass DROP INDEX jidx; CREATE INDEX jidx ON testjsonb USING gin (j jsonb_path_ops); SET enable_seqscan = off; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}'; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC"}'; SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC", "public":true}'; SELECT count(*) FROM testjsonb WHERE j @> '{"age":25}'; SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}'; -- exercise GIN_SEARCH_MODE_ALL SELECT count(*) FROM testjsonb WHERE j @> '{}'; RESET enable_seqscan; DROP INDEX jidx; -- nested tests SELECT '{"ff":{"a":12,"b":16}}'::jsonb; SELECT '{"ff":{"a":12,"b":16},"qq":123}'::jsonb; SELECT '{"aa":["a","aaa"],"qq":{"a":12,"b":16,"c":["c1","c2"],"d":{"d1":"d1","d2":"d2","d1":"d3"}}}'::jsonb; SELECT '{"aa":["a","aaa"],"qq":{"a":"12","b":"16","c":["c1","c2"],"d":{"d1":"d1","d2":"d2"}}}'::jsonb; SELECT '{"aa":["a","aaa"],"qq":{"a":"12","b":"16","c":["c1","c2",["c3"],{"c4":4}],"d":{"d1":"d1","d2":"d2"}}}'::jsonb; SELECT '{"ff":["a","aaa"]}'::jsonb; SELECT '{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'ff', '{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'qq', ('{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'Y') IS NULL AS f, ('{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb ->> 'Y') IS NULL AS t, '{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'x'; -- nested containment SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[1,2]}'; SELECT '{"a":[2,1],"c":"b"}'::jsonb @> '{"a":[1,2]}'; SELECT '{"a":{"1":2},"c":"b"}'::jsonb @> '{"a":[1,2]}'; SELECT '{"a":{"2":1},"c":"b"}'::jsonb @> '{"a":[1,2]}'; SELECT '{"a":{"1":2},"c":"b"}'::jsonb @> '{"a":{"1":2}}'; SELECT '{"a":{"2":1},"c":"b"}'::jsonb @> '{"a":{"1":2}}'; SELECT '["a","b"]'::jsonb @> '["a","b","c","b"]'; SELECT '["a","b","c","b"]'::jsonb @> '["a","b"]'; SELECT '["a","b","c",[1,2]]'::jsonb @> '["a",[1,2]]'; SELECT '["a","b","c",[1,2]]'::jsonb @> '["b",[1,2]]'; SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[1]}'; SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[2]}'; SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[3]}'; SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"c":3}]}'; SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"x":4}]}'; SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"x":4},3]}'; SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"x":4},1]}'; -- check some corner cases for indexed nested containment (bug #13756) create temp table nestjsonb (j jsonb); insert into nestjsonb (j) values ('{"a":[["b",{"x":1}],["b",{"x":2}]],"c":3}'); insert into nestjsonb (j) values ('[[14,2,3]]'); insert into nestjsonb (j) values ('[1,[14,2,3]]'); create index on nestjsonb using gin(j jsonb_path_ops); set enable_seqscan = on; set enable_bitmapscan = off; select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb; select * from nestjsonb where j @> '{"c":3}'; select * from nestjsonb where j @> '[[14]]'; set enable_seqscan = off; set enable_bitmapscan = on; select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb; select * from nestjsonb where j @> '{"c":3}'; select * from nestjsonb where j @> '[[14]]'; reset enable_seqscan; reset enable_bitmapscan; -- nested object field / array index lookup SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'n'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'a'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'b'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'c'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'd'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'd' -> '1'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'e'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 0; --expecting error SELECT '["a","b","c",[1,2],null]'::jsonb -> 0; SELECT '["a","b","c",[1,2],null]'::jsonb -> 1; SELECT '["a","b","c",[1,2],null]'::jsonb -> 2; SELECT '["a","b","c",[1,2],null]'::jsonb -> 3; SELECT '["a","b","c",[1,2],null]'::jsonb -> 3 -> 1; SELECT '["a","b","c",[1,2],null]'::jsonb -> 4; SELECT '["a","b","c",[1,2],null]'::jsonb -> 5; SELECT '["a","b","c",[1,2],null]'::jsonb -> -1; SELECT '["a","b","c",[1,2],null]'::jsonb -> -5; SELECT '["a","b","c",[1,2],null]'::jsonb -> -6; --nested path extraction SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '{"a":"b","c":[1,2,3]}'::jsonb SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb --nested exists SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'n'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'a'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'b'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'c'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'd'; SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'e'; -- jsonb_strip_nulls select jsonb_strip_nulls(null); select jsonb_strip_nulls('1'); select jsonb_strip_nulls('"a string"'); select jsonb_strip_nulls('null'); select jsonb_strip_nulls('[1,2,null,3,4]'); select jsonb_strip_nulls('{"a":1,"b":null,"c":[2,null,3],"d":{"e":4,"f":null}}'); select jsonb_strip_nulls('[1,{"a":1,"b":null,"c":2},3]'); -- an empty object is not null and should not be stripped select jsonb_strip_nulls('{"a": {"b": null, "c": null}, "d": {} }'); select jsonb_pretty('{"a": "test", "b": [1, 2, 3], "c": "test3", "d":{"dd": "test4", "dd2":{"ddd": "test5"}}}'); select jsonb_pretty('[{"f1":1,"f2":null},2,null,[[{"x":true},6,7],8],3]'); select jsonb_pretty('{"a":["b", "c"], "d": {"e":"f"}}'); select jsonb_concat('{"d": "test", "a": [1, 2]}', '{"g": "test2", "c": {"c1":1, "c2":2}}'); select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"cq":"l", "b":"g", "fg":false}'; select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"aq":"l"}'; select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"aa":"l"}'; select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{}'; select '["a", "b"]'::jsonb || '["c"]'; select '["a", "b"]'::jsonb || '["c", "d"]'; select '["c"]' || '["a", "b"]'::jsonb; select '["a", "b"]'::jsonb || '"c"'; select '"c"' || '["a", "b"]'::jsonb; select '[]'::jsonb || '["a"]'::jsonb; select '[]'::jsonb || '"a"'::jsonb; select '"b"'::jsonb || '"a"'::jsonb; select '{}'::jsonb || '{"a":"b"}'::jsonb; select '[]'::jsonb || '{"a":"b"}'::jsonb; select '{"a":"b"}'::jsonb || '[]'::jsonb; select '"a"'::jsonb || '{"a":1}'; select '{"a":1}' || '"a"'::jsonb; select '["a", "b"]'::jsonb || '{"c":1}'; select '{"c": 1}'::jsonb || '["a", "b"]'; select '{}'::jsonb || '{"cq":"l", "b":"g", "fg":false}'; select pg_column_size('{}'::jsonb || '{}'::jsonb) = pg_column_size('{}'::jsonb); select pg_column_size('{"aa":1}'::jsonb || '{"b":2}'::jsonb) = pg_column_size('{"aa":1, "b":2}'::jsonb); select pg_column_size('{"aa":1, "b":2}'::jsonb || '{}'::jsonb) = pg_column_size('{"aa":1, "b":2}'::jsonb); select pg_column_size('{}'::jsonb || '{"aa":1, "b":2}'::jsonb) = pg_column_size('{"aa":1, "b":2}'::jsonb); select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'a'); select jsonb_delete('{"a":null , "b":2, "c":3}'::jsonb, 'a'); select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'b'); select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'c'); select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'd'); select '{"a":1 , "b":2, "c":3}'::jsonb - 'a'; select '{"a":null , "b":2, "c":3}'::jsonb - 'a'; select '{"a":1 , "b":2, "c":3}'::jsonb - 'b'; select '{"a":1 , "b":2, "c":3}'::jsonb - 'c'; select '{"a":1 , "b":2, "c":3}'::jsonb - 'd'; select pg_column_size('{"a":1 , "b":2, "c":3}'::jsonb - 'b') = pg_column_size('{"a":1, "b":2}'::jsonb); select '["a","b","c"]'::jsonb - 3; select '["a","b","c"]'::jsonb - 2; select '["a","b","c"]'::jsonb - 1; select '["a","b","c"]'::jsonb - 0; select '["a","b","c"]'::jsonb - -1; select '["a","b","c"]'::jsonb - -2; select '["a","b","c"]'::jsonb - -3; select '["a","b","c"]'::jsonb - -4; select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{n}', '[1,2,3]'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '[1,2,3]'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,1,0}', '[1,2,3]'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,NULL,0}', '[1,2,3]'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{n}', '{"1": 2}'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '{"1": 2}'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,1,0}', '{"1": 2}'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,NULL,0}', '{"1": 2}'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '"test"'); select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '{"f": "test"}'); select jsonb_delete_path('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '{n}'); select jsonb_delete_path('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '{b,-1}'); select jsonb_delete_path('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '{d,1,0}'); select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb #- '{b,-1e}'; -- invalid array subscript select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb #- '{d,1,0}'; -- empty structure and error conditions for delete and replace select '"a"'::jsonb - 'a'; -- error select '{}'::jsonb - 'a'; select '[]'::jsonb - 'a'; select '"a"'::jsonb - 1; -- error select '{}'::jsonb - 1; -- error select '[]'::jsonb - 1; select '"a"'::jsonb #- '{a}'; -- error select '{}'::jsonb select '[]'::jsonb select jsonb_set('"a"','{a}','"b"'); --error select jsonb_set('{}','{a}','"b"', false); select jsonb_set('[]','{1}','"b"', false); -- jsonb_set adding instead of replacing -- prepend to array select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{b,-33}','{"foo":123}'); -- append to array select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{b,33}','{"foo":123}'); -- check nesting levels addition select jsonb_set('{"a":1,"b":[4,5,[0,1,2],6,7],"c":{"d":4}}','{b,2,33}','{"foo":123}'); -- add new key select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{c,e}','{"foo":123}'); -- adding doesn't do anything if elements before last aren't present select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{x,-33}','{"foo":123}'); select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{x,y}','{"foo":123}'); -- add to empty object select jsonb_set('{}','{x}','{"foo":123}'); --add to empty array select jsonb_set('[]','{0}','{"foo":123}'); select jsonb_set('[]','{99}','{"foo":123}'); select jsonb_set('[]','{-99}','{"foo":123}'); select jsonb_set('{"a": [1, 2, 3]}', '{a, non_integer}', '"new_value"'); select jsonb_set('{"a": {"b": [1, 2, 3]}}', '{a, b, non_integer}', '"new_value"'); select jsonb_set('{"a": {"b": [1, 2, 3]}}', '{a, b, NULL}', '"new_value"');