repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
bugcy013/opennms-tmp-tools
opennms-webapp/src/main/java/org/opennms/dashboard/client/ResourceGraph.java
3091
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.dashboard.client; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.ui.Image; /** * <p>ResourceGraph class.</p> * * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> * @version $Id: $ * @since 1.8.1 */ public class ResourceGraph extends Image { /** * <p>Constructor for ResourceGraph.</p> */ public ResourceGraph() { super(); } /** * <p>displayNoGraph</p> */ public void displayNoGraph() { setUrl("images/rrd/error.png"); } /** * <p>setGraph</p> * * @param resourceId a {@link java.lang.String} object. * @param reportName a {@link java.lang.String} object. * @param start a {@link java.lang.String} object. * @param end a {@link java.lang.String} object. */ public void setGraph(String resourceId, String reportName, String start, String end) { setUrl(buildGraphUrl(resourceId, reportName, start, end)); } /** * <p>prefetchGraph</p> * * @param resourceId a {@link java.lang.String} object. * @param reportName a {@link java.lang.String} object. * @param start a {@link java.lang.String} object. * @param end a {@link java.lang.String} object. */ public void prefetchGraph(String resourceId, String reportName, String start, String end) { Image.prefetch(buildGraphUrl(resourceId, reportName, start, end)); } private String buildGraphUrl(String resourceId, String report, String start, String end) { return "graph/graph.png?resourceId=" + URL.encodeQueryString(resourceId) + "&report=" + URL.encodeQueryString(report) + "&start=" + start + "&end=" + end; } }
gpl-2.0
TEAMMATES/teammates
src/test/java/teammates/ui/webapi/JsonResultTest.java
1512
package teammates.ui.webapi; import java.util.ArrayList; import java.util.List; import javax.servlet.http.Cookie; import org.testng.annotations.Test; import teammates.test.BaseTestCase; import teammates.test.MockHttpServletResponse; import teammates.ui.output.MessageOutput; /** * SUT: {@link JsonResult}. */ public class JsonResultTest extends BaseTestCase { @Test public void testConstructorAndSendResponse() throws Exception { ______TS("json result with output message only"); JsonResult result = new JsonResult("output message"); MessageOutput output = (MessageOutput) result.getOutput(); assertEquals("output message", output.getMessage()); assertEquals(0, result.getCookies().size()); MockHttpServletResponse resp = new MockHttpServletResponse(); result.send(resp); assertEquals(0, resp.getCookies().size()); ______TS("json result with output message and cookies"); List<Cookie> cookies = new ArrayList<>(); cookies.add(new Cookie("cookieName", "cookieValue")); result = new JsonResult(new MessageOutput("output message"), cookies); output = (MessageOutput) result.getOutput(); assertEquals("output message", output.getMessage()); assertEquals(1, result.getCookies().size()); MockHttpServletResponse respWithCookie = new MockHttpServletResponse(); result.send(respWithCookie); assertEquals(1, respWithCookie.getCookies().size()); } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/jdktools/modules/jpda/src/test/java/org/apache/harmony/jpda/tests/jdwp/Events/Class2Prepare.java
1254
/* * 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. */ /** * @author Anton V. Karnachuk */ /** * Created on 06.04.2005 */ package org.apache.harmony.jpda.tests.jdwp.Events; import org.apache.harmony.jpda.tests.framework.LogWriter; /** * Internal class used in ClassPrepareTest */ class Class2Prepare { public Class2Prepare(LogWriter logWriter) { super(); logWriter.println("Class2Prepare default constructor is called"); } }
gpl-2.0
jeffgdotorg/opennms
features/dhcpd/src/main/java/org/opennms/features/dhcpd/Dhcpd.java
1602
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2019 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2019 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.dhcpd; import java.io.IOException; import org.opennms.features.dhcpd.impl.TransactionImpl; public interface Dhcpd { Transaction executeTransaction(final String hostAddress, final String macAddress, final boolean relayMode, String myIpAddress, final boolean extendedMode, final String requestIpAddress, final int timeout) throws IOException; void shutdown(); }
gpl-2.0
lewurm/graal
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/HotSpotReferenceMap.java
6929
/* * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.hotspot; import java.io.*; import java.util.*; import com.oracle.graal.api.code.CodeUtil.RefMapFormatter; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.common.*; public class HotSpotReferenceMap implements ReferenceMap, Serializable { private static final long serialVersionUID = -1052183095979496819L; private static final int BITS_PER_WORD = 3; /** * Contains 3 bits per scalar register, and n*3 bits per n-word vector register (e.g., on a * 64-bit system, a 256-bit vector register requires 12 reference map bits). * <p> * These bits can have the following values (LSB first): * * <pre> * 000 - contains no references * 100 - contains a wide oop * 110 - contains a narrow oop in the lower half * 101 - contains a narrow oop in the upper half * 111 - contains two narrow oops * </pre> */ private final BitSet registerRefMap; /** * Contains 3 bits per stack word. * <p> * These bits can have the following values (LSB first): * * <pre> * 000 - contains no references * 100 - contains a wide oop * 110 - contains a narrow oop in the lower half * 101 - contains a narrow oop in the upper half * 111 - contains two narrow oops * </pre> */ private final BitSet frameRefMap; private final TargetDescription target; public HotSpotReferenceMap(int registerCount, int frameSlotCount, TargetDescription target) { if (registerCount > 0) { this.registerRefMap = new BitSet(registerCount * BITS_PER_WORD); } else { this.registerRefMap = null; } this.frameRefMap = new BitSet(frameSlotCount * BITS_PER_WORD); this.target = target; } private static void setOop(BitSet map, int startIdx, LIRKind kind) { int length = kind.getPlatformKind().getVectorLength(); map.clear(BITS_PER_WORD * startIdx, BITS_PER_WORD * (startIdx + length) - 1); for (int i = 0, idx = BITS_PER_WORD * startIdx; i < length; i++, idx += BITS_PER_WORD) { if (kind.isReference(i)) { map.set(idx); } } } private static void setNarrowOop(BitSet map, int idx, LIRKind kind) { int length = kind.getPlatformKind().getVectorLength(); int nextIdx = idx + (length + 1) / 2; map.clear(BITS_PER_WORD * idx, BITS_PER_WORD * nextIdx - 1); for (int i = 0, regIdx = BITS_PER_WORD * idx; i < length; i += 2, regIdx += BITS_PER_WORD) { if (kind.isReference(i)) { map.set(regIdx); map.set(regIdx + 1); } if ((i + 1) < length && kind.isReference(i + 1)) { map.set(regIdx); map.set(regIdx + 2); } } } public void setRegister(int idx, LIRKind kind) { if (kind.isDerivedReference()) { throw GraalInternalError.shouldNotReachHere("derived reference cannot be inserted in ReferenceMap"); } PlatformKind platformKind = kind.getPlatformKind(); int bytesPerElement = target.getSizeInBytes(platformKind) / platformKind.getVectorLength(); if (bytesPerElement == target.wordSize) { setOop(registerRefMap, idx, kind); } else if (bytesPerElement == target.wordSize / 2) { setNarrowOop(registerRefMap, idx, kind); } else { assert kind.isValue() : "unsupported reference kind " + kind; } } public void setStackSlot(int offset, LIRKind kind) { if (kind.isDerivedReference()) { throw GraalInternalError.shouldNotReachHere("derived reference cannot be inserted in ReferenceMap"); } PlatformKind platformKind = kind.getPlatformKind(); int bytesPerElement = target.getSizeInBytes(platformKind) / platformKind.getVectorLength(); assert offset % bytesPerElement == 0 : "unaligned value in ReferenceMap"; if (bytesPerElement == target.wordSize) { setOop(frameRefMap, offset / target.wordSize, kind); } else if (bytesPerElement == target.wordSize / 2) { if (platformKind.getVectorLength() > 1) { setNarrowOop(frameRefMap, offset / target.wordSize, kind); } else { // in this case, offset / target.wordSize may not divide evenly // so setNarrowOop won't work correctly int idx = offset / target.wordSize; if (kind.isReference(0)) { frameRefMap.set(BITS_PER_WORD * idx); if (offset % target.wordSize == 0) { frameRefMap.set(BITS_PER_WORD * idx + 1); } else { frameRefMap.set(BITS_PER_WORD * idx + 2); } } } } else { assert kind.isValue() : "unknown reference kind " + kind; } } public boolean hasRegisterRefMap() { return registerRefMap != null && registerRefMap.size() > 0; } public boolean hasFrameRefMap() { return frameRefMap != null && frameRefMap.size() > 0; } public void appendRegisterMap(StringBuilder sb, RefMapFormatter formatter) { for (int reg = registerRefMap.nextSetBit(0); reg >= 0; reg = registerRefMap.nextSetBit(reg + BITS_PER_WORD)) { sb.append(' ').append(formatter.formatRegister(reg / BITS_PER_WORD)); } } public void appendFrameMap(StringBuilder sb, RefMapFormatter formatter) { for (int slot = frameRefMap.nextSetBit(0); slot >= 0; slot = frameRefMap.nextSetBit(slot + BITS_PER_WORD)) { sb.append(' ').append(formatter.formatStackSlot(slot / BITS_PER_WORD)); } } }
gpl-2.0
xiaosea/easyreader
src/main/java/org/geometerplus/android/fbreader/api/ApiService.java
1077
/* * Copyright (C) 2009-2014 Geometer Plus <contact@geometerplus.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.android.fbreader.api; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class ApiService extends Service { @Override public IBinder onBind(Intent intent) { return new ApiServerImplementation(this); } }
gpl-2.0
openjdk/jdk7u
jdk/src/share/classes/sun/awt/im/CompositionAreaHandler.java
12421
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.awt.im; import java.awt.Component; import java.awt.Container; import java.awt.Rectangle; import java.awt.event.InputMethodEvent; import java.awt.event.InputMethodListener; import java.awt.font.TextAttribute; import java.awt.font.TextHitInfo; import java.awt.im.InputMethodRequests; import java.text.AttributedCharacterIterator; import java.text.AttributedCharacterIterator.Attribute; import java.text.AttributedString; /** * A composition area handler handles events and input method requests for * the composition area. Typically each input method context has its own * composition area handler if it supports passive clients or below-the-spot * input, but all handlers share a single composition area. * * @author JavaSoft International */ class CompositionAreaHandler implements InputMethodListener, InputMethodRequests { private static CompositionArea compositionArea; private static Object compositionAreaLock = new Object(); private static CompositionAreaHandler compositionAreaOwner; // synchronized through compositionArea private AttributedCharacterIterator composedText; private TextHitInfo caret = null; private Component clientComponent = null; private InputMethodContext inputMethodContext; /** * Constructs the composition area handler. */ CompositionAreaHandler(InputMethodContext context) { inputMethodContext = context; } /** * Creates the composition area. */ private void createCompositionArea() { synchronized(compositionAreaLock) { compositionArea = new CompositionArea(); if (compositionAreaOwner != null) { compositionArea.setHandlerInfo(compositionAreaOwner, inputMethodContext); } // If the client component is an active client using below-the-spot style, then // make the composition window undecorated without a title bar. if(clientComponent!=null){ InputMethodRequests req = clientComponent.getInputMethodRequests(); if (req != null && inputMethodContext.useBelowTheSpotInput()) { setCompositionAreaUndecorated(true); } } } } void setClientComponent(Component clientComponent) { this.clientComponent = clientComponent; } /** * Grabs the composition area, makes this handler its owner, and installs * the handler and its input context into the composition area for event * and input method request handling. * If doUpdate is true, updates the composition area with previously sent * composed text. */ void grabCompositionArea(boolean doUpdate) { synchronized (compositionAreaLock) { if (compositionAreaOwner != this) { compositionAreaOwner = this; if (compositionArea != null) { compositionArea.setHandlerInfo(this, inputMethodContext); } if (doUpdate) { // Create the composition area if necessary if ((composedText != null) && (compositionArea == null)) { createCompositionArea(); } if (compositionArea != null) { compositionArea.setText(composedText, caret); } } } } } /** * Releases and closes the composition area if it is currently owned by * this composition area handler. */ void releaseCompositionArea() { synchronized (compositionAreaLock) { if (compositionAreaOwner == this) { compositionAreaOwner = null; if (compositionArea != null) { compositionArea.setHandlerInfo(null, null); compositionArea.setText(null, null); } } } } /** * Releases and closes the composition area if it has been created, * independent of the current owner. */ static void closeCompositionArea() { if (compositionArea != null) { synchronized (compositionAreaLock) { compositionAreaOwner = null; compositionArea.setHandlerInfo(null, null); compositionArea.setText(null, null); } } } /** * Returns whether the composition area is currently visible */ boolean isCompositionAreaVisible() { if (compositionArea != null) { return compositionArea.isCompositionAreaVisible(); } return false; } /** * Shows or hides the composition Area */ void setCompositionAreaVisible(boolean visible) { if (compositionArea != null) { compositionArea.setCompositionAreaVisible(visible); } } void processInputMethodEvent(InputMethodEvent event) { if (event.getID() == InputMethodEvent.INPUT_METHOD_TEXT_CHANGED) { inputMethodTextChanged(event); } else { caretPositionChanged(event); } } /** * set the compositionArea frame decoration */ void setCompositionAreaUndecorated(boolean undecorated) { if (compositionArea != null) { compositionArea.setCompositionAreaUndecorated(undecorated); } } // // InputMethodListener methods // private static final Attribute[] IM_ATTRIBUTES = { TextAttribute.INPUT_METHOD_HIGHLIGHT }; public void inputMethodTextChanged(InputMethodEvent event) { AttributedCharacterIterator text = event.getText(); int committedCharacterCount = event.getCommittedCharacterCount(); // extract composed text and prepare it for display composedText = null; caret = null; if (text != null && committedCharacterCount < text.getEndIndex() - text.getBeginIndex()) { // Create the composition area if necessary if (compositionArea == null) { createCompositionArea(); } // copy the composed text AttributedString composedTextString; composedTextString = new AttributedString(text, text.getBeginIndex() + committedCharacterCount, // skip over committed text text.getEndIndex(), IM_ATTRIBUTES); composedTextString.addAttribute(TextAttribute.FONT, compositionArea.getFont()); composedText = composedTextString.getIterator(); caret = event.getCaret(); } if (compositionArea != null) { compositionArea.setText(composedText, caret); } // send any committed text to the text component if (committedCharacterCount > 0) { inputMethodContext.dispatchCommittedText(((Component) event.getSource()), text, committedCharacterCount); // this may have changed the text location, so reposition the window if (isCompositionAreaVisible()) { compositionArea.updateWindowLocation(); } } // event has been handled, so consume it event.consume(); } public void caretPositionChanged(InputMethodEvent event) { if (compositionArea != null) { compositionArea.setCaret(event.getCaret()); } // event has been handled, so consume it event.consume(); } // // InputMethodRequests methods // /** * Returns the input method request handler of the client component. * When using the composition window for an active client (below-the-spot * input), input method requests that do not relate to the display of * the composed text are forwarded to the client component. */ InputMethodRequests getClientInputMethodRequests() { if (clientComponent != null) { return clientComponent.getInputMethodRequests(); } return null; } public Rectangle getTextLocation(TextHitInfo offset) { synchronized (compositionAreaLock) { if (compositionAreaOwner == this && isCompositionAreaVisible()) { return compositionArea.getTextLocation(offset); } else if (composedText != null) { // there's composed text, but it's not displayed, so fake a rectangle return new Rectangle(0, 0, 0, 10); } else { InputMethodRequests requests = getClientInputMethodRequests(); if (requests != null) { return requests.getTextLocation(offset); } else { // passive client, no composed text, so fake a rectangle return new Rectangle(0, 0, 0, 10); } } } } public TextHitInfo getLocationOffset(int x, int y) { synchronized (compositionAreaLock) { if (compositionAreaOwner == this && isCompositionAreaVisible()) { return compositionArea.getLocationOffset(x, y); } else { return null; } } } public int getInsertPositionOffset() { InputMethodRequests req = getClientInputMethodRequests(); if (req != null) { return req.getInsertPositionOffset(); } // we don't have access to the client component's text. return 0; } private static final AttributedCharacterIterator EMPTY_TEXT = (new AttributedString("")).getIterator(); public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, Attribute[] attributes) { InputMethodRequests req = getClientInputMethodRequests(); if(req != null) { return req.getCommittedText(beginIndex, endIndex, attributes); } // we don't have access to the client component's text. return EMPTY_TEXT; } public int getCommittedTextLength() { InputMethodRequests req = getClientInputMethodRequests(); if(req != null) { return req.getCommittedTextLength(); } // we don't have access to the client component's text. return 0; } public AttributedCharacterIterator cancelLatestCommittedText(Attribute[] attributes) { InputMethodRequests req = getClientInputMethodRequests(); if(req != null) { return req.cancelLatestCommittedText(attributes); } // we don't have access to the client component's text. return null; } public AttributedCharacterIterator getSelectedText(Attribute[] attributes) { InputMethodRequests req = getClientInputMethodRequests(); if(req != null) { return req.getSelectedText(attributes); } // we don't have access to the client component's text. return EMPTY_TEXT; } }
gpl-2.0
arodchen/MaxSim
maxine/com.oracle.max.tests/src/jtt/except/BC_idiv.java
1267
/* * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @Harness: java * @Runs: (1,2)=0; * @Runs: (11,0)=!java.lang.ArithmeticException */ package jtt.except; public class BC_idiv { public static int test(int a, int b) { return a / b; } }
gpl-2.0
TEAMMATES/teammates
src/client/java/teammates/client/connector/DatastoreClient.java
1968
package teammates.client.connector; import com.google.cloud.datastore.DatastoreOptions; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; import teammates.client.util.ClientProperties; import teammates.common.util.Config; import teammates.logic.core.LogicStarter; import teammates.storage.api.OfyHelper; /** * Enables access to any datastore (local/production). */ public abstract class DatastoreClient { /** * Gets the Objectify instance. */ protected Objectify ofy() { return ObjectifyService.ofy(); } /** * Performs the entire operation routine: setting up connection to the back-end, * performing the operation itself, and tearing down the connection. */ protected void doOperationRemotely() { String appUrl = ClientProperties.TARGET_URL.replaceAll("^https?://", ""); String appDomain = appUrl.split(":")[0]; int appPort = appUrl.contains(":") ? Integer.parseInt(appUrl.split(":")[1]) : 443; System.out.println("--- Starting remote operation ---"); System.out.println("Going to connect to:" + appDomain + ":" + appPort); DatastoreOptions.Builder builder = DatastoreOptions.newBuilder().setProjectId(Config.APP_ID); if (ClientProperties.isTargetUrlDevServer()) { builder.setHost(ClientProperties.TARGET_URL); } ObjectifyService.init(new ObjectifyFactory(builder.build().getService())); OfyHelper.registerEntityClasses(); try (Closeable objectifySession = ObjectifyService.begin()) { LogicStarter.initializeDependencies(); doOperation(); } System.out.println("--- Remote operation completed ---"); } /** * Performs the remote operation to the back-end. */ protected abstract void doOperation(); }
gpl-2.0
logicmoo/jrelisp-abcl-ws
TheRealDiffernce/lisp/Do.java
8769
/* * Do.java * * Copyright (C) 2003-2006 Peter Graves * $Id: Do.java,v 1.21 2006/03/19 19:09:54 piso Exp $ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.armedbear.lisp; import static org.armedbear.lisp.Lisp.*; public final class Do { // ### do private static final SpecialOperator DO = new sf_do(); private static final class sf_do extends SpecialOperator { sf_do() { super(Symbol.DO, "varlist endlist &body body"); } public LispObject execute(LispObject args, Environment env) { return _do(args, env, false); } }; // ### do* private static final SpecialOperator DO_STAR = new sf_do_star(); private static final class sf_do_star extends SpecialOperator { sf_do_star() { super(Symbol.DO_STAR, "varlist endlist &body body"); } public LispObject execute(LispObject args, Environment env) { return _do(args, env, true); } }; /* removal of synthetic method (was private)*/ static final LispObject _do(LispObject args, Environment env, boolean sequential) throws ConditionThrowable { LispObject varlist = args.car(); LispObject second = args.cadr(); LispObject end_test_form = second.car(); LispObject result_forms = second.cdr(); LispObject body = args.cddr(); // Process variable specifications. final int numvars = varlist.length(); Symbol[] vars = new Symbol[numvars]; LispObject[] initforms = new LispObject[numvars]; LispObject[] stepforms = new LispObject[numvars]; for (int i = 0; i < numvars; i++) { final LispObject varspec = varlist.car(); if (varspec instanceof Cons) { vars[i] = checkSymbol(varspec.car()); initforms[i] = varspec.cadr(); // Is there a step form? if (varspec.cddr() != NIL) stepforms[i] = varspec.caddr(); } else { // Not a cons, must be a symbol. vars[i] = checkSymbol(varspec); initforms[i] = NIL; } varlist = varlist.cdr(); } final LispThread thread = LispThread.currentThread(); final LispObject stack = thread.getStack(); final SpecialBinding lastSpecialBinding = thread.lastSpecialBinding; // Process declarations. LispObject specials = NIL; while (body != NIL) { LispObject obj = body.car(); if (obj instanceof Cons && obj.car() == Symbol.DECLARE) { LispObject decls = obj.cdr(); while (decls != NIL) { LispObject decl = decls.car(); if (decl instanceof Cons && decl.car() == Symbol.SPECIAL) { LispObject names = decl.cdr(); while (names != NIL) { specials = new Cons(names.car(), specials); names = names.cdr(); } } decls = decls.cdr(); } body = body.cdr(); } else break; } final Environment ext = new Environment(env); for (int i = 0; i < numvars; i++) { Symbol var = vars[i]; LispObject value = eval(initforms[i], (sequential ? ext : env), thread); if (specials != NIL && memq(var, specials)) thread.bindSpecial(var, value); else if (var.isSpecialVariable()) thread.bindSpecial(var, value); else ext.bind(var, value); } LispObject list = specials; while (list != NIL) { ext.declareSpecial(checkSymbol(list.car())); list = list.cdr(); } // Look for tags. LispObject remaining = body; while (remaining != NIL) { LispObject current = remaining.car(); remaining = remaining.cdr(); if (current instanceof Cons) continue; // It's a tag. ext.addTagBinding(current, remaining); } try { // Implicit block. ext.addBlock(NIL, new LispObject()); while (true) { // Execute body. // Test for termination. if (eval(end_test_form, ext, thread) != NIL) break; remaining = body; while (remaining != NIL) { LispObject current = remaining.car(); if (current instanceof Cons) { try { // Handle GO inline if possible. if (current.car() == Symbol.GO) { LispObject tag = current.cadr(); Binding binding = ext.getTagBinding(tag); if (binding != null && binding.value != null) { remaining = binding.value; continue; } throw new Go(tag); } eval(current, ext, thread); } catch (Go go) { LispObject tag = go.getTag(); Binding binding = ext.getTagBinding(tag); if (binding != null && binding.value != null) { remaining = binding.value; thread.setStack(stack); continue; } throw go; } } remaining = remaining.cdr(); } // Update variables. if (sequential) { for (int i = 0; i < numvars; i++) { LispObject step = stepforms[i]; if (step != null) { Symbol symbol = vars[i]; LispObject value = eval(step, ext, thread); if (symbol.isSpecialVariable() || ext.isDeclaredSpecial(symbol)) thread.rebindSpecial(symbol, value); else ext.rebind(symbol, value); } } } else { // Evaluate step forms. LispObject results[] = new LispObject[numvars]; for (int i = 0; i < numvars; i++) { LispObject step = stepforms[i]; if (step != null) { LispObject result = eval(step, ext, thread); results[i] = result; } } // Update variables. for (int i = 0; i < numvars; i++) { if (results[i] != null) { Symbol symbol = vars[i]; LispObject value = results[i]; if (symbol.isSpecialVariable() || ext.isDeclaredSpecial(symbol)) thread.rebindSpecial(symbol, value); else ext.rebind(symbol, value); } } } if (interrupted) handleInterrupt(); } LispObject result = progn(result_forms, ext, thread); return result; } catch (Return ret) { if (ret.getTag() == NIL) { thread.setStack(stack); return ret.getResult(); } throw ret; } finally { thread.lastSpecialBinding = lastSpecialBinding; } } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/sun/security/action/OpenFileInputStreamAction.java
1843
/* * Copyright 2002-2004 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package sun.security.action; import java.io.*; import java.security.PrivilegedExceptionAction; /** * A convenience class for opening a FileInputStream as a privileged action. * * @author Andreas Sterbenz */ public class OpenFileInputStreamAction implements PrivilegedExceptionAction<FileInputStream> { private final File file; public OpenFileInputStreamAction(File file) { this.file = file; } public OpenFileInputStreamAction(String filename) { this.file = new File(filename); } public FileInputStream run() throws Exception { return new FileInputStream(file); } }
gpl-2.0
Liciax/Projet-Salle
src/representation/GestionSalleImpl.java
10306
/** * */ package representation; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import BDD.BaseDeDonnee; /** * @author Lenny Lucas but: implemente la construction de tout les objets de la BDD ainsi que toutes * les fonctions. on suppose que l'interface a deja trouvé les id des elements. */ public class GestionSalleImpl implements GestionSalle { private BaseDeDonnee bdd; private FactorySalle factSalle; private List<String> listeDesClefs; public GestionSalleImpl() { this.bdd = new BaseDeDonnee(); this.factSalle = new FactorySalleImpl(); this.listeDesClefs = new ArrayList<String>(); } public Object get(String key) { return bdd.get(key); } public boolean clefExiste(String key) { return listeDesClefs.contains(key); } // --------------------------------------------------------------------// // pour les adresses // // --------------------------------------------------------------------// public boolean creationAdresse(int noRue, String rue, int codePostal, String ville, String complement) { Adresse a = factSalle.createAdresse(noRue, rue, codePostal, ville, complement); String key = bdd.put(a); return listeDesClefs.add(key); } public HashMap<String, Adresse> affichageAdresse() { HashMap<String, Adresse> liste = new HashMap<String, Adresse>(); for (String s : listeDesClefs) { if (s.charAt(0) == 'A') { liste.put(s, (Adresse) bdd.get(s)); } } return liste; } public boolean removeAdresse(String idAdr) { return (bdd.remove(idAdr) && listeDesClefs.remove(idAdr)); } // --------------------------------------------------------------------// // pour les Batiments // // --------------------------------------------------------------------// public boolean creationBatiment(String adresseBat) { Batiment a = factSalle.createBatiment(adresseBat); String key = bdd.put(a); return listeDesClefs.add(key); } public HashMap<String, Batiment> affichageBatiment() { HashMap<String, Batiment> liste = new HashMap<String, Batiment>(); for (String s : listeDesClefs) { if (s.charAt(0) == 'B') { liste.put(s, (Batiment) bdd.get(s)); } } return liste; } public boolean removeBatiment(String idBat) { BatimentImpl bat = (BatimentImpl) bdd.get(idBat); // on detruit toutes les salles du batiment for (String s : bat.getSalles()) { removeSalle(s); } return (bdd.remove(idBat) && listeDesClefs.remove(idBat)); } public boolean ajouterSalleABatiment(String idSalle, String idBat) { BatimentImpl bat = (BatimentImpl) bdd.get(idBat); SalleImpl salle = (SalleImpl) bdd.get(idSalle); salle.setIdBat(idBat); bat.addSalle(idSalle); return (bdd.update(idSalle, salle) && bdd.update(idBat, bat)); } public boolean retirerSalleABatiment(String idSalle, String idBat) { BatimentImpl bat = (BatimentImpl) bdd.get(idBat); SalleImpl salle = (SalleImpl) bdd.get(idSalle); salle.setIdBat(""); bat.removeSalle(idSalle); return (bdd.update(idSalle, salle) && bdd.update(idBat, bat)); } public HashMap<String, Salle> afficherSallesDeBatiment(String idbat) { BatimentImpl salle = (BatimentImpl) bdd.get(idbat); HashMap<String, Salle> map = new HashMap<String, Salle>(); for (String s : salle.getSalles()) { map.put(s, (Salle) bdd.get(s)); } return map; } // --------------------------------------------------------------------// // pour les Salles // // --------------------------------------------------------------------// public String creationSalle(int noEtage, int noSalle, int superficie, String typeSalle) { Salle s = factSalle.createSalle(noEtage, noSalle, "", superficie, typeSalle); String key = bdd.put(s); listeDesClefs.add(key); return key; } public HashMap<String, Salle> affichageSalle() { HashMap<String, Salle> liste = new HashMap<String, Salle>(); for (String s : listeDesClefs) { if (s.charAt(0) == 'S') { liste.put(s, (Salle) bdd.get(s)); } } return liste; } // public boolean ajouterMaterielASalle(String idMat, String idSalle) { // SalleImpl salle = (SalleImpl) bdd.get(idSalle); // MaterielImpl mat = (MaterielImpl) bdd.get(idMat); // salle.addMateriel(idMat); // mat.setIdSalle(idSalle); // return (bdd.update(idSalle, salle) && bdd.update(idMat, mat)); // } // // // public boolean retirerMaterielASalle(String idMat, String idSalle) { // SalleImpl salle = (SalleImpl) bdd.get(idSalle); // MaterielImpl mat = (MaterielImpl) bdd.get(idMat); // mat.setIdSalle(""); // mat.freeMateriel(new GregorianCalendar()); // salle.removeMateriel(idMat); // return (bdd.update(idSalle, salle) && bdd.update(idMat, mat)); // } public HashMap<String, Materiel> afficherMaterielDeSalle(String idSalle) { SalleImpl salle = (SalleImpl) bdd.get(idSalle); HashMap<String, Materiel> map = new HashMap<String, Materiel>(); for (String s : salle.getMateriauxFixes()) { map.put(s, (Materiel) bdd.get(s)); } return map; } public boolean removeSalle(String idSalle) { SalleImpl salle = (SalleImpl) bdd.get(idSalle); MaterielImpl mat; ReservationImpl res; for (String s : salle.getMateriauxFixes()) { mat = (MaterielImpl) bdd.get(s); mat.freeMateriel(new GregorianCalendar()); bdd.update(s, mat); } if (salle.getIdBat() != "") { retirerSalleABatiment(idSalle, salle.getIdBat()); } for (String s : listeDesClefs) { if (s.charAt(0) == 'R') { res = (ReservationImpl) bdd.get(s); if (res.getIdSalle().equals(idSalle)) { bdd.remove(s); listeDesClefs.remove(s); // for(String m:res.getMateriauxMobiles()) { // res.retirerMaterielMobile(m); // } } } } return (bdd.remove(idSalle) && listeDesClefs.remove(idSalle)); } // --------------------------------------------------------------------// // pour les Materiaux // // --------------------------------------------------------------------// public boolean creationMateriaux(String codeMateriel, String nomMateriel, String descrMateriel, double tarif) { Materiel s = factSalle.createMateriel(codeMateriel, nomMateriel, descrMateriel, tarif); String key = bdd.put(s); return listeDesClefs.add(key); } public HashMap<String, Materiel> affichageMateriaux(Calendar cd, Calendar cf) { HashMap<String, Materiel> liste = new HashMap<String, Materiel>(); MaterielImpl mat; for (String s : listeDesClefs) { if (s.charAt(0) == 'M') { mat = (MaterielImpl) bdd.get(s); if (mat.getType() == TypeMateriel.FIXE) {// indispo apres date if ((mat.getDateDeChangement().compareTo(cd) >= 0) && (mat.getDateDeChangement().compareTo(cf) >= 0)) { liste.put(s, mat); } } else if (mat.getType() == TypeMateriel.MOBILE) {// indispo jusqu'a date if ((mat.getDateDeChangement().compareTo(cd) <= 0) && (mat.getDateDeChangement().compareTo(cf) <= 0)) { liste.put(s, mat); } } } } return liste; } public void fixerMat(Calendar cd, String idSalle, String idMat) { MaterielImpl mat = (MaterielImpl) bdd.get(idMat); SalleImpl salle = (SalleImpl) bdd.get(idSalle); mat.fixMateriel(cd, idSalle); salle.addMateriel(idMat); ReservationImpl r; for (String s : listeDesClefs) { if (s.charAt(0) == 'R') { r = (ReservationImpl) bdd.get(s); if (r.getIdSalle().equals(idSalle)) { r.retirerMaterielMobile(idMat); } } } } public void libererMat(Calendar cd, String idSalle, String idMat) { MaterielImpl mat = (MaterielImpl) bdd.get(idMat); if (mat.getType() == TypeMateriel.FIXE) { SalleImpl salle = (SalleImpl) bdd.get(idSalle); mat.freeMateriel(cd); salle.removeMateriel(idMat); ReservationImpl r; for (String s : listeDesClefs) { if (s.charAt(0) == 'R') { r = (ReservationImpl) bdd.get(s); if (r.getIdSalle().equals(idSalle)) { r.ajoutDansListeMateriauxMobile(idMat); } } } } } public void removeMateriaux(String idMat) { MaterielImpl mat = (MaterielImpl) bdd.get(idMat); if (mat.getType() == TypeMateriel.FIXE) { libererMat(new GregorianCalendar(), mat.getIdSalle(), idMat); } else { mat.materielARetirer(); } // return (bdd.remove(idSalle) || listeDesClefs.remove(idSalle)); } // --------------------------------------------------------------------// // pour les Reservations // // --------------------------------------------------------------------// public String creationReservation(String salleReservee, Calendar dateDebutReserve, Calendar dateFinReserve, String idClient) { Reservation r = factSalle.createReservation(salleReservee, dateDebutReserve, dateFinReserve, idClient); String key = bdd.put(r); if (!key.equals("err")) { listeDesClefs.add(key); } return key; } public HashMap<String, Reservation> affichageReservation() { HashMap<String, Reservation> liste = new HashMap<String, Reservation>(); for (String s : listeDesClefs) { if (s.charAt(0) == 'R') { liste.put(s, (Reservation) bdd.get(s)); } } return liste; } public boolean removeReservation(String idReservation, String idDemandeur) { if(((ReservationImpl)bdd.get(idReservation)).getIdClient().equals(idDemandeur)) { return (bdd.remove(idReservation) && listeDesClefs.remove(idReservation)); } else { return false; } } public BaseDeDonnee getBdd() { return bdd; } }
gpl-2.0
donatellosantoro/freESBee
moduloInteroperabilita/src/it/unibas/icar/freesbee/ws/registroservizi/client/stub/GetServizioSPCoopCorrelatoResponse.java
1740
package it.unibas.icar.freesbee.ws.registroservizi.client.stub; import it.unibas.icar.freesbee.ws.registroservizi.ServizioRSRisposta; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getServizioSPCoopCorrelatoResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getServizioSPCoopCorrelatoResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://icar.unibas.it/freesbee/}servizioRSRisposta" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getServizioSPCoopCorrelatoResponse", propOrder = { "_return" }) public class GetServizioSPCoopCorrelatoResponse { @XmlElement(name = "return") protected ServizioRSRisposta _return; /** * Gets the value of the return property. * * @return * possible object is * {@link ServizioRSRisposta } * */ public ServizioRSRisposta getReturn() { return _return; } /** * Sets the value of the return property. * * @param value * allowed object is * {@link ServizioRSRisposta } * */ public void setReturn(ServizioRSRisposta value) { this._return = value; } }
gpl-2.0
rpereira-dev/VoxelEngine
VoxelEngine/src/com/grillecube/common/world/block/BlockCubeOpaque.java
905
/** ** This file is part of the project https://github.com/toss-dev/VoxelEngine ** ** License is available here: https://raw.githubusercontent.com/toss-dev/VoxelEngine/master/LICENSE.md ** ** PEREIRA Romain ** 4-----7 ** /| /| ** 0-----3 | ** | 5___|_6 ** |/ | / ** 1-----2 */ package com.grillecube.common.world.block; public abstract class BlockCubeOpaque extends BlockCube { public BlockCubeOpaque(int blockID) { super(blockID); } @Override public boolean isVisible() { return (true); } @Override public boolean isOpaque() { return (true); } @Override public boolean hasTransparency() { return (false); } }
gpl-2.0
arodchen/MaxSim
maxine/com.oracle.max.asmdis/src/com/sun/max/asm/dis/amd64/package-info.java
1126
/* * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * An AMD64 disassembler. */ package com.sun.max.asm.dis.amd64;
gpl-2.0
mur47x111/GraalVM
graal/com.oracle.graal.nodes.test/src/com/oracle/graal/nodes/test/ObjectStampMeetTest.java
4715
/* * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes.test; import jdk.internal.jvmci.meta.*; import org.junit.*; import com.oracle.graal.compiler.common.type.*; public class ObjectStampMeetTest extends AbstractObjectStampTest { // class A // class B extends A // class C extends B implements I // class D extends A // abstract class E extends A // interface I @Test public void testMeet0() { Stamp a = StampFactory.declared(getType(A.class)); Stamp b = StampFactory.declared(getType(B.class)); Assert.assertEquals(a, meet(a, b)); } @Test public void testMeet1() { Stamp a = StampFactory.declared(getType(A.class)); Stamp aNonNull = StampFactory.declaredNonNull(getType(A.class)); Stamp b = StampFactory.declared(getType(B.class)); Stamp bNonNull = StampFactory.declaredNonNull(getType(B.class)); Assert.assertEquals(a, meet(aNonNull, b)); Assert.assertEquals(aNonNull, meet(aNonNull, bNonNull)); } @Test public void testMeet2() { Stamp a = StampFactory.declared(getType(A.class)); Stamp aExact = StampFactory.exactNonNull(getType(A.class)); Stamp b = StampFactory.declared(getType(B.class)); Assert.assertEquals(a, meet(aExact, b)); } @Test public void testMeet3() { Stamp a = StampFactory.declared(getType(A.class)); Stamp d = StampFactory.declared(getType(D.class)); Stamp c = StampFactory.declared(getType(C.class)); Assert.assertEquals(a, meet(c, d)); } @Test public void testMeet4() { Stamp dExactNonNull = StampFactory.exactNonNull(getType(D.class)); Stamp cExactNonNull = StampFactory.exactNonNull(getType(C.class)); Stamp aNonNull = StampFactory.declaredNonNull(getType(A.class)); Assert.assertEquals(aNonNull, meet(cExactNonNull, dExactNonNull)); } @Test public void testMeet() { Stamp dExact = StampFactory.exact(getType(D.class)); Stamp c = StampFactory.declared(getType(C.class)); Stamp a = StampFactory.declared(getType(A.class)); Assert.assertEquals(a, meet(dExact, c)); } @Test public void testMeet6() { Stamp dExactNonNull = StampFactory.exactNonNull(getType(D.class)); Stamp alwaysNull = StampFactory.alwaysNull(); Stamp dExact = StampFactory.exact(getType(D.class)); Assert.assertEquals(dExact, meet(dExactNonNull, alwaysNull)); } @Test public void testMeet7() { Stamp aExact = StampFactory.exact(getType(A.class)); Stamp e = StampFactory.declared(getType(E.class)); Stamp a = StampFactory.declared(getType(A.class)); Assert.assertEquals(a, meet(aExact, e)); } @Test public void testMeetInterface0() { Stamp a = StampFactory.declared(getType(A.class)); Stamp i = StampFactory.declaredTrusted(getType(I.class)); Assert.assertEquals(StampFactory.declared(getType(Object.class)), meet(a, i)); } @Test public void testMeetIllegal1() { for (Class<?> clazz : new Class<?>[]{A.class, B.class, C.class, D.class, E.class, I.class, Object.class}) { ResolvedJavaType type = getType(clazz); for (Stamp test : new Stamp[]{StampFactory.declared(type), StampFactory.declaredNonNull(type), StampFactory.exact(type), StampFactory.exactNonNull(type)}) { if (type.isConcrete() || !((ObjectStamp) test).isExactType()) { Assert.assertEquals("meeting empty and " + test, test, meet(StampFactory.empty(Kind.Object), test)); } } } } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest04677.java
2502
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest04677") public class BenchmarkTest04677 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> names = request.getParameterNames(); if (names.hasMoreElements()) { param = names.nextElement(); // just grab first element } String bar; String guess = "ABC"; char switchTarget = guess.charAt(2); // Simple case statement that assigns param to bar on conditions 'A' or 'C' switch (switchTarget) { case 'A': bar = param; break; case 'B': bar = "bobs_your_uncle"; break; case 'C': case 'D': bar = param; break; default: bar = "bobs_your_uncle"; break; } String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'"; try { java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement(); statement.addBatch( sql ); int[] counts = statement.executeBatch(); } catch (java.sql.SQLException e) { throw new ServletException(e); } } }
gpl-2.0
gsssrao/AndroidOpenCVDemo
AndroidOpenCVDemo/generated/jderobot/SubscriptionPushFailedException.java
1546
// ********************************************************************** // // Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.5.1 // // <auto-generated> // // Generated from file `exceptions.ice' // // Warning: do not edit this file. // // </auto-generated> // package jderobot; public class SubscriptionPushFailedException extends JderobotException { public SubscriptionPushFailedException() { super(); } public SubscriptionPushFailedException(Throwable __cause) { super(__cause); } public SubscriptionPushFailedException(String what) { super(what); } public SubscriptionPushFailedException(String what, Throwable __cause) { super(what, __cause); } public String ice_name() { return "jderobot::SubscriptionPushFailedException"; } protected void __writeImpl(IceInternal.BasicStream __os) { __os.startWriteSlice("::jderobot::SubscriptionPushFailedException", -1, false); __os.endWriteSlice(); super.__writeImpl(__os); } protected void __readImpl(IceInternal.BasicStream __is) { __is.startReadSlice(); __is.endReadSlice(); super.__readImpl(__is); } public static final long serialVersionUID = 5405112280036873889L; }
gpl-2.0
Neraud/PADListener
SandroProxyLib/src/main/java/org/sandrop/webscarab/plugin/proxy/RevealHidden.java
6065
/*********************************************************************** * * This file is part of SandroProxy, * For details, please see http://code.google.com/p/sandrop/ * * Copyright (c) 2012 supp.sandrob@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Getting Source * ============== * * Source for this application is maintained at * http://code.google.com/p/sandrop/ * * Software is build from sources of WebScarab project * For details, please see http://www.sourceforge.net/projects/owasp * */ package org.sandrop.webscarab.plugin.proxy; // import org.owasp.util.StringUtil; import org.sandrop.webscarab.httpclient.HTTPClient; import org.sandrop.webscarab.model.Preferences; import org.sandrop.webscarab.model.Request; import org.sandrop.webscarab.model.Response; import org.sandrop.webscarab.plugin.proxy.ProxyPlugin; import java.io.IOException; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * * @author rdawes */ public class RevealHidden extends ProxyPlugin { private boolean _enabled = false; /** Creates a new instance of RevealHidden */ public RevealHidden() { parseProperties(); } public void parseProperties() { String prop = "RevealHidden.enabled"; _enabled = Preferences.getPreferenceBoolean(prop, false); } public String getPluginName() { return new String("Reveal Hidden"); } /* public void setEnabled(boolean bool) { _enabled = bool; String prop = "RevealHidden.enabled"; Preferences.setPreferenceB(prop,Boolean.toString(bool)); } */ public boolean getEnabled() { return _enabled; } public HTTPClient getProxyPlugin(HTTPClient in) { return new Plugin(in); } private class Plugin implements HTTPClient { private HTTPClient _in; public Plugin(HTTPClient in) { _in = in; } public Response fetchResponse(Request request) throws IOException { Response response = _in.fetchResponse(request); if (_enabled) { String ct = response.getHeader("Content-Type"); if (ct != null && ct.matches("text/.*") && !ct.matches("text/javascript")) { byte[] content = response.getContent(); if (content != null) { response.setContent(revealHidden(content)); response.addHeader("X-RevealHidden", "possibly modified"); } } } return response; } private byte[] revealHidden(byte[] content) { /* We split this pattern into two parts, one before "hidden" and one after * Then it is simple to concatenate part 1 + "text" + part 2 to get an * "unhidden" input tag */ Pattern inputPattern = Pattern.compile("(<input.+?type\\s*=\\s*[\"']{0,1})hidden([\"']{0,1}.+?>)", Pattern.CASE_INSENSITIVE); Matcher inputMatcher = inputPattern.matcher(new String(content)); StringBuffer outbuf = new StringBuffer(); /* matched hidden input parameter */ while(inputMatcher.find()) { String input = inputMatcher.group(); String name = "noname"; // extract hidden field name Pattern namePattern = Pattern.compile("name=[\"']{0,1}(\\w+)[\"']{0,1}", Pattern.CASE_INSENSITIVE); Matcher nameMatcher = namePattern.matcher(input); if (nameMatcher.find() && nameMatcher.groupCount() == 1){ name = nameMatcher.group(1); } // make hidden field a text field - there MUST be 2 groups // Note: this way we don't have to care about which quotes are being used input = inputMatcher.group(1) + "text" + inputMatcher.group(2); /* insert [hidden] <fieldname> before the field itself */ // inputMatcher.appendReplacement(outbuf, "<STRONG style=\"background-color: white;\"> [hidden field name =\"" + name + "\"]:</STRONG> "+ input + "<BR/>"); inputMatcher.appendReplacement(outbuf, constructReplacement(name, input)); } inputMatcher.appendTail(outbuf); return outbuf.toString().getBytes(); } private String constructReplacement(final String name, final String input) { final StringBuffer result = new StringBuffer(); result.append("<div style=\"background: pink; border: red 1px solid; padding: 2px; margin:4px; text-align: left;\">"); result.append("<p style=\"color: red; text-align: left; margin-top: 0px; font-size: xx-small;\">Hidden Input Field</p>"); result.append("<p style=\"text-align: center; color: black; margin: 0px; font-size: normal;\">"); result.append("[").append(name).append("]").append("&nbsp;").append(input); result.append("</p>"); result.append("<p style=\"color: red; text-align: right; margin-bottom: 0px; font-size: xx-small;\">Revealed by SandroProxy</p>"); result.append("</div>"); return result.toString(); } } }
gpl-2.0
bogeymanEST/CmdHelper
src/main/java/me/bogeymanEST/cmdhelper/tagdef/NoteBlockDef.java
1074
/* * CmdHelper * Copyright (C) 2013 bogeymanEST * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package me.bogeymanEST.cmdhelper.tagdef; /** * User: Bogeyman * Date: 14.09.13 * Time: 10:57 */ public class NoteBlockDef extends TileEntityDef { @Info("The pitch (number of right-clicks)") public Byte note; @Override public String getName() { return "NoteBlock"; } }
gpl-2.0
OSUCartography/FlexProjector
src/ika/geo/grid/GridMask.java
215
/* * * */ package ika.geo.grid; /** * * @author Bernhard Jenny, Institute of Cartography, ETH Zurich. */ public interface GridMask { public float getWeight(int col, int row, int pyramidLevel); }
gpl-2.0
boomboompower/XPCraftHub
src/main/java/org/originmc/hub/commands/CmdHelp.java
1307
package org.originmc.hub.commands; import com.google.common.collect.ImmutableSet; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.originmc.hub.Hub; import org.originmc.hub.Perm; import static org.bukkit.ChatColor.*; public final class CmdHelp implements CommandExecutor { private static final ImmutableSet<String> HELP_MESSAGE = ImmutableSet.of( GOLD + "_____________.[" + DARK_GREEN + " Help for \"Hub Plugin\" " + GOLD + "]._____________", AQUA + "/eject " + YELLOW + " Ejects the player riding you", AQUA + "/links " + YELLOW + " View all server links", AQUA + "/msg " + DARK_AQUA + "<player> <message>" + YELLOW + " Message a player", AQUA + "/reply " + DARK_AQUA + "<message>" + YELLOW + " Reply to message partner" ); public CmdHelp(Hub plugin) { plugin.getCommand("help").setExecutor(this); } @Override public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) { // Do nothing if sender does not have permission. if (!Perm.HELP.has(sender)) return true; // Send all help messages. HELP_MESSAGE.forEach(sender::sendMessage); return true; } }
gpl-2.0
sigeu-deseg/sigeu-deseg
sigeu/src/br/edu/utfpr/dv/sigeu/jsfbeans/PesquisaProfessorBean.java
1449
package br.edu.utfpr.dv.sigeu.jsfbeans; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import org.omnifaces.cdi.ViewScoped; import br.edu.utfpr.dv.sigeu.entities.Professor; import br.edu.utfpr.dv.sigeu.service.ProfessorService; @Named @ViewScoped public class PesquisaProfessorBean extends JavaBean { @Inject private LoginBean loginBean; private static final long serialVersionUID = -7335395433L; // private String textoPesquisa; private List<Professor> lista; // @PostConstruct public void init() { try { lista = ProfessorService.pesquisar(loginBean.getCampus(), null); //this.addInfoMessage("Pesquisar", "Exibindo " + HibernateDAO.PESQUISA_LIMITE + " itens. Pesquise utilizando parâmetros para obter mais registros."); } catch (Exception e) { //this.addErrorMessage("Pesquisar", "Erro ao realizar pesquisa inicial. Entre em contato com o Admin."); } } /** * Realiza a pesquisa de itens */ public void pesquisa() { try { this.lista = ProfessorService.pesquisar(loginBean.getCampus(), textoPesquisa); } catch (Exception e) { e.printStackTrace(); addErrorMessage("Pesquisar", "Erro na pesquisa"); } } public List<Professor> getLista() { return lista; } public String getTextoPesquisa() { return textoPesquisa; } public void setTextoPesquisa(String textoPesquisa) { this.textoPesquisa = textoPesquisa; } }
gpl-2.0
jkinder/jakstab
src/org/jakstab/analysis/explicit/BasedConstantPropagation.java
2747
/* * BasedConstantPropagation.java - This file is part of the Jakstab project. * Copyright 2007-2015 Johannes Kinder <jk@jakstab.org> * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, see <http://www.gnu.org/licenses/>. */ package org.jakstab.analysis.explicit; import java.util.Set; import org.jakstab.AnalysisProperties; import org.jakstab.analysis.*; import org.jakstab.cfa.CFAEdge; import org.jakstab.cfa.Location; import org.jakstab.cfa.StateTransformer; import org.jakstab.rtl.statements.RTLStatement; import org.jakstab.util.Logger; import org.jakstab.util.Pair; /** * @author Johannes Kinder */ public class BasedConstantPropagation implements ConfigurableProgramAnalysis { public static void register(AnalysisProperties p) { p.setShortHand('b'); p.setName("Based Constant Propagation"); p.setDescription("Constant propagation with region-offset values."); p.setExplicit(true); } @SuppressWarnings("unused") private final static Logger logger = Logger.getLogger(BasedConstantPropagation.class); public BasedConstantPropagation() { } @Override public AbstractState merge(AbstractState s1, AbstractState s2, Precision precision) { return CPAOperators.mergeJoin(s1, s2, precision); } @Override public boolean stop(AbstractState s, ReachedSet reached, Precision precision) { return CPAOperators.stopSep(s, reached, precision); } @Override public Set<AbstractState> post(AbstractState state, CFAEdge cfaEdge, Precision precision) { return ((BasedNumberValuation)state).abstractPost((RTLStatement)cfaEdge.getTransformer(), precision); } @Override public AbstractState strengthen(AbstractState s, Iterable<AbstractState> otherStates, CFAEdge cfaEdge, Precision precision) { return s; } @Override public Pair<AbstractState, Precision> prec(AbstractState s, Precision precision, ReachedSet reached) { return Pair.create(s, precision); } @Override public AbstractState initStartState(Location location) { return BasedNumberValuation.createInitialState(); } @Override public Precision initPrecision(Location location, StateTransformer transformer) { return new ExplicitPrecision(1); } }
gpl-2.0
tharindum/opennms_dashboard
opennms-services/src/main/java/org/opennms/netmgt/statsd/ReportDefinitionBuilder.java
5933
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.statsd; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.dao.StatisticsDaemonConfigDao; import org.opennms.netmgt.dao.castor.statsd.PackageReport; import org.opennms.netmgt.dao.castor.statsd.Report; import org.opennms.netmgt.dao.castor.statsd.StatsdPackage; import org.opennms.netmgt.model.AttributeStatisticVisitorWithResults; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.util.Assert; /** * <p>ReportDefinitionBuilder class.</p> * * @author ranger * @version $Id: $ */ public class ReportDefinitionBuilder implements InitializingBean { private StatisticsDaemonConfigDao m_statsdConfigDao; /** * <p>reload</p> * * @throws org.springframework.dao.DataAccessResourceFailureException if any. */ public void reload() throws DataAccessResourceFailureException { m_statsdConfigDao.reloadConfiguration(); } /** * Builds and schedules all reports enabled in the statsd-configuration. * This method has the capability to throw a ton of exceptions, just generically throwing <code>Exception</code> * * @return a <code>Collection</code> of enabled reports from the statsd-configuration. * @throws java.lang.Exception if any. */ public Collection<ReportDefinition> buildReportDefinitions() throws Exception { Set<ReportDefinition> reportDefinitions = new HashSet<ReportDefinition>(); for (StatsdPackage pkg : m_statsdConfigDao.getPackages()) { for (PackageReport packageReport : pkg.getReports()) { Report report = packageReport.getReport(); if (!packageReport.isEnabled()) { log().debug("skipping report '" + report.getName() + "' in package '" + pkg.getName() + "' because the report is not enabled"); } Class<? extends AttributeStatisticVisitorWithResults> clazz; try { clazz = createClassForReport(report); } catch (ClassNotFoundException e) { throw new DataAccessResourceFailureException("Could not find class '" + report.getClassName() + "'; nested exception: " + e, e); } Assert.isAssignable(AttributeStatisticVisitorWithResults.class, clazz, "the class specified by class-name in the '" + report.getName() + "' report does not implement the interface " + AttributeStatisticVisitorWithResults.class.getName() + "; "); ReportDefinition reportDef = new ReportDefinition(); reportDef.setReport(packageReport); reportDef.setReportClass(clazz); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(reportDef); try { bw.setPropertyValues(packageReport.getAggregateParameters()); } catch (BeansException e) { log().error("Could not set properties on report definition: " + e.getMessage(), e); } reportDef.afterPropertiesSet(); reportDefinitions.add(reportDef); } } return reportDefinitions; } @SuppressWarnings("unchecked") private Class<? extends AttributeStatisticVisitorWithResults> createClassForReport(Report report) throws ClassNotFoundException { return (Class<? extends AttributeStatisticVisitorWithResults>) Class.forName(report.getClassName()); } private ThreadCategory log() { return ThreadCategory.getInstance(getClass()); } /** * <p>afterPropertiesSet</p> */ @Override public void afterPropertiesSet() { Assert.state(m_statsdConfigDao != null, "property statsdConfigDao must be set to a non-null value"); } /** * <p>getStatsdConfigDao</p> * * @return a {@link org.opennms.netmgt.dao.StatisticsDaemonConfigDao} object. */ public StatisticsDaemonConfigDao getStatsdConfigDao() { return m_statsdConfigDao; } /** * <p>setStatsdConfigDao</p> * * @param statsdConfigDao a {@link org.opennms.netmgt.dao.StatisticsDaemonConfigDao} object. */ public void setStatsdConfigDao(StatisticsDaemonConfigDao statsdConfigDao) { m_statsdConfigDao = statsdConfigDao; } }
gpl-2.0
ntj/ComplexRapidMiner
src/com/rapidminer/operator/preprocessing/filter/TFIDFFilter.java
5141
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.preprocessing.filter; import java.util.Iterator; import java.util.List; import com.rapidminer.example.Attribute; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.operator.IOObject; import com.rapidminer.operator.Operator; import com.rapidminer.operator.OperatorDescription; import com.rapidminer.operator.OperatorException; import com.rapidminer.operator.UserError; import com.rapidminer.parameter.ParameterType; import com.rapidminer.parameter.ParameterTypeBoolean; /** * This operator generates TF-IDF values from the input data. The input example * set must contain either simple counts, which will be normalized during * calculation of the term frequency TF, or it already contains the calculated * term frequency values (in this case no normalization will be done). * * @author Ingo Mierswa * @version $Id: TFIDFFilter.java,v 1.7 2008/07/07 07:06:40 ingomierswa Exp $ */ public class TFIDFFilter extends Operator { /** The parameter name for &quot;Indicates if term frequency values should be generated (must be done if input data is given as simple occurence counts).&quot; */ public static final String PARAMETER_CALCULATE_TERM_FREQUENCIES = "calculate_term_frequencies"; private static final Class[] INPUT_CLASSES = { ExampleSet.class }; private static final Class[] OUTPUT_CLASSES = { ExampleSet.class }; public Class<?>[] getInputClasses() { return INPUT_CLASSES; } public Class<?>[] getOutputClasses() { return OUTPUT_CLASSES; } public TFIDFFilter(OperatorDescription description) { super(description); } public IOObject[] apply() throws OperatorException { ExampleSet exampleSet = getInput(ExampleSet.class); if (exampleSet.size() < 1) throw new UserError(this, 110, new Object[] { "1" }); if (exampleSet.getAttributes().size() == 0) throw new UserError(this, 106, new Object[0]); for (Attribute attribute : exampleSet.getAttributes()) { if (!attribute.isNumerical()) throw new UserError(this, 104, new Object[] { getName(), attribute.getName() }); } // init double[] termFrequencySum = new double[exampleSet.size()]; int[] documentFrequencies = new int[exampleSet.getAttributes().size()]; // calculate frequencies int exampleCounter = 0; Iterator<Example> reader = exampleSet.iterator(); while (reader.hasNext()) { Example example = reader.next(); int i = 0; for (Attribute attribute : exampleSet.getAttributes()) { double value = example.getValue(attribute); termFrequencySum[exampleCounter] += value; if (value > 0) documentFrequencies[i]++; i++; } exampleCounter++; checkForStop(); } // calculate IDF values double[] inverseDocumentFrequencies = new double[documentFrequencies.length]; for (int i = 0; i < exampleSet.getAttributes().size(); i++) inverseDocumentFrequencies[i] = Math.log((double) exampleSet.size() / (double) documentFrequencies[i]); // set values boolean calculateTermFrequencies = getParameterAsBoolean(PARAMETER_CALCULATE_TERM_FREQUENCIES); exampleCounter = 0; reader = exampleSet.iterator(); while (reader.hasNext()) { Example example = reader.next(); int i = 0; for (Attribute attribute : exampleSet.getAttributes()) { double value = example.getValue(attribute); if (termFrequencySum[exampleCounter] == 0.0d) { example.setValue(attribute, 0.0d); } else { double tf = value; if (calculateTermFrequencies) tf /= termFrequencySum[exampleCounter]; double idf = inverseDocumentFrequencies[i]; example.setValue(attribute, (tf * idf)); } i++; } exampleCounter++; checkForStop(); } return new IOObject[] { exampleSet }; } public List<ParameterType> getParameterTypes() { List<ParameterType> types = super.getParameterTypes(); ParameterType type = new ParameterTypeBoolean(PARAMETER_CALCULATE_TERM_FREQUENCIES, "Indicates if term frequency values should be generated (must be done if input data is given as simple occurence counts).", true); type.setExpert(false); types.add(type); return types; } }
gpl-2.0
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/element/db/DbKeysElement.java
2824
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.db; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; /** * DOM implementation of OpenDocument element {@odf.element db:keys}. * */ public class DbKeysElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.DB, "keys"); /** * Create the instance of <code>DbKeysElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public DbKeysElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element db:keys}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Create child element {@odf.element db:key}. * * @param dbTypeValue the <code>String</code> value of <code>DbTypeAttribute</code>, see {@odf.attribute db:type} at specification * Child element is new in Odf 1.2 * * Child element is mandatory. * * @return the element {@odf.element db:key} */ public DbKeyElement newDbKeyElement(String dbTypeValue) { DbKeyElement dbKey = ((OdfFileDom) this.ownerDocument).newOdfElement(DbKeyElement.class); dbKey.setDbTypeAttribute(dbTypeValue); this.appendChild(dbKey); return dbKey; } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
gpl-2.0
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/element/number/NumberTimeStyleElement.java
21643
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.number; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; import org.odftoolkit.odfdom.dom.element.style.StyleMapElement; import org.odftoolkit.odfdom.dom.element.style.StyleTextPropertiesElement; import org.odftoolkit.odfdom.dom.attribute.number.NumberCountryAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberFormatSourceAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberLanguageAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberRfcLanguageTagAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberScriptAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberTitleAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberTransliterationCountryAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberTransliterationFormatAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberTransliterationLanguageAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberTransliterationStyleAttribute; import org.odftoolkit.odfdom.dom.attribute.number.NumberTruncateOnOverflowAttribute; import org.odftoolkit.odfdom.dom.attribute.style.StyleDisplayNameAttribute; import org.odftoolkit.odfdom.dom.attribute.style.StyleNameAttribute; import org.odftoolkit.odfdom.dom.attribute.style.StyleVolatileAttribute; /** * DOM implementation of OpenDocument element {@odf.element number:time-style}. * */ public class NumberTimeStyleElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.NUMBER, "time-style"); /** * Create the instance of <code>NumberTimeStyleElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public NumberTimeStyleElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element number:time-style}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Receives the value of the ODFDOM attribute representation <code>NumberCountryAttribute</code> , See {@odf.attribute number:country} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberCountryAttribute() { NumberCountryAttribute attr = (NumberCountryAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "country"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberCountryAttribute</code> , See {@odf.attribute number:country} * * @param numberCountryValue The type is <code>String</code> */ public void setNumberCountryAttribute(String numberCountryValue) { NumberCountryAttribute attr = new NumberCountryAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberCountryValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberFormatSourceAttribute</code> , See {@odf.attribute number:format-source} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberFormatSourceAttribute() { NumberFormatSourceAttribute attr = (NumberFormatSourceAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "format-source"); if (attr != null) { return String.valueOf(attr.getValue()); } return NumberFormatSourceAttribute.DEFAULT_VALUE; } /** * Sets the value of ODFDOM attribute representation <code>NumberFormatSourceAttribute</code> , See {@odf.attribute number:format-source} * * @param numberFormatSourceValue The type is <code>String</code> */ public void setNumberFormatSourceAttribute(String numberFormatSourceValue) { NumberFormatSourceAttribute attr = new NumberFormatSourceAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberFormatSourceValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberLanguageAttribute</code> , See {@odf.attribute number:language} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberLanguageAttribute() { NumberLanguageAttribute attr = (NumberLanguageAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "language"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberLanguageAttribute</code> , See {@odf.attribute number:language} * * @param numberLanguageValue The type is <code>String</code> */ public void setNumberLanguageAttribute(String numberLanguageValue) { NumberLanguageAttribute attr = new NumberLanguageAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberLanguageValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberRfcLanguageTagAttribute</code> , See {@odf.attribute number:rfc-language-tag} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberRfcLanguageTagAttribute() { NumberRfcLanguageTagAttribute attr = (NumberRfcLanguageTagAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "rfc-language-tag"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberRfcLanguageTagAttribute</code> , See {@odf.attribute number:rfc-language-tag} * * @param numberRfcLanguageTagValue The type is <code>String</code> */ public void setNumberRfcLanguageTagAttribute(String numberRfcLanguageTagValue) { NumberRfcLanguageTagAttribute attr = new NumberRfcLanguageTagAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberRfcLanguageTagValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberScriptAttribute</code> , See {@odf.attribute number:script} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberScriptAttribute() { NumberScriptAttribute attr = (NumberScriptAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "script"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberScriptAttribute</code> , See {@odf.attribute number:script} * * @param numberScriptValue The type is <code>String</code> */ public void setNumberScriptAttribute(String numberScriptValue) { NumberScriptAttribute attr = new NumberScriptAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberScriptValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberTitleAttribute</code> , See {@odf.attribute number:title} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberTitleAttribute() { NumberTitleAttribute attr = (NumberTitleAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "title"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberTitleAttribute</code> , See {@odf.attribute number:title} * * @param numberTitleValue The type is <code>String</code> */ public void setNumberTitleAttribute(String numberTitleValue) { NumberTitleAttribute attr = new NumberTitleAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberTitleValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberTransliterationCountryAttribute</code> , See {@odf.attribute number:transliteration-country} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberTransliterationCountryAttribute() { NumberTransliterationCountryAttribute attr = (NumberTransliterationCountryAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "transliteration-country"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberTransliterationCountryAttribute</code> , See {@odf.attribute number:transliteration-country} * * @param numberTransliterationCountryValue The type is <code>String</code> */ public void setNumberTransliterationCountryAttribute(String numberTransliterationCountryValue) { NumberTransliterationCountryAttribute attr = new NumberTransliterationCountryAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberTransliterationCountryValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberTransliterationFormatAttribute</code> , See {@odf.attribute number:transliteration-format} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberTransliterationFormatAttribute() { NumberTransliterationFormatAttribute attr = (NumberTransliterationFormatAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "transliteration-format"); if (attr != null) { return String.valueOf(attr.getValue()); } return NumberTransliterationFormatAttribute.DEFAULT_VALUE; } /** * Sets the value of ODFDOM attribute representation <code>NumberTransliterationFormatAttribute</code> , See {@odf.attribute number:transliteration-format} * * @param numberTransliterationFormatValue The type is <code>String</code> */ public void setNumberTransliterationFormatAttribute(String numberTransliterationFormatValue) { NumberTransliterationFormatAttribute attr = new NumberTransliterationFormatAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberTransliterationFormatValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberTransliterationLanguageAttribute</code> , See {@odf.attribute number:transliteration-language} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberTransliterationLanguageAttribute() { NumberTransliterationLanguageAttribute attr = (NumberTransliterationLanguageAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "transliteration-language"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>NumberTransliterationLanguageAttribute</code> , See {@odf.attribute number:transliteration-language} * * @param numberTransliterationLanguageValue The type is <code>String</code> */ public void setNumberTransliterationLanguageAttribute(String numberTransliterationLanguageValue) { NumberTransliterationLanguageAttribute attr = new NumberTransliterationLanguageAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberTransliterationLanguageValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberTransliterationStyleAttribute</code> , See {@odf.attribute number:transliteration-style} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getNumberTransliterationStyleAttribute() { NumberTransliterationStyleAttribute attr = (NumberTransliterationStyleAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "transliteration-style"); if (attr != null) { return String.valueOf(attr.getValue()); } return NumberTransliterationStyleAttribute.DEFAULT_VALUE; } /** * Sets the value of ODFDOM attribute representation <code>NumberTransliterationStyleAttribute</code> , See {@odf.attribute number:transliteration-style} * * @param numberTransliterationStyleValue The type is <code>String</code> */ public void setNumberTransliterationStyleAttribute(String numberTransliterationStyleValue) { NumberTransliterationStyleAttribute attr = new NumberTransliterationStyleAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(numberTransliterationStyleValue); } /** * Receives the value of the ODFDOM attribute representation <code>NumberTruncateOnOverflowAttribute</code> , See {@odf.attribute number:truncate-on-overflow} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getNumberTruncateOnOverflowAttribute() { NumberTruncateOnOverflowAttribute attr = (NumberTruncateOnOverflowAttribute) getOdfAttribute(OdfDocumentNamespace.NUMBER, "truncate-on-overflow"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(NumberTruncateOnOverflowAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>NumberTruncateOnOverflowAttribute</code> , See {@odf.attribute number:truncate-on-overflow} * * @param numberTruncateOnOverflowValue The type is <code>Boolean</code> */ public void setNumberTruncateOnOverflowAttribute(Boolean numberTruncateOnOverflowValue) { NumberTruncateOnOverflowAttribute attr = new NumberTruncateOnOverflowAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(numberTruncateOnOverflowValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>StyleDisplayNameAttribute</code> , See {@odf.attribute style:display-name} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getStyleDisplayNameAttribute() { StyleDisplayNameAttribute attr = (StyleDisplayNameAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "display-name"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>StyleDisplayNameAttribute</code> , See {@odf.attribute style:display-name} * * @param styleDisplayNameValue The type is <code>String</code> */ public void setStyleDisplayNameAttribute(String styleDisplayNameValue) { StyleDisplayNameAttribute attr = new StyleDisplayNameAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(styleDisplayNameValue); } /** * Receives the value of the ODFDOM attribute representation <code>StyleNameAttribute</code> , See {@odf.attribute style:name} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getStyleNameAttribute() { StyleNameAttribute attr = (StyleNameAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "name"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>StyleNameAttribute</code> , See {@odf.attribute style:name} * * @param styleNameValue The type is <code>String</code> */ public void setStyleNameAttribute(String styleNameValue) { StyleNameAttribute attr = new StyleNameAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(styleNameValue); } /** * Receives the value of the ODFDOM attribute representation <code>StyleVolatileAttribute</code> , See {@odf.attribute style:volatile} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getStyleVolatileAttribute() { StyleVolatileAttribute attr = (StyleVolatileAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "volatile"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>StyleVolatileAttribute</code> , See {@odf.attribute style:volatile} * * @param styleVolatileValue The type is <code>Boolean</code> */ public void setStyleVolatileAttribute(Boolean styleVolatileValue) { StyleVolatileAttribute attr = new StyleVolatileAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(styleVolatileValue.booleanValue()); } /** * Create child element {@odf.element number:am-pm}. * * @return the element {@odf.element number:am-pm} */ public NumberAmPmElement newNumberAmPmElement() { NumberAmPmElement numberAmPm = ((OdfFileDom) this.ownerDocument).newOdfElement(NumberAmPmElement.class); this.appendChild(numberAmPm); return numberAmPm; } /** * Create child element {@odf.element number:hours}. * * @return the element {@odf.element number:hours} */ public NumberHoursElement newNumberHoursElement() { NumberHoursElement numberHours = ((OdfFileDom) this.ownerDocument).newOdfElement(NumberHoursElement.class); this.appendChild(numberHours); return numberHours; } /** * Create child element {@odf.element number:minutes}. * * @return the element {@odf.element number:minutes} */ public NumberMinutesElement newNumberMinutesElement() { NumberMinutesElement numberMinutes = ((OdfFileDom) this.ownerDocument).newOdfElement(NumberMinutesElement.class); this.appendChild(numberMinutes); return numberMinutes; } /** * Create child element {@odf.element number:seconds}. * * @return the element {@odf.element number:seconds} */ public NumberSecondsElement newNumberSecondsElement() { NumberSecondsElement numberSeconds = ((OdfFileDom) this.ownerDocument).newOdfElement(NumberSecondsElement.class); this.appendChild(numberSeconds); return numberSeconds; } /** * Create child element {@odf.element number:text}. * * @return the element {@odf.element number:text} */ public NumberTextElement newNumberTextElement() { NumberTextElement numberText = ((OdfFileDom) this.ownerDocument).newOdfElement(NumberTextElement.class); this.appendChild(numberText); return numberText; } /** * Create child element {@odf.element style:map}. * * @param styleApplyStyleNameValue the <code>String</code> value of <code>StyleApplyStyleNameAttribute</code>, see {@odf.attribute style:apply-style-name} at specification * @param styleConditionValue the <code>String</code> value of <code>StyleConditionAttribute</code>, see {@odf.attribute style:condition} at specification * @return the element {@odf.element style:map} */ public StyleMapElement newStyleMapElement(String styleApplyStyleNameValue, String styleConditionValue) { StyleMapElement styleMap = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleMapElement.class); styleMap.setStyleApplyStyleNameAttribute(styleApplyStyleNameValue); styleMap.setStyleConditionAttribute(styleConditionValue); this.appendChild(styleMap); return styleMap; } /** * Create child element {@odf.element style:text-properties}. * * @param textDisplayValue the <code>String</code> value of <code>TextDisplayAttribute</code>, see {@odf.attribute text:display} at specification * @return the element {@odf.element style:text-properties} */ public StyleTextPropertiesElement newStyleTextPropertiesElement(String textDisplayValue) { StyleTextPropertiesElement styleTextProperties = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleTextPropertiesElement.class); styleTextProperties.setTextDisplayAttribute(textDisplayValue); this.appendChild(styleTextProperties); return styleTextProperties; } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
gpl-2.0
tharindum/opennms_dashboard
opennms-services/src/main/java/org/opennms/protocols/jmx/JMXPeer.java
6471
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ /* * Created on Mar 3, 2005 * */ package org.opennms.protocols.jmx; import java.net.InetAddress; /** * <p>JMXPeer class.</p> * * @author ranger * @version $Id: $ */ public class JMXPeer extends Object implements Cloneable { /** * The internet address of the peer */ private InetAddress m_peer; // the remote agent /** * The remote port of the agent. By default this is usually 161, but it can * change. */ private int m_port; // the remote port /** * The local port of the agent. By default this is usually 0 when acting as * manager, 161 as agent */ private int m_serverport = 0; // the local server port /** * The number of time to resend the datagram to the host. */ private int m_retries; // # of retries /** * The length of time to wait on the remote agent to respond. The time is * measured in milliseconds (1/1000th of a second). */ private int m_timeout; // in milliseconds /** * The default remote port. On most systems this is port 161, the default * trap receiver is on port 162. */ public static final int defaultRemotePort = 9004; /** * The library default for the number of retries. */ public static final int defaultRetries = 3; /** * The library default for the number of milliseconds to wait for a reply * from the remote agent. */ public static final int defaultTimeout = 8000; // .8 seconds /** * Class constructor. Constructs a JMXPeer to the passed remote agent. * * @param peer * The remote internet address */ public JMXPeer(InetAddress peer) { m_peer = peer; m_port = defaultRemotePort; m_timeout = defaultTimeout; m_retries = defaultRetries; } /** * Class constructor. Constructs a peer object with the specified internet * address and port. * * @param peer * The remote agent address * @param port * The port on the remote */ public JMXPeer(InetAddress peer, int port) { this(peer); m_port = port; } /** * Class copy constructor. Constructs a JMXPeer object that is identical to * the passed JMXPeer object. * * @param second * The peer object to copy. */ public JMXPeer(JMXPeer second) { m_peer = second.m_peer; m_port = second.m_port; m_timeout = second.m_timeout; m_retries = second.m_retries; } /** * Returns the peer agent's internet address to the caller * * @return The peer's internet address */ public InetAddress getPeer() { return m_peer; } /** * Used to set the peer's internet address for the remote agent. * * @param addr * The remote agents internet address */ public void setPeer(InetAddress addr) { m_peer = addr; } /** * Used to set the peer's internet address and port for communications. * * @param addr * The remote agent's internet address * @param port * The remote agent's port */ public void setPeer(InetAddress addr, int port) { m_peer = addr; m_port = port; } /** * Returns the remote agent's port for communications * * @return The remote agent's port */ public int getPort() { return m_port; } /** * Used to set the remote communication port * * @param port * The remote communication port */ public void setPort(int port) { m_port = port; } /** * Returns the local agent's port for communications * * @return The local agent's port */ public int getServerPort() { return m_serverport; } /** * Used to set the local communication port * * @param port * The local communication port */ public void setServerPort(int port) { m_serverport = port; } /** * Returns the currently set number of retries defined by this peer * * @return The currently configured number of retries. */ public int getRetries() { return m_retries; } /** * Used to set the default number of retries for this peer agent. * * @param retry * The new number of retries for the peer */ public void setRetries(int retry) { m_retries = retry; } /** * Retreives the currently configured timeout for the remote agent in * milliseconds (1/1000th second). * * @return The timeout value in milliseconds. */ public int getTimeout() { return m_timeout; } /** * Sets the millisecond timeout for the communications with the remote * agent. * * @param timeout * The timeout in milliseconds */ public void setTimeout(int timeout) { m_timeout = timeout; } /** * {@inheritDoc} * * Used to get a newly created copy of the current object. */ @Override public Object clone() { return new JMXPeer(this); } }
gpl-2.0
LinEvil/ProtocolSupport
src/protocolsupport/protocol/transformer/middlepacketimpl/clientbound/play/v_1_4_1_5_1_6_1_7/BlockChangeMulti.java
1345
package protocolsupport.protocol.transformer.middlepacketimpl.clientbound.play.v_1_4_1_5_1_6_1_7; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.ClientBoundPacket; import protocolsupport.protocol.transformer.middlepacket.clientbound.play.MiddleBlockChangeMulti; import protocolsupport.protocol.transformer.middlepacketimpl.PacketData; import protocolsupport.protocol.typeremapper.id.IdRemapper; import protocolsupport.protocol.typeremapper.id.RemappingTable; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class BlockChangeMulti extends MiddleBlockChangeMulti<RecyclableCollection<PacketData>> { @Override public RecyclableCollection<PacketData> toData(ProtocolVersion version) { RemappingTable remapper = IdRemapper.BLOCK.getTable(version); PacketData serializer = PacketData.create(ClientBoundPacket.PLAY_BLOCK_CHANGE_MULTI_ID, version); serializer.writeInt(chunkX); serializer.writeInt(chunkZ); serializer.writeShort(records.length); serializer.writeInt(records.length * 4); for (Record record : records) { serializer.writeShort(record.coord); int id = record.id; serializer.writeShort((remapper.getRemap(id >> 4) << 4) | (id & 0xF)); } return RecyclableSingletonList.create(serializer); } }
gpl-3.0
home9464/ABCGrid
worker/src/pku/cbi/abcgrid/worker/tar/TarHeader.java
13183
package pku.cbi.abcgrid.worker.tar; /* ** Authored by Timothy Gerard Endres ** <mailto:time@gjt.org> <http://www.trustice.com> ** ** This work has been placed into the public domain. ** You may use this work in any way and for any purpose you wish. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */ /** * This class encapsulates the Tar Entry Header used in Tar Archives. * The class also holds a number of tar constants, used mostly in headers. * * @author Timothy Gerard Endres, <time@gjt.org> */ public class TarHeader extends Object implements Cloneable { /** * The length of the name field in a header buffer. */ public static final int NAMELEN = 100; /** * The offset of the name field in a header buffer. */ public static final int NAMEOFFSET = 0; /** * The length of the name prefix field in a header buffer. */ public static final int PREFIXLEN = 155; /** * The offset of the name prefix field in a header buffer. */ public static final int PREFIXOFFSET = 345; /** * The length of the mode field in a header buffer. */ public static final int MODELEN = 8; /** * The length of the user id field in a header buffer. */ public static final int UIDLEN = 8; /** * The length of the group id field in a header buffer. */ public static final int GIDLEN = 8; /** * The length of the checksum field in a header buffer. */ public static final int CHKSUMLEN = 8; /** * The length of the size field in a header buffer. */ public static final int SIZELEN = 12; /** * The length of the magic field in a header buffer. */ public static final int MAGICLEN = 8; /** * The length of the modification time field in a header buffer. */ public static final int MODTIMELEN = 12; /** * The length of the user name field in a header buffer. */ public static final int UNAMELEN = 32; /** * The length of the group name field in a header buffer. */ public static final int GNAMELEN = 32; /** * The length of the devices field in a header buffer. */ public static final int DEVLEN = 8; /** * LF_ constants represent the "link flag" of an entry, or more commonly, * the "entry type". This is the "old way" of indicating a normal file. */ public static final byte LF_OLDNORM = 0; /** * Normal file type. */ public static final byte LF_NORMAL = (byte) '0'; /** * Link file type. */ public static final byte LF_LINK = (byte) '1'; /** * Symbolic link file type. */ public static final byte LF_SYMLINK = (byte) '2'; /** * Character device file type. */ public static final byte LF_CHR = (byte) '3'; /** * Block device file type. */ public static final byte LF_BLK = (byte) '4'; /** * Directory file type. */ public static final byte LF_DIR = (byte) '5'; /** * FIFO (pipe) file type. */ public static final byte LF_FIFO = (byte) '6'; /** * Contiguous file type. */ public static final byte LF_CONTIG = (byte) '7'; /** * The magic tag representing a POSIX tar archive. */ public static final String TMAGIC = "ustar"; /** * The magic tag representing a GNU tar archive. */ public static final String GNU_TMAGIC = "ustar "; /** * The entry's name. */ public StringBuffer name; /** * The entry's permission mode. */ public int mode; /** * The entry's user id. */ public int userId; /** * The entry's group id. */ public int groupId; /** * The entry's size. */ public long size; /** * The entry's modification time. */ public long modTime; /** * The entry's checksum. */ public int checkSum; /** * The entry's link flag. */ public byte linkFlag; /** * The entry's link name. */ public StringBuffer linkName; /** * The entry's magic tag. */ public StringBuffer magic; /** * The entry's user name. */ public StringBuffer userName; /** * The entry's group name. */ public StringBuffer groupName; /** * The entry's major device number. */ public int devMajor; /** * The entry's minor device number. */ public int devMinor; public TarHeader() { this.magic = new StringBuffer( TarHeader.TMAGIC ); this.name = new StringBuffer(); this.linkName = new StringBuffer(); String user = System.getProperty( "user.name", "" ); if ( user.length() > 31 ) user = user.substring( 0, 31 ); this.userId = 0; this.groupId = 0; this.userName = new StringBuffer( user ); this.groupName = new StringBuffer( "" ); } /** * TarHeaders can be cloned. */ public Object clone() { TarHeader hdr = null; try { hdr = (TarHeader) super.clone(); hdr.name = (this.name == null ) ? null : new StringBuffer( this.name.toString() ); hdr.mode = this.mode; hdr.userId = this.userId; hdr.groupId = this.groupId; hdr.size = this.size; hdr.modTime = this.modTime; hdr.checkSum = this.checkSum; hdr.linkFlag = this.linkFlag; hdr.linkName = (this.linkName == null ) ? null : new StringBuffer( this.linkName.toString() ); hdr.magic = (this.magic == null ) ? null : new StringBuffer( this.magic.toString() ); hdr.userName = (this.userName == null ) ? null : new StringBuffer( this.userName.toString() ); hdr.groupName = (this.groupName == null ) ? null : new StringBuffer( this.groupName.toString() ); hdr.devMajor = this.devMajor; hdr.devMinor = this.devMinor; } catch ( CloneNotSupportedException ex ) { ex.printStackTrace( System.err ); } return hdr; } /** * Get the name of this entry. * * @return Teh entry's name. */ public String getName() { return this.name.toString(); } /** * Parse an octal string from a header buffer. This is used for the * file permission mode value. * * @param header The header buffer from which to parse. * @param offset The offset into the buffer from which to parse. * @param length The number of header bytes to parse. * @return The long value of the octal string. */ public static long parseOctal( byte[] header, int offset, int length ) throws InvalidHeaderException { long result = 0; boolean stillPadding = true; int end = offset + length; for ( int i = offset ; i < end ; ++i ) { if ( header[i] == 0 ) break; if ( header[i] == (byte) ' ' || header[i] == '0' ) { if ( stillPadding ) continue; if ( header[i] == (byte) ' ' ) break; } stillPadding = false; result = (result << 3) + (header[i] - '0'); } return result; } /** * Parse a file name from a header buffer. This is different from * parseName() in that is recognizes 'ustar' names and will handle * adding on the "prefix" field to the name. * * Contributed by Dmitri Tikhonov <dxt2431@yahoo.com> * * @param header The header buffer from which to parse. * @param offset The offset into the buffer from which to parse. * @param length The number of header bytes to parse. * @return The header's entry name. */ public static StringBuffer parseFileName( byte[] header ) { StringBuffer result = new StringBuffer( 256 ); // If header[345] is not equal to zero, then it is the "prefix" // that 'ustar' defines. It must be prepended to the "normal" // name field. We are responsible for the separating '/'. // if ( header[345] != 0 ) { for ( int i = 345 ; i < 500 && header[i] != 0 ; ++i ) { result.append( (char)header[i] ); } result.append( "/" ); } for ( int i = 0 ; i < 100 && header[i] != 0 ; ++i ) { result.append( (char)header[i] ); } return result; } /** * Parse an entry name from a header buffer. * * @param header The header buffer from which to parse. * @param offset The offset into the buffer from which to parse. * @param length The number of header bytes to parse. * @return The header's entry name. */ public static StringBuffer parseName( byte[] header, int offset, int length ) throws InvalidHeaderException { StringBuffer result = new StringBuffer( length ); int end = offset + length; for ( int i = offset ; i < end ; ++i ) { if ( header[i] == 0 ) break; result.append( (char)header[i] ); } return result; } /** * This method, like getNameBytes(), is intended to place a name * into a TarHeader's buffer. However, this method is sophisticated * enough to recognize long names (name.length() > NAMELEN). In these * cases, the method will break the name into a prefix and suffix and * place the name in the header in 'ustar' format. It is up to the * TarEntry to manage the "entry header format". This method assumes * the name is valid for the type of archive being generated. * * @param outbuf The buffer containing the entry header to modify. * @param newName The new name to place into the header buffer. * @return The current offset in the tar header (always TarHeader.NAMELEN). * @throws InvalidHeaderException If the name will not fit in the header. */ public static int getFileNameBytes( String newName, byte[] outbuf ) throws InvalidHeaderException { if ( newName.length() > 100 ) { // Locate a pathname "break" prior to the maximum name length... int index = newName.indexOf( "/", newName.length() - 100 ); if ( index == -1 ) throw new InvalidHeaderException ( "file name is greater than 100 characters, " + newName ); // Get the "suffix subpath" of the name. String name = newName.substring( index + 1 ); // Get the "prefix subpath", or "prefix", of the name. String prefix = newName.substring( 0, index ); if ( prefix.length() > TarHeader.PREFIXLEN ) throw new InvalidHeaderException ( "file prefix is greater than 155 characters" ); TarHeader.getNameBytes ( new StringBuffer( name ), outbuf, TarHeader.NAMEOFFSET, TarHeader.NAMELEN ); TarHeader.getNameBytes ( new StringBuffer( prefix ), outbuf, TarHeader.PREFIXOFFSET, TarHeader.PREFIXLEN ); } else { TarHeader.getNameBytes ( new StringBuffer( newName ), outbuf, TarHeader.NAMEOFFSET, TarHeader.NAMELEN ); } // The offset, regardless of the format, is now the end of the // original name field. // return TarHeader.NAMELEN; } /** * Move the bytes from the name StringBuffer into the header's buffer. * * @param header The header buffer into which to copy the name. * @param offset The offset into the buffer at which to store. * @param length The number of header bytes to store. * @return The new offset (offset + length). */ public static int getNameBytes( StringBuffer name, byte[] buf, int offset, int length ) { int i; for ( i = 0 ; i < length && i < name.length() ; ++i ) { buf[ offset + i ] = (byte) name.charAt( i ); } for ( ; i < length ; ++i ) { buf[ offset + i ] = 0; } return offset + length; } /** * Parse an octal integer from a header buffer. * * @param header The header buffer from which to parse. * @param offset The offset into the buffer from which to parse. * @param length The number of header bytes to parse. * @return The integer value of the octal bytes. */ public static int getOctalBytes( long value, byte[] buf, int offset, int length ) { byte[] result = new byte[ length ]; int idx = length - 1; buf[ offset + idx ] = 0; --idx; buf[ offset + idx ] = (byte) ' '; --idx; if ( value == 0 ) { buf[ offset + idx ] = (byte) '0'; --idx; } else { for ( long val = value ; idx >= 0 && val > 0 ; --idx ) { buf[ offset + idx ] = (byte) ( (byte) '0' + (byte) (val & 7) ); val = val >> 3; } } for ( ; idx >= 0 ; --idx ) { buf[ offset + idx ] = (byte) ' '; } return offset + length; } /** * Parse an octal long integer from a header buffer. * * @param header The header buffer from which to parse. * @param offset The offset into the buffer from which to parse. * @param length The number of header bytes to parse. * @return The long value of the octal bytes. */ public static int getLongOctalBytes( long value, byte[] buf, int offset, int length ) { byte[] temp = new byte[ length + 1 ]; TarHeader.getOctalBytes( value, temp, 0, length + 1 ); System.arraycopy( temp, 0, buf, offset, length ); return offset + length; } /** * Parse the checksum octal integer from a header buffer. * * @param header The header buffer from which to parse. * @param offset The offset into the buffer from which to parse. * @param length The number of header bytes to parse. * @return The integer value of the entry's checksum. */ public static int getCheckSumOctalBytes( long value, byte[] buf, int offset, int length ) { TarHeader.getOctalBytes( value, buf, offset, length ); buf[ offset + length - 1 ] = (byte) ' '; buf[ offset + length - 2 ] = 0; return offset + length; } }
gpl-3.0
Limezero/libreoffice
qadevOOo/runner/graphical/PerformanceContainer.java
8571
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package graphical; import java.io.File; import java.io.PrintStream; import java.io.RandomAccessFile; public class PerformanceContainer /* extends *//* implements */ { /* simple helper functions to start/stop a timer, to know how long a process need in milliseconds */ public long getStartTime() { return System.currentTimeMillis(); } public void setStartTime(long _nStartTime) { } /* return the time, which is done until last startTime() */ private long meanTime(long _nCurrentTimer) { if (_nCurrentTimer == 0) { GlobalLogWriter.println("Forgotten to initialise a start timer."); return 0; } long nMeanTime = System.currentTimeMillis(); return nMeanTime - _nCurrentTimer; } /* public long stopTimer() { if (m_nStartTime == 0) { System.out.println("Forgotten to initialise start timer."); return 0; } long nStopTime = System.currentTimeMillis(); return nStopTime - m_nStartTime; } */ final static int Load = 0; final static int Store = 1; final static int Print = 2; final static int OfficeStart = 3; final static int StoreAsPDF = 4; final static int OfficeStop = 5; final static int AllTime = 6; private final static int LAST_VALUE = 7; // THIS MUST BE ALWAYS THE LAST AND THE BIGGEST VALUE! private long m_nTime[]; private String m_sMSOfficeVersion; public PerformanceContainer() { m_nTime = new long[LAST_VALUE]; // @todo: is this need? for (int i=0;i<LAST_VALUE;i++) { m_nTime[i] = 0; } } public void setTime(int _nIndex, long _nValue) { m_nTime[_nIndex] = _nValue; } public long getTime(int _nIndex) { return m_nTime[_nIndex]; } public void startTime(int _nIndex) { m_nTime[_nIndex] = getStartTime(); } public void stopTime(int _nIndex) { m_nTime[_nIndex] = meanTime(m_nTime[_nIndex]); } public String getMSOfficeVersion() { return m_sMSOfficeVersion; } public void print(PrintStream out) { out.println("loadtime=" + m_nTime[ Load ]); out.println("storetime=" + m_nTime[ Store ]); out.println("printtime=" + m_nTime[ Print ]); out.println("officestarttime=" + m_nTime[ OfficeStart ]); out.println("officestoptime=" + m_nTime[ OfficeStop ]); out.println("storeaspdftime=" + m_nTime[ StoreAsPDF ]); out.println("alltime=" + m_nTime[ AllTime ]); } public void print(IniFile _aIniFile, String _sSection) { _aIniFile.insertValue(_sSection, "loadtime" , String.valueOf(m_nTime[ Load ])); _aIniFile.insertValue(_sSection, "storetime" , String.valueOf(m_nTime[ Store ])); _aIniFile.insertValue(_sSection, "printtime" , String.valueOf(m_nTime[ Print ])); _aIniFile.insertValue(_sSection, "officestarttime" , String.valueOf(m_nTime[ OfficeStart ])); _aIniFile.insertValue(_sSection, "officestoptime" , String.valueOf(m_nTime[ OfficeStop ])); _aIniFile.insertValue(_sSection, "storeaspdftime" , String.valueOf(m_nTime[ StoreAsPDF ])); _aIniFile.insertValue(_sSection, "alltime" , String.valueOf(m_nTime[ AllTime ])); } private static double stringToDouble(String _sStr) { double nValue = 0; try { nValue = Double.parseDouble( _sStr ); } catch (NumberFormatException e) { GlobalLogWriter.println("Can't convert string to double " + _sStr); } return nValue; } private static long secondsToMilliSeconds(double _nSeconds) { return (long)(_nSeconds * 1000.0); } /* Helper function, which read some values from a given file sample of wordinfofile name=c:\doc-pool\wntmsci\samples\msoffice\word\LineSpacing.doc WordVersion=11.0 WordStartTime=0.340490102767944 WordLoadTime=0.650935888290405 WordPrintTime=0.580835103988647 */ public void readWordValuesFromFile(String sFilename) { File aFile = new File(sFilename); if (! aFile.exists()) { GlobalLogWriter.println("couldn't find file " + sFilename); return; } RandomAccessFile aRandomAccessFile = null; try { aRandomAccessFile = new RandomAccessFile(aFile,"r"); String sLine = ""; while (sLine != null) { sLine = aRandomAccessFile.readLine(); if ( (sLine != null) && (sLine.length() >= 2 ) && (! sLine.startsWith("#"))) { if (sLine.startsWith("WordStartTime=")) { String sTime = sLine.substring(14); m_nTime[OfficeStart] = secondsToMilliSeconds(stringToDouble(sTime)); } else if (sLine.startsWith("WordLoadTime=")) { String sTime = sLine.substring(13); m_nTime[Load] = secondsToMilliSeconds(stringToDouble(sTime)); } else if (sLine.startsWith("WordPrintTime=")) { String sTime = sLine.substring(14); m_nTime[Print] = secondsToMilliSeconds(stringToDouble(sTime)); } else if (sLine.startsWith("WordVersion=")) { String sMSOfficeVersion = sLine.substring(12); m_sMSOfficeVersion = "Word:" + sMSOfficeVersion; } else if (sLine.startsWith("ExcelVersion=")) { String sMSOfficeVersion = sLine.substring(13); m_sMSOfficeVersion = "Excel:" + sMSOfficeVersion; } else if (sLine.startsWith("PowerPointVersion=")) { String sMSOfficeVersion = sLine.substring(18); m_sMSOfficeVersion = "PowerPoint:" + sMSOfficeVersion; } } } } catch (java.io.FileNotFoundException fne) { GlobalLogWriter.println("couldn't open file " + sFilename); GlobalLogWriter.println("Message: " + fne.getMessage()); } catch (java.io.IOException ie) { GlobalLogWriter.println("Exception while reading file " + sFilename); GlobalLogWriter.println("Message: " + ie.getMessage()); } try { aRandomAccessFile.close(); } catch (java.io.IOException ie) { GlobalLogWriter.println("Couldn't close file " + sFilename); GlobalLogWriter.println("Message: " + ie.getMessage()); } } }
gpl-3.0
kevin-wayne/algs4
src/main/java/edu/princeton/cs/algs4/FlowEdge.java
9096
/****************************************************************************** * Compilation: javac FlowEdge.java * Execution: java FlowEdge * Dependencies: StdOut.java * * Capacitated edge with a flow in a flow network. * ******************************************************************************/ package edu.princeton.cs.algs4; /** * The {@code FlowEdge} class represents a capacitated edge with a * flow in a {@link FlowNetwork}. Each edge consists of two integers * (naming the two vertices), a real-valued capacity, and a real-valued * flow. The data type provides methods for accessing the two endpoints * of the directed edge and the weight. It also provides methods for * changing the amount of flow on the edge and determining the residual * capacity of the edge. * <p> * For additional documentation, see <a href="https://algs4.cs.princeton.edu/64maxflow">Section 6.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class FlowEdge { // to deal with floating-point roundoff errors private static final double FLOATING_POINT_EPSILON = 1E-10; private final int v; // from private final int w; // to private final double capacity; // capacity private double flow; // flow /** * Initializes an edge from vertex {@code v} to vertex {@code w} with * the given {@code capacity} and zero flow. * @param v the tail vertex * @param w the head vertex * @param capacity the capacity of the edge * @throws IllegalArgumentException if either {@code v} or {@code w} * is a negative integer * @throws IllegalArgumentException if {@code capacity < 0.0} */ public FlowEdge(int v, int w, double capacity) { if (v < 0) throw new IllegalArgumentException("vertex index must be a non-negative integer"); if (w < 0) throw new IllegalArgumentException("vertex index must be a non-negative integer"); if (!(capacity >= 0.0)) throw new IllegalArgumentException("Edge capacity must be non-negative"); this.v = v; this.w = w; this.capacity = capacity; this.flow = 0.0; } /** * Initializes an edge from vertex {@code v} to vertex {@code w} with * the given {@code capacity} and {@code flow}. * @param v the tail vertex * @param w the head vertex * @param capacity the capacity of the edge * @param flow the flow on the edge * @throws IllegalArgumentException if either {@code v} or {@code w} * is a negative integer * @throws IllegalArgumentException if {@code capacity} is negative * @throws IllegalArgumentException unless {@code flow} is between * {@code 0.0} and {@code capacity}. */ public FlowEdge(int v, int w, double capacity, double flow) { if (v < 0) throw new IllegalArgumentException("vertex index must be a non-negative integer"); if (w < 0) throw new IllegalArgumentException("vertex index must be a non-negative integer"); if (!(capacity >= 0.0)) throw new IllegalArgumentException("edge capacity must be non-negative"); if (!(flow <= capacity)) throw new IllegalArgumentException("flow exceeds capacity"); if (!(flow >= 0.0)) throw new IllegalArgumentException("flow must be non-negative"); this.v = v; this.w = w; this.capacity = capacity; this.flow = flow; } /** * Initializes a flow edge from another flow edge. * @param e the edge to copy */ public FlowEdge(FlowEdge e) { this.v = e.v; this.w = e.w; this.capacity = e.capacity; this.flow = e.flow; } /** * Returns the tail vertex of the edge. * @return the tail vertex of the edge */ public int from() { return v; } /** * Returns the head vertex of the edge. * @return the head vertex of the edge */ public int to() { return w; } /** * Returns the capacity of the edge. * @return the capacity of the edge */ public double capacity() { return capacity; } /** * Returns the flow on the edge. * @return the flow on the edge */ public double flow() { return flow; } /** * Returns the endpoint of the edge that is different from the given vertex * (unless the edge represents a self-loop in which case it returns the same vertex). * @param vertex one endpoint of the edge * @return the endpoint of the edge that is different from the given vertex * (unless the edge represents a self-loop in which case it returns the same vertex) * @throws IllegalArgumentException if {@code vertex} is not one of the endpoints * of the edge */ public int other(int vertex) { if (vertex == v) return w; else if (vertex == w) return v; else throw new IllegalArgumentException("invalid endpoint"); } /** * Returns the residual capacity of the edge in the direction * to the given {@code vertex}. * @param vertex one endpoint of the edge * @return the residual capacity of the edge in the direction to the given vertex * If {@code vertex} is the tail vertex, the residual capacity equals * {@code capacity() - flow()}; if {@code vertex} is the head vertex, the * residual capacity equals {@code flow()}. * @throws IllegalArgumentException if {@code vertex} is not one of the endpoints of the edge */ public double residualCapacityTo(int vertex) { if (vertex == v) return flow; // backward edge else if (vertex == w) return capacity - flow; // forward edge else throw new IllegalArgumentException("invalid endpoint"); } /** * Increases the flow on the edge in the direction to the given vertex. * If {@code vertex} is the tail vertex, this increases the flow on the edge by {@code delta}; * if {@code vertex} is the head vertex, this decreases the flow on the edge by {@code delta}. * @param vertex one endpoint of the edge * @param delta amount by which to increase flow * @throws IllegalArgumentException if {@code vertex} is not one of the endpoints * of the edge * @throws IllegalArgumentException if {@code delta} makes the flow on * on the edge either negative or larger than its capacity * @throws IllegalArgumentException if {@code delta} is {@code NaN} */ public void addResidualFlowTo(int vertex, double delta) { if (!(delta >= 0.0)) throw new IllegalArgumentException("Delta must be non-negative"); if (vertex == v) flow -= delta; // backward edge else if (vertex == w) flow += delta; // forward edge else throw new IllegalArgumentException("invalid endpoint"); // round flow to 0 or capacity if within floating-point precision if (Math.abs(flow) <= FLOATING_POINT_EPSILON) flow = 0; if (Math.abs(flow - capacity) <= FLOATING_POINT_EPSILON) flow = capacity; if (!(flow >= 0.0)) throw new IllegalArgumentException("Flow is negative"); if (!(flow <= capacity)) throw new IllegalArgumentException("Flow exceeds capacity"); } /** * Returns a string representation of the edge. * @return a string representation of the edge */ public String toString() { return v + "->" + w + " " + flow + "/" + capacity; } /** * Unit tests the {@code FlowEdge} data type. * * @param args the command-line arguments */ public static void main(String[] args) { FlowEdge e = new FlowEdge(12, 23, 4.56); StdOut.println(e); } } /****************************************************************************** * Copyright 2002-2020, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
gpl-3.0
slipcor/MobArena
src/main/java/com/garbagemule/MobArena/signs/HandlesWorldUnload.java
963
package com.garbagemule.MobArena.signs; import org.bukkit.World; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.world.WorldUnloadEvent; import java.util.List; import java.util.logging.Logger; class HandlesWorldUnload implements Listener { private final SignStore store; private final Logger log; HandlesWorldUnload( SignStore store, Logger log ) { this.store = store; this.log = log; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void on(WorldUnloadEvent event) { World world = event.getWorld(); List<ArenaSign> removed = store.removeByWorld(world); if (!removed.isEmpty()) { log.info(removed.size() + " arena sign(s) unloaded due to unloading of world '" + world.getName() + "' (" + world.getUID().toString() + ")."); } } }
gpl-3.0
idega/com.idega.builder
src/java/com/idega/builder/business/ComponentBasedPage.java
1257
/* * $Id: ComponentBasedPage.java,v 1.2 2005/09/06 12:19:59 tryggvil Exp $ * Created on 19.12.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.builder.business; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import com.idega.presentation.IWContext; import com.idega.presentation.Page; /** * <p> * This is an interface for declaring a "component-based" Builder page that is rendered through JSF.<br/> * This means that the page is entirely based up on and rendered through JSF components or existing classes, * The opposite of this is e.g. a JSP based Builder page. <br/> * Old style IBXML pages are populated into a com.idega.presentation.Page and rended as such. * </p> * Last modified: $Date: 2005/09/06 12:19:59 $ by $Author: tryggvil $ * * @author <a href="mailto:tryggvil@idega.com">Tryggvi Larusson</a> * @version $Revision: 1.2 $ */ public interface ComponentBasedPage { public Page getNewPageCloned(); public Page getPage(IWContext iwc); public Page getNewPage(IWContext iwc); public UIComponent createComponent(FacesContext context); }
gpl-3.0
Armarr/Autorank-2
src/me/armar/plugins/autorank/pathbuilder/builders/ResultBuilder.java
6767
package me.armar.plugins.autorank.pathbuilder.builders; import me.armar.plugins.autorank.Autorank; import me.armar.plugins.autorank.pathbuilder.result.AbstractResult; import me.armar.plugins.autorank.util.AutorankTools; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import java.util.*; /** * This class is used to create a new AbstractResult. It uses the Factory Method Design Pattern. */ public class ResultBuilder { private static final Map<String, Class<? extends AbstractResult>> results = new HashMap<String, Class<? extends AbstractResult>>(); // Keep track of the associated abstractResult. private AbstractResult abstractResult = null; // Whether the associated abstractResult is valid. private boolean isValid = false; // Extra metadata for the associated abstractResult. private String pathName, resultName, originalResultString; /** * Add a new type of AbstractResult that can be used in the Paths.yml file. * * @param type String literal that must be used in the file to identify the abstractResult. * @param result Class of the AbstractResult that must be instantiated. */ public static void registerResult(final String type, final Class<? extends AbstractResult> result) { results.put(type, result); // Add type to the list of AutorankTools so it can use the correct name. AutorankTools.registerResult(type); } /** * Remove a registered result with the given type. * * @param type Identifier of the result * @return true if it was removed, false if there was no element with the given identifier. */ public static boolean unRegisterResult(String type) { if (!results.containsKey(type)) { return false; } results.remove(type); return true; } /** * Get all results that are registered. * * @return A collection of result classes that are registered. */ public static List<Class<? extends AbstractResult>> getRegisteredResults() { return new ArrayList<>(results.values()); } /** * Get the result that is registered with the given type. * * @param type Identifier of the result. * @return result if found, or null. */ public static Optional<Class<? extends AbstractResult>> getRegisteredResult(String type) { return Optional.ofNullable(results.getOrDefault(type, null)); } /** * Create a AbstractResult using the ResultBuilder factory. * * @param pathName Name of the path the abstractResult is in. * @param resultType Type of the abstractResult, which does not have to be the exact string value. * @param stringValue Value of the abstractResult string. * @return a newly created AbstractResult with the given storage, or null if invalid storage was given. */ public static AbstractResult createResult(String pathName, String resultType, String stringValue) { ResultBuilder builder = new ResultBuilder().createEmpty(pathName, resultType).populateResult(stringValue); // Check if abstractResult is valid before building it. if (!builder.isValid()) { return null; } // Get abstractResult of ResultBuilder. return builder.finish(); } public final Autorank getAutorank() { return Autorank.getInstance(); } /** * Create an empty AbstractResult. * * @param pathName Name of the path that this abstractResult is in. * @param resultType Type of the abstractResult. * @return this builder. */ public ResultBuilder createEmpty(String pathName, String resultType) { this.pathName = pathName; this.originalResultString = resultType; resultType = AutorankTools.findMatchingResultName(resultType); this.resultName = resultType; if (resultType == null) { Autorank.getInstance().getWarningManager().registerWarning( String.format("You are using a '%s' result in path '%s', but that result doesn't " + "exist!", originalResultString, pathName), 10); return this; } final Class<? extends AbstractResult> c = results.get(resultType); if (c != null) { try { abstractResult = c.newInstance(); } catch (final Exception e) { e.printStackTrace(); } } else { Bukkit.getServer().getConsoleSender() .sendMessage("[Autorank] " + ChatColor.RED + "Result '" + originalResultString + "' is not a " + "valid " + "result type!"); } return this; } /** * Populate the created AbstractResult with storage. * * @return this builder. */ public ResultBuilder populateResult(String stringValue) { if (abstractResult == null) { return this; } if (stringValue == null) { return this; } // Initialize the abstractResult with options. abstractResult.setOptions(stringValue.split(";")); // Check if there is a custom description set for this result, if so, set it. if (getAutorank().getPathsConfig().hasCustomResultDescription(this.pathName, this.originalResultString)) { abstractResult.setCustomDescription(getAutorank().getPathsConfig().getCustomResultDescription(this .pathName, this.originalResultString)); } abstractResult.setGlobal(getAutorank().getPathsConfig().isResultGlobal(this.pathName, this.originalResultString)); // AbstractResult is non-null and populated with storage, so valid. isValid = true; return this; } /** * Finish the creation of the AbstractResult, will return the abstractResult object that was created. * * @return created AbstractResult object. * @throws IllegalStateException if the abstractResult was not valid and could not be finished. */ public AbstractResult finish() throws IllegalStateException { if (!isValid || abstractResult == null) { throw new IllegalStateException("Result '" + originalResultString + "' of '" + pathName + "' was not " + "valid and could not be finished."); } return abstractResult; } /** * Check whether the associated abstractResult is valid. * * @return true if it is, false otherwise. */ public boolean isValid() { return isValid; } }
gpl-3.0
randomstuffpaul/KernelAdiutor
app/src/main/java/com/grarak/kerneladiutor/utils/kernel/cpu/Temperature.java
6184
/* * Copyright (C) 2015-2016 Willi Ye <williye97@gmail.com> * * This file is part of Kernel Adiutor. * * Kernel Adiutor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Kernel Adiutor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>. * */ package com.grarak.kerneladiutor.utils.kernel.cpu; import android.content.Context; import android.util.Log; import com.grarak.kerneladiutor.R; import com.grarak.kerneladiutor.utils.Device; import com.grarak.kerneladiutor.utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; /** * Created by willi on 21.04.16. */ public class Temperature { private static final HashMap<String, Integer> sCPUTemps = new HashMap<>(); private static final String THERMAL_ZONE0 = "/sys/class/thermal/thermal_zone0/temp"; static { sCPUTemps.put("/sys/devices/platform/omap/omap_temp_sensor.0/temperature", 1000); sCPUTemps.put("/proc/mtktscpu/mtktscpu_temperature", 1000); } private static TempJson TEMP_JSON; private static String CPU_NODE; private static int CPU_OFFSET; private static String GPU_NODE; private static int GPU_OFFSET; public static String getGPU(Context context) { double temp = getGPUTemp(); boolean useFahrenheit = Utils.useFahrenheit(context); if (useFahrenheit) temp = Utils.celsiusToFahrenheit(temp); return Utils.roundTo2Decimals(temp) + context.getString(useFahrenheit ? R.string.fahrenheit : R.string.celsius); } private static double getGPUTemp() { return (double) Utils.strToInt(Utils.readFile(GPU_NODE)) / GPU_OFFSET; } public static boolean hasGPU() { if (TEMP_JSON != null && TEMP_JSON.getGPU() != null) { GPU_NODE = TEMP_JSON.getGPU(); if (Utils.existFile(GPU_NODE)) { GPU_OFFSET = TEMP_JSON.getGPUOffset(); if (GPU_OFFSET != 1 && Utils.readFile(GPU_NODE).length() == 2) { GPU_OFFSET = 1; } return true; } GPU_NODE = null; } return false; } public static String getCPU(Context context) { double temp = getCPUTemp(); boolean useFahrenheit = Utils.useFahrenheit(context); if (useFahrenheit) temp = Utils.celsiusToFahrenheit(temp); return Utils.roundTo2Decimals(temp) + context.getString(useFahrenheit ? R.string.fahrenheit : R.string.celsius); } private static double getCPUTemp() { return (double) Utils.strToInt(Utils.readFile(CPU_NODE)) / CPU_OFFSET; } public static boolean hasCPU() { if (TEMP_JSON != null && TEMP_JSON.getCPU() != null) { CPU_NODE = TEMP_JSON.getCPU(); if (Utils.existFile(CPU_NODE)) { CPU_OFFSET = TEMP_JSON.getCPUOffset(); if (CPU_OFFSET != 1 && Utils.readFile(CPU_NODE).length() == 2) { CPU_OFFSET = 1; } return true; } CPU_NODE = null; } if (CPU_NODE != null) return true; for (String node : sCPUTemps.keySet()) { if (Utils.existFile(node)) { CPU_NODE = node; CPU_OFFSET = sCPUTemps.get(CPU_NODE); return true; } } if (CPU_NODE == null && Utils.existFile(THERMAL_ZONE0)) { CPU_NODE = THERMAL_ZONE0; CPU_OFFSET = 1000; } if (CPU_NODE != null && Utils.readFile(CPU_NODE).length() == 2) { CPU_OFFSET = 1; } return CPU_NODE != null; } public static boolean supported(Context context) { if (TEMP_JSON == null) { TEMP_JSON = new TempJson(context); if (!TEMP_JSON.supported()) { TEMP_JSON = null; } } return hasCPU() || hasGPU(); } private static class TempJson { private static final String TAG = TempJson.class.getSimpleName(); private JSONObject mDeviceJson; private TempJson(Context context) { try { JSONArray tempArray = new JSONArray(Utils.readAssetFile(context, "temp.json")); for (int i = 0; i < tempArray.length(); i++) { JSONObject device = tempArray.getJSONObject(i); if (Device.getBoard().equalsIgnoreCase(device.getString("board"))) { mDeviceJson = device; break; } } } catch (JSONException ignored) { Log.e(TAG, "Can't read temp.json"); } } private int getGPUOffset() { try { return mDeviceJson.getInt("gpu-offset"); } catch (JSONException ignored) { return 1; } } private int getCPUOffset() { try { return mDeviceJson.getInt("cpu-offset"); } catch (JSONException ignored) { return 1; } } public String getGPU() { try { return mDeviceJson.getString("gpu"); } catch (JSONException ignored) { return null; } } public String getCPU() { try { return mDeviceJson.getString("cpu"); } catch (JSONException ignored) { return null; } } public boolean supported() { return mDeviceJson != null; } } }
gpl-3.0
spMohanty/sigmah_svn_to_git_migration_test
sigmah/src/main/java/org/sigmah/client/page/project/ProjectState.java
5038
/* * All Sigmah code is released under the GNU General Public License v3 * See COPYRIGHT.txt and LICENSE.txt. */ package org.sigmah.client.page.project; import java.util.Collections; import java.util.List; import org.sigmah.client.page.HasTab; import org.sigmah.client.page.PageId; import org.sigmah.client.page.PageState; import org.sigmah.client.page.PageStateParser; import org.sigmah.client.page.TabPage; import org.sigmah.client.ui.Tab; /** * Serialized state of a project page. * * @author Denis Colliot (dcolliot@ideia.fr) */ public class ProjectState implements PageState, TabPage, HasTab { private int projectId; private String tabTitle; private Tab tab; private Integer currentSection; private String argument; public ProjectState(int projectId) { this.projectId = projectId; } public static class Parser implements PageStateParser { @Override public PageState parse(String token) { final String[] tokens = token.split("/"); final ProjectState state = new ProjectState(Integer.parseInt(tokens[0])); if (tokens.length > 1) { state.setCurrentSection(Integer.parseInt(tokens[1])); if (tokens.length > 2) { state.setArgument(tokens[2]); } else { state.argument = null; } } return state; } } @Override public String serializeAsHistoryToken() { StringBuilder tokenBuilder = new StringBuilder(); if (currentSection != null) tokenBuilder.append(currentSection.toString()); if (argument != null) tokenBuilder.append('/').append(argument); if (tokenBuilder.length() == 0) return null; else return tokenBuilder.toString(); } /** * Creates a new <code>ProjectState</code> object using the same project but * with a different section. The argument is also setted to null. * * @param section * Id of the section. * @return A new <code>ProjectState</code> object. */ public ProjectState deriveTo(int section) { final ProjectState derivation = new ProjectState(projectId); derivation.setCurrentSection(section); return derivation; } @Override public PageId getPageId() { return new PageId(ProjectPresenter.PAGE_ID.toString() + '!' + projectId); } @Override public List<PageId> getEnclosingFrames() { return Collections.singletonList(ProjectPresenter.PAGE_ID); } public PageId getManualPageId() { StringBuilder tokenBuilder = new StringBuilder(); tokenBuilder.append(ProjectPresenter.PAGE_ID.toString()); tokenBuilder.append("/"); if (currentSection != null) { tokenBuilder.append(currentSection.toString()); } else { tokenBuilder.append("0"); } return new PageId(tokenBuilder.toString()); } public int getProjectId() { return projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public int getCurrentSection() { if (currentSection == null) return 0; else return currentSection; } public void setCurrentSection(Integer currentSection) { this.currentSection = currentSection; } public void setTabTitle(String tabTitle) { this.tabTitle = tabTitle; if (tab != null) { tab.setTitle(tabTitle); } } @Override public String getTabTitle() { return tabTitle; } @Override public Tab getTab() { return tab; } @Override public void setTab(Tab tab) { this.tab = tab; } public String getArgument() { return argument; } public void setArgument(String argument) { this.argument = argument; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ProjectState other = (ProjectState) obj; if (this.projectId != other.projectId) { return false; } if (this.currentSection != other.currentSection && (this.currentSection == null || !this.currentSection.equals(other.currentSection))) { return false; } if ((this.argument == null) ? (other.argument != null) : !this.argument.equals(other.argument)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 83 * hash + this.projectId; hash = 83 * hash + (this.currentSection != null ? this.currentSection.hashCode() : 0); hash = 83 * hash + (this.argument != null ? this.argument.hashCode() : 0); return hash; } }
gpl-3.0
ac2cz/FoxTelem
lib/mysql-connector-java-8.0.13/src/main/user-api/java/com/mysql/cj/jdbc/ha/ReplicationConnection.java
2346
/* * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj.jdbc.ha; import java.sql.SQLException; import com.mysql.cj.jdbc.JdbcConnection; public interface ReplicationConnection extends JdbcConnection { public long getConnectionGroupId(); public JdbcConnection getCurrentConnection(); public JdbcConnection getMasterConnection(); public void promoteSlaveToMaster(String host) throws SQLException; public void removeMasterHost(String host) throws SQLException; public void removeMasterHost(String host, boolean waitUntilNotInUse) throws SQLException; public boolean isHostMaster(String host); public JdbcConnection getSlavesConnection(); public void addSlaveHost(String host) throws SQLException; public void removeSlave(String host) throws SQLException; public void removeSlave(String host, boolean closeGently) throws SQLException; public boolean isHostSlave(String host); }
gpl-3.0
f-droid/fdroidclient
app/src/test/java/org/fdroid/fdroid/updater/AcceptableMultiIndexUpdaterTest.java
3857
package org.fdroid.fdroid.updater; import android.content.ContentValues; import android.util.Log; import org.fdroid.fdroid.IndexUpdater.UpdateException; import org.fdroid.fdroid.data.Repo; import org.fdroid.fdroid.data.RepoProvider; import org.fdroid.fdroid.data.Schema.RepoTable.Cols; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.List; import androidx.annotation.NonNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(RobolectricTestRunner.class) public class AcceptableMultiIndexUpdaterTest extends MultiIndexUpdaterTest { private static final String TAG = "AcceptableMultiRepoTest"; private void assertSomewhatAcceptable() { Log.i(TAG, "Asserting at least one versions of each .apk is in index."); List<Repo> repos = RepoProvider.Helper.all(context); assertEquals("Repos", 3, repos.size()); assertApp2048(); assertAppAdaway(); assertAppAdbWireless(); assertAppIcsImport(); } @Test public void testAcceptableConflictingThenMainThenArchive() throws UpdateException { assertEmpty(); updateConflicting(); updateMain(); updateArchive(); assertSomewhatAcceptable(); } @Test public void testAcceptableConflictingThenArchiveThenMain() throws UpdateException { assertEmpty(); updateConflicting(); updateArchive(); updateMain(); assertSomewhatAcceptable(); } @Test public void testAcceptableArchiveThenMainThenConflicting() throws UpdateException { assertEmpty(); updateArchive(); updateMain(); updateConflicting(); assertSomewhatAcceptable(); } @Test public void testAcceptableArchiveThenConflictingThenMain() throws UpdateException { assertEmpty(); updateArchive(); updateConflicting(); updateMain(); assertSomewhatAcceptable(); } @Test public void testAcceptableMainThenArchiveThenConflicting() throws UpdateException { assertEmpty(); updateMain(); updateArchive(); updateConflicting(); assertSomewhatAcceptable(); } @Test public void testAcceptableMainThenConflictingThenArchive() throws UpdateException { assertEmpty(); updateMain(); updateConflicting(); updateArchive(); assertSomewhatAcceptable(); } @NonNull private Repo getMainRepo() { Repo repo = RepoProvider.Helper.findByAddress(context, REPO_MAIN_URI); assertNotNull(repo); return repo; } @NonNull private Repo getArchiveRepo() { Repo repo = RepoProvider.Helper.findByAddress(context, REPO_ARCHIVE_URI); assertNotNull(repo); return repo; } @NonNull private Repo getConflictingRepo() { Repo repo = RepoProvider.Helper.findByAddress(context, REPO_CONFLICTING_URI); assertNotNull(repo); return repo; } @Test public void testOrphanedApps() throws UpdateException { assertEmpty(); updateArchive(); updateMain(); updateConflicting(); assertSomewhatAcceptable(); disableRepo(getArchiveRepo()); disableRepo(getMainRepo()); disableRepo(getConflictingRepo()); RepoProvider.Helper.purgeApps(context, getArchiveRepo()); RepoProvider.Helper.purgeApps(context, getMainRepo()); RepoProvider.Helper.purgeApps(context, getConflictingRepo()); assertEmpty(); } private void disableRepo(Repo repo) { ContentValues values = new ContentValues(1); values.put(Cols.IN_USE, 0); RepoProvider.Helper.update(context, repo, values); } }
gpl-3.0
codebucketdev/HoloAPI
src/com/comphenix/packetwrapper/WrapperPlayClientBlockDig.java
5498
/* * PacketWrapper - Contains wrappers for each packet in Minecraft. * Copyright (C) 2012 Kristian S. Stangeland * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ package com.comphenix.packetwrapper; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.reflect.IntEnum; public class WrapperPlayClientBlockDig extends AbstractPacket { public static final PacketType TYPE = PacketType.Play.Client.BLOCK_DIG; public enum Status { STARTED_DIGGING, // 0 CANCELLED_DIGGING, // 1 FINISHED_DIGGING, // 2 DROP_ITEM_STACK, // 3 DROP_ITEM, // 4 /** * Shooting arrows or finishing eating. */ SHOOT_ARROW // 5 } public static class BlockSide extends IntEnum { /** * Represents the bottom face of a block. * <p> * Offset: -Y */ public static final int BOTTOM = 0; /** * Represents the top face of a block. * <p> * Offset: Y */ public static final int TOP = 1; /** * Represents the face behind the block as seen by the player. * <p> * Offset: -Z */ public static final int BEHIND = 2; /** * Represents the face in front of the block as seen by the player. * <p> * Offset: Z */ public static final int FRONT = 3; /** * Represents the face to the left of the block as seen by the player. * <p> * Offset: -X */ public static final int LEFT = 4; /** * Represents the face to the right of the block as seen by the player. * <p> * Offset: X */ public static final int RIGHT = 5; /** * The singleton instance. Can also be retrieved from the parent class. */ private static BlockSide INSTANCE = new BlockSide(); /** * Retrieve an instance of the BlockSide enum. * @return BlockSide enum. */ public static BlockSide getInstance() { return INSTANCE; } private static final int[] xOffset = new int[] { 0, 0, 0, 0, -1, 1 }; private static final int[] yOffset = new int[] { -1, 1, 0, 0, 0, 0 }; private static final int[] zOffset = new int[] { 0, 0, -1, 1, 0, 0 }; public static int getXOffset(int blockFace) { return xOffset[blockFace]; } public static int getYOffset(int blockFace) { return yOffset[blockFace]; } public static int getZOffset(int blockFace) { return zOffset[blockFace]; } // We only allow a single instance of this class private BlockSide() { super(); } } public WrapperPlayClientBlockDig() { super(new PacketContainer(TYPE), TYPE); handle.getModifier().writeDefaults(); } public WrapperPlayClientBlockDig(PacketContainer packet) { super(packet, TYPE); } /** * Retrieve the action the player is taking against the block. * @return The current Status */ public Status getStatus() { return Status.values()[handle.getIntegers().read(4)]; } /** * Set the action the player is taking against the block. * @param value - new action. */ public void setStatus(Status value) { handle.getIntegers().write(4, value.ordinal()); } /** * Retrieve block position. * @return The current X */ public int getX() { return handle.getIntegers().read(0); } /** * Set block position. * @param value - new value. */ public void setX(int value) { handle.getIntegers().write(0, value); } /** * Retrieve block position. * @return The current Y */ public byte getY() { return handle.getIntegers().read(1).byteValue(); } /** * Set block position. * @param value - new value. */ public void setY(byte value) { handle.getIntegers().write(1, (int) value); } /** * Retrieve block position. * @return The current Z */ public int getZ() { return handle.getIntegers().read(2); } /** * Set block position. * @param value - new value. */ public void setZ(int value) { handle.getIntegers().write(2, value); } /** * Retrieve the face being hit. See {@link Packet0EPlayerDigging.BlockSide BlockSide}. * @return The current block side. */ public int getFace() { return handle.getIntegers().read(3).byteValue(); } /** * Set the face being hit. See {@link Packet0EPlayerDigging.BlockSide BlockSide}. * @param value - new value. */ public void setFace(int value) { handle.getIntegers().write(3, value); } }
gpl-3.0
BjerknesClimateDataCentre/QuinCe
WebApp/junit/junit/uk/ac/exeter/QuinCe/data/Dataset/MeasurementTest.java
5591
package junit.uk.ac.exeter.QuinCe.data.Dataset; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.flywaydb.test.annotation.FlywayTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import junit.uk.ac.exeter.QuinCe.TestBase.BaseTest; import uk.ac.exeter.QuinCe.data.Dataset.Measurement; import uk.ac.exeter.QuinCe.data.Dataset.MeasurementValue; import uk.ac.exeter.QuinCe.data.Dataset.QC.Flag; import uk.ac.exeter.QuinCe.data.Instrument.SensorDefinition.SensorType; import uk.ac.exeter.QuinCe.data.Instrument.SensorDefinition.SensorTypeNotFoundException; import uk.ac.exeter.QuinCe.web.system.ResourceManager; public class MeasurementTest extends BaseTest { private static final String POSITION_MESSAGE = "POSMESSAGE"; private static final String SENSOR_MESSAGE = "SENSORMESSAGE"; private static final String ADDED_POSITION_MESSAGE = Measurement.POSITION_QC_PREFIX + POSITION_MESSAGE; @BeforeEach public void init() { initResourceManager(); } /** * Get a {@link SensorType} object for Intake Temperature. Useful as a general * SensorType. * * @return The SensorType * @throws SensorTypeNotFoundException */ private SensorType intakeTemperature() throws SensorTypeNotFoundException { return ResourceManager.getInstance().getSensorsConfiguration() .getSensorType("Intake Temperature"); } /** * Create a measurement containing {@link MeasurementValue}s for position and * another sensor, each with the specified QC flags. * * @param positionFlag * The flag for the position value * @param sensorFlag * The flag for the other sensor value * @return The measurement * @throws SensorTypeNotFoundException */ private Measurement makePositionFlagMeasurement(Flag positionFlag, Flag sensorFlag) throws SensorTypeNotFoundException { Measurement result = new Measurement(1L, 1L, LocalDateTime.now(), "RunType"); if (null != positionFlag) { List<String> posMessage = new ArrayList<String>(1); posMessage.add(POSITION_MESSAGE); MeasurementValue longitude = new MeasurementValue(SensorType.LONGITUDE_ID, Arrays.asList(new Long[] { 1L }), null, 1, 0D, positionFlag, posMessage, null); MeasurementValue latitude = new MeasurementValue(SensorType.LATITUDE_ID, Arrays.asList(new Long[] { 2L }), null, 1, 0D, positionFlag, posMessage, null); result.setMeasurementValue(longitude); result.setMeasurementValue(latitude); } ArrayList<String> sensorMessage = new ArrayList<String>(1); sensorMessage.add(SENSOR_MESSAGE); MeasurementValue other = new MeasurementValue(intakeTemperature().getId(), Arrays.asList(new Long[] { 3L }), null, 1, 0D, sensorFlag, sensorMessage, null); result.setMeasurementValue(other); return result; } @FlywayTest @Test public void postprocessMeasurementValuesNoPositionTest() throws SensorTypeNotFoundException { Measurement measurement = makePositionFlagMeasurement(null, Flag.GOOD); measurement.postProcessMeasurementValues(); assertEquals(Flag.GOOD, measurement.getMeasurementValue(intakeTemperature()).getQcFlag()); } @FlywayTest @Test public void postprocessMeasurementValuesBadPosGoodSensorTest() throws SensorTypeNotFoundException { Measurement measurement = makePositionFlagMeasurement(Flag.BAD, Flag.GOOD); measurement.postProcessMeasurementValues(); assertEquals(Flag.BAD, measurement.getMeasurementValue(intakeTemperature()).getQcFlag()); String qcMessage = measurement.getMeasurementValue(intakeTemperature()) .getQcMessage(false); assertTrue(qcMessage.contains(ADDED_POSITION_MESSAGE)); } @FlywayTest @Test public void postprocessMeasurementValuesBadPosQuestionableSensorTest() throws SensorTypeNotFoundException { Measurement measurement = makePositionFlagMeasurement(Flag.BAD, Flag.QUESTIONABLE); // Before post-processing, the questionable sensor message should be present String preQcMessage = measurement.getMeasurementValue(intakeTemperature()) .getQcMessage(false); assertTrue(preQcMessage.contains(SENSOR_MESSAGE)); measurement.postProcessMeasurementValues(); assertEquals(Flag.BAD, measurement.getMeasurementValue(intakeTemperature()).getQcFlag()); String qcMessage = measurement.getMeasurementValue(intakeTemperature()) .getQcMessage(false); assertTrue(qcMessage.contains(ADDED_POSITION_MESSAGE)); // Now the sensor message should have gone - replaced by the position // message assertFalse(qcMessage.contains(SENSOR_MESSAGE)); } @FlywayTest @Test public void postprocessMeasurementValuesBadPosBadSensorTest() throws SensorTypeNotFoundException { Measurement measurement = makePositionFlagMeasurement(Flag.BAD, Flag.BAD); measurement.postProcessMeasurementValues(); assertEquals(Flag.BAD, measurement.getMeasurementValue(intakeTemperature()).getQcFlag()); String qcMessage = measurement.getMeasurementValue(intakeTemperature()) .getQcMessage(false); // Both sensor and position messages should be present assertTrue(qcMessage.contains(ADDED_POSITION_MESSAGE)); assertTrue(qcMessage.contains(SENSOR_MESSAGE)); } }
gpl-3.0
PuzzlesLab/PuzzlesCon
PuzzlesCon Bronze League/Bronze League I/B/2837374_kingkingyyk_B.java
595
import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main (String [] args) { Scanner sc=new Scanner(System.in); StringTokenizer st; int n=Integer.parseInt(sc.nextLine()); for (int gg=0;gg<n;gg++) { st=new StringTokenizer(sc.nextLine()); int sum=Integer.parseInt(st.nextToken()); int diff=Integer.parseInt(st.nextToken()); if (sum<diff || (sum+diff)%2!=0) { System.out.println("impossible"); } else { int x=(sum+diff)/2; int y=(sum-diff)/2; System.out.println(Math.max(x,y)+" "+Math.min(x,y)); } } } }
gpl-3.0
openbase/bco.bcozy
src/main/java/org/openbase/bco/bcozy/EmphasisControlLauncher.java
174
package org.openbase.bco.bcozy; public class EmphasisControlLauncher { public static void main(String[] args) { EmphasisControlPanePrototype.main(args); } }
gpl-3.0
WinXaito/zest-writer
src/main/java/com/zestedesavoir/zestwriter/utils/LocalDirectoryFactory.java
921
/* * 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 com.zestedesavoir.zestwriter.utils; import java.io.File; import java.io.IOException; /** * * @author fdambrine */ public class LocalDirectoryFactory { private LocalDirectorySaver baseSaver; public LocalDirectoryFactory(String baseDirectory){ baseSaver = new LocalDirectorySaver(baseDirectory); } public String getWorkspaceDir(){ return baseSaver.getBaseDirectory(); } public LocalDirectorySaver getOnlineSaver() { return new LocalDirectorySaver(baseSaver.getBaseDirectory() + File.separator + "online"); } public LocalDirectorySaver getOfflineSaver() { return new LocalDirectorySaver(baseSaver.getBaseDirectory() + File.separator + "offline"); } }
gpl-3.0
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/client/stream/MetadataPlayerDeath.java
631
package net.minecraft.client.stream; import net.minecraft.entity.EntityLivingBase; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class MetadataPlayerDeath extends Metadata { public MetadataPlayerDeath(EntityLivingBase p_i46066_1_, EntityLivingBase p_i46066_2_) { super("player_death"); if (p_i46066_1_ != null) { this.func_152808_a("player", p_i46066_1_.getName()); } if (p_i46066_2_ != null) { this.func_152808_a("killer", p_i46066_2_.getName()); } } }
gpl-3.0
studio-368/monsters
editor/src/main/java/edu/bsu/storygame/editor/model/SkillTrigger.java
1993
/* * Copyright 2016 Traveler's Notebook: Monster Tales project authors * * This file is part of monsters * * monsters is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * monsters is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with monsters. If not, see <http://www.gnu.org/licenses/>. */ package edu.bsu.storygame.editor.model; public class SkillTrigger { public String skill; public Conclusion conclusion; public static final String[] availableSkills = { null, "Athleticism", "Logic", "Magic", "Persuasion", "Stealth", "Weapon Use" }; public SkillTrigger(String skill, Conclusion conclusion) { this.skill = skill; this.conclusion = conclusion; } @Override public String toString() { if (skill == null) { return "No skill"; } return skill; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SkillTrigger that = (SkillTrigger) o; if (skill != null ? !skill.equals(that.skill) : that.skill != null) return false; return conclusion != null ? conclusion.equals(that.conclusion) : that.conclusion == null; } @Override public int hashCode() { int result = skill != null ? skill.hashCode() : 0; result = 31 * result + (conclusion != null ? conclusion.hashCode() : 0); return result; } }
gpl-3.0
PLRI/arden2bytecode
test/arden/tests/specification/operators/IsComparisonOperatorsTest.java
10522
package arden.tests.specification.operators; import org.junit.Test; import arden.tests.specification.testcompiler.ArdenVersion; import arden.tests.specification.testcompiler.CompatibilityRule.Compatibility; import arden.tests.specification.testcompiler.SpecificationTest; public class IsComparisonOperatorsTest extends SpecificationTest { @Test public void testWithinTo() throws Exception { assertEvaluatesTo("3 IS WITHIN 2 TO 5", "TRUE"); assertEvaluatesTo("1990-03-10T00:00:00 IS WITHIN 1990-03-05T00:00:00 TO 1990-03-15T00:00:00", "TRUE"); assertEvaluatesTo("3 DAYS WERE WITHIN 2 DAYS TO 5 MONTHS", "TRUE"); assertEvaluatesTo("\"ccc\" WAS WITHIN \"a\" TO \"d\"", "TRUE"); assertEvaluatesTo("(1,2) IS WITHIN (0,2) TO (3,4)", "(TRUE,TRUE)"); assertEvaluatesTo("(1,2) IS WITHIN 2 TO (3,4)", "(FALSE,TRUE)"); } @Test @Compatibility(min = ArdenVersion.V2_6) public void testWithinToTimeOfDay() throws Exception { assertEvaluatesTo("2000-06-06T13:00:00 IS WITHIN 12:30:00 TO 14:00:00", "TRUE"); assertEvaluatesTo("2000-06-06T13:00:00 IS WITHIN 13:30:00 TO 22:00:00", "FALSE"); assertEvaluatesTo("2000-06-06T01:00:00 IS WITHIN 22:00:00 TO 02:00:00", "TRUE"); } @Test @Compatibility(min = ArdenVersion.V2_6) public void testWithinToDayOfWeek() throws Exception { assertEvaluatesTo("WEDNESDAY IS WITHIN MONDAY TO FRIDAY", "TRUE"); assertEvaluatesTo("WEDNESDAY IS WITHIN FRIDAY TO SUNDAY", "FALSE"); assertEvaluatesTo("SUNDAY IS WITHIN SATURDAY TO MONDAY", "FALSE"); } @Test public void testWithin() throws Exception { assertEvaluatesTo("1990-03-08T00:00:00 WERE WITHIN 3 days PRECEDING 1990-03-10T00:00:00", "TRUE"); assertEvaluatesTo("1990-03-08T00:00:00 IS WITHIN 3 days FOLLOWING 1990-03-10T00:00:00", "FALSE"); assertEvaluatesTo("1990-03-08T00:00:00 IS WITHIN 3 days SURROUNDING 1990-03-10T00:00:00", "TRUE"); assertEvaluatesTo("1990-03-08T00:00:00 WAS WITHIN PAST 3 days", "FALSE"); assertEvaluatesTo("1990-03-08T11:11:11 IS WITHIN SAME DAY AS 1990-03-08T01:01:01", "TRUE"); } @Test @Compatibility(min = ArdenVersion.V2_6) public void testWithinTimeOfDay() throws Exception { assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 5 HOURS PRECEDING 17:00:00", "TRUE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 1 HOUR PRECEDING 17:00:00", "FALSE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 2 HOURS FOLLOWING 14:00:00", "TRUE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 30 MINUTES FOLLOWING 14:00:00", "FALSE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 2 HOURS SURROUNDING 16:00:00", "TRUE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 2 HOURS SURROUNDING 14:00:00", "TRUE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN 1 HOUR SURROUNDING 13:00:00", "FALSE"); assertEvaluatesTo("1990-03-10T15:00:00 IS WITHIN SAME DAY AS 15:00:00", "NULL"); assertEvaluatesTo("15:00:00 IS WITHIN SAME DAY AS 1990-03-10T15:00:00", "NULL"); assertEvaluatesTo("16:00:00 IS WITHIN PAST 5 DAYS", "NULL"); } @Test public void testBeforeAfter() throws Exception { assertEvaluatesTo("1990-03-08T00:00:00 IS BEFORE 1990-03-07T00:00:00", "FALSE"); assertEvaluatesTo("1990-03-08T00:00:00 IS AFTER 1990-03-07T00:00:00", "TRUE"); assertEvaluatesTo("1990-03-08T00:00:00 IS BEFORE 1990-03-08T00:00:01", "TRUE"); assertEvaluatesTo("1990-03-08T00:00:02 IS BEFORE 1990-03-08T00:00:01", "FALSE"); // not inclusive assertEvaluatesTo("1990-03-08T00:50:00 IS BEFORE 1990-03-08T00:50:00", "FALSE"); assertEvaluatesTo("1990-03-08T00:50:00 IS AFTER 1990-03-08T00:50:00", "FALSE"); } @Test @Compatibility(min = ArdenVersion.V2_6) public void testBeforeAfterTimeOfDay() throws Exception { assertEvaluatesTo("1990-03-08T05:00:00 IS AFTER 18:00:00", "FALSE"); assertEvaluatesTo("1990-03-08T05:00:00 IS BEFORE 18:00:00", "TRUE"); assertEvaluatesTo("1990-03-08T20:00:00 IS AFTER 18:00:00", "TRUE"); assertEvaluatesTo("1990-03-08T20:00:00 IS BEFORE 18:00:00", "FALSE"); // not inclusive assertEvaluatesTo("1990-03-08T18:00:00 IS BEFORE 18:00:00", "FALSE"); assertEvaluatesTo("1990-03-08T18:00:00 IS BEFORE 18:00:00", "FALSE"); } @Test public void testIsIn() throws Exception { assertEvaluatesTo("2 IS IN (3,2,6)", "TRUE"); assertEvaluatesTo("2 IS IN (4,5,6)", "FALSE"); assertEvaluatesTo("(3,4) IS IN (4,5,6)", "(FALSE,TRUE)"); assertEvaluatesTo("(1,2,3) IS IN (0,3)", "(FALSE,FALSE,TRUE)"); assertEvaluatesTo("NULL IS IN (1/0,2)", "TRUE"); assertEvaluatesTo("2 IS NOT IN (4,5,6)", "TRUE"); assertEvaluatesTo("2 IS IN (4,5,6)", "FALSE"); String data = createCodeBuilder() .addData("x := 5; TIME x := 1990-01-01T00:00:00;") .addData("y := 3; TIME y := 1990-01-02T00:00:00;") .addData("z := 2; TIME z := 1990-01-03T00:00:00;") .toString(); assertEvaluatesToWithData(data, "TIME FIRST ((x,y) IS IN (x,y,z))", "1990-01-01T00:00:00"); assertEvaluatesToWithData(data, "TIME FIRST ((5,y) IS IN (x,y,z))", "NULL"); } @Test @Compatibility(min = ArdenVersion.V2_9) public void testIsInFuzzy() throws Exception { String data = createCodeBuilder() .addData("middle_aged := FUZZY SET (15, truth value 0),(20, truth value 1),(60, truth value 1), (70, truth value 0);") .addData("cook_time := 5 MINUTES FUZZIFIED BY 1 MINUTE;") .toString(); assertEvaluatesToWithData(data, "40 IS IN middle_aged", "TRUE"); assertEvaluatesToWithData(data, "10 IN middle_aged", "FALSE"); assertEvaluatesToWithData(data, "(17.5 IS IN middle_aged) IS WITHIN TRUTH VALUE 0.49 TO TRUTH VALUE 0.51", "TRUE"); assertEvaluatesToWithData(data, "5 MINUTES IS IN cook_time", "TRUE"); assertEvaluatesToWithData(data, "(5.5 MINUTES IS IN cook_time) IS WITHIN TRUTH VALUE 0.49 TO TRUTH VALUE 0.51", "TRUE"); assertEvaluatesToWithData(data, "2 HOURS IS IN cook_time", "FALSE"); assertEvaluatesToWithData(data, "(4 IS IN 5 FUZZIFIED BY 2) IS WITHIN TRUTH VALUE 0.49 TO TRUTH VALUE 0.51", "TRUE"); } @Test @Compatibility(min = ArdenVersion.V2_1) public void testIn() throws Exception { assertEvaluatesTo("2 IN (3,2,6)", "TRUE"); assertEvaluatesTo("2 IN (4,5,6)", "FALSE"); assertEvaluatesTo("2 NOT IN (4,5,6)", "TRUE"); assertEvaluatesTo("NULL IN (1/0,2)", "TRUE"); } @Test public void testPresentNull() throws Exception { assertEvaluatesTo("3 IS PRESENT", "TRUE"); assertEvaluatesTo("NULL IS PRESENT", "FALSE"); assertEvaluatesTo("(3,NULL) IS NOT NULL", "(TRUE,FALSE)"); assertEvaluatesTo("(3,NULL) IS NULL", "(FALSE,TRUE)"); } @Test public void testType() throws Exception { assertEvaluatesTo("FALSE IS BOOLEAN", "TRUE"); assertEvaluatesTo("FALSE IS NOT BOOLEAN", "FALSE"); assertEvaluatesTo("NULL IS BOOLEAN", "FALSE"); assertEvaluatesTo("(NULL, FALSE, \"asdf\") IS BOOLEAN", "(FALSE,TRUE,FALSE)"); assertEvaluatesTo("3 IS NUMBER", "TRUE"); assertEvaluatesTo("\"abc\" IS STRING", "TRUE"); assertEvaluatesTo("1991-03-12T00:00:00 IS TIME", "TRUE"); assertEvaluatesTo("(3 DAYS) IS DURATION", "TRUE"); assertEvaluatesTo("(1, 2, 3) IS LIST", "TRUE"); assertEvaluatesTo("(,3) IS LIST", "TRUE"); } @Test @Compatibility(min = ArdenVersion.V2_9) public void testTypeTruthValue() throws Exception { assertEvaluatesTo("TRUTH VALUE 1 IS BOOLEAN", "TRUE"); assertEvaluatesTo("TRUTH VALUE 0 IS BOOLEAN", "TRUE"); assertEvaluatesTo("TRUTH VALUE 0.5 IS BOOLEAN", "FALSE"); assertEvaluatesTo("TRUTH VALUE 0.5 IS TRUTH VALUE", "TRUE"); assertEvaluatesTo("TRUTH VALUE 0.5 IS NOT TRUTH VALUE", "FALSE"); assertEvaluatesTo("3 IS TRUTH VALUE", "FALSE"); assertEvaluatesTo("TRUTH VALUE 1 IS TRUTH VALUE", "TRUE"); assertEvaluatesTo("TRUE IS TRUTH VALUE", "TRUE"); } @Test @Compatibility(min = ArdenVersion.V2_6) public void testTypeTimeOfDay() throws Exception { assertEvaluatesTo("20:00:00 IS TIME", "FALSE"); assertEvaluatesTo("20:00:00 IS TIME OF DAY", "TRUE"); assertEvaluatesTo("10:30:12.123 IS TIME OF DAY", "TRUE"); assertEvaluatesTo("1990-01-01T20:00:00 IS TIME OF DAY", "FALSE"); assertEvaluatesTo("NULL IS TIME OF DAY", "FALSE"); } @Test @Compatibility(min = ArdenVersion.V2_9) public void testTypeLinguisticVariable() throws Exception { String data = createCodeBuilder() .addData("RangeOfAge := LINGUISTIC VARIABLE [young, middleAge, old];") .addData("Age := new RangeOfAge;") .addData("Age.young := FUZZY SET (0 YEARS, TRUE), (25 YEARS, TRUE),(35 YEARS, FALSE);") .addData("Age.middleAge := FUZZY SET (25 YEARS, FALSE), (35 YEARS, TRUE), (55 YEARS, TRUE), (65 YEARS, FALSE);") .addData("Age.old := FUZZY SET (55 YEARS, FALSE), (65 YEARS, TRUE);") .toString(); assertEvaluatesToWithData(data, "RangeOfAge IS LINGUISTIC VARIABLE", "TRUE"); assertEvaluatesTo("3 IS LINGUISTIC VARIABLE", "FALSE"); assertEvaluatesTo("3 IS NOT LINGUISTIC VARIABLE", "TRUE"); } @Test @Compatibility(min = ArdenVersion.V2_5) public void testTypeObject() throws Exception { String pixelObject = createCodeBuilder() .addData("Pixel := OBJECT [x, y];") .addData("Image := OBJECT [pixel_list];") .addData("p := NEW Pixel;") .toString(); assertEvaluatesToWithData(pixelObject, "p IS OBJECT", "TRUE"); assertEvaluatesToWithData(pixelObject, "p IS Pixel", "TRUE"); assertEvaluatesToWithData(pixelObject, "p IS Image", "FALSE"); assertEvaluatesToWithData(pixelObject, "3 IS Image", "FALSE"); assertEvaluatesTo("3 IS OBJECT", "FALSE"); } @Test @Compatibility(min = ArdenVersion.V2_9) public void testTypeFuzzy() throws Exception { assertEvaluatesTo("3 IS FUZZY", "FALSE"); assertEvaluatesTo("3 IS NOT FUZZY", "TRUE"); assertEvaluatesTo("TRUTH VALUE 0.5 IS FUZZY", "FALSE"); assertEvaluatesTo("(FUZZY SET (0, TRUTH VALUE 0), (1, TRUTH VALUE 1)) IS FUZZY", "TRUE"); assertEvaluatesTo("(2000-01-01T00:00:00 FUZZIFIED BY 2 days) IS FUZZY", "TRUE"); assertEvaluatesTo("(1 WEEK FUZZIFIED BY 2 days) IS FUZZY", "TRUE"); assertEvaluatesTo("(1 WEEK FUZZIFIED BY 2 days) IS NOT FUZZY", "FALSE"); } @Test @Compatibility(min = ArdenVersion.V2_9) public void testTypeCrisp() throws Exception { assertEvaluatesTo("3 IS CRISP", "TRUE"); assertEvaluatesTo("3 IS NOT CRISP", "FALSE"); assertEvaluatesTo("TRUTH VALUE 0.5 IS CRISP", "TRUE"); assertEvaluatesTo("(FUZZY SET (0, TRUTH VALUE 0), (1, TRUTH VALUE 1)) IS CRISP", "FALSE"); assertEvaluatesTo("(2000-01-01T00:00:00 FUZZIFIED BY 2 days) IS CRISP", "FALSE"); assertEvaluatesTo("(1 WEEK FUZZIFIED BY 2 days) IS CRISP", "FALSE"); assertEvaluatesTo("(1 WEEK FUZZIFIED BY 2 days) IS NOT CRISP", "TRUE"); } }
gpl-3.0
shymmq/librus-client
app/src/main/java/pl/librus/client/ui/NavigationOps.java
619
package pl.librus.client.ui; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import com.google.common.base.Optional; import pl.librus.client.domain.LuckyNumber; import pl.librus.client.domain.Me; import pl.librus.client.presentation.FragmentPresenter; /** * Created by robwys on 09/04/2017. */ public interface NavigationOps { void setupDrawer(Me me, Optional<LuckyNumber> luckyNumber); Fragment getCurrentFragmentId(); @Nullable Integer getInitialFragmentTitle(); void displayFragment(FragmentPresenter fragmentPresenter); void setupToolbar(); }
gpl-3.0
rodrigo-morais/registrolivre
src/main/java/br/com/registrolivre/configurations/DataSourceConfiguration.java
1072
package br.com.registrolivre.configurations; import br.com.registrolivre.utils.DatabaseEnvironmentVariables; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.net.URI; import java.net.URISyntaxException; @Configuration() public class DataSourceConfiguration { @Bean public BasicDataSource dataSource() throws URISyntaxException { URI databaseUri = new URI(System.getenv(DatabaseEnvironmentVariables.URL)); String userName = databaseUri.getUserInfo().split(":")[0]; String password = databaseUri.getUserInfo().split(":")[1]; String databaseUrl = String.format("jdbc:postgresql://%s:%s%s", databaseUri.getHost(), databaseUri.getPort(), databaseUri.getPath()); BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setUrl(databaseUrl); basicDataSource.setUsername(userName); basicDataSource.setPassword(password); return basicDataSource; } }
gpl-3.0
jesselix/zz-algorithms
algorithms-primer/src/main/java/li/jesse/datastructure/list/linkedlist/DoublyLinkedList.java
482
package li.jesse.datastructure.list.linkedlist; public class DoublyLinkedList { // head node private DoublyLinkedListNode headNode; // position of the node private int position = 0; // ******************************************* constructors ******************************************* public DoublyLinkedList() { this.headNode = null; } public DoublyLinkedList(DoublyLinkedListNode headNode) { this.headNode = headNode; } }
gpl-3.0
fanguangdong/TSOA
src/cn/ts987/oa/service/RoleService.java
1134
package cn.ts987.oa.service; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.ts987.oa.domain.Role; @Service public class RoleService extends BaseService{ @Transactional public List<Role> list() { List<Role> roleList = roleDao.findAll(); return roleList; } @Transactional public void add(Role entity) { roleDao.save(entity); } @Transactional public void update(Role entity) { roleDao.update(entity); } @Transactional public void delete(long id) { roleDao.delete(id); } @Transactional public Role findById(long id) { return roleDao.findById(id); } @Transactional public List<Role> findAll() { return roleDao.findAll(); } @Transactional public List<Role> findByIds(Long[] roleIds) { List<Long> roles = new ArrayList<Long>(); Collections.addAll(roles, roleIds); if(roles.size() == 0) { return Collections.emptyList(); } return roleDao.findByIds(roles); } }
gpl-3.0
muxiaobai/OOAD
task3/SSH/src/main/java/ooad/trad/Constant.java
688
package ooad.trad; public class Constant { /** * 男性 */ public static final int GENDER_MALE = 1; /** * 女性 */ public static final int GENDER_FEMALE = 2; /** * 默认每页显示多少条记录 */ public static final int DEFAULT_PAGE_SIZE = 15; /** * 默认显示第几页记录 */ public static final int DEFAULT_PAGE_NUM = 1; /** * 默认学生性别 */ public static final int DEFAULT_GENDER = 0; /** * 默认倒叙输出 */ public static final String DEFAULT_ORDERBY="DESC"; /** * 倒叙输出 */ public static final String ORDER_BY_DESC="DESC"; /** * 正序输出 */ public static final String ORDER_BY_ESC="ASC"; }
gpl-3.0
Mahdi-Rom/android_packages_apps_KernelTweaker
src/com/dsht/kerneltweaker/fragments/CpuSchedulerPreferenceFragment.java
6787
package com.dsht.kerneltweaker.fragments; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeoutException; import com.dsht.kerneltweaker.CustomPreference; import com.dsht.kerneltweaker.Helpers; import com.dsht.kerneltweaker.ListViewMultiChoiceModeListener; import com.dsht.kerneltweaker.MainActivity; import com.dsht.kerneltweaker.R; import com.dsht.kerneltweaker.database.DataItem; import com.dsht.kerneltweaker.database.DatabaseHandler; import com.dsht.kernetweaker.cmdprocessor.CMDProcessor; import com.dsht.settings.SettingsFragment; import com.stericson.RootTools.RootTools; import com.stericson.RootTools.exceptions.RootDeniedException; import com.stericson.RootTools.execution.CommandCapture; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.text.InputType; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager.LayoutParams; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; public class CpuSchedulerPreferenceFragment extends PreferenceFragment { private static PreferenceCategory mCategory; private static Context mContext; private PreferenceScreen mRoot; private static String category = "scheduler"; private static DatabaseHandler db = MainActivity.db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_screen_scheduler); mRoot = (PreferenceScreen) findPreference("key_root"); mCategory = (PreferenceCategory) findPreference("key_sched_category"); mContext = getActivity(); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.layout_list, container,false); File f = new File("/sys/block/mmcblk0/queue/iosched"); String curSched = Helpers.getCurrentScheduler(); File[] files = f.listFiles(); if(files.length != 0) { MainActivity.menu.setEnabled(false); addPreferences(); mCategory.setTitle(curSched + " Tweakable values"); }else { Preference pref = new Preference(mContext); pref.setTitle("No tweakable values"); pref.setSummary(curSched + " Doesn\'t have tweakable values"); mCategory.addPreference(pref); } return v; } public static void addPreferences() { class LongOperation extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { if(mCategory.getPreferenceCount() != 0) { mCategory.removeAll(); } File f = new File("/sys/block/mmcblk0/queue/iosched"); File[] files = f.listFiles(); for(File file : files) { String fileName = file.getName(); String filePath = file.getAbsolutePath(); final String fileContent = Helpers.getFileContent(file); CustomPreference pref = new CustomPreference(mContext, true, category); pref.setTitle(fileName); String color = "#ff0099cc"; if(MainActivity.mPrefs.getBoolean(SettingsFragment.KEY_ENABLE_GLOBAL, false)) { int col = MainActivity.mPrefs.getInt(SettingsFragment.KEY_GLOBAL_COLOR, Color.parseColor("#ff0099cc")); color = "#"+Integer.toHexString(col); pref.setTitleColor(color); }else { pref.setTitleColor(color); } pref.setSummary(fileContent); pref.setKey(filePath); mCategory.addPreference(pref); pref.setOnPreferenceClickListener(new OnPreferenceClickListener(){ @Override public boolean onPreferenceClick(final Preference p) { // TODO Auto-generated method stub AlertDialog.Builder builder = new AlertDialog.Builder(mContext); LinearLayout ll = new LinearLayout(mContext); ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); final EditText et = new EditText(mContext); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(40, 40, 40, 40); params.gravity = Gravity.CENTER; String val = p.getSummary().toString(); et.setLayoutParams(params); et.setRawInputType(InputType.TYPE_CLASS_NUMBER); et.setGravity(Gravity.CENTER_HORIZONTAL); et.setText(val); ll.addView(et); builder.setView(ll); builder.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub String value = et.getText().toString(); p.setSummary(value); //Log.d("TEST", "echo "+value+" > "+ p.getKey()); CMDProcessor.runSuCommand("echo "+value+" > "+p.getKey()); updateListDb(p, value, ((CustomPreference) p).isBootChecked()); } } ); AlertDialog dialog = builder.create(); dialog.show(); dialog.getWindow().getAttributes().windowAnimations = R.style.dialog_animation; Window window = dialog.getWindow(); window.setLayout(600, LayoutParams.WRAP_CONTENT); return true; } }); } return "Executed"; } @Override protected void onPostExecute(String result) { } @Override protected void onPreExecute() {} } new LongOperation().execute(); } private static void updateListDb(final Preference p, final String value, final boolean isChecked) { class LongOperation extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { if(isChecked) { List<DataItem> items = db.getAllItems(); for(DataItem item : items) { if(item.getName().equals("'"+p.getKey()+"'")) { db.deleteItemByName("'"+p.getKey()+"'"); } } db.addItem(new DataItem("'"+p.getKey()+"'", value, p.getTitle().toString(), category)); } else { if(db.getContactsCount() != 0) { db.deleteItemByName("'"+p.getKey()+"'"); } } return "Executed"; } @Override protected void onPostExecute(String result) { } } new LongOperation().execute(); } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-cloud/spring-cloud-task/springcloudtasksink/src/main/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplication.java
474
package com.baeldung.SpringCloudTaskFinal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.task.launcher.annotation.EnableTaskLauncher; @SpringBootApplication @EnableTaskLauncher public class SpringCloudTaskSinkApplication { public static void main(String[] args) { SpringApplication.run( SpringCloudTaskSinkApplication.class, args); } }
gpl-3.0
izstas/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/importers/ScriptImporter.java
3686
/* * Copyright (C) 2010-2015 JPEXS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package com.jpexs.decompiler.flash.importers; import com.jpexs.decompiler.flash.action.parser.ActionParseException; import com.jpexs.decompiler.flash.tags.base.ASMSource; import com.jpexs.decompiler.graph.CompilationException; import com.jpexs.helpers.Helper; import com.jpexs.helpers.Path; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author JPEXS */ public class ScriptImporter { private static final Logger logger = Logger.getLogger(ScriptImporter.class.getName()); public void importScripts(String scriptsFolder, Map<String, ASMSource> asms) { if (!scriptsFolder.endsWith(File.separator)) { scriptsFolder += File.separator; } Map<String, List<String>> existingNamesMap = new HashMap<>(); for (String key : asms.keySet()) { ASMSource asm = asms.get(key); String currentOutDir = scriptsFolder + key + File.separator; currentOutDir = new File(currentOutDir).getParentFile().toString() + File.separator; List<String> existingNames = existingNamesMap.get(currentOutDir); if (existingNames == null) { existingNames = new ArrayList<>(); existingNamesMap.put(currentOutDir, existingNames); } String name = Helper.makeFileName(asm.getExportFileName()); int i = 1; String baseName = name; while (existingNames.contains(name)) { i++; name = baseName + "_" + i; } existingNames.add(name); String fileName = Path.combine(currentOutDir, name) + ".as"; if (new File(fileName).exists()) { String as = Helper.readTextFile(fileName); com.jpexs.decompiler.flash.action.parser.script.ActionScriptParser par = new com.jpexs.decompiler.flash.action.parser.script.ActionScriptParser(asm.getSwf().version); try { asm.setActions(par.actionsFromString(as)); } catch (ActionParseException ex) { logger.log(Level.SEVERE, "%error% on line %line%, file: %file%".replace("%error%", ex.text).replace("%line%", Long.toString(ex.line)).replace("%file%", fileName), ex); } catch (CompilationException ex) { logger.log(Level.SEVERE, "%error% on line %line%, file: %file%".replace("%error%", ex.text).replace("%line%", Long.toString(ex.line)).replace("%file%", fileName), ex); } catch (IOException ex) { logger.log(Level.SEVERE, "error during script import, file: %file%".replace("%file%", fileName), ex); } asm.setModified(); } } } }
gpl-3.0
abocz/darcy-ui
src/main/java/com/redhat/darcy/ui/internal/IdOfHandler.java
2585
/* Copyright 2014 Red Hat, Inc. and/or its affiliates. This file is part of darcy-web. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.redhat.darcy.ui.internal; import com.redhat.darcy.ui.By; import com.redhat.darcy.ui.DarcyException; import com.redhat.darcy.ui.api.Context; import com.redhat.darcy.ui.api.Locator; import com.redhat.darcy.ui.api.elements.Findable; import com.redhat.darcy.ui.api.elements.HasAttributes; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Optional; public class IdOfHandler implements InvocationHandler { private final Context context; private final Class type; private final Findable original; private Findable usingId; public IdOfHandler(Locator locator, Class type, Context context) { this.context = context; this.type = type; original = locator.find(type, context); if (!(original instanceof HasAttributes)) { throw new DarcyException("Cannot lookup an id for a Findable if it does not implement " + "HasAttributes. Findable was, " + original); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (usingId == null && original.isPresent()) { Optional<String> id = getId((HasAttributes) original); if (id.isPresent()) { usingId = By.id(id.get()).find(type, context); } } if ("getWrappedElement".equals(method.getName())) { return findable(); } return method.invoke(findable(), args); } private Optional<String> getId(HasAttributes hasAttributes) { String id = hasAttributes.getAttribute("id"); if (id == null || id.trim().isEmpty()) { return Optional.empty(); } return Optional.of(id); } private Findable findable() { return (usingId == null) ? original : usingId; } }
gpl-3.0
raginggoblin/ragingphotosdesktop
src/main/java/raging/goblin/ragingphotosdesktop/ui/ShownImages.java
1296
package raging.goblin.ragingphotosdesktop.ui; import java.util.ArrayList; import java.util.List; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import raging.goblin.ragingphotosdesktop.data.Image; @NoArgsConstructor(access = AccessLevel.PRIVATE) @Getter public final class ShownImages { private static ShownImages instance; private List<Image> images = new ArrayList<>(); private int cursor; public static ShownImages getInstance() { if (instance == null) { instance = new ShownImages(); } return instance; } public synchronized void setImages(List<Image> images) { this.images = images; } public synchronized void setCursorToImage(Image image) { cursor = ShownImages.getInstance().getImages().indexOf(image); } public Image getImageAtCursor() { if (cursor >= 0 && cursor < ShownImages.getInstance().getImages().size()) { return images.get(cursor); } return null; } public synchronized void moveCursorForwards() { cursor++; if (cursor >= images.size()) { cursor = images.size() - 1; } } public synchronized void moveCursorBackwards() { cursor--; if (cursor < 0) { cursor = 0; } } }
gpl-3.0
AnodeCathode/ForestryMC
src/main/java/forestry/core/multiblock/CoordTriplet.java
2442
package forestry.core.multiblock; import javax.annotation.Nonnull; import net.minecraft.world.ChunkCoordIntPair; import net.minecraftforge.common.util.ForgeDirection; /* * Simple wrapper class for XYZ coordinates. */ public class CoordTriplet implements Comparable { public int x, y, z; public CoordTriplet(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int getChunkX() { return x >> 4; } public int getChunkZ() { return z >> 4; } public long getChunkXZHash() { return ChunkCoordIntPair.chunkXZ2Int(x >> 4, z >> 4); } @Override public boolean equals(Object other) { if (other == null) { return false; } else if (other instanceof CoordTriplet) { CoordTriplet otherTriplet = (CoordTriplet) other; return this.x == otherTriplet.x && this.y == otherTriplet.y && this.z == otherTriplet.z; } else { return false; } } public void translate(ForgeDirection dir) { this.x += dir.offsetX; this.y += dir.offsetY; this.z += dir.offsetZ; } public boolean equals(int x, int y, int z) { return this.x == x && this.y == y && this.z == z; } // Suggested implementation from NetBeans 7.1 public int hashCode() { int hash = 7; hash = 71 * hash + this.x; hash = 71 * hash + this.y; hash = 71 * hash + this.z; return hash; } public CoordTriplet copy() { return new CoordTriplet(x, y, z); } public void copy(CoordTriplet other) { this.x = other.x; this.y = other.y; this.z = other.z; } ///// IComparable @Override public int compareTo(@Nonnull Object o) { if (o instanceof CoordTriplet) { CoordTriplet other = (CoordTriplet) o; if (this.x < other.x) { return -1; } else if (this.x > other.x) { return 1; } else if (this.y < other.y) { return -1; } else if (this.y > other.y) { return 1; } else if (this.z < other.z) { return -1; } else if (this.z > other.z) { return 1; } else { return 0; } } return 0; } @Override public String toString() { return String.format("(%d, %d, %d)", this.x, this.y, this.z); } public int compareTo(int xCoord, int yCoord, int zCoord) { if (this.x < xCoord) { return -1; } else if (this.x > xCoord) { return 1; } else if (this.y < yCoord) { return -1; } else if (this.y > yCoord) { return 1; } else if (this.z < zCoord) { return -1; } else if (this.z > zCoord) { return 1; } else { return 0; } } }
gpl-3.0
danielyc/test-1.9.4
build/tmp/recompileMc/sources/net/minecraftforge/client/settings/KeyModifier.java
3736
package net.minecraftforge.client.settings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import org.lwjgl.input.Keyboard; public enum KeyModifier { CONTROL { @Override public boolean matches(int keyCode) { if (Minecraft.IS_RUNNING_ON_MAC) { return keyCode == Keyboard.KEY_LMETA || keyCode == Keyboard.KEY_RMETA; } else { return keyCode == Keyboard.KEY_LCONTROL || keyCode == Keyboard.KEY_RCONTROL; } } @Override public boolean isActive() { return GuiScreen.isCtrlKeyDown(); } @Override public String getLocalizedComboName(int keyCode) { String keyName = GameSettings.getKeyDisplayString(keyCode); String localizationFormatKey = Minecraft.IS_RUNNING_ON_MAC ? "forge.controlsgui.control.mac" : "forge.controlsgui.control"; return I18n.format(localizationFormatKey, keyName); } }, SHIFT { @Override public boolean matches(int keyCode) { return keyCode == Keyboard.KEY_LSHIFT || keyCode == Keyboard.KEY_RSHIFT; } @Override public boolean isActive() { return GuiScreen.isShiftKeyDown(); } @Override public String getLocalizedComboName(int keyCode) { String keyName = GameSettings.getKeyDisplayString(keyCode); return I18n.format("forge.controlsgui.shift", keyName); } }, ALT { @Override public boolean matches(int keyCode) { return keyCode == Keyboard.KEY_LMENU || keyCode == Keyboard.KEY_RMENU; } @Override public boolean isActive() { return GuiScreen.isAltKeyDown(); } @Override public String getLocalizedComboName(int keyCode) { String keyName = GameSettings.getKeyDisplayString(keyCode); return I18n.format("forge.controlsgui.alt", keyName); } }, NONE { @Override public boolean matches(int keyCode) { return false; } @Override public boolean isActive() { return true; } @Override public String getLocalizedComboName(int keyCode) { return GameSettings.getKeyDisplayString(keyCode); } }; public static final KeyModifier[] MODIFIER_VALUES = {SHIFT, CONTROL, ALT}; public static KeyModifier getActiveModifier() { for (KeyModifier keyModifier : MODIFIER_VALUES) { if (keyModifier.isActive()) { return keyModifier; } } return NONE; } public static boolean isKeyCodeModifier(int keyCode) { for (KeyModifier keyModifier : MODIFIER_VALUES) { if (keyModifier.matches(keyCode)) { return true; } } return false; } public static KeyModifier valueFromString(String stringValue) { try { return valueOf(stringValue); } catch (NullPointerException ignored) { return NONE; } catch (IllegalArgumentException ignored) { return NONE; } } public abstract boolean matches(int keyCode); public abstract boolean isActive(); public abstract String getLocalizedComboName(int keyCode); }
gpl-3.0
obiba/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/ui/celltable/BookmarksCell.java
3358
/* * Copyright (c) 2021 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.opal.web.gwt.app.client.ui.celltable; import java.util.ArrayList; import java.util.List; import org.obiba.opal.web.gwt.app.client.js.JsArrays; import org.obiba.opal.web.gwt.app.client.support.BookmarkHelper; import org.obiba.opal.web.model.client.opal.BookmarkDto; import org.obiba.opal.web.model.client.opal.LinkDto; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.CompositeCell; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.cell.client.HasCell; import com.google.gwt.cell.client.TextCell; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; public class BookmarksCell extends AbstractCell<BookmarkDto> { private CompositeCell<BookmarkDto> bookmarkCells; private final PlaceManager placeManager; public BookmarksCell(PlaceManager placeManager) { this.placeManager = placeManager; } @Override public void render(Context context, BookmarkDto bookmarkDto, SafeHtmlBuilder sb) { bookmarkCells = createBookmarks(bookmarkDto); bookmarkCells.render(context, bookmarkDto, sb); } private CompositeCell<BookmarkDto> createBookmarks(BookmarkDto bookmarkDto) { List<LinkDto> linksDto = JsArrays.toList(bookmarkDto.getLinksArray()); List<HasCell<BookmarkDto, ?>> hasCells = new ArrayList<HasCell<BookmarkDto, ?>>(); int upper = linksDto.size() - 1; int count = 0; for(LinkDto linkDto : linksDto) { hasCells.add(new Bookmark(linkDto)); if (count++ < upper) hasCells.add(new Separator()); } return new CompositeCell<BookmarkDto>(hasCells); } private class Bookmark implements HasCell<BookmarkDto, String> { private final PlaceRequestCell placeCell; private final LinkDto link; public Bookmark(LinkDto linkDto) { link = linkDto; placeCell = createPlaceCell(); } @Override public Cell<String> getCell() { return placeCell; } @Override public FieldUpdater<BookmarkDto, String> getFieldUpdater() { return null; } @Override public String getValue(BookmarkDto bookmarkDto) { return link.getLink(); } private PlaceRequestCell<String> createPlaceCell() { return new PlaceRequestCell<String>(placeManager) { @Override public PlaceRequest getPlaceRequest(String value) { return BookmarkHelper.createPlaceRequest(link); } }; } } private class Separator implements HasCell<BookmarkDto, String> { private final TextCell separatorCell; public Separator() { separatorCell = new TextCell(); } @Override public Cell<String> getCell() { return separatorCell; } @Override public FieldUpdater<BookmarkDto, String> getFieldUpdater() { return null; } @Override public String getValue(BookmarkDto bookmarkDto) { return "/"; } } }
gpl-3.0
E3V3A/snoopsnitch
SnoopSnitch/src/de/srlabs/snoopsnitch/EnableAutoUploadModeActivity.java
3018
package de.srlabs.snoopsnitch; import java.util.Vector; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import de.srlabs.snoopsnitch.analysis.Event; import de.srlabs.snoopsnitch.analysis.ImsiCatcher; import de.srlabs.snoopsnitch.qdmon.MsdSQLiteOpenHelper; import de.srlabs.snoopsnitch.upload.FileState; import de.srlabs.snoopsnitch.util.MsdDatabaseManager; import de.srlabs.snoopsnitch.util.MsdDialog; public class EnableAutoUploadModeActivity extends BaseActivity { public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; private int notificationId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MsdDatabaseManager.initializeInstance(new MsdSQLiteOpenHelper(EnableAutoUploadModeActivity.this)); Bundle extras = getIntent().getExtras(); notificationId = extras.getInt(NOTIFICATION_ID); String msg = getString(R.string.notification_enable_auto_upload_mode_confirm); MsdDialog.makeConfirmationDialog(this, msg, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { enableAutoUploadMode(); uploadAllUploadableEvents(); cancelNotification(); finish(); } }, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // Don't delete notification when pressing the back button finish(); } }, "Yes", "No", true).show(); } private void enableAutoUploadMode(){ SharedPreferences sharedPrefs = this.getSharedPreferences("de.srlabs.snoopsnitch_preferences", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);; Editor editor = sharedPrefs.edit(); editor.putBoolean("settings_auto_upload_mode", true); editor.commit(); } private void uploadAllUploadableEvents(){ Vector<Event> events = getMsdServiceHelperCreator().getMsdServiceHelper().getData().getEvent(0,System.currentTimeMillis()); for(Event event:events){ if(event.getUploadState() == FileState.STATE_AVAILABLE) try{ event.upload(); } catch(Exception e){} } Vector<ImsiCatcher> imsiCatchers = getMsdServiceHelperCreator().getMsdServiceHelper().getData().getImsiCatchers(0,System.currentTimeMillis()); for(ImsiCatcher imsi:imsiCatchers){ if(imsi.getUploadState() == FileState.STATE_AVAILABLE) try { imsi.upload(); } catch (Exception e){} } getMsdServiceHelperCreator().getMsdServiceHelper().triggerUploading(); } private void cancelNotification(){ NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.cancel(notificationId); } }
gpl-3.0
automenta/adams-core
src/main/java/adams/core/VariablesInspectionHandler.java
1319
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * VariablesInspectionHandler.java * Copyright (C) 2014 University of Waikato, Hamilton, New Zealand */ package adams.core; import java.io.Serializable; /** * Interface for classes that can restrict the inspection of certain classes. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see VariablesFinder */ public interface VariablesInspectionHandler extends Serializable { /** * Checks whether the class' options can be inspected. * * @param cls the class to check * @return true if it can be inspected, false otherwise */ public boolean canInspectOptions(Class cls); }
gpl-3.0
nishanttotla/predator
cpachecker/src/org/sosy_lab/cpachecker/cpa/smgfork/objects/SMGAbstractObject.java
1063
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.smgfork.objects; public interface SMGAbstractObject { public boolean isAbstract(); public boolean matchGenericShape(SMGAbstractObject pOther); public boolean matchSpecificShape(SMGAbstractObject pOther); }
gpl-3.0
Deonyi/Transport-Tycoon
tt_test/BasicTileMapper2.java
3815
import java.awt.*; import java.applet.*; /** * BasicTileMapper2.java<p> * Draws a simple tile based image on the screen * @author Eric R. Northam (enorth1@gl.umbc.edu) * @version 1.0 28 March 1999 */ public class BasicTileMapper2 extends Applet { Image screenImage; // Image used for double buffering and its respective Graphics screenGC; // graphics context static final int SW = 400; static final int SH = 400; Image tileImage; // Use to store the image for the tiles static final int NUMTILES = 6; // The number of tiles int tileWidth; int tileImageHeight; int tileHeight; Tile[] tiles; // An array to hold all of the tiles static final byte[][] BGMAP = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 2, 0, 0, 0, 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 1, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 1}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1}, {1, 1, 5, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1, 2, 0, 0, 0, 0, 3, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1}, {1, 1, 1, 5, 0, 0, 0, 0, 4, 1, 1, 1, 1, 5, 0, 0, 0, 4, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; static final int BGW = 20; static final int BGH = 16; int numXtiles; int numYtiles; int mapX = 0; int mapY = 0; /** * Loads an image, splits it into tiles, and then displays each of the tiles * diagonally. * note: Netscape does not properly load the applet if calls to getImage() are * in the init() method, so I decided to put them in the start() method */ public void start() { tileImage = getImage(getDocumentBase(), "grass.png"); // Wait for the image to load MediaTracker tracker = new MediaTracker(this); tracker.addImage(tileImage, 0); try { tracker.waitForID(0); } catch (InterruptedException e) {} // Get tile dimensions tileImageHeight = tileImage.getHeight(this); tileWidth = tileImage.getWidth(this); tileHeight = tileImageHeight/NUMTILES; // Create an offsreen image for double buffering screenImage = createImage(SW, SH); screenGC = screenImage.getGraphics(); // Break image into tiles. prepareTiles(); // Draw the upper left portion of the map numXtiles = SW/tileWidth; numYtiles = SH/tileHeight; drawMap(); } /** * Break the tile image into tiles */ public void prepareTiles() { tiles = new Tile[NUMTILES]; // Assume the tile images are arranged vertically for(int i = 0; i < NUMTILES; i++) tiles[i] = new Tile(tileImage, tileWidth, tileHeight, i); } /** * Draw a portion of the map */ public void drawMap() { int curX = 0; int curY = 0; for(int i = 0; i <= numYtiles; i++){ for(int j = 0; j <= numXtiles; j++){ tiles[BGMAP[i][j]].paint(screenGC, curX, curY); curX += tileWidth; } curY += tileHeight; curX = 0; } } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.drawImage(screenImage, 0, 0, null); } public void destroy() { screenGC.dispose(); } }
gpl-3.0
lookwhatlook/WeiboWeiBaTong
src/org/zarroboogs/weibo/adapter/MentionsTimeLinePagerAdapter.java
2717
package org.zarroboogs.weibo.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.util.SparseArray; import org.zarroboogs.weibo.R; import org.zarroboogs.weibo.fragment.MentionsCommentTimeLineFragment; import org.zarroboogs.weibo.fragment.MentionsTimeLineFragment; import org.zarroboogs.weibo.fragment.MentionsWeiboTimeLineFragment; import org.zarroboogs.weibo.support.lib.AppFragmentPagerAdapter; public class MentionsTimeLinePagerAdapter extends AppFragmentPagerAdapter { private SparseArray<Fragment> fragmentList; public MentionsTimeLinePagerAdapter(MentionsTimeLineFragment fragment, ViewPager viewPager, FragmentManager fm, SparseArray<Fragment> fragmentList) { super(fm); this.fragmentList = fragmentList; fragmentList.append(MentionsTimeLineFragment.MENTIONS_WEIBO_CHILD_POSITION, fragment.getMentionsWeiboTimeLineFragment()); fragmentList.append(MentionsTimeLineFragment.MENTIONS_COMMENT_CHILD_POSITION, fragment.getMentionsCommentTimeLineFragment()); FragmentTransaction transaction = fragment.getChildFragmentManager().beginTransaction(); if (!fragmentList.get(MentionsTimeLineFragment.MENTIONS_WEIBO_CHILD_POSITION).isAdded()) transaction.add(viewPager.getId(), fragmentList.get(MentionsTimeLineFragment.MENTIONS_WEIBO_CHILD_POSITION), MentionsWeiboTimeLineFragment.class.getName()); if (!fragmentList.get(MentionsTimeLineFragment.MENTIONS_COMMENT_CHILD_POSITION).isAdded()) transaction.add(viewPager.getId(), fragmentList.get(MentionsTimeLineFragment.MENTIONS_COMMENT_CHILD_POSITION), MentionsCommentTimeLineFragment.class.getName()); if (!transaction.isEmpty()) { transaction.commit(); fragment.getChildFragmentManager().executePendingTransactions(); } } public Fragment getItem(int position) { return fragmentList.get(position); } @Override protected String getTag(int position) { SparseArray<String> tagList = new SparseArray<String>(); tagList.append(MentionsTimeLineFragment.MENTIONS_WEIBO_CHILD_POSITION, MentionsWeiboTimeLineFragment.class.getName()); tagList.append(MentionsTimeLineFragment.MENTIONS_COMMENT_CHILD_POSITION, MentionsCommentTimeLineFragment.class.getName()); return tagList.get(position); } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { if (position == 0) { return fragmentList.get(position).getActivity().getResources().getString(R.string.mentions_weibo); } return fragmentList.get(position).getActivity().getResources().getString(R.string.mentions_to_me); } }
gpl-3.0
s20121035/rk3288_android5.1_repo
libcore/luni/src/main/java/java/lang/ref/ReferenceQueue.java
5789
/* * 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 java.lang.ref; /** * The {@code ReferenceQueue} is the container on which reference objects are * enqueued when the garbage collector detects the reachability type specified * for the referent. * * @since 1.2 */ public class ReferenceQueue<T> { private static final int NANOS_PER_MILLI = 1000000; private Reference<? extends T> head; private Reference<? extends T> tail; /** * Constructs a new instance of this class. */ public ReferenceQueue() { } /** * Returns the next available reference from the queue, removing it in the * process. Does not wait for a reference to become available. * * @return the next available reference, or {@code null} if no reference is * immediately available */ @SuppressWarnings("unchecked") public synchronized Reference<? extends T> poll() { if (head == null) { return null; } Reference<? extends T> ret = head; if (head == tail) { tail = null; head = null; } else { head = head.queueNext; } ret.queueNext = null; return ret; } /** * Returns the next available reference from the queue, removing it in the * process. Waits indefinitely for a reference to become available. * * @throws InterruptedException if the blocking call was interrupted */ public Reference<? extends T> remove() throws InterruptedException { return remove(0L); } /** * Returns the next available reference from the queue, removing it in the * process. Waits for a reference to become available or the given timeout * period to elapse, whichever happens first. * * @param timeoutMillis maximum time to spend waiting for a reference object * to become available. A value of {@code 0} results in the method * waiting indefinitely. * @return the next available reference, or {@code null} if no reference * becomes available within the timeout period * @throws IllegalArgumentException if {@code timeoutMillis < 0}. * @throws InterruptedException if the blocking call was interrupted */ public synchronized Reference<? extends T> remove(long timeoutMillis) throws InterruptedException { if (timeoutMillis < 0) { throw new IllegalArgumentException("timeout < 0: " + timeoutMillis); } if (head != null) { return poll(); } // avoid overflow: if total > 292 years, just wait forever if (timeoutMillis == 0 || (timeoutMillis > Long.MAX_VALUE / NANOS_PER_MILLI)) { do { wait(0); } while (head == null); return poll(); } // guaranteed to not overflow long nanosToWait = timeoutMillis * NANOS_PER_MILLI; int timeoutNanos = 0; // wait until notified or the timeout has elapsed long startTime = System.nanoTime(); while (true) { wait(timeoutMillis, timeoutNanos); if (head != null) { break; } long nanosElapsed = System.nanoTime() - startTime; long nanosRemaining = nanosToWait - nanosElapsed; if (nanosRemaining <= 0) { break; } timeoutMillis = nanosRemaining / NANOS_PER_MILLI; timeoutNanos = (int) (nanosRemaining - timeoutMillis * NANOS_PER_MILLI); } return poll(); } /** * Enqueue the reference object on the receiver. * * @param reference * reference object to be enqueued. */ synchronized void enqueue(Reference<? extends T> reference) { if (tail == null) { head = reference; } else { tail.queueNext = reference; } // The newly enqueued reference becomes the new tail, and always // points to itself. tail = reference; tail.queueNext = reference; notify(); } /** @hide */ public static Reference<?> unenqueued = null; static void add(Reference<?> list) { synchronized (ReferenceQueue.class) { if (unenqueued == null) { unenqueued = list; } else { // Find the last element in unenqueued. Reference<?> last = unenqueued; while (last.pendingNext != unenqueued) { last = last.pendingNext; } // Add our list to the end. Update the pendingNext to point back to enqueued. last.pendingNext = list; last = list; while (last.pendingNext != list) { last = last.pendingNext; } last.pendingNext = unenqueued; } ReferenceQueue.class.notifyAll(); } } }
gpl-3.0
winder/Universal-G-Code-Sender
ugs-platform/ugs-platform-plugin-designer/src/main/java/org/kabeja/parser/ParserBuilder.java
8861
/* Copyright 2005 Simon Mieth 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.kabeja.parser; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import org.kabeja.parser.entities.DXF3DFaceHandler; import org.kabeja.parser.entities.DXF3DSolidHandler; import org.kabeja.parser.entities.DXFArcHandler; import org.kabeja.parser.entities.DXFBodyHandler; import org.kabeja.parser.entities.DXFCircleHandler; import org.kabeja.parser.entities.DXFDimensionHandler; import org.kabeja.parser.entities.DXFEllipseHandler; import org.kabeja.parser.entities.DXFHatchHandler; import org.kabeja.parser.entities.DXFImageHandler; import org.kabeja.parser.entities.DXFInsertHandler; import org.kabeja.parser.entities.DXFLWPolylineHandler; import org.kabeja.parser.entities.DXFLeaderHandler; import org.kabeja.parser.entities.DXFLineHandler; import org.kabeja.parser.entities.DXFMLineHandler; import org.kabeja.parser.entities.DXFMTextHandler; import org.kabeja.parser.entities.DXFPolylineHandler; import org.kabeja.parser.entities.DXFRayHandler; import org.kabeja.parser.entities.DXFRegionHandler; import org.kabeja.parser.entities.DXFSolidHandler; import org.kabeja.parser.entities.DXFSplineHandler; import org.kabeja.parser.entities.DXFTextHandler; import org.kabeja.parser.entities.DXFToleranceHandler; import org.kabeja.parser.entities.DXFTraceHandler; import org.kabeja.parser.entities.DXFViewportHandler; import org.kabeja.parser.entities.DXFXLineHandler; import org.kabeja.parser.objects.DXFDictionaryHandler; import org.kabeja.parser.objects.DXFImageDefHandler; import org.kabeja.parser.objects.DXFLayoutHandler; import org.kabeja.parser.objects.DXFMLineStyleHandler; import org.kabeja.parser.objects.DXFPlotsettingsHandler; import org.kabeja.parser.table.DXFDimensionStyleTableHandler; import org.kabeja.parser.table.DXFLayerTableHandler; import org.kabeja.parser.table.DXFLineTypeTableHandler; import org.kabeja.parser.table.DXFStyleTableHandler; import org.kabeja.parser.table.DXFVPortTableHandler; import org.kabeja.parser.table.DXFViewTableHandler; /** * @author <a href="mailto:simon.mieth@gmx.de>Simon Mieth</a> * * * */ public class ParserBuilder { public static Parser createDefaultParser() { DXFParser parser = new DXFParser(); Handler handler; handler = new DXFHeaderSectionHandler(); parser.addHandler(handler); // the blocks handler HandlerManager handlerManager = new DXFBlocksSectionHandler(); parser.addHandler(handlerManager); Handler h = new DXFLineHandler(); handlerManager.addHandler(h); h = new DXFCircleHandler(); handlerManager.addHandler(h); h = new DXFArcHandler(); handlerManager.addHandler(h); h = new DXFPolylineHandler(); handlerManager.addHandler(h); h = new DXFLWPolylineHandler(); handlerManager.addHandler(h); h = new DXFMTextHandler(); handlerManager.addHandler(h); h = new DXFTextHandler(); handlerManager.addHandler(h); h = new DXFInsertHandler(); handlerManager.addHandler(h); h = new DXFEllipseHandler(); handlerManager.addHandler(h); h = new DXFSolidHandler(); handlerManager.addHandler(h); h = new DXFTraceHandler(); handlerManager.addHandler(h); h = new DXFDimensionHandler(); handlerManager.addHandler(h); h = new DXFHatchHandler(); handlerManager.addHandler(h); h = new DXFImageHandler(); handlerManager.addHandler(h); h = new DXF3DFaceHandler(); handlerManager.addHandler(h); h = new DXFRayHandler(); handlerManager.addHandler(h); h = new DXFXLineHandler(); handlerManager.addHandler(h); h = new DXFRegionHandler(); handlerManager.addHandler(h); h = new DXFBodyHandler(); handlerManager.addHandler(h); h = new DXF3DSolidHandler(); handlerManager.addHandler(h); h = new DXFSplineHandler(); handlerManager.addHandler(h); h = new DXFMLineHandler(); handlerManager.addHandler(h); h = new DXFLeaderHandler(); handlerManager.addHandler(h); h = new DXFToleranceHandler(); handlerManager.addHandler(h); h = new DXFViewportHandler(); handlerManager.addHandler(h); // the table handler handlerManager = new DXFTableSectionHandler(); parser.addHandler(handlerManager); handler = new DXFLayerTableHandler(); handlerManager.addHandler(handler); handler = new DXFLineTypeTableHandler(); handlerManager.addHandler(handler); handler = new DXFDimensionStyleTableHandler(); handlerManager.addHandler(handler); handler = new DXFStyleTableHandler(); handlerManager.addHandler(handler); handler = new DXFVPortTableHandler(); handlerManager.addHandler(handler); handler = new DXFViewTableHandler(); handlerManager.addHandler(handler); // the entity section handler handlerManager = new DXFEntitiesSectionHandler(); parser.addHandler(handlerManager); // the entity handlers h = new DXFLineHandler(); handlerManager.addHandler(h); h = new DXFCircleHandler(); handlerManager.addHandler(h); h = new DXFArcHandler(); handlerManager.addHandler(h); h = new DXFPolylineHandler(); handlerManager.addHandler(h); h = new DXFLWPolylineHandler(); handlerManager.addHandler(h); h = new DXFMTextHandler(); handlerManager.addHandler(h); h = new DXFTextHandler(); handlerManager.addHandler(h); h = new DXFInsertHandler(); handlerManager.addHandler(h); h = new DXFEllipseHandler(); handlerManager.addHandler(h); h = new DXFSolidHandler(); handlerManager.addHandler(h); h = new DXFTraceHandler(); handlerManager.addHandler(h); h = new DXFDimensionHandler(); handlerManager.addHandler(h); h = new DXFHatchHandler(); handlerManager.addHandler(h); h = new DXFImageHandler(); handlerManager.addHandler(h); h = new DXF3DFaceHandler(); handlerManager.addHandler(h); h = new DXFRayHandler(); handlerManager.addHandler(h); h = new DXFXLineHandler(); handlerManager.addHandler(h); h = new DXFRegionHandler(); handlerManager.addHandler(h); h = new DXFBodyHandler(); handlerManager.addHandler(h); h = new DXF3DSolidHandler(); handlerManager.addHandler(h); h = new DXFSplineHandler(); handlerManager.addHandler(h); h = new DXFMLineHandler(); handlerManager.addHandler(h); h = new DXFLeaderHandler(); handlerManager.addHandler(h); h = new DXFToleranceHandler(); handlerManager.addHandler(h); h = new DXFViewportHandler(); handlerManager.addHandler(h); // the OBJECTS section handlerManager = new DXFObjectsSectionHandler(); h = new DXFImageDefHandler(); handlerManager.addHandler(h); h = new DXFDictionaryHandler(); handlerManager.addHandler(h); h = new DXFPlotsettingsHandler(); handlerManager.addHandler(h); h = new DXFLayoutHandler(); handlerManager.addHandler(h); h = new DXFMLineStyleHandler(); handlerManager.addHandler(h); //add the HandlerManager as Handler to the parser parser.addHandler(handlerManager); return parser; } /** * @see org.kabeja.parser.SAXParserBuilder the SAXParserBuilder for XML * description * * @param file * @return the DXFParser build from the XML description file */ public static Parser buildFromXML(String file) { try { return buildFromXML(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } public static Parser buildFromXML(InputStream in) { return SAXParserBuilder.buildFromStream(in); } }
gpl-3.0
SuperMap-iDesktop/SuperMap-iDesktop-Cross
MapView/src/main/java/com/supermap/desktop/DefaultValues.java
339
package com.supermap.desktop; public class DefaultValues { public static final int DEFAULT_LABEL_WIDTH = 100; public static final int DEFAULT_COMPONENT_WIDTH = 200; public static final int DEFAULT_COMPONENT_HEIGHT = 23; public static final int NONE_VALUE = -1; private DefaultValues() { // 工具类,不提供构造方法 } }
gpl-3.0
Carnewal/CastleClash
src/server/world/entity/npc/dialogue/NiceWizardDialogue.java
669
package server.world.entity.npc.dialogue; import server.world.entity.npc.NpcDialogue; import server.world.entity.player.Player; /** * A conversation between the player and a nice wizard. * * @author lare96 */ public class NiceWizardDialogue extends NpcDialogue { @Override public void dialogue(Player player) { switch (player.getConversationStage()) { case 0: oneLineMobDialogue(player, Expression.HAPPY, "Hi " + player.getUsername() + "! Nice day today isn't it?", 460); this.stop(player); break; } } @Override public int dialogueId() { return 2; } }
gpl-3.0
andiwand/svm
src/at/stefl/svm/enumeration/PolygonFlag.java
1127
package at.stefl.svm.enumeration; import java.util.Map; import at.stefl.commons.util.collection.CollectionUtil; import at.stefl.commons.util.object.ObjectTransformer; public enum PolygonFlag { NORMAL(PolygonFlagConstants.POLY_NORMAL), SMOOTH( PolygonFlagConstants.POLY_SMOOTH), CONTROL( PolygonFlagConstants.POLY_CONTROL), SYMMETRY( PolygonFlagConstants.POLY_SYMMTR); private static final ObjectTransformer<PolygonFlag, Byte> CODE_KEY_GENERATOR = new ObjectTransformer<PolygonFlag, Byte>() { @Override public Byte transform(PolygonFlag value) { return value.code; } }; private static final Map<Byte, PolygonFlag> BY_CODE_MAP; static { BY_CODE_MAP = CollectionUtil.toHashMap(CODE_KEY_GENERATOR, values()); } public static PolygonFlag getActionTypeByCode(int code) { return BY_CODE_MAP.get(code); } private final byte code; private PolygonFlag(byte code) { this.code = code; } public int getCode() { return code; } }
gpl-3.0
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/registration/service/CodeVerificationRequest.java
14380
package org.thoughtcrime.securesms.registration.service; import android.content.Context; import android.os.AsyncTask; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.signal.core.util.concurrent.SignalExecutors; import org.signal.core.util.logging.Log; import org.signal.zkgroup.profiles.ProfileKey; import org.thoughtcrime.securesms.AppCapabilities; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; import org.thoughtcrime.securesms.crypto.PreKeyUtil; import org.thoughtcrime.securesms.crypto.ProfileKeyUtil; import org.thoughtcrime.securesms.crypto.SenderKeyUtil; import org.thoughtcrime.securesms.crypto.SessionUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.IdentityDatabase; import org.thoughtcrime.securesms.database.RecipientDatabase; import org.thoughtcrime.securesms.dependencies.ApplicationDependencies; import org.thoughtcrime.securesms.jobmanager.JobManager; import org.thoughtcrime.securesms.jobs.DirectoryRefreshJob; import org.thoughtcrime.securesms.jobs.RotateCertificateJob; import org.thoughtcrime.securesms.keyvalue.SignalStore; import org.thoughtcrime.securesms.pin.PinRestoreRepository; import org.thoughtcrime.securesms.pin.PinRestoreRepository.TokenData; import org.thoughtcrime.securesms.pin.PinState; import org.thoughtcrime.securesms.push.AccountManagerFactory; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientId; import org.thoughtcrime.securesms.service.DirectoryRefreshListener; import org.thoughtcrime.securesms.service.RotateSignedPreKeyListener; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libsignal.IdentityKeyPair; import org.whispersystems.libsignal.state.PreKeyRecord; import org.whispersystems.libsignal.state.SignedPreKeyRecord; import org.whispersystems.libsignal.util.KeyHelper; import org.whispersystems.libsignal.util.guava.Optional; import org.whispersystems.signalservice.api.KbsPinData; import org.whispersystems.signalservice.api.KeyBackupSystemNoDataException; import org.whispersystems.signalservice.api.SignalServiceAccountManager; import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess; import org.whispersystems.signalservice.api.push.exceptions.RateLimitException; import org.whispersystems.signalservice.api.util.UuidUtil; import org.whispersystems.signalservice.internal.push.LockedException; import org.whispersystems.signalservice.internal.push.VerifyAccountResponse; import java.io.IOException; import java.util.List; import java.util.UUID; public final class CodeVerificationRequest { private static final String TAG = Log.tag(CodeVerificationRequest.class); private enum Result { SUCCESS, PIN_LOCKED, KBS_WRONG_PIN, RATE_LIMITED, KBS_ACCOUNT_LOCKED, ERROR } /** * Asynchronously verify the account via the code. * * @param fcmToken The FCM token for the device. * @param code The code that was delivered to the user. * @param pin The users registration pin. * @param callback Exactly one method on this callback will be called. * @param kbsTokenData By keeping the token, on failure, a newly returned token will be reused in subsequent pin * attempts, preventing certain attacks, we can also track the attempts making missing replies easier to spot. */ static void verifyAccount(@NonNull Context context, @NonNull Credentials credentials, @Nullable String fcmToken, @NonNull String code, @Nullable String pin, @Nullable TokenData kbsTokenData, @NonNull VerifyCallback callback) { new AsyncTask<Void, Void, Result>() { private volatile LockedException lockedException; private volatile TokenData tokenData; @Override protected Result doInBackground(Void... voids) { final boolean pinSupplied = pin != null; final boolean tryKbs = tokenData != null; try { this.tokenData = kbsTokenData; verifyAccount(context, credentials, code, pin, tokenData, fcmToken); return Result.SUCCESS; } catch (KeyBackupSystemNoDataException e) { Log.w(TAG, "No data found on KBS"); return Result.KBS_ACCOUNT_LOCKED; } catch (KeyBackupSystemWrongPinException e) { tokenData = TokenData.withResponse(tokenData, e.getTokenResponse()); return Result.KBS_WRONG_PIN; } catch (LockedException e) { if (pinSupplied && tryKbs) { throw new AssertionError("KBS Pin appeared to matched but reg lock still failed!"); } Log.w(TAG, e); lockedException = e; if (e.getBasicStorageCredentials() != null) { try { tokenData = getToken(e.getBasicStorageCredentials()); if (tokenData == null || tokenData.getTriesRemaining() == 0) { return Result.KBS_ACCOUNT_LOCKED; } } catch (IOException ex) { Log.w(TAG, e); return Result.ERROR; } } return Result.PIN_LOCKED; } catch (RateLimitException e) { Log.w(TAG, e); return Result.RATE_LIMITED; } catch (IOException e) { Log.w(TAG, e); return Result.ERROR; } } @Override protected void onPostExecute(Result result) { switch (result) { case SUCCESS: handleSuccessfulRegistration(context); callback.onSuccessfulRegistration(); break; case PIN_LOCKED: if (tokenData != null) { if (lockedException.getBasicStorageCredentials() == null) { throw new AssertionError("KBS Token set, but no storage credentials supplied."); } Log.w(TAG, "Reg Locked: V2 pin needed for registration"); callback.onKbsRegistrationLockPinRequired(lockedException.getTimeRemaining(), tokenData, lockedException.getBasicStorageCredentials()); } else { Log.w(TAG, "Reg Locked: V1 pin needed for registration"); callback.onV1RegistrationLockPinRequiredOrIncorrect(lockedException.getTimeRemaining()); } break; case RATE_LIMITED: callback.onRateLimited(); break; case ERROR: callback.onError(); break; case KBS_WRONG_PIN: Log.w(TAG, "KBS Pin was wrong"); callback.onIncorrectKbsRegistrationLockPin(tokenData); break; case KBS_ACCOUNT_LOCKED: Log.w(TAG, "KBS Account is locked"); callback.onKbsAccountLocked(lockedException != null ? lockedException.getTimeRemaining() : null); break; } } }.executeOnExecutor(SignalExecutors.UNBOUNDED); } private static TokenData getToken(@Nullable String basicStorageCredentials) throws IOException { if (basicStorageCredentials == null) return null; return new PinRestoreRepository().getTokenSync(basicStorageCredentials); } private static void handleSuccessfulRegistration(@NonNull Context context) { JobManager jobManager = ApplicationDependencies.getJobManager(); jobManager.add(new DirectoryRefreshJob(false)); jobManager.add(new RotateCertificateJob()); DirectoryRefreshListener.schedule(context); RotateSignedPreKeyListener.schedule(context); } private static void verifyAccount(@NonNull Context context, @NonNull Credentials credentials, @NonNull String code, @Nullable String pin, @Nullable TokenData kbsTokenData, @Nullable String fcmToken) throws IOException, KeyBackupSystemWrongPinException, KeyBackupSystemNoDataException { boolean isV2RegistrationLock = kbsTokenData != null; int registrationId = KeyHelper.generateRegistrationId(false); boolean universalUnidentifiedAccess = TextSecurePreferences.isUniversalUnidentifiedAccess(context); ProfileKey profileKey = findExistingProfileKey(context, credentials.getE164number()); if (profileKey == null) { profileKey = ProfileKeyUtil.createNew(); Log.i(TAG, "No profile key found, created a new one"); } byte[] unidentifiedAccessKey = UnidentifiedAccess.deriveAccessKeyFrom(profileKey); TextSecurePreferences.setLocalRegistrationId(context, registrationId); SessionUtil.archiveAllSessions(context); SenderKeyUtil.clearAllState(context); SignalServiceAccountManager accountManager = AccountManagerFactory.createUnauthenticated(context, credentials.getE164number(), credentials.getPassword()); KbsPinData kbsData = isV2RegistrationLock ? PinState.restoreMasterKey(pin, kbsTokenData.getEnclave(), kbsTokenData.getBasicAuth(), kbsTokenData.getTokenResponse()) : null; String registrationLockV2 = kbsData != null ? kbsData.getMasterKey().deriveRegistrationLock() : null; String registrationLockV1 = isV2RegistrationLock ? null : pin; boolean hasFcm = fcmToken != null; Log.i(TAG, "Calling verifyAccountWithCode(): reglockV1? " + !TextUtils.isEmpty(registrationLockV1) + ", reglockV2? " + !TextUtils.isEmpty(registrationLockV2)); VerifyAccountResponse response = accountManager.verifyAccountWithCode(code, null, registrationId, !hasFcm, registrationLockV1, registrationLockV2, unidentifiedAccessKey, universalUnidentifiedAccess, AppCapabilities.getCapabilities(true), SignalStore.phoneNumberPrivacy().getPhoneNumberListingMode().isDiscoverable()); UUID uuid = UuidUtil.parseOrThrow(response.getUuid()); boolean hasPin = response.isStorageCapable(); IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(context); List<PreKeyRecord> records = PreKeyUtil.generatePreKeys(context); SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(context, identityKey, true); accountManager = AccountManagerFactory.createAuthenticated(context, uuid, credentials.getE164number(), credentials.getPassword()); accountManager.setPreKeys(identityKey.getPublicKey(), signedPreKey, records); if (hasFcm) { accountManager.setGcmId(Optional.fromNullable(fcmToken)); } RecipientDatabase recipientDatabase = DatabaseFactory.getRecipientDatabase(context); RecipientId selfId = Recipient.externalPush(context, uuid, credentials.getE164number(), true).getId(); recipientDatabase.setProfileSharing(selfId, true); recipientDatabase.markRegisteredOrThrow(selfId, uuid); TextSecurePreferences.setLocalNumber(context, credentials.getE164number()); TextSecurePreferences.setLocalUuid(context, uuid); recipientDatabase.setProfileKey(selfId, profileKey); ApplicationDependencies.getRecipientCache().clearSelf(); TextSecurePreferences.setFcmToken(context, fcmToken); TextSecurePreferences.setFcmDisabled(context, !hasFcm); TextSecurePreferences.setWebsocketRegistered(context, true); DatabaseFactory.getIdentityDatabase(context) .saveIdentity(selfId, identityKey.getPublicKey(), IdentityDatabase.VerifiedStatus.VERIFIED, true, System.currentTimeMillis(), true); TextSecurePreferences.setPushRegistered(context, true); TextSecurePreferences.setPushServerPassword(context, credentials.getPassword()); TextSecurePreferences.setSignedPreKeyRegistered(context, true); TextSecurePreferences.setPromptedPushRegistration(context, true); TextSecurePreferences.setUnauthorizedReceived(context, false); PinState.onRegistration(context, kbsData, pin, hasPin); } private static @Nullable ProfileKey findExistingProfileKey(@NonNull Context context, @NonNull String e164number) { RecipientDatabase recipientDatabase = DatabaseFactory.getRecipientDatabase(context); Optional<RecipientId> recipient = recipientDatabase.getByE164(e164number); if (recipient.isPresent()) { return ProfileKeyUtil.profileKeyOrNull(Recipient.resolved(recipient.get()).getProfileKey()); } return null; } public interface VerifyCallback { void onSuccessfulRegistration(); /** * The account is locked with a V1 (non-KBS) pin. * * @param timeRemaining Time until pin expires and number can be reused. */ void onV1RegistrationLockPinRequiredOrIncorrect(long timeRemaining); /** * The account is locked with a V2 (KBS) pin. Called before any user pin guesses. */ void onKbsRegistrationLockPinRequired(long timeRemaining, @NonNull TokenData kbsTokenData, @NonNull String kbsStorageCredentials); /** * The account is locked with a V2 (KBS) pin. Called after a user pin guess. * <p> * i.e. an attempt has likely been used. */ void onIncorrectKbsRegistrationLockPin(@NonNull TokenData kbsTokenResponse); /** * V2 (KBS) pin is set, but there is no data on KBS. * * @param timeRemaining Non-null if known. */ void onKbsAccountLocked(@Nullable Long timeRemaining); void onRateLimited(); void onError(); } }
gpl-3.0
AdvancedMods/AdvancedFoods
src/main/java/com/advancedmods/advancedfoods/common/blocks/crops/CornPlant.java
1987
package com.advancedmods.advancedfoods.common.blocks.crops; import com.advancedmods.advancedfoods.common.generic.AFBlockCrop; import com.advancedmods.advancedfoods.core.AFProps; import com.advancedmods.advancedfoods.core.AFRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import net.minecraft.util.IIcon; import java.util.Random; /** * Created by Dennisbonke on 12-2-2015. */ public class CornPlant extends AFBlockCrop { public CornPlant() { // Basic block setup this.setBlockName("cornplant"); this.setBlockTextureName(AFProps.modid.toLowerCase() + ":corn_0"); } /** * Returns the quantity of items to drop on block destruction. */ @Override public int quantityDropped(int parMetadata, int parFortune, Random parRand) { return (parMetadata / 2); } @Override public Item getItemDropped(int parMetadata, Random parRand, int parFortune) { return (AFRegistry.banana); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister parIIconRegister) { iIcon = new IIcon[maxGrowthStage + 1]; iIcon[0] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_0"); iIcon[1] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_0"); iIcon[2] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_1"); iIcon[3] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_1"); iIcon[4] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_2"); iIcon[5] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_2"); iIcon[6] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_3"); iIcon[7] = parIIconRegister.registerIcon(AFProps.modid.toLowerCase() + ":corn_3"); } }
gpl-3.0
rudin-io/s7connector
src/main/java/com/github/s7connector/api/SiemensPLCS.java
437
package com.github.s7connector.api; /** * @author wupeng * Create on 2/27/19. * @version 1.0 */ public enum SiemensPLCS { /** * S200 */ S200, /** * S200Smart */ S200Smart, /** * except the 200 series */ SNon200, /** * S300 */ S300, /** * S400 */ S400, /** * S1200 */ S1200, /** * S1500 */ S1500, }
gpl-3.0
CoffeeCodeSwitzerland/Lernkartei_2017
src/scrollyv8/Robob.java
2710
package scrollyv8; import java.awt.Graphics; public class Robob extends Enemy { private SpriteManager sMan_r, sMan_l, sMan_d, sMan_D; public char state; public Robob(double xs, double ys, double ws, double hs, String sPath) { super(xs, ys, ws, hs); alive = true; type = 'r'; dCy=-4; sMan_r = new SpriteManager(sPath + "robob_right.png", 40, 30, 4, true); sMan_l = new SpriteManager(sPath + "robob_left.png", 40, 30, 4, true); sMan_d = new SpriteManager(sPath + "robob_right_death.png", 40, 30, 8, false); sMan_D= new SpriteManager(sPath + "robob_left_death.png", 40, 30, 8, false); sMan_d.setDelay(8); sMan_D.setDelay(8); state = 'r'; } public boolean addImage(String fN) { return false; } public void draw(Graphics g, double x0, double y0) { int dy = 4; switch (state) { case 'r': g.drawImage(sMan_r.get(), (int) (x - x0), (int) (y - y0+dy), (int) w, (int) h, null); break; case 'l': g.drawImage(sMan_l.get(), (int) (x - x0), (int) (y - y0+dy), (int) w, (int) h, null); break; case 'd': g.drawImage(sMan_d.get(), (int) (x - x0), (int) (y - y0+dy), (int) w, (int) h, null); break; case 'D': g.drawImage(sMan_D.get(), (int) (x - x0), (int) (y - y0+dy), (int) w, (int) h, null); break; } } public void iterate(double d, boolean collH, boolean collV, boolean willFall, double dVX, double dVY) { super.iterate(d, collH, collV, willFall, dVX, dVY); if (isAlive()) { if (vx >= 0) { state = 'r'; } else { state = 'l'; } } switch (state) { case 'r': sMan_r.iterate(d); break; case 'l': sMan_l.iterate(d); break; case 'd': sMan_d.iterate(d); break; case 'D': sMan_D.iterate(d); break; } } public boolean setState(char c) { if (c == 'l') { state = 'l'; return true; } else if (c == 'r') { state = 'r'; return true; } else { return false; } } public void kill() { alive = false; if(state == 'r') { state = 'd'; } else state = 'D'; } }
gpl-3.0
gstreamer-java/gir2java
generated-src/generated/gio20/gio/GDBusObjectIface.java
868
package generated.gio20.gio; import generated.gobject20.gobject.GTypeInterface; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Field; import org.bridj.ann.Library; @Library("gio-2.0") public class GDBusObjectIface extends StructObject { static { BridJ.register(); } public GDBusObjectIface() { super(); } public GDBusObjectIface(Pointer pointer) { super(pointer); } @Field(0) public GTypeInterface gdbusobjectiface_field_parent_iface() { return this.io.getNativeObjectField(this, 0); } @Field(0) public GDBusObjectIface gdbusobjectiface_field_parent_iface(GTypeInterface gdbusobjectiface_field_parent_iface) { this.io.setNativeObjectField(this, 0, gdbusobjectiface_field_parent_iface); return this; } }
gpl-3.0
RiccardoDeMasellis/First-order-LTL-monitoring
src/test/java/FoLtlTemporalFormulaTest.java
10825
import language.foltl.*; import org.junit.Assert; import org.junit.Test; import static util.ParsingUtils.*; /** * Created by Simone Calciolari on 10/08/15. */ public class FoLtlTemporalFormulaTest { //Boolean flag used to display extra information during the execution private static final boolean DEBUG = true; @Test public void testTemporalFormulaBuilding(){ System.out.println("\n*** TEMPORAL FORMULA BUILDING TEST ***"); //G P(a) & F Q(a, b) FoLtlConstant a = new FoLtlConstant("a"); FoLtlConstant b = new FoLtlConstant("b"); FoLtlPredicate P = new FoLtlPredicate("P", 1); FoLtlPredicate Q = new FoLtlPredicate("Q", 2); FoLtlLocalAtom Pa = new FoLtlLocalAtom(P, a); FoLtlLocalAtom Qab = new FoLtlLocalAtom(Q, a, b); FoLtlFormula globPa = new FoLtlGloballyFormula(Pa); FoLtlFormula evnQab = new FoLtlEventuallyFormula(Qab); FoLtlFormula globAndEvn = new FoLtlTempAndFormula(globPa, evnQab); FoLtlFormula builtFormula = globAndEvn; Assert.assertEquals("", "(G(P(a))) TeAND (F(Q(a, b)))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); //P(a) & Q(b, d) U P(c) & Q(a, b) FoLtlConstant c = new FoLtlConstant("c"); FoLtlConstant d = new FoLtlConstant("d"); FoLtlLocalAtom Pc = new FoLtlLocalAtom(P, c); FoLtlLocalAtom Qbd = new FoLtlLocalAtom(Q, b, d); FoLtlFormula PaAndQbd = new FoLtlLocalAndFormula(Pa, Qbd); FoLtlFormula PcAndQab = new FoLtlLocalAndFormula(Pc, Qab); FoLtlFormula andUntiland = new FoLtlUntilFormula(PaAndQbd, PcAndQab); builtFormula = andUntiland; Assert.assertEquals("", "((P(a)) AND (Q(b, d))) U ((P(c)) AND (Q(a, b)))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); //(P(a) & P(b)) U ((X Q(c, c) & (P(c) U P(d))) FoLtlLocalAtom Pb = new FoLtlLocalAtom(P, b); FoLtlLocalAtom Pd = new FoLtlLocalAtom(P, d); FoLtlLocalAtom Qcc = new FoLtlLocalAtom(Q, c, c); FoLtlFormula PaAndPb = new FoLtlLocalAndFormula(Pa, Pb); FoLtlFormula PcUntPd = new FoLtlUntilFormula(Pc, Pd); FoLtlFormula nextQcc = new FoLtlNextFormula(Qcc); FoLtlFormula xqAndpUp = new FoLtlTempAndFormula(nextQcc, PcUntPd); FoLtlFormula andUand = new FoLtlUntilFormula(PaAndPb, xqAndpUp); builtFormula = andUand; Assert.assertEquals("", "((P(a)) AND (P(b))) U ((X(Q(c, c))) TeAND ((P(c)) U (P(d))))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); //((P(a) & P(b)) U ((X P(c)) & (P(d)))) R // ( ((WX (P(a) -> P(a))) WU (G P(a) R P(a))) <-> (P(a) U P(a)) ) FoLtlFormula and1 = new FoLtlLocalAndFormula(Pa, Pb); FoLtlFormula next1 = new FoLtlNextFormula(Pc); FoLtlFormula and2 = new FoLtlTempAndFormula(next1, Pd); FoLtlFormula unt1 = new FoLtlUntilFormula(and1, and2); FoLtlFormula impl1 = new FoLtlLocalImplFormula(Pa, Pa); FoLtlFormula wNext1 = new FoLtlWeakNextFormula(impl1); FoLtlFormula glob1 = new FoLtlGloballyFormula(Pa); FoLtlFormula rel1 = new FoLtlReleaseFormula(glob1, Pa); FoLtlFormula wUnt1 = new FoLtlWeakUntilFormula(wNext1, rel1); FoLtlFormula unt2 = new FoLtlUntilFormula(Pa, Pa); FoLtlFormula dImpl1 = new FoLtlTempDoubleImplFormula(wUnt1, unt2); FoLtlFormula rel2 = new FoLtlReleaseFormula(unt1, dImpl1); builtFormula = rel2; Assert.assertEquals("", "(((P(a)) AND (P(b))) U ((X(P(c))) TeAND (P(d)))) R (((WX((P(a)) IMPL (P(a)))) WU ((G(P(a))) " + "R (P(a)))) TeDIMPL ((P(a)) U (P(a))))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); //Forall ?x ((P(?x)) U (Exists ?y ((!(?x = ?y)) && (P(?y))))) FoLtlVariable x = new FoLtlVariable("x"); FoLtlVariable y = new FoLtlVariable("y"); FoLtlLocalAtom Px = new FoLtlLocalAtom(P, x); FoLtlLocalAtom Py = new FoLtlLocalAtom(P, y); FoLtlFormula xEQy = new FoLtlLocalEqualityFormula(x, y); FoLtlFormula neq = new FoLtlLocalNotFormula(xEQy); FoLtlFormula and = new FoLtlLocalAndFormula(neq, Py); FoLtlFormula existsY = new FoLtlLocalExistsFormula(and, y); FoLtlFormula until = new FoLtlUntilFormula(Px, existsY); FoLtlFormula forallX = new FoLtlAcrossForallFormula(until, x); builtFormula = forallX; Assert.assertEquals("", "xsForall ?x: ((P(?x)) U (Exists ?y: ((NOT(?x = ?y)) AND (P(?y)))))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); //Forall ?x (Forall ?y P(?x) & Q(?x, ?x) | G P(?y) U Q(?y, ?y)) FoLtlLocalAtom Qxx = new FoLtlLocalAtom(Q, x, x); FoLtlLocalAtom Qyy = new FoLtlLocalAtom(Q, y, y); FoLtlFormula pxAndQxx = new FoLtlLocalAndFormula(Px, Qxx); FoLtlFormula gPy = new FoLtlGloballyFormula(Py); FoLtlFormula gpyUQyy = new FoLtlUntilFormula(gPy, Qyy); FoLtlFormula tor = new FoLtlTempOrFormula(pxAndQxx, gpyUQyy); FoLtlFormula forallY = new FoLtlAcrossForallFormula(tor, y); forallX = new FoLtlAcrossForallFormula(forallY, x); builtFormula = forallX; Assert.assertEquals("", "xsForall ?x: (xsForall ?y: (((P(?x)) AND (Q(?x, ?x))) TeOR ((G(P(?y))) U (Q(?y, ?y)))))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); //Forall ?x (Forall ?y P(?x) & Q(?x, ?x) | FALSE U Q(?y, ?y)) FoLtlFormula fsUQyy = new FoLtlUntilFormula(new FoLtlLocalFalseAtom(), Qyy); FoLtlFormula tor1 = new FoLtlTempOrFormula(pxAndQxx, fsUQyy); FoLtlFormula forallY1 = new FoLtlAcrossForallFormula(tor1, y); forallX = new FoLtlAcrossForallFormula(forallY1, x); builtFormula = forallX; Assert.assertEquals("", "xsForall ?x: (xsForall ?y: (((P(?x)) AND (Q(?x, ?x))) TeOR ((FALSE) U (Q(?y, ?y)))))", builtFormula.toString()); System.out.println("\nBuilt formula: " + builtFormula.toString()); } @Test public void testTemporalFormulaParsing(){ System.out.println("\n\n*** TEMPORAL FORMULA PARSING TEST ***\n"); //G P(a) & F Q(a, b) FoLtlConstant a = new FoLtlConstant("a"); FoLtlConstant b = new FoLtlConstant("b"); FoLtlPredicate P = new FoLtlPredicate("P", 1); FoLtlPredicate Q = new FoLtlPredicate("Q", 2); FoLtlLocalAtom Pa = new FoLtlLocalAtom(P, a); FoLtlLocalAtom Qab = new FoLtlLocalAtom(Q, a, b); FoLtlFormula globPa = new FoLtlGloballyFormula(Pa); FoLtlFormula evnQab = new FoLtlEventuallyFormula(Qab); FoLtlFormula globAndEvn = new FoLtlTempAndFormula(globPa, evnQab); FoLtlFormula target = globAndEvn; Assert.assertEquals("", target, parseFoLtlFormula("G P(a) & F Q(a, b)")); //P(a) & Q(b, d) U P(c) & Q(a, b) FoLtlConstant c = new FoLtlConstant("c"); FoLtlConstant d = new FoLtlConstant("d"); FoLtlLocalAtom Pc = new FoLtlLocalAtom(P, c); FoLtlLocalAtom Qbd = new FoLtlLocalAtom(Q, b, d); FoLtlFormula PaAndQbd = new FoLtlLocalAndFormula(Pa, Qbd); FoLtlFormula PcAndQab = new FoLtlLocalAndFormula(Pc, Qab); FoLtlFormula andUntiland = new FoLtlUntilFormula(PaAndQbd, PcAndQab); target = andUntiland; Assert.assertEquals("", target, parseFoLtlFormula("P(a) & Q(b, d) U P(c) & Q(a, b)")); //(P(a) & P(b)) U ((X Q(c, c) & (P(c) U P(d))) FoLtlLocalAtom Pb = new FoLtlLocalAtom(P, b); FoLtlLocalAtom Pd = new FoLtlLocalAtom(P, d); FoLtlLocalAtom Qcc = new FoLtlLocalAtom(Q, c, c); FoLtlFormula PaAndPb = new FoLtlLocalAndFormula(Pa, Pb); FoLtlFormula PcUntPd = new FoLtlUntilFormula(Pc, Pd); FoLtlFormula nextQcc = new FoLtlNextFormula(Qcc); FoLtlFormula xqAndpUp = new FoLtlTempAndFormula(nextQcc, PcUntPd); FoLtlFormula andUand = new FoLtlUntilFormula(PaAndPb, xqAndpUp); target = andUand; Assert.assertEquals("", target, parseFoLtlFormula("(P(a) & P(b)) U (X Q(c, c) & (P(c) U P(d)))")); //((P(a) & P(b)) U ((X P(c)) & (P(d)))) R // ( ((WX (P(a) -> P(a))) WU (G P(a) R P(a))) <-> (P(a) U P(a)) ) FoLtlFormula and1 = new FoLtlLocalAndFormula(Pa, Pb); FoLtlFormula next1 = new FoLtlNextFormula(Pc); FoLtlFormula and2 = new FoLtlTempAndFormula(next1, Pd); FoLtlFormula unt1 = new FoLtlUntilFormula(and1, and2); FoLtlFormula impl1 = new FoLtlLocalImplFormula(Pa, Pa); FoLtlFormula wNext1 = new FoLtlWeakNextFormula(impl1); FoLtlFormula glob1 = new FoLtlGloballyFormula(Pa); FoLtlFormula rel1 = new FoLtlReleaseFormula(glob1, Pa); FoLtlFormula wUnt1 = new FoLtlWeakUntilFormula(wNext1, rel1); FoLtlFormula unt2 = new FoLtlUntilFormula(Pa, Pa); FoLtlFormula dImpl1 = new FoLtlTempDoubleImplFormula(wUnt1, unt2); FoLtlFormula rel2 = new FoLtlReleaseFormula(unt1, dImpl1); target = rel2; Assert.assertEquals("", target, parseFoLtlFormula("(P(a) & P(b) U ((X P(c)) & P(d))) R (((WX P(a) -> P(a)) WU (G P(a) R P(a))) <-> P(a) U P(a))")); //Forall ?x ((P(?x)) U (Exists ?y ((!(?x = ?y)) && (P(?y))))) FoLtlVariable x = new FoLtlVariable("x"); FoLtlVariable y = new FoLtlVariable("y"); FoLtlLocalAtom Px = new FoLtlLocalAtom(P, x); FoLtlLocalAtom Py = new FoLtlLocalAtom(P, y); FoLtlFormula xEQy = new FoLtlLocalEqualityFormula(x, y); FoLtlFormula neq = new FoLtlLocalNotFormula(xEQy); FoLtlFormula and = new FoLtlLocalAndFormula(neq, Py); FoLtlFormula existsY = new FoLtlLocalExistsFormula(and, y); FoLtlFormula until = new FoLtlUntilFormula(Px, existsY); FoLtlFormula forallX = new FoLtlAcrossForallFormula(until, x); target = forallX; Assert.assertEquals("", target, parseFoLtlFormula("Forall ?x (P(?x) U Exists ?y !(?x = ?y) & P(?y))")); //Forall ?x (Forall ?y P(?x) & Q(?x, ?x) | G P(?y) U Q(?y, ?y)) FoLtlLocalAtom Qxx = new FoLtlLocalAtom(Q, x, x); FoLtlLocalAtom Qyy = new FoLtlLocalAtom(Q, y, y); FoLtlFormula pxAndQxx = new FoLtlLocalAndFormula(Px, Qxx); FoLtlFormula gPy = new FoLtlGloballyFormula(Py); FoLtlFormula gpyUQyy = new FoLtlUntilFormula(gPy, Qyy); FoLtlFormula tor = new FoLtlTempOrFormula(pxAndQxx, gpyUQyy); FoLtlFormula forallY = new FoLtlAcrossForallFormula(tor, y); forallX = new FoLtlAcrossForallFormula(forallY, x); target = forallX; Assert.assertEquals("", target, parseFoLtlFormula("Forall ?x (Forall ?y (P(?x) & Q(?x, ?x) | G P(?y) U Q(?y, ?y)))")); //Forall ?x (Forall ?y P(?x) & Q(?x, ?x) | FALSE U Q(?y, ?y)) FoLtlFormula fsUQyy = new FoLtlUntilFormula(new FoLtlGloballyFormula(new FoLtlLocalFalseAtom()), Qyy); FoLtlFormula tor1 = new FoLtlTempOrFormula(pxAndQxx, fsUQyy); FoLtlFormula forallY1 = new FoLtlAcrossForallFormula(tor1, y); forallX = new FoLtlAcrossForallFormula(forallY1, x); target = forallX; Assert.assertEquals("", target, parseFoLtlFormula("Forall ?x (Forall ?y (P(?x) & Q(?x, ?x) | G false U Q(?y, ?y)))")); //G P(a) U LAST FoLtlFormula last = new FoLtlTempNotFormula(new FoLtlNextFormula(new FoLtlLocalTrueAtom())); target = new FoLtlUntilFormula(new FoLtlGloballyFormula(Pa), last); Assert.assertEquals("", target, parseFoLtlFormula("G P(a) U LAST")); } }
gpl-3.0
RaysaOliveira/cloudsim-plus
cloudsim-plus/src/main/java/org/cloudsimplus/builders/tables/AbstractTableColumn.java
5430
/* * CloudSim Plus: A modern, highly-extensible and easier-to-use Framework for * Modeling and Simulation of Cloud Computing Infrastructures and Services. * http://cloudsimplus.org * * Copyright (C) 2015-2016 Universidade da Beira Interior (UBI, Portugal) and * the Instituto Federal de Educação Ciência e Tecnologia do Tocantins (IFTO, Brazil). * * This file is part of CloudSim Plus. * * CloudSim Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CloudSim Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CloudSim Plus. If not, see <http://www.gnu.org/licenses/>. */ package org.cloudsimplus.builders.tables; /** * A column of a table to be generated using a {@link TableBuilder} class. * @author Manoel Campos da Silva Filho */ public abstract class AbstractTableColumn implements TableColumn { /** * @see #getTitle() */ private String title; /** * @see #getSubTitle() */ private String subTitle; /** * @see #getFormat() */ private String format; /** * @see #getTable() */ private TableBuilder table; /** * Creates a column with a specific title. * @param table The table that the column belongs to. * @param title The column title. */ public AbstractTableColumn(final TableBuilder table, final String title) { this(table, title, ""); } /** * Creates a column with a specific title and sub-title. * @param title The column title. * @param subTitle The column sub-title. */ public AbstractTableColumn(final String title, final String subTitle) { this(null, title, subTitle); } /** * Creates a column with a specific title and sub-title for a given table. * @param title The column title. * @param subTitle The column sub-title. */ public AbstractTableColumn(final TableBuilder table, final String title, final String subTitle) { this.table = table; this.title = title; this.setFormat(""); this.subTitle = subTitle; } /** * * @return The title to be displayed at the top of the column. */ @Override public String getTitle() { return title; } @Override public AbstractTableColumn setTitle(String title) { this.title = title; return this; } /** * * @return The subtitle to be displayed below the title of the column (optional). */ @Override public String getSubTitle() { return subTitle; } @Override public AbstractTableColumn setSubTitle(String subTitle) { this.subTitle = subTitle; return this; } /** * * @return The format to be used to display the content of the column, * according to the {@link String#format(java.lang.String, java.lang.Object...)} (optional). */ @Override public String getFormat() { return format; } @Override public final AbstractTableColumn setFormat(String format) { this.format = format; return this; } @Override public String toString() { return getTitle(); } /** * * @return The table that the column belongs to. */ @Override public TableBuilder getTable() { return table; } @Override public AbstractTableColumn setTable(TableBuilder table) { this.table = table; return this; } /** * Generates the string that represents the data of the column, * formatted according to the {@link #getFormat() format}. * @param data The data of the column to be formatted * @return a string containing the formatted column data */ @Override public String generateData(final Object data){ if(format.trim().isEmpty()) return String.valueOf(data); return String.format(format, data); } /** * Generates a header for the column, either for the title or subtitle header. * * @param str header title or subtitle * @return the generated header string */ protected abstract String generateHeader(String str); @Override public String generateTitleHeader() { return generateHeader(title); } @Override public String generateSubtitleHeader() { return generateHeader(subTitle); } /** * * @return The index of the current column into the * column list of the {@link #getTable() TableBuilder}. */ protected int getIndex() { return table.getColumns().indexOf(this); } /** * Indicates if the current column is the last one * in the column list of the {@link #getTable() TableBuilder}. * @return true if it is the last column, false otherwise. */ protected boolean isLastColumn() { return getIndex() == getTable().getColumns().size()-1; } }
gpl-3.0
zerokullneo/PCTR
PCTR-Codigos/Codigos_tema6/src/Ejemplo_Bloques_Sincronizados.java
913
/** * @(#)Ejemplo_Bloques_Sincronizados.java * * * @author Antonio Tomeu * @version 1.00 2011/4/27 */ public class Ejemplo_Bloques_Sincronizados { private int Valor_1; private int Valor_2; protected Object Cerrojo_1 = new Object (); protected Object Cerrojo_2 = new Object (); public int Observa_1 () { synchronized (Cerrojo_1){ return (Valor_1); } } public void Modifica_1 (int dato) { synchronized (Cerrojo_1){ Valor_1 = dato; } } public void Modifica_2 (int dato) { synchronized (Cerrojo_2){ Valor_2 = dato; } } public int Observa_2 () { synchronized (Cerrojo_2){ return (Valor_2); } } public Ejemplo_Bloques_Sincronizados() { synchronized (Cerrojo_1){ synchronized (Cerrojo_2){ Valor_1 = Valor_2 = 1; } } } }
gpl-3.0
seadas/beam
beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/spectrum/CursorSpectrumPixelPositionListener.java
4270
package org.esa.beam.visat.toolviews.spectrum; import com.bc.ceres.glayer.support.ImageLayer; import java.awt.event.MouseEvent; import javax.swing.SwingWorker; import org.esa.beam.framework.ui.PixelPositionListener; public class CursorSpectrumPixelPositionListener implements PixelPositionListener { private final SpectrumToolView toolView; private final WorkerChain workerChain; private final WorkerChainSupport support; public CursorSpectrumPixelPositionListener(SpectrumToolView toolView) { this.toolView = toolView; workerChain = new WorkerChain(); support = new WorkerChainSupport() { @Override public void removeWorkerAndStartNext(SwingWorker worker) { workerChain.removeCurrentWorkerAndExecuteNext(worker); } }; } @Override public void pixelPosChanged(ImageLayer imageLayer, int pixelX, int pixelY, int currentLevel, boolean pixelPosValid, MouseEvent e) { CursorSpectraUpdater worker = new CursorSpectraUpdater(pixelPosValid, pixelX, pixelY, currentLevel, e.isShiftDown(), support); workerChain.setOrExecuteNextWorker(worker, false); } @Override public void pixelPosNotAvailable() { CursorSpectraRemover worker = new CursorSpectraRemover(support); workerChain.setOrExecuteNextWorker(worker, false); } private boolean shouldUpdateCursorPosition() { return toolView.isVisible() && toolView.isShowingCursorSpectrum(); } private class CursorSpectraRemover extends SwingWorker<Void, Void> { private final WorkerChainSupport support; CursorSpectraRemover(WorkerChainSupport support) { this.support = support; } @Override protected Void doInBackground() throws Exception { if (shouldUpdateCursorPosition()) { toolView.removeCursorSpectraFromDataset(); } return null; } @Override protected void done() { toolView.updateChart(); support.removeWorkerAndStartNext(this); } } private class CursorSpectraUpdater extends SwingWorker<Void, Void> { private final boolean pixelPosValid; private final int pixelX; private final int pixelY; private final int currentLevel; private final boolean adjustAxes; private final WorkerChainSupport support; CursorSpectraUpdater(boolean pixelPosValid, int pixelX, int pixelY, int currentLevel, boolean adjustAxes, WorkerChainSupport support) { this.pixelPosValid = pixelPosValid; this.pixelX = pixelX; this.pixelY = pixelY; this.currentLevel = currentLevel; this.adjustAxes = adjustAxes; this.support = support; } @Override protected Void doInBackground() throws Exception { if (pixelPosValid) { if (shouldUpdateCursorPosition()) { Waiter waiter = new Waiter(); waiter.execute(); toolView.updateData(pixelX, pixelY, currentLevel); waiter.cancel(true); } } else if (toolView.hasValidCursorPosition()) { toolView.removeCursorSpectraFromDataset(); } return null; } @Override protected void done() { toolView.updateChart(adjustAxes); support.removeWorkerAndStartNext(this); } } private class Waiter extends SwingWorker<Void, Void> { @Override protected Void doInBackground() throws Exception { Thread.sleep(1000); return null; } @Override protected void done() { toolView.setPrepareForUpdateMessage(); } } //todo copied (and changed very slightly) from time-series-tool: Move to BEAM or Ceres static interface WorkerChainSupport { void removeWorkerAndStartNext(SwingWorker worker); } }
gpl-3.0
Shappiro/GEOFRAME
PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/src/cern/colt/matrix/tfloat/algo/solver/FloatGivensRotation.java
3075
/* * Copyright (C) 2003-2006 Bjørn-Ove Heimsund * * This file is part of MTJ. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package cern.colt.matrix.tfloat.algo.solver; import cern.colt.matrix.tfloat.FloatMatrix1D; import cern.colt.matrix.tfloat.FloatMatrix2D; /** * Givens plane rotation */ public class FloatGivensRotation { /** * Cosine and sine of the rotation angle. c = x / sqrt(x^2 + y^2), and s = * -y / sqrt(x^2 + y^2) */ private final float c, s; /** * Constructs a Givens plane rotation for a given 2-vector * * @param x * First component of the vector * @param y * Second component of the vector */ public FloatGivensRotation(float x, float y) { float roe = Math.abs(x) > Math.abs(y) ? x : y; float scale = Math.abs(x) + Math.abs(y); if (scale != 0) { float xs = x / scale; float ys = y / scale; float r = scale * (float) Math.sqrt(xs * xs + ys * ys); if (roe < 0) r *= -1; c = x / r; s = y / r; } else { c = 1; s = 0; } } /** * Applies the Givens rotation to two elements in a matrix column * * @param H * Matrix to apply to * @param column * Column index * @param i1 * Row index of first element * @param i2 * Row index of second element */ public void apply(FloatMatrix2D H, int column, int i1, int i2) { float temp = c * H.getQuick(i1, column) + s * H.getQuick(i2, column); H.setQuick(i2, column, -s * H.getQuick(i1, column) + c * H.getQuick(i2, column)); H.setQuick(i1, column, temp); } /** * Applies the Givens rotation to two elements of a vector * * @param x * Vector to apply to * @param i1 * Index of first element * @param i2 * Index of second element */ public void apply(FloatMatrix1D x, int i1, int i2) { float temp = c * x.getQuick(i1) + s * x.getQuick(i2); x.setQuick(i2, -s * x.getQuick(i1) + c * x.getQuick(i2)); x.setQuick(i1, temp); } }
gpl-3.0
boy0001/FastAsyncWorldedit
core/src/main/java/com/sk89q/worldedit/util/command/fluent/DispatcherNode.java
6876
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.util.command.fluent; import com.boydti.fawe.config.Commands; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.worldedit.util.command.CallableProcessor; import com.sk89q.worldedit.util.command.CommandCallable; import com.sk89q.worldedit.util.command.Dispatcher; import com.sk89q.worldedit.util.command.SimpleDispatcher; import com.sk89q.worldedit.util.command.parametric.ParametricBuilder; import javax.annotation.Nullable; /** * A collection of commands. */ public class DispatcherNode { private final CommandGraph graph; private final DispatcherNode parent; private final SimpleDispatcher dispatcher; /** * Create a new instance. * * @param graph the root fluent graph object * @param parent the parent node, or null * @param dispatcher the dispatcher for this node */ public DispatcherNode(CommandGraph graph, DispatcherNode parent, SimpleDispatcher dispatcher) { this.graph = graph; this.parent = parent; this.dispatcher = dispatcher; } /** * Set the description. * <p> * <p>This can only be used on {@link DispatcherNode}s returned by * {@link #group(String...)}.</p> * * @param description the description * @return this object */ public DispatcherNode describeAs(String description) { dispatcher.getDescription().setDescription(description); return this; } /** * Register a command with this dispatcher. * * @param callable the executor * @param alias the list of aliases, where the first alias is the primary one */ public DispatcherNode register(CommandCallable callable, String... alias) { dispatcher.registerCommand(callable, alias); return this; } /** * Build and register a command with this dispatcher using the * {@link ParametricBuilder} assigned on the root {@link CommandGraph}. * * @param object the object provided to the {@link ParametricBuilder} * @return this object * @see ParametricBuilder#registerMethodsAsCommands(com.sk89q.worldedit.util.command.Dispatcher, Object) */ public DispatcherNode registerMethods(Object object) { return registerMethods(object, null); } /** * Build and register a command with this dispatcher using the * {@link ParametricBuilder} assigned on the root {@link CommandGraph}. * * @param object the object provided to the {@link ParametricBuilder} * @return this object * @see ParametricBuilder#registerMethodsAsCommands(com.sk89q.worldedit.util.command.Dispatcher, Object) */ public DispatcherNode registerMethods(Object object, @Nullable CallableProcessor processor) { ParametricBuilder builder = graph.getBuilder(); if (builder == null) { throw new RuntimeException("No ParametricBuilder set"); } builder.registerMethodsAsCommands(getDispatcher(), object, processor); return this; } /** * Build and register sub commands with this dispatcher using the * {@link ParametricBuilder} assigned on the objects registered command aliases {@link com.sk89q.minecraft.util.commands.Command}. * * @param object the object provided to the {@link ParametricBuilder} * @return this object */ public DispatcherNode registerSubMethods(Object object) { return registerSubMethods(object, null); } /** * Build and register sub commands with this dispatcher using the * {@link ParametricBuilder} assigned on the objects registered command aliases {@link com.sk89q.minecraft.util.commands.Command}. * * @param object the object provided to the {@link ParametricBuilder} * @param processor the command processor * @return this object */ public DispatcherNode registerSubMethods(Object object, @Nullable CallableProcessor processor) { Class<? extends Object> clazz = object.getClass(); return groupAndDescribe(clazz).registerMethods(object, processor).parent(); } public DispatcherNode groupAndDescribe(Class clazz) { Command cmd = (Command) clazz.getAnnotation(Command.class); if (cmd == null) { throw new RuntimeException("This class does not have any command annotations"); } cmd = Commands.translate(clazz, cmd); DispatcherNode res = group(cmd.aliases()); if (cmd.desc() != null && !cmd.desc().isEmpty()) { res = res.describeAs(cmd.desc()); } return res; } /** * Create a new command that will contain sub-commands. * <p> * <p>The object returned by this method can be used to add sub-commands. To * return to this "parent" context, use {@link DispatcherNode#graph()}.</p> * * @param alias the list of aliases, where the first alias is the primary one * @return an object to place sub-commands */ public DispatcherNode group(String... alias) { SimpleDispatcher command = new SimpleDispatcher(); getDispatcher().registerCommand(command, alias); DispatcherNode res = new DispatcherNode(graph, this, command); return res; } /** * Return the parent node. * * @return the parent node * @throws RuntimeException if there is no parent node. */ public DispatcherNode parent() { if (parent != null) { return parent; } throw new RuntimeException("This node does not have a parent"); } /** * Get the root command graph. * * @return the root command graph */ public CommandGraph graph() { return graph; } /** * Get the underlying dispatcher of this object. * * @return the dispatcher */ public Dispatcher getDispatcher() { return dispatcher; } public static Class<?> inject() { return DispatcherNode.class; } }
gpl-3.0
djkimrivet/hr-portal
portlets/hrportal-services-portlet/docroot/WEB-INF/service/com/hrportal/service/ClpSerializer.java
5993
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.hrportal.service; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream; import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.ClassLoaderObjectInputStream; import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.BaseModel; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * @author Rivet Logic */ public class ClpSerializer { public static String getServletContextName() { if (Validator.isNotNull(_servletContextName)) { return _servletContextName; } synchronized (ClpSerializer.class) { if (Validator.isNotNull(_servletContextName)) { return _servletContextName; } try { ClassLoader classLoader = ClpSerializer.class.getClassLoader(); Class<?> portletPropsClass = classLoader.loadClass( "com.liferay.util.portlet.PortletProps"); Method getMethod = portletPropsClass.getMethod("get", new Class<?>[] { String.class }); String portletPropsServletContextName = (String)getMethod.invoke(null, "hrportal-services-portlet-deployment-context"); if (Validator.isNotNull(portletPropsServletContextName)) { _servletContextName = portletPropsServletContextName; } } catch (Throwable t) { if (_log.isInfoEnabled()) { _log.info( "Unable to locate deployment context from portlet properties"); } } if (Validator.isNull(_servletContextName)) { try { String propsUtilServletContextName = PropsUtil.get( "hrportal-services-portlet-deployment-context"); if (Validator.isNotNull(propsUtilServletContextName)) { _servletContextName = propsUtilServletContextName; } } catch (Throwable t) { if (_log.isInfoEnabled()) { _log.info( "Unable to locate deployment context from portal properties"); } } } if (Validator.isNull(_servletContextName)) { _servletContextName = "hrportal-services-portlet"; } return _servletContextName; } } public static Object translateInput(BaseModel<?> oldModel) { return oldModel; } public static Object translateInput(List<Object> oldList) { List<Object> newList = new ArrayList<Object>(oldList.size()); for (int i = 0; i < oldList.size(); i++) { Object curObj = oldList.get(i); newList.add(translateInput(curObj)); } return newList; } public static Object translateInput(Object obj) { if (obj instanceof BaseModel<?>) { return translateInput((BaseModel<?>)obj); } else if (obj instanceof List<?>) { return translateInput((List<Object>)obj); } else { return obj; } } public static Object translateOutput(BaseModel<?> oldModel) { return oldModel; } public static Object translateOutput(List<Object> oldList) { List<Object> newList = new ArrayList<Object>(oldList.size()); for (int i = 0; i < oldList.size(); i++) { Object curObj = oldList.get(i); newList.add(translateOutput(curObj)); } return newList; } public static Object translateOutput(Object obj) { if (obj instanceof BaseModel<?>) { return translateOutput((BaseModel<?>)obj); } else if (obj instanceof List<?>) { return translateOutput((List<Object>)obj); } else { return obj; } } public static Throwable translateThrowable(Throwable throwable) { if (_useReflectionToTranslateThrowable) { try { UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(unsyncByteArrayOutputStream); objectOutputStream.writeObject(throwable); objectOutputStream.flush(); objectOutputStream.close(); UnsyncByteArrayInputStream unsyncByteArrayInputStream = new UnsyncByteArrayInputStream(unsyncByteArrayOutputStream.unsafeGetByteArray(), 0, unsyncByteArrayOutputStream.size()); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); ObjectInputStream objectInputStream = new ClassLoaderObjectInputStream(unsyncByteArrayInputStream, contextClassLoader); throwable = (Throwable)objectInputStream.readObject(); objectInputStream.close(); return throwable; } catch (SecurityException se) { if (_log.isInfoEnabled()) { _log.info("Do not use reflection to translate throwable"); } _useReflectionToTranslateThrowable = false; } catch (Throwable throwable2) { _log.error(throwable2, throwable2); return throwable2; } } Class<?> clazz = throwable.getClass(); String className = clazz.getName(); if (className.equals(PortalException.class.getName())) { return new PortalException(); } if (className.equals(SystemException.class.getName())) { return new SystemException(); } return throwable; } private static Log _log = LogFactoryUtil.getLog(ClpSerializer.class); private static String _servletContextName; private static boolean _useReflectionToTranslateThrowable = true; }
gpl-3.0
whilkes/realm-platform
derived/src/test/java/net/realmproject/platform/schema/tests/PrintObject.java
886
package net.realmproject.platform.schema.tests; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import net.objectof.model.Resource; import net.objectof.model.ResourceException; import net.objectof.model.Transaction; import net.objectof.model.impl.IKind; import net.objectof.model.impl.IPackage; public class PrintObject { public static void print(Transaction aTx, Object aObject) { @SuppressWarnings("unchecked") Resource<Object> o = (Resource<Object>) aObject; IKind<Object> kind = (IKind<Object>) o.id().kind(); Writer w = new OutputStreamWriter(System.out); try { kind.datatype().toJson(o.value(), (IPackage) aTx.getPackage(), w); w.write('\n'); w.flush(); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
gpl-3.0
HuygensING/timbuctoo
timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/v5/queue/QueueManager.java
155
package nl.knaw.huygens.timbuctoo.v5.queue; public interface QueueManager { <T> QueueCreator<T> createQueue(Class<T> messageType, String queueName); }
gpl-3.0
ImagoTrigger/sdrtrunk
src/main/java/io/github/dsheirer/module/decode/p25/phase1/P25P1ChannelStatusProcessor.java
2656
/* * ****************************************************************************** * sdrtrunk * Copyright (C) 2014-2019 Dennis Sheirer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * ***************************************************************************** */ package io.github.dsheirer.module.decode.p25.phase1; import io.github.dsheirer.dsp.symbol.Dibit; import io.github.dsheirer.module.decode.p25.reference.Direction; import io.github.dsheirer.sample.Listener; /** * Processes P25 status dibits to determine if the channel being monitored is the output of a repeater or if * the channel is from a mobile subscriber. * * Dibit 00 is used by the subscriber * Dibits 01 and 11 are used by the repeater. * Dibit 10 is used by both and is ignored by this processor. */ public class P25P1ChannelStatusProcessor implements Listener<Dibit> { private int mSubscriberCount = 0; private int mRepeaterCount = 0; private Direction mDirection = Direction.OUTBOUND; public void receive(Dibit status) { switch(status) { case D00_PLUS_1: mSubscriberCount++; break; case D01_PLUS_3: case D11_MINUS_3: mRepeaterCount++; break; } update(); } private void update() { //This doesn't appear to be reliable and sometimes it fails on Harris systems. // if(mRepeaterCount > mSubscriberCount) // { // mDirection = Direction.OUTBOUND; // // if(mRepeaterCount == Integer.MAX_VALUE) // { // mRepeaterCount = 1000; // mSubscriberCount = 0; // } // } // else // { // mDirection = Direction.INBOUND; // // if(mSubscriberCount == Integer.MAX_VALUE) // { // mSubscriberCount = 1000; // mRepeaterCount = 0; // } // } } public Direction getDirection() { return mDirection; } }
gpl-3.0
pocmo/focus-android
app/src/androidTest/java/org/mozilla/focus/activity/RestartTest.java
6317
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity; import android.content.Context; import android.content.Intent; import android.os.RemoteException; import android.preference.PreferenceManager; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.uiautomator.By; import android.support.test.uiautomator.UiObject; import android.support.test.uiautomator.UiObjectNotFoundException; import android.support.test.uiautomator.UiSelector; import android.support.test.uiautomator.Until; import junit.framework.Assert; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.mozilla.focus.helpers.TestHelper; import static junit.framework.Assert.assertTrue; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertThat; import static org.mozilla.focus.helpers.TestHelper.waitingTime; import static org.mozilla.focus.fragment.FirstrunFragment.FIRSTRUN_PREF; // This test closes the app via recent apps list, and restarts @RunWith(AndroidJUnit4.class) public class RestartTest { private static final String TEST_PATH = "/"; private Context appContext; private MockWebServer webServer; @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class) { @Override protected void beforeActivityLaunched() { super.beforeActivityLaunched(); appContext = InstrumentationRegistry.getInstrumentation() .getTargetContext() .getApplicationContext(); PreferenceManager.getDefaultSharedPreferences(appContext) .edit() .putBoolean(FIRSTRUN_PREF, true) .apply(); webServer = new MockWebServer(); try { webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("image_test.html"))); webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("rabbit.jpg"))); webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("download.jpg"))); webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("image_test.html"))); webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("rabbit.jpg"))); webServer.enqueue(new MockResponse() .setBody(TestHelper.readTestAsset("download.jpg"))); webServer.start(); } catch (IOException e) { throw new AssertionError("Could not start web server", e); } } @Override protected void afterActivityFinished() { super.afterActivityFinished(); try { webServer.close(); webServer.shutdown(); } catch (IOException e) { throw new AssertionError("Could not stop web server", e); } } }; @After public void tearDown() throws Exception { mActivityTestRule.getActivity().finishAndRemoveTask(); } @Test public void restartFocus() throws InterruptedException, UiObjectNotFoundException, RemoteException { final int LAUNCH_TIMEOUT = 5000; final String FOCUS_DEBUG_APP = "org.mozilla.focus.debug"; // Open a webpage TestHelper.inlineAutocompleteEditText.waitForExists(waitingTime); TestHelper.inlineAutocompleteEditText.clearTextField(); TestHelper.inlineAutocompleteEditText.setText(webServer.url(TEST_PATH).toString()); TestHelper.hint.waitForExists(waitingTime); TestHelper.pressEnterKey(); UiObject webImage = TestHelper.mDevice.findObject(new UiSelector() .className("android.view.View") .instance(2) .enabled(true)); webImage.waitForExists(waitingTime); Assert.assertTrue(webImage.exists()); // Open recent apps list, then close focus from there TestHelper.pressRecentAppsKey(); UiObject dismissFocusBtn = TestHelper.mDevice.findObject(new UiSelector() .resourceId("com.android.systemui:id/dismiss_task") .descriptionContains("Dismiss Firefox Focus") .enabled(true)); dismissFocusBtn.click(); dismissFocusBtn.waitUntilGone(waitingTime); assertTrue(!dismissFocusBtn.exists()); TestHelper.pressHomeKey(); // Wait for launcher final String launcherPackage = TestHelper.mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); TestHelper.mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Re-Launch the app Context context = InstrumentationRegistry.getInstrumentation() .getTargetContext() .getApplicationContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(FOCUS_DEBUG_APP); mActivityTestRule.launchActivity(intent); // Make sure website can be loaded without issue TestHelper.inlineAutocompleteEditText.waitForExists(waitingTime); Assert.assertTrue(TestHelper.inlineAutocompleteEditText.exists()); TestHelper.inlineAutocompleteEditText.clearTextField(); TestHelper.inlineAutocompleteEditText.setText(webServer.url(TEST_PATH).toString()); TestHelper.hint.waitForExists(waitingTime); TestHelper.pressEnterKey(); webImage.waitForExists(waitingTime); Assert.assertTrue(webImage.exists()); } }
mpl-2.0
ShwethaThammaiah/muzima-android-1
src/main/java/com/muzima/utils/ConnectivityChangeReceiver.java
1124
package com.muzima.utils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.muzima.MuzimaApplication; import com.muzima.api.model.User; import com.muzima.scheduler.RealTimeFormUploader; /** * Created by shwethathammaiah on 07/10/14. */ public class ConnectivityChangeReceiver extends BroadcastReceiver { private static final String TAG = "ConnectivityChangeReceiver"; public ConnectivityChangeReceiver(){ } @Override public void onReceive(final Context context, Intent intent) { Log.i(TAG,"Connectivity change receiver triggered."); if (intent.getExtras() != null) { User authenticatedUser = ((MuzimaApplication) context.getApplicationContext()).getAuthenticatedUser(); if (authenticatedUser != null) { Log.i(TAG,"Device got connected to network. Trying to start Muzima Real time Sync of completed forms."); RealTimeFormUploader.getInstance().uploadAllCompletedForms(context.getApplicationContext()); } } } }
mpl-2.0
miloszpiglas/h2mod
src/main/org/h2/engine/UserDataType.java
1445
/* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.engine; import org.h2.message.DbException; import org.h2.message.Trace; import org.h2.table.Column; import org.h2.table.Table; /** * Represents a domain (user-defined data type). */ public class UserDataType extends DbObjectBase { private Column column; public UserDataType(Database database, int id, String name) { initDbObjectBase(database, id, name, Trace.DATABASE); } @Override public String getCreateSQLForCopy(Table table, String quotedName) { throw DbException.throwInternalError(); } @Override public String getDropSQL() { return "DROP DOMAIN IF EXISTS " + getSQL(); } @Override public String getCreateSQL() { return "CREATE DOMAIN " + getSQL() + " AS " + column.getCreateSQL(); } public Column getColumn() { return column; } @Override public int getType() { return DbObject.USER_DATATYPE; } @Override public void removeChildrenAndResources(Session session) { database.removeMeta(session, getId()); } @Override public void checkRename() { // ok } public void setColumn(Column column) { this.column = column; } }
mpl-2.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/COE/src/ims/coe/forms/assesssleeping/IFormUILogicCode.java
2204
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.coe.forms.assesssleeping; public interface IFormUILogicCode { // No methods yet. }
agpl-3.0
yukoff/concourse-connect
src/main/java/com/concursive/connect/web/modules/documents/portlets/main/SaveFolderAction.java
5122
/* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.documents.portlets.main; import com.concursive.commons.web.mvc.beans.GenericBean; import com.concursive.connect.Constants; import com.concursive.connect.web.modules.documents.dao.FileFolder; import com.concursive.connect.web.modules.login.dao.User; import com.concursive.connect.web.modules.profile.dao.Project; import com.concursive.connect.web.modules.profile.utils.ProjectUtils; import com.concursive.connect.web.portal.IPortletAction; import com.concursive.connect.web.portal.PortalUtils; import static com.concursive.connect.web.portal.PortalUtils.*; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import java.sql.Connection; /** * Save action * * @author matt rajkowski * @created January 24, 2009 */ public class SaveFolderAction implements IPortletAction { public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception { // Determine the project container to use Project project = findProject(request); if (project == null) { throw new Exception("Project is null"); } // Check the user's permissions User user = getUser(request); // Populate any info from the request FileFolder thisRecord = (FileFolder) getFormBean(request, FileFolder.class); // Set default values when saving records thisRecord.setLinkModuleId(Constants.PROJECTS_FILES); thisRecord.setLinkItemId(project.getId()); thisRecord.setModifiedBy(user.getId()); // Determine the database connection to use Connection db = useConnection(request); // Save the record boolean recordInserted = false; int resultCount = -1; if (thisRecord.getId() == -1) { // This is a new record if (!ProjectUtils.hasAccess(project.getId(), user, "project-documents-folders-add")) { throw new PortletException("Unauthorized to add in this project"); } // Prevent hierarchical folder structures to avoid user confusion thisRecord.setParentId(-1); thisRecord.setEnteredBy(user.getId()); recordInserted = thisRecord.insert(db); } else { // This is an existing record if (!ProjectUtils.hasAccess(project.getId(), user, "project-documents-folders-edit")) { throw new PortletException("Unauthorized to edit in this project"); } resultCount = thisRecord.update(db); } if (recordInserted) { //trigger the workflow PortalUtils.processInsertHook(request, thisRecord); } // Check if an error occurred if (!recordInserted && resultCount <= 0) { return thisRecord; } // Index the record PortalUtils.indexAddItem(request, thisRecord); // This call will close panels and perform redirects return (PortalUtils.performRefresh(request, response, "/show/folder/" + thisRecord.getId())); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/therapies/vo/domain/BobathTreatmentVoAssembler.java
18693
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.therapies.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Sean Nesbitt */ public class BobathTreatmentVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.therapies.vo.BobathTreatmentVo copy(ims.therapies.vo.BobathTreatmentVo valueObjectDest, ims.therapies.vo.BobathTreatmentVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_BobathTreatment(valueObjectSrc.getID_BobathTreatment()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // AreaTreated valueObjectDest.setAreaTreated(valueObjectSrc.getAreaTreated()); // Position valueObjectDest.setPosition(valueObjectSrc.getPosition()); // Analysis valueObjectDest.setAnalysis(valueObjectSrc.getAnalysis()); // ClinicalReasoning valueObjectDest.setClinicalReasoning(valueObjectSrc.getClinicalReasoning()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createBobathTreatmentVoCollectionFromBobathTreatment(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.therapies.treatment.domain.objects.BobathTreatment objects. */ public static ims.therapies.vo.BobathTreatmentVoCollection createBobathTreatmentVoCollectionFromBobathTreatment(java.util.Set domainObjectSet) { return createBobathTreatmentVoCollectionFromBobathTreatment(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.therapies.treatment.domain.objects.BobathTreatment objects. */ public static ims.therapies.vo.BobathTreatmentVoCollection createBobathTreatmentVoCollectionFromBobathTreatment(DomainObjectMap map, java.util.Set domainObjectSet) { ims.therapies.vo.BobathTreatmentVoCollection voList = new ims.therapies.vo.BobathTreatmentVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.therapies.treatment.domain.objects.BobathTreatment domainObject = (ims.therapies.treatment.domain.objects.BobathTreatment) iterator.next(); ims.therapies.vo.BobathTreatmentVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.therapies.treatment.domain.objects.BobathTreatment objects. */ public static ims.therapies.vo.BobathTreatmentVoCollection createBobathTreatmentVoCollectionFromBobathTreatment(java.util.List domainObjectList) { return createBobathTreatmentVoCollectionFromBobathTreatment(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.therapies.treatment.domain.objects.BobathTreatment objects. */ public static ims.therapies.vo.BobathTreatmentVoCollection createBobathTreatmentVoCollectionFromBobathTreatment(DomainObjectMap map, java.util.List domainObjectList) { ims.therapies.vo.BobathTreatmentVoCollection voList = new ims.therapies.vo.BobathTreatmentVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.therapies.treatment.domain.objects.BobathTreatment domainObject = (ims.therapies.treatment.domain.objects.BobathTreatment) domainObjectList.get(i); ims.therapies.vo.BobathTreatmentVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.therapies.treatment.domain.objects.BobathTreatment set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractBobathTreatmentSet(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.BobathTreatmentVoCollection voCollection) { return extractBobathTreatmentSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractBobathTreatmentSet(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.BobathTreatmentVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.therapies.vo.BobathTreatmentVo vo = voCollection.get(i); ims.therapies.treatment.domain.objects.BobathTreatment domainObject = BobathTreatmentVoAssembler.extractBobathTreatment(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.therapies.treatment.domain.objects.BobathTreatment list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractBobathTreatmentList(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.BobathTreatmentVoCollection voCollection) { return extractBobathTreatmentList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractBobathTreatmentList(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.BobathTreatmentVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.therapies.vo.BobathTreatmentVo vo = voCollection.get(i); ims.therapies.treatment.domain.objects.BobathTreatment domainObject = BobathTreatmentVoAssembler.extractBobathTreatment(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.therapies.treatment.domain.objects.BobathTreatment object. * @param domainObject ims.therapies.treatment.domain.objects.BobathTreatment */ public static ims.therapies.vo.BobathTreatmentVo create(ims.therapies.treatment.domain.objects.BobathTreatment domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.therapies.treatment.domain.objects.BobathTreatment object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.therapies.vo.BobathTreatmentVo create(DomainObjectMap map, ims.therapies.treatment.domain.objects.BobathTreatment domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.therapies.vo.BobathTreatmentVo valueObject = (ims.therapies.vo.BobathTreatmentVo) map.getValueObject(domainObject, ims.therapies.vo.BobathTreatmentVo.class); if ( null == valueObject ) { valueObject = new ims.therapies.vo.BobathTreatmentVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.therapies.treatment.domain.objects.BobathTreatment */ public static ims.therapies.vo.BobathTreatmentVo insert(ims.therapies.vo.BobathTreatmentVo valueObject, ims.therapies.treatment.domain.objects.BobathTreatment domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.therapies.treatment.domain.objects.BobathTreatment */ public static ims.therapies.vo.BobathTreatmentVo insert(DomainObjectMap map, ims.therapies.vo.BobathTreatmentVo valueObject, ims.therapies.treatment.domain.objects.BobathTreatment domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_BobathTreatment(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // AreaTreated valueObject.setAreaTreated(domainObject.getAreaTreated()); // Position valueObject.setPosition(domainObject.getPosition()); // Analysis valueObject.setAnalysis(domainObject.getAnalysis()); // ClinicalReasoning valueObject.setClinicalReasoning(domainObject.getClinicalReasoning()); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.therapies.treatment.domain.objects.BobathTreatment extractBobathTreatment(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.BobathTreatmentVo valueObject) { return extractBobathTreatment(domainFactory, valueObject, new HashMap()); } public static ims.therapies.treatment.domain.objects.BobathTreatment extractBobathTreatment(ims.domain.ILightweightDomainFactory domainFactory, ims.therapies.vo.BobathTreatmentVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_BobathTreatment(); ims.therapies.treatment.domain.objects.BobathTreatment domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.therapies.treatment.domain.objects.BobathTreatment)domMap.get(valueObject); } // ims.therapies.vo.BobathTreatmentVo ID_BobathTreatment field is unknown domainObject = new ims.therapies.treatment.domain.objects.BobathTreatment(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_BobathTreatment()); if (domMap.get(key) != null) { return (ims.therapies.treatment.domain.objects.BobathTreatment)domMap.get(key); } domainObject = (ims.therapies.treatment.domain.objects.BobathTreatment) domainFactory.getDomainObject(ims.therapies.treatment.domain.objects.BobathTreatment.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_BobathTreatment()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getAreaTreated() != null && valueObject.getAreaTreated().equals("")) { valueObject.setAreaTreated(null); } domainObject.setAreaTreated(valueObject.getAreaTreated()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getPosition() != null && valueObject.getPosition().equals("")) { valueObject.setPosition(null); } domainObject.setPosition(valueObject.getPosition()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getAnalysis() != null && valueObject.getAnalysis().equals("")) { valueObject.setAnalysis(null); } domainObject.setAnalysis(valueObject.getAnalysis()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getClinicalReasoning() != null && valueObject.getClinicalReasoning().equals("")) { valueObject.setClinicalReasoning(null); } domainObject.setClinicalReasoning(valueObject.getClinicalReasoning()); return domainObject; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/AppointmentClinicalNotesRefVoCollection.java
6153
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to RefMan.AppointmentClinicalNotes business object (ID: 1096100059). */ public class AppointmentClinicalNotesRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<AppointmentClinicalNotesRefVo> { private static final long serialVersionUID = 1L; private ArrayList<AppointmentClinicalNotesRefVo> col = new ArrayList<AppointmentClinicalNotesRefVo>(); public final String getBoClassName() { return "ims.RefMan.domain.objects.AppointmentClinicalNotes"; } public ims.domain.IDomainGetter[] getIDomainGetterItems() { ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()]; col.toArray(result); return result; } public boolean add(AppointmentClinicalNotesRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, AppointmentClinicalNotesRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(AppointmentClinicalNotesRefVo instance) { return col.indexOf(instance); } public AppointmentClinicalNotesRefVo get(int index) { return this.col.get(index); } public boolean set(int index, AppointmentClinicalNotesRefVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(AppointmentClinicalNotesRefVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(AppointmentClinicalNotesRefVo instance) { return indexOf(instance) >= 0; } public Object clone() { AppointmentClinicalNotesRefVoCollection clone = new AppointmentClinicalNotesRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((AppointmentClinicalNotesRefVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { return true; } public String[] validate() { return null; } public AppointmentClinicalNotesRefVo[] toArray() { AppointmentClinicalNotesRefVo[] arr = new AppointmentClinicalNotesRefVo[col.size()]; col.toArray(arr); return arr; } public AppointmentClinicalNotesRefVoCollection sort() { return sort(SortOrder.ASCENDING); } public AppointmentClinicalNotesRefVoCollection sort(SortOrder order) { return sort(new AppointmentClinicalNotesRefVoComparator(order)); } @SuppressWarnings("unchecked") public AppointmentClinicalNotesRefVoCollection sort(Comparator comparator) { Collections.sort(this.col, comparator); return this; } public Iterator<AppointmentClinicalNotesRefVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class AppointmentClinicalNotesRefVoComparator implements Comparator { private int direction = 1; public AppointmentClinicalNotesRefVoComparator() { this(SortOrder.ASCENDING); } public AppointmentClinicalNotesRefVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { this.direction = -1; } } public int compare(Object obj1, Object obj2) { AppointmentClinicalNotesRefVo voObj1 = (AppointmentClinicalNotesRefVo)obj1; AppointmentClinicalNotesRefVo voObj2 = (AppointmentClinicalNotesRefVo)obj2; return direction*(voObj1.compareTo(voObj2)); } } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/EAS/src/ims/eas/forms/easrequestimagetransfer/Logic.java
9351
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 4847.21738) // Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved. package ims.eas.forms.easrequestimagetransfer; import java.util.ArrayList; import ims.ccosched.vo.lookups.SeenAt; import ims.configuration.gen.ConfigFlag; import ims.domain.exceptions.StaleObjectException; import ims.eas.forms.easrequestimagetransfer.GenForm.grdImageTransferRow; import ims.eas.vo.EASImageTransferVo; import ims.eas.vo.EASImageTransferVoCollection; import ims.eas.vo.ElectronicActionSheetVo; import ims.framework.Control; import ims.framework.enumerations.FormMode; import ims.framework.exceptions.PresentationLogicException; import ims.oncology.vo.lookups.EASImageType; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; // OnFormOpen method required to bind lookups protected void onFormOpen(Object[] args) throws PresentationLogicException { } /** * Initialise this component */ public void initialise() { // Initialise the summary information too form.getContextMenus().EAS.getProtocolPhaseConfigMenuADDItem().setEnabled(true); form.getContextMenus().EAS.getProtocolPhaseConfigMenuADDItem().setVisible(true); form.getContextMenus().EAS.getProtocolPhaseConfigMenuEDITItem().setEnabled(false); form.getContextMenus().EAS.getProtocolPhaseConfigMenuEDITItem().setVisible(false); form.setMode(FormMode.EDIT); } /** * Set the Electronic Action Sheet for view / edit */ public void setValue(ims.eas.vo.ElectronicActionSheetVo actionSheet) { form.grdImageTransfer().getRows().clear(); if (actionSheet == null) { if (form.getLocalContext().getPatientEAS() != null ) form.getLocalContext().getPatientEAS().setImageTransfers(null); return; } form.getLocalContext().setPatientEAS(actionSheet); // Load the grid with image transfer information from the actionSheet form.ccSummary().initialise(actionSheet.getPrimaryTumour().getPrimaryTumour(), actionSheet.getTreatmentSite().getTreatmentSite(), actionSheet.getProtocol(), actionSheet.getEasStatus().getStatus()); if (actionSheet.getImageTransfers() == null) return; for (EASImageTransferVo transfer : actionSheet.getImageTransfers()) { grdImageTransferRow row = form.grdImageTransfer().getRows().newRow(); row.setcolASite(transfer.getAnatomicalSite()); row.setCellcolASiteTooltip(transfer.getAnatomicalSite()); row.setcolComment(transfer.getLocationTaken()); row.setCellcolCommentTooltip(transfer.getLocationTaken()); if (transfer.getImageTakenAtIsNotNull()) { row.setcolLocation(transfer.getImageTakenAt()); row.setCellcolLocationTooltip(transfer.getImageTakenAt().getText()); } row.setcolDate(transfer.getImageDate()); row.setCellcolDateTooltip(transfer.getImageDate() != null ? transfer.getImageDate().toString(): ""); row.setcolImageType(transfer.getImageType()); row.setCellcolImageTypeTooltip(transfer.getImageType() != null ? transfer.getImageType().getText(): ""); row.setValue(transfer); } updateControlsState(); } /** * Save the given Electronic Action Sheet at component level. Return true on success, otherwise return false */ public Boolean save() { ElectronicActionSheetVo eas = copyScreenToData(); if (!validateData(true)) return false; String errors[] = eas.validate(validateUiRules()); if (errors != null) { engine.showErrors(errors); return false; } try { eas = domain.save(eas); } catch (StaleObjectException e) { engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()); setValue(domain.getEAS(form.getLocalContext().getPatientEAS())); return false; } // Update Local context with newly saved EAS form.getLocalContext().setPatientEAS(eas); return true; } private String[] validateUiRules() { ArrayList<String> listOfErrors = new ArrayList<String>(); for (int i = 0; i < form.grdImageTransfer().getRows().size(); i++) { grdImageTransferRow row = form.grdImageTransfer().getRows().get(i); if (row.getcolLocation() == null) { listOfErrors.add("Please enter Location Taken."); } } int errorCount = listOfErrors.size(); String[] result = new String[errorCount]; for (int x = 0; x < errorCount; x++) result[x] = (String) listOfErrors.get(x); return result; } private boolean validateData(boolean bShowMessages) { return true; } private ElectronicActionSheetVo copyScreenToData() { ElectronicActionSheetVo eas = form.getLocalContext().getPatientEAS(); if (eas == null) // should never really be! eas = new ElectronicActionSheetVo(); // Clear the collection and re-create EASImageTransferVoCollection coll = eas.getImageTransfers(); if (coll == null) coll = new EASImageTransferVoCollection(); else coll.clear(); Boolean removedSetToFalse = Boolean.FALSE; // Build up the image transfer details for (int i=0; i<form.grdImageTransfer().getRows().size(); i++) { grdImageTransferRow row = form.grdImageTransfer().getRows().get(i); EASImageTransferVo transfer = row.getValue(); if (transfer == null) { transfer = new EASImageTransferVo(); eas.setRemovedStat(Boolean.FALSE); removedSetToFalse = Boolean.TRUE; } //WDEV-17643 else if (!removedSetToFalse) { if (Boolean.TRUE.equals(transfer.getImageRequested())) { eas.setRemovedStat(Boolean.TRUE); } else { eas.setRemovedStat(Boolean.FALSE); removedSetToFalse = Boolean.TRUE; } } transfer.setAnatomicalSite(row.getcolASite()); transfer.setImageDate(row.getcolDate()); transfer.setImageTakenAt((SeenAt) row.getcolLocation()); transfer.setImageType((EASImageType) row.getcolImageType()); transfer.setLocationTaken(row.getcolComment()); coll.add(transfer); } eas.setImageTransfers(coll); return eas; } /** * Return the ElectronicActionSheet record */ public ims.eas.vo.ElectronicActionSheetVo getValue() { return (form.getLocalContext().getPatientEAS()); } protected void onContextMenuItemClick(int menuItemID, Control sender) throws PresentationLogicException { switch (menuItemID) { case GenForm.ContextMenus.EASNamespace.ProtocolPhaseConfigMenu.ADD: form.grdImageTransfer().getRows().newRow(true); updateControlsState(); break; case GenForm.ContextMenus.EASNamespace.ProtocolPhaseConfigMenu.REMOVE: form.grdImageTransfer().getRows().remove(form.grdImageTransfer().getSelectedRowIndex()); updateControlsState(); break; } } protected void onGrdImageTransferSelectionChanged() throws PresentationLogicException { updateControlsState(); } private void updateControlsState() { form.getContextMenus().EAS.getProtocolPhaseConfigMenuADDItem().setVisible(form.getMode().equals(FormMode.EDIT)); form.getContextMenus().EAS.getProtocolPhaseConfigMenuREMOVEItem().setVisible(form.grdImageTransfer().getSelectedRow() != null && form.getMode().equals(FormMode.EDIT)); } protected void onGrdImageTransferSelectionCleared() throws PresentationLogicException { updateControlsState(); } }
agpl-3.0
teoincontatto/engine
mongodb/repl/src/test/java/com/torodb/mongodb/repl/oplogreplier/analyzed/UpdateSetAnalyzedOpTest.java
2766
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.torodb.mongodb.repl.oplogreplier.analyzed; import com.torodb.core.language.AttributeReference; import com.torodb.core.logging.DefaultLoggerFactory; import com.torodb.kvdocument.values.KvInteger; import com.torodb.kvdocument.values.KvValue; import com.torodb.mongodb.language.update.SetFieldUpdateAction; import org.apache.logging.log4j.Logger; import java.util.Collections; public class UpdateSetAnalyzedOpTest extends AbstractAnalyzedOpTest<UpdateSetAnalyzedOp> { private static final Logger LOGGER = DefaultLoggerFactory.get(UpdateSetAnalyzedOpTest.class); @Override UpdateSetAnalyzedOp getAnalyzedOp(KvValue<?> mongoDocId) { return new UpdateSetAnalyzedOp(mongoDocId, (oldDoc) -> { return UpdateActionsTool.applyModification(//modification is $set: {a: 3} oldDoc, new SetFieldUpdateAction( Collections.singleton( new AttributeReference.Builder().addObjectKey("a").build()), KvInteger.of(3) ) ); }); } @Override Logger getLogger() { return LOGGER; } //TODO: Callback checks can be improved @Override void andThenInsertTest() { andThenInsert(this::emptyConsumer3, this::emptyBiConsumer); } //TODO: Callback checks can be improved @Override void andThenUpdateModTest() { andThenUpdateMod(this::emptyConsumer3, this::emptyBiConsumer); } //TODO: Callback checks can be improved @Override void andThenUpdateSetTest() { andThenUpdateSet(this::emptyConsumer3, this::emptyBiConsumer); } //TODO: Callback checks can be improved @Override void andThenUpsertModTest() { andThenUpsertMod(this::emptyConsumer3, this::emptyBiConsumer); } //TODO: Callback checks can be improved @Override void andThenUpsertSetTest() { andThenUpsertSet(this::emptyConsumer3, this::emptyBiConsumer); } //TODO: Callback checks can be improved @Override void andThenDeleteTest() { andThenDelete(this::emptyConsumer3, this::emptyBiConsumer); } }
agpl-3.0
aihua/opennms
features/newts/src/main/java/org/opennms/netmgt/newts/support/RedisResourceMetadataCache.java
7652
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2015 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2015 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.newts.support; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import org.nustaq.serialization.FSTConfiguration; import org.opennms.newts.api.Context; import org.opennms.newts.api.Resource; import org.opennms.newts.cassandra.search.ResourceIdSplitter; import org.opennms.newts.cassandra.search.ResourceMetadata; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Transaction; /** * A caching strategy that stores the {@link org.opennms.newts.cassandra.search.ResourceMetadata} in * a Redis database. * * Can be used when the cache needs to be shared amongst several JVMs, or when persistence is required. * * Note that this cache will operate slower than the {@link GuavaSearchableResourceMetadataCache} since * it requires network I/O and serialization/deserialization of the associated structures. However, this * cache will also operate with significantly less memory. * * FST is used for serialization instead Java's default implementation. * * @author jwhite */ public class RedisResourceMetadataCache implements SearchableResourceMetadataCache { private static final String METADATA_PREFIX = "_M"; private static final String SEARCH_PREFIX = "_S"; private static final FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); private static final Joiner m_keyJoiner = Joiner.on(ResourceIdSplitter.SEPARATOR); private final ResourceIdSplitter m_resourceIdSplitter; private final JedisPool m_pool; @Inject public RedisResourceMetadataCache(@Named("redis.hostname") String hostname, @Named("redis.port") Integer port, @Named("newts.writer_threads") Integer numWriterThreads, MetricRegistry registry, ResourceIdSplitter resourceIdSplitter) { Preconditions.checkNotNull(hostname, " hostname argument"); Preconditions.checkNotNull(port, "port argument"); JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMinIdle(numWriterThreads); poolConfig.setMaxTotal(numWriterThreads * 4); m_pool = new JedisPool(poolConfig, hostname, port); Preconditions.checkNotNull(registry, "registry argument"); registry.register(MetricRegistry.name("cache", "size"), new Gauge<Long>() { @Override public Long getValue() { try (Jedis jedis = m_pool.getResource()) { return jedis.dbSize(); } } }); registry.register(MetricRegistry.name("cache", "max-size"), new Gauge<Long>() { @Override public Long getValue() { return 0L; } }); m_resourceIdSplitter = Preconditions.checkNotNull(resourceIdSplitter, "resourceIdSplitter argument"); } @Override public void merge(Context context, Resource resource, ResourceMetadata metadata) { final Optional<ResourceMetadata> o = get(context, resource); try (Jedis jedis = m_pool.getResource()) { if (!o.isPresent()) { final ResourceMetadata newMetadata = new ResourceMetadata(); newMetadata.merge(metadata); final Transaction t = jedis.multi(); final byte[] key = key(METADATA_PREFIX, context.getId(), resource.getId()); t.set(key, conf.asByteArray(newMetadata)); // Index the key, element by element, in order to support calls to getResourceIdsWithPrefix() final List<String> elements = Lists.newArrayList(SEARCH_PREFIX, context.getId()); for (String el : m_resourceIdSplitter.splitIdIntoElements(resource.getId())) { elements.add(el); t.lpush(m_resourceIdSplitter.joinElementsToId(elements).getBytes(), key); } // Update the keys in transaction t.exec(); } else if (o.get().merge(metadata)) { // Update the value stored in the cache if it was changed as a result of the merge jedis.set(key(METADATA_PREFIX, context.getId(), resource.getId()), conf.asByteArray(o.get())); } } } @Override public Optional<ResourceMetadata> get(Context context, Resource resource) { try (Jedis jedis = m_pool.getResource()) { final byte[] bytes = jedis.get(key(METADATA_PREFIX, context.getId(), resource.getId())); return (bytes != null) ? Optional.of((ResourceMetadata)conf.asObject(bytes)): Optional.absent(); } } @Override public void delete(final Context context, final Resource resource) { try (Jedis jedis = m_pool.getResource()) { jedis.del(key(METADATA_PREFIX, context.getId(), resource.getId())); } } @Override public List<String> getResourceIdsWithPrefix(Context context, String resourceIdPrefix) { try (Jedis jedis = m_pool.getResource()) { final List<String> elements = Lists.newArrayList(SEARCH_PREFIX, context.getId()); elements.addAll(m_resourceIdSplitter.splitIdIntoElements(resourceIdPrefix)); return jedis.lrange(m_resourceIdSplitter.joinElementsToId(elements).getBytes(), 0, -1).stream() .map(bytes -> resourceId(METADATA_PREFIX, context.getId(), bytes)) .collect(Collectors.toList()); } } /** * Creates a unique key for the (prefix, contextId, resourceId) tuple */ private static byte[] key(String prefix, String contextId, String resourceId) { return m_keyJoiner.join(prefix, contextId, resourceId).getBytes(); } /** * Extracts the resource id from a key produced by {@link #key(String, String, String)} */ private String resourceId(String prefix, String contextId, byte[] key) { return new String(key).substring(prefix.length() + contextId.length() + 2); } }
agpl-3.0
a-gogo/agogo
AMW_shakedown/AMW_stp_jdbc/src/main/java/ch/puzzle/itc/mobiliar/stp/db/DB_STP.java
1156
package ch.puzzle.itc.mobiliar.stp.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DB_STP { /** * @param args * takes two arguments: The jdbc connection string, the user name * and the password, additionally requires the jdbc driver in its * classpath */ public static void main(String[] args) { if (args.length > 2) { String jdbcConnectionString = args[0]; String userName = args[1]; String password = args[2]; Connection conn; try { conn = DriverManager.getConnection(jdbcConnectionString, userName, password); conn.close(); System.out.println("Successfully connected to database ("+jdbcConnectionString+" with user "+userName+")!"); System.exit(0); } catch (SQLException e) { System.err.println("Was not able to connect to database ("+jdbcConnectionString+" with user "+userName+")!" + e.getMessage()); System.exit(1); } } else { System.out.println("Missing parameters! The jdbc connection string, the username and the password is needed to be passed as arguments!"); System.exit(1); } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/VSPupilsCollection.java
8197
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to core.vitals.Pupils business object (ID: 1022100009). */ public class VSPupilsCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<VSPupils> { private static final long serialVersionUID = 1L; private ArrayList<VSPupils> col = new ArrayList<VSPupils>(); public String getBoClassName() { return "ims.core.vitals.domain.objects.Pupils"; } public boolean add(VSPupils value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, VSPupils value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(VSPupils instance) { return col.indexOf(instance); } public VSPupils get(int index) { return this.col.get(index); } public boolean set(int index, VSPupils value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(VSPupils instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(VSPupils instance) { return indexOf(instance) >= 0; } public Object clone() { VSPupilsCollection clone = new VSPupilsCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((VSPupils)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public VSPupilsCollection sort() { return sort(SortOrder.ASCENDING); } public VSPupilsCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public VSPupilsCollection sort(SortOrder order) { return sort(new VSPupilsComparator(order)); } public VSPupilsCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new VSPupilsComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public VSPupilsCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.core.vitals.vo.PupilsRefVoCollection toRefVoCollection() { ims.core.vitals.vo.PupilsRefVoCollection result = new ims.core.vitals.vo.PupilsRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public VSPupils[] toArray() { VSPupils[] arr = new VSPupils[col.size()]; col.toArray(arr); return arr; } public Iterator<VSPupils> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class VSPupilsComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public VSPupilsComparator() { this(SortOrder.ASCENDING); } public VSPupilsComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public VSPupilsComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { VSPupils voObj1 = (VSPupils)obj1; VSPupils voObj2 = (VSPupils)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.core.vo.beans.VSPupilsBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.core.vo.beans.VSPupilsBean[] getBeanCollectionArray() { ims.core.vo.beans.VSPupilsBean[] result = new ims.core.vo.beans.VSPupilsBean[col.size()]; for(int i = 0; i < col.size(); i++) { VSPupils vo = ((VSPupils)col.get(i)); result[i] = (ims.core.vo.beans.VSPupilsBean)vo.getBean(); } return result; } public static VSPupilsCollection buildFromBeanCollection(java.util.Collection beans) { VSPupilsCollection coll = new VSPupilsCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.core.vo.beans.VSPupilsBean)iter.next()).buildVo()); } return coll; } public static VSPupilsCollection buildFromBeanCollection(ims.core.vo.beans.VSPupilsBean[] beans) { VSPupilsCollection coll = new VSPupilsCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
agpl-3.0
JanMarvin/rstudio
src/gwt/src/org/rstudio/studio/client/application/ui/impl/header/MenubarPanel.java
2002
/* * MenubarPanel.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.application.ui.impl.header; import com.google.gwt.core.client.GWT; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.resources.client.ImageResource.ImageOptions; import com.google.gwt.resources.client.ImageResource.RepeatStyle; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; public class MenubarPanel extends Composite { static { ((Resources)GWT.create(Resources.class)).styles().ensureInjected(); } interface Resources extends ClientBundle { @Source("MenubarPanel.css") Styles styles(); ImageResource menubarLeft(); @ImageOptions(repeatStyle = RepeatStyle.Horizontal) ImageResource menubarTile(); ImageResource menubarRight(); } interface Styles extends CssResource { String panel(); String left(); String center(); String right(); } interface MyUiBinder extends UiBinder<Widget, MenubarPanel> {} public MenubarPanel(Widget widget) { widget_ = widget; initWidget(((MyUiBinder)GWT.create(MyUiBinder.class)).createAndBindUi(this)); } @UiField(provided = true) final Widget widget_; }
agpl-3.0
openhealthcare/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/LocationMinVoAssembler.java
15733
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author George Cristian Josan */ public class LocationMinVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.LocationMinVo copy(ims.core.vo.LocationMinVo valueObjectDest, ims.core.vo.LocationMinVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_Location(valueObjectSrc.getID_Location()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // Name valueObjectDest.setName(valueObjectSrc.getName()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createLocationMinVoCollectionFromLocation(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects. */ public static ims.core.vo.LocationMinVoCollection createLocationMinVoCollectionFromLocation(java.util.Set domainObjectSet) { return createLocationMinVoCollectionFromLocation(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects. */ public static ims.core.vo.LocationMinVoCollection createLocationMinVoCollectionFromLocation(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.LocationMinVoCollection voList = new ims.core.vo.LocationMinVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) iterator.next(); ims.core.vo.LocationMinVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects. */ public static ims.core.vo.LocationMinVoCollection createLocationMinVoCollectionFromLocation(java.util.List domainObjectList) { return createLocationMinVoCollectionFromLocation(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects. */ public static ims.core.vo.LocationMinVoCollection createLocationMinVoCollectionFromLocation(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.LocationMinVoCollection voList = new ims.core.vo.LocationMinVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) domainObjectList.get(i); ims.core.vo.LocationMinVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.resource.place.domain.objects.Location set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocationMinVoCollection voCollection) { return extractLocationSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocationMinVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.core.vo.LocationMinVo vo = voCollection.get(i); ims.core.resource.place.domain.objects.Location domainObject = LocationMinVoAssembler.extractLocation(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.resource.place.domain.objects.Location list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocationMinVoCollection voCollection) { return extractLocationList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocationMinVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.core.vo.LocationMinVo vo = voCollection.get(i); ims.core.resource.place.domain.objects.Location domainObject = LocationMinVoAssembler.extractLocation(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.resource.place.domain.objects.Location object. * @param domainObject ims.core.resource.place.domain.objects.Location */ public static ims.core.vo.LocationMinVo create(ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.resource.place.domain.objects.Location object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.LocationMinVo create(DomainObjectMap map, ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.LocationMinVo valueObject = (ims.core.vo.LocationMinVo) map.getValueObject(domainObject, ims.core.vo.LocationMinVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.LocationMinVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.resource.place.domain.objects.Location */ public static ims.core.vo.LocationMinVo insert(ims.core.vo.LocationMinVo valueObject, ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.resource.place.domain.objects.Location */ public static ims.core.vo.LocationMinVo insert(DomainObjectMap map, ims.core.vo.LocationMinVo valueObject, ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_Location(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // Name valueObject.setName(domainObject.getName()); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocationMinVo valueObject) { return extractLocation(domainFactory, valueObject, new HashMap()); } public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocationMinVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_Location(); ims.core.resource.place.domain.objects.Location domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject); } // ims.core.vo.LocationMinVo ID_Location field is unknown domainObject = new ims.core.resource.place.domain.objects.Location(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location()); if (domMap.get(key) != null) { return (ims.core.resource.place.domain.objects.Location)domMap.get(key); } domainObject = (ims.core.resource.place.domain.objects.Location) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_Location()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getName() != null && valueObject.getName().equals("")) { valueObject.setName(null); } domainObject.setName(valueObject.getName()); return domainObject; } }
agpl-3.0