code
stringlengths
4
1.01M
language
stringclasses
2 values
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #ifndef ARANGOD_SCHEDULER_JOB_GUARD_H #define ARANGOD_SCHEDULER_JOB_GUARD_H 1 #include "Basics/Common.h" #include "Basics/SameThreadAsserter.h" #include "Scheduler/EventLoop.h" #include "Scheduler/Scheduler.h" namespace arangodb { namespace rest { class Scheduler; } class JobGuard : public SameThreadAsserter { public: JobGuard(JobGuard const&) = delete; JobGuard& operator=(JobGuard const&) = delete; explicit JobGuard(EventLoop const& loop) : SameThreadAsserter(), _scheduler(loop._scheduler) {} explicit JobGuard(rest::Scheduler* scheduler) : SameThreadAsserter(), _scheduler(scheduler) {} ~JobGuard() { release(); } public: void work() { TRI_ASSERT(!_isWorkingFlag); if (0 == _isWorking) { _scheduler->workThread(); } ++_isWorking; _isWorkingFlag = true; } void block() { TRI_ASSERT(!_isBlockedFlag); if (0 == _isBlocked) { _scheduler->blockThread(); } ++_isBlocked; _isBlockedFlag = true; } private: void release() { if (_isWorkingFlag) { --_isWorking; _isWorkingFlag = false; if (0 == _isWorking) { _scheduler->unworkThread(); } } if (_isBlockedFlag) { --_isBlocked; _isBlockedFlag = false; if (0 == _isBlocked) { _scheduler->unblockThread(); } } } private: rest::Scheduler* _scheduler; bool _isWorkingFlag = false; bool _isBlockedFlag = false; static thread_local size_t _isWorking; static thread_local size_t _isBlocked; }; } #endif
Java
package org.ns.vk.cachegrabber.ui; import java.awt.event.ActionEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import org.ns.func.Callback; import org.ns.ioc.IoC; import org.ns.vk.cachegrabber.api.Application; import org.ns.vk.cachegrabber.api.vk.Audio; import org.ns.vk.cachegrabber.api.vk.VKApi; /** * * @author stupak */ public class TestAction extends AbstractAction { public TestAction() { super("Test action"); } @Override public void actionPerformed(ActionEvent e) { VKApi vkApi = IoC.get(Application.class).getVKApi(); String ownerId = "32659923"; String audioId = "259636837"; vkApi.getById(ownerId, audioId, new Callback<Audio>() { @Override public void call(Audio audio) { Logger.getLogger(TestAction.class.getName()).log(Level.INFO, "loaded audio: {0}", audio); } }); } }
Java
--- layout: event title: "OSM Bangladesh: Bringing scattered OSM activities under single platform" theme: Community growth and diversity, outreach theme_full: Community growth and diversity, outreach, Organisational, legal category: Community growth and diversity, outreach audience: "(1a) Data contributors: Community" audience_full: "(1a) Data contributors: Community, (2c) Data users: Personal, (3b) Core OSM: OSMF working groups (community, licence, data...), (3c) Core OSM: OSMF board (strategy and vision)" name: Ahasanul Hoque organization: OpenStreetMap Bangladesh Community twitter: osm: aHaSaN room: Room 1 tags: - slot14 youtube_recording: nMxSDjKiZ-M youtube_time: [4,0] slides: https://speakerdeck.com/sotm2017/day2-1130-osm-bangladesh-bringing-scattered-osm-activities-under-single-platform --- My session will be based on three discussion topics. Firstly, the uneven journey of OpenStreetMap in Bangladesh and tackling the obstacles. Secondly, the ongoing OSM activities in Bangladesh by different government and non government agencies, chapters and small communities. And lastly, how to integrate the scattered OSM group and activities under a single platform.
Java
# Lestibudesia Thouars GENUS #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
package com.mapswithme.maps.maplayer.traffic; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import com.mapswithme.util.log.Logger; import com.mapswithme.util.log.LoggerFactory; import java.util.ArrayList; import java.util.List; @MainThread public enum TrafficManager { INSTANCE; private final static String TAG = TrafficManager.class.getSimpleName(); @NonNull private final Logger mLogger = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.TRAFFIC); @NonNull private final TrafficState.StateChangeListener mStateChangeListener = new TrafficStateListener(); @NonNull private TrafficState mState = TrafficState.DISABLED; @NonNull private final List<TrafficCallback> mCallbacks = new ArrayList<>(); private boolean mInitialized = false; public void initialize() { mLogger.d(TAG, "Initialization of traffic manager and setting the listener for traffic state changes"); TrafficState.nativeSetListener(mStateChangeListener); mInitialized = true; } public void toggle() { checkInitialization(); if (isEnabled()) disable(); else enable(); } private void enable() { mLogger.d(TAG, "Enable traffic"); TrafficState.nativeEnable(); } private void disable() { checkInitialization(); mLogger.d(TAG, "Disable traffic"); TrafficState.nativeDisable(); } public boolean isEnabled() { checkInitialization(); return TrafficState.nativeIsEnabled(); } public void attach(@NonNull TrafficCallback callback) { checkInitialization(); if (mCallbacks.contains(callback)) { throw new IllegalStateException("A callback '" + callback + "' is already attached. Check that the 'detachAll' method was called."); } mLogger.d(TAG, "Attach callback '" + callback + "'"); mCallbacks.add(callback); postPendingState(); } private void postPendingState() { mStateChangeListener.onTrafficStateChanged(mState.ordinal()); } public void detachAll() { checkInitialization(); if (mCallbacks.isEmpty()) { mLogger.w(TAG, "There are no attached callbacks. Invoke the 'detachAll' method " + "only when it's really needed!", new Throwable()); return; } for (TrafficCallback callback : mCallbacks) mLogger.d(TAG, "Detach callback '" + callback + "'"); mCallbacks.clear(); } private void checkInitialization() { if (!mInitialized) throw new AssertionError("Traffic manager is not initialized!"); } public void setEnabled(boolean enabled) { checkInitialization(); if (isEnabled() == enabled) return; if (enabled) enable(); else disable(); } private class TrafficStateListener implements TrafficState.StateChangeListener { @Override @MainThread public void onTrafficStateChanged(int index) { TrafficState newTrafficState = TrafficState.values()[index]; mLogger.d(TAG, "onTrafficStateChanged current state = " + mState + " new value = " + newTrafficState); if (mState == newTrafficState) return; mState = newTrafficState; mState.activate(mCallbacks); } } public interface TrafficCallback { void onEnabled(); void onDisabled(); void onWaitingData(); void onOutdated(); void onNetworkError(); void onNoData(); void onExpiredData(); void onExpiredApp(); } }
Java
package brennus.asm; import static brennus.model.ExistingType.VOID; import static brennus.model.ExistingType.existing; import static brennus.model.Protection.PUBLIC; import static junit.framework.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import brennus.Builder; import brennus.MethodBuilder; import brennus.SwitchBuilder; import brennus.ThenBuilder; import brennus.asm.TestGeneration.DynamicClassLoader; import brennus.model.FutureType; import brennus.printer.TypePrinter; import org.junit.Test; public class TestGoto { abstract public static class FSA { private List<String> states = new ArrayList<String>(); abstract public void exec(); public void state(String p) { states.add(p); } public List<String> getStates() { return states; } } abstract public static class FSA2 { private List<String> states = new ArrayList<String>(); abstract public void exec(Iterator<Integer> it); public void state(String p) { states.add(p); } public List<String> getStates() { return states; } } @Test public void testGoto() throws Exception { FutureType testClass = new Builder() .startClass("brennus.asm.TestGoto$TestClass", existing(FSA.class)) .startMethod(PUBLIC, VOID, "exec") .label("a") .exec().callOnThis("state").literal("a").endCall().endExec() .gotoLabel("c") .label("b") .exec().callOnThis("state").literal("b").endCall().endExec() .gotoLabel("end") .label("c") .exec().callOnThis("state").literal("c").endCall().endExec() .gotoLabel("b") .label("end") .endMethod() .endClass(); // new TypePrinter().print(testClass); DynamicClassLoader cl = new DynamicClassLoader(); cl.define(testClass); Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass"); FSA fsa = (FSA)generated.newInstance(); fsa.exec(); assertEquals(Arrays.asList("a", "c", "b"), fsa.getStates()); } @Test public void testFSA() throws Exception { int[][] fsa = { {0,1,2,3}, {0,1,2,3}, {0,1,2,3}, {0,1,2,3} }; MethodBuilder m = new Builder() .startClass("brennus.asm.TestGoto$TestClass2", existing(FSA2.class)) .startMethod(PUBLIC, VOID, "exec").param(existing(Iterator.class), "it") .gotoLabel("start") .label("start"); for (int i = 0; i < fsa.length; i++) { m = m.label("s_"+i) .exec().callOnThis("state").literal("s_"+i).endCall().endExec(); SwitchBuilder<ThenBuilder<MethodBuilder>> s = m.ifExp().get("it").callNoParam("hasNext").thenBlock() .switchOn().get("it").callNoParam("next").switchBlock(); for (int j = 0; j < fsa[i].length; j++) { int to = fsa[i][j]; s = s.caseBlock(j) .gotoLabel("s_"+to) .endCase(); } m = s.endSwitch() .elseBlock() .gotoLabel("end") .endIf(); } FutureType testClass = m.label("end").endMethod().endClass(); new TypePrinter().print(testClass); Logger.getLogger("brennus").setLevel(Level.FINEST); Logger.getLogger("brennus").addHandler(new Handler() { public void publish(LogRecord record) { System.out.println(record.getMessage()); } public void flush() { System.out.flush(); } public void close() throws SecurityException { System.out.flush(); } }); DynamicClassLoader cl = new DynamicClassLoader(); cl.define(testClass); Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass2"); FSA2 compiledFSA = (FSA2)generated.newInstance(); compiledFSA.exec(Arrays.asList(3,2,1).iterator()); assertEquals(Arrays.asList("s_0", "s_3", "s_2", "s_1"), compiledFSA.getStates()); } }
Java
/*- * #%L * Simmetrics - Examples * %% * Copyright (C) 2014 - 2021 Simmetrics Authors * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.github.mpkorstanje.simmetrics.example; import static com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder.with; import com.github.mpkorstanje.simmetrics.StringDistance; import com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder; import com.github.mpkorstanje.simmetrics.metrics.EuclideanDistance; import com.github.mpkorstanje.simmetrics.metrics.StringDistances; import com.github.mpkorstanje.simmetrics.tokenizers.Tokenizers; /** * The StringDistances utility class contains a predefined list of well * known distance metrics for strings. */ final class StringDistanceExample { /** * Two strings can be compared using a predefined distance metric. */ static float example01() { String str1 = "This is a sentence. It is made of words"; String str2 = "This sentence is similar. It has almost the same words"; StringDistance metric = StringDistances.levenshtein(); return metric.distance(str1, str2); // 30.0000 } /** * A tokenizer is included when the metric is a set or list metric. For the * euclidean distance, it is a whitespace tokenizer. * * Note that most predefined metrics are setup with a whitespace tokenizer. */ static float example02() { String str1 = "A quirky thing it is. This is a sentence."; String str2 = "This sentence is similar. A quirky thing it is."; StringDistance metric = StringDistances.euclideanDistance(); return metric.distance(str1, str2); // 2.0000 } /** * Using the string distance builder distance metrics can be customized. * Instead of a whitespace tokenizer a q-gram tokenizer is used. * * For more examples see StringDistanceBuilderExample. */ static float example03() { String str1 = "A quirky thing it is. This is a sentence."; String str2 = "This sentence is similar. A quirky thing it is."; StringDistance metric = StringDistanceBuilder.with(new EuclideanDistance<>()) .tokenize(Tokenizers.qGram(3)) .build(); return metric.distance(str1, str2); // 4.8989 } }
Java
/** * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.hdodenhof.androidstatemachine; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import android.util.Log; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * <p>The state machine defined here is a hierarchical state machine which processes messages * and can have states arranged hierarchically.</p> * * <p>A state is a <code>State</code> object and must implement * <code>processMessage</code> and optionally <code>enter/exit/getName</code>. * The enter/exit methods are equivalent to the construction and destruction * in Object Oriented programming and are used to perform initialization and * cleanup of the state respectively. The <code>getName</code> method returns the * name of the state the default implementation returns the class name it may be * desirable to have this return the name of the state instance name instead. * In particular if a particular state class has multiple instances.</p> * * <p>When a state machine is created <code>addState</code> is used to build the * hierarchy and <code>setInitialState</code> is used to identify which of these * is the initial state. After construction the programmer calls <code>start</code> * which initializes and starts the state machine. The first action the StateMachine * is to the invoke <code>enter</code> for all of the initial state's hierarchy, * starting at its eldest parent. The calls to enter will be done in the context * of the StateMachines Handler not in the context of the call to start and they * will be invoked before any messages are processed. For example, given the simple * state machine below mP1.enter will be invoked and then mS1.enter. Finally, * messages sent to the state machine will be processed by the current state, * in our simple state machine below that would initially be mS1.processMessage.</p> <code> mP1 / \ mS2 mS1 ----&gt; initial state </code> * <p>After the state machine is created and started, messages are sent to a state * machine using <code>sendMessage</code> and the messages are created using * <code>obtainMessage</code>. When the state machine receives a message the * current state's <code>processMessage</code> is invoked. In the above example * mS1.processMessage will be invoked first. The state may use <code>transitionTo</code> * to change the current state to a new state</p> * * <p>Each state in the state machine may have a zero or one parent states and if * a child state is unable to handle a message it may have the message processed * by its parent by returning false or NOT_HANDLED. If a message is never processed * <code>unhandledMessage</code> will be invoked to give one last chance for the state machine * to process the message.</p> * * <p>When all processing is completed a state machine may choose to call * <code>transitionToHaltingState</code>. When the current <code>processingMessage</code> * returns the state machine will transfer to an internal <code>HaltingState</code> * and invoke <code>halting</code>. Any message subsequently received by the state * machine will cause <code>haltedProcessMessage</code> to be invoked.</p> * * <p>If it is desirable to completely stop the state machine call <code>quit</code> or * <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents, * call <code>onQuiting</code> and then exit Thread/Loopers.</p> * * <p>In addition to <code>processMessage</code> each <code>State</code> has * an <code>enter</code> method and <code>exit</code> method which may be overridden.</p> * * <p>Since the states are arranged in a hierarchy transitioning to a new state * causes current states to be exited and new states to be entered. To determine * the list of states to be entered/exited the common parent closest to * the current state is found. We then exit from the current state and its * parent's up to but not including the common parent state and then enter all * of the new states below the common parent down to the destination state. * If there is no common parent all states are exited and then the new states * are entered.</p> * * <p>Two other methods that states can use are <code>deferMessage</code> and * <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends * a message but places it on the front of the queue rather than the back. The * <code>deferMessage</code> causes the message to be saved on a list until a * transition is made to a new state. At which time all of the deferred messages * will be put on the front of the state machine queue with the oldest message * at the front. These will then be processed by the new current state before * any other messages that are on the queue or might be added later. Both of * these are protected and may only be invoked from within a state machine.</p> * * <p>To illustrate some of these properties we'll use state machine with an 8 * state hierarchy:</p> <code> mP0 / \ mP1 mS0 / \ mS2 mS1 / \ \ mS3 mS4 mS5 ---&gt; initial state </code> * <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5. * So the order of calling processMessage when a message is received is mS5, * mS1, mP1, mP0 assuming each processMessage indicates it can't handle this * message by returning false or NOT_HANDLED.</p> * * <p>Now assume mS5.processMessage receives a message it can handle, and during * the handling determines the machine should change states. It could call * transitionTo(mS4) and return true or HANDLED. Immediately after returning from * processMessage the state machine runtime will find the common parent, * which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then * mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So * when the next message is received mS4.processMessage will be invoked.</p> * * <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine. * It responds with "Hello World" being printed to the log for every message.</p> <code> class HelloWorld extends StateMachine { HelloWorld(String name) { super(name); addState(mState1); setInitialState(mState1); } public static HelloWorld makeHelloWorld() { HelloWorld hw = new HelloWorld("hw"); hw.start(); return hw; } class State1 extends State { &#64;Override public boolean processMessage(Message message) { log("Hello World"); return HANDLED; } } State1 mState1 = new State1(); } void testHelloWorld() { HelloWorld hw = makeHelloWorld(); hw.sendMessage(hw.obtainMessage()); } </code> * <p>A more interesting state machine is one with four states * with two independent parent states.</p> <code> mP1 mP2 / \ mS2 mS1 </code> * <p>Here is a description of this state machine using pseudo code.</p> <code> state mP1 { enter { log("mP1.enter"); } exit { log("mP1.exit"); } on msg { CMD_2 { send(CMD_3); defer(msg); transitonTo(mS2); return HANDLED; } return NOT_HANDLED; } } INITIAL state mS1 parent mP1 { enter { log("mS1.enter"); } exit { log("mS1.exit"); } on msg { CMD_1 { transitionTo(mS1); return HANDLED; } return NOT_HANDLED; } } state mS2 parent mP1 { enter { log("mS2.enter"); } exit { log("mS2.exit"); } on msg { CMD_2 { send(CMD_4); return HANDLED; } CMD_3 { defer(msg); transitionTo(mP2); return HANDLED; } return NOT_HANDLED; } } state mP2 { enter { log("mP2.enter"); send(CMD_5); } exit { log("mP2.exit"); } on msg { CMD_3, CMD_4 { return HANDLED; } CMD_5 { transitionTo(HaltingState); return HANDLED; } return NOT_HANDLED; } } </code> * <p>The implementation is below and also in StateMachineTest:</p> <code> class Hsm1 extends StateMachine { public static final int CMD_1 = 1; public static final int CMD_2 = 2; public static final int CMD_3 = 3; public static final int CMD_4 = 4; public static final int CMD_5 = 5; public static Hsm1 makeHsm1() { log("makeHsm1 E"); Hsm1 sm = new Hsm1("hsm1"); sm.start(); log("makeHsm1 X"); return sm; } Hsm1(String name) { super(name); log("ctor E"); // Add states, use indentation to show hierarchy addState(mP1); addState(mS1, mP1); addState(mS2, mP1); addState(mP2); // Set the initial state setInitialState(mS1); log("ctor X"); } class P1 extends State { &#64;Override public void enter() { log("mP1.enter"); } &#64;Override public boolean processMessage(Message message) { boolean retVal; log("mP1.processMessage what=" + message.what); switch(message.what) { case CMD_2: // CMD_2 will arrive in mS2 before CMD_3 sendMessage(obtainMessage(CMD_3)); deferMessage(message); transitionTo(mS2); retVal = HANDLED; break; default: // Any message we don't understand in this state invokes unhandledMessage retVal = NOT_HANDLED; break; } return retVal; } &#64;Override public void exit() { log("mP1.exit"); } } class S1 extends State { &#64;Override public void enter() { log("mS1.enter"); } &#64;Override public boolean processMessage(Message message) { log("S1.processMessage what=" + message.what); if (message.what == CMD_1) { // Transition to ourself to show that enter/exit is called transitionTo(mS1); return HANDLED; } else { // Let parent process all other messages return NOT_HANDLED; } } &#64;Override public void exit() { log("mS1.exit"); } } class S2 extends State { &#64;Override public void enter() { log("mS2.enter"); } &#64;Override public boolean processMessage(Message message) { boolean retVal; log("mS2.processMessage what=" + message.what); switch(message.what) { case(CMD_2): sendMessage(obtainMessage(CMD_4)); retVal = HANDLED; break; case(CMD_3): deferMessage(message); transitionTo(mP2); retVal = HANDLED; break; default: retVal = NOT_HANDLED; break; } return retVal; } &#64;Override public void exit() { log("mS2.exit"); } } class P2 extends State { &#64;Override public void enter() { log("mP2.enter"); sendMessage(obtainMessage(CMD_5)); } &#64;Override public boolean processMessage(Message message) { log("P2.processMessage what=" + message.what); switch(message.what) { case(CMD_3): break; case(CMD_4): break; case(CMD_5): transitionToHaltingState(); break; } return HANDLED; } &#64;Override public void exit() { log("mP2.exit"); } } &#64;Override void onHalting() { log("halting"); synchronized (this) { this.notifyAll(); } } P1 mP1 = new P1(); S1 mS1 = new S1(); S2 mS2 = new S2(); P2 mP2 = new P2(); } </code> * <p>If this is executed by sending two messages CMD_1 and CMD_2 * (Note the synchronize is only needed because we use hsm.wait())</p> <code> Hsm1 hsm = makeHsm1(); synchronize(hsm) { hsm.sendMessage(obtainMessage(hsm.CMD_1)); hsm.sendMessage(obtainMessage(hsm.CMD_2)); try { // wait for the messages to be handled hsm.wait(); } catch (InterruptedException e) { loge("exception while waiting " + e.getMessage()); } } </code> * <p>The output is:</p> <code> D/hsm1 ( 1999): makeHsm1 E D/hsm1 ( 1999): ctor E D/hsm1 ( 1999): ctor X D/hsm1 ( 1999): mP1.enter D/hsm1 ( 1999): mS1.enter D/hsm1 ( 1999): makeHsm1 X D/hsm1 ( 1999): mS1.processMessage what=1 D/hsm1 ( 1999): mS1.exit D/hsm1 ( 1999): mS1.enter D/hsm1 ( 1999): mS1.processMessage what=2 D/hsm1 ( 1999): mP1.processMessage what=2 D/hsm1 ( 1999): mS1.exit D/hsm1 ( 1999): mS2.enter D/hsm1 ( 1999): mS2.processMessage what=2 D/hsm1 ( 1999): mS2.processMessage what=3 D/hsm1 ( 1999): mS2.exit D/hsm1 ( 1999): mP1.exit D/hsm1 ( 1999): mP2.enter D/hsm1 ( 1999): mP2.processMessage what=3 D/hsm1 ( 1999): mP2.processMessage what=4 D/hsm1 ( 1999): mP2.processMessage what=5 D/hsm1 ( 1999): mP2.exit D/hsm1 ( 1999): halting </code> */ public class StateMachine { // Name of the state machine and used as logging tag private String mName; /** Message.what value when quitting */ private static final int SM_QUIT_CMD = -1; /** Message.what value when initializing */ private static final int SM_INIT_CMD = -2; /** * Convenience constant that maybe returned by processMessage * to indicate the the message was processed and is not to be * processed by parent states */ public static final boolean HANDLED = true; /** * Convenience constant that maybe returned by processMessage * to indicate the the message was NOT processed and is to be * processed by parent states */ public static final boolean NOT_HANDLED = false; /** * StateMachine logging record. */ public static class LogRec { private StateMachine mSm; private long mTime; private int mWhat; private String mInfo; private IState mState; private IState mOrgState; private IState mDstState; /** * Constructor * * @param msg * @param state the state which handled the message * @param orgState is the first state the received the message but * did not processes the message. * @param transToState is the state that was transitioned to after the message was * processed. */ LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState, IState transToState) { update(sm, msg, info, state, orgState, transToState); } /** * Update the information in the record. * @param state that handled the message * @param orgState is the first state the received the message * @param dstState is the state that was the transition target when logging */ public void update(StateMachine sm, Message msg, String info, IState state, IState orgState, IState dstState) { mSm = sm; mTime = System.currentTimeMillis(); mWhat = (msg != null) ? msg.what : 0; mInfo = info; mState = state; mOrgState = orgState; mDstState = dstState; } /** * @return time stamp */ public long getTime() { return mTime; } /** * @return msg.what */ public long getWhat() { return mWhat; } /** * @return the command that was executing */ public String getInfo() { return mInfo; } /** * @return the state that handled this message */ public IState getState() { return mState; } /** * @return the state destination state if a transition is occurring or null if none. */ public IState getDestState() { return mDstState; } /** * @return the original state that received the message. */ public IState getOriginalState() { return mOrgState; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("time="); Calendar c = Calendar.getInstance(); c.setTimeInMillis(mTime); sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c)); sb.append(" processed="); sb.append(mState == null ? "<null>" : mState.getName()); sb.append(" org="); sb.append(mOrgState == null ? "<null>" : mOrgState.getName()); sb.append(" dest="); sb.append(mDstState == null ? "<null>" : mDstState.getName()); sb.append(" what="); String what = mSm != null ? mSm.getWhatToString(mWhat) : ""; if (TextUtils.isEmpty(what)) { sb.append(mWhat); sb.append("(0x"); sb.append(Integer.toHexString(mWhat)); sb.append(")"); } else { sb.append(what); } if (!TextUtils.isEmpty(mInfo)) { sb.append(" "); sb.append(mInfo); } return sb.toString(); } } /** * A list of log records including messages recently processed by the state machine. * * The class maintains a list of log records including messages * recently processed. The list is finite and may be set in the * constructor or by calling setSize. The public interface also * includes size which returns the number of recent records, * count which is the number of records processed since the * the last setSize, get which returns a record and * add which adds a record. */ private static class LogRecords { private static final int DEFAULT_SIZE = 20; private Vector<LogRec> mLogRecVector = new Vector<LogRec>(); private int mMaxSize = DEFAULT_SIZE; private int mOldestIndex = 0; private int mCount = 0; private boolean mLogOnlyTransitions = false; /** * private constructor use add */ private LogRecords() { } /** * Set size of messages to maintain and clears all current records. * * @param maxSize number of records to maintain at anyone time. */ synchronized void setSize(int maxSize) { mMaxSize = maxSize; mCount = 0; mLogRecVector.clear(); } synchronized void setLogOnlyTransitions(boolean enable) { mLogOnlyTransitions = enable; } synchronized boolean logOnlyTransitions() { return mLogOnlyTransitions; } /** * @return the number of recent records. */ synchronized int size() { return mLogRecVector.size(); } /** * @return the total number of records processed since size was set. */ synchronized int count() { return mCount; } /** * Clear the list of records. */ synchronized void cleanup() { mLogRecVector.clear(); } /** * @return the information on a particular record. 0 is the oldest * record and size()-1 is the newest record. If the index is to * large null is returned. */ synchronized LogRec get(int index) { int nextIndex = mOldestIndex + index; if (nextIndex >= mMaxSize) { nextIndex -= mMaxSize; } if (nextIndex >= size()) { return null; } else { return mLogRecVector.get(nextIndex); } } /** * Add a processed message. * * @param msg * @param messageInfo to be stored * @param state that handled the message * @param orgState is the first state the received the message but * did not processes the message. * @param transToState is the state that was transitioned to after the message was * processed. * */ synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state, IState orgState, IState transToState) { mCount += 1; if (mLogRecVector.size() < mMaxSize) { mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState)); } else { LogRec pmi = mLogRecVector.get(mOldestIndex); mOldestIndex += 1; if (mOldestIndex >= mMaxSize) { mOldestIndex = 0; } pmi.update(sm, msg, messageInfo, state, orgState, transToState); } } } private static class SmHandler extends Handler { /** true if StateMachine has quit */ private boolean mHasQuit = false; /** The debug flag */ private boolean mDbg = false; /** The SmHandler object, identifies that message is internal */ private static final Object mSmHandlerObj = new Object(); /** The current message */ private Message mMsg; /** A list of log records including messages this state machine has processed */ private LogRecords mLogRecords = new LogRecords(); /** true if construction of the state machine has not been completed */ private boolean mIsConstructionCompleted; /** Stack used to manage the current hierarchy of states */ private StateInfo mStateStack[]; /** Top of mStateStack */ private int mStateStackTopIndex = -1; /** A temporary stack used to manage the state stack */ private StateInfo mTempStateStack[]; /** The top of the mTempStateStack */ private int mTempStateStackCount; /** State used when state machine is halted */ private HaltingState mHaltingState = new HaltingState(); /** State used when state machine is quitting */ private QuittingState mQuittingState = new QuittingState(); /** Reference to the StateMachine */ private StateMachine mSm; /** * Information about a state. * Used to maintain the hierarchy. */ private class StateInfo { /** The state */ State state; /** The parent of this state, null if there is no parent */ StateInfo parentStateInfo; /** True when the state has been entered and on the stack */ boolean active; /** * Convert StateInfo to string */ @Override public String toString() { return "state=" + state.getName() + ",active=" + active + ",parent=" + ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName()); } } /** The map of all of the states in the state machine */ private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>(); /** The initial state that will process the first message */ private State mInitialState; /** The destination state when transitionTo has been invoked */ private State mDestState; /** The list of deferred messages */ private ArrayList<Message> mDeferredMessages = new ArrayList<Message>(); /** * State entered when transitionToHaltingState is called. */ private class HaltingState extends State { @Override public boolean processMessage(Message msg) { mSm.haltedProcessMessage(msg); return true; } } /** * State entered when a valid quit message is handled. */ private class QuittingState extends State { @Override public boolean processMessage(Message msg) { return NOT_HANDLED; } } /** * Handle messages sent to the state machine by calling * the current state's processMessage. It also handles * the enter/exit calls and placing any deferred messages * back onto the queue when transitioning to a new state. */ @Override public final void handleMessage(Message msg) { if (!mHasQuit) { if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what); /** Save the current message */ mMsg = msg; /** State that processed the message */ State msgProcessedState = null; if (mIsConstructionCompleted) { /** Normal path */ msgProcessedState = processMsg(msg); } else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD) && (mMsg.obj == mSmHandlerObj)) { /** Initial one time path. */ mIsConstructionCompleted = true; invokeEnterMethods(0); } else { throw new RuntimeException("StateMachine.handleMessage: " + "The start method not called, received msg: " + msg); } performTransitions(msgProcessedState, msg); // We need to check if mSm == null here as we could be quitting. if (mDbg && mSm != null) mSm.log("handleMessage: X"); } } /** * Do any transitions * @param msgProcessedState is the state that processed the message */ private void performTransitions(State msgProcessedState, Message msg) { /** * If transitionTo has been called, exit and then enter * the appropriate states. We loop on this to allow * enter and exit methods to use transitionTo. */ State orgState = mStateStack[mStateStackTopIndex].state; /** * Record whether message needs to be logged before we transition and * and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which * always set msg.obj to the handler. */ boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != mSmHandlerObj); if (mLogRecords.logOnlyTransitions()) { /** Record only if there is a transition */ if (mDestState != null) { mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState, mDestState); } } else if (recordLogMsg) { /** Record message */ mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState, mDestState); } State destState = mDestState; if (destState != null) { /** * Process the transitions including transitions in the enter/exit methods */ while (true) { if (mDbg) mSm.log("handleMessage: new destination call exit/enter"); /** * Determine the states to exit and enter and return the * common ancestor state of the enter/exit states. Then * invoke the exit methods then the enter methods. */ StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState); invokeExitMethods(commonStateInfo); int stateStackEnteringIndex = moveTempStateStackToStateStack(); invokeEnterMethods(stateStackEnteringIndex); /** * Since we have transitioned to a new state we need to have * any deferred messages moved to the front of the message queue * so they will be processed before any other messages in the * message queue. */ moveDeferredMessageAtFrontOfQueue(); if (destState != mDestState) { // A new mDestState so continue looping destState = mDestState; } else { // No change in mDestState so we're done break; } } mDestState = null; } /** * After processing all transitions check and * see if the last transition was to quit or halt. */ if (destState != null) { if (destState == mQuittingState) { /** * Call onQuitting to let subclasses cleanup. */ mSm.onQuitting(); cleanupAfterQuitting(); } else if (destState == mHaltingState) { /** * Call onHalting() if we've transitioned to the halting * state. All subsequent messages will be processed in * in the halting state which invokes haltedProcessMessage(msg); */ mSm.onHalting(); } } } /** * Cleanup all the static variables and the looper after the SM has been quit. */ private final void cleanupAfterQuitting() { if (mSm.mSmThread != null) { // If we made the thread then quit looper which stops the thread. getLooper().quit(); mSm.mSmThread = null; } mSm.mSmHandler = null; mSm = null; mMsg = null; mLogRecords.cleanup(); mStateStack = null; mTempStateStack = null; mStateInfo.clear(); mInitialState = null; mDestState = null; mDeferredMessages.clear(); mHasQuit = true; } /** * Complete the construction of the state machine. */ private final void completeConstruction() { if (mDbg) mSm.log("completeConstruction: E"); /** * Determine the maximum depth of the state hierarchy * so we can allocate the state stacks. */ int maxDepth = 0; for (StateInfo si : mStateInfo.values()) { int depth = 0; for (StateInfo i = si; i != null; depth++) { i = i.parentStateInfo; } if (maxDepth < depth) { maxDepth = depth; } } if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth); mStateStack = new StateInfo[maxDepth]; mTempStateStack = new StateInfo[maxDepth]; setupInitialStateStack(); /** Sending SM_INIT_CMD message to invoke enter methods asynchronously */ sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj)); if (mDbg) mSm.log("completeConstruction: X"); } /** * Process the message. If the current state doesn't handle * it, call the states parent and so on. If it is never handled then * call the state machines unhandledMessage method. * @return the state that processed the message */ private final State processMsg(Message msg) { StateInfo curStateInfo = mStateStack[mStateStackTopIndex]; if (mDbg) { mSm.log("processMsg: " + curStateInfo.state.getName()); } if (isQuit(msg)) { transitionTo(mQuittingState); } else { while (!curStateInfo.state.processMessage(msg)) { /** * Not processed */ curStateInfo = curStateInfo.parentStateInfo; if (curStateInfo == null) { /** * No parents left so it's not handled */ mSm.unhandledMessage(msg); break; } if (mDbg) { mSm.log("processMsg: " + curStateInfo.state.getName()); } } } return (curStateInfo != null) ? curStateInfo.state : null; } /** * Call the exit method for each state from the top of stack * up to the common ancestor state. */ private final void invokeExitMethods(StateInfo commonStateInfo) { while ((mStateStackTopIndex >= 0) && (mStateStack[mStateStackTopIndex] != commonStateInfo)) { State curState = mStateStack[mStateStackTopIndex].state; if (mDbg) mSm.log("invokeExitMethods: " + curState.getName()); curState.exit(); mStateStack[mStateStackTopIndex].active = false; mStateStackTopIndex -= 1; } } /** * Invoke the enter method starting at the entering index to top of state stack */ private final void invokeEnterMethods(int stateStackEnteringIndex) { for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) { if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName()); mStateStack[i].state.enter(); mStateStack[i].active = true; } } /** * Move the deferred message to the front of the message queue. */ private final void moveDeferredMessageAtFrontOfQueue() { /** * The oldest messages on the deferred list must be at * the front of the queue so start at the back, which * as the most resent message and end with the oldest * messages at the front of the queue. */ for (int i = mDeferredMessages.size() - 1; i >= 0; i--) { Message curMsg = mDeferredMessages.get(i); if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what); sendMessageAtFrontOfQueue(curMsg); } mDeferredMessages.clear(); } /** * Move the contents of the temporary stack to the state stack * reversing the order of the items on the temporary stack as * they are moved. * * @return index into mStateStack where entering needs to start */ private final int moveTempStateStackToStateStack() { int startingIndex = mStateStackTopIndex + 1; int i = mTempStateStackCount - 1; int j = startingIndex; while (i >= 0) { if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j); mStateStack[j] = mTempStateStack[i]; j += 1; i -= 1; } mStateStackTopIndex = j - 1; if (mDbg) { mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex + ",startingIndex=" + startingIndex + ",Top=" + mStateStack[mStateStackTopIndex].state.getName()); } return startingIndex; } /** * Setup the mTempStateStack with the states we are going to enter. * * This is found by searching up the destState's ancestors for a * state that is already active i.e. StateInfo.active == true. * The destStae and all of its inactive parents will be on the * TempStateStack as the list of states to enter. * * @return StateInfo of the common ancestor for the destState and * current state or null if there is no common parent. */ private final StateInfo setupTempStateStackWithStatesToEnter(State destState) { /** * Search up the parent list of the destination state for an active * state. Use a do while() loop as the destState must always be entered * even if it is active. This can happen if we are exiting/entering * the current state. */ mTempStateStackCount = 0; StateInfo curStateInfo = mStateInfo.get(destState); do { mTempStateStack[mTempStateStackCount++] = curStateInfo; curStateInfo = curStateInfo.parentStateInfo; } while ((curStateInfo != null) && !curStateInfo.active); if (mDbg) { mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount=" + mTempStateStackCount + ",curStateInfo: " + curStateInfo); } return curStateInfo; } /** * Initialize StateStack to mInitialState. */ private final void setupInitialStateStack() { if (mDbg) { mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName()); } StateInfo curStateInfo = mStateInfo.get(mInitialState); for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) { mTempStateStack[mTempStateStackCount] = curStateInfo; curStateInfo = curStateInfo.parentStateInfo; } // Empty the StateStack mStateStackTopIndex = -1; moveTempStateStackToStateStack(); } /** * @return current message */ private final Message getCurrentMessage() { return mMsg; } /** * @return current state */ private final IState getCurrentState() { return mStateStack[mStateStackTopIndex].state; } /** * Add a new state to the state machine. Bottom up addition * of states is allowed but the same state may only exist * in one hierarchy. * * @param state the state to add * @param parent the parent of state * @return stateInfo for this state */ private final StateInfo addState(State state, State parent) { if (mDbg) { mSm.log("addStateInternal: E state=" + state.getName() + ",parent=" + ((parent == null) ? "" : parent.getName())); } StateInfo parentStateInfo = null; if (parent != null) { parentStateInfo = mStateInfo.get(parent); if (parentStateInfo == null) { // Recursively add our parent as it's not been added yet. parentStateInfo = addState(parent, null); } } StateInfo stateInfo = mStateInfo.get(state); if (stateInfo == null) { stateInfo = new StateInfo(); mStateInfo.put(state, stateInfo); } // Validate that we aren't adding the same state in two different hierarchies. if ((stateInfo.parentStateInfo != null) && (stateInfo.parentStateInfo != parentStateInfo)) { throw new RuntimeException("state already added"); } stateInfo.state = state; stateInfo.parentStateInfo = parentStateInfo; stateInfo.active = false; if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo); return stateInfo; } /** * Constructor * * @param looper for dispatching messages * @param sm the hierarchical state machine */ private SmHandler(Looper looper, StateMachine sm) { super(looper); mSm = sm; addState(mHaltingState, null); addState(mQuittingState, null); } /** @see StateMachine#setInitialState(State) */ private final void setInitialState(State initialState) { if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName()); mInitialState = initialState; } /** @see StateMachine#transitionTo(IState) */ private final void transitionTo(IState destState) { mDestState = (State) destState; if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName()); } /** @see StateMachine#deferMessage(Message) */ private final void deferMessage(Message msg) { if (mDbg) mSm.log("deferMessage: msg=" + msg.what); /* Copy the "msg" to "newMsg" as "msg" will be recycled */ Message newMsg = obtainMessage(); newMsg.copyFrom(msg); mDeferredMessages.add(newMsg); } /** @see StateMachine#quit() */ private final void quit() { if (mDbg) mSm.log("quit:"); sendMessage(obtainMessage(SM_QUIT_CMD, mSmHandlerObj)); } /** @see StateMachine#quitNow() */ private final void quitNow() { if (mDbg) mSm.log("quitNow:"); sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, mSmHandlerObj)); } /** Validate that the message was sent by quit or quitNow. */ private final boolean isQuit(Message msg) { return (msg.what == SM_QUIT_CMD) && (msg.obj == mSmHandlerObj); } /** @see StateMachine#isDbg() */ private final boolean isDbg() { return mDbg; } /** @see StateMachine#setDbg(boolean) */ private final void setDbg(boolean dbg) { mDbg = dbg; } } private SmHandler mSmHandler; private HandlerThread mSmThread; /** * Initialize. * * @param looper for this state machine * @param name of the state machine */ private void initStateMachine(String name, Looper looper) { mName = name; mSmHandler = new SmHandler(looper, this); } /** * Constructor creates a StateMachine with its own thread. * * @param name of the state machine */ protected StateMachine(String name) { mSmThread = new HandlerThread(name); mSmThread.start(); Looper looper = mSmThread.getLooper(); initStateMachine(name, looper); } /** * Constructor creates a StateMachine using the looper. * * @param name of the state machine */ protected StateMachine(String name, Looper looper) { initStateMachine(name, looper); } /** * Constructor creates a StateMachine using the handler. * * @param name of the state machine */ protected StateMachine(String name, Handler handler) { initStateMachine(name, handler.getLooper()); } /** * Add a new state to the state machine * @param state the state to add * @param parent the parent of state */ protected final void addState(State state, State parent) { mSmHandler.addState(state, parent); } /** * Add a new state to the state machine, parent will be null * @param state to add */ protected final void addState(State state) { mSmHandler.addState(state, null); } /** * Set the initial state. This must be invoked before * and messages are sent to the state machine. * * @param initialState is the state which will receive the first message. */ protected final void setInitialState(State initialState) { mSmHandler.setInitialState(initialState); } /** * @return current message */ protected final Message getCurrentMessage() { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return null; return smh.getCurrentMessage(); } /** * @return current state */ protected final IState getCurrentState() { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return null; return smh.getCurrentState(); } /** * transition to destination state. Upon returning * from processMessage the current state's exit will * be executed and upon the next message arriving * destState.enter will be invoked. * * this function can also be called inside the enter function of the * previous transition target, but the behavior is undefined when it is * called mid-way through a previous transition (for example, calling this * in the enter() routine of a intermediate node when the current transition * target is one of the nodes descendants). * * @param destState will be the state that receives the next message. */ protected final void transitionTo(IState destState) { mSmHandler.transitionTo(destState); } /** * transition to halt state. Upon returning * from processMessage we will exit all current * states, execute the onHalting() method and then * for all subsequent messages haltedProcessMessage * will be called. */ protected final void transitionToHaltingState() { mSmHandler.transitionTo(mSmHandler.mHaltingState); } /** * Defer this message until next state transition. * Upon transitioning all deferred messages will be * placed on the queue and reprocessed in the original * order. (i.e. The next state the oldest messages will * be processed first) * * @param msg is deferred until the next transition. */ protected final void deferMessage(Message msg) { mSmHandler.deferMessage(msg); } /** * Called when message wasn't handled * * @param msg that couldn't be handled. */ protected void unhandledMessage(Message msg) { if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what); } /** * Called for any message that is received after * transitionToHalting is called. */ protected void haltedProcessMessage(Message msg) { } /** * This will be called once after handling a message that called * transitionToHalting. All subsequent messages will invoke * {@link StateMachine#haltedProcessMessage(Message)} */ protected void onHalting() { } /** * This will be called once after a quit message that was NOT handled by * the derived StateMachine. The StateMachine will stop and any subsequent messages will be * ignored. In addition, if this StateMachine created the thread, the thread will * be stopped after this method returns. */ protected void onQuitting() { } /** * @return the name */ public final String getName() { return mName; } /** * Set number of log records to maintain and clears all current records. * * @param maxSize number of messages to maintain at anyone time. */ public final void setLogRecSize(int maxSize) { mSmHandler.mLogRecords.setSize(maxSize); } /** * Set to log only messages that cause a state transition * * @param enable {@code true} to enable, {@code false} to disable */ public final void setLogOnlyTransitions(boolean enable) { mSmHandler.mLogRecords.setLogOnlyTransitions(enable); } /** * @return number of log records */ public final int getLogRecSize() { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return 0; return smh.mLogRecords.size(); } /** * @return the total number of records processed */ public final int getLogRecCount() { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return 0; return smh.mLogRecords.count(); } /** * @return a log record, or null if index is out of range */ public final LogRec getLogRec(int index) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return null; return smh.mLogRecords.get(index); } /** * @return a copy of LogRecs as a collection */ public final Collection<LogRec> copyLogRecs() { Vector<LogRec> vlr = new Vector<LogRec>(); SmHandler smh = mSmHandler; if (smh != null) { for (LogRec lr : smh.mLogRecords.mLogRecVector) { vlr.add(lr); } } return vlr; } /** * Add the string to LogRecords. * * @param string */ protected void addLogRec(String string) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(), smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState); } /** * @return true if msg should be saved in the log, default is true. */ protected boolean recordLogRec(Message msg) { return true; } /** * Return a string to be logged by LogRec, default * is an empty string. Override if additional information is desired. * * @param msg that was processed * @return information to be logged as a String */ protected String getLogRecString(Message msg) { return ""; } /** * @return the string for msg.what */ protected String getWhatToString(int what) { return null; } /** * @return Handler, maybe null if state machine has quit. */ public final Handler getHandler() { return mSmHandler; } /** * Get a message and set Message.target state machine handler. * * Note: The handler can be null if the state machine has quit, * which means target will be null and may cause a AndroidRuntimeException * in MessageQueue#enqueMessage if sent directly or if sent using * StateMachine#sendMessage the message will just be ignored. * * @return A Message object from the global pool */ public final Message obtainMessage() { return Message.obtain(mSmHandler); } /** * Get a message and set Message.target state machine handler, what. * * Note: The handler can be null if the state machine has quit, * which means target will be null and may cause a AndroidRuntimeException * in MessageQueue#enqueMessage if sent directly or if sent using * StateMachine#sendMessage the message will just be ignored. * * @param what is the assigned to Message.what. * @return A Message object from the global pool */ public final Message obtainMessage(int what) { return Message.obtain(mSmHandler, what); } /** * Get a message and set Message.target state machine handler, * what and obj. * * Note: The handler can be null if the state machine has quit, * which means target will be null and may cause a AndroidRuntimeException * in MessageQueue#enqueMessage if sent directly or if sent using * StateMachine#sendMessage the message will just be ignored. * * @param what is the assigned to Message.what. * @param obj is assigned to Message.obj. * @return A Message object from the global pool */ public final Message obtainMessage(int what, Object obj) { return Message.obtain(mSmHandler, what, obj); } /** * Get a message and set Message.target state machine handler, * what, arg1 and arg2 * * Note: The handler can be null if the state machine has quit, * which means target will be null and may cause a AndroidRuntimeException * in MessageQueue#enqueMessage if sent directly or if sent using * StateMachine#sendMessage the message will just be ignored. * * @param what is assigned to Message.what * @param arg1 is assigned to Message.arg1 * @return A Message object from the global pool */ public final Message obtainMessage(int what, int arg1) { // use this obtain so we don't match the obtain(h, what, Object) method return Message.obtain(mSmHandler, what, arg1, 0); } /** * Get a message and set Message.target state machine handler, * what, arg1 and arg2 * * Note: The handler can be null if the state machine has quit, * which means target will be null and may cause a AndroidRuntimeException * in MessageQueue#enqueMessage if sent directly or if sent using * StateMachine#sendMessage the message will just be ignored. * * @param what is assigned to Message.what * @param arg1 is assigned to Message.arg1 * @param arg2 is assigned to Message.arg2 * @return A Message object from the global pool */ public final Message obtainMessage(int what, int arg1, int arg2) { return Message.obtain(mSmHandler, what, arg1, arg2); } /** * Get a message and set Message.target state machine handler, * what, arg1, arg2 and obj * * Note: The handler can be null if the state machine has quit, * which means target will be null and may cause a AndroidRuntimeException * in MessageQueue#enqueMessage if sent directly or if sent using * StateMachine#sendMessage the message will just be ignored. * * @param what is assigned to Message.what * @param arg1 is assigned to Message.arg1 * @param arg2 is assigned to Message.arg2 * @param obj is assigned to Message.obj * @return A Message object from the global pool */ public final Message obtainMessage(int what, int arg1, int arg2, Object obj) { return Message.obtain(mSmHandler, what, arg1, arg2, obj); } /** * Enqueue a message to this state machine. * * Message is ignored if state machine has quit. */ public final void sendMessage(int what) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessage(obtainMessage(what)); } /** * Enqueue a message to this state machine. * * Message is ignored if state machine has quit. */ public final void sendMessage(int what, Object obj) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessage(obtainMessage(what, obj)); } /** * Enqueue a message to this state machine. * * Message is ignored if state machine has quit. */ public final void sendMessage(int what, int arg1) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessage(obtainMessage(what, arg1)); } /** * Enqueue a message to this state machine. * * Message is ignored if state machine has quit. */ public final void sendMessage(int what, int arg1, int arg2) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessage(obtainMessage(what, arg1, arg2)); } /** * Enqueue a message to this state machine. * * Message is ignored if state machine has quit. */ public final void sendMessage(int what, int arg1, int arg2, Object obj) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessage(obtainMessage(what, arg1, arg2, obj)); } /** * Enqueue a message to this state machine. * * Message is ignored if state machine has quit. */ public final void sendMessage(Message msg) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessage(msg); } /** * Enqueue a message to this state machine after a delay. * * Message is ignored if state machine has quit. */ public final void sendMessageDelayed(int what, long delayMillis) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageDelayed(obtainMessage(what), delayMillis); } /** * Enqueue a message to this state machine after a delay. * * Message is ignored if state machine has quit. */ public final void sendMessageDelayed(int what, Object obj, long delayMillis) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis); } /** * Enqueue a message to this state machine after a delay. * * Message is ignored if state machine has quit. */ public final void sendMessageDelayed(int what, int arg1, long delayMillis) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageDelayed(obtainMessage(what, arg1), delayMillis); } /** * Enqueue a message to this state machine after a delay. * * Message is ignored if state machine has quit. */ public final void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageDelayed(obtainMessage(what, arg1, arg2), delayMillis); } /** * Enqueue a message to this state machine after a delay. * * Message is ignored if state machine has quit. */ public final void sendMessageDelayed(int what, int arg1, int arg2, Object obj, long delayMillis) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageDelayed(obtainMessage(what, arg1, arg2, obj), delayMillis); } /** * Enqueue a message to this state machine after a delay. * * Message is ignored if state machine has quit. */ public final void sendMessageDelayed(Message msg, long delayMillis) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageDelayed(msg, delayMillis); } /** * Enqueue a message to the front of the queue for this state machine. * Protected, may only be called by instances of StateMachine. * * Message is ignored if state machine has quit. */ protected final void sendMessageAtFrontOfQueue(int what) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageAtFrontOfQueue(obtainMessage(what)); } /** * Enqueue a message to the front of the queue for this state machine. * Protected, may only be called by instances of StateMachine. * * Message is ignored if state machine has quit. */ protected final void sendMessageAtFrontOfQueue(int what, Object obj) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj)); } /** * Enqueue a message to the front of the queue for this state machine. * Protected, may only be called by instances of StateMachine. * * Message is ignored if state machine has quit. */ protected final void sendMessageAtFrontOfQueue(int what, int arg1) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1)); } /** * Enqueue a message to the front of the queue for this state machine. * Protected, may only be called by instances of StateMachine. * * Message is ignored if state machine has quit. */ protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2)); } /** * Enqueue a message to the front of the queue for this state machine. * Protected, may only be called by instances of StateMachine. * * Message is ignored if state machine has quit. */ protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2, Object obj) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2, obj)); } /** * Enqueue a message to the front of the queue for this state machine. * Protected, may only be called by instances of StateMachine. * * Message is ignored if state machine has quit. */ protected final void sendMessageAtFrontOfQueue(Message msg) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.sendMessageAtFrontOfQueue(msg); } /** * Removes a message from the message queue. * Protected, may only be called by instances of StateMachine. */ protected final void removeMessages(int what) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.removeMessages(what); } /** * Validate that the message was sent by * {@link StateMachine#quit} or {@link StateMachine#quitNow}. * */ protected final boolean isQuit(Message msg) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return msg.what == SM_QUIT_CMD; return smh.isQuit(msg); } /** * Quit the state machine after all currently queued up messages are processed. */ protected final void quit() { // mSmHandler can be null if the state machine is already stopped. SmHandler smh = mSmHandler; if (smh == null) return; smh.quit(); } /** * Quit the state machine immediately all currently queued messages will be discarded. */ protected final void quitNow() { // mSmHandler can be null if the state machine is already stopped. SmHandler smh = mSmHandler; if (smh == null) return; smh.quitNow(); } /** * @return if debugging is enabled */ public boolean isDbg() { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return false; return smh.isDbg(); } /** * Set debug enable/disabled. * * @param dbg is true to enable debugging. */ public void setDbg(boolean dbg) { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; smh.setDbg(dbg); } /** * Start the state machine. */ public void start() { // mSmHandler can be null if the state machine has quit. SmHandler smh = mSmHandler; if (smh == null) return; /** Send the complete construction message */ smh.completeConstruction(); } /** * Dump the current state. * * @param fd * @param pw * @param args */ public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { pw.println(getName() + ":"); pw.println(" total records=" + getLogRecCount()); for (int i = 0; i < getLogRecSize(); i++) { pw.printf(" rec[%d]: %s\n", i, getLogRec(i).toString()); pw.flush(); } pw.println("curState=" + getCurrentState().getName()); } /** * Log with debug and add to the LogRecords. * * @param s is string log */ protected void logAndAddLogRec(String s) { addLogRec(s); log(s); } /** * Log with debug * * @param s is string log */ protected void log(String s) { Log.d(mName, s); } /** * Log with debug attribute * * @param s is string log */ protected void logd(String s) { Log.d(mName, s); } /** * Log with verbose attribute * * @param s is string log */ protected void logv(String s) { Log.v(mName, s); } /** * Log with info attribute * * @param s is string log */ protected void logi(String s) { Log.i(mName, s); } /** * Log with warning attribute * * @param s is string log */ protected void logw(String s) { Log.w(mName, s); } /** * Log with error attribute * * @param s is string log */ protected void loge(String s) { Log.e(mName, s); } /** * Log with error attribute * * @param s is string log * @param e is a Throwable which logs additional information. */ protected void loge(String s, Throwable e) { Log.e(mName, s, e); } }
Java
/* * Copyright 2015-2020 Noel Welsh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package doodle package java2d package effect import cats.effect.IO import doodle.core.{Point,Transform} // import doodle.java2d.algebra.Algebra import java.awt.event._ import java.util.concurrent.atomic.AtomicReference import javax.swing.{JFrame, Timer, WindowConstants} import monix.reactive.subjects.PublishSubject /** * A [[Canvas]] is an area on the screen to which Pictures can be drawn. */ final class Canvas(frame: Frame) extends JFrame(frame.title) { val panel = new Java2DPanel(frame) /** * The current global transform from logical to screen coordinates */ private val currentInverseTx: AtomicReference[Transform] = new AtomicReference(Transform.identity) /** * Draw the given Picture to this [[Canvas]]. */ def render[A](picture: Picture[A]): IO[A] = { // Possible race condition here setting the currentInverseTx def register(cb: Either[Throwable, Java2DPanel.RenderResult[A]] => Unit): Unit = { // val drawing = picture(algebra) // val (bb, rdr) = drawing.runA(List.empty).value // val (w, h) = Java2d.size(bb, frame.size) // val rr = Java2DPanel.RenderRequest(bb, w, h, rdr, cb) panel.render(Java2DPanel.RenderRequest(picture, frame, cb)) } IO.async(register).map{result => val inverseTx = Java2d.inverseTransform(result.boundingBox, result.width, result.height, frame.center) currentInverseTx.set(inverseTx) result.value } } val redraw = PublishSubject[Int]() val frameRateMs = (1000.0 * (1 / 60.0)).toInt val frameEvent = { /** Delay between frames when rendering at 60fps */ var firstFrame = true var lastFrameTime = 0L new ActionListener { def actionPerformed(e: ActionEvent): Unit = { val now = e.getWhen() if (firstFrame) { firstFrame = false lastFrameTime = now redraw.onNext(0) () } else { redraw.onNext((now - lastFrameTime).toInt) lastFrameTime = now } } } } val timer = new Timer(frameRateMs, frameEvent) val mouseMove = PublishSubject[Point]() this.addMouseMotionListener( new MouseMotionListener { import scala.concurrent.duration.Duration import scala.concurrent.Await def mouseDragged(e: MouseEvent): Unit = () def mouseMoved(e: MouseEvent): Unit = { val pt = e.getPoint() val inverseTx = currentInverseTx.get() val ack = mouseMove.onNext(inverseTx(Point(pt.getX(), pt.getY()))) Await.ready(ack, Duration.Inf) () } } ) this.addWindowListener( new WindowAdapter { override def windowClosed(evt: WindowEvent): Unit = timer.stop() } ) getContentPane().add(panel) pack() setVisible(true) setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) repaint() timer.start() }
Java
// stdafx.cpp : source file that includes just the standard includes // importkeyboard.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
Java
namespace GeolocationBoundingBox.Google.Json { public class Geometry { public Location location { get; set; } public string location_type { get; set; } public Viewport viewport { get; set; } public Bounds bounds { get; set; } } }
Java
/* * Camunda BPM REST API * OpenApi Spec for Camunda BPM REST API. * * The version of the OpenAPI document: 7.13.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.camunda.consulting.openapi.client.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for MissingAuthorizationDto */ public class MissingAuthorizationDtoTest { private final MissingAuthorizationDto model = new MissingAuthorizationDto(); /** * Model tests for MissingAuthorizationDto */ @Test public void testMissingAuthorizationDto() { // TODO: test MissingAuthorizationDto } /** * Test the property 'permissionName' */ @Test public void permissionNameTest() { // TODO: test permissionName } /** * Test the property 'resourceName' */ @Test public void resourceNameTest() { // TODO: test resourceName } /** * Test the property 'resourceId' */ @Test public void resourceIdTest() { // TODO: test resourceId } }
Java
package th.ac.kmitl.ce.ooad.cest.repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import th.ac.kmitl.ce.ooad.cest.domain.Course; import th.ac.kmitl.ce.ooad.cest.domain.Faculty; import java.util.List; public interface CourseRepository extends CrudRepository<Course, Long>{ Course findFirstByCourseId(String courseId); Course findFirstByCourseName(String courseName); List<Course> findByCourseNameContainingOrCourseIdContainingOrderByCourseNameAsc(String courseName, String courseId); List<Course> findByFacultyOrderByCourseNameAsc(Faculty faculty); List<Course> findByDepartmentOrderByCourseNameAsc(String department); @Query("select c from Course c where c.department = ?2 or c.department = '' and c.faculty = ?1 order by c.courseName") List<Course> findByFacultyAndDepartmentOrNone(Faculty faculty, String department); }
Java
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009-2011 Alan Wright. All rights reserved. // Distributable under the terms of either the Apache License (Version 2.0) // or the GNU Lesser General Public License. ///////////////////////////////////////////////////////////////////////////// #include "TestInc.h" #include "LuceneTestFixture.h" #include "ConcurrentMergeScheduler.h" #include "DateTools.h" namespace Lucene { LuceneTestFixture::LuceneTestFixture() { DateTools::setDateOrder(DateTools::DATEORDER_LOCALE); ConcurrentMergeScheduler::setTestMode(); } LuceneTestFixture::~LuceneTestFixture() { DateTools::setDateOrder(DateTools::DATEORDER_LOCALE); if (ConcurrentMergeScheduler::anyUnhandledExceptions()) { // Clear the failure so that we don't just keep failing subsequent test cases ConcurrentMergeScheduler::clearUnhandledExceptions(); BOOST_FAIL("ConcurrentMergeScheduler hit unhandled exceptions"); } } }
Java
macimport os import subprocess name = "gobuildmaster" current_hash = "" for line in os.popen("md5sum " + name).readlines(): current_hash = line.split(' ')[0] # Move the old version over for line in os.popen('cp ' + name + ' old' + name).readlines(): print line.strip() # Rebuild for line in os.popen('go build').readlines(): print line.strip() size_1 = os.path.getsize('./old' + name) size_2 = os.path.getsize('./' + name) lines = os.popen('ps -ef | grep ' + name).readlines() running = False for line in lines: if "./" + name in line: running = True new_hash = "" for line in os.popen("md5sum " + name).readlines(): new_hash = line.split(' ')[0] if size_1 != size_2 or new_hash != current_hash or not running: if not running: for line in os.popen('cat out.txt | mail -E -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines(): pass for line in os.popen('echo "" > out.txt').readlines(): pass for line in os.popen('killall ' + name).readlines(): pass subprocess.Popen(['./' + name])
Java
import unittest2 import helper import simplejson as json from nose.plugins.attrib import attr PORTAL_ID = 62515 class ListsClientTest(unittest2.TestCase): """ Unit tests for the HubSpot List API Python wrapper (hapipy) client. This file contains some unittest tests for the List API. Questions, comments, etc: http://developers.hubspot.com """ def setUp(self): self.client = ListsClient(**helper.get_options()) def tearDown(self): pass @attr('api') def test_get_list(self): # create a list to get dummy_data = json.dumps(dict( name='try_and_get_me', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was created self.asserTrue(len(created_list['lists'])) # the id number of the list the test is trying to get id_to_get = created_list['listID'] # try and get it recieved_lists = self.client.get_list(id_to_get) # see if the test got the right list self.assertEqual(recieved_lists['lists'][0]['listId'], created_list['listId']) print "Got this list: %s" % json.dumps(recieved_list['lists'][0]) # clean up self.client.delete_list(id_to_get) @attr('api') def test_get_batch_lists(self): # holds the ids of the lists being retrieved list_ids = [] # make a list to get dummy_data = json.dumps(dict( name='first_test_list', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(created_list['listID']) # put the id of the newly made list in list_ids list_ids[0] = created_list['listId'] #change the data a little and make another list dummy_data['name'] = 'second_test_list' created_list = self.client.create_list(dummy_data) # make sure itwas actually made self.assertTrue(created_list['listID']) # put the id number in list_ids list_ids[1] = created_list['listId'] # try and get them batch_lists = self.client.get_batch_lists(list_ids) # make sure you got as many lists as you were searching for self.assertEqual(len(list_ids), len(batch_lists['lists'])) # clean up self.client.delete_list(list_ids[0]) self.client.delete_list(list_ids[1]) @attr('api') def test_get_lists(self): # try and get lists recieved_lists = self.client.get_lists() # see if the test got at least one if len(recieved_lists['lists']) == 0: self.fail("Unable to retrieve any lists") else: print "Got these lists %s" % json.dumps(recieved_lists) @attr('api') def test_get_static_lists(self): # create a static list to get dummy_data = json.dumps(dict( name='static_test_list', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(created_list['listID']) # this call will return 20 lists if not given another value static_lists = self.client.get_static_lists() if len(static_lists['lists']) == 0: self.fail("Unable to retrieve any static lists") else: print "Found these static lists: %s" % json.dumps(static_lists) # clean up self.client.delete_list(created_list['listId']) @attr('api') def test_get_dynamic_lists(self): # make a dynamic list to get dummy_data = json.dumps(dict( name='test_dynamic_list', dynamic=True, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure the dynamic list was made self.assertTrue(created_list['listId']) dynamic_lists = self.client.get_dynamic_lists() if len(dynamic_lists['lists']) == 0: self.fail("Unable to retrieve any dynamic lists") else: print "Found these dynamic lists: %s" % json.dumps(dynamic_lists) # clean up self.client.delete_list(created_list['listId']) @attr('api') def test_get_list_contacts(self): # the id number of the list you want the contacts of # which_list = # try and get the contacts contacts = self.client.get_list_contacts(which_list) # make sure you get at least one self.assertTrue(len(contacts['contacts']) print "Got these contacts: %s from this list: %s" % json.dumps(contacts), which_list) @attr('api') def test_get_list_contacts_recent(self): # the id number of the list you want the recent contacts of which_list = recent_contacts = self.client.get_list_contacts_recent(which_list) if len(recent_contacts['lists']) == 0: self.fail("Did not find any recent contacts") else: print "Found these recent contacts: %s" % json.dumps(recent_conacts) @attr('api') def test_create_list(self): # the data for the list the test is making dummy_data = json.dumps(dict( list_name='test_list', dynamic=False, portalId=PORTAL_ID )) # try and make the list created_list = self.client.create_list(dummy_data) # make sure it was created if len(created_lists['lists']) == 0: self.fail("Did not create the list") else: print "Created this list: %s" % json.dumps(created_lists) # clean up self.client.delete_list(created_lists['lists'][0]['listId']) @attr('api') def test_update_list(self): # make a list to update dummy_data = json.dumps(dict( name='delete_me', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(len(created_list['listId'])) # get the id number of the list update_list_id = created_list['listId'] # this is the data updating the list update_data = json.dumps(dict( list_name='really_delete_me', )) # try and do the update http_response = self.client.update_list(update_list_id, update_data) if http_response >= 400: self.fail("Unable to update list!") else: print("Updated a list!") # clean up self.client.delete_list(update_list_id) @attr('api') def test_add_contacts_to_list_from_emails(self): # make a list to add contacts to dummy_data = json.dumps(dict( name='give_me_contact_emails', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(len(created_list['lists'])) # the id number of the list being added to which_list = created_list['listId'] # the emails of the contacts being added emails = json.dumps(dict( emails )) # try and add the contacts self.client.add_contacts_to_list_from_emails(which_list, emails) @attr('api') def test_add_contact_to_list(self): # make a list to add a contact to dummy_data = json.dumps(dict( name='add_a_contact', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(created_list['listId']) # the id number of the list the contact is being added to which_list = created_list['listId'] # the id number of the contact being added to the list which_contact = added = self.client.add_contact_to_list(which_list, which_contact) if added['updated'] == which_contact: print "Succesfully added contact: %s to list: %s" % which_contact, which_list # if it worked, clean up self.client.delete_list(which_list) else: self.fail("Did not add contact: %s to list: %a" % which_contact, which_list) @attr('api') def test_remove_contact_from_list(self): # make a list to remove a contact from fake_data = json.dumps(dict( name='remove_this_contact' dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(fake_data) # make sure it was actually made self.assertTrue(created_list['listId']) # the id number of the list the contact is being deleted from which_list = created_list['listId'] # the id number of the contact being deleted which_contact = # put the contact in the list so it can be removed added = self.client.add_contact_to_list(which_list, which_contact) # make sure it was added self.assertTrue(added['updated']) # try and remove it removed = self.client.remove_contact_from_list(which_list, which_contact) # check if it was actually removed if removed['updated'] == which_contact: print "Succesfully removed contact: %s from list: %s" % which_contact, which_list # clean up self.client.delete_list(created_list['listId']) else: self.fail("Did not remove contact %s from list: %s" % which_contact, which_list) @attr('api') def test_delete_list(self): # make a list to delete dummy_data = json.dumps(dict( name='should_be_deleted', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # check if it was actually made self.assertTrue(created_list['listId']) # the id number of the list being deleted id_to_delete = created_list['listId'] # try deleting it self.client.delete_list(id_to_delete) # try and get the list that should have been deleted check = self.client.get_list(id_to_delete) # check should not have any lists self.assertEqual(len(check['lists']), 0) print "Sucessfully deleted a test list" @attr('api') def test_refresh_list(self): # make a dynamic list to refresh dummy_data = json.dumps(dict( name='refresh_this_list', dynamic=True, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it actually made the list self.assertTrue(created_list['listId']) # do the refresh refresh_response = self.client.refresh_list(created_list['listId']) # check if it worked if refresh_response >= 400: self.fail("Failed to refresh list: %s" % json.dumps(created_list)) else: print "Succesfully refreshed list: %s" % json.dumps(created_list) # clean up self.client.delete_list(created_list['listId']) if __name__ == "__main__": unittest2.main()
Java
package org.apache.lucene.facet.sampling; import java.io.IOException; import java.util.Collections; import org.apache.lucene.document.Document; import org.apache.lucene.facet.FacetTestCase; import org.apache.lucene.facet.index.FacetFields; import org.apache.lucene.facet.params.FacetIndexingParams; import org.apache.lucene.facet.params.FacetSearchParams; import org.apache.lucene.facet.sampling.RandomSampler; import org.apache.lucene.facet.sampling.Sampler; import org.apache.lucene.facet.sampling.SamplingAccumulator; import org.apache.lucene.facet.sampling.SamplingParams; import org.apache.lucene.facet.search.CountFacetRequest; import org.apache.lucene.facet.search.FacetRequest; import org.apache.lucene.facet.search.FacetResult; import org.apache.lucene.facet.search.FacetResultNode; import org.apache.lucene.facet.search.FacetsCollector; import org.apache.lucene.facet.search.StandardFacetsAccumulator; import org.apache.lucene.facet.search.FacetRequest.ResultMode; import org.apache.lucene.facet.taxonomy.CategoryPath; import org.apache.lucene.facet.taxonomy.TaxonomyReader; import org.apache.lucene.facet.taxonomy.TaxonomyWriter; import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader; import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.util.IOUtils; import org.junit.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class OversampleWithDepthTest extends FacetTestCase { @Test public void testCountWithdepthUsingSampling() throws Exception, IOException { Directory indexDir = newDirectory(); Directory taxoDir = newDirectory(); FacetIndexingParams fip = new FacetIndexingParams(randomCategoryListParams()); // index 100 docs, each with one category: ["root", docnum/10, docnum] // e.g. root/8/87 index100Docs(indexDir, taxoDir, fip); DirectoryReader r = DirectoryReader.open(indexDir); TaxonomyReader tr = new DirectoryTaxonomyReader(taxoDir); CountFacetRequest facetRequest = new CountFacetRequest(new CategoryPath("root"), 10); // Setting the depth to '2', should potentially get all categories facetRequest.setDepth(2); facetRequest.setResultMode(ResultMode.PER_NODE_IN_TREE); FacetSearchParams fsp = new FacetSearchParams(fip, facetRequest); // Craft sampling params to enforce sampling final SamplingParams params = new SamplingParams(); params.setMinSampleSize(2); params.setMaxSampleSize(50); params.setOversampleFactor(5); params.setSamplingThreshold(60); params.setSampleRatio(0.1); FacetResult res = searchWithFacets(r, tr, fsp, params); FacetRequest req = res.getFacetRequest(); assertEquals(facetRequest, req); FacetResultNode rootNode = res.getFacetResultNode(); // Each node below root should also have sub-results as the requested depth was '2' for (FacetResultNode node : rootNode.subResults) { assertTrue("node " + node.label + " should have had children as the requested depth was '2'", node.subResults.size() > 0); } IOUtils.close(r, tr, indexDir, taxoDir); } private void index100Docs(Directory indexDir, Directory taxoDir, FacetIndexingParams fip) throws IOException { IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, null); IndexWriter w = new IndexWriter(indexDir, iwc); TaxonomyWriter tw = new DirectoryTaxonomyWriter(taxoDir); FacetFields facetFields = new FacetFields(tw, fip); for (int i = 0; i < 100; i++) { Document doc = new Document(); CategoryPath cp = new CategoryPath("root",Integer.toString(i / 10), Integer.toString(i)); facetFields.addFields(doc, Collections.singletonList(cp)); w.addDocument(doc); } IOUtils.close(tw, w); } /** search reader <code>r</code>*/ private FacetResult searchWithFacets(IndexReader r, TaxonomyReader tr, FacetSearchParams fsp, final SamplingParams params) throws IOException { // a FacetsCollector with a sampling accumulator Sampler sampler = new RandomSampler(params, random()); StandardFacetsAccumulator sfa = new SamplingAccumulator(sampler, fsp, r, tr); FacetsCollector fcWithSampling = FacetsCollector.create(sfa); IndexSearcher s = new IndexSearcher(r); s.search(new MatchAllDocsQuery(), fcWithSampling); // there's only one expected result, return just it. return fcWithSampling.getFacetResults().get(0); } }
Java
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json from six.moves.urllib import parse as urllib from tempest_lib import exceptions as lib_exc from tempest.api_schema.response.compute.v2_1 import images as schema from tempest.common import service_client from tempest.common import waiters class ImagesClientJSON(service_client.ServiceClient): def create_image(self, server_id, name, meta=None): """Creates an image of the original server.""" post_body = { 'createImage': { 'name': name, } } if meta is not None: post_body['createImage']['metadata'] = meta post_body = json.dumps(post_body) resp, body = self.post('servers/%s/action' % str(server_id), post_body) self.validate_response(schema.create_image, resp, body) return service_client.ResponseBody(resp, body) def list_images(self, params=None): """Returns a list of all images filtered by any parameters.""" url = 'images' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.validate_response(schema.list_images, resp, body) return service_client.ResponseBodyList(resp, body['images']) def list_images_with_detail(self, params=None): """Returns a detailed list of images filtered by any parameters.""" url = 'images/detail' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.validate_response(schema.list_images_details, resp, body) return service_client.ResponseBodyList(resp, body['images']) def show_image(self, image_id): """Returns the details of a single image.""" resp, body = self.get("images/%s" % str(image_id)) self.expected_success(200, resp.status) body = json.loads(body) self.validate_response(schema.get_image, resp, body) return service_client.ResponseBody(resp, body['image']) def delete_image(self, image_id): """Deletes the provided image.""" resp, body = self.delete("images/%s" % str(image_id)) self.validate_response(schema.delete, resp, body) return service_client.ResponseBody(resp, body) def wait_for_image_status(self, image_id, status): """Waits for an image to reach a given status.""" waiters.wait_for_image_status(self, image_id, status) def list_image_metadata(self, image_id): """Lists all metadata items for an image.""" resp, body = self.get("images/%s/metadata" % str(image_id)) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_client.ResponseBody(resp, body['metadata']) def set_image_metadata(self, image_id, meta): """Sets the metadata for an image.""" post_body = json.dumps({'metadata': meta}) resp, body = self.put('images/%s/metadata' % str(image_id), post_body) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_client.ResponseBody(resp, body['metadata']) def update_image_metadata(self, image_id, meta): """Updates the metadata for an image.""" post_body = json.dumps({'metadata': meta}) resp, body = self.post('images/%s/metadata' % str(image_id), post_body) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_client.ResponseBody(resp, body['metadata']) def get_image_metadata_item(self, image_id, key): """Returns the value for a specific image metadata key.""" resp, body = self.get("images/%s/metadata/%s" % (str(image_id), key)) body = json.loads(body) self.validate_response(schema.image_meta_item, resp, body) return service_client.ResponseBody(resp, body['meta']) def set_image_metadata_item(self, image_id, key, meta): """Sets the value for a specific image metadata key.""" post_body = json.dumps({'meta': meta}) resp, body = self.put('images/%s/metadata/%s' % (str(image_id), key), post_body) body = json.loads(body) self.validate_response(schema.image_meta_item, resp, body) return service_client.ResponseBody(resp, body['meta']) def delete_image_metadata_item(self, image_id, key): """Deletes a single image metadata key/value pair.""" resp, body = self.delete("images/%s/metadata/%s" % (str(image_id), key)) self.validate_response(schema.delete, resp, body) return service_client.ResponseBody(resp, body) def is_resource_deleted(self, id): try: self.show_image(id) except lib_exc.NotFound: return True return False @property def resource_type(self): """Returns the primary type of resource this client works with.""" return 'image'
Java
using System; using System.Data; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility;//ÇëÏÈÌí¼ÓÒýÓà namespace TSM.DAL { /// <summary> /// Êý¾Ý·ÃÎÊÀàCK_People¡£ /// </summary> public class CK_People { public CK_People() {} #region ³ÉÔ±·½·¨ /// <summary> /// µÃµ½×î´óID /// </summary> public int GetMaxId() { return DbHelperSQL.GetMaxID("CK_PeopleID", "CK_People"); } /// <summary> /// ÊÇ·ñ´æÔڸüǼ /// </summary> public bool Exists(int CK_PeopleID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) from CK_People"); strSql.Append(" where CK_PeopleID=@CK_PeopleID "); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)}; parameters[0].Value = CK_PeopleID; return DbHelperSQL.Exists(strSql.ToString(),parameters); } /// <summary> /// Ôö¼ÓÒ»ÌõÊý¾Ý /// </summary> public int Add(TSM.Model.CK_People model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into CK_People("); strSql.Append("CK_PeopleName,CK_PhoneNo,CK_Comment)"); strSql.Append(" values ("); strSql.Append("@CK_PeopleName,@CK_PhoneNo,@CK_Comment)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32), new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32), new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)}; parameters[0].Value = model.CK_PeopleName; parameters[1].Value = model.CK_PhoneNo; parameters[2].Value = model.CK_Comment; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 1; } else { return Convert.ToInt32(obj); } } /// <summary> /// ¸üÐÂÒ»ÌõÊý¾Ý /// </summary> public void Update(TSM.Model.CK_People model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update CK_People set "); strSql.Append("CK_PeopleName=@CK_PeopleName,"); strSql.Append("CK_PhoneNo=@CK_PhoneNo,"); strSql.Append("CK_Comment=@CK_Comment"); strSql.Append(" where CK_PeopleID=@CK_PeopleID "); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4), new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32), new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32), new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)}; parameters[0].Value = model.CK_PeopleID; parameters[1].Value = model.CK_PeopleName; parameters[2].Value = model.CK_PhoneNo; parameters[3].Value = model.CK_Comment; DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); } /// <summary> /// ɾ³ýÒ»ÌõÊý¾Ý /// </summary> public void Delete(int CK_PeopleID) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from CK_People "); strSql.Append(" where CK_PeopleID=@CK_PeopleID "); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)}; parameters[0].Value = CK_PeopleID; DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); } /// <summary> /// µÃµ½Ò»¸ö¶ÔÏóʵÌå /// </summary> public TSM.Model.CK_People GetModel(int CK_PeopleID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select top 1 CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment from CK_People "); strSql.Append(" where CK_PeopleID=@CK_PeopleID "); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)}; parameters[0].Value = CK_PeopleID; TSM.Model.CK_People model=new TSM.Model.CK_People(); DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters); if(ds.Tables[0].Rows.Count>0) { if(ds.Tables[0].Rows[0]["CK_PeopleID"].ToString()!="") { model.CK_PeopleID=int.Parse(ds.Tables[0].Rows[0]["CK_PeopleID"].ToString()); } model.CK_PeopleName=ds.Tables[0].Rows[0]["CK_PeopleName"].ToString(); model.CK_PhoneNo=ds.Tables[0].Rows[0]["CK_PhoneNo"].ToString(); model.CK_Comment=ds.Tables[0].Rows[0]["CK_Comment"].ToString(); return model; } else { return null; } } /// <summary> /// »ñµÃÊý¾ÝÁбí /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment "); strSql.Append(" FROM CK_People "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// »ñµÃǰ¼¸ÐÐÊý¾Ý /// </summary> public DataSet GetList(int Top,string strWhere,string filedOrder) { StringBuilder strSql=new StringBuilder(); strSql.Append("select "); if(Top>0) { strSql.Append(" top "+Top.ToString()); } strSql.Append(" CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment "); strSql.Append(" FROM CK_People "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } strSql.Append(" order by " + filedOrder); return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// ·ÖÒ³»ñÈ¡Êý¾ÝÁбí /// </summary> public DataSet GetList(int PageSize,int PageIndex,string strWhere) { SqlParameter[] parameters = { new SqlParameter("@tblName", SqlDbType.VarChar, 255), new SqlParameter("@fldName", SqlDbType.VarChar, 255), new SqlParameter("@PageSize", SqlDbType.Int), new SqlParameter("@PageIndex", SqlDbType.Int), new SqlParameter("@IsReCount", SqlDbType.Bit), new SqlParameter("@OrderType", SqlDbType.Bit), new SqlParameter("@strWhere", SqlDbType.VarChar,1000), }; parameters[0].Value = "CK_People"; parameters[1].Value = "CK_PeopleID"; parameters[2].Value = PageSize; parameters[3].Value = PageIndex; parameters[4].Value = 0; parameters[5].Value = 0; parameters[6].Value = strWhere; return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds"); } #endregion ³ÉÔ±·½·¨ } }
Java
// Copyright 2016 Benjamin Glatzel // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // UI related includes #include "ui_IntrinsicEdPropertyEditorString.h" class IntrinsicEdPropertyEditorString : public QWidget { Q_OBJECT public: IntrinsicEdPropertyEditorString(rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties, rapidjson::Value* p_CurrentProperty, const char* p_PropertyName, QWidget* parent = nullptr); ~IntrinsicEdPropertyEditorString(); public slots: void onValueChanged(); signals: void valueChanged(rapidjson::Value& p_Properties); private: void updateFromProperty(); Ui::IntrinsicEdPropertyEditorStringClass _ui; rapidjson::Value* _property; rapidjson::Value* _properties; rapidjson::Document* _document; _INTR_STRING _propertyName; };
Java
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.jsprit.core.util; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.graphhopper.jsprit.core.algorithm.listener.AlgorithmEndsListener; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; import com.graphhopper.jsprit.core.problem.job.Job; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute; public class SolutionVerifier implements AlgorithmEndsListener { @Override public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) { for (VehicleRoutingProblemSolution solution : solutions) { Set<Job> jobsInSolution = new HashSet<Job>(); for (VehicleRoute route : solution.getRoutes()) { jobsInSolution.addAll(route.getTourActivities().getJobs()); } if (jobsInSolution.size() != problem.getJobs().size()) { throw new IllegalStateException("we are at the end of the algorithm and still have not found a valid solution." + "This cannot be."); } } } }
Java
package jp.ac.keio.bio.fun.xitosbml.image; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import ij.ImagePlus; import ij.ImageStack; import ij.process.ByteProcessor; /** * The class Filler, which provides several morphological operations for filling holes in the image. * Date Created: Feb 21, 2017 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Filler { /** The ImageJ image object. */ private ImagePlus image; /** The width of an image. */ private int width; /** The height of an image. */ private int height; /** The depth of an image. */ private int depth; /** The width of an image including padding. */ private int lwidth; /** The height of an image including padding. */ private int lheight; /** The depth of an image including padding. */ private int ldepth; /** The mask which stores the label of each pixel. */ private int[] mask; /** * The hashmap of pixel value. &lt;labelnumber, pixel value&gt;. * The domain which has pixel value = 0 will have a label = 1. */ private HashMap<Integer, Byte> hashPix = new HashMap<Integer, Byte>(); // label number, pixel value /** The raw data (1D byte array) of the image. */ private byte[] pixels; /** The raw data (1D int array) of inverted the image. */ private int[] invert; /** * Fill a hole in the given image (ImagePlus object) by morphology operation, * and returns the filled image. * * @param image the ImageJ image object * @return the filled ImageJ image (ImagePlus) object */ public ImagePlus fill(ImagePlus image){ this.width = image.getWidth(); this.height = image.getHeight(); this.depth = image.getStackSize(); this.image = image; pixels = ImgProcessUtil.copyMat(image); invertMat(); label(); if (checkHole()) { while (checkHole()) { fillHole(); hashPix.clear(); label(); } ImageStack stack = createStack(); image.setStack(stack); image.updateImage(); } return image; } /** * Fill a hole in the given image ({@link SpatialImage} object) by morphology operation, * and returns the filled image as ImageJ image object. * * @param spImg the SpatialImage object * @return the filled ImageJ image (ImagePlus) object */ public ImagePlus fill(SpatialImage spImg){ this.width = spImg.getWidth(); this.height = spImg.getHeight(); this.depth = spImg.getDepth(); this.image = spImg.getImage(); this.pixels = spImg.getRaw(); invertMat(); label(); if(checkHole()){ while(checkHole()){ fillHole(); hashPix.clear(); label(); } ImageStack stack = createStack(); image.setStack(stack); image.updateImage(); } return image; } /** * Creates the stack of images from raw data (1D array) of image (pixels[]), * and returns the stack of images. * * @return the stack of images */ private ImageStack createStack(){ ImageStack altimage = new ImageStack(width, height); for(int d = 0 ; d < depth ; d++){ byte[] matrix = new byte[width * height]; System.arraycopy(pixels, d * height * width, matrix, 0, matrix.length); altimage.addSlice(new ByteProcessor(width,height,matrix,null)); } return altimage; } /** * Create an inverted 1D array of an image (invert[]) from 1D array of an image (pixels[]). * Each pixel value will be inverted (0 -> 1, otherwise -> 0). For example, the Black and White * binary image will be converted to a White and Black binary image. */ private void invertMat(){ lwidth = width + 2; lheight = height + 2; if(depth < 3) ldepth = depth; else ldepth = depth + 2; invert = new int[lwidth * lheight * ldepth]; mask = new int[lwidth * lheight * ldepth]; if (ldepth > depth) { // 3D image for (int d = 0; d < ldepth; d++) { for (int h = 0; h < lheight; h++) { for (int w = 0; w < lwidth; w++) { if (d == 0 || d == ldepth - 1 || h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1) { invert[d * lheight * lwidth + h * lwidth + w] = 1; mask[d * lheight * lwidth + h * lwidth + w] = 1; continue; } if (pixels[(d - 1) * height * width + (h - 1) * width + w - 1] == 0) invert[d * lheight * lwidth + h * lwidth + w] = 1; else invert[d * lheight * lwidth + h * lwidth + w] = 0; } } } } else { // 2D image for (int d = 0; d < ldepth; d++) { for (int h = 0; h < lheight; h++) { for (int w = 0; w < lwidth; w++) { if(h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1){ invert[d * lheight * lwidth + h * lwidth + w] = 1; mask[d * lheight * lwidth + h * lwidth + w] = 1; continue; } if (pixels[d * height * width + (h - 1) * width + w - 1] == 0) invert[d * lheight * lwidth + h * lwidth + w] = 1; else invert[d * lheight * lwidth + h * lwidth + w] = 0; } } } } } /** The label count. */ private int labelCount; /** * Assign a label (label number) to each pixel. * The label number will be stored in mask[] array. * The domain which has pixel value = 0 will have a label = 1. */ public void label(){ hashPix.put(1, (byte)0); labelCount = 2; if (ldepth > depth) { for (int d = 1; d < ldepth - 1; d++) { for (int h = 1; h < lheight - 1; h++) { for (int w = 1; w < lwidth - 1; w++) { if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[(d-1) * height * width + (h-1) * width + w - 1] == 0) { mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]); }else{ mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]); } } } } }else{ for (int d = 0; d < ldepth; d++) { for (int h = 1; h < lheight - 1; h++) { for (int w = 1; w < lwidth - 1; w++) { if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[d * height * width + (h-1) * width + w - 1] == 0) { mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]); }else{ mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]); } } } } } } /** * Check whether a hole exists in the hashmap of pixels (HashMap&lt;label number, pixel value&gt;). * * @return true, if a hole exists */ public boolean checkHole(){ if(Collections.frequency(hashPix.values(), (byte) 0) > 1) return true; else return false; } /** * Fill a hole in the hashmap of pixels (HashMap&lt;label number, pixel value&gt; by morphology operation. * The fill operation will be applied to each domain (which has unique label number). */ public void fillHole(){ for(Entry<Integer, Byte> e : hashPix.entrySet()){ if(!e.getKey().equals(1) && e.getValue().equals((byte)0)){ fill(e.getKey()); } } } /** * Fill a hole in the hashmap of pixels (HashMap&lt;label number, pixel value&gt; by morphology operation. * The hole will be filled with the pixel value of adjacent pixel. * * @param labelNum the label number */ public void fill(int labelNum){ if (ldepth > depth) { // 3D image for (int d = 1; d < ldepth; d++) { for (int h = 1; h < lheight - 1; h++) { for (int w = 1; w < lwidth - 1; w++) { if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) { pixels[(d-1) * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum); } } } } } else { // 2D image for (int d = 0; d < ldepth; d++) { for (int h = 1; h < lheight - 1; h++) { for (int w = 1; w < lwidth - 1; w++) { if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) { pixels[d * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum); } } } } } } /** * Check adjacent pixels whether it contains the given label (labelNum). * If all the adjacent pixels have same label with given label, then return 0. * If the adjacent pixels contain different labels, then returns the pixel * value of most enclosing adjacent domain. * * @param w the x offset * @param h the y offset * @param d the z offset * @param labelNum the label number * @return the pixel value of most enclosing adjacent domain if different domain exists, otherwise 0 */ public byte checkAdjacentsLabel(int w, int h, int d, int labelNum){ List<Byte> adjVal = new ArrayList<Byte>(); //check right if(mask[d * lheight * lwidth + h * lwidth + w + 1] != labelNum) adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w + 1])); //check left if(mask[d * lheight * lwidth + h * lwidth + w - 1] != labelNum) adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1])); //check down if(mask[d * lheight * lwidth + (h+1) * lwidth + w ] != labelNum) adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h+1) * lwidth + w])); //check up if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != labelNum) adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w])); //check above if(d != depth - 1 && mask[(d+1) * lheight * lwidth + h * lwidth + w] != labelNum) adjVal.add(hashPix.get(mask[(d+1) * lheight * lwidth + h * lwidth + w])); //check below if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != labelNum) adjVal.add(hashPix.get(mask[(d - 1) * lheight * lwidth + h * lwidth + w])); if(adjVal.isEmpty()) return 0; int max = 0; int count = 0; int freq, temp; Byte val = 0; for(int n = 0 ; n < adjVal.size() ; n++){ val = adjVal.get(n); if(val == 0) continue; freq = Collections.frequency(adjVal, val); temp = val & 0xFF; if(freq > count){ max = temp; count = freq; } if(freq == count && max < temp){ max = temp; count = freq; } } return (byte) max; } /** * Sets the label of the given pixel (x offset, y offset, z offset) with its pixel value. * Checks whether the adjacent pixel has the zero pixel value, and its label is already assigned. * * @param w the x offset * @param h the y offset * @param d the z offset * @param pixVal the pixel value * @return the label as integer value */ private int setLabel(int w , int h, int d, byte pixVal){ List<Integer> adjVal = new ArrayList<Integer>(); //check left if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) == (byte)0) adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]); //check up if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) == (byte)0) adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]); //check below if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) == (byte)0) adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]); if(adjVal.isEmpty()){ hashPix.put(labelCount, pixVal); return labelCount++; } Collections.sort(adjVal); //if all element are same or list has only one element if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size()) return adjVal.get(0); int min = adjVal.get(0); for(int i = 1; i < adjVal.size(); i++){ if(min == adjVal.get(i)) continue; rewriteLabel(d, min, adjVal.get(i)); hashPix.remove(adjVal.get(i)); } return min; } /** * Sets back the label of the given pixel (x offset, y offset, z offset) with its pixel value. * Checks whether the adjacent pixel has the non-zero pixel value, and its label is already assigned. * * @param w the x offset * @param h the y offset * @param d the z offset * @param pixVal the pixel value * @return the label as integer value */ private int setbackLabel(int w , int h, int d, byte pixVal){ List<Integer> adjVal = new ArrayList<Integer>(); //check left if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) != (byte)0) adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]); //check up if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) != (byte)0) adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]); //check below if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) != (byte)0) adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]); if(adjVal.isEmpty()){ hashPix.put(labelCount, pixVal); return labelCount++; } Collections.sort(adjVal); //if all element are same or list has only one element if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size()) return adjVal.get(0); int min = adjVal.get(0); for(int i = 1; i < adjVal.size(); i++){ if(min == adjVal.get(i)) continue; hashPix.remove(adjVal.get(i)); rewriteLabel(d, min, adjVal.get(i)); } return min; } /** * Replace the label of pixels in the spatial image which has "before" to "after". * * @param dEnd the end of the depth * @param after the label to set by this replacement * @param before the label to be replaced */ private void rewriteLabel(int dEnd, int after, int before){ if (ldepth > depth) { for (int d = 1; d <= dEnd; d++) { for (int h = 1; h < lheight - 1; h++) { for (int w = 1; w < lwidth - 1; w++) { if (mask[d * lheight * lwidth + h * lwidth + w] == before) mask[d * lheight * lwidth + h * lwidth + w] = after; } } } }else{ for (int d = 0; d <= dEnd; d++) { for (int h = 1; h < lheight - 1; h++) { for (int w = 1; w < lwidth - 1; w++) { if (mask[d * lheight * lwidth + h * lwidth + w] == before) mask[d * lheight * lwidth + h * lwidth + w] = after; } } } } } }
Java
/* * Copyright 2015 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.core; import com.adaptris.annotation.Removal; import com.adaptris.core.stubs.UpgradedToJunit4; import com.adaptris.interlok.junit.scaffolding.ExampleConfigGenerator; @Deprecated @Removal(version = "4.0.0", message = "moved to com.adaptris.interlok.junit.scaffolding") public abstract class ExampleConfigCase extends ExampleConfigGenerator implements UpgradedToJunit4 { }
Java
/*! \file Texture.h * \author Jared Hoberock * \brief Defines the interface to a class abstracting * textures for shading. */ #pragma once #include <array2/Array2.h> #include "../include/detail/Spectrum.h" class Texture : protected Array2<Spectrum> { public: /*! Null constructor creates a 1x1 white Texture. */ Texture(void); /*! Constructor calls the Parent. * \param w The width of the Texture. * \param h The height of the Texture. * \param pixels The pixel data to copy into this Texture. */ Texture(const size_t w, const size_t h, const Spectrum *pixels); /*! Constructor takes a filename referring to * an image file on disk. * \param filename The name of the image file of interest. */ Texture(const char *filename); /*! This method provides const access to pixels. * \param x The column index of the pixel of interest. * \param y The row index of the pixel of interest. * \return A const reference to pixel (x,y). */ virtual const Spectrum &texRect(const size_t x, const size_t y) const; /*! This method provides nearest-neighbor filtering * given pixel coordinates in [0,1]^2. * \param u The u-coordinate of the pixel location of interest. * \param v The v-coordinate of the pixel location of interest. * \return The box-filtered pixel at (u,v). */ virtual const Spectrum &tex2D(const float u, const float v) const; /*! This method loads this Texture's data from an * image file on disk. * \param filename * \param filename The name of the image file of interest. */ virtual void load(const char *filename); protected: /*! \typedef Parent * \brief Shorthand. */ typedef Array2<Spectrum> Parent; }; // end Texture
Java
package org.ak.gitanalyzer.http.processor; import org.ak.gitanalyzer.util.writer.CSVWriter; import org.ak.gitanalyzer.util.writer.HTMLWriter; import java.text.NumberFormat; import java.util.Collection; import java.util.function.BiConsumer; import java.util.function.Function; /** * Created by Andrew on 02.12.2016. */ public class ProcessorMock extends BaseAnalysisProcessor { public ProcessorMock(NumberFormat nf) { super(nf); } @Override public <T> String getCSVForReport(String[] headers, Collection<T> collection, BiConsumer<T, StringBuilder> consumer) { return super.getCSVForReport(headers, collection, consumer); } @Override public <T> String getJSONForTable(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) { return super.getJSONForTable(collection, consumer); } @Override public <T> String getJSONFor2D(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) { return super.getJSONFor2D(collection, consumer); } @Override public <T> String getJSONForGraph(Collection<T> collection, Function<T, Integer> nodeIdSupplier, TriConsumer<T, StringBuilder, Integer> consumer) { return super.getJSONForGraph(collection, nodeIdSupplier, consumer); } @Override public String getTypeString(double weight, double thickThreshold, double normalThreshold) { return super.getTypeString(weight, thickThreshold, normalThreshold); } public HTMLWriter getHtmlWriter() { return htmlWriter; } public CSVWriter getCsvWriter() { return csvWriter; } }
Java
# require './lib/class_extensions' # require './lib/mylogger' # DEV Only requries above. require './lib/code_detector' require './lib/dsl/style_dsl' require './lib/dsl/selector_dsl' require './lib/tag_helper' require './lib/html/html_class_finder' require './lib/html/style_list' require './lib/highlighter/highlighters_enum' require './lib/theme_store' # Do bunch of apply, then invoke end_apply to close the style tag class StyleGenerator include HtmlClassFinder, HighlightersEnum, CodeDetector def initialize(tag_helper, lang = 'none') @tag_helper = tag_helper # $logger.info(lang) # # theming. # @colorizer = if lang == 'git' || iscmd # DarkColorizer.new # elsif ['asp', 'csharp'].include?(lang) # VisualStudioColorizer.new # else # LightColorizer.new # end # $logger.debug(@colorizer) @lang = lang end def style_front(front_card_block) front_style = style {} front_style.styles << build_main no_tag = @tag_helper.untagged? || @tag_helper.back_only? front_style.styles << build_tag unless no_tag tags = find(front_card_block, :span) build_code(tags) { |style| front_style.styles << style } front_style.styles << build_inline if inline?(front_card_block) front_style end def style_back(back_card_block) back_style = style(get_theme) {} back_style.styles << build_main no_tag = @tag_helper.untagged? || @tag_helper.front_only? back_style.styles << build_tag unless no_tag back_style.styles << build_figure if @tag_helper.figure? back_style.styles << build_command if command?(back_card_block) back_style.styles << build_well if well?(back_card_block) back_style.styles << build_inline if inline?(back_card_block) tags = find(back_card_block, :span) build_code(tags) { |style| back_style.styles << style } back_style end def get_theme case @lang when HighlightersEnum::RUBY ThemeStore::SublimeText2_Sunburst_Ruby else ThemeStore::Default end end def build_main select 'div.main' do font_size '16pt' text_align 'left' end end def build_tag select 'span.tag' do background_color '#5BC0DE' border_radius '5px' color 'white' font_size '14pt' padding '2px' margin_right '10px' end end def build_answer_only select 'span.answer' do background_color '#D9534F' border_radius '5px' color 'white' display 'table' font_weight 'bold' margin '0 auto' padding '2px 5px' end end def build_figure select '.fig', :line_height, '70%' end def build_inline select 'code.inline' do background_color '#F1F1F1' border '1px solid #DDD' border_radius '5px' color 'black' font_family 'monaco, courier' font_size '13pt' padding_left '2px' padding_right '2px' end end def build_command select 'code.command' do color 'white' background_color 'black' end end def build_well select 'code.well' do background_color '#F1F1F1' border '1px solid #E3E3E3' border_radius '4px' box_shadow 'inset 0 1px 1px rgba(0, 0, 0, 0.05)' color 'black' display 'block' font_family 'monaco, courier' font_size '14pt' margin_bottom '20px' min_height '20px' padding '19px' end end def build_code(tags) style_list = StyleList.new(tags) style_list.add('keyword', :color, '#7E0854') style_list.add('comment', :color, '#417E60') style_list.add('quote', :color, '#1324BF') style_list.add('var', :color, '#426F9C') style_list.add('url', :color, 'blue') style_list.add('html', :color, '#446FBD') style_list.add('attr', :color, '#6D8600') style_list.add('cls', :color, '#6D8600') style_list.add('num', :color, '#812050') style_list.add('opt', :color, 'darkgray') # style_list.add('cmd', :color, '#7E0854') # Per language Styles style_list.add('phptag', :color, '#FC0D1B') if @lang == PHP style_list.add('ann', :color, '#FC0D1B') if @lang == JAVA style_list.add('symbol', :color, '#808080') if @lang == ASP if @lang == GIT style_list.add('opt', :color, 'black') style_list.add('cmd', :color, '#FFFF9B') end style_list.each { |style| yield style } end end # # tag_helper = TagHelper.new(tags: []) # # tag_helper = TagHelper.new(tags: [:Concept]) # tag_helper = TagHelper.new(tags: [:FB]) # # tag_helper = TagHelper.new(tags: [:BF]) # generator = StyleGenerator.new(tag_helper) # puts( generator.style_back(['span class="keyword comment"']) )
Java
# Tristachya bequaertii var. vanderystii VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
"""A client for the REST API of imeji instances.""" import logging from collections import OrderedDict import requests from six import string_types from pyimeji import resource from pyimeji.config import Config log = logging.getLogger(__name__) class ImejiError(Exception): def __init__(self, message, error): super(ImejiError, self).__init__(message) self.error = error.get('error') if isinstance(error, dict) else error class GET(object): """Handle GET requests. This includes requests - to retrieve single objects, - to fetch lists of object references (which are returned as `OrderedDict` mapping object `id` to additional metadata present in the response). """ def __init__(self, api, name): """Initialize a handler. :param api: An Imeji API instance. :param name: Name specifying the kind of object(s) to retrieve. We check whether\ this name has a plural "s" to determine if a list is to be retrieved. """ self._list = name.endswith('s') self.rsc = getattr(resource, (name[:-1] if self._list else name).capitalize()) self.api = api self.name = name self.path = name if not self._list: self.path += 's' def __call__(self, id='', **kw): """Calling the handler initiates an HTTP request to the imeji server. :param id: If a single object is to be retrieved it must be specified by id. :return: An OrderedDict mapping id to additional metadata for lists, a \ :py:class:`pyimeji.resource.Resource` instance for single objects. """ if not self._list and not id: raise ValueError('no id given') if id: id = '/' + id res = self.api._req('/%s%s' % (self.path, id), params=kw) if not self._list: return self.rsc(res, self.api) return OrderedDict([(d['id'], d) for d in res]) class Imeji(object): """The client. >>> api = Imeji(service_url='http://demo.imeji.org/imeji/') >>> collection_id = list(api.collections().keys())[0] >>> collection = api.collection(collection_id) >>> collection = api.create('collection', title='the new collection') >>> item = collection.add_item(fetchUrl='http://example.org') >>> item.delete() """ def __init__(self, cfg=None, service_url=None): self.cfg = cfg or Config() self.service_url = service_url or self.cfg.get('service', 'url') user = self.cfg.get('service', 'user', default=None) password = self.cfg.get('service', 'password', default=None) self.session = requests.Session() if user and password: self.session.auth = (user, password) def _req(self, path, method='get', json=True, assert_status=200, **kw): """Make a request to the API of an imeji instance. :param path: HTTP path. :param method: HTTP method. :param json: Flag signalling whether the response should be treated as JSON. :param assert_status: Expected HTTP response status of a successful request. :param kw: Additional keyword parameters will be handed through to the \ appropriate function of the requests library. :return: The return value of the function of the requests library or a decoded \ JSON object/array. """ method = getattr(self.session, method.lower()) res = method(self.service_url + '/rest' + path, **kw) status_code = res.status_code if json: try: res = res.json() except ValueError: # pragma: no cover log.error(res.text[:1000]) raise if assert_status: if status_code != assert_status: log.error( 'got HTTP %s, expected HTTP %s' % (status_code, assert_status)) log.error(res.text[:1000] if hasattr(res, 'text') else res) raise ImejiError('Unexpected HTTP status code', res) return res def __getattr__(self, name): """Names of resource classes are accepted and resolved as dynamic attribute names. This allows convenient retrieval of resources as api.<resource-class>(id=<id>), or api.<resource-class>s(q='x'). """ return GET(self, name) def create(self, rsc, **kw): if isinstance(rsc, string_types): cls = getattr(resource, rsc.capitalize()) rsc = cls(kw, self) return rsc.save() def delete(self, rsc): return rsc.delete() def update(self, rsc, **kw): for k, v in kw.items(): setattr(rsc, k, v) return rsc.save()
Java
// // $Id: RawFileTypes.h 10422 2017-02-02 19:51:54Z chambm $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2008 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef _RAWFILETYPES_H_ #define _RAWFILETYPES_H_ #include "pwiz/utility/misc/Export.hpp" #include <string> #include <vector> #include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string/predicate.hpp> namespace bal = boost::algorithm; namespace pwiz { namespace vendor_api { namespace Thermo { enum PWIZ_API_DECL InstrumentModelType { InstrumentModelType_Unknown = -1, // Finnigan MAT InstrumentModelType_MAT253, InstrumentModelType_MAT900XP, InstrumentModelType_MAT900XP_Trap, InstrumentModelType_MAT95XP, InstrumentModelType_MAT95XP_Trap, InstrumentModelType_SSQ_7000, InstrumentModelType_TSQ_7000, InstrumentModelType_TSQ, // Thermo Electron InstrumentModelType_Element_2, // Thermo Finnigan InstrumentModelType_Delta_Plus_Advantage, InstrumentModelType_Delta_Plus_XP, InstrumentModelType_LCQ_Advantage, InstrumentModelType_LCQ_Classic, InstrumentModelType_LCQ_Deca, InstrumentModelType_LCQ_Deca_XP_Plus, InstrumentModelType_Neptune, InstrumentModelType_DSQ, InstrumentModelType_PolarisQ, InstrumentModelType_Surveyor_MSQ, InstrumentModelType_Tempus_TOF, InstrumentModelType_Trace_DSQ, InstrumentModelType_Triton, // Thermo Scientific InstrumentModelType_LTQ, InstrumentModelType_LTQ_Velos, InstrumentModelType_LTQ_Velos_Plus, InstrumentModelType_LTQ_FT, InstrumentModelType_LTQ_FT_Ultra, InstrumentModelType_LTQ_Orbitrap, InstrumentModelType_LTQ_Orbitrap_Discovery, InstrumentModelType_LTQ_Orbitrap_XL, InstrumentModelType_LTQ_Orbitrap_Velos, InstrumentModelType_LTQ_Orbitrap_Elite, InstrumentModelType_LXQ, InstrumentModelType_LCQ_Fleet, InstrumentModelType_ITQ_700, InstrumentModelType_ITQ_900, InstrumentModelType_ITQ_1100, InstrumentModelType_GC_Quantum, InstrumentModelType_LTQ_XL_ETD, InstrumentModelType_LTQ_Orbitrap_XL_ETD, InstrumentModelType_DFS, InstrumentModelType_DSQ_II, InstrumentModelType_ISQ, InstrumentModelType_MALDI_LTQ_XL, InstrumentModelType_MALDI_LTQ_Orbitrap, InstrumentModelType_TSQ_Quantum, InstrumentModelType_TSQ_Quantum_Access, InstrumentModelType_TSQ_Quantum_Ultra, InstrumentModelType_TSQ_Quantum_Ultra_AM, InstrumentModelType_TSQ_Vantage_Standard, InstrumentModelType_TSQ_Vantage_EMR, InstrumentModelType_Element_XR, InstrumentModelType_Element_GD, InstrumentModelType_GC_IsoLink, InstrumentModelType_Exactive, InstrumentModelType_Q_Exactive, InstrumentModelType_Surveyor_PDA, InstrumentModelType_Accela_PDA, InstrumentModelType_Orbitrap_Fusion, InstrumentModelType_Orbitrap_Fusion_ETD, InstrumentModelType_TSQ_Quantiva, InstrumentModelType_TSQ_Endura, InstrumentModelType_Count, }; inline InstrumentModelType parseInstrumentModelType(const std::string& instrumentModel) { std::string type = bal::to_upper_copy(instrumentModel); if (type == "MAT253") return InstrumentModelType_MAT253; else if (type == "MAT900XP") return InstrumentModelType_MAT900XP; else if (type == "MAT900XP Trap") return InstrumentModelType_MAT900XP_Trap; else if (type == "MAT95XP") return InstrumentModelType_MAT95XP; else if (type == "MAT95XP Trap") return InstrumentModelType_MAT95XP_Trap; else if (type == "SSQ 7000") return InstrumentModelType_SSQ_7000; else if (type == "TSQ 7000") return InstrumentModelType_TSQ_7000; else if (type == "TSQ") return InstrumentModelType_TSQ; else if (type == "ELEMENT2" || type == "ELEMENT 2") return InstrumentModelType_Element_2; else if (type == "DELTA PLUSADVANTAGE") return InstrumentModelType_Delta_Plus_Advantage; else if (type == "DELTAPLUSXP") return InstrumentModelType_Delta_Plus_XP; else if (type == "LCQ ADVANTAGE") return InstrumentModelType_LCQ_Advantage; else if (type == "LCQ CLASSIC") return InstrumentModelType_LCQ_Classic; else if (type == "LCQ DECA") return InstrumentModelType_LCQ_Deca; else if (type == "LCQ DECA XP" || type == "LCQ DECA XP PLUS") return InstrumentModelType_LCQ_Deca_XP_Plus; else if (type == "NEPTUNE") return InstrumentModelType_Neptune; else if (type == "DSQ") return InstrumentModelType_DSQ; else if (type == "POLARISQ") return InstrumentModelType_PolarisQ; else if (type == "SURVEYOR MSQ") return InstrumentModelType_Surveyor_MSQ; else if (type == "TEMPUS TOF") return InstrumentModelType_Tempus_TOF; else if (type == "TRACE DSQ") return InstrumentModelType_Trace_DSQ; else if (type == "TRITON") return InstrumentModelType_Triton; else if (type == "LTQ" || type == "LTQ XL") return InstrumentModelType_LTQ; else if (type == "LTQ FT" || type == "LTQ-FT") return InstrumentModelType_LTQ_FT; else if (type == "LTQ FT ULTRA") return InstrumentModelType_LTQ_FT_Ultra; else if (type == "LTQ ORBITRAP") return InstrumentModelType_LTQ_Orbitrap; else if (type == "LTQ ORBITRAP DISCOVERY") return InstrumentModelType_LTQ_Orbitrap_Discovery; else if (type == "LTQ ORBITRAP XL") return InstrumentModelType_LTQ_Orbitrap_XL; else if (bal::contains(type, "ORBITRAP VELOS")) return InstrumentModelType_LTQ_Orbitrap_Velos; else if (bal::contains(type, "ORBITRAP ELITE")) return InstrumentModelType_LTQ_Orbitrap_Elite; else if (bal::contains(type, "VELOS PLUS")) return InstrumentModelType_LTQ_Velos_Plus; else if (bal::contains(type, "VELOS PRO")) return InstrumentModelType_LTQ_Velos_Plus; else if (type == "LTQ VELOS") return InstrumentModelType_LTQ_Velos; else if (type == "LXQ") return InstrumentModelType_LXQ; else if (type == "LCQ FLEET") return InstrumentModelType_LCQ_Fleet; else if (type == "ITQ 700") return InstrumentModelType_ITQ_700; else if (type == "ITQ 900") return InstrumentModelType_ITQ_900; else if (type == "ITQ 1100") return InstrumentModelType_ITQ_1100; else if (type == "GC QUANTUM") return InstrumentModelType_GC_Quantum; else if (type == "LTQ XL ETD") return InstrumentModelType_LTQ_XL_ETD; else if (type == "LTQ ORBITRAP XL ETD") return InstrumentModelType_LTQ_Orbitrap_XL_ETD; else if (type == "DFS") return InstrumentModelType_DFS; else if (type == "DSQ II") return InstrumentModelType_DSQ_II; else if (type == "ISQ") return InstrumentModelType_ISQ; else if (type == "MALDI LTQ XL") return InstrumentModelType_MALDI_LTQ_XL; else if (type == "MALDI LTQ ORBITRAP") return InstrumentModelType_MALDI_LTQ_Orbitrap; else if (type == "TSQ QUANTUM") return InstrumentModelType_TSQ_Quantum; else if (bal::contains(type, "TSQ QUANTUM ACCESS")) return InstrumentModelType_TSQ_Quantum_Access; else if (type == "TSQ QUANTUM ULTRA") return InstrumentModelType_TSQ_Quantum_Ultra; else if (type == "TSQ QUANTUM ULTRA AM") return InstrumentModelType_TSQ_Quantum_Ultra_AM; else if (type == "TSQ VANTAGE STANDARD") return InstrumentModelType_TSQ_Vantage_Standard; else if (type == "TSQ VANTAGE EMR") return InstrumentModelType_TSQ_Vantage_EMR; else if (type == "TSQ QUANTIVA") return InstrumentModelType_TSQ_Quantiva; else if (type == "TSQ ENDURA") return InstrumentModelType_TSQ_Endura; else if (type == "ELEMENT XR") return InstrumentModelType_Element_XR; else if (type == "ELEMENT GD") return InstrumentModelType_Element_GD; else if (type == "GC ISOLINK") return InstrumentModelType_GC_IsoLink; else if (bal::contains(type, "Q EXACTIVE")) return InstrumentModelType_Q_Exactive; else if (bal::contains(type, "EXACTIVE")) return InstrumentModelType_Exactive; else if (bal::contains(type, "FUSION")) return bal::contains(type, "ETD") ? InstrumentModelType_Orbitrap_Fusion_ETD : InstrumentModelType_Orbitrap_Fusion; else if (type == "SURVEYOR PDA") return InstrumentModelType_Surveyor_PDA; else if (type == "ACCELA PDA") return InstrumentModelType_Accela_PDA; else return InstrumentModelType_Unknown; } enum PWIZ_API_DECL IonizationType { IonizationType_Unknown = -1, IonizationType_EI = 0, // Electron Ionization IonizationType_CI, // Chemical Ionization IonizationType_FAB, // Fast Atom Bombardment IonizationType_ESI, // Electrospray Ionization IonizationType_NSI, // Nanospray Ionization IonizationType_APCI, // Atmospheric Pressure Chemical Ionization IonizationType_TSP, // Thermospray IonizationType_FD, // Field Desorption IonizationType_MALDI, // Matrix-assisted Laser Desorption Ionization IonizationType_GD, // Glow Discharge IonizationType_Count }; inline std::vector<IonizationType> getIonSourcesForInstrumentModel(InstrumentModelType type) { std::vector<IonizationType> ionSources; switch (type) { case InstrumentModelType_SSQ_7000: case InstrumentModelType_TSQ_7000: case InstrumentModelType_Surveyor_MSQ: case InstrumentModelType_LCQ_Advantage: case InstrumentModelType_LCQ_Classic: case InstrumentModelType_LCQ_Deca: case InstrumentModelType_LCQ_Deca_XP_Plus: case InstrumentModelType_LCQ_Fleet: case InstrumentModelType_LXQ: case InstrumentModelType_LTQ: case InstrumentModelType_LTQ_XL_ETD: case InstrumentModelType_LTQ_Velos: case InstrumentModelType_LTQ_Velos_Plus: case InstrumentModelType_LTQ_FT: case InstrumentModelType_LTQ_FT_Ultra: case InstrumentModelType_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Discovery: case InstrumentModelType_LTQ_Orbitrap_XL: case InstrumentModelType_LTQ_Orbitrap_XL_ETD: case InstrumentModelType_LTQ_Orbitrap_Velos: case InstrumentModelType_LTQ_Orbitrap_Elite: case InstrumentModelType_Exactive: case InstrumentModelType_Q_Exactive: case InstrumentModelType_Orbitrap_Fusion: case InstrumentModelType_Orbitrap_Fusion_ETD: case InstrumentModelType_TSQ: case InstrumentModelType_TSQ_Quantum: case InstrumentModelType_TSQ_Quantum_Access: case InstrumentModelType_TSQ_Quantum_Ultra: case InstrumentModelType_TSQ_Quantum_Ultra_AM: case InstrumentModelType_TSQ_Vantage_Standard: case InstrumentModelType_TSQ_Vantage_EMR: case InstrumentModelType_TSQ_Quantiva: case InstrumentModelType_TSQ_Endura: ionSources.push_back(IonizationType_ESI); break; case InstrumentModelType_DSQ: case InstrumentModelType_PolarisQ: case InstrumentModelType_ITQ_700: case InstrumentModelType_ITQ_900: case InstrumentModelType_ITQ_1100: case InstrumentModelType_Trace_DSQ: case InstrumentModelType_GC_Quantum: case InstrumentModelType_DFS: case InstrumentModelType_DSQ_II: case InstrumentModelType_ISQ: case InstrumentModelType_GC_IsoLink: ionSources.push_back(IonizationType_EI); break; case InstrumentModelType_MALDI_LTQ_XL: case InstrumentModelType_MALDI_LTQ_Orbitrap: ionSources.push_back(IonizationType_MALDI); break; case InstrumentModelType_Element_GD: ionSources.push_back(IonizationType_GD); break; case InstrumentModelType_Element_XR: case InstrumentModelType_Element_2: case InstrumentModelType_Delta_Plus_Advantage: case InstrumentModelType_Delta_Plus_XP: case InstrumentModelType_Neptune: case InstrumentModelType_Tempus_TOF: case InstrumentModelType_Triton: case InstrumentModelType_MAT253: case InstrumentModelType_MAT900XP: case InstrumentModelType_MAT900XP_Trap: case InstrumentModelType_MAT95XP: case InstrumentModelType_MAT95XP_Trap: // TODO: get source information for these instruments break; case InstrumentModelType_Surveyor_PDA: case InstrumentModelType_Accela_PDA: case InstrumentModelType_Unknown: default: break; } return ionSources; } enum PWIZ_API_DECL ScanFilterMassAnalyzerType { ScanFilterMassAnalyzerType_Unknown = -1, ScanFilterMassAnalyzerType_ITMS = 0, // Ion Trap ScanFilterMassAnalyzerType_TQMS = 1, // Triple Quadrupole ScanFilterMassAnalyzerType_SQMS = 2, // Single Quadrupole ScanFilterMassAnalyzerType_TOFMS = 3, // Time of Flight ScanFilterMassAnalyzerType_FTMS = 4, // Fourier Transform ScanFilterMassAnalyzerType_Sector = 5, // Magnetic Sector ScanFilterMassAnalyzerType_Count = 6 }; enum PWIZ_API_DECL MassAnalyzerType { MassAnalyzerType_Unknown = -1, MassAnalyzerType_Linear_Ion_Trap, MassAnalyzerType_Quadrupole_Ion_Trap, MassAnalyzerType_Single_Quadrupole, MassAnalyzerType_Triple_Quadrupole, MassAnalyzerType_TOF, MassAnalyzerType_Orbitrap, MassAnalyzerType_FTICR, MassAnalyzerType_Magnetic_Sector, MassAnalyzerType_Count }; inline MassAnalyzerType convertScanFilterMassAnalyzer(ScanFilterMassAnalyzerType scanFilterType, InstrumentModelType instrumentModel) { switch (instrumentModel) { case InstrumentModelType_Exactive: case InstrumentModelType_Q_Exactive: return MassAnalyzerType_Orbitrap; case InstrumentModelType_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Discovery: case InstrumentModelType_LTQ_Orbitrap_XL: case InstrumentModelType_LTQ_Orbitrap_XL_ETD: case InstrumentModelType_MALDI_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Velos: case InstrumentModelType_LTQ_Orbitrap_Elite: case InstrumentModelType_Orbitrap_Fusion: case InstrumentModelType_Orbitrap_Fusion_ETD: { switch (scanFilterType) { case ScanFilterMassAnalyzerType_FTMS: return MassAnalyzerType_Orbitrap; //case ScanFilterMassAnalyzerType_SQMS: return MassAnalyzerType_Single_Quadrupole; FIXME: is this possible on the Fusion? default: case ScanFilterMassAnalyzerType_ITMS: return MassAnalyzerType_Linear_Ion_Trap; } } case InstrumentModelType_LTQ_FT: case InstrumentModelType_LTQ_FT_Ultra: if (scanFilterType == ScanFilterMassAnalyzerType_FTMS) return MassAnalyzerType_FTICR; else return MassAnalyzerType_Linear_Ion_Trap; case InstrumentModelType_SSQ_7000: case InstrumentModelType_Surveyor_MSQ: case InstrumentModelType_DSQ: case InstrumentModelType_DSQ_II: case InstrumentModelType_ISQ: case InstrumentModelType_Trace_DSQ: case InstrumentModelType_GC_IsoLink: return MassAnalyzerType_Single_Quadrupole; case InstrumentModelType_TSQ_7000: case InstrumentModelType_TSQ: case InstrumentModelType_TSQ_Quantum: case InstrumentModelType_TSQ_Quantum_Access: case InstrumentModelType_TSQ_Quantum_Ultra: case InstrumentModelType_TSQ_Quantum_Ultra_AM: case InstrumentModelType_TSQ_Vantage_Standard: case InstrumentModelType_TSQ_Vantage_EMR: case InstrumentModelType_GC_Quantum: case InstrumentModelType_TSQ_Quantiva: case InstrumentModelType_TSQ_Endura: return MassAnalyzerType_Triple_Quadrupole; case InstrumentModelType_LCQ_Advantage: case InstrumentModelType_LCQ_Classic: case InstrumentModelType_LCQ_Deca: case InstrumentModelType_LCQ_Deca_XP_Plus: case InstrumentModelType_LCQ_Fleet: case InstrumentModelType_PolarisQ: case InstrumentModelType_ITQ_700: case InstrumentModelType_ITQ_900: return MassAnalyzerType_Quadrupole_Ion_Trap; case InstrumentModelType_LTQ: case InstrumentModelType_LXQ: case InstrumentModelType_LTQ_XL_ETD: case InstrumentModelType_ITQ_1100: case InstrumentModelType_MALDI_LTQ_XL: case InstrumentModelType_LTQ_Velos: case InstrumentModelType_LTQ_Velos_Plus: return MassAnalyzerType_Linear_Ion_Trap; case InstrumentModelType_DFS: case InstrumentModelType_MAT253: case InstrumentModelType_MAT900XP: case InstrumentModelType_MAT900XP_Trap: case InstrumentModelType_MAT95XP: case InstrumentModelType_MAT95XP_Trap: return MassAnalyzerType_Magnetic_Sector; case InstrumentModelType_Tempus_TOF: return MassAnalyzerType_TOF; case InstrumentModelType_Element_XR: case InstrumentModelType_Element_2: case InstrumentModelType_Element_GD: case InstrumentModelType_Delta_Plus_Advantage: case InstrumentModelType_Delta_Plus_XP: case InstrumentModelType_Neptune: case InstrumentModelType_Triton: // TODO: get mass analyzer information for these instruments return MassAnalyzerType_Unknown; case InstrumentModelType_Surveyor_PDA: case InstrumentModelType_Accela_PDA: case InstrumentModelType_Unknown: default: return MassAnalyzerType_Unknown; } } inline std::vector<MassAnalyzerType> getMassAnalyzersForInstrumentModel(InstrumentModelType type) { std::vector<MassAnalyzerType> massAnalyzers; switch (type) { case InstrumentModelType_Exactive: case InstrumentModelType_Q_Exactive: massAnalyzers.push_back(MassAnalyzerType_Orbitrap); break; case InstrumentModelType_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Discovery: case InstrumentModelType_LTQ_Orbitrap_XL: case InstrumentModelType_MALDI_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Velos: case InstrumentModelType_LTQ_Orbitrap_Elite: case InstrumentModelType_Orbitrap_Fusion: // has a quadrupole but only for mass filtering, not analysis case InstrumentModelType_Orbitrap_Fusion_ETD: // has a quadrupole but only for mass filtering, not analysis massAnalyzers.push_back(MassAnalyzerType_Orbitrap); massAnalyzers.push_back(MassAnalyzerType_Linear_Ion_Trap); break; case InstrumentModelType_LTQ_FT: case InstrumentModelType_LTQ_FT_Ultra: massAnalyzers.push_back(MassAnalyzerType_FTICR); massAnalyzers.push_back(MassAnalyzerType_Linear_Ion_Trap); break; case InstrumentModelType_SSQ_7000: case InstrumentModelType_Surveyor_MSQ: case InstrumentModelType_DSQ: case InstrumentModelType_DSQ_II: case InstrumentModelType_ISQ: case InstrumentModelType_Trace_DSQ: case InstrumentModelType_GC_IsoLink: massAnalyzers.push_back(MassAnalyzerType_Single_Quadrupole); break; case InstrumentModelType_TSQ_7000: case InstrumentModelType_TSQ: case InstrumentModelType_TSQ_Quantum: case InstrumentModelType_TSQ_Quantum_Access: case InstrumentModelType_TSQ_Quantum_Ultra: case InstrumentModelType_TSQ_Quantum_Ultra_AM: case InstrumentModelType_TSQ_Vantage_Standard: case InstrumentModelType_TSQ_Vantage_EMR: case InstrumentModelType_GC_Quantum: case InstrumentModelType_TSQ_Quantiva: case InstrumentModelType_TSQ_Endura: massAnalyzers.push_back(MassAnalyzerType_Triple_Quadrupole); break; case InstrumentModelType_LCQ_Advantage: case InstrumentModelType_LCQ_Classic: case InstrumentModelType_LCQ_Deca: case InstrumentModelType_LCQ_Deca_XP_Plus: case InstrumentModelType_LCQ_Fleet: case InstrumentModelType_PolarisQ: case InstrumentModelType_ITQ_700: case InstrumentModelType_ITQ_900: massAnalyzers.push_back(MassAnalyzerType_Quadrupole_Ion_Trap); break; case InstrumentModelType_LTQ: case InstrumentModelType_LXQ: case InstrumentModelType_LTQ_XL_ETD: case InstrumentModelType_LTQ_Orbitrap_XL_ETD: case InstrumentModelType_ITQ_1100: case InstrumentModelType_MALDI_LTQ_XL: case InstrumentModelType_LTQ_Velos: case InstrumentModelType_LTQ_Velos_Plus: massAnalyzers.push_back(MassAnalyzerType_Linear_Ion_Trap); break; case InstrumentModelType_DFS: case InstrumentModelType_MAT253: case InstrumentModelType_MAT900XP: case InstrumentModelType_MAT900XP_Trap: case InstrumentModelType_MAT95XP: case InstrumentModelType_MAT95XP_Trap: massAnalyzers.push_back(MassAnalyzerType_Magnetic_Sector); break; case InstrumentModelType_Tempus_TOF: massAnalyzers.push_back(MassAnalyzerType_TOF); break; case InstrumentModelType_Element_XR: case InstrumentModelType_Element_2: case InstrumentModelType_Element_GD: case InstrumentModelType_Delta_Plus_Advantage: case InstrumentModelType_Delta_Plus_XP: case InstrumentModelType_Neptune: case InstrumentModelType_Triton: // TODO: get mass analyzer information for these instruments break; case InstrumentModelType_Surveyor_PDA: case InstrumentModelType_Accela_PDA: case InstrumentModelType_Unknown: default: break; } return massAnalyzers; } enum PWIZ_API_DECL DetectorType { DetectorType_Unknown = -1, DetectorType_Electron_Multiplier, DetectorType_Inductive, DetectorType_Photo_Diode_Array, DetectorType_Count }; inline std::vector<DetectorType> getDetectorsForInstrumentModel(InstrumentModelType type) { std::vector<DetectorType> detectors; switch (type) { case InstrumentModelType_Exactive: case InstrumentModelType_Q_Exactive: detectors.push_back(DetectorType_Inductive); break; case InstrumentModelType_LTQ_FT: case InstrumentModelType_LTQ_FT_Ultra: case InstrumentModelType_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Discovery: case InstrumentModelType_LTQ_Orbitrap_XL: case InstrumentModelType_LTQ_Orbitrap_XL_ETD: case InstrumentModelType_MALDI_LTQ_Orbitrap: case InstrumentModelType_LTQ_Orbitrap_Velos: case InstrumentModelType_LTQ_Orbitrap_Elite: case InstrumentModelType_Orbitrap_Fusion: case InstrumentModelType_Orbitrap_Fusion_ETD: detectors.push_back(DetectorType_Inductive); detectors.push_back(DetectorType_Electron_Multiplier); break; case InstrumentModelType_SSQ_7000: case InstrumentModelType_TSQ_7000: case InstrumentModelType_TSQ: case InstrumentModelType_LCQ_Advantage: case InstrumentModelType_LCQ_Classic: case InstrumentModelType_LCQ_Deca: case InstrumentModelType_LCQ_Deca_XP_Plus: case InstrumentModelType_Surveyor_MSQ: case InstrumentModelType_LTQ: case InstrumentModelType_MALDI_LTQ_XL: case InstrumentModelType_LXQ: case InstrumentModelType_LCQ_Fleet: case InstrumentModelType_LTQ_XL_ETD: case InstrumentModelType_LTQ_Velos: case InstrumentModelType_LTQ_Velos_Plus: case InstrumentModelType_TSQ_Quantum: case InstrumentModelType_TSQ_Quantum_Access: case InstrumentModelType_TSQ_Quantum_Ultra: case InstrumentModelType_TSQ_Quantum_Ultra_AM: case InstrumentModelType_TSQ_Vantage_Standard: case InstrumentModelType_TSQ_Vantage_EMR: case InstrumentModelType_DSQ: case InstrumentModelType_PolarisQ: case InstrumentModelType_ITQ_700: case InstrumentModelType_ITQ_900: case InstrumentModelType_ITQ_1100: case InstrumentModelType_Trace_DSQ: case InstrumentModelType_GC_Quantum: case InstrumentModelType_DFS: case InstrumentModelType_DSQ_II: case InstrumentModelType_ISQ: case InstrumentModelType_GC_IsoLink: case InstrumentModelType_TSQ_Quantiva: case InstrumentModelType_TSQ_Endura: detectors.push_back(DetectorType_Electron_Multiplier); break; case InstrumentModelType_Surveyor_PDA: case InstrumentModelType_Accela_PDA: detectors.push_back(DetectorType_Photo_Diode_Array); case InstrumentModelType_Element_GD: case InstrumentModelType_Element_XR: case InstrumentModelType_Element_2: case InstrumentModelType_Delta_Plus_Advantage: case InstrumentModelType_Delta_Plus_XP: case InstrumentModelType_Neptune: case InstrumentModelType_Tempus_TOF: case InstrumentModelType_Triton: case InstrumentModelType_MAT253: case InstrumentModelType_MAT900XP: case InstrumentModelType_MAT900XP_Trap: case InstrumentModelType_MAT95XP: case InstrumentModelType_MAT95XP_Trap: // TODO: get detector information for these instruments break; case InstrumentModelType_Unknown: default: break; } return detectors; } enum PWIZ_API_DECL ActivationType { ActivationType_Unknown = 0, ActivationType_CID = 1, // Collision Induced Dissociation ActivationType_MPD = 2, // TODO: what is this? ActivationType_ECD = 4, // Electron Capture Dissociation ActivationType_PQD = 8, // Pulsed Q Dissociation ActivationType_ETD = 16, // Electron Transfer Dissociation ActivationType_HCD = 32, // High Energy CID ActivationType_Any = 64, // "any activation type" when used as input parameter ActivationType_PTR = 128, // Proton Transfer Reaction ActivationType_NETD = 256, // TODO: nano-ETD? ActivationType_NPTR = 512, // TODO: nano-PTR? ActivationType_Count = 1024 }; enum PWIZ_API_DECL MSOrder { MSOrder_NeutralGain = -3, MSOrder_NeutralLoss = -2, MSOrder_ParentScan = -1, MSOrder_Any = 0, MSOrder_MS = 1, MSOrder_MS2 = 2, MSOrder_MS3 = 3, MSOrder_MS4 = 4, MSOrder_MS5 = 5, MSOrder_MS6 = 6, MSOrder_MS7 = 7, MSOrder_MS8 = 8, MSOrder_MS9 = 9, MSOrder_MS10 = 10, MSOrder_Count = 11 }; enum PWIZ_API_DECL ScanType { ScanType_Unknown = -1, ScanType_Full = 0, ScanType_Zoom = 1, ScanType_SIM = 2, ScanType_SRM = 3, ScanType_CRM = 4, ScanType_Any = 5, /// "any scan type" when used as an input parameter ScanType_Q1MS = 6, ScanType_Q3MS = 7, ScanType_Count = 8 }; enum PWIZ_API_DECL PolarityType { PolarityType_Unknown = -1, PolarityType_Positive = 0, PolarityType_Negative, PolarityType_Count }; enum PWIZ_API_DECL DataPointType { DataPointType_Unknown = -1, DataPointType_Centroid = 0, DataPointType_Profile, DataPointType_Count }; enum PWIZ_API_DECL AccurateMassType { AccurateMass_Unknown = -1, AccurateMass_NotActive = 0, // NOTE: in filter as "!AM": accurate mass not active AccurateMass_Active, // accurate mass active AccurateMass_ActiveWithInternalCalibration, // accurate mass with internal calibration AccurateMass_ActiveWithExternalCalibration // accurate mass with external calibration }; enum PWIZ_API_DECL TriBool { TriBool_Unknown = -1, TriBool_False = 0, TriBool_True = 1 }; } // namespace Thermo } // namespace vendor_api } // namespace pwiz #endif // _RAWFILETYPES_H_
Java
-- main.lua -- Implements the plugin entrypoint (in this case the entire plugin) -- Global variables: local g_Plugin = nil local g_PluginFolder = "" local g_Stats = {} local g_TrackedPages = {} local function LoadAPIFiles(a_Folder, a_DstTable) assert(type(a_Folder) == "string") assert(type(a_DstTable) == "table") local Folder = g_PluginFolder .. a_Folder; for _, fnam in ipairs(cFile:GetFolderContents(Folder)) do local FileName = Folder .. fnam; -- We only want .lua files from the folder: if (cFile:IsFile(FileName) and fnam:match(".*%.lua$")) then local TablesFn, Err = loadfile(FileName); if (type(TablesFn) ~= "function") then LOGWARNING("Cannot load API descriptions from " .. FileName .. ", Lua error '" .. Err .. "'."); else local Tables = TablesFn(); if (type(Tables) ~= "table") then LOGWARNING("Cannot load API descriptions from " .. FileName .. ", returned object is not a table (" .. type(Tables) .. ")."); break end for k, cls in pairs(Tables) do a_DstTable[k] = cls; end end -- if (TablesFn) end -- if (is lua file) end -- for fnam - Folder[] end local function CreateAPITables() --[[ We want an API table of the following shape: local API = { { Name = "cCuboid", Functions = { {Name = "Sort"}, {Name = "IsInside"} }, Constants = { }, Variables = { }, Descendants = {}, -- Will be filled by ReadDescriptions(), array of class APIs (references to other member in the tree) }, { Name = "cBlockArea", Functions = { {Name = "Clear"}, {Name = "CopyFrom"}, ... }, Constants = { {Name = "baTypes", Value = 0}, {Name = "baMetas", Value = 1}, ... }, Variables = { }, ... }, cCuboid = {} -- Each array item also has the map item by its name }; local Globals = { Functions = { ... }, Constants = { ... } }; --]] local Globals = {Functions = {}, Constants = {}, Variables = {}, Descendants = {}}; local API = {}; local function Add(a_APIContainer, a_ObjName, a_ObjValue) if (type(a_ObjValue) == "function") then table.insert(a_APIContainer.Functions, {Name = a_ObjName}); elseif ( (type(a_ObjValue) == "number") or (type(a_ObjValue) == "string") ) then table.insert(a_APIContainer.Constants, {Name = a_ObjName, Value = a_ObjValue}); end end local function ParseClass(a_ClassName, a_ClassObj) local res = {Name = a_ClassName, Functions = {}, Constants = {}, Variables = {}, Descendants = {}}; -- Add functions and constants: for i, v in pairs(a_ClassObj) do Add(res, i, v); end -- Member variables: local SetField = a_ClassObj[".set"] or {}; if ((a_ClassObj[".get"] ~= nil) and (type(a_ClassObj[".get"]) == "table")) then for k in pairs(a_ClassObj[".get"]) do if (SetField[k] == nil) then -- It is a read-only variable, add it as a constant: table.insert(res.Constants, {Name = k, Value = ""}); else -- It is a read-write variable, add it as a variable: table.insert(res.Variables, { Name = k }); end end end return res; end for i, v in pairs(_G) do if ( (v ~= _G) and -- don't want the global namespace (v ~= _G.packages) and -- don't want any packages (v ~= _G[".get"]) and (v ~= g_APIDesc) ) then if (type(v) == "table") then local cls = ParseClass(i, v) table.insert(API, cls); API[cls.Name] = cls else Add(Globals, i, v); end end end return API, Globals; end local function WriteArticles(f) f:write([[ <a name="articles"><h2>Articles</h2></a> <p>The following articles provide various extra information on plugin development</p> <ul> ]]); for _, extra in ipairs(g_APIDesc.ExtraPages) do local SrcFileName = g_PluginFolder .. "/" .. extra.FileName; if (cFile:Exists(SrcFileName)) then local DstFileName = "API/" .. extra.FileName; if (cFile:Exists(DstFileName)) then cFile:Delete(DstFileName); end cFile:Copy(SrcFileName, DstFileName); f:write("<li><a href=\"" .. extra.FileName .. "\">" .. extra.Title .. "</a></li>\n"); else f:write("<li>" .. extra.Title .. " <i>(file is missing)</i></li>\n"); end end f:write("</ul><hr />"); end -- Make a link out of anything with the special linkifying syntax {{link|title}} local function LinkifyString(a_String, a_Referrer) assert(a_Referrer ~= nil); assert(a_Referrer ~= ""); --- Adds a page to the list of tracked pages (to be checked for existence at the end) local function AddTrackedPage(a_PageName) local Pg = (g_TrackedPages[a_PageName] or {}); table.insert(Pg, a_Referrer); g_TrackedPages[a_PageName] = Pg; end --- Creates the HTML for the specified link and title local function CreateLink(Link, Title) if (Link:sub(1, 7) == "http://") then -- The link is a full absolute URL, do not modify, do not track: return "<a href=\"" .. Link .. "\">" .. Title .. "</a>"; end local idxHash = Link:find("#"); if (idxHash ~= nil) then -- The link contains an anchor: if (idxHash == 1) then -- Anchor in the current page, no need to track: return "<a href=\"" .. Link .. "\">" .. Title .. "</a>"; end -- Anchor in another page: local PageName = Link:sub(1, idxHash - 1); AddTrackedPage(PageName); return "<a href=\"" .. PageName .. ".html#" .. Link:sub(idxHash + 1) .. "\">" .. Title .. "</a>"; end -- Link without anchor: AddTrackedPage(Link); return "<a href=\"" .. Link .. ".html\">" .. Title .. "</a>"; end -- Linkify the strings using the CreateLink() function: local txt = a_String:gsub("{{([^|}]*)|([^}]*)}}", CreateLink) -- {{link|title}} txt = txt:gsub("{{([^|}]*)}}", -- {{LinkAndTitle}} function(LinkAndTitle) local idxHash = LinkAndTitle:find("#"); if (idxHash ~= nil) then -- The LinkAndTitle contains a hash, remove the hashed part from the title: return CreateLink(LinkAndTitle, LinkAndTitle:sub(1, idxHash - 1)); end return CreateLink(LinkAndTitle, LinkAndTitle); end ); return txt; end local function WriteHtmlHook(a_Hook, a_HookNav) local fnam = "API/" .. a_Hook.DefaultFnName .. ".html"; local f, error = io.open(fnam, "w"); if (f == nil) then LOG("Cannot write \"" .. fnam .. "\": \"" .. error .. "\"."); return; end local HookName = a_Hook.DefaultFnName; f:write([[<!DOCTYPE html><html> <head> <title>MCServer API - ]], HookName, [[ Hook</title> <link rel="stylesheet" type="text/css" href="main.css" /> <link rel="stylesheet" type="text/css" href="prettify.css" /> <script src="prettify.js"></script> <script src="lang-lua.js"></script> </head> <body> <div id="content"> <header> <h1>]], a_Hook.Name, [[</h1> <hr /> </header> <table><tr><td style="vertical-align: top;"> Index:<br /> <a href='index.html#articles'>Articles</a><br /> <a href='index.html#classes'>Classes</a><br /> <a href='index.html#hooks'>Hooks</a><br /> <br /> Quick navigation:<br /> ]]); f:write(a_HookNav); f:write([[ </td><td style="vertical-align: top;"><p> ]]); f:write(LinkifyString(a_Hook.Desc, HookName)); f:write("</p>\n<hr /><h1>Callback function</h1>\n<p>The default name for the callback function is "); f:write(a_Hook.DefaultFnName, ". It has the following signature:\n"); f:write("<pre class=\"prettyprint lang-lua\">function ", HookName, "("); if (a_Hook.Params == nil) then a_Hook.Params = {}; end for i, param in ipairs(a_Hook.Params) do if (i > 1) then f:write(", "); end f:write(param.Name); end f:write(")</pre>\n<hr /><h1>Parameters:</h1>\n<table><tr><th>Name</th><th>Type</th><th>Notes</th></tr>\n"); for _, param in ipairs(a_Hook.Params) do f:write("<tr><td>", param.Name, "</td><td>", LinkifyString(param.Type, HookName), "</td><td>", LinkifyString(param.Notes, HookName), "</td></tr>\n"); end f:write("</table>\n<p>" .. (a_Hook.Returns or "") .. "</p>\n\n"); f:write([[<hr /><h1>Code examples</h1><h2>Registering the callback</h2>]]); f:write("<pre class=\"prettyprint lang-lua\">\n"); f:write([[cPluginManager:AddHook(cPluginManager.]] .. a_Hook.Name .. ", My" .. a_Hook.DefaultFnName .. [[);]]); f:write("</pre>\n\n"); local Examples = a_Hook.CodeExamples or {}; for _, example in ipairs(Examples) do f:write("<h2>", (example.Title or "<i>missing Title</i>"), "</h2>\n"); f:write("<p>", (example.Desc or "<i>missing Desc</i>"), "</p>\n"); f:write("<pre class=\"prettyprint lang-lua\">", (example.Code or "<i>missing Code</i>"), "\n</pre>\n\n"); end f:write([[</td></tr></table></div><script>prettyPrint();</script></body></html>]]); f:close(); end local function WriteHooks(f, a_Hooks, a_UndocumentedHooks, a_HookNav) f:write([[ <a name="hooks"><h2>Hooks</h2></a> <p> A plugin can register to be called whenever an "interesting event" occurs. It does so by calling <a href="cPluginManager.html">cPluginManager</a>'s AddHook() function and implementing a callback function to handle the event.</p> <p> A plugin can decide whether it will let the event pass through to the rest of the plugins, or hide it from them. This is determined by the return value from the hook callback function. If the function returns false or no value, the event is propagated further. If the function returns true, the processing is stopped, no other plugin receives the notification (and possibly MCServer disables the default behavior for the event). See each hook's details to see the exact behavior.</p> <table> <tr> <th>Hook name</th> <th>Called when</th> </tr> ]]); for _, hook in ipairs(a_Hooks) do if (hook.DefaultFnName == nil) then -- The hook is not documented yet f:write(" <tr>\n <td>" .. hook.Name .. "</td>\n <td><i>(No documentation yet)</i></td>\n </tr>\n"); table.insert(a_UndocumentedHooks, hook.Name); else f:write(" <tr>\n <td><a href=\"" .. hook.DefaultFnName .. ".html\">" .. hook.Name .. "</a></td>\n <td>" .. LinkifyString(hook.CalledWhen, hook.Name) .. "</td>\n </tr>\n"); WriteHtmlHook(hook, a_HookNav); end end f:write([[ </table> <hr /> ]]); end local function ReadDescriptions(a_API) -- Returns true if the class of the specified name is to be ignored local function IsClassIgnored(a_ClsName) if (g_APIDesc.IgnoreClasses == nil) then return false; end for _, name in ipairs(g_APIDesc.IgnoreClasses) do if (a_ClsName:match(name)) then return true; end end return false; end -- Returns true if the function is to be ignored local function IsFunctionIgnored(a_ClassName, a_FnName) if (g_APIDesc.IgnoreFunctions == nil) then return false; end if (((g_APIDesc.Classes[a_ClassName] or {}).Functions or {})[a_FnName] ~= nil) then -- The function is documented, don't ignore return false; end local FnName = a_ClassName .. "." .. a_FnName; for _, name in ipairs(g_APIDesc.IgnoreFunctions) do if (FnName:match(name)) then return true; end end return false; end -- Returns true if the constant (specified by its fully qualified name) is to be ignored local function IsConstantIgnored(a_CnName) if (g_APIDesc.IgnoreConstants == nil) then return false; end; for _, name in ipairs(g_APIDesc.IgnoreConstants) do if (a_CnName:match(name)) then return true; end end return false; end -- Returns true if the member variable (specified by its fully qualified name) is to be ignored local function IsVariableIgnored(a_VarName) if (g_APIDesc.IgnoreVariables == nil) then return false; end; for _, name in ipairs(g_APIDesc.IgnoreVariables) do if (a_VarName:match(name)) then return true; end end return false; end -- Remove ignored classes from a_API: local APICopy = {}; for _, cls in ipairs(a_API) do if not(IsClassIgnored(cls.Name)) then table.insert(APICopy, cls); end end for i = 1, #a_API do a_API[i] = APICopy[i]; end; -- Process the documentation for each class: for _, cls in ipairs(a_API) do -- Initialize default values for each class: cls.ConstantGroups = {}; cls.NumConstantsInGroups = 0; cls.NumConstantsInGroupsForDescendants = 0; -- Rename special functions: for _, fn in ipairs(cls.Functions) do if (fn.Name == ".call") then fn.DocID = "constructor"; fn.Name = "() <i>(constructor)</i>"; elseif (fn.Name == ".add") then fn.DocID = "operator_plus"; fn.Name = "<i>operator +</i>"; elseif (fn.Name == ".div") then fn.DocID = "operator_div"; fn.Name = "<i>operator /</i>"; elseif (fn.Name == ".mul") then fn.DocID = "operator_mul"; fn.Name = "<i>operator *</i>"; elseif (fn.Name == ".sub") then fn.DocID = "operator_sub"; fn.Name = "<i>operator -</i>"; elseif (fn.Name == ".eq") then fn.DocID = "operator_eq"; fn.Name = "<i>operator ==</i>"; end end local APIDesc = g_APIDesc.Classes[cls.Name]; if (APIDesc ~= nil) then APIDesc.IsExported = true; cls.Desc = APIDesc.Desc; cls.AdditionalInfo = APIDesc.AdditionalInfo; -- Process inheritance: if (APIDesc.Inherits ~= nil) then for _, icls in ipairs(a_API) do if (icls.Name == APIDesc.Inherits) then table.insert(icls.Descendants, cls); cls.Inherits = icls; end end end cls.UndocumentedFunctions = {}; -- This will contain names of all the functions that are not documented cls.UndocumentedConstants = {}; -- This will contain names of all the constants that are not documented cls.UndocumentedVariables = {}; -- This will contain names of all the variables that are not documented local DoxyFunctions = {}; -- This will contain all the API functions together with their documentation local function AddFunction(a_Name, a_Params, a_Return, a_Notes) table.insert(DoxyFunctions, {Name = a_Name, Params = a_Params, Return = a_Return, Notes = a_Notes}); end if (APIDesc.Functions ~= nil) then -- Assign function descriptions: for _, func in ipairs(cls.Functions) do local FnName = func.DocID or func.Name; local FnDesc = APIDesc.Functions[FnName]; if (FnDesc == nil) then -- No description for this API function AddFunction(func.Name); if not(IsFunctionIgnored(cls.Name, FnName)) then table.insert(cls.UndocumentedFunctions, FnName); end else -- Description is available if (FnDesc[1] == nil) then -- Single function definition AddFunction(func.Name, FnDesc.Params, FnDesc.Return, FnDesc.Notes); else -- Multiple function overloads for _, desc in ipairs(FnDesc) do AddFunction(func.Name, desc.Params, desc.Return, desc.Notes); end -- for k, desc - FnDesc[] end FnDesc.IsExported = true; end end -- for j, func -- Replace functions with their described and overload-expanded versions: cls.Functions = DoxyFunctions; else -- if (APIDesc.Functions ~= nil) for _, func in ipairs(cls.Functions) do local FnName = func.DocID or func.Name; if not(IsFunctionIgnored(cls.Name, FnName)) then table.insert(cls.UndocumentedFunctions, FnName); end end end -- if (APIDesc.Functions ~= nil) if (APIDesc.Constants ~= nil) then -- Assign constant descriptions: for _, cons in ipairs(cls.Constants) do local CnDesc = APIDesc.Constants[cons.Name]; if (CnDesc == nil) then -- Not documented if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then table.insert(cls.UndocumentedConstants, cons.Name); end else cons.Notes = CnDesc.Notes; CnDesc.IsExported = true; end end -- for j, cons else -- if (APIDesc.Constants ~= nil) for _, cons in ipairs(cls.Constants) do if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then table.insert(cls.UndocumentedConstants, cons.Name); end end end -- else if (APIDesc.Constants ~= nil) -- Assign member variables' descriptions: if (APIDesc.Variables ~= nil) then for _, var in ipairs(cls.Variables) do local VarDesc = APIDesc.Variables[var.Name]; if (VarDesc == nil) then -- Not documented if not(IsVariableIgnored(cls.Name .. "." .. var.Name)) then table.insert(cls.UndocumentedVariables, var.Name); end else -- Copy all documentation: for k, v in pairs(VarDesc) do var[k] = v end end end -- for j, var else -- if (APIDesc.Variables ~= nil) for _, var in ipairs(cls.Variables) do if not(IsVariableIgnored(cls.Name .. "." .. var.Name)) then table.insert(cls.UndocumentedVariables, var.Name); end end end -- else if (APIDesc.Variables ~= nil) if (APIDesc.ConstantGroups ~= nil) then -- Create links between the constants and the groups: local NumInGroups = 0; local NumInDescendantGroups = 0; for j, group in pairs(APIDesc.ConstantGroups) do group.Name = j; group.Constants = {}; if (type(group.Include) == "string") then group.Include = { group.Include }; end local NumInGroup = 0; for _, incl in ipairs(group.Include or {}) do for _, cons in ipairs(cls.Constants) do if ((cons.Group == nil) and cons.Name:match(incl)) then cons.Group = group; table.insert(group.Constants, cons); NumInGroup = NumInGroup + 1; end end -- for cidx - cls.Constants[] end -- for idx - group.Include[] NumInGroups = NumInGroups + NumInGroup; if (group.ShowInDescendants) then NumInDescendantGroups = NumInDescendantGroups + NumInGroup; end -- Sort the constants: table.sort(group.Constants, function(c1, c2) return (c1.Name < c2.Name); end ); end -- for j - APIDesc.ConstantGroups[] cls.ConstantGroups = APIDesc.ConstantGroups; cls.NumConstantsInGroups = NumInGroups; cls.NumConstantsInGroupsForDescendants = NumInDescendantGroups; -- Remove grouped constants from the normal list: local NewConstants = {}; for _, cons in ipairs(cls.Constants) do if (cons.Group == nil) then table.insert(NewConstants, cons); end end cls.Constants = NewConstants; end -- if (ConstantGroups ~= nil) else -- if (APIDesc ~= nil) -- Class is not documented at all, add all its members to Undocumented lists: cls.UndocumentedFunctions = {}; cls.UndocumentedConstants = {}; cls.UndocumentedVariables = {}; cls.Variables = cls.Variables or {}; g_Stats.NumUndocumentedClasses = g_Stats.NumUndocumentedClasses + 1; for _, func in ipairs(cls.Functions) do local FnName = func.DocID or func.Name; if not(IsFunctionIgnored(cls.Name, FnName)) then table.insert(cls.UndocumentedFunctions, FnName); end end -- for j, func - cls.Functions[] for _, cons in ipairs(cls.Constants) do if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then table.insert(cls.UndocumentedConstants, cons.Name); end end -- for j, cons - cls.Constants[] for _, var in ipairs(cls.Variables) do if not(IsConstantIgnored(cls.Name .. "." .. var.Name)) then table.insert(cls.UndocumentedVariables, var.Name); end end -- for j, var - cls.Variables[] end -- else if (APIDesc ~= nil) -- Remove ignored functions: local NewFunctions = {}; for _, fn in ipairs(cls.Functions) do if (not(IsFunctionIgnored(cls.Name, fn.Name))) then table.insert(NewFunctions, fn); end end -- for j, fn cls.Functions = NewFunctions; -- Sort the functions (they may have been renamed): table.sort(cls.Functions, function(f1, f2) if (f1.Name == f2.Name) then -- Same name, either comparing the same function to itself, or two overloads, in which case compare the params if ((f1.Params == nil) or (f2.Params == nil)) then return 0; end return (f1.Params < f2.Params); end return (f1.Name < f2.Name); end ); -- Remove ignored constants: local NewConstants = {}; for _, cn in ipairs(cls.Constants) do if (not(IsFunctionIgnored(cls.Name, cn.Name))) then table.insert(NewConstants, cn); end end -- for j, cn cls.Constants = NewConstants; -- Sort the constants: table.sort(cls.Constants, function(c1, c2) return (c1.Name < c2.Name); end ); -- Remove ignored member variables: local NewVariables = {}; for _, var in ipairs(cls.Variables) do if (not(IsVariableIgnored(cls.Name .. "." .. var.Name))) then table.insert(NewVariables, var); end end -- for j, var cls.Variables = NewVariables; -- Sort the member variables: table.sort(cls.Variables, function(v1, v2) return (v1.Name < v2.Name); end ); end -- for i, cls -- Sort the descendants lists: for _, cls in ipairs(a_API) do table.sort(cls.Descendants, function(c1, c2) return (c1.Name < c2.Name); end ); end -- for i, cls end local function ReadHooks(a_Hooks) --[[ a_Hooks = { { Name = "HOOK_1"}, { Name = "HOOK_2"}, ... }; We want to add hook descriptions to each hook in this array --]] for _, hook in ipairs(a_Hooks) do local HookDesc = g_APIDesc.Hooks[hook.Name]; if (HookDesc ~= nil) then for key, val in pairs(HookDesc) do hook[key] = val; end end end -- for i, hook - a_Hooks[] g_Stats.NumTotalHooks = #a_Hooks; end local function WriteHtmlClass(a_ClassAPI, a_ClassMenu) local cf, err = io.open("API/" .. a_ClassAPI.Name .. ".html", "w"); if (cf == nil) then LOGINFO("Cannot write HTML API for class " .. a_ClassAPI.Name .. ": " .. err) return; end -- Writes a table containing all functions in the specified list, with an optional "inherited from" header when a_InheritedName is valid local function WriteFunctions(a_Functions, a_InheritedName) if (#a_Functions == 0) then return; end if (a_InheritedName ~= nil) then cf:write("<h2>Functions inherited from ", a_InheritedName, "</h2>\n"); end cf:write("<table>\n<tr><th>Name</th><th>Parameters</th><th>Return value</th><th>Notes</th></tr>\n"); for _, func in ipairs(a_Functions) do cf:write("<tr><td>", func.Name, "</td>\n"); cf:write("<td>", LinkifyString(func.Params or "", (a_InheritedName or a_ClassAPI.Name)), "</td>\n"); cf:write("<td>", LinkifyString(func.Return or "", (a_InheritedName or a_ClassAPI.Name)), "</td>\n"); cf:write("<td>", LinkifyString(func.Notes or "<i>(undocumented)</i>", (a_InheritedName or a_ClassAPI.Name)), "</td></tr>\n"); end cf:write("</table>\n"); end local function WriteConstantTable(a_Constants, a_Source) cf:write("<table>\n<tr><th>Name</th><th>Value</th><th>Notes</th></tr>\n"); for _, cons in ipairs(a_Constants) do cf:write("<tr><td>", cons.Name, "</td>\n"); cf:write("<td>", cons.Value, "</td>\n"); cf:write("<td>", LinkifyString(cons.Notes or "", a_Source), "</td></tr>\n"); end cf:write("</table>\n\n"); end local function WriteConstants(a_Constants, a_ConstantGroups, a_NumConstantGroups, a_InheritedName) if ((#a_Constants == 0) and (a_NumConstantGroups == 0)) then return; end local Source = a_ClassAPI.Name if (a_InheritedName ~= nil) then cf:write("<h2>Constants inherited from ", a_InheritedName, "</h2>\n"); Source = a_InheritedName; end if (#a_Constants > 0) then WriteConstantTable(a_Constants, Source); end for _, group in pairs(a_ConstantGroups) do if ((a_InheritedName == nil) or group.ShowInDescendants) then cf:write("<a name='", group.Name, "'><p>"); cf:write(LinkifyString(group.TextBefore or "", Source)); WriteConstantTable(group.Constants, a_InheritedName or a_ClassAPI.Name); cf:write(LinkifyString(group.TextAfter or "", Source), "</a></p>"); end end end local function WriteVariables(a_Variables, a_InheritedName) if (#a_Variables == 0) then return; end if (a_InheritedName ~= nil) then cf:write("<h2>Member variables inherited from ", a_InheritedName, "</h2>\n"); end cf:write("<table><tr><th>Name</th><th>Type</th><th>Notes</th></tr>\n"); for _, var in ipairs(a_Variables) do cf:write("<tr><td>", var.Name, "</td>\n"); cf:write("<td>", LinkifyString(var.Type or "<i>(undocumented)</i>", a_InheritedName or a_ClassAPI.Name), "</td>\n"); cf:write("<td>", LinkifyString(var.Notes or "", a_InheritedName or a_ClassAPI.Name), "</td>\n </tr>\n"); end cf:write("</table>\n\n"); end local function WriteDescendants(a_Descendants) if (#a_Descendants == 0) then return; end cf:write("<ul>"); for _, desc in ipairs(a_Descendants) do cf:write("<li><a href=\"", desc.Name, ".html\">", desc.Name, "</a>"); WriteDescendants(desc.Descendants); cf:write("</li>\n"); end cf:write("</ul>\n"); end local ClassName = a_ClassAPI.Name; -- Build an array of inherited classes chain: local InheritanceChain = {}; local CurrInheritance = a_ClassAPI.Inherits; while (CurrInheritance ~= nil) do table.insert(InheritanceChain, CurrInheritance); CurrInheritance = CurrInheritance.Inherits; end cf:write([[<!DOCTYPE html><html> <head> <title>MCServer API - ]], a_ClassAPI.Name, [[ Class</title> <link rel="stylesheet" type="text/css" href="main.css" /> <link rel="stylesheet" type="text/css" href="prettify.css" /> <script src="prettify.js"></script> <script src="lang-lua.js"></script> </head> <body> <div id="content"> <header> <h1>]], a_ClassAPI.Name, [[</h1> <hr /> </header> <table><tr><td style="vertical-align: top;"> Index:<br /> <a href='index.html#articles'>Articles</a><br /> <a href='index.html#classes'>Classes</a><br /> <a href='index.html#hooks'>Hooks</a><br /> <br /> Quick navigation:<br /> ]]); cf:write(a_ClassMenu); cf:write([[ </td><td style="vertical-align: top;"><h1>Contents</h1> <p><ul> ]]); local HasInheritance = ((#a_ClassAPI.Descendants > 0) or (a_ClassAPI.Inherits ~= nil)); local HasConstants = (#a_ClassAPI.Constants > 0) or (a_ClassAPI.NumConstantsInGroups > 0); local HasFunctions = (#a_ClassAPI.Functions > 0); local HasVariables = (#a_ClassAPI.Variables > 0); for _, cls in ipairs(InheritanceChain) do HasConstants = HasConstants or (#cls.Constants > 0) or (cls.NumConstantsInGroupsForDescendants > 0); HasFunctions = HasFunctions or (#cls.Functions > 0); HasVariables = HasVariables or (#cls.Variables > 0); end -- Write the table of contents: if (HasInheritance) then cf:write("<li><a href=\"#inherits\">Inheritance</a></li>\n"); end if (HasConstants) then cf:write("<li><a href=\"#constants\">Constants</a></li>\n"); end if (HasVariables) then cf:write("<li><a href=\"#variables\">Member variables</a></li>\n"); end if (HasFunctions) then cf:write("<li><a href=\"#functions\">Functions</a></li>\n"); end if (a_ClassAPI.AdditionalInfo ~= nil) then for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do cf:write("<li><a href=\"#additionalinfo_", i, "\">", (additional.Header or "<i>(No header)</i>"), "</a></li>\n"); end end cf:write("</ul></p>\n"); -- Write the class description: cf:write("<hr /><a name=\"desc\"><h1>", ClassName, " class</h1></a>\n"); if (a_ClassAPI.Desc ~= nil) then cf:write("<p>"); cf:write(LinkifyString(a_ClassAPI.Desc, ClassName)); cf:write("</p>\n\n"); end; -- Write the inheritance, if available: if (HasInheritance) then cf:write("<hr /><a name=\"inherits\"><h1>Inheritance</h1></a>\n"); if (#InheritanceChain > 0) then cf:write("<p>This class inherits from the following parent classes:<ul>\n"); for _, cls in ipairs(InheritanceChain) do cf:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n"); end cf:write("</ul></p>\n"); end if (#a_ClassAPI.Descendants > 0) then cf:write("<p>This class has the following descendants:\n"); WriteDescendants(a_ClassAPI.Descendants); cf:write("</p>\n\n"); end end -- Write the constants: if (HasConstants) then cf:write("<a name=\"constants\"><hr /><h1>Constants</h1></a>\n"); WriteConstants(a_ClassAPI.Constants, a_ClassAPI.ConstantGroups, a_ClassAPI.NumConstantsInGroups, nil); g_Stats.NumTotalConstants = g_Stats.NumTotalConstants + #a_ClassAPI.Constants + (a_ClassAPI.NumConstantsInGroups or 0); for _, cls in ipairs(InheritanceChain) do WriteConstants(cls.Constants, cls.ConstantGroups, cls.NumConstantsInGroupsForDescendants, cls.Name); end; end; -- Write the member variables: if (HasVariables) then cf:write("<a name=\"variables\"><hr /><h1>Member variables</h1></a>\n"); WriteVariables(a_ClassAPI.Variables, nil); g_Stats.NumTotalVariables = g_Stats.NumTotalVariables + #a_ClassAPI.Variables; for _, cls in ipairs(InheritanceChain) do WriteVariables(cls.Variables, cls.Name); end; end -- Write the functions, including the inherited ones: if (HasFunctions) then cf:write("<a name=\"functions\"><hr /><h1>Functions</h1></a>\n"); WriteFunctions(a_ClassAPI.Functions, nil); g_Stats.NumTotalFunctions = g_Stats.NumTotalFunctions + #a_ClassAPI.Functions; for _, cls in ipairs(InheritanceChain) do WriteFunctions(cls.Functions, cls.Name); end end -- Write the additional infos: if (a_ClassAPI.AdditionalInfo ~= nil) then for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do cf:write("<a name=\"additionalinfo_", i, "\"><h1>", additional.Header, "</h1></a>\n"); cf:write(LinkifyString(additional.Contents, ClassName)); end end cf:write([[</td></tr></table></div><script>prettyPrint();</script></body></html>]]); cf:close(); end local function WriteClasses(f, a_API, a_ClassMenu) f:write([[ <a name="classes"><h2>Class index</h2></a> <p>The following classes are available in the MCServer Lua scripting language: <ul> ]]); for _, cls in ipairs(a_API) do f:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n"); WriteHtmlClass(cls, a_ClassMenu); end f:write([[ </ul></p> <hr /> ]]); end --- Writes a list of undocumented objects into a file local function ListUndocumentedObjects(API, UndocumentedHooks) f = io.open("API/_undocumented.lua", "w"); if (f ~= nil) then f:write("\n-- This is the list of undocumented API objects, automatically generated by APIDump\n\n"); f:write("g_APIDesc =\n{\n\tClasses =\n\t{\n"); for _, cls in ipairs(API) do local HasFunctions = ((cls.UndocumentedFunctions ~= nil) and (#cls.UndocumentedFunctions > 0)); local HasConstants = ((cls.UndocumentedConstants ~= nil) and (#cls.UndocumentedConstants > 0)); local HasVariables = ((cls.UndocumentedVariables ~= nil) and (#cls.UndocumentedVariables > 0)); g_Stats.NumUndocumentedFunctions = g_Stats.NumUndocumentedFunctions + #cls.UndocumentedFunctions; g_Stats.NumUndocumentedConstants = g_Stats.NumUndocumentedConstants + #cls.UndocumentedConstants; g_Stats.NumUndocumentedVariables = g_Stats.NumUndocumentedVariables + #cls.UndocumentedVariables; if (HasFunctions or HasConstants or HasVariables) then f:write("\t\t" .. cls.Name .. " =\n\t\t{\n"); if ((cls.Desc == nil) or (cls.Desc == "")) then f:write("\t\t\tDesc = \"\"\n"); end end if (HasFunctions) then f:write("\t\t\tFunctions =\n\t\t\t{\n"); table.sort(cls.UndocumentedFunctions); for _, fn in ipairs(cls.UndocumentedFunctions) do f:write("\t\t\t\t" .. fn .. " = { Params = \"\", Return = \"\", Notes = \"\" },\n"); end -- for j, fn - cls.UndocumentedFunctions[] f:write("\t\t\t},\n\n"); end if (HasConstants) then f:write("\t\t\tConstants =\n\t\t\t{\n"); table.sort(cls.UndocumentedConstants); for _, cn in ipairs(cls.UndocumentedConstants) do f:write("\t\t\t\t" .. cn .. " = { Notes = \"\" },\n"); end -- for j, fn - cls.UndocumentedConstants[] f:write("\t\t\t},\n\n"); end if (HasVariables) then f:write("\t\t\tVariables =\n\t\t\t{\n"); table.sort(cls.UndocumentedVariables); for _, vn in ipairs(cls.UndocumentedVariables) do f:write("\t\t\t\t" .. vn .. " = { Type = \"\", Notes = \"\" },\n"); end -- for j, fn - cls.UndocumentedVariables[] f:write("\t\t\t},\n\n"); end if (HasFunctions or HasConstants or HasVariables) then f:write("\t\t},\n\n"); end end -- for i, cls - API[] f:write("\t},\n"); if (#UndocumentedHooks > 0) then f:write("\n\tHooks =\n\t{\n"); for i, hook in ipairs(UndocumentedHooks) do if (i > 1) then f:write("\n"); end f:write("\t\t" .. hook .. " =\n\t\t{\n"); f:write("\t\t\tCalledWhen = \"\",\n"); f:write("\t\t\tDefaultFnName = \"On\", -- also used as pagename\n"); f:write("\t\t\tDesc = [[\n\t\t\t\t\n\t\t\t]],\n"); f:write("\t\t\tParams =\n\t\t\t{\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n"); f:write("\t\t\t},\n"); f:write("\t\t\tReturns = [[\n\t\t\t\t\n\t\t\t]],\n"); f:write("\t\t}, -- " .. hook .. "\n"); end f:write("\t},\n"); end f:write("}\n\n\n\n"); f:close(); end g_Stats.NumUndocumentedHooks = #UndocumentedHooks; end --- Lists the API objects that are documented but not available in the API: local function ListUnexportedObjects() f = io.open("API/_unexported-documented.txt", "w"); if (f ~= nil) then for clsname, cls in pairs(g_APIDesc.Classes) do if not(cls.IsExported) then -- The whole class is not exported f:write("class\t" .. clsname .. "\n"); else if (cls.Functions ~= nil) then for fnname, fnapi in pairs(cls.Functions) do if not(fnapi.IsExported) then f:write("func\t" .. clsname .. "." .. fnname .. "\n"); end end -- for j, fn - cls.Functions[] end if (cls.Constants ~= nil) then for cnname, cnapi in pairs(cls.Constants) do if not(cnapi.IsExported) then f:write("const\t" .. clsname .. "." .. cnname .. "\n"); end end -- for j, fn - cls.Functions[] end end end -- for i, cls - g_APIDesc.Classes[] f:close(); end end local function ListMissingPages() local MissingPages = {}; local NumLinks = 0; for PageName, Referrers in pairs(g_TrackedPages) do NumLinks = NumLinks + 1; if not(cFile:Exists("API/" .. PageName .. ".html")) then table.insert(MissingPages, {Name = PageName, Refs = Referrers} ); end end; g_Stats.NumTrackedLinks = NumLinks; g_TrackedPages = {}; if (#MissingPages == 0) then -- No missing pages, congratulations! return; end -- Sort the pages by name: table.sort(MissingPages, function (Page1, Page2) return (Page1.Name < Page2.Name); end ); -- Output the pages: local f, err = io.open("API/_missingPages.txt", "w"); if (f == nil) then LOGWARNING("Cannot open _missingPages.txt for writing: '" .. err .. "'. There are " .. #MissingPages .. " pages missing."); return; end for _, pg in ipairs(MissingPages) do f:write(pg.Name .. ":\n"); -- Sort and output the referrers: table.sort(pg.Refs); f:write("\t" .. table.concat(pg.Refs, "\n\t")); f:write("\n\n"); end f:close(); g_Stats.NumInvalidLinks = #MissingPages; end --- Writes the documentation statistics (in g_Stats) into the given HTML file local function WriteStats(f) local function ExportMeter(a_Percent) local Color; if (a_Percent > 99) then Color = "green"; elseif (a_Percent > 50) then Color = "orange"; else Color = "red"; end local meter = { "\n", "<div style=\"background-color: black; padding: 1px; width: 100px\">\n", "<div style=\"background-color: ", Color, "; width: ", a_Percent, "%; height: 16px\"></div></div>\n</td><td>", string.format("%.2f", a_Percent), " %", }; return table.concat(meter, ""); end f:write([[ <hr /><a name="docstats"><h2>Documentation statistics</h2></a> <table><tr><th>Object</th><th>Total</th><th>Documented</th><th>Undocumented</th><th colspan="2">Documented %</th></tr> ]]); f:write("<tr><td>Classes</td><td>", g_Stats.NumTotalClasses); f:write("</td><td>", g_Stats.NumTotalClasses - g_Stats.NumUndocumentedClasses); f:write("</td><td>", g_Stats.NumUndocumentedClasses); f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalClasses - g_Stats.NumUndocumentedClasses) / g_Stats.NumTotalClasses)); f:write("</td></tr>\n"); f:write("<tr><td>Functions</td><td>", g_Stats.NumTotalFunctions); f:write("</td><td>", g_Stats.NumTotalFunctions - g_Stats.NumUndocumentedFunctions); f:write("</td><td>", g_Stats.NumUndocumentedFunctions); f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalFunctions - g_Stats.NumUndocumentedFunctions) / g_Stats.NumTotalFunctions)); f:write("</td></tr>\n"); f:write("<tr><td>Member variables</td><td>", g_Stats.NumTotalVariables); f:write("</td><td>", g_Stats.NumTotalVariables - g_Stats.NumUndocumentedVariables); f:write("</td><td>", g_Stats.NumUndocumentedVariables); f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalVariables - g_Stats.NumUndocumentedVariables) / g_Stats.NumTotalVariables)); f:write("</td></tr>\n"); f:write("<tr><td>Constants</td><td>", g_Stats.NumTotalConstants); f:write("</td><td>", g_Stats.NumTotalConstants - g_Stats.NumUndocumentedConstants); f:write("</td><td>", g_Stats.NumUndocumentedConstants); f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalConstants - g_Stats.NumUndocumentedConstants) / g_Stats.NumTotalConstants)); f:write("</td></tr>\n"); f:write("<tr><td>Hooks</td><td>", g_Stats.NumTotalHooks); f:write("</td><td>", g_Stats.NumTotalHooks - g_Stats.NumUndocumentedHooks); f:write("</td><td>", g_Stats.NumUndocumentedHooks); f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalHooks - g_Stats.NumUndocumentedHooks) / g_Stats.NumTotalHooks)); f:write("</td></tr>\n"); f:write([[ </table> <p>There are ]], g_Stats.NumTrackedLinks, " internal links, ", g_Stats.NumInvalidLinks, " of them are invalid.</p>" ); end local function DumpAPIHtml(a_API) LOG("Dumping all available functions and constants to API subfolder..."); -- Create the output folder if not(cFile:IsFolder("API")) then cFile:CreateFolder("API"); end LOG("Copying static files.."); cFile:CreateFolder("API/Static"); local localFolder = g_Plugin:GetLocalFolder(); for _, fnam in ipairs(cFile:GetFolderContents(localFolder .. "/Static")) do cFile:Delete("API/Static/" .. fnam); cFile:Copy(localFolder .. "/Static/" .. fnam, "API/Static/" .. fnam); end -- Extract hook constants: local Hooks = {}; local UndocumentedHooks = {}; for name, obj in pairs(cPluginManager) do if ( (type(obj) == "number") and name:match("HOOK_.*") and (name ~= "HOOK_MAX") and (name ~= "HOOK_NUM_HOOKS") ) then table.insert(Hooks, { Name = name }); end end table.sort(Hooks, function(Hook1, Hook2) return (Hook1.Name < Hook2.Name); end ); ReadHooks(Hooks); -- Create a "class index" file, write each class as a link to that file, -- then dump class contents into class-specific file LOG("Writing HTML files..."); local f, err = io.open("API/index.html", "w"); if (f == nil) then LOGINFO("Cannot output HTML API: " .. err); return; end -- Create a class navigation menu that will be inserted into each class file for faster navigation (#403) local ClassMenuTab = {}; for _, cls in ipairs(a_API) do table.insert(ClassMenuTab, "<a href='"); table.insert(ClassMenuTab, cls.Name); table.insert(ClassMenuTab, ".html'>"); table.insert(ClassMenuTab, cls.Name); table.insert(ClassMenuTab, "</a><br />"); end local ClassMenu = table.concat(ClassMenuTab, ""); -- Create a hook navigation menu that will be inserted into each hook file for faster navigation(#403) local HookNavTab = {}; for _, hook in ipairs(Hooks) do table.insert(HookNavTab, "<a href='"); table.insert(HookNavTab, hook.DefaultFnName); table.insert(HookNavTab, ".html'>"); table.insert(HookNavTab, (hook.Name:gsub("^HOOK_", ""))); -- remove the "HOOK_" part of the name table.insert(HookNavTab, "</a><br />"); end local HookNav = table.concat(HookNavTab, ""); -- Write the HTML file: f:write([[<!DOCTYPE html> <html> <head> <title>MCServer API - Index</title> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <body> <div id="content"> <header> <h1>MCServer API - Index</h1> <hr /> </header> <p>The API reference is divided into the following sections:</p> <ul> <li><a href="#articles">Articles</a></li> <li><a href="#classes">Class index</a></li> <li><a href="#hooks">Hooks</a></li> <li><a href="#docstats">Documentation statistics</a></li> </ul> <hr /> ]]); WriteArticles(f); WriteClasses(f, a_API, ClassMenu); WriteHooks(f, Hooks, UndocumentedHooks, HookNav); -- Copy the static files to the output folder: local StaticFiles = { "main.css", "prettify.js", "prettify.css", "lang-lua.js", }; for _, fnam in ipairs(StaticFiles) do cFile:Delete("API/" .. fnam); cFile:Copy(g_Plugin:GetLocalFolder() .. "/" .. fnam, "API/" .. fnam); end -- List the documentation problems: LOG("Listing leftovers..."); ListUndocumentedObjects(a_API, UndocumentedHooks); ListUnexportedObjects(); ListMissingPages(); WriteStats(f); f:write([[ </ul> </div> </body> </html>]]); f:close(); LOG("API subfolder written"); end --- Returns the string with extra tabs and CR/LFs removed local function CleanUpDescription(a_Desc) -- Get rid of indent and newlines, normalize whitespace: local res = a_Desc:gsub("[\n\t]", "") res = a_Desc:gsub("%s%s+", " ") -- Replace paragraph marks with newlines: res = res:gsub("<p>", "\n") res = res:gsub("</p>", "") -- Replace list items with dashes: res = res:gsub("</?ul>", "") res = res:gsub("<li>", "\n - ") res = res:gsub("</li>", "") return res end --- Writes a list of methods into the specified file in ZBS format local function WriteZBSMethods(f, a_Methods) for _, func in ipairs(a_Methods or {}) do f:write("\t\t\t[\"", func.Name, "\"] =\n") f:write("\t\t\t{\n") f:write("\t\t\t\ttype = \"method\",\n") if ((func.Notes ~= nil) and (func.Notes ~= "")) then f:write("\t\t\t\tdescription = [[", CleanUpDescription(func.Notes or ""), " ]],\n") end f:write("\t\t\t},\n") end end --- Writes a list of constants into the specified file in ZBS format local function WriteZBSConstants(f, a_Constants) for _, cons in ipairs(a_Constants or {}) do f:write("\t\t\t[\"", cons.Name, "\"] =\n") f:write("\t\t\t{\n") f:write("\t\t\t\ttype = \"value\",\n") if ((cons.Desc ~= nil) and (cons.Desc ~= "")) then f:write("\t\t\t\tdescription = [[", CleanUpDescription(cons.Desc or ""), " ]],\n") end f:write("\t\t\t},\n") end end --- Writes one MCS class definition into the specified file in ZBS format local function WriteZBSClass(f, a_Class) assert(type(a_Class) == "table") -- Write class header: f:write("\t", a_Class.Name, " =\n\t{\n") f:write("\t\ttype = \"class\",\n") f:write("\t\tdescription = [[", CleanUpDescription(a_Class.Desc or ""), " ]],\n") f:write("\t\tchilds =\n") f:write("\t\t{\n") -- Export methods and constants: WriteZBSMethods(f, a_Class.Functions) WriteZBSConstants(f, a_Class.Constants) -- Finish the class definition: f:write("\t\t},\n") f:write("\t},\n\n") end --- Dumps the entire API table into a file in the ZBS format local function DumpAPIZBS(a_API) LOG("Dumping ZBS API description...") local f, err = io.open("mcserver_api.lua", "w") if (f == nil) then LOG("Cannot open mcserver_lua.lua for writing, ZBS API will not be dumped. " .. err) return end -- Write the file header: f:write("-- This is a MCServer API file automatically generated by the APIDump plugin\n") f:write("-- Note that any manual changes will be overwritten by the next dump\n\n") f:write("return {\n") -- Export each class except Globals, store those aside: local Globals for _, cls in ipairs(a_API) do if (cls.Name ~= "Globals") then WriteZBSClass(f, cls) else Globals = cls end end -- Export the globals: if (Globals) then WriteZBSMethods(f, Globals.Functions) WriteZBSConstants(f, Globals.Constants) end -- Finish the file: f:write("}\n") f:close() LOG("ZBS API dumped...") end --- Returns true if a_Descendant is declared to be a (possibly indirect) descendant of a_Base local function IsDeclaredDescendant(a_DescendantName, a_BaseName, a_API) -- Check params: assert(type(a_DescendantName) == "string") assert(type(a_BaseName) == "string") assert(type(a_API) == "table") if not(a_API[a_BaseName]) then return false end assert(type(a_API[a_BaseName]) == "table", "Not a class name: " .. a_BaseName) assert(type(a_API[a_BaseName].Descendants) == "table") -- Check direct inheritance: for _, desc in ipairs(a_API[a_BaseName].Descendants) do if (desc.Name == a_DescendantName) then return true end end -- for desc - a_BaseName's descendants -- Check indirect inheritance: for _, desc in ipairs(a_API[a_BaseName].Descendants) do if (IsDeclaredDescendant(a_DescendantName, desc.Name, a_API)) then return true end end -- for desc - a_BaseName's descendants return false end --- Checks the specified class' inheritance -- Reports any problems as new items in the a_Report table local function CheckClassInheritance(a_Class, a_API, a_Report) -- Check params: assert(type(a_Class) == "table") assert(type(a_API) == "table") assert(type(a_Report) == "table") -- Check that the declared descendants are really descendants: local registry = debug.getregistry() for _, desc in ipairs(a_Class.Descendants or {}) do local isParent = false local parents = registry["tolua_super"][_G[desc.Name]] if not(parents[a_Class.Name]) then table.insert(a_Report, desc.Name .. " is not a descendant of " .. a_Class.Name) end end -- for desc - a_Class.Descendants[] -- Check that all inheritance is listed for the class: local parents = registry["tolua_super"][_G[a_Class.Name]] -- map of "classname" -> true for each class that a_Class inherits for clsName, isParent in pairs(parents or {}) do if ((clsName ~= "") and not(clsName:match("const .*"))) then if not(IsDeclaredDescendant(a_Class.Name, clsName, a_API)) then table.insert(a_Report, a_Class.Name .. " inherits from " .. clsName .. " but this isn't documented") end end end end --- Checks each class's declared inheritance versus the actual inheritance local function CheckAPIDescendants(a_API) -- Check each class: local report = {} for _, cls in ipairs(a_API) do if (cls.Name ~= "Globals") then CheckClassInheritance(cls, a_API, report) end end -- If there's anything to report, output it to a file: if (report[1] ~= nil) then LOG("There are inheritance errors in the API description:") for _, msg in ipairs(report) do LOG(" " .. msg) end local f, err = io.open("API/_inheritance_errors.txt", "w") if (f == nil) then LOG("Cannot report inheritance problems to a file: " .. tostring(err)) return end f:write(table.concat(report, "\n")) f:close() end end local function DumpApi() LOG("Dumping the API...") -- Load the API descriptions from the Classes and Hooks subfolders: -- This needs to be done each time the command is invoked because the export modifies the tables' contents dofile(g_PluginFolder .. "/APIDesc.lua") if (g_APIDesc.Classes == nil) then g_APIDesc.Classes = {}; end if (g_APIDesc.Hooks == nil) then g_APIDesc.Hooks = {}; end LoadAPIFiles("/Classes/", g_APIDesc.Classes); LoadAPIFiles("/Hooks/", g_APIDesc.Hooks); -- Reset the stats: g_TrackedPages = {}; -- List of tracked pages, to be checked later whether they exist. Each item is an array of referring pagenames. g_Stats = -- Statistics about the documentation { NumTotalClasses = 0, NumUndocumentedClasses = 0, NumTotalFunctions = 0, NumUndocumentedFunctions = 0, NumTotalConstants = 0, NumUndocumentedConstants = 0, NumTotalVariables = 0, NumUndocumentedVariables = 0, NumTotalHooks = 0, NumUndocumentedHooks = 0, NumTrackedLinks = 0, NumInvalidLinks = 0, } -- Create the API tables: local API, Globals = CreateAPITables(); -- Sort the classes by name: table.sort(API, function (c1, c2) return (string.lower(c1.Name) < string.lower(c2.Name)); end ); g_Stats.NumTotalClasses = #API; -- Add Globals into the API: Globals.Name = "Globals"; table.insert(API, Globals); -- Read in the descriptions: LOG("Reading descriptions..."); ReadDescriptions(API); -- Check that the API lists the inheritance properly, report any problems to a file: CheckAPIDescendants(API) -- Dump all available API objects in HTML format into a subfolder: DumpAPIHtml(API); -- Dump all available API objects in format used by ZeroBraneStudio API descriptions: DumpAPIZBS(API) LOG("APIDump finished"); return true end local function HandleWebAdminDump(a_Request) if (a_Request.PostParams["Dump"] ~= nil) then DumpApi() end return [[ <p>Pressing the button will generate the API dump on the server. Note that this can take some time.</p> <form method="POST"><input type="submit" name="Dump" value="Dump the API"/></form> ]] end local function HandleCmdApi(a_Split) DumpApi() return true end function Initialize(Plugin) g_Plugin = Plugin; g_PluginFolder = Plugin:GetLocalFolder(); LOG("Initialising " .. Plugin:GetName() .. " v." .. Plugin:GetVersion()) -- Bind a console command to dump the API: cPluginManager:BindConsoleCommand("api", HandleCmdApi, "Dumps the Lua API docs into the API/ subfolder") -- Add a WebAdmin tab that has a Dump button g_Plugin:AddWebTab("APIDump", HandleWebAdminDump) return true end
Java
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/glue/Glue_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/glue/model/TaskStatusType.h> #include <aws/glue/model/TaskRunProperties.h> #include <aws/core/utils/DateTime.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Glue { namespace Model { class AWS_GLUE_API GetMLTaskRunResult { public: GetMLTaskRunResult(); GetMLTaskRunResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); GetMLTaskRunResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The unique identifier of the task run.</p> */ inline const Aws::String& GetTransformId() const{ return m_transformId; } /** * <p>The unique identifier of the task run.</p> */ inline void SetTransformId(const Aws::String& value) { m_transformId = value; } /** * <p>The unique identifier of the task run.</p> */ inline void SetTransformId(Aws::String&& value) { m_transformId = std::move(value); } /** * <p>The unique identifier of the task run.</p> */ inline void SetTransformId(const char* value) { m_transformId.assign(value); } /** * <p>The unique identifier of the task run.</p> */ inline GetMLTaskRunResult& WithTransformId(const Aws::String& value) { SetTransformId(value); return *this;} /** * <p>The unique identifier of the task run.</p> */ inline GetMLTaskRunResult& WithTransformId(Aws::String&& value) { SetTransformId(std::move(value)); return *this;} /** * <p>The unique identifier of the task run.</p> */ inline GetMLTaskRunResult& WithTransformId(const char* value) { SetTransformId(value); return *this;} /** * <p>The unique run identifier associated with this run.</p> */ inline const Aws::String& GetTaskRunId() const{ return m_taskRunId; } /** * <p>The unique run identifier associated with this run.</p> */ inline void SetTaskRunId(const Aws::String& value) { m_taskRunId = value; } /** * <p>The unique run identifier associated with this run.</p> */ inline void SetTaskRunId(Aws::String&& value) { m_taskRunId = std::move(value); } /** * <p>The unique run identifier associated with this run.</p> */ inline void SetTaskRunId(const char* value) { m_taskRunId.assign(value); } /** * <p>The unique run identifier associated with this run.</p> */ inline GetMLTaskRunResult& WithTaskRunId(const Aws::String& value) { SetTaskRunId(value); return *this;} /** * <p>The unique run identifier associated with this run.</p> */ inline GetMLTaskRunResult& WithTaskRunId(Aws::String&& value) { SetTaskRunId(std::move(value)); return *this;} /** * <p>The unique run identifier associated with this run.</p> */ inline GetMLTaskRunResult& WithTaskRunId(const char* value) { SetTaskRunId(value); return *this;} /** * <p>The status for this task run.</p> */ inline const TaskStatusType& GetStatus() const{ return m_status; } /** * <p>The status for this task run.</p> */ inline void SetStatus(const TaskStatusType& value) { m_status = value; } /** * <p>The status for this task run.</p> */ inline void SetStatus(TaskStatusType&& value) { m_status = std::move(value); } /** * <p>The status for this task run.</p> */ inline GetMLTaskRunResult& WithStatus(const TaskStatusType& value) { SetStatus(value); return *this;} /** * <p>The status for this task run.</p> */ inline GetMLTaskRunResult& WithStatus(TaskStatusType&& value) { SetStatus(std::move(value)); return *this;} /** * <p>The names of the log groups that are associated with the task run.</p> */ inline const Aws::String& GetLogGroupName() const{ return m_logGroupName; } /** * <p>The names of the log groups that are associated with the task run.</p> */ inline void SetLogGroupName(const Aws::String& value) { m_logGroupName = value; } /** * <p>The names of the log groups that are associated with the task run.</p> */ inline void SetLogGroupName(Aws::String&& value) { m_logGroupName = std::move(value); } /** * <p>The names of the log groups that are associated with the task run.</p> */ inline void SetLogGroupName(const char* value) { m_logGroupName.assign(value); } /** * <p>The names of the log groups that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithLogGroupName(const Aws::String& value) { SetLogGroupName(value); return *this;} /** * <p>The names of the log groups that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithLogGroupName(Aws::String&& value) { SetLogGroupName(std::move(value)); return *this;} /** * <p>The names of the log groups that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithLogGroupName(const char* value) { SetLogGroupName(value); return *this;} /** * <p>The list of properties that are associated with the task run.</p> */ inline const TaskRunProperties& GetProperties() const{ return m_properties; } /** * <p>The list of properties that are associated with the task run.</p> */ inline void SetProperties(const TaskRunProperties& value) { m_properties = value; } /** * <p>The list of properties that are associated with the task run.</p> */ inline void SetProperties(TaskRunProperties&& value) { m_properties = std::move(value); } /** * <p>The list of properties that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithProperties(const TaskRunProperties& value) { SetProperties(value); return *this;} /** * <p>The list of properties that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithProperties(TaskRunProperties&& value) { SetProperties(std::move(value)); return *this;} /** * <p>The error strings that are associated with the task run.</p> */ inline const Aws::String& GetErrorString() const{ return m_errorString; } /** * <p>The error strings that are associated with the task run.</p> */ inline void SetErrorString(const Aws::String& value) { m_errorString = value; } /** * <p>The error strings that are associated with the task run.</p> */ inline void SetErrorString(Aws::String&& value) { m_errorString = std::move(value); } /** * <p>The error strings that are associated with the task run.</p> */ inline void SetErrorString(const char* value) { m_errorString.assign(value); } /** * <p>The error strings that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithErrorString(const Aws::String& value) { SetErrorString(value); return *this;} /** * <p>The error strings that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithErrorString(Aws::String&& value) { SetErrorString(std::move(value)); return *this;} /** * <p>The error strings that are associated with the task run.</p> */ inline GetMLTaskRunResult& WithErrorString(const char* value) { SetErrorString(value); return *this;} /** * <p>The date and time when this task run started.</p> */ inline const Aws::Utils::DateTime& GetStartedOn() const{ return m_startedOn; } /** * <p>The date and time when this task run started.</p> */ inline void SetStartedOn(const Aws::Utils::DateTime& value) { m_startedOn = value; } /** * <p>The date and time when this task run started.</p> */ inline void SetStartedOn(Aws::Utils::DateTime&& value) { m_startedOn = std::move(value); } /** * <p>The date and time when this task run started.</p> */ inline GetMLTaskRunResult& WithStartedOn(const Aws::Utils::DateTime& value) { SetStartedOn(value); return *this;} /** * <p>The date and time when this task run started.</p> */ inline GetMLTaskRunResult& WithStartedOn(Aws::Utils::DateTime&& value) { SetStartedOn(std::move(value)); return *this;} /** * <p>The date and time when this task run was last modified.</p> */ inline const Aws::Utils::DateTime& GetLastModifiedOn() const{ return m_lastModifiedOn; } /** * <p>The date and time when this task run was last modified.</p> */ inline void SetLastModifiedOn(const Aws::Utils::DateTime& value) { m_lastModifiedOn = value; } /** * <p>The date and time when this task run was last modified.</p> */ inline void SetLastModifiedOn(Aws::Utils::DateTime&& value) { m_lastModifiedOn = std::move(value); } /** * <p>The date and time when this task run was last modified.</p> */ inline GetMLTaskRunResult& WithLastModifiedOn(const Aws::Utils::DateTime& value) { SetLastModifiedOn(value); return *this;} /** * <p>The date and time when this task run was last modified.</p> */ inline GetMLTaskRunResult& WithLastModifiedOn(Aws::Utils::DateTime&& value) { SetLastModifiedOn(std::move(value)); return *this;} /** * <p>The date and time when this task run was completed.</p> */ inline const Aws::Utils::DateTime& GetCompletedOn() const{ return m_completedOn; } /** * <p>The date and time when this task run was completed.</p> */ inline void SetCompletedOn(const Aws::Utils::DateTime& value) { m_completedOn = value; } /** * <p>The date and time when this task run was completed.</p> */ inline void SetCompletedOn(Aws::Utils::DateTime&& value) { m_completedOn = std::move(value); } /** * <p>The date and time when this task run was completed.</p> */ inline GetMLTaskRunResult& WithCompletedOn(const Aws::Utils::DateTime& value) { SetCompletedOn(value); return *this;} /** * <p>The date and time when this task run was completed.</p> */ inline GetMLTaskRunResult& WithCompletedOn(Aws::Utils::DateTime&& value) { SetCompletedOn(std::move(value)); return *this;} /** * <p>The amount of time (in seconds) that the task run consumed resources.</p> */ inline int GetExecutionTime() const{ return m_executionTime; } /** * <p>The amount of time (in seconds) that the task run consumed resources.</p> */ inline void SetExecutionTime(int value) { m_executionTime = value; } /** * <p>The amount of time (in seconds) that the task run consumed resources.</p> */ inline GetMLTaskRunResult& WithExecutionTime(int value) { SetExecutionTime(value); return *this;} private: Aws::String m_transformId; Aws::String m_taskRunId; TaskStatusType m_status; Aws::String m_logGroupName; TaskRunProperties m_properties; Aws::String m_errorString; Aws::Utils::DateTime m_startedOn; Aws::Utils::DateTime m_lastModifiedOn; Aws::Utils::DateTime m_completedOn; int m_executionTime; }; } // namespace Model } // namespace Glue } // namespace Aws
Java
using MatrixApi.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Data.Json; namespace MatrixPhone.DataModel { public static class UserDataSource { public static User user = new User(); public static User GetUser() { return user; } public static async void Login(string Email, string Password) { user.Email = Email; user.Password = Password; var httpClient = new appHttpClient(); var response = await httpClient.GetAsync("Users"); try { response.EnsureSuccessStatusCode(); // Throw on error code. } catch { user = new User(); } var result = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<User>(result); } public static string Auth() { var authText = string.Format("{0}:{1}", user.Email, user.Password); return Convert.ToBase64String(Encoding.UTF8.GetBytes(authText)); } } }
Java
// svgmap.js 0.2.0 // // Copyright (c) 2014 jalal @ gnomedia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // var SvgMap = function (opts) { /*global Snap:false, console:false */ 'use strict'; console.log("SvgMap initializing"); var defaults = { svgid: '', mapurl: '', mapid: '', coordsurl: '', hoverFill: '#fff', strokeColor: '#000', resultid: 'results' }; var svgid = opts.svgid || defaults.svgid, mapurl = opts.mapurl || defaults.mapurl, mapid = opts.mapid || defaults.mapid, coordsurl = opts.coordsurl || defaults.coordsurl, strokeColor = opts.strokeColor || defaults.strokeColor, hoverFill = opts.hoverFill || defaults.hoverFill, resultid = opts.resultid || defaults.resultid; var i, w, h, areas, pre; var s = new Snap(svgid); var group = s.group(); Snap.load(mapurl, function (f) { i = f.select('image'); h = i.attr('height'); w = i.attr('width'); group.append(f); s.attr({ viewBox: [0, 0, w, h] }); var newmap = document.getElementById('newmap'); if (newmap) { newmap.style.height = h + 'px'; newmap.style.maxWidth = w + 'px'; } }); var shadow = new Snap(svgid); areas = document.getElementsByTagName('area'); var area; for (var j = areas.length - 1; j >= 0; j--) { area = areas[j]; // console.log("Coord: " + area.coords); var coords = area.coords.split(','); var path = 'M '; if (coords.length) { for (var k = 0; k < coords.length; k += 2) { if (!k) {pre = ''; } else {pre = ' L '; } path += pre + coords[k] + ',' + coords[k + 1]; } } var p = new Snap(); var el = p.path(path); el.attr({ id: area.title, fill: 'none', stroke: strokeColor, link: area.href, d: path, title: area.title}); el.hover(function () { this.attr('fill', hoverFill); }, function () { this.attr('fill', 'transparent'); }); el.click(function () { // console.log('click: ' + this.attr('id')); hideAll(); show('Clicked: ' + this.attr('id')); }); el.touchstart(function () { console.log('touch: ' + this.attr('id')); this.attr('fill', hoverFill); hideAll(); show('Touched: ' + this.attr('id')); }); el.touchend(function () { this.attr('fill', 'transparent'); }); shadow.append(el); } function hideAll() { var el = document.getElementById(resultid); if (el) {el.style.display = "none"; } // $(resultid).hide(); } function show(txt) { var el = document.getElementById(resultid); if (el) { el.style.display = ""; if (el.firstChild) { el.removeChild(el.firstChild); } var t = document.createTextNode(txt); el.appendChild(t); } } };
Java
package com.yezi.text.widget; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SwitchCompat; import android.view.View; import android.widget.CompoundButton; import com.yezi.text.activity.AdapterSampleActivity; import com.yezi.text.activity.AnimatorSampleActivity; import com.yezi.text.R; public class MyRecycleview extends AppCompatActivity { private boolean enabledGrid = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mycycleview); findViewById(R.id.btn_animator_sample).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MyRecycleview.this, AnimatorSampleActivity.class); i.putExtra("GRID", enabledGrid); startActivity(i); } }); findViewById(R.id.btn_adapter_sample).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MyRecycleview.this, AdapterSampleActivity.class); i.putExtra("GRID", enabledGrid); startActivity(i); } }); ((SwitchCompat) findViewById(R.id.grid)).setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { enabledGrid = isChecked; } }); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.datalint.open.shared.xml; import java.util.ArrayList; import java.util.List; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Text; import com.datalint.open.shared.xml.impl.XMLParserImpl; /** * This class represents the client interface to XML parsing. */ public class XMLParser { private static final XMLParserImpl impl = XMLParserImpl.getInstance(); /** * This method creates a new document, to be manipulated by the DOM API. * * @return the newly created document */ public static Document createDocument() { return impl.createDocument(); } /** * This method parses a new document from the supplied string, throwing a * <code>DOMParseException</code> if the parse fails. * * @param contents the String to be parsed into a <code>Document</code> * @return the newly created <code>Document</code> */ public static Document parse(String contents) { return impl.parse(contents); } // Update on 2020-05-10, does not work with XPath. public static Document parseReadOnly(String contents) { return impl.parseReadOnly(contents); } /** * This method removes all <code>Text</code> nodes which are made up of only * white space. * * @param n the node which is to have all of its whitespace descendents removed. */ public static void removeWhitespace(Node n) { removeWhitespaceInner(n, null); } /** * This method determines whether the browser supports {@link CDATASection} as * distinct entities from <code>Text</code> nodes. * * @return true if the browser supports {@link CDATASection}, otherwise * <code>false</code>. */ public static boolean supportsCDATASection() { return impl.supportsCDATASection(); } /* * The inner recursive method for removeWhitespace */ private static void removeWhitespaceInner(Node n, Node parent) { // This n is removed from the parent if n is a whitespace node if (parent != null && n instanceof Text && (!(n instanceof CDATASection))) { Text t = (Text) n; if (t.getData().matches("[ \t\n]*")) { parent.removeChild(t); } } if (n.hasChildNodes()) { int length = n.getChildNodes().getLength(); List<Node> toBeProcessed = new ArrayList<Node>(); // We collect all the nodes to iterate as the child nodes will // change upon removal for (int i = 0; i < length; i++) { toBeProcessed.add(n.getChildNodes().item(i)); } // This changes the child nodes, but the iterator of nodes never // changes meaning that this is safe for (Node childNode : toBeProcessed) { removeWhitespaceInner(childNode, n); } } } /** * Not instantiable. */ private XMLParser() { } }
Java
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2016 the original author or authors. */ package org.assertj.core.api; import static org.assertj.core.util.Lists.newArrayList; import org.junit.Rule; import org.junit.Test; public class JUnitBDDSoftAssertionsSuccessTest { @Rule public final JUnitBDDSoftAssertions softly = new JUnitBDDSoftAssertions(); @Test public void all_assertions_should_pass() throws Throwable { softly.then(1).isEqualTo(1); softly.then(newArrayList(1, 2)).containsOnly(1, 2); } }
Java
(function () { 'use strict'; app.service('reportService', reportService); function reportService($http, $window, $interval, timeAgo, restCall, queryService, dashboardFactory, ngAuthSettings, reportServiceUrl) { var populateReport = function (report, url) { function successCallback(response) { if (response.data.data.length === 0) { report.status = 'EMPTY' } else { report.status = 'SUCCESS'; report.data = response.data.data; report.getTotal(); console.log(report); } } function errorCallback(error) { console.log(error); this.status = 'FAILED'; } restCall('GET', url, null, successCallback, errorCallback) } var getReport = function () { return { data: {}, searchParam : { startdate: null, enddate: null, type: "ENTERPRISE", generateexcel: false, userid: null, username: null }, total : { totalVendor: 0, totalDelivery: 0, totalPending: 0, totalInProgress: 0, totalCompleted: 0, totalCancelled: 0, totalProductPrice: 0, totalDeliveryCharge: 0 }, getTotal: function () { var itSelf = this; itSelf.total.totalVendor = 0; itSelf.total.totalDelivery = 0; itSelf.total.totalPending = 0; itSelf.total.totalInProgress = 0; itSelf.total.totalCompleted = 0; itSelf.total.totalCancelled = 0; itSelf.total.totalProductPrice = 0; itSelf.total.totalDeliveryCharge = 0; angular.forEach(this.data, function (value, key) { itSelf.total.totalVendor += 1; itSelf.total.totalDelivery += value.TotalDelivery; itSelf.total.totalPending += value.TotalPending; itSelf.total.totalInProgress += value.TotalInProgress; itSelf.total.totalCompleted += value.TotalCompleted; itSelf.total.totalCancelled += value.TotalCancelled; itSelf.total.totalProductPrice += value.TotalProductPrice; itSelf.total.totalDeliveryCharge += value.TotalDeliveryCharge; }); console.log(this.total) }, getUrl: function () { // FIXME: need to be refactored if (this.searchParam.type === "BIKE_MESSENGER") { return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type; } return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type; }, getReport: function () { var reportUrl = this.getUrl(); this.status = 'IN_PROGRESS'; populateReport(this, reportUrl); }, goToReportJobs : function (user) { console.log(user) console.log(this.data) if (this.searchParam.type === "BIKE_MESSENGER") { $window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate + "&usertype=BIKE_MESSENGER" + "&userid=" + this.data[user].UserId, '_blank'); } else { $window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate + "&usertype=" + this.searchParam.type + "&username=" + user, '_blank'); } }, exportExcel : function () { var excelReportUrl = reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type + "&generateexcel=true"; $window.open(excelReportUrl, '_blank'); }, status : 'NONE' } } return { getReport: getReport } } })();
Java
/******************************************************************************* * Copyright 2013-2015 alladin-IT GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package at.alladin.rmbt.controlServer; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Locale; import java.util.ResourceBundle; import javax.naming.NamingException; import org.joda.time.DateTime; import org.json.JSONException; import org.json.JSONObject; import org.restlet.data.Reference; import org.restlet.engine.header.Header; import org.restlet.representation.Representation; import org.restlet.resource.Options; import org.restlet.resource.ResourceException; import org.restlet.util.Series; import at.alladin.rmbt.db.DbConnection; import at.alladin.rmbt.shared.ResourceManager; import at.alladin.rmbt.util.capability.Capabilities; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class ServerResource extends org.restlet.resource.ServerResource { protected Connection conn; protected ResourceBundle labels; protected ResourceBundle settings; protected Capabilities capabilities = new Capabilities(); public static class MyDateTimeAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> { public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsJsonPrimitive().getAsString()); } } public void readCapabilities(final JSONObject request) throws JSONException { if (request != null) { if (request.has("capabilities")) { capabilities = new Gson().fromJson(request.get("capabilities").toString(), Capabilities.class); } } } public static Gson getGson(boolean prettyPrint) { GsonBuilder gb = new GsonBuilder() .registerTypeAdapter(DateTime.class, new MyDateTimeAdapter()); if (prettyPrint) gb = gb.setPrettyPrinting(); return gb.create(); } @Override public void doInit() throws ResourceException { super.doInit(); settings = ResourceManager.getCfgBundle(); // Set default Language for System Locale.setDefault(new Locale(settings.getString("RMBT_DEFAULT_LANGUAGE"))); labels = ResourceManager.getSysMsgBundle(); try { if (getQuery().getNames().contains("capabilities")) { capabilities = new Gson().fromJson(getQuery().getValues("capabilities"), Capabilities.class); } } catch (final Exception e) { e.printStackTrace(); } // Get DB-Connection try { conn = DbConnection.getConnection(); } catch (final NamingException e) { e.printStackTrace(); } catch (final SQLException e) { System.out.println(labels.getString("ERROR_DB_CONNECTION_FAILED")); e.printStackTrace(); } } @Override protected void doRelease() throws ResourceException { try { if (conn != null) conn.close(); } catch (final SQLException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") protected void addAllowOrigin() { Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers"); if (responseHeaders == null) { responseHeaders = new Series<>(Header.class); getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders); } responseHeaders.add("Access-Control-Allow-Origin", "*"); responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,OPTIONS"); responseHeaders.add("Access-Control-Allow-Headers", "Content-Type"); responseHeaders.add("Access-Control-Allow-Credentials", "false"); responseHeaders.add("Access-Control-Max-Age", "60"); } @Options public void doOptions(final Representation entity) { addAllowOrigin(); } @SuppressWarnings("unchecked") public String getIP() { final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers"); final String realIp = headers.getFirstValue("X-Real-IP", true); if (realIp != null) return realIp; else return getRequest().getClientInfo().getAddress(); } @SuppressWarnings("unchecked") public Reference getURL() { final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers"); final String realURL = headers.getFirstValue("X-Real-URL", true); if (realURL != null) return new Reference(realURL); else return getRequest().getOriginalRef(); } protected String getSetting(String key, String lang) { if (conn == null) return null; try (final PreparedStatement st = conn.prepareStatement( "SELECT value" + " FROM settings" + " WHERE key=? AND (lang IS NULL OR lang = ?)" + " ORDER BY lang NULLS LAST LIMIT 1");) { st.setString(1, key); st.setString(2, lang); try (final ResultSet rs = st.executeQuery();) { if (rs != null && rs.next()) return rs.getString("value"); } return null; } catch (SQLException e) { e.printStackTrace(); return null; } } }
Java
package io.github.marktony.reader.qsbk; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import io.github.marktony.reader.R; import io.github.marktony.reader.adapter.QsbkArticleAdapter; import io.github.marktony.reader.data.Qiushibaike; import io.github.marktony.reader.interfaze.OnRecyclerViewClickListener; import io.github.marktony.reader.interfaze.OnRecyclerViewLongClickListener; /** * Created by Lizhaotailang on 2016/8/4. */ public class QsbkFragment extends Fragment implements QsbkContract.View { private QsbkContract.Presenter presenter; private QsbkArticleAdapter adapter; private RecyclerView recyclerView; private SwipeRefreshLayout refreshLayout; public QsbkFragment() { // requires empty constructor } public static QsbkFragment newInstance(int page) { return new QsbkFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.joke_list_fragment, container, false); initViews(view); presenter.loadArticle(true); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { presenter.loadArticle(true); adapter.notifyDataSetChanged(); if (refreshLayout.isRefreshing()){ refreshLayout.setRefreshing(false); } } }); recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { boolean isSlidingToLast = false; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); // 当不滚动时 if (newState == RecyclerView.SCROLL_STATE_IDLE) { // 获取最后一个完全显示的itemposition int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition(); int totalItemCount = manager.getItemCount(); // 判断是否滚动到底部并且是向下滑动 if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) { presenter.loadMore(); } } super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); isSlidingToLast = dy > 0; } }); return view; } @Override public void setPresenter(QsbkContract.Presenter presenter) { if (presenter != null) { this.presenter = presenter; } } @Override public void initViews(View view) { recyclerView = (RecyclerView) view.findViewById(R.id.qsbk_rv); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh); } @Override public void showResult(ArrayList<Qiushibaike.Item> articleList) { if (adapter == null) { adapter = new QsbkArticleAdapter(getActivity(), articleList); recyclerView.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); } adapter.setOnItemClickListener(new OnRecyclerViewClickListener() { @Override public void OnClick(View v, int position) { presenter.shareTo(position); } }); adapter.setOnItemLongClickListener(new OnRecyclerViewLongClickListener() { @Override public void OnLongClick(View view, int position) { presenter.copyToClipboard(position); } }); } @Override public void startLoading() { refreshLayout.post(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(true); } }); } @Override public void stopLoading() { refreshLayout.post(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(false); } }); } @Override public void showLoadError() { Snackbar.make(recyclerView, "加载失败", Snackbar.LENGTH_SHORT) .setAction("重试", new View.OnClickListener() { @Override public void onClick(View view) { presenter.loadArticle(false); } }).show(); } @Override public void onResume() { super.onResume(); presenter.start(); } }
Java
package org.gradle.test.performance.mediummonolithicjavaproject.p428; import org.junit.Test; import static org.junit.Assert.*; public class Test8570 { Production8570 objectUnderTest = new Production8570(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
Java
var array = trace ( new Array()); var m = trace ( 0 ); var n = trace ( 3 ); var o = trace ( 5 ); var p = trace ( 7 ); array[0] = m; array[1] = n; array[2] = o; array[3] = p; var result = new Array(); // FOR-IN Schleife for ( i in array ) { result.push(i); x = i; z = 7; } var a = result; var b = result[0]; var c = 7; var d = x;
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Logger; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.distributed.DistributedSystemDisconnectedException; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.InternalCacheForClientAccess; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.management.ManagementService; /** * Super class to all Management Service * * @since GemFire 7.0 */ public abstract class BaseManagementService extends ManagementService { private static final Logger logger = LogService.getLogger(); /** * The main mapping between different resources and Service instance Object can be Cache */ @MakeNotStatic protected static final Map<Object, BaseManagementService> instances = new HashMap<Object, BaseManagementService>(); /** List of connected <code>DistributedSystem</code>s */ @MakeNotStatic private static final List<InternalDistributedSystem> systems = new ArrayList<InternalDistributedSystem>(1); /** Protected constructor. */ protected BaseManagementService() {} // Static block to initialize the ConnectListener on the System static { initInternalDistributedSystem(); } /** * This method will close the service. Any operation on the service instance will throw exception */ protected abstract void close(); /** * This method will close the service. Any operation on the service instance will throw exception */ protected abstract boolean isClosed(); /** * Returns a ManagementService to use for the specified Cache. * * @param cache defines the scope of resources to be managed */ public static ManagementService getManagementService(InternalCacheForClientAccess cache) { synchronized (instances) { BaseManagementService service = instances.get(cache); if (service == null) { service = SystemManagementService.newSystemManagementService(cache); instances.put(cache, service); } return service; } } public static ManagementService getExistingManagementService(InternalCache cache) { synchronized (instances) { BaseManagementService service = instances.get(cache.getCacheForProcessingClientRequests()); return service; } } /** * Initialises the distributed system listener */ private static void initInternalDistributedSystem() { synchronized (instances) { // Initialize our own list of distributed systems via a connect listener @SuppressWarnings("unchecked") List<InternalDistributedSystem> existingSystems = InternalDistributedSystem .addConnectListener(new InternalDistributedSystem.ConnectListener() { @Override public void onConnect(InternalDistributedSystem sys) { addInternalDistributedSystem(sys); } }); // While still holding the lock on systems, add all currently known // systems to our own list for (InternalDistributedSystem sys : existingSystems) { try { if (sys.isConnected()) { addInternalDistributedSystem(sys); } } catch (DistributedSystemDisconnectedException e) { if (logger.isDebugEnabled()) { logger.debug("DistributedSystemDisconnectedException {}", e.getMessage(), e); } } } } } /** * Add an Distributed System and adds a Discon Listener */ private static void addInternalDistributedSystem(InternalDistributedSystem sys) { synchronized (instances) { sys.addDisconnectListener(new InternalDistributedSystem.DisconnectListener() { @Override public String toString() { return "Disconnect listener for BaseManagementService"; } @Override public void onDisconnect(InternalDistributedSystem ss) { removeInternalDistributedSystem(ss); } }); systems.add(sys); } } /** * Remove a Distributed System from the system lists. If list is empty it closes down all the * services if not closed */ private static void removeInternalDistributedSystem(InternalDistributedSystem sys) { synchronized (instances) { systems.remove(sys); if (systems.isEmpty()) { for (Object key : instances.keySet()) { BaseManagementService service = (BaseManagementService) instances.get(key); try { if (!service.isClosed()) { // Service close method should take care of the cleaning up // activities service.close(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("ManagementException while removing InternalDistributedSystem {}", e.getMessage(), e); } } } instances.clear(); } } } }
Java
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.adapter.okhttp.extractor; import okhttp3.Connection; import okhttp3.Request; /** * @author zhaoyuguang */ public class DefaultOkHttpResourceExtractor implements OkHttpResourceExtractor { @Override public String extract(Request request, Connection connection) { return request.method() + ":" + request.url().toString(); } }
Java
'use strict' /*eslint-env node */ exports.config = { specs: [ 'test/e2e/**/*.js' ], baseUrl: 'http://localhost:9000', chromeOnly: true }
Java
--- title: Fall's Fabulous Floral, Fruit, and Foliage Finery date: 2014-10-13 00:00:00 -06:00 categories: - whats-blooming layout: post blog-banner: whats-blooming-now-fall.jpg post-date: October 13, 2014 post-time: 2:32 PM blog-image: wbn-default.jpg --- <div class="text-center">Fall weather brings about a fabulous display throughout the Garden. Many of our plants are creating a show not only with their flowers, but with their fruits and leaves as well. Be sure to take heed of the cool autumn air as it beckons you to the Garden!</div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x377xRudbeckia,P20fulgida,P20var.,P20sullivantii,P20,P27Goldstrum,P27,P20Fall,P20Flower,P20Fruit,P20SQS12.jpg.pagespeed.ic.f1uSSoBXkl.jpg" width="560" height="377" alt="" title="" /> <p>Black-Eyed Susan &nbsp;&nbsp;<i> Rudbeckia fulgida</i>&nbsp;var.&nbsp;<i>sullivantii &nbsp;</i> 'Goldstrum'</p> <p>Bright yellow petals adorn this perennial in the summer, but fall has given this sturdy flower a more manila appearance.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x718xDianthus,P20chinensis,P20,P27Baby,P20Doll,P27,P20Flower,P20SQS14.jpg.pagespeed.ic.NulNQJ865H.jpg" width="560" height="718" alt="" title="" /> <p>Baby Doll Dianthus&nbsp;&nbsp;<i>Dianthus chinensis</i>&nbsp;'Baby Doll'</p> <p>This diminutive Dianthus displays blooms that range from a deep rose pink to a bright white and about every shade in between.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x804xDelphinium,P20elatum,P20,P27Royal,P20Aspirations,P27,P20Flower,P20SQS14.jpg.pagespeed.ic.HiSf5VqLN4.jpg" width="560" height="804" alt="" title="" /> <p>Candle Larkspur&nbsp;&nbsp;<i> Delphinium elatum</i>&nbsp;'Royal Aspirations'</p> <p>Bold spikes of purple-blue are complemented with white centers on this dense-flowering larkspur.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x712xDatura,P20wrightii,P20Fruit,P20SQS14.jpg.pagespeed.ic.XnicWsL0jE.jpg" width="560" height="712" alt="" title="" /> <p>Sacred Datura&nbsp;&nbsp;<i> Datura wrightii</i>&nbsp;</p> <p>Large, fragrant white flowers develop into decorative, but poisonous, spiky fruits on this Utah native.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x383xScabiosa,P20ochroleuca,P20Fruit,P20SQS12.jpg.pagespeed.ic.2fjs1lx_k0.jpg" width="560" height="383" alt="" title="" /> <p>Yellow Scabiosa &nbsp;&nbsp;<i> Scabiosa ochroleuca</i>&nbsp;</p> <p>The multitude of spikes adorning this fun, decorative seed head give this plant it's other common name of pincushion flower.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x395xTaxus,P20x,P20media,P20,P27Hicksii,P27,P20Fruit,P20SQS14.jpg.pagespeed.ic.qczwZHOutw.jpg" width="560" height="395" alt="" title="" /> <p>Hick's Yew &nbsp;&nbsp;<i> Taxus x media</i>&nbsp; 'Hicksii'</p> <p>The almost alien looking fruits of this evergreen range from bright red to opaque pink.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x383xScabiosa,P20ochroleuca,P20Fruit,P20SQS12.jpg.pagespeed.ic.2fjs1lx_k0.jpg" width="560" height="383" alt="" title="" /> <p>Yellow Scabiosa &nbsp;&nbsp;<i> Scabiosa ochroleuca</i>&nbsp;</p> <p>The multitude of spikes adorning this fun, decorative seed head give this plant it's other common name of pincushion flower.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x383xScabiosa,P20ochroleuca,P20Fruit,P20SQS12.jpg.pagespeed.ic.2fjs1lx_k0.jpg" width="560" height="383" alt="" title="" /> <p>Yellow Scabiosa &nbsp;&nbsp;<i> Scabiosa ochroleuca</i>&nbsp;</p> <p>The multitude of spikes adorning this fun, decorative seed head give this plant it's other common name of pincushion flower.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x395xTaxus,P20x,P20media,P20,P27Hicksii,P27,P20Fruit,P20SQS14.jpg.pagespeed.ic.qczwZHOutw.jpg" width="560" height="395" alt="" title="" /> <p>Hick's Yew &nbsp;&nbsp;<i> Taxus x media</i>&nbsp; 'Hicksii'</p> <p>The almost alien looking fruits of this evergreen range from bright red to opaque pink.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x367xEuonymus,P20europaeus,P20,P27Red,P20Cascade,P27,P20Fall,P20Leaves,P20SQS12,P202.jpg.pagespeed.ic._frvi_J7Kk.jpg" width="560" height="367" alt="" title="" /> <p>Common Spindle Tree &nbsp;&nbsp;<i> Euonymus europaeus</i>&nbsp; 'Red Cascade'</p> <p>The leaves of this tree become decorated with a spectacular array and design of colors in the fall.</p> </div> <br> <br> <div class="text-center"> <img src="/images/blogs/old-posts/550x563xViburnum,P20x,P20burkwoodii,P20Fall,P20Leaves,P20SQS13.JPG.pagespeed.ic.qQmTdz6e3i.jpg" width="560" height="563" alt="" title="" /> <p>Burkwood Viburnum &nbsp;&nbsp;<i>Viburnum x burkwoodii</i>&nbsp; </p> <p>The leaves of this Viburnum make a lovely show of their transition from green to a deep wine-red hue.</p> </div> <br> <br> <div class="text-center"> <p>This is a spectacular time of year to visit the Garden and bask in the warmth of the sun. Don't take these autumnal opportunities for granted, winter will be here soon!</p> </div> <br> <h5 class="text-center green">Photos by Sarah Sandoval</h5>
Java
package com.melvin.share.ui.activity; import android.content.Context; import android.databinding.DataBindingUtil; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.jcodecraeer.xrecyclerview.ProgressStyle; import com.melvin.share.R; import com.melvin.share.Utils.ShapreUtils; import com.melvin.share.Utils.Utils; import com.melvin.share.databinding.ActivityOrderEvaluateBinding; import com.melvin.share.model.Evaluation; import com.melvin.share.model.WaitPayOrderInfo; import com.melvin.share.model.list.CommonList; import com.melvin.share.model.serverReturn.CommonReturnModel; import com.melvin.share.modelview.acti.OrderEvaluateViewModel; import com.melvin.share.network.GlobalUrl; import com.melvin.share.rx.RxActivityHelper; import com.melvin.share.rx.RxFragmentHelper; import com.melvin.share.rx.RxModelSubscribe; import com.melvin.share.rx.RxSubscribe; import com.melvin.share.ui.activity.common.BaseActivity; import com.melvin.share.ui.activity.shopcar.ShoppingCarActivity; import com.melvin.share.ui.fragment.productinfo.ProductEvaluateFragment; import com.melvin.share.view.MyRecyclerView; import com.melvin.share.view.RatingBar; import java.util.HashMap; import java.util.Map; import static com.melvin.share.R.id.map; import static com.melvin.share.R.id.ratingbar; /** * Author: Melvin * <p/> * Data: 2017/4/8 * <p/> * 描述: 订单评价页面 */ public class OderEvaluateActivity extends BaseActivity { private ActivityOrderEvaluateBinding binding; private Context mContext = null; private int starCount; private WaitPayOrderInfo.OrderBean.OrderItemResponsesBean orderItemResponsesBean; @Override protected void initView() { binding = DataBindingUtil.setContentView(this, R.layout.activity_order_evaluate); mContext = this; initWindow(); initToolbar(binding.toolbar); ininData(); } private void ininData() { binding.ratingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() { @Override public void onRatingChange(int var1) { starCount = var1; } }); orderItemResponsesBean = getIntent().getParcelableExtra("orderItemResponsesBean"); if (orderItemResponsesBean != null) { String[] split = orderItemResponsesBean.mainPicture.split("\\|"); if (split != null && split.length >= 1) { String url = GlobalUrl.SERVICE_URL + split[0]; Glide.with(mContext) .load(url) .placeholder(R.mipmap.logo) .centerCrop() .into(binding.image); } binding.name.setText(orderItemResponsesBean.productName); } } public void submit(View view) { String contents = binding.content.getText().toString(); if (TextUtils.isEmpty(contents)) { Utils.showToast(mContext, "请评价"); } if (starCount == 0) { Utils.showToast(mContext, "请评分"); } Map map = new HashMap(); map.put("orderItemId", orderItemResponsesBean.id); map.put("startlevel", starCount); map.put("picture", orderItemResponsesBean.mainPicture); map.put("content", contents); ShapreUtils.putParamCustomerId(map); JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = (JsonObject) jsonParser.parse((new Gson().toJson(map))); fromNetwork.insertOderItemEvaluation(jsonObject) .compose(new RxActivityHelper<CommonReturnModel>().ioMain(OderEvaluateActivity.this, true)) .subscribe(new RxSubscribe<CommonReturnModel>(mContext, true) { @Override protected void myNext(CommonReturnModel commonReturnModel) { Utils.showToast(mContext, commonReturnModel.message); finish(); } @Override protected void myError(String message) { Utils.showToast(mContext, message); } }); } }
Java
# Weebly ============= http://themehack.beta.weebly.com/weebly/main.php
Java
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, OnDestroy } from '@angular/core'; import { Platform, NavParams } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { CoreEventsProvider } from '@providers/events'; import { CoreSitesProvider } from '@providers/sites'; import { AddonMessagesProvider } from '../../providers/messages'; import { CoreDomUtilsProvider } from '@providers/utils/dom'; import { CoreUtilsProvider } from '@providers/utils/utils'; import { CoreAppProvider } from '@providers/app'; import { AddonPushNotificationsDelegate } from '@addon/pushnotifications/providers/delegate'; /** * Component that displays the list of discussions. */ @Component({ selector: 'addon-messages-discussions', templateUrl: 'addon-messages-discussions.html', }) export class AddonMessagesDiscussionsComponent implements OnDestroy { protected newMessagesObserver: any; protected readChangedObserver: any; protected cronObserver: any; protected appResumeSubscription: any; protected loadingMessages: string; protected siteId: string; loaded = false; loadingMessage: string; discussions: any; discussionUserId: number; pushObserver: any; search = { enabled: false, showResults: false, results: [], loading: '', text: '' }; constructor(private eventsProvider: CoreEventsProvider, sitesProvider: CoreSitesProvider, translate: TranslateService, private messagesProvider: AddonMessagesProvider, private domUtils: CoreDomUtilsProvider, navParams: NavParams, private appProvider: CoreAppProvider, platform: Platform, utils: CoreUtilsProvider, pushNotificationsDelegate: AddonPushNotificationsDelegate) { this.search.loading = translate.instant('core.searching'); this.loadingMessages = translate.instant('core.loading'); this.siteId = sitesProvider.getCurrentSiteId(); // Update discussions when new message is received. this.newMessagesObserver = eventsProvider.on(AddonMessagesProvider.NEW_MESSAGE_EVENT, (data) => { if (data.userId) { const discussion = this.discussions.find((disc) => { return disc.message.user == data.userId; }); if (typeof discussion == 'undefined') { this.loaded = false; this.refreshData().finally(() => { this.loaded = true; }); } else { // An existing discussion has a new message, update the last message. discussion.message.message = data.message; discussion.message.timecreated = data.timecreated; } } }, this.siteId); // Update discussions when a message is read. this.readChangedObserver = eventsProvider.on(AddonMessagesProvider.READ_CHANGED_EVENT, (data) => { if (data.userId) { const discussion = this.discussions.find((disc) => { return disc.message.user == data.userId; }); if (typeof discussion != 'undefined') { // A discussion has been read reset counter. discussion.unread = false; // Discussions changed, invalidate them. this.messagesProvider.invalidateDiscussionsCache(); } } }, this.siteId); // Update discussions when cron read is executed. this.cronObserver = eventsProvider.on(AddonMessagesProvider.READ_CRON_EVENT, (data) => { this.refreshData(); }, this.siteId); // Refresh the view when the app is resumed. this.appResumeSubscription = platform.resume.subscribe(() => { if (!this.loaded) { return; } this.loaded = false; this.refreshData(); }); this.discussionUserId = navParams.get('discussionUserId') || false; // If a message push notification is received, refresh the view. this.pushObserver = pushNotificationsDelegate.on('receive').subscribe((notification) => { // New message received. If it's from current site, refresh the data. if (utils.isFalseOrZero(notification.notif) && notification.site == this.siteId) { this.refreshData(); } }); } /** * Component loaded. */ ngOnInit(): void { if (this.discussionUserId) { // There is a discussion to load, open the discussion in a new state. this.gotoDiscussion(this.discussionUserId); } this.fetchData().then(() => { if (!this.discussionUserId && this.discussions.length > 0) { // Take first and load it. this.gotoDiscussion(this.discussions[0].message.user, undefined, true); } }); } /** * Refresh the data. * * @param {any} [refresher] Refresher. * @return {Promise<any>} Promise resolved when done. */ refreshData(refresher?: any): Promise<any> { return this.messagesProvider.invalidateDiscussionsCache().then(() => { return this.fetchData().finally(() => { if (refresher) { // Actions to take if refresh comes from the user. this.eventsProvider.trigger(AddonMessagesProvider.READ_CHANGED_EVENT, undefined, this.siteId); refresher.complete(); } }); }); } /** * Fetch discussions. * * @return {Promise<any>} Promise resolved when done. */ protected fetchData(): Promise<any> { this.loadingMessage = this.loadingMessages; this.search.enabled = this.messagesProvider.isSearchMessagesEnabled(); return this.messagesProvider.getDiscussions().then((discussions) => { // Convert to an array for sorting. const discussionsSorted = []; for (const userId in discussions) { discussions[userId].unread = !!discussions[userId].unread; discussionsSorted.push(discussions[userId]); } this.discussions = discussionsSorted.sort((a, b) => { return b.message.timecreated - a.message.timecreated; }); }).catch((error) => { this.domUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); }).finally(() => { this.loaded = true; }); } /** * Clear search and show discussions again. */ clearSearch(): void { this.loaded = false; this.search.showResults = false; this.search.text = ''; // Reset searched string. this.fetchData().finally(() => { this.loaded = true; }); } /** * Search messages cotaining text. * * @param {string} query Text to search for. * @return {Promise<any>} Resolved when done. */ searchMessage(query: string): Promise<any> { this.appProvider.closeKeyboard(); this.loaded = false; this.loadingMessage = this.search.loading; return this.messagesProvider.searchMessages(query).then((searchResults) => { this.search.showResults = true; this.search.results = searchResults; }).catch((error) => { this.domUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); }).finally(() => { this.loaded = true; }); } /** * Navigate to a particular discussion. * * @param {number} discussionUserId Discussion Id to load. * @param {number} [messageId] Message to scroll after loading the discussion. Used when searching. * @param {boolean} [onlyWithSplitView=false] Only go to Discussion if split view is on. */ gotoDiscussion(discussionUserId: number, messageId?: number, onlyWithSplitView: boolean = false): void { this.discussionUserId = discussionUserId; const params = { discussion: discussionUserId, onlyWithSplitView: onlyWithSplitView }; if (messageId) { params['message'] = messageId; } this.eventsProvider.trigger(AddonMessagesProvider.SPLIT_VIEW_LOAD_EVENT, params, this.siteId); } /** * Component destroyed. */ ngOnDestroy(): void { this.newMessagesObserver && this.newMessagesObserver.off(); this.readChangedObserver && this.readChangedObserver.off(); this.cronObserver && this.cronObserver.off(); this.appResumeSubscription && this.appResumeSubscription.unsubscribe(); this.pushObserver && this.pushObserver.unsubscribe(); } }
Java
# Crataegus nitidula var. recedens (Sarg.) Kruschke VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
package clockworktest.water; import com.clockwork.app.SimpleApplication; import com.clockwork.audio.AudioNode; import com.clockwork.audio.LowPassFilter; import com.clockwork.effect.ParticleEmitter; import com.clockwork.effect.ParticleMesh; import com.clockwork.input.KeyInput; import com.clockwork.input.controls.ActionListener; import com.clockwork.input.controls.KeyTrigger; import com.clockwork.light.DirectionalLight; import com.clockwork.material.Material; import com.clockwork.material.RenderState.BlendMode; import com.clockwork.math.ColorRGBA; import com.clockwork.math.FastMath; import com.clockwork.math.Quaternion; import com.clockwork.math.Vector3f; import com.clockwork.post.FilterPostProcessor; import com.clockwork.post.filters.BloomFilter; import com.clockwork.post.filters.DepthOfFieldFilter; import com.clockwork.post.filters.LightScatteringFilter; import com.clockwork.renderer.Camera; import com.clockwork.renderer.queue.RenderQueue.Bucket; import com.clockwork.renderer.queue.RenderQueue.ShadowMode; import com.clockwork.scene.Geometry; import com.clockwork.scene.Node; import com.clockwork.scene.Spatial; import com.clockwork.scene.shape.Box; import com.clockwork.terrain.geomipmap.TerrainQuad; import com.clockwork.terrain.heightmap.AbstractHeightMap; import com.clockwork.terrain.heightmap.ImageBasedHeightMap; import com.clockwork.texture.Texture; import com.clockwork.texture.Texture.WrapMode; import com.clockwork.texture.Texture2D; import com.clockwork.util.SkyFactory; import com.clockwork.water.WaterFilter; import java.util.ArrayList; import java.util.List; /** * test * */ public class TestPostWater extends SimpleApplication { private Vector3f lightDir = new Vector3f(-4.9236743f, -1.27054665f, 5.896916f); private WaterFilter water; TerrainQuad terrain; Material matRock; AudioNode waves; LowPassFilter underWaterAudioFilter = new LowPassFilter(0.5f, 0.1f); LowPassFilter underWaterReverbFilter = new LowPassFilter(0.5f, 0.1f); LowPassFilter aboveWaterAudioFilter = new LowPassFilter(1, 1); public static void main(String[] args) { TestPostWater app = new TestPostWater(); app.start(); } @Override public void simpleInitApp() { setDisplayFps(false); setDisplayStatView(false); Node mainScene = new Node("Main Scene"); rootNode.attachChild(mainScene); createTerrain(mainScene); DirectionalLight sun = new DirectionalLight(); sun.setDirection(lightDir); sun.setColor(ColorRGBA.White.clone().multLocal(1.7f)); mainScene.addLight(sun); DirectionalLight l = new DirectionalLight(); l.setDirection(Vector3f.UNIT_Y.mult(-1)); l.setColor(ColorRGBA.White.clone().multLocal(0.3f)); // mainScene.addLight(l); flyCam.setMoveSpeed(50); //cam.setLocation(new Vector3f(-700, 100, 300)); //cam.setRotation(new Quaternion().fromAngleAxis(0.5f, Vector3f.UNIT_Z)); cam.setLocation(new Vector3f(-327.21957f, 61.6459f, 126.884346f)); cam.setRotation(new Quaternion(0.052168474f, 0.9443102f, -0.18395276f, 0.2678024f)); cam.setRotation(new Quaternion().fromAngles(new float[]{FastMath.PI * 0.06f, FastMath.PI * 0.65f, 0})); Spatial sky = SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false); sky.setLocalScale(350); mainScene.attachChild(sky); cam.setFrustumFar(4000); //cam.setFrustumNear(100); //private FilterPostProcessor fpp; water = new WaterFilter(rootNode, lightDir); FilterPostProcessor fpp = new FilterPostProcessor(assetManager); fpp.addFilter(water); BloomFilter bloom = new BloomFilter(); //bloom.getE bloom.setExposurePower(55); bloom.setBloomIntensity(1.0f); fpp.addFilter(bloom); LightScatteringFilter lsf = new LightScatteringFilter(lightDir.mult(-300)); lsf.setLightDensity(1.0f); fpp.addFilter(lsf); DepthOfFieldFilter dof = new DepthOfFieldFilter(); dof.setFocusDistance(0); dof.setFocusRange(100); fpp.addFilter(dof); // // fpp.addFilter(new TranslucentBucketFilter()); // // fpp.setNumSamples(4); water.setWaveScale(0.003f); water.setMaxAmplitude(2f); water.setFoamExistence(new Vector3f(1f, 4, 0.5f)); water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg")); //water.setNormalScale(0.5f); //water.setRefractionConstant(0.25f); water.setRefractionStrength(0.2f); //water.setFoamHardness(0.6f); water.setWaterHeight(initialWaterHeight); uw = cam.getLocation().y < waterHeight; waves = new AudioNode(assetManager, "Sound/Environment/Ocean Waves.ogg", false); waves.setLooping(true); waves.setReverbEnabled(true); if (uw) { waves.setDryFilter(new LowPassFilter(0.5f, 0.1f)); } else { waves.setDryFilter(aboveWaterAudioFilter); } audioRenderer.playSource(waves); // viewPort.addProcessor(fpp); inputManager.addListener(new ActionListener() { public void onAction(String name, boolean isPressed, float tpf) { if (isPressed) { if (name.equals("foam1")) { water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam.jpg")); } if (name.equals("foam2")) { water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg")); } if (name.equals("foam3")) { water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam3.jpg")); } if (name.equals("upRM")) { water.setReflectionMapSize(Math.min(water.getReflectionMapSize() * 2, 4096)); System.out.println("Reflection map size : " + water.getReflectionMapSize()); } if (name.equals("downRM")) { water.setReflectionMapSize(Math.max(water.getReflectionMapSize() / 2, 32)); System.out.println("Reflection map size : " + water.getReflectionMapSize()); } } } }, "foam1", "foam2", "foam3", "upRM", "downRM"); inputManager.addMapping("foam1", new KeyTrigger(KeyInput.KEY_1)); inputManager.addMapping("foam2", new KeyTrigger(KeyInput.KEY_2)); inputManager.addMapping("foam3", new KeyTrigger(KeyInput.KEY_3)); inputManager.addMapping("upRM", new KeyTrigger(KeyInput.KEY_PGUP)); inputManager.addMapping("downRM", new KeyTrigger(KeyInput.KEY_PGDN)); // createBox(); // createFire(); } Geometry box; private void createBox() { //creating a transluscent box box = new Geometry("box", new Box(new Vector3f(0, 0, 0), 50, 50, 50)); Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(1.0f, 0, 0, 0.3f)); mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); //mat.getAdditionalRenderState().setDepthWrite(false); //mat.getAdditionalRenderState().setDepthTest(false); box.setMaterial(mat); box.setQueueBucket(Bucket.Translucent); //creating a post view port // ViewPort post=renderManager.createPostView("transpPost", cam); // post.setClearFlags(false, true, true); box.setLocalTranslation(-600, 0, 300); //attaching the box to the post viewport //Don't forget to updateGeometricState() the box in the simpleUpdate // post.attachScene(box); rootNode.attachChild(box); } private void createFire() { /** * Uses Texture from CW-test-data library! */ ParticleEmitter fire = new ParticleEmitter("Emitter", ParticleMesh.Type.Triangle, 30); Material mat_red = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"); mat_red.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png")); fire.setMaterial(mat_red); fire.setImagesX(2); fire.setImagesY(2); // 2x2 texture animation fire.setEndColor(new ColorRGBA(1f, 0f, 0f, 1f)); // red fire.setStartColor(new ColorRGBA(1f, 1f, 0f, 0.5f)); // yellow fire.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 2, 0)); fire.setStartSize(10f); fire.setEndSize(1f); fire.setGravity(0, 0, 0); fire.setLowLife(0.5f); fire.setHighLife(1.5f); fire.getParticleInfluencer().setVelocityVariation(0.3f); fire.setLocalTranslation(-350, 40, 430); fire.setQueueBucket(Bucket.Transparent); rootNode.attachChild(fire); } private void createTerrain(Node rootNode) { matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matRock.setBoolean("useTriPlanarMapping", false); matRock.setBoolean("WardIso", true); matRock.setTexture("AlphaMap", assetManager.loadTexture("Textures/Terrain/splat/alphamap.png")); Texture heightMapImage = assetManager.loadTexture("Textures/Terrain/splat/mountains512.png"); Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap", grass); matRock.setFloat("DiffuseMap_0_scale", 64); Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg"); dirt.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_1", dirt); matRock.setFloat("DiffuseMap_1_scale", 16); Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg"); rock.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_2", rock); matRock.setFloat("DiffuseMap_2_scale", 128); Texture normalMap0 = assetManager.loadTexture("Textures/Terrain/splat/grass_normal.jpg"); normalMap0.setWrap(WrapMode.Repeat); Texture normalMap1 = assetManager.loadTexture("Textures/Terrain/splat/dirt_normal.png"); normalMap1.setWrap(WrapMode.Repeat); Texture normalMap2 = assetManager.loadTexture("Textures/Terrain/splat/road_normal.png"); normalMap2.setWrap(WrapMode.Repeat); matRock.setTexture("NormalMap", normalMap0); matRock.setTexture("NormalMap_1", normalMap2); matRock.setTexture("NormalMap_2", normalMap2); AbstractHeightMap heightmap = null; try { heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f); heightmap.load(); } catch (Exception e) { e.printStackTrace(); } terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap()); List<Camera> cameras = new ArrayList<Camera>(); cameras.add(getCamera()); terrain.setMaterial(matRock); terrain.setLocalScale(new Vector3f(5, 5, 5)); terrain.setLocalTranslation(new Vector3f(0, -30, 0)); terrain.setLocked(false); // unlock it so we can edit the height terrain.setShadowMode(ShadowMode.Receive); rootNode.attachChild(terrain); } //This part is to emulate tides, slightly varrying the height of the water plane private float time = 0.0f; private float waterHeight = 0.0f; private float initialWaterHeight = 90f;//0.8f; private boolean uw = false; @Override public void simpleUpdate(float tpf) { super.simpleUpdate(tpf); // box.updateGeometricState(); time += tpf; waterHeight = (float) Math.cos(((time * 0.6f) % FastMath.TWO_PI)) * 1.5f; water.setWaterHeight(initialWaterHeight + waterHeight); if (water.isUnderWater() && !uw) { waves.setDryFilter(new LowPassFilter(0.5f, 0.1f)); uw = true; } if (!water.isUnderWater() && uw) { uw = false; //waves.setReverbEnabled(false); waves.setDryFilter(new LowPassFilter(1, 1f)); //waves.setDryFilter(new LowPassFilter(1,1f)); } } }
Java
/******************************************************************************* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. *******************************************************************************/ package com.github.lothar.security.acl.elasticsearch.repository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; import com.github.lothar.security.acl.elasticsearch.domain.UnknownStrategyObject; @Repository public interface UnknownStrategyRepository extends ElasticsearchRepository<UnknownStrategyObject, Long> { }
Java
# Meliosma cuneifolia Franch. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> </head> <body> <script type="text/javascript"> window.alert("你好"); console.log("今天是"); console.warn("星期五"); console.info("哈哈"); console.error("天气很好"); document.write("今天下雪啦"); </script> </body> </html>
Java
-- phpMyAdmin SQL Dump -- version 4.1.12 -- http://www.phpmyadmin.net -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 12-08-2014 a las 22:00:26 -- Versión del servidor: 5.5.36 -- Versión de PHP: 5.4.27 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de datos: `smeagol` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `menu` -- CREATE TABLE IF NOT EXISTS `menu` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, `label` varchar(150) DEFAULT NULL, `url` varchar(250) DEFAULT NULL, `parent_id` int(11) NOT NULL DEFAULT '0', `order_id` int(11) NOT NULL DEFAULT '0', `node_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_menu_node1_idx` (`node_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ; -- -- Volcado de datos para la tabla `menu` -- INSERT INTO `menu` (`id`, `name`, `label`, `url`, `parent_id`, `order_id`, `node_id`) VALUES (1, 'default', NULL, NULL, 0, 0, NULL), (2, 'admin', NULL, NULL, 0, 0, NULL), (3, NULL, 'Inicio', '/', 1, 0, NULL), (4, NULL, 'Nosotros', NULL, 1, 1, 1), (5, NULL, 'Servicios', NULL, 1, 2, 5), (6, NULL, 'Programación web', NULL, 5, 0, 4), (7, NULL, 'Desarrollo de Portales', NULL, 5, 1, 6), (8, NULL, 'Soluciones', NULL, 1, 3, 7), (9, NULL, 'Soporte', NULL, 1, 4, 8), (10, NULL, 'Contáctenos', NULL, 1, 5, 9), (11, NULL, 'Dashboard', 'admin', 2, 0, NULL), (12, NULL, 'Contenido', 'admin/page', 2, 1, NULL), (13, NULL, 'Noticias', 'admin/noticias', 2, 2, NULL), (14, NULL, 'Menus', 'admin/menus', 2, 3, NULL), (15, NULL, 'Temas', 'admin/themes', 2, 4, NULL), (16, NULL, 'Usuarios', 'admin/users', 2, 5, NULL), (17, NULL, 'Permisos', 'admin/permissions', 16, 1, NULL), (18, NULL, 'Roles', 'admin/roles', 16, 0, NULL), (19, NULL, 'Smeagol CMS', NULL, 7, 0, 10), (20, NULL, 'Drupal CMS', NULL, 7, 1, 11); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `node` -- CREATE TABLE IF NOT EXISTS `node` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(250) NOT NULL, `content` text NOT NULL, `url` varchar(250) NOT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, `node_type_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `fk_node_node_type1_idx` (`node_type_id`), KEY `fk_node_user1_idx` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ; -- -- Volcado de datos para la tabla `node` -- INSERT INTO `node` (`id`, `title`, `content`, `url`, `created`, `modified`, `node_type_id`, `user_id`) VALUES (1, 'Nosotros', '<p><strong>Smeagol CMS, un</strong><strong>&nbsp;demo de desarrolado en Zend Framework 2</strong></p>\r\n\r\n<p>Nosotros somos hinchas de Zend Framework 2</p>\r\n\r\n<p>Gurus del php&nbsp;</p>\r\n\r\n<p>que deasrrollamos aplicaciones alucinantes</p>\r\n', 'nosotros', '2014-07-01 20:47:24', '2014-07-17 13:56:17', 1, 1), (2, 'Smeagol primer CMS en ZF2', 'haber si funca', 'noticias/smeagol-primer-cms-en-zf2', '2014-07-01 20:47:24', NULL, 2, 1), (3, 'El mundial Brasil 2014 esta que quema', 'El mundial esta super emocionante', 'noticias/mundialsuper-emocionante', '2014-07-01 20:47:24', NULL, 2, 1), (4, 'Programación Web', '<p>Somos unos tigres del PHP y dem&aacute;s hierbas</p>\r\n', 'servicios/programacion-web', '2014-07-10 22:47:08', '2014-07-17 13:50:46', 1, 1), (5, 'Servicios', '<p>Somos Expertos Programadores y le ofrecemos los siguientes servicios</p>\r\n\r\n<p><a href="/servicios/programacion-web">Programaci&oacute;n web</a>&nbsp;</p>\r\n\r\n<p><a href="/servicios/desarrollo-de-portales">Desarrollo de Portales</a></p>\r\n', 'servicios', '2014-07-17 13:50:18', '2014-07-17 13:50:18', 1, 1), (6, 'Desarrollo de Portales', '<p>Creamos portales con smeagol y drupal&nbsp;</p>\r\n', 'servicios/desarrollo-de-portales', '2014-07-17 13:52:35', '2014-07-17 13:52:35', 1, 1), (7, 'Soluciones', '<p><img alt="" src="/files/fotos/puesta-de-sol.jpg" style="float:left; height:141px; width:188px" />Hacemos desarrollo de software a medida y contamos con las siguientes soluciones</p>\r\n\r\n<p><a href="/soluciones/smeagolcms">Smeagol CMS</a></p>\r\n\r\n<p><a href="/soluciones/intranets">Intranets</a></p>\r\n', 'soluciones/intranets', '2014-07-17 13:54:35', '2014-08-03 19:41:00', 1, 1), (8, 'Soporte', '<p>Brindamos el mejor soporte al mejor precio</p>\r\n\r\n<p>en planes</p>\r\n\r\n<p>8x5</p>\r\n\r\n<p>24x7</p>\r\n', 'soporte', '2014-07-17 13:58:17', '2014-08-12 21:58:34', 1, 3), (9, 'Contactenos', '<p>Cont&aacute;ctenos y no se arrepentir&aacute;</p>\r\n\r\n<p>al fono &nbsp;666-666-666</p>\r\n', 'contactenos', '2014-07-17 13:59:13', '2014-07-17 13:59:13', 1, 1), (10, 'Smeagol', '<h1>El mejor CMS en Zend Frammework 2 :D</h1>', 'servicios/desarrollo-de-portales/smeagol', '2014-07-22 08:05:00', NULL, 1, 1), (11, 'Drupal 7', '<h1> El Mejor CMS del mundo</h1>\r\n<h2> Que lo usa hasta el tío Obama<h2>', 'servicios/desarrollo-de-portales/drupal', '2014-07-22 08:05:00', NULL, 1, 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `node_type` -- CREATE TABLE IF NOT EXISTS `node_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Volcado de datos para la tabla `node_type` -- INSERT INTO `node_type` (`id`, `name`) VALUES (1, 'page'), (2, 'notice'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `permission` -- CREATE TABLE IF NOT EXISTS `permission` ( `resource` varchar(250) NOT NULL, `description` varchar(250) NOT NULL, PRIMARY KEY (`resource`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `permission` -- INSERT INTO `permission` (`resource`, `description`) VALUES ('mvc:admin.*', 'Acceso total al módulo de administración'), ('mvc:admin.index.index', 'Acceso al Dashboard del Admin'), ('mvc:admin.page.*', 'Acceso total para crear, editar, borrar páginas estáticas de cualquier usuario'), ('mvc:admin.page.add', 'Crear páginas estáticas'), ('mvc:admin.page.delete:owner', 'Borrar páginas estáticas que sean propiedad del usuario'), ('mvc:admin.page.edit:owner', 'Editar páginas estáticas que sean propiedad del usuario'), ('mvc:admin.page.index', 'Acceso al listado de páginas estáticas'), ('mvc:application.*', 'Acceso total al módulo público'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `role` -- CREATE TABLE IF NOT EXISTS `role` ( `type` varchar(30) NOT NULL, `description` varchar(250) NOT NULL, PRIMARY KEY (`type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `role` -- INSERT INTO `role` (`type`, `description`) VALUES ('admin', 'Usuarios Administradores, todos los permisos'), ('editor', 'Usuarios con el rol de editor, por defecto puede crear, editar y borrar todos los contenidos'), ('guest', 'Usuarios anónimos, por defecto pueden acceder a todos los contenidos'), ('member', 'Usuarios Autenticados, por defecto pueden editar su propio contenido'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `role_permission` -- CREATE TABLE IF NOT EXISTS `role_permission` ( `role_type` varchar(30) NOT NULL, `permission_resource` varchar(250) NOT NULL, PRIMARY KEY (`role_type`,`permission_resource`), KEY `fk_role_permission_role1_idx` (`role_type`), KEY `fk_role_permission_permission1_idx` (`permission_resource`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `role_permission` -- INSERT INTO `role_permission` (`role_type`, `permission_resource`) VALUES ('admin', 'mvc:admin.*'), ('admin', 'mvc:application.*'), ('editor', 'mvc:admin.index.index'), ('editor', 'mvc:admin.page.*'), ('editor', 'mvc:application.*'), ('guest', 'mvc:application.*'), ('member', 'mvc:admin.index.index'), ('member', 'mvc:admin.page.add'), ('member', 'mvc:admin.page.delete:owner'), ('member', 'mvc:admin.page.edit:owner'), ('member', 'mvc:admin.page.index'), ('member', 'mvc:application.*'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(32) NOT NULL, `name` varchar(100) DEFAULT NULL, `surname` varchar(100) DEFAULT NULL, `email` varchar(150) NOT NULL, `active` int(11) DEFAULT '1', `last_login` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, `role_type` varchar(30) NOT NULL, PRIMARY KEY (`id`), KEY `fk_user_role_idx` (`role_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- Volcado de datos para la tabla `user` -- INSERT INTO `user` (`id`, `username`, `password`, `name`, `surname`, `email`, `active`, `last_login`, `modified`, `role_type`) VALUES (1, 'admin', 'c6865cf98b133f1f3de596a4a2894630', 'Admin', 'of Universe', 'tucorreo@gmail.com', 1, NULL, '2014-07-01 20:47:24', 'admin'), (2, 'pepito', 'c6865cf98b133f1f3de596a4a2894630', 'Pepito', 'Linuxero', 'pepito@hotmail.com', 1, '2014-08-04 00:00:00', '2014-08-04 00:00:00', 'editor'), (3, 'tuxito', 'c6865cf98b133f1f3de596a4a2894630', 'Tuxito', 'Linuxero', 'tuxito@adiestra.pe', 1, '2014-08-11 17:17:00', '2014-08-11 17:17:00', 'member'); -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `menu` -- ALTER TABLE `menu` ADD CONSTRAINT `fk_menu_node1` FOREIGN KEY (`node_id`) REFERENCES `node` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `node` -- ALTER TABLE `node` ADD CONSTRAINT `fk_node_node_type1` FOREIGN KEY (`node_type_id`) REFERENCES `node_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_node_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `role_permission` -- ALTER TABLE `role_permission` ADD CONSTRAINT `fk_role_permission_permission1` FOREIGN KEY (`permission_resource`) REFERENCES `permission` (`resource`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_role_permission_role1` FOREIGN KEY (`role_type`) REFERENCES `role` (`type`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `user` -- ALTER TABLE `user` ADD CONSTRAINT `fk_user_role` FOREIGN KEY (`role_type`) REFERENCES `role` (`type`) ON DELETE NO ACTION ON UPDATE NO ACTION; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
# Exoacantha cryptantha Rech.f. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Phyllachora concinna Syd., 1938 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Annls mycol. 36(2/3): 160 (1938) #### Original name Phyllachora concinna Syd., 1938 ### Remarks null
Java
# Rhaphiodendron Moebius, 1876 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in Beil. Tegebl. , 49. #### Original name null ### Remarks null
Java
# Gymnosporangium nanwutaianum F.L. Tai & C.C. Cheo, 1937 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Gymnosporangium nanwutaianum F.L. Tai & C.C. Cheo, 1937 ### Remarks null
Java
# Biconidinium M.A. Islam, 1983 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in Palynology 7: 84. #### Original name null ### Remarks null
Java
# Clavaria megalorrhiza Berk. & Broome SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Clavaria megalorrhiza Berk. & Broome ### Remarks null
Java
# Conostylis serrulata R.Br. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Erythrotrichia porphyroides N.L. Gardner SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Magonia martei Kuntze SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Flexibacter elegans (ex Lewin, 1969, non Soriano, 1945) Reichenbach, 1989 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Primula calyptrata X.Gong & R.C.Fang SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Linq; using System.Windows.Forms; using Cube.Mixin.String; namespace Cube.Forms.Behaviors { /* --------------------------------------------------------------------- */ /// /// OpenFileBehavior /// /// <summary> /// Provides functionality to show a open-file dialog. /// </summary> /// /* --------------------------------------------------------------------- */ public class OpenFileBehavior : MessageBehavior<OpenFileMessage> { /* ----------------------------------------------------------------- */ /// /// OpenFileBehavior /// /// <summary> /// Initializes a new instance of the OpenFileBehavior class /// with the specified presentable object. /// </summary> /// /// <param name="aggregator">Aggregator object.</param> /// /* ----------------------------------------------------------------- */ public OpenFileBehavior(IAggregator aggregator) : base(aggregator, e => { var view = new OpenFileDialog { CheckPathExists = e.CheckPathExists, Multiselect = e.Multiselect, Filter = e.GetFilterText(), FilterIndex = e.GetFilterIndex(), }; if (e.Text.HasValue()) view.Title = e.Text; if (e.Value.Any()) view.FileName = e.Value.First(); if (e.InitialDirectory.HasValue()) view.InitialDirectory = e.InitialDirectory; e.Cancel = view.ShowDialog() != DialogResult.OK; if (!e.Cancel) e.Value = view.FileNames; }) { } } }
Java
package javassist.build; /** * A generic build exception when applying a transformer. * Wraps the real cause of the (probably javassist) root exception. * @author SNI */ @SuppressWarnings("serial") public class JavassistBuildException extends Exception { public JavassistBuildException() { super(); } public JavassistBuildException(String message, Throwable throwable) { super(message, throwable); } public JavassistBuildException(String message) { super(message); } public JavassistBuildException(Throwable throwable) { super(throwable); } }
Java
package com.hcentive.webservice.soap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import com.hcentive.service.FormResponse; import com.hcentive.webservice.exception.HcentiveSOAPException; import org.apache.log4j.Logger; /** * @author Mebin.Jacob *Endpoint class. */ @Endpoint public final class FormEndpoint { private static final String NAMESPACE_URI = "http://hcentive.com/service"; Logger logger = Logger.getLogger(FormEndpoint.class); @Autowired FormRepository formRepo; @PayloadRoot(namespace = NAMESPACE_URI, localPart = "FormResponse") @ResponsePayload public FormResponse submitForm(@RequestPayload FormResponse request) throws HcentiveSOAPException { // GetCountryResponse response = new GetCountryResponse(); // response.setCountry(countryRepository.findCountry(request.getName())); FormResponse response = null; logger.debug("AAGAYA"); try{ response = new FormResponse(); response.setForm1(formRepo.findForm("1")); //make API call }catch(Exception exception){ throw new HcentiveSOAPException("Something went wrong!!! The exception is --- " + exception); } return response; // return null; } }
Java
/* * Copyright 2015 Luca Capra <luca.capra@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.createnet.compose.data; /** * * @author Luca Capra <luca.capra@gmail.com> */ public class GeoPointRecord extends Record<String> { public Point point; protected String value; public GeoPointRecord() {} public GeoPointRecord(String point) { this.point = new Point(point); } public GeoPointRecord(double latitude, double longitude) { this.point = new Point(latitude, longitude); } @Override public String getValue() { return point.toString(); } @Override public void setValue(Object value) { this.value = parseValue(value); this.point = new Point(this.value); } @Override public String parseValue(Object raw) { return (String)raw; } @Override public String getType() { return "geo_point"; } public class Point { public double latitude; public double longitude; public Point(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } public Point(String val) { String[] coords = val.split(","); longitude = Double.parseDouble(coords[0].trim()); latitude = Double.parseDouble(coords[1].trim()); } @Override public String toString() { return this.longitude + "," + this.latitude; } } }
Java
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.ide.intellij; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.facebook.buck.android.AssumeAndroidPlatform; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.xml.XmlDomParser; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.w3c.dom.Node; public class ProjectIntegrationTest { @Rule public TemporaryPaths temporaryFolder = new TemporaryPaths(); @Before public void setUp() throws Exception { // These tests consistently fail on Windows due to path separator issues. Assume.assumeFalse(Platform.detect() == Platform.WINDOWS); } @Test public void testAndroidLibraryProject() throws InterruptedException, IOException { runBuckProjectAndVerify("android_library"); } @Test public void testAndroidBinaryProject() throws InterruptedException, IOException { runBuckProjectAndVerify("android_binary"); } @Test public void testVersion2BuckProject() throws InterruptedException, IOException { runBuckProjectAndVerify("project1"); } @Test public void testVersion2BuckProjectWithoutAutogeneratingSources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_without_autogeneration"); } @Test public void testVersion2BuckProjectSlice() throws InterruptedException, IOException { runBuckProjectAndVerify("project_slice", "--without-tests", "modules/dep1:dep1"); } @Test public void testVersion2BuckProjectSourceMerging() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation"); } @Test public void testBuckProjectWithCustomAndroidSdks() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_custom_android_sdks"); } @Test public void testBuckProjectWithCustomJavaSdks() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_custom_java_sdks"); } @Test public void testBuckProjectWithIntellijSdk() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_intellij_sdk"); } @Test public void testVersion2BuckProjectWithProjectSettings() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_project_settings"); } @Test public void testVersion2BuckProjectWithScripts() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_scripts", "//modules/dep1:dep1"); } @Test public void testVersion2BuckProjectWithUnusedLibraries() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_unused_libraries", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess("buck project should exit cleanly"); assertFalse(workspace.resolve(".idea/libraries/library_libs_jsr305.xml").toFile().exists()); } @Test public void testVersion2BuckProjectWithExcludedResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_excluded_resources"); } @Test public void testVersion2BuckProjectWithAssets() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_assets"); } @Test public void testVersion2BuckProjectWithLanguageLevel() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_language_level"); } @Test public void testVersion2BuckProjectWithOutputUrl() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_output_url"); } @Test public void testVersion2BuckProjectWithJavaResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_java_resources"); } public void testVersion2BuckProjectWithExtraOutputModules() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_extra_output_modules"); } @Test public void testVersion2BuckProjectWithGeneratedSources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_generated_sources"); } @Test public void testBuckProjectWithSubdirGlobResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_subdir_glob_resources"); } @Test public void testRobolectricTestRule() throws InterruptedException, IOException { runBuckProjectAndVerify("robolectric_test"); } @Test public void testAndroidResourcesInDependencies() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_android_resources"); } @Test public void testPrebuiltJarWithJavadoc() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_prebuilt_jar"); } @Test public void testZipFile() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_zipfile"); } @Test public void testAndroidResourcesAndLibraryInTheSameFolder() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resources_in_the_same_folder"); } @Test public void testAndroidResourcesWithPackagesAtTheSameLocation() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_multiple_resources_with_package_names"); } @Test public void testCxxLibrary() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_cxx_library"); } @Test public void testAggregatingCxxLibrary() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation_with_cxx_library"); } @Test public void testSavingGeneratedFilesList() throws InterruptedException, IOException { runBuckProjectAndVerify( "save_generated_files_list", "--file-with-list-of-generated-files", ".idea/generated-files.txt"); } @Test public void testMultipleLibraries() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_multiple_libraries"); } @Test public void testProjectWithIgnoredTargets() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_ignored_targets"); } @Test public void testProjectWithCustomPackages() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation_with_custom_packages"); } @Test public void testAndroidResourceAggregation() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resource_aggregation"); } @Test public void testAndroidResourceAggregationWithLimit() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resource_aggregation_with_limit"); } @Test public void testProjectIncludesTestsByDefault() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_tests_by_default", "//modules/lib:lib"); } @Test public void testProjectExcludesTestsWhenRequested() throws InterruptedException, IOException { runBuckProjectAndVerify("project_without_tests", "--without-tests", "//modules/lib:lib"); } @Test public void testProjectExcludesDepTestsWhenRequested() throws InterruptedException, IOException { runBuckProjectAndVerify( "project_without_dep_tests", "--without-dependencies-tests", "//modules/lib:lib"); } @Test public void testUpdatingExistingWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("update_existing_workspace"); } @Test public void testCreateNewWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("create_new_workspace"); } @Test public void testUpdateMalformedWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("update_malformed_workspace"); } @Test public void testUpdateWorkspaceWithoutIgnoredNodes() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_ignored_nodes"); } @Test public void testUpdateWorkspaceWithoutManagerNode() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_manager_node"); } @Test public void testUpdateWorkspaceWithoutProjectNode() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_project_node"); } @Test public void testProjectWthPackageBoundaryException() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_package_boundary_exception", "//project2:lib"); } @Test public void testProjectWithProjectRoot() throws InterruptedException, IOException { runBuckProjectAndVerify( "project_with_project_root", "--intellij-project-root", "project1", "--intellij-include-transitive-dependencies", "--intellij-module-group-name", "", "//project1/lib:lib"); } @Test public void testGeneratingAndroidManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("generate_android_manifest"); } @Test public void testGeneratingAndroidManifestWithMinSdkWithDifferentVersionsFromManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_different_from_manifests"); } @Test public void testGeneratingAndroidManifestWithMinSdkFromBinaryManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_from_binary_manifest"); } @Test public void testGeneratingAndroidManifestWithMinSdkFromBuckConfig() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_from_buck_config"); } @Test public void testGeneratingAndroidManifestWithNoMinSdkConfig() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_with_no_config"); } @Test public void testPreprocessScript() throws InterruptedException, IOException { ProcessResult result = runBuckProjectAndVerify("preprocess_script_test"); assertEquals("intellij", result.getStdout().trim()); } @Test public void testScalaProject() throws InterruptedException, IOException { runBuckProjectAndVerify("scala_project"); } @Test public void testIgnoredPathAddedToExcludedFolders() throws InterruptedException, IOException { runBuckProjectAndVerify("ignored_excluded"); } @Test public void testBuckModuleRegenerateSubproject() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "incrementalProject", temporaryFolder.newFolder()) .setUp(); final String extraModuleFilePath = "modules/extra/modules_extra.iml"; final File extraModuleFile = workspace.getPath(extraModuleFilePath).toFile(); workspace .runBuckCommand("project", "--intellij-aggregation-mode=none", "//modules/tip:tip") .assertSuccess(); assertFalse(extraModuleFile.exists()); final String modulesBefore = workspace.getFileContents(".idea/modules.xml"); final String fileXPath = String.format( "/project/component/modules/module[contains(@filepath,'%s')]", extraModuleFilePath); assertThat(XmlDomParser.parse(modulesBefore), Matchers.not(Matchers.hasXPath(fileXPath))); // Run regenerate on the new modules workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra") .assertSuccess(); assertTrue(extraModuleFile.exists()); final String modulesAfter = workspace.getFileContents(".idea/modules.xml"); assertThat(XmlDomParser.parse(modulesAfter), Matchers.hasXPath(fileXPath)); workspace.verify(); } @Test public void testBuckModuleRegenerateSubprojectNoOp() throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "incrementalProject", temporaryFolder.newFolder()) .setUp(); workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "//modules/tip:tip", "//modules/extra:extra") .assertSuccess(); workspace.verify(); // Run regenerate, should be a no-op relative to previous workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra") .assertSuccess(); workspace.verify(); } @Test public void testCrossCellIntelliJProject() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace primary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/primary", temporaryFolder.newFolder()); primary.setUp(); ProjectWorkspace secondary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/secondary", temporaryFolder.newFolder()); secondary.setUp(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of( "repositories", ImmutableMap.of("secondary", secondary.getPath(".").normalize().toString()))); // First try with cross-cell enabled String target = "//apps/sample:app_with_cross_cell_android_lib"; ProcessResult result = primary.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=true", "--ide", "intellij", target); result.assertSuccess(); String libImlPath = ".idea/libraries/secondary__java_com_crosscell_crosscell.xml"; Node doc = XmlDomParser.parse(primary.getFileContents(libImlPath)); String urlXpath = "/component/library/CLASSES/root/@url"; // Assert that the library URL is inside the project root assertThat( doc, Matchers.hasXPath( urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/buck-out/cells/secondary/gen/"))); result = primary.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=false", "--ide", "intellij", target); result.assertSuccess(); Node doc2 = XmlDomParser.parse(primary.getFileContents(libImlPath)); // Assert that the library URL is outside the project root assertThat(doc2, Matchers.hasXPath(urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/.."))); } private ProcessResult runBuckProjectAndVerify(String folderWithTestData, String... commandArgs) throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, folderWithTestData, temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand(Lists.asList("project", commandArgs).toArray(new String[0])); result.assertSuccess("buck project should exit cleanly"); workspace.verify(); return result; } }
Java
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.MobileServices.Eventing { /// <summary> /// Represents a mobile service event. /// </summary> public interface IMobileServiceEvent { /// <summary> /// Gets the event name. /// </summary> string Name { get; } } }
Java
/* * Copyright 2016 John Grosh <john.a.grosh@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.jmusicbot.commands; import java.util.List; import java.util.concurrent.TimeUnit; import com.jagrosh.jdautilities.commandclient.CommandEvent; import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.audio.QueuedTrack; import com.jagrosh.jmusicbot.utils.FormatUtil; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.exceptions.PermissionException; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class QueueCmd extends MusicCommand { private final PaginatorBuilder builder; public QueueCmd(Bot bot) { super(bot); this.name = "queue"; this.help = "shows the current queue"; this.arguments = "[pagenum]"; this.aliases = new String[]{"list"}; this.bePlaying = true; this.botPermissions = new Permission[]{Permission.MESSAGE_ADD_REACTION,Permission.MESSAGE_EMBED_LINKS}; builder = new PaginatorBuilder() .setColumns(1) .setFinalAction(m -> {try{m.clearReactions().queue();}catch(PermissionException e){}}) .setItemsPerPage(10) .waitOnSinglePage(false) .useNumberedItems(true) .showPageNumbers(true) .setEventWaiter(bot.getWaiter()) .setTimeout(1, TimeUnit.MINUTES) ; } @Override public void doCommand(CommandEvent event) { int pagenum = 1; try{ pagenum = Integer.parseInt(event.getArgs()); }catch(NumberFormatException e){} AudioHandler ah = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler(); List<QueuedTrack> list = ah.getQueue().getList(); if(list.isEmpty()) { event.replyWarning("There is no music in the queue!" +(!ah.isMusicPlaying() ? "" : " Now playing:\n\n**"+ah.getPlayer().getPlayingTrack().getInfo().title+"**\n"+FormatUtil.embedformattedAudio(ah))); return; } String[] songs = new String[list.size()]; long total = 0; for(int i=0; i<list.size(); i++) { total += list.get(i).getTrack().getDuration(); songs[i] = list.get(i).toString(); } long fintotal = total; builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal)) .setItems(songs) .setUsers(event.getAuthor()) .setColor(event.getSelfMember().getColor()) ; builder.build().paginate(event.getChannel(), pagenum); } private String getQueueTitle(AudioHandler ah, String success, int songslength, long total) { StringBuilder sb = new StringBuilder(); if(ah.getPlayer().getPlayingTrack()!=null) sb.append("**").append(ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n").append(FormatUtil.embedformattedAudio(ah)).append("\n\n"); return sb.append(success).append(" Current Queue | ").append(songslength).append(" entries | `").append(FormatUtil.formatTime(total)).append("` ").toString(); } }
Java
import { Configuration } from "./configuration"; import { ConfigurationParser } from "./configuration-parser"; import { CustomReporterResult } from "./custom-reporter-result"; import { ExecutionDisplay } from "./execution-display"; import { ExecutionMetrics } from "./execution-metrics"; import CustomReporter = jasmine.CustomReporter; import SuiteInfo = jasmine.SuiteInfo; import RunDetails = jasmine.RunDetails; export class HtmlSpecReporter implements CustomReporter { private started: boolean = false; private finished: boolean = false; private display: ExecutionDisplay; private metrics: ExecutionMetrics; private configuration: Configuration; constructor(configuration?: Configuration) { this.configuration = ConfigurationParser.parse(configuration); this.display = new ExecutionDisplay(this.configuration); this.metrics = new ExecutionMetrics(); } public jasmineStarted(suiteInfo: SuiteInfo): void { this.started = true; this.metrics.start(suiteInfo); this.display.jasmineStarted(suiteInfo); } public jasmineDone(runDetails: RunDetails): void { this.metrics.stop(runDetails); this.display.summary(runDetails, this.metrics); this.finished = true; } public suiteStarted(result: CustomReporterResult): void { this.display.suiteStarted(result); } public suiteDone(result: CustomReporterResult): void { this.display.suiteDone(); } public specStarted(result: CustomReporterResult): void { this.metrics.startSpec(); this.display.specStarted(result); } public specDone(result: CustomReporterResult): void { this.metrics.stopSpec(result); if (result.status === "pending") { this.metrics.pendingSpecs++; this.display.pending(result); } else if (result.status === "passed") { this.metrics.successfulSpecs++; this.display.successful(result); } else if (result.status === "failed") { this.metrics.failedSpecs++; this.display.failed(result); } this.display.specDone(result); } }
Java
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.opsworks.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterEcsCluster" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeregisterEcsClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeregisterEcsClusterResult == false) return false; DeregisterEcsClusterResult other = (DeregisterEcsClusterResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeregisterEcsClusterResult clone() { try { return (DeregisterEcsClusterResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
Java
#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1beta1 import firestore_pb2_grpc from google.firestore.v1beta1 import document_pb2 from google.firestore.v1beta1 import document_pb2_grpc from google.firestore.v1beta1 import common_pb2 from google.firestore.v1beta1 import common_pb2_grpc from google.firestore.v1beta1 import write_pb2 from google.firestore.v1beta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_message(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write # here just write one as example messages = [ firestore_pb2.WriteRequest(database=database, writes = []), firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token) ] for msg in messages: yield msg def main(): fl = os.path.dirname(os.path.abspath(__file__)) fn = os.path.join(fl, 'grpc.json') with open(fn) as grpc_file: item = json.load(grpc_file) creds = item["grpc"]["Write"]["credentials"] credentials = service_account.Credentials.from_service_account_file("{}".format(creds)) scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore']) http_request = google.auth.transport.requests.Request() channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443') stub = firestore_pb2_grpc.FirestoreStub(channel) database = item["grpc"]["Write"]["database"] name = item["grpc"]["Write"]["name"] first_write = write_pb2.Write() responses = stub.Write(first_message(database, first_write)) for response in responses: print("Received message %s" % (response.stream_id)) print(response.stream_token) value_ = document_pb2.Value(string_value = "foo_boo") update = document_pb2.Document(name=name, fields={"foo":value_}) writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update) r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token)) for r in r2: print(r.write_results) if __name__ == "__main__": main()
Java
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Directory = Lucene.Net.Store.Directory; /// <summary> /// This class emulates the new Java 7 "Try-With-Resources" statement. /// Remove once Lucene is on Java 7. /// <para/> /// @lucene.internal /// </summary> [ExceptionToClassNameConvention] public sealed class IOUtils { /// <summary> /// UTF-8 <see cref="Encoding"/> instance to prevent repeated /// <see cref="Encoding.UTF8"/> lookups </summary> [Obsolete("Use Encoding.UTF8 instead.")] public static readonly Encoding CHARSET_UTF_8 = Encoding.UTF8; /// <summary> /// UTF-8 charset string. /// <para/>Where possible, use <see cref="Encoding.UTF8"/> instead, /// as using the <see cref="string"/> constant may slow things down. </summary> /// <seealso cref="Encoding.UTF8"/> public static readonly string UTF_8 = "UTF-8"; private IOUtils() // no instance { } /// <summary> /// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s /// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>, /// if one is supplied, or the first of suppressed exceptions, or completes normally.</para> /// <para>Sample usage: /// <code> /// IDisposable resource1 = null, resource2 = null, resource3 = null; /// ExpectedException priorE = null; /// try /// { /// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException /// ..do..stuff.. // May throw ExpectedException /// } /// catch (ExpectedException e) /// { /// priorE = e; /// } /// finally /// { /// IOUtils.CloseWhileHandlingException(priorE, resource1, resource2, resource3); /// } /// </code> /// </para> /// </summary> /// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param> /// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param> [Obsolete("Use DisposeWhileHandlingException(Exception, params IDisposable[]) instead.")] public static void CloseWhileHandlingException(Exception priorException, params IDisposable[] objects) { DisposeWhileHandlingException(priorException, objects); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary> /// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/> [Obsolete("Use DisposeWhileHandlingException(Exception, IEnumerable<IDisposable>) instead.")] public static void CloseWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects) { DisposeWhileHandlingException(priorException, objects); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s. Some of the /// <see cref="IDisposable"/>s may be <c>null</c>; they are /// ignored. After everything is closed, the method either /// throws the first exception it hit while closing, or /// completes normally if there were no exceptions. /// </summary> /// <param name="objects"> /// Objects to call <see cref="IDisposable.Dispose()"/> on </param> [Obsolete("Use Dispose(params IDisposable[]) instead.")] public static void Close(params IDisposable[] objects) { Dispose(objects); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s. </summary> /// <seealso cref="Dispose(IDisposable[])"/> [Obsolete("Use Dispose(IEnumerable<IDisposable>) instead.")] public static void Close(IEnumerable<IDisposable> objects) { Dispose(objects); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. /// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored. /// </summary> /// <param name="objects"> /// Objects to call <see cref="IDisposable.Dispose()"/> on </param> [Obsolete("Use DisposeWhileHandlingException(params IDisposable[]) instead.")] public static void CloseWhileHandlingException(params IDisposable[] objects) { DisposeWhileHandlingException(objects); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary> /// <seealso cref="DisposeWhileHandlingException(IEnumerable{IDisposable})"/> /// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/> [Obsolete("Use DisposeWhileHandlingException(IEnumerable<IDisposable>) instead.")] public static void CloseWhileHandlingException(IEnumerable<IDisposable> objects) { DisposeWhileHandlingException(objects); } // LUCENENET specific - added overloads starting with Dispose... instead of Close... /// <summary> /// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s /// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>, /// if one is supplied, or the first of suppressed exceptions, or completes normally.</para> /// <para>Sample usage: /// <code> /// IDisposable resource1 = null, resource2 = null, resource3 = null; /// ExpectedException priorE = null; /// try /// { /// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException /// ..do..stuff.. // May throw ExpectedException /// } /// catch (ExpectedException e) /// { /// priorE = e; /// } /// finally /// { /// IOUtils.DisposeWhileHandlingException(priorE, resource1, resource2, resource3); /// } /// </code> /// </para> /// </summary> /// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param> /// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param> public static void DisposeWhileHandlingException(Exception priorException, params IDisposable[] objects) { Exception th = null; foreach (IDisposable @object in objects) { try { if (@object != null) { @object.Dispose(); } } catch (Exception t) { AddSuppressed(priorException ?? th, t); if (th == null) { th = t; } } } if (priorException != null) { throw priorException; } else { ReThrow(th); } } /// <summary> /// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary> /// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/> public static void DisposeWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects) { Exception th = null; foreach (IDisposable @object in objects) { try { if (@object != null) { @object.Dispose(); } } catch (Exception t) { AddSuppressed(priorException ?? th, t); if (th == null) { th = t; } } } if (priorException != null) { throw priorException; } else { ReThrow(th); } } /// <summary> /// Disposes all given <see cref="IDisposable"/>s. Some of the /// <see cref="IDisposable"/>s may be <c>null</c>; they are /// ignored. After everything is closed, the method either /// throws the first exception it hit while closing, or /// completes normally if there were no exceptions. /// </summary> /// <param name="objects"> /// Objects to call <see cref="IDisposable.Dispose()"/> on </param> public static void Dispose(params IDisposable[] objects) { Exception th = null; foreach (IDisposable @object in objects) { try { if (@object != null) { @object.Dispose(); } } catch (Exception t) { AddSuppressed(th, t); if (th == null) { th = t; } } } ReThrow(th); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s. </summary> /// <seealso cref="Dispose(IDisposable[])"/> public static void Dispose(IEnumerable<IDisposable> objects) { Exception th = null; foreach (IDisposable @object in objects) { try { if (@object != null) { @object.Dispose(); } } catch (Exception t) { AddSuppressed(th, t); if (th == null) { th = t; } } } ReThrow(th); } /// <summary> /// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. /// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored. /// </summary> /// <param name="objects"> /// Objects to call <see cref="IDisposable.Dispose()"/> on </param> public static void DisposeWhileHandlingException(params IDisposable[] objects) { foreach (var o in objects) { try { if (o != null) { o.Dispose(); } } catch (Exception) { //eat it } } } /// <summary> /// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary> /// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/> public static void DisposeWhileHandlingException(IEnumerable<IDisposable> objects) { foreach (IDisposable @object in objects) { try { if (@object != null) { @object.Dispose(); } } catch (Exception) { //eat it } } } /// <summary> /// Since there's no C# equivalent of Java's Exception.AddSuppressed, we add the /// suppressed exceptions to a data field via the /// <see cref="Support.ExceptionExtensions.AddSuppressed(Exception, Exception)"/> method. /// <para/> /// The exceptions can be retrieved by calling <see cref="ExceptionExtensions.GetSuppressed(Exception)"/> /// or <see cref="ExceptionExtensions.GetSuppressedAsList(Exception)"/>. /// </summary> /// <param name="exception"> this exception should get the suppressed one added </param> /// <param name="suppressed"> the suppressed exception </param> private static void AddSuppressed(Exception exception, Exception suppressed) { if (exception != null && suppressed != null) { exception.AddSuppressed(suppressed); } } /// <summary> /// Wrapping the given <see cref="Stream"/> in a reader using a <see cref="Encoding"/>. /// Unlike Java's defaults this reader will throw an exception if your it detects /// the read charset doesn't match the expected <see cref="Encoding"/>. /// <para/> /// Decoding readers are useful to load configuration files, stopword lists or synonym files /// to detect character set problems. However, its not recommended to use as a common purpose /// reader. /// </summary> /// <param name="stream"> The stream to wrap in a reader </param> /// <param name="charSet"> The expected charset </param> /// <returns> A wrapping reader </returns> public static TextReader GetDecodingReader(Stream stream, Encoding charSet) { return new StreamReader(stream, charSet); } /// <summary> /// Opens a <see cref="TextReader"/> for the given <see cref="FileInfo"/> using a <see cref="Encoding"/>. /// Unlike Java's defaults this reader will throw an exception if your it detects /// the read charset doesn't match the expected <see cref="Encoding"/>. /// <para/> /// Decoding readers are useful to load configuration files, stopword lists or synonym files /// to detect character set problems. However, its not recommended to use as a common purpose /// reader. </summary> /// <param name="file"> The file to open a reader on </param> /// <param name="charSet"> The expected charset </param> /// <returns> A reader to read the given file </returns> public static TextReader GetDecodingReader(FileInfo file, Encoding charSet) { FileStream stream = null; bool success = false; try { stream = file.OpenRead(); TextReader reader = GetDecodingReader(stream, charSet); success = true; return reader; } finally { if (!success) { IOUtils.Dispose(stream); } } } /// <summary> /// Opens a <see cref="TextReader"/> for the given resource using a <see cref="Encoding"/>. /// Unlike Java's defaults this reader will throw an exception if your it detects /// the read charset doesn't match the expected <see cref="Encoding"/>. /// <para/> /// Decoding readers are useful to load configuration files, stopword lists or synonym files /// to detect character set problems. However, its not recommended to use as a common purpose /// reader. </summary> /// <param name="clazz"> The class used to locate the resource </param> /// <param name="resource"> The resource name to load </param> /// <param name="charSet"> The expected charset </param> /// <returns> A reader to read the given file </returns> public static TextReader GetDecodingReader(Type clazz, string resource, Encoding charSet) { Stream stream = null; bool success = false; try { stream = clazz.GetTypeInfo().Assembly.FindAndGetManifestResourceStream(clazz, resource); TextReader reader = GetDecodingReader(stream, charSet); success = true; return reader; } finally { if (!success) { IOUtils.Dispose(stream); } } } /// <summary> /// Deletes all given files, suppressing all thrown <see cref="Exception"/>s. /// <para/> /// Note that the files should not be <c>null</c>. /// </summary> public static void DeleteFilesIgnoringExceptions(Directory dir, params string[] files) { foreach (string name in files) { try { dir.DeleteFile(name); } catch (Exception) { // ignore } } } /// <summary> /// Copy one file's contents to another file. The target will be overwritten /// if it exists. The source must exist. /// </summary> public static void Copy(FileInfo source, FileInfo target) { FileStream fis = null; FileStream fos = null; try { fis = source.OpenRead(); fos = target.OpenWrite(); byte[] buffer = new byte[1024 * 8]; int len; while ((len = fis.Read(buffer, 0, buffer.Length)) > 0) { fos.Write(buffer, 0, len); } } finally { Dispose(fis, fos); } } /// <summary> /// Simple utilty method that takes a previously caught /// <see cref="Exception"/> and rethrows either /// <see cref="IOException"/> or an unchecked exception. If the /// argument is <c>null</c> then this method does nothing. /// </summary> public static void ReThrow(Exception th) { if (th != null) { if (th is System.IO.IOException) { throw th; } ReThrowUnchecked(th); } } /// <summary> /// Simple utilty method that takes a previously caught /// <see cref="Exception"/> and rethrows it as an unchecked exception. /// If the argument is <c>null</c> then this method does nothing. /// </summary> public static void ReThrowUnchecked(Exception th) { if (th != null) { throw th; } } // LUCENENET specific: Fsync is pointless in .NET, since we are // calling FileStream.Flush(true) before the stream is disposed // which means we never need it at the point in Java where it is called. // /// <summary> // /// Ensure that any writes to the given file is written to the storage device that contains it. </summary> // /// <param name="fileToSync"> The file to fsync </param> // /// <param name="isDir"> If <c>true</c>, the given file is a directory (we open for read and ignore <see cref="IOException"/>s, // /// because not all file systems and operating systems allow to fsync on a directory) </param> // public static void Fsync(string fileToSync, bool isDir) // { // // Fsync does not appear to function properly for Windows and Linux platforms. In Lucene version // // they catch this in IOException branch and return if the call is for the directory. // // In Lucene.Net the exception is UnauthorizedAccessException and is not handled by // // IOException block. No need to even attempt to fsync, just return if the call is for directory // if (isDir) // { // return; // } // var retryCount = 1; // while (true) // { // FileStream file = null; // bool success = false; // try // { // // If the file is a directory we have to open read-only, for regular files we must open r/w for the fsync to have an effect. // // See http://blog.httrack.com/blog/2013/11/15/everything-you-always-wanted-to-know-about-fsync/ // file = new FileStream(fileToSync, // FileMode.Open, // We shouldn't create a file when syncing. // // Java version uses FileChannel which doesn't create the file if it doesn't already exist, // // so there should be no reason for attempting to create it in Lucene.Net. // FileAccess.Write, // FileShare.ReadWrite); // //FileSupport.Sync(file); // file.Flush(true); // success = true; // } //#pragma warning disable 168 // catch (IOException e) //#pragma warning restore 168 // { // if (retryCount == 5) // { // throw; // } //#if !NETSTANDARD1_6 // try // { //#endif // // Pause 5 msec // Thread.Sleep(5); //#if !NETSTANDARD1_6 // } // catch (ThreadInterruptedException ie) // { // var ex = new ThreadInterruptedException(ie.ToString(), ie); // ex.AddSuppressed(e); // throw ex; // } //#endif // } // finally // { // if (file != null) // { // file.Dispose(); // } // } // if (success) // { // return; // } // retryCount++; // } // } } }
Java
// /******************************************************************************* // * Copyright 2012-2018 Esri // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // ******************************************************************************/ using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Threading; using Android.Content; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Toolkit.Internal; namespace Esri.ArcGISRuntime.Toolkit.UI.Controls { [Register("Esri.ArcGISRuntime.Toolkit.UI.Controls.LayerLegend")] public partial class LayerLegend { private ListView _listView; private Android.OS.Handler _uithread; /// <summary> /// Initializes a new instance of the <see cref="LayerLegend"/> class. /// </summary> /// <param name="context">The Context the view is running in, through which it can access resources, themes, etc.</param> public LayerLegend(Context context) : base(context ?? throw new ArgumentNullException(nameof(context))) { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="LayerLegend"/> class. /// </summary> /// <param name="context">The Context the view is running in, through which it can access resources, themes, etc.</param> /// <param name="attr">The attributes of the AXML element declaring the view.</param> public LayerLegend(Context context, IAttributeSet? attr) : base(context ?? throw new ArgumentNullException(nameof(context)), attr) { Initialize(); } [MemberNotNull(nameof(_listView), nameof(_uithread))] private void Initialize() { _uithread = new Android.OS.Handler(Context!.MainLooper!); _listView = new ListView(Context) { ClipToOutline = true, Clickable = false, ChoiceMode = ChoiceMode.None, LayoutParameters = new LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent), ScrollingCacheEnabled = false, PersistentDrawingCache = PersistentDrawingCaches.NoCache, }; AddView(_listView); } private void Refresh() { if (_listView == null) { return; } if (LayerContent == null) { _listView.Adapter = null; return; } if (LayerContent is ILoadable loadable) { if (loadable.LoadStatus != LoadStatus.Loaded) { loadable.Loaded += Layer_Loaded; loadable.LoadAsync(); return; } } var items = new ObservableCollection<LegendInfo>(); LoadRecursive(items, LayerContent, IncludeSublayers); _listView.Adapter = new LayerLegendAdapter(Context, items); _listView.SetHeightBasedOnChildren(); } private void Layer_Loaded(object sender, System.EventArgs e) { if (sender is ILoadable loadable) { loadable.Loaded -= Layer_Loaded; } _uithread.Post(Refresh); } /// <inheritdoc /> protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); // Initialize dimensions of root layout MeasureChild(_listView, widthMeasureSpec, MeasureSpec.MakeMeasureSpec(MeasureSpec.GetSize(heightMeasureSpec), MeasureSpecMode.AtMost)); // Calculate the ideal width and height for the view var desiredWidth = PaddingLeft + PaddingRight + _listView.MeasuredWidth; var desiredHeight = PaddingTop + PaddingBottom + _listView.MeasuredHeight; // Get the width and height of the view given any width and height constraints indicated by the width and height spec values var width = ResolveSize(desiredWidth, widthMeasureSpec); var height = ResolveSize(desiredHeight, heightMeasureSpec); SetMeasuredDimension(width, height); } /// <inheritdoc /> protected override void OnLayout(bool changed, int l, int t, int r, int b) { // Forward layout call to the root layout _listView.Layout(PaddingLeft, PaddingTop, _listView.MeasuredWidth + PaddingLeft, _listView.MeasuredHeight + PaddingBottom); } } }
Java
package com.google.api.ads.adwords.jaxws.v201509.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Represents a criterion belonging to a shared set. * * * <p>Java class for SharedCriterion complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SharedCriterion"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="sharedSetId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="criterion" type="{https://adwords.google.com/api/adwords/cm/v201509}Criterion" minOccurs="0"/> * &lt;element name="negative" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SharedCriterion", propOrder = { "sharedSetId", "criterion", "negative" }) public class SharedCriterion { protected Long sharedSetId; protected Criterion criterion; protected Boolean negative; /** * Gets the value of the sharedSetId property. * * @return * possible object is * {@link Long } * */ public Long getSharedSetId() { return sharedSetId; } /** * Sets the value of the sharedSetId property. * * @param value * allowed object is * {@link Long } * */ public void setSharedSetId(Long value) { this.sharedSetId = value; } /** * Gets the value of the criterion property. * * @return * possible object is * {@link Criterion } * */ public Criterion getCriterion() { return criterion; } /** * Sets the value of the criterion property. * * @param value * allowed object is * {@link Criterion } * */ public void setCriterion(Criterion value) { this.criterion = value; } /** * Gets the value of the negative property. * * @return * possible object is * {@link Boolean } * */ public Boolean isNegative() { return negative; } /** * Sets the value of the negative property. * * @param value * allowed object is * {@link Boolean } * */ public void setNegative(Boolean value) { this.negative = value; } }
Java
package de.choesel.blechwiki.model; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.UUID; /** * Created by christian on 05.05.16. */ @DatabaseTable(tableName = "komponist") public class Komponist { @DatabaseField(generatedId = true) private UUID id; @DatabaseField(canBeNull = true, uniqueCombo = true) private String name; @DatabaseField(canBeNull = true) private String kurzname; @DatabaseField(canBeNull = true, uniqueCombo = true) private Integer geboren; @DatabaseField(canBeNull = true) private Integer gestorben; public UUID getId() { return id; } public String getName() { return name; } public String getKurzname() { return kurzname; } public Integer getGeboren() { return geboren; } public Integer getGestorben() { return gestorben; } public void setId(UUID id) { this.id = id; } public void setName(String name) { this.name = name; } public void setKurzname(String kurzname) { this.kurzname = kurzname; } public void setGeboren(Integer geboren) { this.geboren = geboren; } public void setGestorben(Integer gestorben) { this.gestorben = gestorben; } }
Java
package server import ( "fmt" "math/big" "net/http" "strconv" "time" "github.com/san-lab/banketh-quorum/banketh/bots" "github.com/san-lab/banketh-quorum/banketh/cryptobank" "github.com/san-lab/banketh-quorum/banketh/data" "github.com/san-lab/banketh-quorum/lib/bank/banktypes" "github.com/san-lab/banketh-quorum/lib/db" "github.com/san-lab/banketh-quorum/lib/ethapi" ) func HandleBackoffice(w http.ResponseWriter, req *http.Request) { if !logged(w, req) { reload(w, req, "/") return } req.ParseForm() whatToShowA, ok := req.Form["whattoshow"] if !ok || whatToShowA[0] == "Cashins" { HandleCashins(w, req) return } else if whatToShowA[0] == "Cashouts" { HandleCashouts(w, req) return } else if whatToShowA[0] == "PaymentTerminations" { HandlePaymentTerminations(w, req) return } showError(w, req, "Navigation error") } func HandleCashins(w http.ResponseWriter, req *http.Request) { cashins, err := db.ReadTable(data.DBNAME, data.DBTABLECASHINS, &data.CashinT{}, "", "Time desc") if err != nil { showErrorf(w, req, "Unable to read cashin transactions table [%v]", err) return } passdata := map[string]interface{}{ "Cashins": cashins, "Currency": cryptobank.CURRENCY, } placeHeader(w, req) templates.ExecuteTemplate(w, "cashins.html", passdata) } func HandleCashouts(w http.ResponseWriter, req *http.Request) { cashouts, err := db.ReadTable(data.DBNAME, data.DBTABLECASHOUTS, &data.CashoutT{}, "", "Time desc") if err != nil { showErrorf(w, req, "Unable to read cashout transactions table [%v]", err) return } passdata := map[string]interface{}{ "Cashouts": cashouts, "Currency": cryptobank.CURRENCY, } placeHeader(w, req) templates.ExecuteTemplate(w, "cashouts.html", passdata) } func HandlePaymentTerminations(w http.ResponseWriter, req *http.Request) { paymentTerminations, err := db.ReadTable(data.DBNAME, data.DBTABLEPAYMENTTERMINATIONS, &data.PaymentTerminationT{}, "", "Time desc") if err != nil { showErrorf(w, req, "Unable to read payment terminations table [%v]", err) return } passdata := map[string]interface{}{ "PaymentTerminations": paymentTerminations, "Currency": cryptobank.CURRENCY, } placeHeader(w, req) templates.ExecuteTemplate(w, "paymentterminations.html", passdata) } func HandleManualAddFunds(w http.ResponseWriter, req *http.Request) { if !logged(w, req) { reload(w, req, "/") return } req.ParseForm() bankaccountA, ok := req.Form["bankaccount"] if !ok { showError(w, req, "Form error") return } banktridA, ok := req.Form["banktrid"] if !ok { showError(w, req, "Form error") return } amountA, ok := req.Form["amount"] if !ok { showError(w, req, "Form error") return } amount, err := strconv.ParseFloat(amountA[0], 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong amount argument %v [%v]", amountA[0], err) reload(w, req, "/backoffice") return } messageA, ok := req.Form["message"] if !ok { showError(w, req, "Form error") return } bankethaccountA, ok := req.Form["bankethaccount"] if !ok { showError(w, req, "Form error") return } bankethaccount, err := strconv.ParseUint(bankethaccountA[0], 0, 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong banketh account %v [%v]", bankethaccountA[0], err) reload(w, req, "/backoffice") return } manyaccounts, err := cryptobank.Many_accounts(ethclient) if int64(bankethaccount) >= manyaccounts { pushAlertf(w, req, ALERT_DANGER, "Account %v does not exist in banketh", bankethaccountA[0]) reload(w, req, "/backoffice") return } account, err := cryptobank.Read_account(ethclient, bankethaccount) if err != nil { showErrorf(w, req, "Error reading account %v from ethereum node [%v]", bankethaccount, err) return } bankethamount, _ := big.NewFloat(0).Mul(big.NewFloat(amount), big.NewFloat(cryptobank.PRECISION)).Int(nil) txHash, err := cryptobank.Add_funds(ethclient, int64(bankethaccount), bankethamount) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Add_funds method call failed! [%v]", err) reload(w, req, "/backoffice") return } newT := data.CashinT{ BankTrID: banktridA[0], Time: db.MyTime(time.Now()), BankAccount: bankaccountA[0], BankAmount: amount, Message: messageA[0], ToAddress: account.Owner, ToAccount: int64(bankethaccount), BankethAmount: big.NewInt(0).Set(bankethamount), AddFundsOrSubmitPaymentHash: txHash, ReturnTrID: "", ReturnMessage: "", Status: data.CASHIN_STATUS_MANUALLY_FINISHED, } err = db.WriteEntry(data.DBNAME, data.DBTABLECASHINS, newT) if err != nil { errMsg := fmt.Sprintf("Sent an addFunds call (hash %v) but could not write it to DB! [%v]", err) pushAlert(w, req, ALERT_DANGER, errMsg) db.RegisterEvent(data.DBNAME, data.DBTABLEEVENTS, db.EVENT_MANUAL_INTERVENTION_NEEDED, errMsg+fmt.Sprintf(" - Need manual intervention, we should record the transaction in the DB; projected transaction was %v", newT)) reload(w, req, "/backoffice") return } } func HandleManualAddTransfer(w http.ResponseWriter, req *http.Request) { if !logged(w, req) { reload(w, req, "/") return } req.ParseForm() banktridA, ok := req.Form["banktrid"] if !ok { showError(w, req, "Form error") return } bankaccountA, ok := req.Form["bankaccount"] if !ok { showError(w, req, "Form error") return } amountA, ok := req.Form["amount"] if !ok { showError(w, req, "Form error") return } amount, err := strconv.ParseFloat(amountA[0], 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong amount argument %v [%v]", amountA[0], err) reload(w, req, "/backoffice") return } typeA, ok := req.Form["type"] if !ok { showError(w, req, "Form error") return } messageA, ok := req.Form["message"] if !ok { showError(w, req, "Form error") return } newTransfer := banktypes.BankTransferT{ TransferID: banktridA[0], Time: db.MyTime(time.Now()), Account: bankaccountA[0], Amount: amount, Type: typeA[0], Message: messageA[0], } d, err := db.ConnectDB(data.DBNAME) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Error connecting to the database [%v]", err) reload(w, req, "/backoffice") return } not_ok := bots.Process_inbound_transfer(d, &newTransfer) if not_ok { pushAlertf(w, req, ALERT_DANGER, "Error processing manual inbound transfer - pls check the console log") reload(w, req, "/backoffice") return } } func HandleManualRemoveFunds(w http.ResponseWriter, req *http.Request) { if !logged(w, req) { reload(w, req, "/") return } req.ParseForm() var redeemFundsHash ethapi.Hash var err error redeemFundsHashA, ok := req.Form["redeemfundshash"] if ok && redeemFundsHashA[0] != "" { redeemFundsHash, err = ethapi.String_to_hash(redeemFundsHashA[0]) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Bad hash %v [%v]", redeemFundsHashA[0], err) reload(w, req, "/backoffice") return } } bankethaccountA, ok := req.Form["bankethaccount"] if !ok { showError(w, req, "Form error") return } bankethaccount, err := strconv.ParseUint(bankethaccountA[0], 0, 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong banketh account %v [%v]", bankethaccountA[0], err) reload(w, req, "/backoffice") return } manyaccounts, err := cryptobank.Many_accounts(ethclient) if int64(bankethaccount) >= manyaccounts { pushAlertf(w, req, ALERT_DANGER, "Account %v does not exist in banketh", bankethaccountA[0]) reload(w, req, "/backoffice") return } account, err := cryptobank.Read_account(ethclient, bankethaccount) if err != nil { showErrorf(w, req, "Error reading account %v from ethereum node [%v]", bankethaccount, err) return } amountA, ok := req.Form["amount"] if !ok { showError(w, req, "Form error") return } amount, err := strconv.ParseFloat(amountA[0], 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong amount argument %v [%v]", amountA[0], err) reload(w, req, "/backoffice") return } bankethamount, _ := big.NewFloat(0).Mul(big.NewFloat(amount), big.NewFloat(cryptobank.PRECISION)).Int(nil) redemptionModeA, ok := req.Form["redemptionmode"] if !ok { showError(w, req, "Form error") return } redemptionMode, err := strconv.ParseUint(redemptionModeA[0], 0, 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong redemption mode %v [%v]", redemptionModeA[0], err) reload(w, req, "/backoffice") return } routingInfoA, given := req.Form["routinginfo"] if given { if len(routingInfoA[0]) > 32 { pushAlertf(w, req, ALERT_DANGER, "Wrong routing info (%v)", routingInfoA[0]) reload(w, req, "/backoffice") return } } var errorCode int64 errorCodeA, given := req.Form["errorcode"] if given { errorCode, err = strconv.ParseInt(errorCodeA[0], 0, 64) if err != nil { pushAlertf(w, req, ALERT_DANGER, "Wrong redemption error code (%v)", errorCodeA[0]) reload(w, req, "/backoffice") return } } /* redemptionCodeSent := big.NewInt(0) redemptionCodeSentA, given := req.Form["redemptioncodesent"] if given { redemptionCodeSent, ok = redemptionCodeSent.SetString(redemptionCodeSentA[0], 0) if !ok { pushAlertf(w, req, ALERT_DANGER, "Wrong redemption code (%v)", redemptionCodeSentA[0]) reload(w, req, "/backoffice") return } } */ bankaccountA, _ := req.Form["bankaccount"] banktridA, _ := req.Form["banktrid"] messageA, _ := req.Form["message"] txHash, err := cryptobank.Remove_funds(ethclient, int64(bankethaccount), bankethamount, redeemFundsHash, errorCode) /* txHash, err := cryptobank.Remove_funds(ethclient, int64(bankethaccount), bankethamount, redemptionCodeSent) */ if err != nil { pushAlertf(w, req, ALERT_DANGER, "Remove_funds method call failed! [%v]", err) reload(w, req, "/backoffice") return } newT := data.CashoutT{ RedeemFundsHash: redeemFundsHash, Time: db.MyTime(time.Now()), FromAccount: int64(bankethaccount), FromAddress: account.Owner, BankethAmount: big.NewInt(0).Set(bankethamount), RedemptionMode: redemptionMode, RoutingInfo: routingInfoA[0], ErrorCode: errorCode, RemoveFundsHash: txHash, // MakeTransferHash: // Not neccessary, since this is a known cashout BankAccount: bankaccountA[0], BankAmount: amount, BankTrID: banktridA[0], Message: messageA[0], Status: data.CASHOUT_STATUS_MANUALLY_FINISHED, } err = db.WriteEntry(data.DBNAME, data.DBTABLECASHOUTS, newT) if err != nil { errMsg := fmt.Sprintf("Sent an remove_funds call (hash %v) but could not write it to DB! [%v]", err) pushAlert(w, req, ALERT_DANGER, errMsg) db.RegisterEvent(data.DBNAME, data.DBTABLEEVENTS, db.EVENT_MANUAL_INTERVENTION_NEEDED, errMsg+fmt.Sprintf(" - Need manual intervention, we should record the transaction in the DB; projected transaction was %v", newT)) reload(w, req, "/backoffice") return } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>OpenNI 1.5.8: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="OpenNILogo.bmp"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">OpenNI 1.5.8 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacexn.html">xn</a></li><li class="navelem"><a class="el" href="classxn_1_1_image_generator.html">ImageGenerator</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">xn::ImageGenerator Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a8ee96495ace6ee2369c9255409cca2b9">AddNeededNode</a>(ProductionNode &amp;needed)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#ae40a63959249614fa7f9a107e5557d81">AddRef</a>()</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a6c925e2cc848841a566eebb27275ef6b">Create</a>(Context &amp;context, Query *pQuery=NULL, EnumerationErrors *pErrors=NULL)</td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a23866c5ad6a10efc2070acbb00470874">Generator</a>(XnNodeHandle hNode=NULL)</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#a9f24a82e98e1421aab4eb71f244f7c37">Generator</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#aa026cae7475aa794aad3cdfaa7d5c726">GetAlternativeViewPointCap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#ae99917e5a3c47578eadadea85ed5e4de">GetAlternativeViewPointCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a96b92b1c193e6d9ac08ea06438668bc3">GetAntiFlickerCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a648c912c117e483ce5c36c50a3cf518c">GetAutoExposureCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a7eae2b728ea6bf591f8987426af6b1b8">GetBacklightCompensationCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#ad74d20839b4ce0de02688e2333049f7a">GetBrightnessCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a7af5b329c639fa6ec66610d3eb882e2e">GetBytesPerPixel</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a84a8fe5b2f56cbc97087529f4c15af77">GetContext</a>(Context &amp;context) const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#ab2ad46e24e4e40ab3ff89ecbac1c332a">GetContext</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#ad88c3b6d477530661c50e52322f68872">GetContrastCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#aa6d8779f6efb6d02fe0be6093e277f7c">GetCroppingCap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a123e60e70cfd477f142e2d96eca649fc">GetCroppingCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a1dd4f7f779f636b7c984cda1edddff02">GetData</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#a5b6c7e53de6b4d459f3e54ccfb81c31e">GetDataSize</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a158c1c8a60ef1eac1fc24ad67024a327">GetErrorStateCap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#af6f5e265c05c32d0652a05dba99331b3">GetErrorStateCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a24e4f2800adca3684ab5ac0821924e5f">GetExposureCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a5cffd52f9b19340afbdb92259d880720">GetFocusCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a5e819081604760a7690a11a20c53856a">GetFrameID</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#ac78aa3433bef155939b0dc43f37e9e0d">GetFrameSyncCap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a2e4eee068a2a915288cb37788dd995a1">GetFrameSyncCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#acd6b97ff72c36c29b7e68ac23a0947c9">GetGainCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#ae73d9805b68b87150ee6b8f1a0ef6c5c">GetGammaCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a4a4ba15b066f3649e1ea67cd3c4ddd63">GetGeneralIntCap</a>(const XnChar *strCapability)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#adfb77adf7676bc13cd234e57fd2a8af1">GetGeneralProperty</a>(const XnChar *strName, XnUInt32 nBufferSize, void *pBuffer) const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#afe501e7330839a3655e87ac781fd7499">GetGrayscale16ImageMap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a65fc9baf5295524f55d67dbdce1430b3">GetGrayscale8ImageMap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a7451f117eee7f28a1c9f4a3b094611ca">GetHandle</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a8e603f389f9e393c0847f48d1fc77cf5">GetHueCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a93eb06e873cb55bbd1c03d34b195608c">GetImageMap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a7c68542292cb6c6054b7f62cdf695b0b">GetInfo</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#abf6ef51084c94c8e45d7f3a22e015546">GetIntProperty</a>(const XnChar *strName, XnUInt64 &amp;nValue) const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a2d2fde7c23c7549cf95c134ac8348621">GetIrisCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a7c3f728018bea1549fd0739d800d6e68">GetLowLightCompensationCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a1fd1a64c376d7a47b2951bd996939644">GetMapOutputMode</a>(XnMapOutputMode &amp;OutputMode) const </td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#addc360efd421476ffde0ddfbf3ada135">GetMetaData</a>(ImageMetaData &amp;metaData) const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a162ee01b3483dcf71075398e4a0bb948">GetMirrorCap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#a67018dd9cc900520937547f747094576">GetMirrorCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#ae9e08bd23c07bf858c7f1ec1b3b658c4">GetName</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a5967318797a653e55fdc8481c402455e">GetPanCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a30dc165c0c6fce19a1c871867cb6d764">GetPixelFormat</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#ac8fb89389a77471200315aa3daa3952d">GetRealProperty</a>(const XnChar *strName, XnDouble &amp;dValue) const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a34b7c4ba1758149c83403c19084f4e45">GetRGB24ImageMap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a89cb3e534c188aed7223e8a48372e4ed">GetRollCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a7941a39b9033bbc1879510dcbd17a782">GetSaturationCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#ab9f8accc14097086dec3cde211ed0956">GetSharpnessCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a83cc813b9359238a2bc3a4d9595451c2">GetStringProperty</a>(const XnChar *strName, XnChar *csValue, XnUInt32 nBufSize) const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a1141e5efac972a65f03a17525b314c13">GetSupportedMapOutputModes</a>(XnMapOutputMode *aModes, XnUInt32 &amp;nCount) const </td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a50a6f2732e27eb270966ff2aca7f82f1">GetSupportedMapOutputModesCount</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a319ba695c9a3b3b617af39a8e9f9d2c0">GetTiltCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a25ac36419b9761a70768cc59330330a2">GetTimestamp</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#ac4584569475826bd69306e93b5dbdd4f">GetWhiteBalanceCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a0bb971192a8946e21981423c1deb0542">GetYUV422ImageMap</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a53d574cbcca2026008127deec244650b">GetZoomCap</a>()</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a36ef73a85b81c02b094b99342ff8979c">ImageGenerator</a>(XnNodeHandle hNode=NULL)</td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a6ff334a06de0e56017cdcf2a114cea07">ImageGenerator</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a26574447d96527d1a9d79994e550037f">IsCapabilitySupported</a>(const XnChar *strCapabilityName) const </td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#a46b2960e843339296201682c04c02b5d">IsDataNew</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a5b1f69de8cfac0767729a4584778d7cf">IsGenerating</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#ab1d6e18ad5169afec58dde1f3cf4f8bf">IsNewDataAvailable</a>(XnUInt64 *pnTimestamp=NULL) const </td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a2be4be723adc6b851c89534550fe4466">IsPixelFormatSupported</a>(XnPixelFormat Format) const </td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a3927cf50a70b01c6a57be2e3cf976269">IsValid</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a28a13885c815a05f93e2c661e5ac380d">LockedNodeEndChanges</a>(XnLockHandle hLock)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a13b8caa654da8dae4767648593c217d5">LockedNodeStartChanges</a>(XnLockHandle hLock)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#ad4e631318f4190de2d12e57525283d8f">LockForChanges</a>(XnLockHandle *phLock)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#ab965e633e37529450548cc3d3951a451">MapGenerator</a>(XnNodeHandle hNode=NULL)</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a9eae3f772388e3622b5dab6133c619ee">MapGenerator</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a82e82d31752ea3ac4c12d303c2a1d613">NodeWrapper</a>(XnNodeHandle hNode)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a734a00bdf029ea60e97d72c16605181a">NodeWrapper</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a30a130aa42cfca995d97cf59204ee5f9">operator XnNodeHandle</a>() const </td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#adfd9b28dd0f715da3ee73f39d2a40bac">operator!=</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a9532d1cbeb5f4d5f76d701a737f7512c">operator=</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#aedd041d6c7100d869e678d94fd39e1cd">operator==</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a12ed2ea37cdaf7dc48f6eb589215c178">ProductionNode</a>(XnNodeHandle hNode=NULL)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#aa8d9e12dc9dd12040513442a399f72c5">ProductionNode</a>(const NodeWrapper &amp;other)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#a5fc2c00997d7e827ce1e86d7b89ec2f1">RegisterToGenerationRunningChange</a>(StateChangedHandler handler, void *pCookie, XnCallbackHandle &amp;hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a282df4d2ddb58e5dc1717c8ceaacd5c9">RegisterToMapOutputModeChange</a>(StateChangedHandler handler, void *pCookie, XnCallbackHandle &amp;hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#a8fcad557eda5746a7f974e51c70bb324">RegisterToNewDataAvailable</a>(StateChangedHandler handler, void *pCookie, XnCallbackHandle &amp;hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a06f084d8db3ed54d1a61ba83d9b5c143">RegisterToPixelFormatChange</a>(StateChangedHandler handler, void *pCookie, XnCallbackHandle &amp;hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#ad94e45cb0bbd21223ed17e77c6893ca6">Release</a>()</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a15178408fda6623a9f6b6e3cae74fea4">RemoveNeededNode</a>(ProductionNode &amp;needed)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a32b34f2102078fbbf6719ac473d988a1">SetGeneralProperty</a>(const XnChar *strName, XnUInt32 nBufferSize, const void *pBuffer)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#af4873f95c91d4c4381a3ca127b791b27">SetHandle</a>(XnNodeHandle hNode)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a6796677af3d968d786d9094d33c6d9f1">SetIntProperty</a>(const XnChar *strName, XnUInt64 nValue)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#aea291fb67aea2d2d21d7b0b159884f9d">SetMapOutputMode</a>(const XnMapOutputMode &amp;OutputMode)</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a1297b84dcc77a2e81300d5fa17b3efec">SetPixelFormat</a>(XnPixelFormat Format)</td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a0b026a014056ab654859f14fe9a1408e">SetRealProperty</a>(const XnChar *strName, XnDouble dValue)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a21b665cca28349b53a3a2ff62355aab5">SetStringProperty</a>(const XnChar *strName, const XnChar *strValue)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a4fa8a933a96765b30537b5203da3381e">StartGenerating</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_generator.html#ae955127df36f3c71e76bdc5f2e383065">StopGenerating</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#ab8082cf957501ca1d7adcce6a5a4b737">TakeOwnership</a>(XnNodeHandle hNode)</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_production_node.html#a57bd03ecd194daab7aa4aada2bc95725">UnlockForChanges</a>(XnLockHandle hLock)</td><td class="entry"><a class="el" href="classxn_1_1_production_node.html">xn::ProductionNode</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a4ef03272d55e2146ae2b0f17db317d38">UnregisterFromGenerationRunningChange</a>(XnCallbackHandle hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_map_generator.html#a5767b2cddd43f0af982306e6693027ef">UnregisterFromMapOutputModeChange</a>(XnCallbackHandle hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_map_generator.html">xn::MapGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#a9f9789cecbcc0e43ecf63817e21ac6da">UnregisterFromNewDataAvailable</a>(XnCallbackHandle hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_image_generator.html#a01a8bb5d0285491222b9db40922f07f9">UnregisterFromPixelFormatChange</a>(XnCallbackHandle hCallback)</td><td class="entry"><a class="el" href="classxn_1_1_image_generator.html">xn::ImageGenerator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classxn_1_1_generator.html#aaf3162a87a79a05fa655f344c835fa2e">WaitAndUpdateData</a>()</td><td class="entry"><a class="el" href="classxn_1_1_generator.html">xn::Generator</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html#a3d43e803c19305dbf8af15281cfa30ff">~NodeWrapper</a>()</td><td class="entry"><a class="el" href="classxn_1_1_node_wrapper.html">xn::NodeWrapper</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Thu Jun 11 2015 12:31:40 for OpenNI 1.5.8 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
Java
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/first_run/first_run.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/strings/string_piece.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run_internal.h" #include "chrome/browser/importer/importer_host.h" #include "chrome/browser/process_singleton.h" #include "chrome/browser/shell_integration.h" #include "chrome/common/chrome_switches.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/master_preferences.h" #include "content/public/common/result_codes.h" #include "googleurl/src/gurl.h" #include "ui/base/ui_base_switches.h" namespace first_run { namespace internal { bool IsOrganicFirstRun() { // We treat all installs as organic. return true; } // TODO(port): This is just a piece of the silent import functionality from // ImportSettings for Windows. It would be nice to get the rest of it ported. bool ImportBookmarks(const base::FilePath& import_bookmarks_path) { const CommandLine& cmdline = *CommandLine::ForCurrentProcess(); CommandLine import_cmd(cmdline.GetProgram()); // Propagate user data directory switch. if (cmdline.HasSwitch(switches::kUserDataDir)) { import_cmd.AppendSwitchPath(switches::kUserDataDir, cmdline.GetSwitchValuePath(switches::kUserDataDir)); } // Since ImportSettings is called before the local state is stored on disk // we pass the language as an argument. GetApplicationLocale checks the // current command line as fallback. import_cmd.AppendSwitchASCII(switches::kLang, g_browser_process->GetApplicationLocale()); import_cmd.CommandLine::AppendSwitchPath(switches::kImportFromFile, import_bookmarks_path); // The importer doesn't need to do any background networking tasks so disable // them. import_cmd.CommandLine::AppendSwitch(switches::kDisableBackgroundNetworking); // Time to launch the process that is going to do the import. We'll wait // for the process to return. base::LaunchOptions options; options.wait = true; return base::LaunchProcess(import_cmd, options, NULL); } base::FilePath MasterPrefsPath() { // The standard location of the master prefs is next to the chrome binary. base::FilePath master_prefs; if (!PathService::Get(base::DIR_EXE, &master_prefs)) return base::FilePath(); return master_prefs.AppendASCII(installer::kDefaultMasterPrefs); } } // namespace internal } // namespace first_run
Java
package request import ( "bytes" "encoding/json" "io/ioutil" ) // A Handlers provides a collection of handlers for various stages of handling requests. type Handlers struct { RequestHandler func(*Request, *interface{}) error ResponseHandler func(*Request, *interface{}) error } // RequestHandler encodes a structure into a JSON string func RequestHandler(request *Request, input *interface{}) error { jsonstr, err := json.Marshal(&input) request.HTTPRequest.Body = ioutil.NopCloser(bytes.NewBuffer(jsonstr)) return err } // ResponseHandler decodes a JSON string into a structure. func ResponseHandler(request *Request, output *interface{}) error { return json.Unmarshal(request.Body, &output) } // ListResponseHandler extracts results from a JSON envelope and decodes them into a structure. // https://docs.atlas.mongodb.com/api/#lists func ListResponseHandler(request *Request, output *interface{}) error { var objmap map[string]*json.RawMessage err := json.Unmarshal(request.Body, &objmap) if err != nil { return err } return json.Unmarshal(*objmap["results"], &output) }
Java
package org.judal.examples.java.model.array; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import javax.jdo.JDOException; import org.judal.storage.DataSource; import org.judal.storage.EngineFactory; import org.judal.storage.java.ArrayRecord; import org.judal.storage.relational.RelationalDataSource; /** * Extend ArrayRecord in order to create model classes manageable by JUDAL. * Add your getters and setters for database fields. */ public class Student extends ArrayRecord { private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "student"; public Student() throws JDOException { this(EngineFactory.getDefaultRelationalDataSource()); } public Student(RelationalDataSource dataSource) throws JDOException { super(dataSource, TABLE_NAME); } @Override public void store(DataSource dts) throws JDOException { // Generate the student Id. from a sequence if it is not provided if (isNull("id_student")) setId ((int) dts.getSequence("seq_student").nextValue()); super.store(dts); } public int getId() { return getInt("id_student"); } public void setId(final int id) { put("id_student", id); } public String getFirstName() { return getString("first_name"); } public void setFirstName(final String firstName) { put("first_name", firstName); } public String getLastName() { return getString("last_name"); } public void setLastName(final String lastName) { put("last_name", lastName); } public Calendar getDateOfBirth() { return getCalendar("date_of_birth"); } public void setDateOfBirth(final Calendar dob) { put("date_of_birth", dob); } public void setDateOfBirth(final String yyyyMMdd) throws ParseException { SimpleDateFormat dobFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = new GregorianCalendar(); cal.setTime(dobFormat.parse(yyyyMMdd)); setDateOfBirth(cal); } public byte[] getPhoto() { return getBytes("photo"); } public void setPhoto(final byte[] photoData) { put("photo", photoData); } }
Java
/* * Bean Java VM * Copyright (C) 2005-2015 Christian Lins <christian@lins.me> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <debug.h> #include <vm.h> void do_IINC_WIDE(Thread *thread, int index, int value) { /* Increment variable in local variable array */ } /* * Increments the variable specified by the first operand (index) * by the int value of the seconds operand. */ void do_IINC(Thread *thread) { dbgmsg("IINC"); int index, value; index = Get1ByteOperand(current_frame(thread)); /* Increments IP by one */ value = Get1ByteOperand(current_frame(thread)); /* Increments IP by one */ do_IINC_WIDE(thread, index, value); }
Java
/* * Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.http.apache.client.impl; import com.amazonaws.ClientConfiguration; import com.amazonaws.http.settings.HttpClientSettings; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ApacheConnectionManagerFactoryTest { private final ApacheConnectionManagerFactory factory = new ApacheConnectionManagerFactory(); @Test public void validateAfterInactivityMillis_RespectedInConnectionManager() { final int validateAfterInactivity = 1234; final HttpClientSettings httpClientSettings = HttpClientSettings.adapt(new ClientConfiguration() .withValidateAfterInactivityMillis(validateAfterInactivity)); final PoolingHttpClientConnectionManager connectionManager = (PoolingHttpClientConnectionManager) factory.create(httpClientSettings); assertEquals(validateAfterInactivity, connectionManager.getValidateAfterInactivity()); } }
Java
using IntelliTect.Coalesce.CodeGeneration.Generation; using IntelliTect.Coalesce.Tests.Util; using IntelliTect.Coalesce.Validation; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace IntelliTect.Coalesce.CodeGeneration.Tests { public class CodeGenTestBase { protected GenerationExecutor BuildExecutor() { return new GenerationExecutor( new Configuration.CoalesceConfiguration { WebProject = new Configuration.ProjectConfiguration { RootNamespace = "MyProject" } }, Microsoft.Extensions.Logging.LogLevel.Information ); } protected async Task AssertSuiteOutputCompiles(IRootGenerator suite) { var project = new DirectoryInfo(Directory.GetCurrentDirectory()) .FindFileInAncestorDirectory("IntelliTect.Coalesce.CodeGeneration.Tests.csproj") .Directory; var suiteName = suite.GetType().Name; suite = suite .WithOutputPath(Path.Combine(project.FullName, "out", suiteName)); var validationResult = ValidateContext.Validate(suite.Model); Assert.Empty(validationResult.Where(r => r.IsError)); await suite.GenerateAsync(); var generators = suite .GetGeneratorsFlattened() .OfType<IFileGenerator>() .Where(g => g.EffectiveOutputPath.EndsWith(".cs")) .ToList(); var tasks = generators.Select(gen => (Generator: gen, Output: gen.GetOutputAsync())); await Task.WhenAll(tasks.Select(t => t.Output )); var dtoFiles = tasks .Select((task) => CSharpSyntaxTree.ParseText( SourceText.From(new StreamReader(task.Output.Result).ReadToEnd()), path: task.Generator.EffectiveOutputPath )) .ToArray(); var comp = ReflectionRepositoryFactory.GetCompilation(dtoFiles); AssertSuccess(comp); } protected void AssertSuccess(CSharpCompilation comp) { var errors = comp .GetDiagnostics() .Where(d => d.Severity >= Microsoft.CodeAnalysis.DiagnosticSeverity.Error); Assert.All(errors, error => { var loc = error.Location; Assert.False(true, "\"" + error.ToString() + $"\" near:```\n" + loc.SourceTree.ToString().Substring(loc.SourceSpan.Start, loc.SourceSpan.Length) + "\n```" ); }); } } }
Java
using System.ComponentModel; using AcceptFramework.Domain.Evaluation; namespace AcceptFramework.Repository.Evaluation { [DataObject] public class EvaluationParagraphScoringRepository : RepositoryBase<EvaluationParagraphScoring> { } }
Java
import sys sys.path.append("helper") import web from helper import session web.config.debug = False urls = ( "/", "controller.start.index", "/1", "controller.start.one", "/2", "controller.start.two", ) app = web.application(urls, globals()) sessions = session.Sessions() if __name__ == "__main__": app.run()
Java
#!/bin/sh # # Copyright 2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" SRC_DIR=${SCRIPT_DIR} SPV_DIR=${SCRIPT_DIR}/../../../assets/shaders SELF_INC_DIR=${SCRIPT_DIR} SELF_INC_DIR=$(realpath --relative-to=${SCRIPT_DIR} ${SELF_INC_DIR}) VKEX_INC_DIR=$(realpath --relative-to=${SCRIPT_DIR} ${SRC_DIR}/..) CAS_INC_DIR=$(realpath --relative-to=${SCRIPT_DIR} ${SRC_DIR}/../../../third_party/FidelityFX/FFX_CAS/ffx-cas-headers) echo ${VKEX_INC_DIR} HLSL_FILES=(draw_cb.hlsl draw_standard.hlsl) for src_file in "${HLSL_FILES[@]}" do echo -e "\nCompiling ${src_file}" base_name=$(basename -s .hlsl ${src_file}) hlsl_file=${SRC_DIR}/${src_file} vs_spv=${SPV_DIR}/${base_name}.vs.spv ps_spv=${SPV_DIR}/${base_name}.ps.spv cmd="dxc -spirv -T vs_6_0 -E vsmain -fvk-use-dx-layout -Fo ${vs_spv} -I ${SELF_INC_DIR} -I ${VKEX_INC_DIR} ${hlsl_file}" echo ${cmd} eval ${cmd} cmd="dxc -spirv -T ps_6_0 -E psmain -fvk-use-dx-layout -Fo ${ps_spv} -I ${SELF_INC_DIR} -I ${VKEX_INC_DIR} ${hlsl_file}" echo ${cmd} eval ${cmd} done HLSL_COMPUTE_FILES=(cas.hlsl checkerboard_upscale.hlsl copy_texture.hlsl image_delta.hlsl) for src_file in "${HLSL_COMPUTE_FILES[@]}" do echo -e "\nCompiling ${src_file}" base_name=$(basename -s .hlsl ${src_file}) hlsl_file=${SRC_DIR}/${src_file} cs_spv=${SPV_DIR}/${base_name}.cs.spv cmd="dxc -spirv -T cs_6_0 -E csmain -fvk-use-dx-layout -Fo ${cs_spv} -I ${SELF_INC_DIR} -I ${VKEX_INC_DIR} -I ${CAS_INC_DIR} ${hlsl_file}" echo ${cmd} eval ${cmd} done read -p "Press enter to continue" nothing
Java
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/core/client/AWSError.h> #include <aws/redshift/RedshiftErrorMarshaller.h> #include <aws/redshift/RedshiftErrors.h> using namespace Aws::Client; using namespace Aws::Redshift; AWSError<CoreErrors> RedshiftErrorMarshaller::FindErrorByName(const char* errorName) const { AWSError<CoreErrors> error = RedshiftErrorMapper::GetErrorForName(errorName); if(error.GetErrorType() != CoreErrors::UNKNOWN) { return error; } return AWSErrorMarshaller::FindErrorByName(errorName); }
Java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_10.html">Class Test_AbaRouteValidator_10</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_20655_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_10.html?line=15785#src-15785" >testAbaNumberCheck_20655_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:39:52 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_20655_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=5501#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
Java
package org.spincast.core.routing; import java.util.List; import org.spincast.core.exchange.RequestContext; /** * The result of the router, when asked to find matches for * a request. */ public interface RoutingResult<R extends RequestContext<?>> { /** * The handlers matching the route (a main handler + filters, if any), * in order they have to be called. */ public List<RouteHandlerMatch<R>> getRouteHandlerMatches(); /** * The main route handler and its information, from the routing result. */ public RouteHandlerMatch<R> getMainRouteHandlerMatch(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package king.flow.common; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.File; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import king.flow.action.business.ShowClockAction; import king.flow.data.TLSResult; import king.flow.view.Action; import king.flow.view.Action.CleanAction; import king.flow.view.Action.EjectCardAction; import king.flow.view.Action.WithdrawCardAction; import king.flow.view.Action.EncryptKeyboardAction; import king.flow.view.Action.HideAction; import king.flow.view.Action.InsertICardAction; import king.flow.view.Action.LimitInputAction; import king.flow.view.Action.MoveCursorAction; import king.flow.view.Action.NumericPadAction; import king.flow.view.Action.OpenBrowserAction; import king.flow.view.Action.PlayMediaAction; import king.flow.view.Action.PlayVideoAction; import king.flow.view.Action.PrintPassbookAction; import king.flow.view.Action.RunCommandAction; import king.flow.view.Action.RwFingerPrintAction; import king.flow.view.Action.SetFontAction; import king.flow.view.Action.SetPrinterAction; import king.flow.view.Action.ShowComboBoxAction; import king.flow.view.Action.ShowGridAction; import king.flow.view.Action.ShowTableAction; import king.flow.view.Action.Swipe2In1CardAction; import king.flow.view.Action.SwipeCardAction; import king.flow.view.Action.UploadFileAction; import king.flow.view.Action.UseTipAction; import king.flow.view.Action.VirtualKeyboardAction; import king.flow.view.Action.WriteICardAction; import king.flow.view.ComponentEnum; import king.flow.view.DefinedAction; import king.flow.view.DeviceEnum; import king.flow.view.JumpAction; import king.flow.view.MsgSendAction; /** * * @author LiuJin */ public class CommonConstants { public static final String APP_STARTUP_ENTRY = "bank.exe"; public static final Charset UTF8 = Charset.forName("UTF-8"); static final File[] SYS_ROOTS = File.listRoots(); public static final int DRIVER_COUNT = SYS_ROOTS.length; public static final String XML_NODE_PREFIX = "N_"; public static final String REVERT = "re_"; public static final String BID = "bid"; public static final String UID_PREFIX = "<" + TLSResult.UID + ">"; public static final String UID_AFFIX = "</" + TLSResult.UID + ">"; public static final String DEFAULT_DATE_FORMATE = "yyyy-MM-dd"; public static final String VALID_BANK_CARD = "validBankCard"; public static final String BALANCED_PAY_MAC = "balancedPayMAC"; public static final String CANCEL_ENCRYPTION_KEYBOARD = "[CANCEL]"; public static final String QUIT_ENCRYPTION_KEYBOARD = "[QUIT]"; public static final String INVALID_ENCRYPTION_LENGTH = "encryption.keyboard.type.length.prompt"; public static final String TIMEOUT_ENCRYPTION_TYPE = "encryption.keyboard.type.timeout.prompt"; public static final String ERROR_ENCRYPTION_TYPE = "encryption.keyboard.type.fail.prompt"; public static final int CONTAINER_KEY = Integer.MAX_VALUE; public static final int NORMAL = 0; public static final int ABNORMAL = 1; public static final int BALANCE = 12345; public static final int RESTART_SIGNAL = 1; public static final int DOWNLOAD_KEY_SIGNAL = 1; public static final int UPDATE_SIGNAL = 1; public static final int WATCHDOG_CHECK_INTERVAL = 5; public static final String VERSION; public static final long DEBUG_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(3); public static final long RUN_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(1); // public static final String VERSION = Paths.get(".").toAbsolutePath().normalize().toString(); static { String workingPath = System.getProperty("user.dir"); final int lastIndexOf = workingPath.lastIndexOf('_'); if (lastIndexOf != -1 && lastIndexOf < workingPath.length() - 1) { VERSION = workingPath.substring(lastIndexOf + 1); } else { VERSION = "Unknown"; } } /* JMX configuration */ private static String getJmxRmiUrl(int port) { return "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi"; } public static final int APP_JMX_RMI_PORT = 9998; public static final String APP_JMX_RMI_URL = getJmxRmiUrl(APP_JMX_RMI_PORT); public static final int WATCHDOG_JMX_RMI_PORT = 9999; public static final String WATCHDOG_JMX_RMI_URL = getJmxRmiUrl(WATCHDOG_JMX_RMI_PORT); /* system variable pattern */ public static final String SYSTEM_VAR_PATTERN = "\\$\\{(_?\\p{Alpha}+_\\p{Alpha}+)+\\}"; public static final String TEXT_MINGLED_SYSTEM_VAR_PATTERN = ".*" + SYSTEM_VAR_PATTERN + ".*"; public static final String TERMINAL_ID_SYS_VAR = "TERMINAL_ID"; /* swing default config */ public static final int DEFAULT_TABLE_ROW_COUNT = 15; public static final int TABLE_ROW_HEIGHT = 25; public static final int DEFAULT_VIDEO_REPLAY_INTERVAL_SECOND = 20; /* packet header ID */ public static final int GENERAL_MSG_CODE = 0; //common message public static final int REGISTRY_MSG_CODE = 1; //terminal registration message public static final int KEY_DOWNLOAD_MSG_CODE = 2; //download secret key message public static final int MANAGER_MSG_CODE = 100; //management message /*MAX_MESSAGES_PER_READ refers to DefaultChannelConfig, AdaptiveRecvByteBufAllocator, FixedRecvByteBufAllocator */ public static final int MAX_MESSAGES_PER_READ = 64; //how many read actions in one message conversation public static final int MIN_RECEIVED_BUFFER_SIZE = 1024; //1024 bytes public static final int RECEIVED_BUFFER_SIZE = 32 * 1024; //32k bytes public static final int MAX_RECEIVED_BUFFER_SIZE = 64 * 1024; //64k bytes /* keyboard cipher key */ public static final String WORK_SECRET_KEY = "workSecretKey"; public static final String MA_KEY = "maKey"; public static final String MASTER_KEY = "masterKey"; /* packet result flag */ public static final int SUCCESSFUL_MSG_CODE = 0; /* xml jaxb context */ public static final String NET_CONF_PACKAGE_CONTEXT = "king.flow.net"; public static final String TLS_PACKAGE_CONTEXT = "king.flow.data"; public static final String UI_CONF_PACKAGE_CONTEXT = "king.flow.view"; public static final String KING_FLOW_BACKGROUND = "king.flow.background"; public static final String KING_FLOW_PROGRESS = "king.flow.progress"; public static final String TEXT_TYPE_TOOL_CONFIG = "chinese.text.type.config"; public static final String COMBOBOX_ITEMS_PROPERTY_PATTERN = "([^,/]*/[^,/]*,)*+([^,/]*/[^,/]*){1}+"; public static final String ADVANCED_TABLE_TOTAL_PAGES = "total"; public static final String ADVANCED_TABLE_VALUE = "value"; public static final String ADVANCED_TABLE_CURRENT_PAGE = "current"; /* card-reading state */ public static final int INVALID_CARD_STATE = -1; public static final int MAGNET_CARD_STATE = 2; public static final int IC_CARD_STATE = 3; /* union-pay transaction type */ public static final String UNION_PAY_REGISTRATION = "1"; public static final String UNION_PAY_TRANSACTION = "3"; public static final String UNION_PAY_TRANSACTION_BALANCE = "4"; /* card affiliation type */ public static final String CARD_AFFILIATION_INTERNAL = "1"; public static final String CARD_AFFILIATION_EXTERNAL = "2"; /* supported driver types */ static final ImmutableSet<DeviceEnum> SUPPORTED_DEVICES = new ImmutableSet.Builder<DeviceEnum>() .add(DeviceEnum.IC_CARD) .add(DeviceEnum.CASH_SAVER) .add(DeviceEnum.GZ_CARD) .add(DeviceEnum.HIS_CARD) .add(DeviceEnum.KEYBOARD) .add(DeviceEnum.MAGNET_CARD) .add(DeviceEnum.MEDICARE_CARD) .add(DeviceEnum.PATIENT_CARD) .add(DeviceEnum.PID_CARD) .add(DeviceEnum.PKG_8583) .add(DeviceEnum.PRINTER) .add(DeviceEnum.SENSOR_CARD) .add(DeviceEnum.TWO_IN_ONE_CARD) .build(); /* action-component relationship map */ public static final String JUMP_ACTION = JumpAction.class.getSimpleName(); public static final String SET_FONT_ACTION = SetFontAction.class.getSimpleName(); public static final String CLEAN_ACTION = CleanAction.class.getSimpleName(); public static final String HIDE_ACTION = HideAction.class.getSimpleName(); public static final String USE_TIP_ACTION = UseTipAction.class.getSimpleName(); public static final String PLAY_MEDIA_ACTION = PlayMediaAction.class.getSimpleName(); public static final String SEND_MSG_ACTION = MsgSendAction.class.getSimpleName(); public static final String MOVE_CURSOR_ACTION = MoveCursorAction.class.getSimpleName(); public static final String LIMIT_INPUT_ACTION = LimitInputAction.class.getSimpleName(); public static final String SHOW_COMBOBOX_ACTION = ShowComboBoxAction.class.getSimpleName(); public static final String SHOW_TABLE_ACTION = ShowTableAction.class.getSimpleName(); public static final String SHOW_CLOCK_ACTION = ShowClockAction.class.getSimpleName(); public static final String OPEN_BROWSER_ACTION = OpenBrowserAction.class.getSimpleName(); public static final String RUN_COMMAND_ACTION = RunCommandAction.class.getSimpleName(); public static final String OPEN_VIRTUAL_KEYBOARD_ACTION = VirtualKeyboardAction.class.getSimpleName(); public static final String PRINT_RECEIPT_ACTION = SetPrinterAction.class.getSimpleName(); public static final String INSERT_IC_ACTION = InsertICardAction.class.getSimpleName(); public static final String WRITE_IC_ACTION = WriteICardAction.class.getSimpleName(); public static final String BALANCE_TRANS_ACTION = "BalanceTransAction"; public static final String PRINT_PASSBOOK_ACTION = PrintPassbookAction.class.getSimpleName(); public static final String UPLOAD_FILE_ACTION = UploadFileAction.class.getSimpleName(); public static final String SWIPE_CARD_ACTION = SwipeCardAction.class.getSimpleName(); public static final String SWIPE_TWO_IN_ONE_CARD_ACTION = Swipe2In1CardAction.class.getSimpleName(); public static final String EJECT_CARD_ACTION = EjectCardAction.class.getSimpleName(); public static final String WITHDRAW_CARD_ACTION = WithdrawCardAction.class.getSimpleName(); public static final String READ_WRITE_FINGERPRINT_ACTION = RwFingerPrintAction.class.getSimpleName(); public static final String PLAY_VIDEO_ACTION = PlayVideoAction.class.getSimpleName(); public static final String CUSTOMIZED_ACTION = DefinedAction.class.getSimpleName(); public static final String ENCRYPT_KEYBORAD_ACTION = EncryptKeyboardAction.class.getSimpleName(); public static final String SHOW_GRID_ACTION = ShowGridAction.class.getSimpleName(); public static final String TYPE_NUMERIC_PAD_ACTION = NumericPadAction.class.getSimpleName(); public static final String WEB_LOAD_ACTION = Action.WebLoadAction.class.getSimpleName(); static final Map<ComponentEnum, List<String>> ACTION_COMPONENT_MAP = new ImmutableMap.Builder<ComponentEnum, List<String>>() .put(ComponentEnum.BUTTON, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(JUMP_ACTION) .add(SET_FONT_ACTION) .add(CLEAN_ACTION) .add(HIDE_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(OPEN_BROWSER_ACTION) .add(RUN_COMMAND_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(PRINT_RECEIPT_ACTION) .add(SEND_MSG_ACTION) .add(INSERT_IC_ACTION) .add(WRITE_IC_ACTION) .add(MOVE_CURSOR_ACTION) .add(PRINT_PASSBOOK_ACTION) .add(UPLOAD_FILE_ACTION) .add(BALANCE_TRANS_ACTION) .add(EJECT_CARD_ACTION) .add(WITHDRAW_CARD_ACTION) .add(WEB_LOAD_ACTION) .build()) .put(ComponentEnum.COMBO_BOX, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_COMBOBOX_ACTION) .add(SWIPE_CARD_ACTION) .add(SWIPE_TWO_IN_ONE_CARD_ACTION) .add(PLAY_MEDIA_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.LABEL, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_CLOCK_ACTION) .build()) .put(ComponentEnum.TEXT_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.PASSWORD_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(MOVE_CURSOR_ACTION) .add(ENCRYPT_KEYBORAD_ACTION) .build()) .put(ComponentEnum.TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_TABLE_ACTION) .build()) .put(ComponentEnum.ADVANCED_TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(SHOW_TABLE_ACTION) .add(SEND_MSG_ACTION) .build()) .put(ComponentEnum.VIDEO_PLAYER, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(PLAY_VIDEO_ACTION) .build()) .put(ComponentEnum.GRID, new ImmutableList.Builder<String>() .add(SHOW_GRID_ACTION) .build()) .put(ComponentEnum.NUMERIC_PAD, new ImmutableList.Builder<String>() .add(TYPE_NUMERIC_PAD_ACTION) .build()) .build(); }
Java
package ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import ca.qc.bergeron.marcantoine.crammeur.librairy.annotations.Entity; import ca.qc.bergeron.marcantoine.crammeur.librairy.exceptions.KeyException; import ca.qc.bergeron.marcantoine.crammeur.android.models.Client; import ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.SQLiteTemplate; import ca.qc.bergeron.marcantoine.crammeur.librairy.repository.i.Repository; /** * Created by Marc-Antoine on 2017-01-11. */ public final class SQLiteClient extends SQLiteTemplate<Client,Integer> implements ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite.i.SQLiteClient { public SQLiteClient(Repository pRepository, Context context) { super(Client.class,Integer.class,pRepository, context); } @Override protected Client convertCursorToEntity(@NonNull Cursor pCursor) { Client o = new Client(); o.Id = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name())); o.Name = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_NAME)); o.EMail = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_EMAIL)); return o; } @Override protected Integer convertCursorToId(@NonNull Cursor pCursor) { Integer result; result = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name())); return result; } @Override public void create() { mDB.execSQL(CREATE_TABLE_CLIENTS); } @NonNull @Override public Integer save(@NonNull Client pData) throws KeyException { ContentValues values = new ContentValues(); try { if (pData.Id == null) { pData.Id = this.getKey(pData); } values.put(mId.getAnnotation(Entity.Id.class).name(), mKey.cast(mId.get(pData))); values.put(F_CLIENT_NAME, pData.Name); values.put(F_CLIENT_EMAIL, pData.EMail); if (mId.get(pData) == null || !this.contains(mKey.cast(mId.get(pData)))) { mId.set(pData, (int) mDB.insert(T_CLIENTS, null, values)); } else { mDB.update(T_CLIENTS, values, mId.getAnnotation(Entity.Id.class).name() + "=?", new String[]{String.valueOf(pData.Id)}); } return pData.Id; } catch (IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Nullable @Override public Integer getKey(@NonNull Client pEntity) { Integer result = null; try { if (mId.get(pEntity) != null) return (Integer) mId.get(pEntity); String[] columns = new String[] {F_ID}; String where = "LOWER(" + F_CLIENT_NAME + ")=LOWER(?) AND LOWER(" + F_CLIENT_EMAIL + ")=LOWER(?)"; String[] whereArgs = new String[] {pEntity.Name,pEntity.EMail}; // limit 1 row = "1"; Cursor cursor = mDB.query(T_CLIENTS, columns, where, whereArgs, null, null, null, "1"); if (cursor.moveToFirst()) { result = cursor.getInt(cursor.getColumnIndex(F_ID)); } } catch (IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } return result; } }
Java
/** * @license AngularJS v1.3.0-build.2690+sha.be7c02c * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * # ngCookies * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * * <div doc-module-components="ngCookies"></div> * * See {@link ngCookies.$cookies `$cookies`} and * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created/deleted at the end of current $eval. * The object's properties can only be strings. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * } * ``` */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were * stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { value = '' + value; cookies[name] = value; } if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc service * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * } * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { var value = $cookies[key]; return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
Java
/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKmath * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2010-13 Stanford University and the Authors. * * Authors: Peter Eastman, Michael Sherman * * Contributors: * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "SimTKmath.h" #include <algorithm> using std::pair; using std::make_pair; #include <iostream> using std::cout; using std::endl; #include <set> // Define this if you want to see voluminous output from MPR (XenoCollide) //#define MPR_DEBUG namespace SimTK { //============================================================================== // CONTACT TRACKER //============================================================================== //------------------------------------------------------------------------------ // ESTIMATE IMPLICIT PAIR CONTACT USING MPR //------------------------------------------------------------------------------ // Generate a rough guess at the contact points. Point P is returned in A's // frame and point Q is in B's frame, but all the work here is done in frame A. // See Snethen, G. "XenoCollide: Complex Collision Made Simple", Game // Programming Gems 7, pp.165-178. // // Note that we intend to use this on smooth convex objects. That means there // can be no guarantee about how many iterations this will take to converge; it // may take a very long time for objects that are just barely touching. On the // other hand we only need an approximate answer because we're going to polish // the solution to machine precision using a Newton iteration afterwards. namespace { // Given a direction in shape A's frame, calculate the support point of the // Minkowski difference shape A-B in that direction. To do that we find A's // support point P in that direction, and B's support point Q in the opposite // direction; i.e. what would be -B's support in the original direction. Then // return the vector v=(P-Q) expressed in A's frame. struct Support { Support(const ContactGeometry& shapeA, const ContactGeometry& shapeB, const Transform& X_AB, const UnitVec3& dirInA) : shapeA(shapeA), shapeB(shapeB), X_AB(X_AB) { computeSupport(dirInA); } // Calculate a new set of supports for the same shapes. void computeSupport(const UnitVec3& dirInA) { const UnitVec3 dirInB = ~X_AB.R() * dirInA; // 15 flops dir = dirInA; A = shapeA.calcSupportPoint( dirInA); // varies; 40 flops for ellipsoid B = shapeB.calcSupportPoint(-dirInB); // " v = A - X_AB*B; // 21 flops depth = dot(v,dir); // 5 flops } Support& operator=(const Support& src) { dir = src.dir; A = src.A; B = src.B; v = src.v; return *this; } void swap(Support& other) { std::swap(dir, other.dir); std::swap(A,other.A); std::swap(B,other.B); std::swap(v,other.v); } void getResult(Vec3& pointP_A, Vec3& pointQ_B, UnitVec3& normalInA) const { pointP_A = A; pointQ_B = B; normalInA = dir; } UnitVec3 dir; // A support direction, exp in A Vec3 A; // support point in direction dir on shapeA, expressed in A Vec3 B; // support point in direction -dir on shapeB, expressed in B Vec3 v; // support point A-B in Minkowski difference shape, exp. in A Real depth; // v . dir (positive when origin is below support plane) private: const ContactGeometry& shapeA; const ContactGeometry& shapeB; const Transform& X_AB; }; const Real MPRAccuracy = Real(.05); // 5% of the surface dimensions const Real SqrtMPRAccuracy = Real(.2236); // roughly sqrt(MPRAccuracy) } /*static*/ bool ContactTracker:: estimateConvexImplicitPairContactUsingMPR (const ContactGeometry& shapeA, const ContactGeometry& shapeB, const Transform& X_AB, Vec3& pointP, Vec3& pointQ, UnitVec3& dirInA, int& numIterations) { const Rotation& R_AB = X_AB.R(); numIterations = 0; // Get some cheap, rough scaling information. // TODO: ideally this would be done using local curvature information. // A reasonable alternative would be to use the smallest dimension of the // shape's oriented bounding box. // We're going to assume the smallest radius is 1/4 of the bounding // sphere radius. Vec3 cA, cB; Real rA, rB; shapeA.getBoundingSphere(cA,rA); shapeB.getBoundingSphere(cB,rB); const Real lengthScale = Real(0.25)*std::min(rA,rB); const Real areaScale = Real(1.5)*square(lengthScale); // ~area of octant // If we determine the depth to within a small fraction of the scale, // or localize the contact area to a small fraction of the surface area, // that is good enough and we can stop. const Real depthGoal = MPRAccuracy*lengthScale; const Real areaGoal = SqrtMPRAccuracy*areaScale; #ifdef MPR_DEBUG printf("\nMPR acc=%g: r=%g, depthGoal=%g areaGoal=%g\n", MPRAccuracy, std::min(rA,rB), depthGoal, areaGoal); #endif // Phase 1: Portal Discovery // ------------------------- // Compute an interior point v0 that is known to be inside the Minkowski // difference, and a ray dir1 directed from that point to the origin. const Vec3 v0 = ( Support(shapeA, shapeB, X_AB, UnitVec3( XAxis)).v + Support(shapeA, shapeB, X_AB, UnitVec3(-XAxis)).v)/2; if (v0 == 0) { // This is a pathological case: the two objects are directly on top of // each other with their centers at exactly the same place. Just // return *some* vaguely plausible contact. pointP = shapeA.calcSupportPoint( UnitVec3( XAxis)); pointQ = shapeB.calcSupportPoint(~R_AB*UnitVec3(-XAxis)); // in B dirInA = XAxis; return true; } // Support 1's direction is initially the "origin ray" that points from // interior point v0 to the origin. Support s1(shapeA, shapeB, X_AB, UnitVec3(-v0)); // Test for NaN once and get out to avoid getting stuck in loops below. if (isNaN(s1.depth)) { pointP = pointQ = NaN; dirInA = UnitVec3(); return false; } if (s1.depth <= 0) { // origin outside 1st support plane s1.getResult(pointP, pointQ, dirInA); return false; } if (s1.v % v0 == 0) { // v0 perpendicular to support plane; origin inside s1.getResult(pointP, pointQ, dirInA); return true; } // Find support point perpendicular to plane containing origin, interior // point v0, and first support v1. Support s2(shapeA, shapeB, X_AB, UnitVec3(s1.v % v0)); if (s2.depth <= 0) { // origin is outside 2nd support plane s2.getResult(pointP, pointQ, dirInA); return false; } // Find support perpendicular to plane containing interior point v0 and // first two support points v1 and v2. Make sure it is on the side that // is closer to the origin; fix point ordering if necessary. UnitVec3 d3 = UnitVec3((s1.v-v0)%(s2.v-v0)); if (~d3*v0 > 0) { // oops -- picked the wrong side s1.swap(s2); d3 = -d3; } Support s3(shapeA, shapeB, X_AB, d3); if (s3.depth <= 0) { // origin is outside 3rd support plane s3.getResult(pointP, pointQ, dirInA); return false; } // We now have a candidate portal (triangle v1,v2,v3). We have to refine it // until the origin ray -v0 intersects the candidate. Check against the // three planes of the tetrahedron that contain v0. By construction above // we know the origin is inside the v0,v1,v2 face already. // We should find a candidate portal very fast, probably in 1 or 2 // iterations. We'll allow an absurdly large number of // iterations and then abort just to make sure we don't get stuck in an // infinite loop. const Real MaxCandidateIters = 100; // should never get anywhere near this int candidateIters = 0; while (true) { ++candidateIters; SimTK_ERRCHK_ALWAYS(candidateIters <= MaxCandidateIters, "ContactTracker::estimateConvexImplicitPairContactUsingMPR()", "Unable to find a candidate portal; should never happen."); if (~v0*(s1.v % s3.v) < -SignificantReal) s2 = s3; // origin outside v0,v1,v3 face; replace v2 else if (~v0*(s3.v % s2.v) < -SignificantReal) s1 = s3; // origin outside v0,v2,v3 face; replace v1 else break; // Choose new candidate. The keepers are in v1 and v2; get a new v3. s3.computeSupport(UnitVec3((s1.v-v0) % (s2.v-v0))); } // Phase 2: Portal Refinement // -------------------------- // We have a portal (triangle v1,v2,v3) that the origin ray passes through. // Now we need to refine v1,v2,v3 until we have portal such that the origin // is inside the tetrahedron v0,v1,v2,v3. const int MinTriesToFindSeparatingPlane = 5; const int MaxTriesToImproveContact = 5; int triesToFindSeparatingPlane=0, triesToImproveContact=0; while (true) { ++numIterations; // Get the normal to the portal, oriented in the general direction of // the origin ray (i.e., the outward normal). const Vec3 portalVec = (s2.v-s1.v) % (s3.v-s1.v); const Real portalArea = portalVec.norm(), ooPortalArea = 1/portalArea; UnitVec3 portalDir(portalVec*ooPortalArea, true); if (~portalDir*v0 > 0) portalDir = -portalDir; // Any portal vertex is a vector from the origin to the portal plane. // Dot one of them with the portal outward normal to get the origin // depth (positive if inside). const Real depth = ~s1.v*portalDir; // Find new support in portal direction. Support s4(shapeA, shapeB, X_AB, portalDir); if (s4.depth <= 0) { // origin is outside new support plane s4.getResult(pointP, pointQ, dirInA); return false; } const Real depthChange = std::abs(s4.depth - depth); bool mustReturn=false, okToReturn=false; if (depth >= 0) { // We found a contact. mustReturn = (++triesToImproveContact >= MaxTriesToImproveContact); okToReturn = true; } else { // No contact yet. okToReturn = (++triesToFindSeparatingPlane >= MinTriesToFindSeparatingPlane); mustReturn = false; } bool accuracyAchieved = (depthChange <= depthGoal || portalArea <= areaGoal); #ifdef MPR_DEBUG printf(" depth=%g, change=%g area=%g changeFrac=%g areaFrac=%g\n", depth, depthChange, portalArea, depthChange/depthGoal, portalArea/areaGoal); printf(" accuracyAchieved=%d okToReturn=%d mustReturn=%d\n", accuracyAchieved, okToReturn, mustReturn); #endif if (mustReturn || (okToReturn && accuracyAchieved)) { // The origin is inside the portal, so we have an intersection. // Compute the barycentric coordinates of the origin ray's // intersection with the portal, and map back to the two surfaces. const Vec3 origin = v0+v0*(~portalDir*(s1.v-v0)/(~portalDir*v0)); const Real area1 = ~portalDir*((s2.v-origin)%(s3.v-origin)); const Real area2 = ~portalDir*((s3.v-origin)%(s1.v-origin)); const Real u = area1*ooPortalArea; const Real v = area2*ooPortalArea; const Real w = 1-u-v; // Compute the contact points in their own shape's frame. pointP = u*s1.A + v*s2.A + w*s3.A; pointQ = u*s1.B + v*s2.B + w*s3.B; dirInA = portalDir; return true; } // We know the origin ray entered the (v1,v2,v3,v4) tetrahedron via the // (v1,v2,v3) face (the portal). New portal is the face that it exits. const Vec3 v4v0 = s4.v % v0; if (~s1.v * v4v0 > 0) { if (~s2.v * v4v0 > 0) s1 = s4; // v4,v2,v3 (new portal) else s3 = s4; // v1,v2,v4 } else { if (~s3.v * v4v0 > 0) s2 = s4; // v1,v4,v3 else s1 = s4; // v4,v2,v3 again } } } //------------------------------------------------------------------------------ // REFINE IMPLICIT PAIR //------------------------------------------------------------------------------ // We have a rough estimate of the contact points. Use Newton iteration to // refine them. If the surfaces are separated, this will find the points of // closest approach. If contacting, this will find the points of maximium // penetration. // Returns true if the desired accuracy is achieved, regardless of whether the // surfaces are separated or in contact. /*static*/ bool ContactTracker:: refineImplicitPair (const ContactGeometry& shapeA, Vec3& pointP, // in/out (in A) const ContactGeometry& shapeB, Vec3& pointQ, // in/out (in B) const Transform& X_AB, Real accuracyRequested, Real& accuracyAchieved, int& numIterations) { // If the initial guess is very bad, or the ellipsoids pathological we // may have to crawl along for a while at the beginning. const int MaxSlowIterations = 8; const int MaxIterations = MaxSlowIterations + 8; const Real MinStepFrac = Real(1e-6); // if we can't take at least this // fraction of Newton step, give it up Vec6 err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB); accuracyAchieved = err.norm(); Vector errVec(6, &err[0], true); // share space with err Mat66 J; // to hold the Jacobian Matrix JMat(6,6,6,&J(0,0)); // share space with J Vec6 delta; Vector deltaVec(6, &delta[0], true); // share space with delta numIterations = 0; while ( accuracyAchieved > accuracyRequested && numIterations < MaxIterations) { ++numIterations; J = calcImplicitPairJacobian(shapeA, pointP, shapeB, pointQ, X_AB, err); // Try to use LU factorization; fall back to QTZ if singular. FactorLU lu(JMat); if (!lu.isSingular()) lu.solve(errVec, deltaVec); // writes into delta also else { FactorQTZ qtz(JMat, SqrtEps); qtz.solve(errVec, deltaVec); // writes into delta also } // Line search for safety in case starting guess bad. Don't accept // any move that makes things worse. Real f = 2; // scale back factor Vec3 oldP = pointP, oldQ = pointQ; Real oldAccuracyAchieved = accuracyAchieved; do { f /= 2; pointP = oldP - f*delta.getSubVec<3>(0); pointQ = oldQ - f*delta.getSubVec<3>(3); err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB); accuracyAchieved = err.norm(); } while (accuracyAchieved > oldAccuracyAchieved && f > MinStepFrac); const bool noProgressMade = (accuracyAchieved > oldAccuracyAchieved); if (noProgressMade) { // Restore best points and fall through. pointP = oldP; pointQ = oldQ; } if ( noProgressMade || (f < 1 && numIterations >= MaxSlowIterations)) // Too slow. { // We don't appear to be getting anywhere. Just project the // points onto the surfaces and then exit. bool inside; UnitVec3 normal; pointP = shapeA.findNearestPoint(pointP, inside, normal); pointQ = shapeB.findNearestPoint(pointQ, inside, normal); err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB); accuracyAchieved = err.norm(); break; } } return accuracyAchieved <= accuracyRequested; } //------------------------------------------------------------------------------ // FIND IMPLICIT PAIR ERROR //------------------------------------------------------------------------------ // We're given two implicitly-defined shapes A and B and candidate surface // contact points P (for A) and Q (for B). There are six equations that real // contact points should satisfy. Here we return the errors in each of those // equations; if all six terms are zero these are contact points. // // Per profiling, this gets called a lot at runtime, so keep it tight! /*static*/ Vec6 ContactTracker:: findImplicitPairError (const ContactGeometry& shapeA, const Vec3& pointP, // in A const ContactGeometry& shapeB, const Vec3& pointQ, // in B const Transform& X_AB) { // Compute the function value and normal vector for each object. const Function& fA = shapeA.getImplicitFunction(); const Function& fB = shapeB.getImplicitFunction(); // Avoid some heap allocations by using stack arrays. Vec3 xData; Vector x(3, &xData[0], true); // shares space with xdata int compData; // just one integer ArrayView_<int> components(&compData, &compData+1); Vec3 gradA, gradB; xData = pointP; // writes into Vector x also for (int i = 0; i < 3; i++) { components[0] = i; gradA[i] = fA.calcDerivative(components, x); } Real errorA = fA.calcValue(x); xData = pointQ; // writes into Vector x also for (int i = 0; i < 3; i++) { components[0] = i; gradB[i] = fB.calcDerivative(components, x); } Real errorB = fB.calcValue(x); // Construct a coordinate frame for each object. // TODO: this needs some work to make sure it is as stable as possible // so the perpendicularity errors are stable as the solution advances // and especially as the Jacobian is calculated by perturbation. UnitVec3 nA(-gradA); UnitVec3 nB(X_AB.R()*(-gradB)); UnitVec3 uA(std::abs(nA[0])>Real(0.5)? nA%Vec3(0, 1, 0) : nA%Vec3(1, 0, 0)); UnitVec3 uB(std::abs(nB[0])>Real(0.5)? nB%Vec3(0, 1, 0) : nB%Vec3(1, 0, 0)); Vec3 vA = nA%uA; // Already a unit vector, so we don't need to normalize it. Vec3 vB = nB%uB; // Compute the error vector. The components indicate, in order, that nA // must be perpendicular to both tangents of object B, that the separation // vector should be zero or perpendicular to the tangents of object A, and // that both points should be on their respective surfaces. Vec3 delta = pointP-X_AB*pointQ; return Vec6(~nA*uB, ~nA*vB, ~delta*uA, ~delta*vA, errorA, errorB); } //------------------------------------------------------------------------------ // CALC IMPLICIT PAIR JACOBIAN //------------------------------------------------------------------------------ // Differentiate the findImplicitPairError() with respect to changes in the // locations of points P and Q in their own surface frames. /*static*/ Mat66 ContactTracker::calcImplicitPairJacobian (const ContactGeometry& shapeA, const Vec3& pointP, const ContactGeometry& shapeB, const Vec3& pointQ, const Transform& X_AB, const Vec6& err0) { Real dt = SqrtEps; Vec3 d1 = dt*Vec3(1, 0, 0); Vec3 d2 = dt*Vec3(0, 1, 0); Vec3 d3 = dt*Vec3(0, 0, 1); Vec6 err1 = findImplicitPairError(shapeA, pointP+d1, shapeB, pointQ, X_AB) - err0; Vec6 err2 = findImplicitPairError(shapeA, pointP+d2, shapeB, pointQ, X_AB) - err0; Vec6 err3 = findImplicitPairError(shapeA, pointP+d3, shapeB, pointQ, X_AB) - err0; Vec6 err4 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d1, X_AB) - err0; Vec6 err5 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d2, X_AB) - err0; Vec6 err6 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d3, X_AB) - err0; return Mat66(err1, err2, err3, err4, err5, err6) / dt; // This is a Central Difference derivative (you should use a somewhat // larger dt in this case). However, I haven't seen any evidence that this // helps, even for some very eccentric ellipsoids. (sherm 20130408) //Vec6 err1 = findImplicitPairError(shapeA, pointP+d1, shapeB, pointQ, X_AB) // - findImplicitPairError(shapeA, pointP-d1, shapeB, pointQ, X_AB); //Vec6 err2 = findImplicitPairError(shapeA, pointP+d2, shapeB, pointQ, X_AB) // - findImplicitPairError(shapeA, pointP-d2, shapeB, pointQ, X_AB); //Vec6 err3 = findImplicitPairError(shapeA, pointP+d3, shapeB, pointQ, X_AB) // - findImplicitPairError(shapeA, pointP-d3, shapeB, pointQ, X_AB); //Vec6 err4 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d1, X_AB) // - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d1, X_AB); //Vec6 err5 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d2, X_AB) // - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d2, X_AB); //Vec6 err6 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d3, X_AB) // - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d3, X_AB); //return Mat66(err1, err2, err3, err4, err5, err6) / (2*dt); } //============================================================================== // HALFSPACE-SPHERE CONTACT TRACKER //============================================================================== // Cost is 21 flops if no contact, 67 with contact. bool ContactTracker::HalfSpaceSphere::trackContact (const Contact& priorStatus, const Transform& X_GH, const ContactGeometry& geoHalfSpace, const Transform& X_GS, const ContactGeometry& geoSphere, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT ( geoHalfSpace.getTypeId()==ContactGeometry::HalfSpace::classTypeId() && geoSphere.getTypeId()==ContactGeometry::Sphere::classTypeId(), "ContactTracker::HalfSpaceSphere::trackContact()"); // No need for an expensive dynamic cast here; we know what we have. const ContactGeometry::Sphere& sphere = ContactGeometry::Sphere::getAs(geoSphere); const Rotation R_HG = ~X_GH.R(); // inverse rotation; no flops // p_HC is vector from H origin to S's center C const Vec3 p_HC = R_HG*(X_GS.p() - X_GH.p()); // 18 flops // Calculate depth of sphere center C given that the halfspace occupies // all of x>0 space. const Real r = sphere.getRadius(); const Real depth = p_HC[0] + r; // 1 flop if (depth <= -cutoff) { // 2 flops currentStatus.clear(); // not touching return true; // successful return } // Calculate the rest of the X_HS transform as required by Contact. const Transform X_HS(R_HG*X_GS.R(), p_HC); // 45 flops const UnitVec3 normal_H(Vec3(-1,0,0), true); // 0 flops const Vec3 origin_H = Vec3(depth/2, p_HC[1], p_HC[2]); // 1 flop // The surfaces are contacting (or close enough to be interesting). // The sphere's radius is also the effective radius. currentStatus = CircularPointContact(priorStatus.getSurface1(), Infinity, priorStatus.getSurface2(), r, X_HS, r, depth, origin_H, normal_H); return true; // success } bool ContactTracker::HalfSpaceSphere::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::HalfSpaceSphere::predictContact() not implemented yet."); return false; } bool ContactTracker::HalfSpaceSphere::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::HalfSpaceSphere::initializeContact() not implemented yet."); return false; } //============================================================================== // HALFSPACE-ELLIPSOID CONTACT TRACKER //============================================================================== // Cost is ~135 flops if no contact, ~425 with contact. // The contact point on the ellipsoid must be the unique point that has its // outward-facing normal in the opposite direction of the half space normal. // We can find that point very fast and see how far it is from the half // space surface. If it is close enough, we'll evaluate the curvatures at // that point in preparation for generating forces with Hertz theory. bool ContactTracker::HalfSpaceEllipsoid::trackContact (const Contact& priorStatus, const Transform& X_GH, const ContactGeometry& geoHalfSpace, const Transform& X_GE, const ContactGeometry& geoEllipsoid, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT ( geoHalfSpace.getTypeId()==ContactGeometry::HalfSpace::classTypeId() && geoEllipsoid.getTypeId()==ContactGeometry::Ellipsoid::classTypeId(), "ContactTracker::HalfSpaceEllipsoid::trackContact()"); // No need for an expensive dynamic cast here; we know what we have. const ContactGeometry::Ellipsoid& ellipsoid = ContactGeometry::Ellipsoid::getAs(geoEllipsoid); // Our half space occupies the +x half so the normal is -x. const Transform X_HE = ~X_GH*X_GE; // 63 flops // Halfspace normal is -x, so the ellipsoid normal we're looking for is // in the half space's +x direction. const UnitVec3& n_E = (~X_HE.R()).x(); // halfspace normal in E const Vec3 Q_E = ellipsoid.findPointWithThisUnitNormal(n_E); // 40 flops const Vec3 Q_H = X_HE*Q_E; // Q measured from half space origin (18 flops) const Real depth = Q_H[0]; // x > 0 is penetrated if (depth <= -cutoff) { // 2 flops currentStatus.clear(); // not touching return true; // successful return } // The surfaces are contacting (or close enough to be interesting). // The ellipsoid's principal curvatures k at the contact point are also // the curvatures of the contact paraboloid since the half space doesn't // add anything interesting. Transform X_EQ; Vec2 k; ellipsoid.findParaboloidAtPointWithNormal(Q_E, n_E, X_EQ, k); // 220 flops // We have the contact paraboloid expressed in frame Q but Qz=n_E has the // wrong sign since we have to express it using the half space normal. // We have to end up with a right handed frame, so one of x or y has // to be negated too. (6 flops) Rotation& R_EQ = X_EQ.updR(); R_EQ.setRotationColFromUnitVecTrustMe(ZAxis, -R_EQ.z()); // changing X_EQ R_EQ.setRotationColFromUnitVecTrustMe(XAxis, -R_EQ.x()); // Now the frame is pointing in the right direction. Measure and express in // half plane frame, then shift origin to half way between contact point // Q on the undeformed ellipsoid and the corresponding contact point P // on the undeformed half plane surface. It's easier to do this shift // in H since it is in the -Hx direction. Transform X_HC = X_HE*X_EQ; X_HC.updP()[0] -= depth/2; // 65 flops currentStatus = EllipticalPointContact(priorStatus.getSurface1(), priorStatus.getSurface2(), X_HE, X_HC, k, depth); return true; // success } bool ContactTracker::HalfSpaceEllipsoid::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::HalfSpaceEllipsoid::predictContact() not implemented yet."); return false; } bool ContactTracker::HalfSpaceEllipsoid::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::HalfSpaceEllipsoid::initializeContact() not implemented yet."); return false; } //============================================================================== // SPHERE-SPHERE CONTACT TRACKER //============================================================================== // Cost is 12 flops if no contact, 139 if contact bool ContactTracker::SphereSphere::trackContact (const Contact& priorStatus, const Transform& X_GS1, const ContactGeometry& geoSphere1, const Transform& X_GS2, const ContactGeometry& geoSphere2, Real cutoff, // 0 for contact Contact& currentStatus) const { SimTK_ASSERT ( geoSphere1.getTypeId()==ContactGeometry::Sphere::classTypeId() && geoSphere2.getTypeId()==ContactGeometry::Sphere::classTypeId(), "ContactTracker::SphereSphere::trackContact()"); // No need for an expensive dynamic casts here; we know what we have. const ContactGeometry::Sphere& sphere1 = ContactGeometry::Sphere::getAs(geoSphere1); const ContactGeometry::Sphere& sphere2 = ContactGeometry::Sphere::getAs(geoSphere2); currentStatus.clear(); // Find the vector from sphere center C1 to C2, expressed in G. const Vec3 p_12_G = X_GS2.p() - X_GS1.p(); // 3 flops const Real d2 = p_12_G.normSqr(); // 5 flops const Real r1 = sphere1.getRadius(); const Real r2 = sphere2.getRadius(); const Real rr = r1 + r2; // 1 flop // Quick check. If separated we can return nothing, unless we were // in contact last time in which case we have to return one last // Contact indicating that contact has been broken and by how much. if (d2 > square(rr+cutoff)) { // 3 flops if (!priorStatus.getContactId().isValid()) return true; // successful return: still separated const Real separation = std::sqrt(d2) - rr; // > cutoff, ~25 flops const Transform X_S1S2(~X_GS1.R()*X_GS2.R(), ~X_GS1.R()*p_12_G); // 60 flops currentStatus = BrokenContact(priorStatus.getSurface1(), priorStatus.getSurface2(), X_S1S2, separation); return true; } const Real d = std::sqrt(d2); // ~20 flops if (d < SignificantReal) { // 1 flop // TODO: If the centers are coincident we should use past information // to determine the most likely normal. For now just fail. return false; } const Transform X_S1S2(~X_GS1.R()*X_GS2.R(), ~X_GS1.R()*p_12_G);// 60 flops const Vec3& p_12 = X_S1S2.p(); // center-to-center vector in S1 const Real depth = rr - d; // >0 for penetration (1 flop) const Real r = r1*r2/rr; // r=r1r2/(r1+r2)=1/(1/r1+1/r2) ~20 flops const UnitVec3 normal_S1(p_12/d, true); // 1/ + 3* = ~20 flops const Vec3 origin_S1 = (r1 - depth/2)*normal_S1; // 5 flops // The surfaces are contacting (or close enough to be interesting). currentStatus = CircularPointContact(priorStatus.getSurface1(), r1, priorStatus.getSurface2(), r2, X_S1S2, r, depth, origin_S1, normal_S1); return true; // success } bool ContactTracker::SphereSphere::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::SphereSphere::predictContact() not implemented yet."); return false; } bool ContactTracker::SphereSphere::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::SphereSphere::initializeContact() not implemented yet."); return false; } //============================================================================== // HALFSPACE - TRIANGLE MESH CONTACT TRACKER //============================================================================== // Cost is TODO bool ContactTracker::HalfSpaceTriangleMesh::trackContact (const Contact& priorStatus, const Transform& X_GH, const ContactGeometry& geoHalfSpace, const Transform& X_GM, const ContactGeometry& geoMesh, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT_ALWAYS ( ContactGeometry::HalfSpace::isInstance(geoHalfSpace) && ContactGeometry::TriangleMesh::isInstance(geoMesh), "ContactTracker::HalfSpaceTriangleMesh::trackContact()"); // We can't handle a "proximity" test, only penetration. SimTK_ASSERT_ALWAYS(cutoff==0, "ContactTracker::HalfSpaceTriangleMesh::trackContact()"); // No need for an expensive dynamic cast here; we know what we have. const ContactGeometry::TriangleMesh& mesh = ContactGeometry::TriangleMesh::getAs(geoMesh); // Transform giving mesh (S2) frame in the halfspace (S1) frame. const Transform X_HM = (~X_GH)*X_GM; // Normal is halfspace -x direction; xdir is first column of R_MH. // That's a unit vector and -unitvec is also a unit vector so this // doesn't require normalization. const UnitVec3 hsNormal_M = -(~X_HM.R()).x(); // Find the height of the halfspace face along the normal, measured // from the mesh origin. const Real hsFaceHeight_M = dot((~X_HM).p(), hsNormal_M); // Now collect all the faces that are all or partially below the // halfspace surface. std::set<int> insideFaces; processBox(mesh, mesh.getOBBTreeNode(), X_HM, hsNormal_M, hsFaceHeight_M, insideFaces); if (insideFaces.empty()) { currentStatus.clear(); // not touching return true; // successful return } currentStatus = TriangleMeshContact(priorStatus.getSurface1(), priorStatus.getSurface2(), X_HM, std::set<int>(), insideFaces); return true; // success } bool ContactTracker::HalfSpaceTriangleMesh::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::HalfSpaceTriangleMesh::predictContact() not implemented yet."); return false; } bool ContactTracker::HalfSpaceTriangleMesh::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::HalfSpaceTriangleMesh::initializeContact() not implemented yet."); return false; } // Check a single OBB and its contents (recursively) against the halfspace, // appending any penetrating faces to the insideFaces list. void ContactTracker::HalfSpaceTriangleMesh::processBox (const ContactGeometry::TriangleMesh& mesh, const ContactGeometry::TriangleMesh::OBBTreeNode& node, const Transform& X_HM, const UnitVec3& hsNormal_M, Real hsFaceHeight_M, std::set<int>& insideFaces) const { // First check against the node's bounding box. const OrientedBoundingBox& bounds = node.getBounds(); const Transform& X_MB = bounds.getTransform(); // box frame in mesh const Vec3 p_BC = bounds.getSize()/2; // from box origin corner to center // Express the half space normal in the box frame, then reflect it into // the first (+,+,+) quadrant where it is the normal of a different // but symmetric and more convenient half space. const UnitVec3 octant1hsNormal_B = (~X_MB.R()*hsNormal_M).abs(); // Dot our octant1 radius p_BC with our octant1 normal to get // the extent of the box from its center in the direction of the octant1 // reflection of the halfspace. const Real extent = dot(p_BC, octant1hsNormal_B); // Compute the height of the box center over the mesh origin, // measured along the real halfspace normal. const Vec3 boxCenter_M = X_MB*p_BC; const Real boxCenterHeight_M = dot(boxCenter_M, hsNormal_M); // Subtract the halfspace surface position to get the height of the // box center over the halfspace. const Real boxCenterHeight = boxCenterHeight_M - hsFaceHeight_M; if (boxCenterHeight >= extent) return; // no penetration if (boxCenterHeight <= -extent) { addAllTriangles(node, insideFaces); // box is entirely in halfspace return; } // Box is partially penetrated into halfspace. If it is not a leaf node, // check its children. if (!node.isLeafNode()) { processBox(mesh, node.getFirstChildNode(), X_HM, hsNormal_M, hsFaceHeight_M, insideFaces); processBox(mesh, node.getSecondChildNode(), X_HM, hsNormal_M, hsFaceHeight_M, insideFaces); return; } // This is a leaf OBB node that is penetrating, so some of its triangles // may be penetrating. const Array_<int>& triangles = node.getTriangles(); for (int i = 0; i < (int) triangles.size(); i++) { for (int vx=0; vx < 3; ++vx) { const int vertex = mesh.getFaceVertex(triangles[i], vx); const Vec3& vertexPos = mesh.getVertexPosition(vertex); const Real vertexHeight_M = dot(vertexPos, hsNormal_M); if (vertexHeight_M < hsFaceHeight_M) { insideFaces.insert(triangles[i]); break; // done with this face } } } } void ContactTracker::HalfSpaceTriangleMesh::addAllTriangles (const ContactGeometry::TriangleMesh::OBBTreeNode& node, std::set<int>& insideFaces) const { if (node.isLeafNode()) { const Array_<int>& triangles = node.getTriangles(); for (int i = 0; i < (int) triangles.size(); i++) insideFaces.insert(triangles[i]); } else { addAllTriangles(node.getFirstChildNode(), insideFaces); addAllTriangles(node.getSecondChildNode(), insideFaces); } } //============================================================================== // SPHERE - TRIANGLE MESH CONTACT TRACKER //============================================================================== // Cost is TODO bool ContactTracker::SphereTriangleMesh::trackContact (const Contact& priorStatus, const Transform& X_GS, const ContactGeometry& geoSphere, const Transform& X_GM, const ContactGeometry& geoMesh, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT_ALWAYS ( ContactGeometry::Sphere::isInstance(geoSphere) && ContactGeometry::TriangleMesh::isInstance(geoMesh), "ContactTracker::SphereTriangleMesh::trackContact()"); // We can't handle a "proximity" test, only penetration. SimTK_ASSERT_ALWAYS(cutoff==0, "ContactTracker::SphereTriangleMesh::trackContact()"); // No need for an expensive dynamic cast here; we know what we have. const ContactGeometry::Sphere& sphere = ContactGeometry::Sphere::getAs(geoSphere); const ContactGeometry::TriangleMesh& mesh = ContactGeometry::TriangleMesh::getAs(geoMesh); // Transform giving mesh (M) frame in the sphere (S) frame. const Transform X_SM = ~X_GS*X_GM; // Want the sphere center measured and expressed in the mesh frame. const Vec3 p_MC = (~X_SM).p(); std::set<int> insideFaces; processBox(mesh, mesh.getOBBTreeNode(), p_MC, square(sphere.getRadius()), insideFaces); if (insideFaces.empty()) { currentStatus.clear(); // not touching return true; // successful return } currentStatus = TriangleMeshContact(priorStatus.getSurface1(), priorStatus.getSurface2(), X_SM, std::set<int>(), insideFaces); return true; // success } // Check a single OBB and its contents (recursively) against the sphere // whose center location in M and radius squared is given, appending any // penetrating faces to the insideFaces list. void ContactTracker::SphereTriangleMesh::processBox (const ContactGeometry::TriangleMesh& mesh, const ContactGeometry::TriangleMesh::OBBTreeNode& node, const Vec3& center_M, Real radius2, std::set<int>& insideFaces) const { // First check against the node's bounding box. const Vec3 nearest_M = node.getBounds().findNearestPoint(center_M); if ((nearest_M-center_M).normSqr() >= radius2) return; // no intersection possible // Bounding box is penetrating. If it's not a leaf node, check its children. if (!node.isLeafNode()) { processBox(mesh, node.getFirstChildNode(), center_M, radius2, insideFaces); processBox(mesh, node.getSecondChildNode(), center_M, radius2, insideFaces); return; } // This is a leaf node that may be penetrating; check the triangles. const Array_<int>& triangles = node.getTriangles(); for (unsigned i = 0; i < triangles.size(); i++) { Vec2 uv; Vec3 nearest_M = mesh.findNearestPointToFace (center_M, triangles[i], uv); if ((nearest_M-center_M).normSqr() < radius2) insideFaces.insert(triangles[i]); } } bool ContactTracker::SphereTriangleMesh::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::SphereTriangleMesh::predictContact() not implemented yet."); return false; } bool ContactTracker::SphereTriangleMesh::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::SphereTriangleMesh::initializeContact() not implemented yet."); return false; } //============================================================================== // TRIANGLE MESH - TRIANGLE MESH CONTACT TRACKER //============================================================================== // Cost is TODO bool ContactTracker::TriangleMeshTriangleMesh::trackContact (const Contact& priorStatus, const Transform& X_GM1, const ContactGeometry& geoMesh1, const Transform& X_GM2, const ContactGeometry& geoMesh2, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT_ALWAYS ( ContactGeometry::TriangleMesh::isInstance(geoMesh1) && ContactGeometry::TriangleMesh::isInstance(geoMesh2), "ContactTracker::TriangleMeshTriangleMesh::trackContact()"); // We can't handle a "proximity" test, only penetration. SimTK_ASSERT_ALWAYS(cutoff==0, "ContactTracker::TriangleMeshTriangleMesh::trackContact()"); // No need for an expensive dynamic cast here; we know what we have. const ContactGeometry::TriangleMesh& mesh1 = ContactGeometry::TriangleMesh::getAs(geoMesh1); const ContactGeometry::TriangleMesh& mesh2 = ContactGeometry::TriangleMesh::getAs(geoMesh2); // Transform giving mesh2 (M2) frame in the mesh1 (M1) frame. const Transform X_M1M2 = ~X_GM1*X_GM2; std::set<int> insideFaces1, insideFaces2; // Get M2's bounding box in M1's frame. const OrientedBoundingBox mesh2Bounds_M1 = X_M1M2*mesh2.getOBBTreeNode().getBounds(); // Find the faces that are actually intersecting faces on the other // surface (this doesn't yet include faces that may be completely buried). findIntersectingFaces(mesh1, mesh2, mesh1.getOBBTreeNode(), mesh2.getOBBTreeNode(), mesh2Bounds_M1, X_M1M2, insideFaces1, insideFaces2); // It should never be the case that one set of faces is empty and the // other isn't, however it is conceivable that roundoff error could cause // this to happen so we'll check both lists. if (insideFaces1.empty() && insideFaces2.empty()) { currentStatus.clear(); // not touching return true; // successful return } // There was an intersection. We now need to identify every triangle and // vertex of each mesh that is inside the other mesh. We found the border // intersections above; now we have to fill in the buried faces. findBuriedFaces(mesh1, mesh2, ~X_M1M2, insideFaces1); findBuriedFaces(mesh2, mesh1, X_M1M2, insideFaces2); currentStatus = TriangleMeshContact(priorStatus.getSurface1(), priorStatus.getSurface2(), X_M1M2, insideFaces1, insideFaces2); return true; // success } void ContactTracker::TriangleMeshTriangleMesh:: findIntersectingFaces (const ContactGeometry::TriangleMesh& mesh1, const ContactGeometry::TriangleMesh& mesh2, const ContactGeometry::TriangleMesh::OBBTreeNode& node1, const ContactGeometry::TriangleMesh::OBBTreeNode& node2, const OrientedBoundingBox& node2Bounds_M1, const Transform& X_M1M2, std::set<int>& triangles1, std::set<int>& triangles2) const { // See if the bounding boxes intersect. if (!node1.getBounds().intersectsBox(node2Bounds_M1)) return; // If either node is not a leaf node, process the children recursively. if (!node1.isLeafNode()) { if (!node2.isLeafNode()) { const OrientedBoundingBox firstChildBounds = X_M1M2*node2.getFirstChildNode().getBounds(); const OrientedBoundingBox secondChildBounds = X_M1M2*node2.getSecondChildNode().getBounds(); findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2); findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2); findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2); findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2); } else { findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2, node2Bounds_M1, X_M1M2, triangles1, triangles2); findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2, node2Bounds_M1, X_M1M2, triangles1, triangles2); } return; } else if (!node2.isLeafNode()) { const OrientedBoundingBox firstChildBounds = X_M1M2*node2.getFirstChildNode().getBounds(); const OrientedBoundingBox secondChildBounds = X_M1M2*node2.getSecondChildNode().getBounds(); findIntersectingFaces(mesh1, mesh2, node1, node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2); findIntersectingFaces(mesh1, mesh2, node1, node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2); return; } // These are both leaf nodes, so check triangles for intersections. const Array_<int>& node1triangles = node1.getTriangles(); const Array_<int>& node2triangles = node2.getTriangles(); for (unsigned i = 0; i < node2triangles.size(); i++) { const int face2 = node2triangles[i]; Vec3 a1 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 0)); Vec3 a2 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 1)); Vec3 a3 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 2)); const Geo::Triangle A(a1,a2,a3); for (unsigned j = 0; j < node1triangles.size(); j++) { const int face1 = node1triangles[j]; const Vec3& b1 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 0)); const Vec3& b2 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 1)); const Vec3& b3 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 2)); const Geo::Triangle B(b1,b2,b3); if (A.overlapsTriangle(B)) { // The triangles intersect. triangles1.insert(face1); triangles2.insert(face2); } } } } static const int Outside = -1; static const int Unknown = 0; static const int Boundary = 1; static const int Inside = 2; void ContactTracker::TriangleMeshTriangleMesh:: findBuriedFaces(const ContactGeometry::TriangleMesh& mesh, // M const ContactGeometry::TriangleMesh& otherMesh, // O const Transform& X_OM, std::set<int>& insideFaces) const { // Find which faces are inside. // We're passed in the list of Boundary faces, that is, those faces of // "mesh" that intersect faces of "otherMesh". Array_<int> faceType(mesh.getNumFaces(), Unknown); for (std::set<int>::iterator iter = insideFaces.begin(); iter != insideFaces.end(); ++iter) faceType[*iter] = Boundary; for (int i = 0; i < (int) faceType.size(); i++) { if (faceType[i] == Unknown) { // Trace a ray from its center to determine whether it is inside. const Vec3 origin_O = X_OM * mesh.findCentroid(i); const UnitVec3 direction_O = X_OM.R()* mesh.getFaceNormal(i); Real distance; int face; Vec2 uv; if ( otherMesh.intersectsRay(origin_O, direction_O, distance, face, uv) && ~direction_O*otherMesh.getFaceNormal(face) > 0) { faceType[i] = Inside; insideFaces.insert(i); } else faceType[i] = Outside; // Recursively mark adjacent inside or outside Faces. tagFaces(mesh, faceType, insideFaces, i, 0); } } } //TODO: the following method uses depth-first recursion to iterate through //unmarked faces. For a large mesh this was observed to produce a stack //overflow in OpenSim. Here we limit the recursion depth; after we get that //deep we'll pop back out and do another expensive intersectsRay() test in //the method above. static const int MaxRecursionDepth = 500; void ContactTracker::TriangleMeshTriangleMesh:: tagFaces(const ContactGeometry::TriangleMesh& mesh, Array_<int>& faceType, std::set<int>& triangles, int index, int depth) const { for (int i = 0; i < 3; i++) { const int edge = mesh.getFaceEdge(index, i); const int face = (mesh.getEdgeFace(edge, 0) == index ? mesh.getEdgeFace(edge, 1) : mesh.getEdgeFace(edge, 0)); if (faceType[face] == Unknown) { faceType[face] = faceType[index]; if (faceType[index] > 0) triangles.insert(face); if (depth < MaxRecursionDepth) tagFaces(mesh, faceType, triangles, face, depth+1); } } } bool ContactTracker::TriangleMeshTriangleMesh::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::TriangleMeshTriangleMesh::predictContact() not implemented yet."); return false; } bool ContactTracker::TriangleMeshTriangleMesh::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::TriangleMeshTriangleMesh::initializeContact() not implemented yet."); return false; } //============================================================================== // CONVEX IMPLICIT SURFACE PAIR CONTACT TRACKER //============================================================================== // This will return an elliptical point contact. bool ContactTracker::ConvexImplicitPair::trackContact (const Contact& priorStatus, const Transform& X_GA, const ContactGeometry& shapeA, const Transform& X_GB, const ContactGeometry& shapeB, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT_ALWAYS ( shapeA.isConvex() && shapeA.isSmooth() && shapeB.isConvex() && shapeB.isSmooth(), "ContactTracker::ConvexImplicitPair::trackContact()"); // We'll work in the shape A frame. const Transform X_AB = ~X_GA*X_GB; // 63 flops const Rotation& R_AB = X_AB.R(); // 1. Get a rough guess at the contact points P and Q and contact normal. Vec3 pointP_A, pointQ_B; // on A and B, resp. UnitVec3 norm_A; int numMPRIters; const bool mightBeContact = estimateConvexImplicitPairContactUsingMPR (shapeA, shapeB, X_AB, pointP_A, pointQ_B, norm_A, numMPRIters); #ifdef MPR_DEBUG std::cout << "MPR: " << (mightBeContact?"MAYBE":"NO") << std::endl; std::cout << " P=" << X_GA*pointP_A << " Q=" << X_GB*pointQ_B << std::endl; std::cout << " N=" << X_GA.R()*norm_A << std::endl; #endif if (!mightBeContact) { currentStatus.clear(); // definitely not touching return true; // successful return } // 2. Refine the contact points to near machine precision. const Real accuracyRequested = SignificantReal; Real accuracyAchieved; int numNewtonIters; bool converged = refineImplicitPair(shapeA, pointP_A, shapeB, pointQ_B, X_AB, accuracyRequested, accuracyAchieved, numNewtonIters); const Vec3 pointQ_A = X_AB*pointQ_B; // Q on B, measured & expressed in A // 3. Compute the curvatures and surface normals of the two surfaces at // P and Q. Once we have the first normal we can check whether there was // actually any contact and duck out early if not. Rotation R_AP; Vec2 curvatureP; shapeA.calcCurvature(pointP_A, curvatureP, R_AP); // If the surfaces are in contact then the vector from Q on surface B // (supposedly inside A) to P on surface A (supposedly inside B) should be // aligned with the outward normal on A. const Real depth = dot(pointP_A-pointQ_A, R_AP.z()); #ifdef MPR_DEBUG printf("MPR %2d iters, Newton %2d iters->accuracy=%g depth=%g\n", numMPRIters, numNewtonIters, accuracyAchieved, depth); #endif if (depth <= 0) { currentStatus.clear(); // not touching return true; // successful return } // The surfaces are in contact. Rotation R_BQ; Vec2 curvatureQ; shapeB.calcCurvature(pointQ_B, curvatureQ, R_BQ); const UnitVec3 maxDirB_A(R_AB*R_BQ.x()); // re-express in A // 4. Compute the effective contact frame C and corresponding relative // curvatures. Transform X_AC; Vec2 curvatureC; // Define the contact frame origin to be at the midpoint of P and Q. X_AC.updP() = (pointP_A+pointQ_A)/2; // Determine the contact frame orientations and composite curvatures. ContactGeometry::combineParaboloids(R_AP, curvatureP, maxDirB_A, curvatureQ, X_AC.updR(), curvatureC); // 5. Return the elliptical point contact for force generation. currentStatus = EllipticalPointContact(priorStatus.getSurface1(), priorStatus.getSurface2(), X_AB, X_AC, curvatureC, depth); return true; // success } bool ContactTracker::ConvexImplicitPair::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::ConvexImplicitPair::predictContact() not implemented yet."); return false; } bool ContactTracker::ConvexImplicitPair::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::ConvexImplicitPair::initializeContact() not implemented yet."); return false; } //============================================================================== // GENERAL IMPLICIT SURFACE PAIR CONTACT TRACKER //============================================================================== // This will return an elliptical point contact. TODO: should return a set // of contacts. //TODO: not implemented yet -- this is just the Convex-convex code here. bool ContactTracker::GeneralImplicitPair::trackContact (const Contact& priorStatus, const Transform& X_GA, const ContactGeometry& shapeA, const Transform& X_GB, const ContactGeometry& shapeB, Real cutoff, Contact& currentStatus) const { SimTK_ASSERT_ALWAYS ( shapeA.isSmooth() && shapeB.isSmooth(), "ContactTracker::GeneralImplicitPair::trackContact()"); // TODO: this won't work unless the shapes are actually convex. return ConvexImplicitPair(shapeA.getTypeId(),shapeB.getTypeId()) .trackContact(priorStatus, X_GA, shapeA, X_GB, shapeB, cutoff, currentStatus); } bool ContactTracker::GeneralImplicitPair::predictContact (const Contact& priorStatus, const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& predictedStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::GeneralImplicitPair::predictContact() not implemented yet."); return false; } bool ContactTracker::GeneralImplicitPair::initializeContact (const Transform& X_GS1, const SpatialVec& V_GS1, const ContactGeometry& surface1, const Transform& X_GS2, const SpatialVec& V_GS2, const ContactGeometry& surface2, Real cutoff, Real intervalOfInterest, Contact& contactStatus) const { SimTK_ASSERT_ALWAYS(!"implemented", "ContactTracker::GeneralImplicitPair::initializeContact() not implemented yet."); return false; } } // namespace SimTK
Java
using System; namespace TheUnacademicPortfolio.Commons.Dtos { public class BaseDto { public Guid Id { get; set; } } }
Java
/* * Copyright 2015 - 2021 TU Dortmund * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.learnlib.alex.learning.services; import de.learnlib.alex.data.entities.ProjectEnvironment; import de.learnlib.alex.data.entities.ProjectUrl; import de.learnlib.alex.data.entities.actions.Credentials; import java.util.HashMap; import java.util.Map; /** * Class to mange a URL and get URL based on this. */ public class BaseUrlManager { private final Map<String, ProjectUrl> urlMap; /** Advanced constructor which sets the base url field. */ public BaseUrlManager(ProjectEnvironment environment) { this.urlMap = new HashMap<>(); environment.getUrls().forEach(u -> this.urlMap.put(u.getName(), u)); } /** * Get the absolute URL of a path, i.e. based on the base url (base url + '/' + path'), as String * and insert the credentials if possible. * * @param path * The path to append on the base url. * @param credentials * The credentials to insert into the URL. * @return An absolute URL as String */ public String getAbsoluteUrl(String urlName, String path, Credentials credentials) { final String url = combineUrls(urlMap.get(urlName).getUrl(), path); return BaseUrlManager.getUrlWithCredentials(url, credentials); } public String getAbsoluteUrl(String urlName, String path) { final String url = combineUrls(urlMap.get(urlName).getUrl(), path); return BaseUrlManager.getUrlWithCredentials(url, null); } /** * Append apiPath to basePath and make sure that only one '/' is between them. * * @param basePath * The prefix of the new URL. * @param apiPath * The suffix of the new URL. * @return The combined URL. */ private String combineUrls(String basePath, String apiPath) { if (basePath.endsWith("/") && apiPath.startsWith("/")) { // both have a '/' -> remove one return basePath + apiPath.substring(1); } else if (!basePath.endsWith("/") && !apiPath.startsWith("/")) { // no one has a '/' -> add one return basePath + "/" + apiPath; } else { // exact 1. '/' in between -> good to go return basePath + apiPath; } } private static String getUrlWithCredentials(String url, Credentials credentials) { if (credentials != null && credentials.areValid()) { return url.replaceFirst("^(http[s]?://)", "$1" + credentials.getName() + ":" + credentials.getPassword() + "@"); } else { return url; } } }
Java
/* * Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedciine.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.socraticgrid.hl7.services.orders.model.types.orderitems; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.socraticgrid.hl7.services.orders.model.OrderItem; import org.socraticgrid.hl7.services.orders.model.primatives.Code; import org.socraticgrid.hl7.services.orders.model.primatives.Identifier; import org.socraticgrid.hl7.services.orders.model.primatives.Period; import org.socraticgrid.hl7.services.orders.model.primatives.Quantity; import org.socraticgrid.hl7.services.orders.model.primatives.Ratio; public class MedicationOrderItem extends OrderItem { /** * */ private static final long serialVersionUID = 1L; private String additionalDosageIntructions; private String comment; private Quantity dispenseQuantity= new Quantity(); private String dosageInstructions; private Code dosageMethod; private Quantity dosageQuantity = new Quantity(); private Ratio dosageRate = new Ratio(); private Code dosageSite = new Code(); private Date dosageTiming; private Period dosageTimingPeriod = new Period(); private List<Identifier> drug = new ArrayList<Identifier>(0); private Date endDate; private Quantity expectedSupplyDuration = new Quantity(); private Ratio maxDosePerPeriod = new Ratio(); private List<Identifier> medication = new ArrayList<Identifier>(0); private int numberOfRepeatsAllowed=0; private Code prescriber; private Code route = new Code(); private String schedule; private Date startDate; /** * @return the additionalDosageIntructions */ public String getAdditionalDosageIntructions() { return additionalDosageIntructions; } /** * @return the comment */ public String getComment() { return comment; } /** * @return the dispenseQuantity */ public Quantity getDispenseQuantity() { return dispenseQuantity; } /** * @return the dosageInstructions */ public String getDosageInstructions() { return dosageInstructions; } /** * @return the dosageMethod */ public Code getDosageMethod() { return dosageMethod; } /** * @return the dosageQuantity */ public Quantity getDosageQuantity() { return dosageQuantity; } /** * @return the dosageRate */ public Ratio getDosageRate() { return dosageRate; } /** * @return the dosageSite */ public Code getDosageSite() { return dosageSite; } /** * @return the dosageTiming */ public Date getDosageTiming() { return dosageTiming; } /** * @return the dosageTimingPeriod */ public Period getDosageTimingPeriod() { return dosageTimingPeriod; } /** * @return the drug */ public List<Identifier> getDrug() { return drug; } /** * @return the endDate */ public Date getEndDate() { return endDate; } /** * @return the expectedSupplyDuration */ public Quantity getExpectedSupplyDuration() { return expectedSupplyDuration; } /** * @return the maxDosePerPeriod */ public Ratio getMaxDosePerPeriod() { return maxDosePerPeriod; } /** * @return the medication */ public List<Identifier> getMedication() { return medication; } /** * @return the numberOfRepeatsAllowed */ public int getNumberOfRepeatsAllowed() { return numberOfRepeatsAllowed; } /** * @return the prescriber */ public Code getPrescriber() { return prescriber; } /** * @return the route */ public Code getRoute() { return route; } /** * @return the schedule */ public String getSchedule() { return schedule; } /** * @return the startDate */ public Date getStartDate() { return startDate; } /** * @param additionalDosageIntructions the additionalDosageIntructions to set */ public void setAdditionalDosageIntructions(String additionalDosageIntructions) { this.additionalDosageIntructions = additionalDosageIntructions; } /** * @param comment the comment to set */ public void setComment(String comment) { this.comment = comment; } /** * @param dispenseQuantity the dispenseQuantity to set */ public void setDispenseQuantity(Quantity dispenseQuantity) { this.dispenseQuantity = dispenseQuantity; } /** * @param dosageInstructions the dosageInstructions to set */ public void setDosageInstructions(String dosageInstructions) { this.dosageInstructions = dosageInstructions; } /** * @param dosageMethod the dosageMethod to set */ public void setDosageMethod(Code dosageMethod) { this.dosageMethod = dosageMethod; } /** * @param dosageQuantity the dosageQuantity to set */ public void setDosageQuantity(Quantity dosageQuantity) { this.dosageQuantity = dosageQuantity; } /** * @param dosageRate the dosageRate to set */ public void setDosageRate(Ratio dosageRate) { this.dosageRate = dosageRate; } /** * @param dosageSite the dosageSite to set */ public void setDosageSite(Code dosageSite) { this.dosageSite = dosageSite; } /** * @param dosageTiming the dosageTiming to set */ public void setDosageTiming(Date dosageTiming) { this.dosageTiming = dosageTiming; } /** * @param dosageTimingPeriod the dosageTimingPeriod to set */ public void setDosageTimingPeriod(Period dosageTimingPeriod) { this.dosageTimingPeriod = dosageTimingPeriod; } /** * @param drug the drug to set */ public void setDrug(List<Identifier> drug) { this.drug = drug; } /** * @param endDate the endDate to set */ public void setEndDate(Date endDate) { this.endDate = endDate; } /** * @param expectedSupplyDuration the expectedSupplyDuration to set */ public void setExpectedSupplyDuration(Quantity expectedSupplyDuration) { this.expectedSupplyDuration = expectedSupplyDuration; } /** * @param maxDosePerPeriod the maxDosePerPeriod to set */ public void setMaxDosePerPeriod(Ratio maxDosePerPeriod) { this.maxDosePerPeriod = maxDosePerPeriod; } /** * @param medication the medication to set */ public void setMedication(List<Identifier> medication) { this.medication = medication; } /** * @param numberOfRepeatsAllowed the numberOfRepeatsAllowed to set */ public void setNumberOfRepeatsAllowed(int numberOfRepeatsAllowed) { this.numberOfRepeatsAllowed = numberOfRepeatsAllowed; } /** * @param prescriber the prescriber to set */ public void setPrescriber(Code prescriber) { this.prescriber = prescriber; } /** * @param route the route to set */ public void setRoute(Code route) { this.route = route; } /** * @param schedule the schedule to set */ public void setSchedule(String schedule) { this.schedule = schedule; } /** * @param startDate the startDate to set */ public void setStartDate(Date startDate) { this.startDate = startDate; } }
Java