repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
dolphinzhang/framework
contract/src/main/java/org/dol/api/Api.java
404
package org.dol.api; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Api { String name() default ""; boolean ignore() default false; String code() default ""; String value() default ""; // aka code String desc() default ""; String permission() default ""; String[] authors() default ""; }
mit
sjfloat/cyclops
cyclops-base/src/test/java/com/aol/cyclops/lambda/monads/UnwrapTest.java
1655
package com.aol.cyclops.lambda.monads; import static com.aol.cyclops.lambda.api.AsAnyM.anyM; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; public class UnwrapTest { @Test public void unwrap(){ Stream<String> stream = anyM("hello","world").asSequence().unwrapStream(); assertThat(stream.collect(Collectors.toList()),equalTo(Arrays.asList("hello","world"))); } @Test public void unwrapOptional(){ Optional<List<String>> stream = anyM("hello","world") .asSequence() .unwrapOptional(); assertThat(stream.get(),equalTo(Arrays.asList("hello","world"))); } @Test public void unwrapOptionalList(){ Optional<List<String>> stream = anyM(Optional.of(Arrays.asList("hello","world"))) .<String>toSequence() .unwrapOptional(); assertThat(stream.get(),equalTo(Arrays.asList("hello","world"))); } @Test public void unwrapCompletableFuture(){ CompletableFuture<List<String>> cf = anyM("hello","world") .asSequence() .unwrapCompletableFuture(); assertThat(cf.join(),equalTo(Arrays.asList("hello","world"))); } @Test public void unwrapCompletableFutureList(){ CompletableFuture<List<String>> cf = anyM(CompletableFuture.completedFuture(Arrays.asList("hello","world"))) .<String>toSequence() .unwrapCompletableFuture(); assertThat(cf.join(),equalTo(Arrays.asList("hello","world"))); } }
mit
jblindsay/jblindsay.github.io
ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/ChangeVectorAnalysis.java
14439
/* * Copyright (C) 2011-2012 Dr. John Lindsay <jlindsay@uoguelph.ca> * * 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 plugins; import java.util.Date; import whitebox.geospatialfiles.WhiteboxRaster; import whitebox.geospatialfiles.WhiteboxRasterBase.DataScale; import whitebox.geospatialfiles.WhiteboxRasterInfo; import whitebox.interfaces.WhiteboxPlugin; import whitebox.interfaces.WhiteboxPluginHost; import whitebox.utilities.BitOps; /** * Change Vector Analysis (CVA) is a change detection method that characterizes the magnitude and change direction in spectral space between two times. * @author Dr. John Lindsay email: jlindsay@uoguelph.ca */ public class ChangeVectorAnalysis implements WhiteboxPlugin { private WhiteboxPluginHost myHost = null; private String[] args; /** * Used to retrieve the plugin tool's name. This is a short, unique name containing no spaces. * @return String containing plugin name. */ @Override public String getName() { return "ChangeVectorAnalysis"; } /** * Used to retrieve the plugin tool's descriptive name. This can be a longer name (containing spaces) and is used in the interface to list the tool. * @return String containing the plugin descriptive name. */ @Override public String getDescriptiveName() { return "Change Vector Analysis (CVA)"; } /** * Used to retrieve a short description of what the plugin tool does. * @return String containing the plugin's description. */ @Override public String getToolDescription() { return "Performs a change vector analysis on a two-date multi-spectral dataset."; } /** * Used to identify which toolboxes this plugin tool should be listed in. * @return Array of Strings. */ @Override public String[] getToolbox() { String[] ret = {"ChangeDetection"}; return ret; } /** * Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the class * that the plugin will send all feedback messages, progress updates, and return objects. * @param host The WhiteboxPluginHost that called the plugin tool. */ @Override public void setPluginHost(WhiteboxPluginHost host) { myHost = host; } /** * Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. * @param feedback String containing the text to display. */ private void showFeedback(String message) { if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } } /** * Used to communicate a return object from a plugin tool to the main Whitebox user-interface. * @return Object, such as an output WhiteboxRaster. */ private void returnData(Object ret) { if (myHost != null) { myHost.returnData(ret); } } private int previousProgress = 0; private String previousProgressLabel = ""; /** * Used to communicate a progress update between a plugin tool and the main Whitebox user interface. * @param progressLabel A String to use for the progress label. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(String progressLabel, int progress) { if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel, progress); } previousProgress = progress; previousProgressLabel = progressLabel; } /** * Used to communicate a progress update between a plugin tool and the main Whitebox user interface. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(int progress) { if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress = progress; } /** * Sets the arguments (parameters) used by the plugin. * @param args An array of string arguments. */ @Override public void setArgs(String[] args) { this.args = args.clone(); } private boolean cancelOp = false; /** * Used to communicate a cancel operation from the Whitebox GUI. * @param cancel Set to true if the plugin should be canceled. */ @Override public void setCancelOp(boolean cancel) { cancelOp = cancel; } private void cancelOperation() { showFeedback("Operation cancelled."); updateProgress("Progress: ", 0); } private boolean amIActive = false; /** * Used by the Whitebox GUI to tell if this plugin is still running. * @return a boolean describing whether or not the plugin is actively being used. */ @Override public boolean isActive() { return amIActive; } /** * Used to execute this plugin tool. */ @Override public void run() { amIActive = true; String inputFilesDate1String = null; String inputFilesDate2String = null; String[] imageFilesDate1 = null; String[] imageFilesDate2 = null; String outputHeader = null; String outputHeaderDirection = null; WhiteboxRasterInfo[] date1Images = null; WhiteboxRasterInfo[] date2Images = null; int nCols = 0; int nRows = 0; double z; int numImages; int progress = 0; int col, row; int a, i, j; double[][] data1; double[][] data2; double noData = -32768; double dist, direction; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } // read the input parameters inputFilesDate1String = args[0]; inputFilesDate2String = args[1]; outputHeader = args[2]; outputHeaderDirection = args[3]; try { // deal with the input images imageFilesDate1 = inputFilesDate1String.split(";"); imageFilesDate2 = inputFilesDate2String.split(";"); numImages = imageFilesDate1.length; if (imageFilesDate2.length != numImages) { showFeedback("The number of specified images must be the same for both dates."); return; } date1Images = new WhiteboxRasterInfo[numImages]; date2Images = new WhiteboxRasterInfo[numImages]; double[] date1NoDataValues = new double[numImages]; double[] date2NoDataValues = new double[numImages]; for (i = 0; i < numImages; i++) { date1Images[i] = new WhiteboxRasterInfo(imageFilesDate1[i]); date2Images[i] = new WhiteboxRasterInfo(imageFilesDate2[i]); if (i == 0) { nCols = date1Images[i].getNumberColumns(); nRows = date1Images[i].getNumberRows(); noData = date1Images[i].getNoDataValue(); if (date2Images[i].getNumberColumns() != nCols || date2Images[i].getNumberRows() != nRows) { showFeedback("All input images must have the same dimensions (rows and columns)."); return; } } else { if (date1Images[i].getNumberColumns() != nCols || date1Images[i].getNumberRows() != nRows) { showFeedback("All input images must have the same dimensions (rows and columns)."); return; } if (date2Images[i].getNumberColumns() != nCols || date2Images[i].getNumberRows() != nRows) { showFeedback("All input images must have the same dimensions (rows and columns)."); return; } } date1NoDataValues[i] = date1Images[i].getNoDataValue(); date2NoDataValues[i] = date2Images[i].getNoDataValue(); } data1 = new double[numImages][]; data2 = new double[numImages][]; double[] directionArray = new double[numImages]; for (i = 0; i < numImages; i++) { directionArray[i] = Math.pow(2, i); } // now set up the output image WhiteboxRaster output = new WhiteboxRaster(outputHeader, "rw", imageFilesDate1[0], WhiteboxRaster.DataType.FLOAT, 0); output.setPreferredPalette("spectrum.pal"); WhiteboxRaster outputDir = new WhiteboxRaster(outputHeaderDirection, "rw", imageFilesDate1[0], WhiteboxRaster.DataType.INTEGER, 0); outputDir.setDataScale(DataScale.CATEGORICAL); outputDir.setPreferredPalette("qual.pal"); for (row = 0; row < nRows; row++) { for (i = 0; i < numImages; i++) { data1[i] = date1Images[i].getRowValues(row); data2[i] = date2Images[i].getRowValues(row); } for (col = 0; col < nCols; col++) { dist = 0; direction = 0; a = 0; for (i = 0; i < numImages; i++) { if (data1[i][col] != date1NoDataValues[i] && data2[i][col] != date2NoDataValues[i]) { z = (data2[i][col] - data1[i][col]); dist += z * z; a++; if (z >= 0) { direction += directionArray[i]; } } } if (a > 0) { output.setValue(row, col, Math.sqrt(dist)); outputDir.setValue(row, col, direction); } else { output.setValue(row, col, noData); outputDir.setValue(row, col, noData); } } if (cancelOp) { cancelOperation(); return; } progress = (int) (100f * row / (nRows - 1)); updateProgress(progress); } for (i = 0; i < numImages; i++) { date1Images[i].close(); date2Images[i].close(); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); output.close(); outputDir.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputDir.addMetadataEntry("Created on " + new Date()); outputDir.close(); // returning a header file string displays the image. returnData(outputHeader); returnData(outputHeaderDirection); // print out a key for interpreting the direction image String ret = "Key For Interpreting The CVA Direction Image:\n\n\tDirection of Change (+ or -)\nValue"; for (i = 0; i < numImages; i++) { ret += "\tBand" + (i + 1) ; } ret += "\n"; String line = ""; for (a = 0; a < (2 * Math.pow(2, (numImages - 1))); a++) { line = a + "\t"; for (i = 0; i < numImages; i++) { if (BitOps.checkBit(a, i)) { line += "+\t"; } else { line += "-\t"; } } ret += line + "\n"; } returnData(ret); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(), e); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } } // // this is only used for debugging the tool // public static void main(String[] args) { // kMeansClassification kmc = new kMeansClassification(); // args = new String[5]; // args[0] = "/Users/johnlindsay/Documents/Teaching/GEOG3420/Winter 2012/Labs/Lab1/Data/LE70180302002142EDC00/band1 clipped.dep;/Users/johnlindsay/Documents/Teaching/GEOG3420/Winter 2012/Labs/Lab1/Data/LE70180302002142EDC00/band2 clipped.dep;/Users/johnlindsay/Documents/Teaching/GEOG3420/Winter 2012/Labs/Lab1/Data/LE70180302002142EDC00/band3 clipped.dep;/Users/johnlindsay/Documents/Teaching/GEOG3420/Winter 2012/Labs/Lab1/Data/LE70180302002142EDC00/band4 clipped.dep;/Users/johnlindsay/Documents/Teaching/GEOG3420/Winter 2012/Labs/Lab1/Data/LE70180302002142EDC00/band5 clipped.dep;"; // args[1] = "/Users/johnlindsay/Documents/Teaching/GEOG3420/Winter 2012/Labs/Lab1/Data/LE70180302002142EDC00/tmp1.dep"; // args[2] = "10"; // args[3] = "25"; // args[4] = "3"; // // kmc.setArgs(args); // kmc.run(); // // } }
mit
Half-Shot/FarnApp
src/android/support/v4/widget/SlidingPaneLayout$AccessibilityDelegate.java
4479
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package android.support.v4.widget; import android.graphics.Rect; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; // Referenced classes of package android.support.v4.widget: // SlidingPaneLayout class this._cls0 extends AccessibilityDelegateCompat { private final Rect mTmpRect = new Rect(); final SlidingPaneLayout this$0; private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat accessibilitynodeinfocompat, AccessibilityNodeInfoCompat accessibilitynodeinfocompat1) { Rect rect = mTmpRect; accessibilitynodeinfocompat1.getBoundsInParent(rect); accessibilitynodeinfocompat.setBoundsInParent(rect); accessibilitynodeinfocompat1.getBoundsInScreen(rect); accessibilitynodeinfocompat.setBoundsInScreen(rect); accessibilitynodeinfocompat.setVisibleToUser(accessibilitynodeinfocompat1.isVisibleToUser()); accessibilitynodeinfocompat.setPackageName(accessibilitynodeinfocompat1.getPackageName()); accessibilitynodeinfocompat.setClassName(accessibilitynodeinfocompat1.getClassName()); accessibilitynodeinfocompat.setContentDescription(accessibilitynodeinfocompat1.getContentDescription()); accessibilitynodeinfocompat.setEnabled(accessibilitynodeinfocompat1.isEnabled()); accessibilitynodeinfocompat.setClickable(accessibilitynodeinfocompat1.isClickable()); accessibilitynodeinfocompat.setFocusable(accessibilitynodeinfocompat1.isFocusable()); accessibilitynodeinfocompat.setFocused(accessibilitynodeinfocompat1.isFocused()); accessibilitynodeinfocompat.setAccessibilityFocused(accessibilitynodeinfocompat1.isAccessibilityFocused()); accessibilitynodeinfocompat.setSelected(accessibilitynodeinfocompat1.isSelected()); accessibilitynodeinfocompat.setLongClickable(accessibilitynodeinfocompat1.isLongClickable()); accessibilitynodeinfocompat.addAction(accessibilitynodeinfocompat1.getActions()); accessibilitynodeinfocompat.setMovementGranularities(accessibilitynodeinfocompat1.getMovementGranularities()); } public boolean filter(View view) { return isDimmed(view); } public void onInitializeAccessibilityEvent(View view, AccessibilityEvent accessibilityevent) { super.onInitializeAccessibilityEvent(view, accessibilityevent); accessibilityevent.setClassName(android/support/v4/widget/SlidingPaneLayout.getName()); } public void onInitializeAccessibilityNodeInfo(View view, AccessibilityNodeInfoCompat accessibilitynodeinfocompat) { AccessibilityNodeInfoCompat accessibilitynodeinfocompat1 = AccessibilityNodeInfoCompat.obtain(accessibilitynodeinfocompat); super.onInitializeAccessibilityNodeInfo(view, accessibilitynodeinfocompat1); copyNodeInfoNoChildren(accessibilitynodeinfocompat, accessibilitynodeinfocompat1); accessibilitynodeinfocompat1.recycle(); accessibilitynodeinfocompat.setClassName(android/support/v4/widget/SlidingPaneLayout.getName()); accessibilitynodeinfocompat.setSource(view); android.view.ViewParent viewparent = ViewCompat.getParentForAccessibility(view); if (viewparent instanceof View) { accessibilitynodeinfocompat.setParent((View)viewparent); } int i = getChildCount(); for (int j = 0; j < i; j++) { View view1 = getChildAt(j); if (!filter(view1) && view1.getVisibility() == 0) { ViewCompat.setImportantForAccessibility(view1, 1); accessibilitynodeinfocompat.addChild(view1); } } } public boolean onRequestSendAccessibilityEvent(ViewGroup viewgroup, View view, AccessibilityEvent accessibilityevent) { if (!filter(view)) { return super.onRequestSendAccessibilityEvent(viewgroup, view, accessibilityevent); } else { return false; } } () { this$0 = SlidingPaneLayout.this; super(); } }
mit
mkchung/react-native-alipay-no-utdid
android/src/main/java/com/yunpeng/alipay/StreamTool.java
754
package com.yunpeng.alipay; import java.io.ByteArrayOutputStream; import java.io.InputStream; /** * Created by m2mbob on 16/5/8. */ public class StreamTool { /** * 从输入流中读取数据 * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inStream.read(buffer)) !=-1 ){ outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray();//网页的二进制数据 outStream.close(); inStream.close(); return data; } }
mit
PerMalmberg/CmdParser4J
src/cmdparser4j/limits/UnboundStringLimit.java
234
// Copyright (c) 2016 Per Malmberg // Licensed under MIT, see LICENSE file. package cmdparser4j.limits; public class UnboundStringLimit extends StringLengthLimit { public UnboundStringLimit() { super(1, Integer.MAX_VALUE); } }
mit
LCA311/leoapp-sources
app/src/main/java/de/slgdev/leoapp/service/StubProvider.java
1345
package de.slgdev.leoapp.service; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; /** * StubProvider. * * Da das SyncAdapter Framework einen ContentProvider benötigt, alle wichtigen Daten aber in SQLite gespeichert werden, * ist diese Klasse lediglich ein Stub ohne wirkliche Funktionalität. * * @author Gianni * @since 0.6.9 * @version 2017.0712 */ public class StubProvider extends ContentProvider { @Override public boolean onCreate() { return true; } @Override public String getType(@NonNull Uri uri) { return null; } @Override public Cursor query( @NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } @Override public Uri insert(@NonNull Uri uri, ContentValues values) { return null; } @Override public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) { return 0; } public int update( @NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } }
mit
Baltasarq/Gia
src/JDom/src/java/org/jdom/input/SAXHandler.java
34859
/*-- $Id: SAXHandler.java,v 1.73 2007/11/10 05:29:00 jhunter Exp $ Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the disclaimer that follows these conditions in the documentation and/or other materials provided with the distribution. 3. The name "JDOM" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact <request_AT_jdom_DOT_org>. 4. Products derived from this software may not be called "JDOM", nor may "JDOM" appear in their name, without prior written permission from the JDOM Project Management <request_AT_jdom_DOT_org>. In addition, we request (but do not require) that you include in the end-user documentation provided with the redistribution and/or in the software itself an acknowledgement equivalent to the following: "This product includes software developed by the JDOM Project (http://www.jdom.org/)." Alternatively, the acknowledgment may be graphical using the logos available at http://www.jdom.org/images/logos. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the JDOM Project and was originally created by Jason Hunter <jhunter_AT_jdom_DOT_org> and Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information on the JDOM Project, please see <http://www.jdom.org/>. */ package org.jdom.input; import java.util.*; import org.jdom.*; import org.xml.sax.*; import org.xml.sax.ext.*; import org.xml.sax.helpers.*; /** * A support class for {@link SAXBuilder}. * * @version $Revision: 1.73 $, $Date: 2007/11/10 05:29:00 $ * @author Brett McLaughlin * @author Jason Hunter * @author Philip Nelson * @author Bradley S. Huffman * @author phil@triloggroup.com */ public class SAXHandler extends DefaultHandler implements LexicalHandler, DeclHandler, DTDHandler { private static final String CVS_ID = "@(#) $RCSfile: SAXHandler.java,v $ $Revision: 1.73 $ $Date: 2007/11/10 05:29:00 $ $Name: jdom_1_1 $"; /** Hash table to map SAX attribute type names to JDOM attribute types. */ private static final Map attrNameToTypeMap = new HashMap(13); /** <code>Document</code> object being built */ private Document document; /** <code>Element</code> object being built */ private Element currentElement; /** Indicator of where in the document we are */ private boolean atRoot; /** Indicator of whether we are in the DocType. Note that the DTD consists * of both the internal subset (inside the <!DOCTYPE> tag) and the * external subset (in a separate .dtd file). */ private boolean inDTD = false; /** Indicator of whether we are in the internal subset */ private boolean inInternalSubset = false; /** Indicator of whether we previously were in a CDATA */ private boolean previousCDATA = false; /** Indicator of whether we are in a CDATA */ private boolean inCDATA = false; /** Indicator of whether we should expand entities */ private boolean expand = true; /** Indicator of whether we are actively suppressing (non-expanding) a current entity */ private boolean suppress = false; /** How many nested entities we're currently within */ private int entityDepth = 0; // XXX may not be necessary anymore? /** Temporary holder for namespaces that have been declared with * startPrefixMapping, but are not yet available on the element */ private List declaredNamespaces; /** Temporary holder for the internal subset */ private StringBuffer internalSubset = new StringBuffer(); /** Temporary holder for Text and CDATA */ private TextBuffer textBuffer = new TextBuffer(); /** The external entities defined in this document */ private Map externalEntities; /** The JDOMFactory used for JDOM object creation */ private JDOMFactory factory; /** Whether to ignore ignorable whitespace */ private boolean ignoringWhite = false; /** Whether to ignore text containing all whitespace */ private boolean ignoringBoundaryWhite = false; /** The SAX Locator object provided by the parser */ private Locator locator; /** * Class initializer: Populate a table to translate SAX attribute * type names into JDOM attribute type value (integer). * <p> * <b>Note that all the mappings defined below are compliant with * the SAX 2.0 specification exception for "ENUMERATION" with is * specific to Crimson 1.1.X and Xerces 2.0.0-betaX which report * attributes of enumerated types with a type "ENUMERATION" * instead of the expected "NMTOKEN". * </p> * <p> * Note also that Xerces 1.4.X is not SAX 2.0 compliant either * but handling its case requires * {@link #getAttributeType specific code}. * </p> */ static { attrNameToTypeMap.put("CDATA", new Integer(Attribute.CDATA_TYPE)); attrNameToTypeMap.put("ID", new Integer(Attribute.ID_TYPE)); attrNameToTypeMap.put("IDREF", new Integer(Attribute.IDREF_TYPE)); attrNameToTypeMap.put("IDREFS", new Integer(Attribute.IDREFS_TYPE)); attrNameToTypeMap.put("ENTITY", new Integer(Attribute.ENTITY_TYPE)); attrNameToTypeMap.put("ENTITIES", new Integer(Attribute.ENTITIES_TYPE)); attrNameToTypeMap.put("NMTOKEN", new Integer(Attribute.NMTOKEN_TYPE)); attrNameToTypeMap.put("NMTOKENS", new Integer(Attribute.NMTOKENS_TYPE)); attrNameToTypeMap.put("NOTATION", new Integer(Attribute.NOTATION_TYPE)); attrNameToTypeMap.put("ENUMERATION", new Integer(Attribute.ENUMERATED_TYPE)); } /** * This will create a new <code>SAXHandler</code> that listens to SAX * events and creates a JDOM Document. The objects will be constructed * using the default factory. */ public SAXHandler() { this(null); } /** * This will create a new <code>SAXHandler</code> that listens to SAX * events and creates a JDOM Document. The objects will be constructed * using the provided factory. * * @param factory <code>JDOMFactory</code> to be used for constructing * objects */ public SAXHandler(JDOMFactory factory) { if (factory != null) { this.factory = factory; } else { this.factory = new DefaultJDOMFactory(); } atRoot = true; declaredNamespaces = new ArrayList(); externalEntities = new HashMap(); document = this.factory.document(null); } /** * Pushes an element onto the tree under construction. Allows subclasses * to put content under a dummy root element which is useful for building * content that would otherwise be a non-well formed document. * * @param element root element under which content will be built */ protected void pushElement(Element element) { if (atRoot) { document.setRootElement(element); // XXX should we use a factory call? atRoot = false; } else { factory.addContent(currentElement, element); } currentElement = element; } /** * Returns the document. Should be called after parsing is complete. * * @return <code>Document</code> - Document that was built */ public Document getDocument() { return document; } /** * Returns the factory used for constructing objects. * * @return <code>JDOMFactory</code> - the factory used for * constructing objects. * * @see #SAXHandler(org.jdom.JDOMFactory) */ public JDOMFactory getFactory() { return factory; } /** * This sets whether or not to expand entities during the build. * A true means to expand entities as normal content. A false means to * leave entities unexpanded as <code>EntityRef</code> objects. The * default is true. * * @param expand <code>boolean</code> indicating whether entity expansion * should occur. */ public void setExpandEntities(boolean expand) { this.expand = expand; } /** * Returns whether or not entities will be expanded during the * build. * * @return <code>boolean</code> - whether entity expansion * will occur during build. * * @see #setExpandEntities */ public boolean getExpandEntities() { return expand; } /** * Specifies whether or not the parser should elminate whitespace in * element content (sometimes known as "ignorable whitespace") when * building the document. Only whitespace which is contained within * element content that has an element only content model will be * eliminated (see XML Rec 3.2.1). For this setting to take effect * requires that validation be turned on. The default value of this * setting is <code>false</code>. * * @param ignoringWhite Whether to ignore ignorable whitespace */ public void setIgnoringElementContentWhitespace(boolean ignoringWhite) { this.ignoringWhite = ignoringWhite; } /** * Specifies whether or not the parser should elminate text() nodes * containing only whitespace when building the document. See * {@link SAXBuilder#setIgnoringBoundaryWhitespace(boolean)}. * * @param ignoringBoundaryWhite Whether to ignore only whitespace content */ public void setIgnoringBoundaryWhitespace(boolean ignoringBoundaryWhite) { this.ignoringBoundaryWhite = ignoringBoundaryWhite; } /** * Returns whether or not the parser will elminate element content * containing only whitespace. * * @return <code>boolean</code> - whether only whitespace content will * be ignored during build. * * @see #setIgnoringBoundaryWhitespace */ public boolean getIgnoringBoundaryWhitespace() { return ignoringBoundaryWhite; } /** * Returns whether or not the parser will elminate whitespace in * element content (sometimes known as "ignorable whitespace") when * building the document. * * @return <code>boolean</code> - whether ignorable whitespace will * be ignored during build. * * @see #setIgnoringElementContentWhitespace */ public boolean getIgnoringElementContentWhitespace() { return ignoringWhite; } public void startDocument() { if (locator != null) { document.setBaseURI(locator.getSystemId()); } } /** * This is called when the parser encounters an external entity * declaration. * * @param name entity name * @param publicID public id * @param systemID system id * @throws SAXException when things go wrong */ public void externalEntityDecl(String name, String publicID, String systemID) throws SAXException { // Store the public and system ids for the name externalEntities.put(name, new String[]{publicID, systemID}); if (!inInternalSubset) return; internalSubset.append(" <!ENTITY ") .append(name); appendExternalId(publicID, systemID); internalSubset.append(">\n"); } /** * This handles an attribute declaration in the internal subset. * * @param eName <code>String</code> element name of attribute * @param aName <code>String</code> attribute name * @param type <code>String</code> attribute type * @param valueDefault <code>String</code> default value of attribute * @param value <code>String</code> value of attribute * @throws SAXException */ public void attributeDecl(String eName, String aName, String type, String valueDefault, String value) throws SAXException { if (!inInternalSubset) return; internalSubset.append(" <!ATTLIST ") .append(eName) .append(' ') .append(aName) .append(' ') .append(type) .append(' '); if (valueDefault != null) { internalSubset.append(valueDefault); } else { internalSubset.append('\"') .append(value) .append('\"'); } if ((valueDefault != null) && (valueDefault.equals("#FIXED"))) { internalSubset.append(" \"") .append(value) .append('\"'); } internalSubset.append(">\n"); } /** * Handle an element declaration in a DTD. * * @param name <code>String</code> name of element * @param model <code>String</code> model of the element in DTD syntax * @throws SAXException */ public void elementDecl(String name, String model) throws SAXException { // Skip elements that come from the external subset if (!inInternalSubset) return; internalSubset.append(" <!ELEMENT ") .append(name) .append(' ') .append(model) .append(">\n"); } /** * Handle an internal entity declaration in a DTD. * * @param name <code>String</code> name of entity * @param value <code>String</code> value of the entity * @throws SAXException */ public void internalEntityDecl(String name, String value) throws SAXException { // Skip entities that come from the external subset if (!inInternalSubset) return; internalSubset.append(" <!ENTITY "); if (name.startsWith("%")) { internalSubset.append("% ").append(name.substring(1)); } else { internalSubset.append(name); } internalSubset.append(" \"") .append(value) .append("\">\n"); } /** * This will indicate that a processing instruction has been encountered. * (The XML declaration is not a processing instruction and will not * be reported.) * * @param target <code>String</code> target of PI * @param data <code>String</code> containing all data sent to the PI. * This typically looks like one or more attribute value * pairs. * @throws SAXException when things go wrong */ public void processingInstruction(String target, String data) throws SAXException { if (suppress) return; flushCharacters(); if (atRoot) { factory.addContent(document, factory.processingInstruction(target, data)); } else { factory.addContent(getCurrentElement(), factory.processingInstruction(target, data)); } } /** * This indicates that an unresolvable entity reference has been * encountered, normally because the external DTD subset has not been * read. * * @param name <code>String</code> name of entity * @throws SAXException when things go wrong */ public void skippedEntity(String name) throws SAXException { // We don't handle parameter entity references. if (name.startsWith("%")) return; flushCharacters(); factory.addContent(getCurrentElement(), factory.entityRef(name)); } /** * This will add the prefix mapping to the JDOM * <code>Document</code> object. * * @param prefix <code>String</code> namespace prefix. * @param uri <code>String</code> namespace URI. */ public void startPrefixMapping(String prefix, String uri) throws SAXException { if (suppress) return; Namespace ns = Namespace.getNamespace(prefix, uri); declaredNamespaces.add(ns); } /** * This reports the occurrence of an actual element. It will include * the element's attributes, with the exception of XML vocabulary * specific attributes, such as * <code>xmlns:[namespace prefix]</code> and * <code>xsi:schemaLocation</code>. * * @param namespaceURI <code>String</code> namespace URI this element * is associated with, or an empty * <code>String</code> * @param localName <code>String</code> name of element (with no * namespace prefix, if one is present) * @param qName <code>String</code> XML 1.0 version of element name: * [namespace prefix]:[localName] * @param atts <code>Attributes</code> list for this element * @throws SAXException when things go wrong */ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (suppress) return; Element element = null; if ((namespaceURI != null) && (!namespaceURI.equals(""))) { String prefix = ""; // Determine any prefix on the Element if (!qName.equals(localName)) { int split = qName.indexOf(":"); prefix = qName.substring(0, split); } Namespace elementNamespace = Namespace.getNamespace(prefix, namespaceURI); element = factory.element(localName, elementNamespace); } else { element = factory.element(localName); } // Take leftover declared namespaces and add them to this element's // map of namespaces if (declaredNamespaces.size() > 0) { transferNamespaces(element); } // Handle attributes for (int i=0, len=atts.getLength(); i<len; i++) { Attribute attribute = null; String attLocalName = atts.getLocalName(i); String attQName = atts.getQName(i); int attType = getAttributeType(atts.getType(i)); // Bypass any xmlns attributes which might appear, as we got // them already in startPrefixMapping(). // This is sometimes necessary when SAXHandler is used with // another source than SAXBuilder, as with JDOMResult. if (attQName.startsWith("xmlns:") || attQName.equals("xmlns")) { continue; } // First clause per http://markmail.org/message/2p245ggcjst27xe6 // patch from Mattias Jiderhamn if ("".equals(attLocalName) && attQName.indexOf(":") == -1) { attribute = factory.attribute(attQName, atts.getValue(i), attType); } else if (!attQName.equals(attLocalName)) { String attPrefix = attQName.substring(0, attQName.indexOf(":")); Namespace attNs = Namespace.getNamespace(attPrefix, atts.getURI(i)); attribute = factory.attribute(attLocalName, atts.getValue(i), attType, attNs); } else { attribute = factory.attribute(attLocalName, atts.getValue(i), attType); } factory.setAttribute(element, attribute); } flushCharacters(); if (atRoot) { document.setRootElement(element); // XXX should we use a factory call? atRoot = false; } else { factory.addContent(getCurrentElement(), element); } currentElement = element; } /** * This will take the supplied <code>{@link Element}</code> and * transfer its namespaces to the global namespace storage. * * @param element <code>Element</code> to read namespaces from. */ private void transferNamespaces(Element element) { Iterator i = declaredNamespaces.iterator(); while (i.hasNext()) { Namespace ns = (Namespace)i.next(); if (ns != element.getNamespace()) { element.addNamespaceDeclaration(ns); } } declaredNamespaces.clear(); } /** * This will report character data (within an element). * * @param ch <code>char[]</code> character array with character data * @param start <code>int</code> index in array where data starts. * @param length <code>int</code> length of data. * @throws SAXException */ public void characters(char[] ch, int start, int length) throws SAXException { if (suppress || (length == 0)) return; if (previousCDATA != inCDATA) { flushCharacters(); } textBuffer.append(ch, start, length); } /** * Capture ignorable whitespace as text. If * setIgnoringElementContentWhitespace(true) has been called then this * method does nothing. * * @param ch <code>[]</code> - char array of ignorable whitespace * @param start <code>int</code> - starting position within array * @param length <code>int</code> - length of whitespace after start * @throws SAXException when things go wrong */ public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (!ignoringWhite) { characters(ch, start, length); } } /** * This will flush any characters from SAX character calls we've * been buffering. * * @throws SAXException when things go wrong */ protected void flushCharacters() throws SAXException { if (ignoringBoundaryWhite) { if (!textBuffer.isAllWhitespace()) { flushCharacters(textBuffer.toString()); } } else { flushCharacters(textBuffer.toString()); } textBuffer.clear(); } /** * Flush the given string into the document. This is a protected method * so subclassers can control text handling without knowledge of the * internals of this class. * * @param data string to flush */ protected void flushCharacters(String data) throws SAXException { if (data.length() == 0) { previousCDATA = inCDATA; return; } /** * This is commented out because of some problems with * the inline DTDs that Xerces seems to have. if (!inDTD) { if (inEntity) { getCurrentElement().setContent(factory.text(data)); } else { getCurrentElement().addContent(factory.text(data)); } */ if (previousCDATA) { factory.addContent(getCurrentElement(), factory.cdata(data)); } else { factory.addContent(getCurrentElement(), factory.text(data)); } previousCDATA = inCDATA; } /** * Indicates the end of an element * (<code>&lt;/[element name]&gt;</code>) is reached. Note that * the parser does not distinguish between empty * elements and non-empty elements, so this will occur uniformly. * * @param namespaceURI <code>String</code> URI of namespace this * element is associated with * @param localName <code>String</code> name of element without prefix * @param qName <code>String</code> name of element in XML 1.0 form * @throws SAXException when things go wrong */ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (suppress) return; flushCharacters(); if (!atRoot) { Parent p = currentElement.getParent(); if (p instanceof Document) { atRoot = true; } else { currentElement = (Element) p; } } else { throw new SAXException( "Ill-formed XML document (missing opening tag for " + localName + ")"); } } /** * This will signify that a DTD is being parsed, and can be * used to ensure that comments and other lexical structures * in the DTD are not added to the JDOM <code>Document</code> * object. * * @param name <code>String</code> name of element listed in DTD * @param publicID <code>String</code> public ID of DTD * @param systemID <code>String</code> system ID of DTD */ public void startDTD(String name, String publicID, String systemID) throws SAXException { flushCharacters(); // Is this needed here? factory.addContent(document, factory.docType(name, publicID, systemID)); inDTD = true; inInternalSubset = true; } /** * This signifies that the reading of the DTD is complete. * * @throws SAXException */ public void endDTD() throws SAXException { document.getDocType().setInternalSubset(internalSubset.toString()); inDTD = false; inInternalSubset = false; } public void startEntity(String name) throws SAXException { entityDepth++; if (expand || entityDepth > 1) { // Short cut out if we're expanding or if we're nested return; } // A "[dtd]" entity indicates the beginning of the external subset if (name.equals("[dtd]")) { inInternalSubset = false; return; } // Ignore DTD references, and translate the standard 5 if ((!inDTD) && (!name.equals("amp")) && (!name.equals("lt")) && (!name.equals("gt")) && (!name.equals("apos")) && (!name.equals("quot"))) { if (!expand) { String pub = null; String sys = null; String[] ids = (String[]) externalEntities.get(name); if (ids != null) { pub = ids[0]; // may be null, that's OK sys = ids[1]; // may be null, that's OK } /** * if no current element, this entity belongs to an attribute * in these cases, it is an error on the part of the parser * to call startEntity but this will help in some cases. * See org/xml/sax/ext/LexicalHandler.html#startEntity(java.lang.String) * for more information */ if (!atRoot) { flushCharacters(); EntityRef entity = factory.entityRef(name, pub, sys); // no way to tell if the entity was from an attribute or element so just assume element factory.addContent(getCurrentElement(), entity); } suppress = true; } } } public void endEntity(String name) throws SAXException { entityDepth--; if (entityDepth == 0) { // No way are we suppressing if not in an entity, // regardless of the "expand" value suppress = false; } if (name.equals("[dtd]")) { inInternalSubset = true; } } /** * Report a CDATA section * * @throws SAXException */ public void startCDATA() throws SAXException { if (suppress) return; inCDATA = true; } /** * Report a CDATA section */ public void endCDATA() throws SAXException { if (suppress) return; previousCDATA = true; inCDATA = false; } /** * This reports that a comments is parsed. If not in the * DTD, this comment is added to the current JDOM * <code>Element</code>, or the <code>Document</code> itself * if at that level. * * @param ch <code>ch[]</code> array of comment characters. * @param start <code>int</code> index to start reading from. * @param length <code>int</code> length of data. * @throws SAXException */ public void comment(char[] ch, int start, int length) throws SAXException { if (suppress) return; flushCharacters(); String commentText = new String(ch, start, length); if (inDTD && inInternalSubset && (expand == false)) { internalSubset.append(" <!--") .append(commentText) .append("-->\n"); return; } if ((!inDTD) && (!commentText.equals(""))) { if (atRoot) { factory.addContent(document, factory.comment(commentText)); } else { factory.addContent(getCurrentElement(), factory.comment(commentText)); } } } /** * Handle the declaration of a Notation in a DTD * * @param name name of the notation * @param publicID the public ID of the notation * @param systemID the system ID of the notation */ public void notationDecl(String name, String publicID, String systemID) throws SAXException { if (!inInternalSubset) return; internalSubset.append(" <!NOTATION ") .append(name); appendExternalId(publicID, systemID); internalSubset.append(">\n"); } /** * Handler for unparsed entity declarations in the DTD * * @param name <code>String</code> of the unparsed entity decl * @param publicID <code>String</code> of the unparsed entity decl * @param systemID <code>String</code> of the unparsed entity decl * @param notationName <code>String</code> of the unparsed entity decl */ public void unparsedEntityDecl(String name, String publicID, String systemID, String notationName) throws SAXException { if (!inInternalSubset) return; internalSubset.append(" <!ENTITY ") .append(name); appendExternalId(publicID, systemID); internalSubset.append(" NDATA ") .append(notationName); internalSubset.append(">\n"); } /** * Appends an external ID to the internal subset buffer. Either publicID * or systemID may be null, but not both. * * @param publicID the public ID * @param systemID the system ID */ private void appendExternalId(String publicID, String systemID) { if (publicID != null) { internalSubset.append(" PUBLIC \"") .append(publicID) .append('\"'); } if (systemID != null) { if (publicID == null) { internalSubset.append(" SYSTEM "); } else { internalSubset.append(' '); } internalSubset.append('\"') .append(systemID) .append('\"'); } } /** * Returns the being-parsed element. * * @return <code>Element</code> - element being built. * @throws SAXException */ public Element getCurrentElement() throws SAXException { if (currentElement == null) { throw new SAXException( "Ill-formed XML document (multiple root elements detected)"); } return currentElement; } /** * Returns the the JDOM Attribute type value from the SAX 2.0 * attribute type string provided by the parser. * * @param typeName <code>String</code> the SAX 2.0 attribute * type string. * * @return <code>int</code> the JDOM attribute type. * * @see Attribute#setAttributeType * @see Attributes#getType */ private static int getAttributeType(String typeName) { Integer type = (Integer)(attrNameToTypeMap.get(typeName)); if (type == null) { if (typeName != null && typeName.length() > 0 && typeName.charAt(0) == '(') { // Xerces 1.4.X reports attributes of enumerated type with // a type string equals to the enumeration definition, i.e. // starting with a parenthesis. return Attribute.ENUMERATED_TYPE; } else { return Attribute.UNDECLARED_TYPE; } } else { return type.intValue(); } } /** * Receives an object for locating the origin of SAX document * events. This method is invoked by the SAX parser. * <p> * {@link org.jdom.JDOMFactory} implementations can use the * {@link #getDocumentLocator} method to get access to the * {@link Locator} during parse. * </p> * * @param locator <code>Locator</code> an object that can return * the location of any SAX document event. */ public void setDocumentLocator(Locator locator) { this.locator = locator; } /** * Provides access to the {@link Locator} object provided by the * SAX parser. * * @return <code>Locator</code> an object that can return * the location of any SAX document event. */ public Locator getDocumentLocator() { return locator; } }
mit
jastination/software-engineering-excercise-repository
seer_java/src/codejam2012/RecycledNumbers.java
1828
package codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new BufferedReader(new FileReader( "A-large-practice.in.txt"))); Output out = new Output("B.out"); int T = scanner.nextInt(); for (int t = 1; t <= T; t++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int count = 0; for(int m = A; m < B; m++ ){ String strM = "" + m; HashSet<String> cache = new HashSet<String>(); for(int p = 1; p < strM.length(); p ++){ if(strM.charAt(p) < strM.charAt(0)){ continue; } String strN = strM.substring(p) + strM.substring(0, p); int n = Integer.parseInt(strN); if(n > m && n <= B && !cache.contains(strN)){ cache.add(strN); count ++; //System.out.println(strM + " " + strN); } } } out.format("Case #%d: %d\n", t, count); } scanner.close(); out.close(); } static class Output { PrintWriter pw; public Output(String filename) throws IOException { pw = new PrintWriter(new BufferedWriter(new FileWriter(filename))); } public void print(String s) { pw.print(s); System.out.print(s); } public void println(String s) { pw.println(s); System.out.println(s); } public void format(String format, Object... args) { pw.format(format, args); System.out.format(format, args); } public void close() { pw.close(); } } }
mit
webarata3/benrippoi
src/main/java/link/webarata3/poi/BenriWorkbookFactory.java
1499
package link.webarata3.poi; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; /** * BenriWorkbookのファクトリー */ public class BenriWorkbookFactory { /** * ファイル名を指定してBenriWorkbookを作成します。 * * @param fileName ファイル名(拡張子でファイルタイプを判定する) * @return BenriWorkbook * @throws IOException * @throws InvalidFormatException */ public static BenriWorkbook create(String fileName) throws IOException, InvalidFormatException { InputStream is = Files.newInputStream(Paths.get(fileName)); return create(is); } /** * InputStreamからBenriWorkbookを作成します。 * * @param is InputStream * @return BenriWorkbook * @throws IOException * @throws InvalidFormatException */ public static BenriWorkbook create(InputStream is) throws IOException, InvalidFormatException { Workbook wb = BenrippoiUtil.open(is); return new BenriWorkbook(wb); } /** * 新規BenriWorkbookの作成 * * @return 新規BenriWorkboo */ public static BenriWorkbook createBlank() { Workbook wb = new XSSFWorkbook(); return new BenriWorkbook(wb); } }
mit
cscfa/bartleby
library/logBack/logback-1.1.3/logback-core/src/main/java/ch/qos/logback/core/net/JMSAppenderBase.java
5218
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core.net; import java.util.Hashtable; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import ch.qos.logback.core.AppenderBase; /** * This class serves as a base class for * JMSTopicAppender and JMSQueueAppender * * For more information about this appender, please refer to: * http://logback.qos.ch/manual/appenders.html#JMSAppenderBase * * @author Ceki G&uuml;lc&uuml; * @author S&eacute;bastien Pennec */ public abstract class JMSAppenderBase<E> extends AppenderBase<E> { protected String securityPrincipalName; protected String securityCredentials; protected String initialContextFactoryName; protected String urlPkgPrefixes; protected String providerURL; protected String userName; protected String password; protected Object lookup(Context ctx, String name) throws NamingException { try { return ctx.lookup(name); } catch (NameNotFoundException e) { addError("Could not find name [" + name + "]."); throw e; } } public Context buildJNDIContext() throws NamingException { Context jndi = null; // addInfo("Getting initial context."); if (initialContextFactoryName != null) { Properties env = buildEnvProperties(); jndi = new InitialContext(env); } else { jndi = new InitialContext(); } return jndi; } public Properties buildEnvProperties() { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName); if (providerURL != null) { env.put(Context.PROVIDER_URL, providerURL); } else { addWarn("You have set InitialContextFactoryName option but not the " + "ProviderURL. This is likely to cause problems."); } if (urlPkgPrefixes != null) { env.put(Context.URL_PKG_PREFIXES, urlPkgPrefixes); } if (securityPrincipalName != null) { env.put(Context.SECURITY_PRINCIPAL, securityPrincipalName); if (securityCredentials != null) { env.put(Context.SECURITY_CREDENTIALS, securityCredentials); } else { addWarn("You have set SecurityPrincipalName option but not the " + "SecurityCredentials. This is likely to cause problems."); } } return env; } /** * Returns the value of the <b>InitialContextFactoryName</b> option. See * {@link #setInitialContextFactoryName} for more details on the meaning of * this option. */ public String getInitialContextFactoryName() { return initialContextFactoryName; } /** * Setting the <b>InitialContextFactoryName</b> method will cause this * <code>JMSAppender</code> instance to use the {@link * InitialContext#InitialContext(Hashtable)} method instead of the no-argument * constructor. If you set this option, you should also at least set the * <b>ProviderURL</b> option. * * <p> * See also {@link #setProviderURL(String)}. */ public void setInitialContextFactoryName(String initialContextFactoryName) { this.initialContextFactoryName = initialContextFactoryName; } public String getProviderURL() { return providerURL; } public void setProviderURL(String providerURL) { this.providerURL = providerURL; } public String getURLPkgPrefixes() { return urlPkgPrefixes; } public void setURLPkgPrefixes(String urlPkgPrefixes) { this.urlPkgPrefixes = urlPkgPrefixes; } public String getSecurityCredentials() { return securityCredentials; } public void setSecurityCredentials(String securityCredentials) { this.securityCredentials = securityCredentials; } public String getSecurityPrincipalName() { return securityPrincipalName; } public void setSecurityPrincipalName(String securityPrincipalName) { this.securityPrincipalName = securityPrincipalName; } public String getUserName() { return userName; } /** * The user name to use when {@link * javax.jms.TopicConnectionFactory#createTopicConnection(String, String)} * creating a topic session}. If you set this option, you should also set the * <b>Password</b> option. See {@link #setPassword(String)}. */ public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } /** * The password to use when creating a topic session. */ public void setPassword(String password) { this.password = password; } }
mit
rubenlagus/TelegramBots
telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/serialization/InlineQueryResultDeserializer.java
5723
package org.telegram.telegrambots.meta.api.objects.inlinequery.result.serialization; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.*; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.*; import java.io.IOException; /** * @author Ruben Bermudez * @version 1.0 */ public class InlineQueryResultDeserializer extends StdDeserializer<InlineQueryResult> { private final ObjectMapper objectMapper; public InlineQueryResultDeserializer() { this(null); } private InlineQueryResultDeserializer(Class<?> vc) { super(vc); this.objectMapper = new ObjectMapper(); } @Override public InlineQueryResult deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); switch (node.get("type").asText()) { case "article": return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultArticle>(){}); case "audio": if (node.has("audio_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultAudio>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedAudio>(){}); } case "contact": return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultContact>(){}); case "document": if (node.has("document_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultDocument>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedDocument>(){}); } case "game": return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultGame>(){}); case "gif": if (node.has("gif_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultGif>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedGif>(){}); } case "location": return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultLocation>(){}); case "mpeg4_gif": if (node.has("mpeg4_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultMpeg4Gif>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedMpeg4Gif>(){}); } case "photo": if (node.has("photo_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultPhoto>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedPhoto>(){}); } case "venue": return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultVenue>(){}); case "video": if (node.has("video_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultVideo>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedVideo>(){}); } case "voice": if (node.has("voice_url")) { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultVoice>(){}); } else { return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedVoice>(){}); } case "sticker": return objectMapper.readValue(node.toString(), new com.fasterxml.jackson.core.type.TypeReference<InlineQueryResultCachedSticker>(){}); } return null; } }
mit
mstojcevich/Radix
core/src/sx/lambda/voxel/net/mc/client/handlers/UpdateTimeHandler.java
591
package sx.lambda.voxel.net.mc.client.handlers; import org.spacehq.mc.protocol.packet.ingame.server.world.ServerUpdateTimePacket; /** * Created by louxiu on 12/19/15. */ public class UpdateTimeHandler implements PacketHandler<ServerUpdateTimePacket> { @Override public void handle(ServerUpdateTimePacket packet) { // TODO: support day night cycle // Gdx.app.debug("", "ServerUpdateTimePacket" // + ", time=" + packet.getTime() // + ", worldAge=" + packet.getWorldAge() // + ", priority=" + packet.isPriority()); } }
mit
pitpitman/GraduateWork
Java_tutorial/essential/threads/example-1dot1/SelfishRunner.java
133
/* * This example requires no changes from the 1.0 version. You can * find the 1.0 version in ../example/SelfishRunner.java. */
mit
Yuchan4342/Pong2
src/com/o_char/pong/GameFrameC.java
1186
package com.o_char.pong; import java.awt.BorderLayout; import java.util.StringTokenizer; import javax.swing.JPanel; /** * PongClient 向けゲーム画面用クラス. */ public final class GameFrameC extends GameFrame { /** * Constructor. * * @param n 設定する n. * @param nid 設定する id. * @param npc 設定する PongController. */ public GameFrameC(int n, int nid, PongController npc) { super(n, npc); // パネルを設定して追加する. JPanel panel = new JPanel(); panel.setLayout(null); this.getContentPane().add(panel, BorderLayout.CENTER); this.id = nid + 2; this.init(); } /** * 点を受け取る. * @param s 受け取る情報が含まれた文字列. */ public synchronized void receivePoint(String s) { StringTokenizer st = new StringTokenizer(s, " "); st.nextToken(); int nid = Integer.parseInt(st.nextToken()); int newPoint = Integer.parseInt(st.nextToken()); if (nid != this.id) { this.point[nid - 1] = newPoint; } } public synchronized void sendPoint(int id, int point) { this.pongController.sendPoint(0, "Point: " + id + " " + point); } }
mit
karim/adila
database/src/main/java/adila/db/andorra.java
208
// This file is automatically generated. package adila.db; /* * Lenovo A820e * * DEVICE: andorra * MODEL: Lenovo A820e */ final class andorra { public static final String DATA = "Lenovo|A820e|"; }
mit
forerunnergames/fg-tools
common/src/test/java/com/forerunnergames/tools/common/StringsTest.java
4883
/* * Copyright © 2011 - 2013 Aaron Mahan * Copyright © 2013 - 2016 Forerunner Games, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.forerunnergames.tools.common; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import org.junit.Test; public class StringsTest { @Test public void testToProperCase () { final String test = " hello world! lol "; final String expected = " Hello World! Lol "; final String actual = Strings.toProperCase (test); assertEquals (expected, actual); } @Test public void testToStringList () { final String element1 = " hello "; final String element2 = " big world "; final String element3 = " galaxy "; final String element4 = " universe "; final String separator = ", "; final LetterCase letterCase = LetterCase.PROPER; final boolean hasAnd = false; final String expected = " Hello , Big World , Galaxy , Universe "; final String actual = Strings.toStringList (separator, letterCase, hasAnd, element1, element2, element3, element4); assertEquals (expected, actual); } @Test public void testSplitByUpperCase () { final String word = " HELLO,WORlD!!! "; final String[] expected = { " ", "H", "E", "L", "L", "O,", "W", "O", "Rl", "D!!! " }; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test public void testSplitByUpperCase2 () { final String word = "ThisIs A Camel-CaseWord.2A"; final String[] expected = { "This", "Is ", "A ", "Camel-", "Case", "Word.2", "A" }; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test public void testSplitByUpperCaseNothingToSplit () { final String word = " this string really doesn't have anything to split... "; final String[] expected = { " this string really doesn't have anything to split... " }; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test public void testSplitByUpperCaseEmptyString () { final String word = ""; final String[] expected = new String [0]; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test public void testSplitByUpperCaseAllWhitespace () { final String word = " \b \t \r \n\n "; final String[] expected = { " \b \t \r \n\n " }; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test public void testSplitByUpperCaseAllUppercase () { final String word = "THISISALLUPPERCASE"; final String[] expected = { "T", "H", "I", "S", "I", "S", "A", "L", "L", "U", "P", "P", "E", "R", "C", "A", "S", "E" }; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test public void testSplitByUpperCaseSingleUpperCaseCharacter () { final String word = "A"; final String[] expected = { "A" }; final String[] actual = Strings.splitByUpperCase (word); assertArrayEqualsPrintAllElementsOnFail (expected, actual); } @Test (expected = IllegalArgumentException.class) public void testSplitByUpperCaseNullStringThrowsException () { Strings.splitByUpperCase (null); } private <T> void assertArrayEqualsPrintAllElementsOnFail (final T[] expected, final T[] actual) { assertArrayEquals ("\n\nExpected:\n" + Strings.toString (expected) + "\nActual:\n" + Strings.toString (actual) + "\n", expected, actual); } }
mit
Anthonyzou/react-native-io-utils
example/android/app/src/main/java/com/example/MainActivity.java
1092
package com.example; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.rn.io.utils.IOUtilsModule; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "example"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new IOUtilsModule() ); } }
mit
Worcade/api-client-java
api/src/main/java/net/worcade/client/api/WebhookApi.java
1174
// Copyright (c) 2017, Worcade. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package net.worcade.client.api; import net.worcade.client.Result; import net.worcade.client.create.WebhookCreate; import net.worcade.client.get.Reference; import net.worcade.client.get.Webhook; import net.worcade.client.get.WebhookTestResult; import net.worcade.client.query.Query; import net.worcade.client.query.WebhookField; import java.util.Collection; public interface WebhookApi { WebhookCreate createBuilder(); /** * Create a new Webhook. Use the {@link #createBuilder()} method for a new, empty template. */ Result<? extends Reference> create(String ownerId, WebhookCreate subject); Result<?> delete(String id); Result<? extends Collection<? extends Webhook>> getWebhookList(Query<WebhookField> query); Result<? extends Collection<? extends Webhook.Log>> getLogs(String id, boolean includeDeleted); /** * @param id The id of the webhook to test */ Result<? extends WebhookTestResult> requestTest(String id); }
mit
appdrvn/RestaurantTemplate-Android
paginate/src/main/java/com/paginate/recycler/WrapperAdapter.java
2555
package com.paginate.recycler; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; class WrapperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int ITEM_VIEW_TYPE_LOADING = Integer.MAX_VALUE - 50; // Magic private final RecyclerView.Adapter wrappedAdapter; private final LoadingListItemCreator loadingListItemCreator; private boolean displayLoadingRow = true; public WrapperAdapter(RecyclerView.Adapter adapter, LoadingListItemCreator creator) { this.wrappedAdapter = adapter; this.loadingListItemCreator = creator; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == ITEM_VIEW_TYPE_LOADING) { return loadingListItemCreator.onCreateViewHolder(parent, viewType); } else { return wrappedAdapter.onCreateViewHolder(parent, viewType); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (isLoadingRow(position)) { loadingListItemCreator.onBindViewHolder(holder, position); } else { wrappedAdapter.onBindViewHolder(holder, position); } } @Override public int getItemCount() { return displayLoadingRow ? wrappedAdapter.getItemCount() + 1 : wrappedAdapter.getItemCount(); } @Override public int getItemViewType(int position) { return isLoadingRow(position) ? ITEM_VIEW_TYPE_LOADING : wrappedAdapter.getItemViewType(position); } @Override public long getItemId(int position) { return isLoadingRow(position) ? RecyclerView.NO_ID : wrappedAdapter.getItemId(position); } @Override public void setHasStableIds(boolean hasStableIds) { super.setHasStableIds(hasStableIds); wrappedAdapter.setHasStableIds(hasStableIds); } public RecyclerView.Adapter getWrappedAdapter() { return wrappedAdapter; } boolean isDisplayLoadingRow() { return displayLoadingRow; } void displayLoadingRow(boolean displayLoadingRow) { if (this.displayLoadingRow != displayLoadingRow) { this.displayLoadingRow = displayLoadingRow; notifyDataSetChanged(); } } boolean isLoadingRow(int position) { return displayLoadingRow && position == getLoadingRowPosition(); } private int getLoadingRowPosition() { return displayLoadingRow ? getItemCount() - 1 : -1; } }
mit
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testFlagAction.java
1401
package generated.zcsclient.mail; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for flagAction complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="flagAction"> * &lt;complexContent> * &lt;extension base="{urn:zimbraMail}filterAction"> * &lt;sequence> * &lt;/sequence> * &lt;attribute name="flagName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "flagAction") public class testFlagAction extends testFilterAction { @XmlAttribute(name = "flagName") protected String flagName; /** * Gets the value of the flagName property. * * @return * possible object is * {@link String } * */ public String getFlagName() { return flagName; } /** * Sets the value of the flagName property. * * @param value * allowed object is * {@link String } * */ public void setFlagName(String value) { this.flagName = value; } }
mit
ChristinGorman/javazone2016
src/main/java/no/javazone/sleep/Sleeper.java
2182
package no.javazone.sleep; import co.paralleluniverse.fibers.Fiber; import co.paralleluniverse.fibers.Suspendable; import java.time.LocalDateTime; import java.util.List; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; public class Sleeper { static class SleepCallback { final long done; final Runnable callback; public SleepCallback(long done, Runnable r) { this.done = done; this.callback = r; } } public static Long sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return millis; } public static Long sleep1Sec() { return sleep(1000); } public static Long sleepwalk1Sec(){ return sleepwalk(1000); } public static Long sleepwalk(long millis) { long timeout = System.currentTimeMillis() + millis; while (System.currentTimeMillis() < timeout) { Thread.yield(); } return millis; } static Queue<SleepCallback> sleepTasks = new ConcurrentLinkedQueue<>(); static { Thread thread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { SleepCallback first = sleepTasks.poll(); if (first != null) { if (System.currentTimeMillis() >= first.done) { first.callback.run(); } else { sleepTasks.offer(first); } } } }); thread.setDaemon(true); thread.start(); } public static void sleep(int millis, Runnable callback) { sleepTasks.offer(new SleepCallback(System.currentTimeMillis() + millis, callback)); } @Suspendable public static Long fiberSleep() { try { Fiber.sleep(1000); return 1000l; } catch (Exception e) { throw new RuntimeException(e); } } }
mit
Mayo-WE01051879/mayosapp
Build/src/tests/junit/org/apache/tools/ant/util/DeweyDecimalTest.java
2747
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.tools.ant.util; import static org.junit.Assert.*; import org.junit.Test; @SuppressWarnings("ResultOfObjectAllocationIgnored") public class DeweyDecimalTest { @Test public void parse() { assertEquals("1.2.3", new DeweyDecimal("1.2.3").toString()); } @Test(expected=NumberFormatException.class) public void misparseEmpty() { new DeweyDecimal("1..2"); } @Test(expected=NumberFormatException.class) public void misparseNonNumeric() { new DeweyDecimal("1.2.3-beta-5"); } @Test(expected=NumberFormatException.class) public void misparseFinalDot() { new DeweyDecimal("1.2."); } // TODO initial dots, empty string, null, negative numbers, ... @Test public void testHashCode() { assertEquals(new DeweyDecimal("1.2.3").hashCode(), new DeweyDecimal("1.2.3").hashCode()); } @Test public void testEquals() { assertTrue(new DeweyDecimal("1.2.3").equals(new DeweyDecimal("1.2.3"))); assertFalse(new DeweyDecimal("1.2.3").equals(new DeweyDecimal("1.2.4"))); assertTrue(new DeweyDecimal("1.2.0").equals(new DeweyDecimal("1.2"))); assertTrue(new DeweyDecimal("1.2").equals(new DeweyDecimal("1.2.0"))); } @Test public void compareTo() { assertTrue(new DeweyDecimal("1.2.3").compareTo(new DeweyDecimal("1.2")) > 0); assertTrue(new DeweyDecimal("1.2").compareTo(new DeweyDecimal("1.2.3")) < 0); assertTrue(new DeweyDecimal("1.2.3").compareTo(new DeweyDecimal("1.2.3")) == 0); assertTrue(new DeweyDecimal("1.2.3").compareTo(new DeweyDecimal("1.1.4")) > 0); assertTrue(new DeweyDecimal("1.2.3").compareTo(new DeweyDecimal("1.2.2.9")) > 0); assertTrue(new DeweyDecimal("1.2.0").compareTo(new DeweyDecimal("1.2")) == 0); assertTrue(new DeweyDecimal("1.2").compareTo(new DeweyDecimal("1.2.0")) == 0); } // TODO isGreaterThan, ... }
mit
fikipollo/stategraems
src/java/classes/analysis/QualityReport.java
4307
/* *************************************************************** * This file is part of STATegra EMS. * * STATegra EMS 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. * * STATegra EMS 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 STATegra EMS. If not, see <http://www.gnu.org/licenses/>. * * More info http://bioinfo.cipf.es/stategraems * Technical contact stategraemsdev@gmail.com * *************************************************************** */ package classes.analysis; import com.google.gson.Gson; /** * * @author Rafa Hernández de Diego */ public class QualityReport { private String studied_step_id; private String software; private String software_version; private String software_configuration; private String results; private String files_location; private String submission_date; public QualityReport(String studied_step_id, String software, String software_version, String software_configuration, String results, String files_location,String submission_date) { this.studied_step_id = studied_step_id; this.software = software; this.software_version = software_version; this.software_configuration = software_configuration; this.results = results; this.files_location = files_location; this.submission_date = submission_date; } /** * This static function returns a new object using the data contained in the * given JSON object (as String). * * @param jsonString the JSON object * @return the new Object. */ public static QualityReport fromJSON(String jsonString) { Gson gson = new Gson(); QualityReport quality_report = gson.fromJson(jsonString, QualityReport.class); return quality_report; } public String toJSON() { Gson gson = new Gson(); String jsonString = gson.toJson(this); return jsonString; } //********************************************************************** //* GETTERS AND SETTERS ************************************************ //********************************************************************** public String getStudied_step_id() { return studied_step_id; } public void setStudiedStepID(String studied_step_id) { this.studied_step_id = studied_step_id; } public String getSoftware() { return software; } public void setSoftware(String software) { this.software = software; } public String getSoftware_version() { return software_version; } public void setSoftware_version(String software_version) { this.software_version = software_version; } public String getResults() { return results; } public void setResults(String results) { this.results = results; } public String getFiles_location() { return files_location; } public void setFiles_location(String files_location) { this.files_location = files_location; } public String getSoftware_configuration() { return software_configuration; } public void setSoftware_configuration(String software_configuration) { this.software_configuration = software_configuration; } public String getSubmissionDate() { return submission_date; } public void setSubmissionDate(String submission_date) { this.submission_date = submission_date; } //*********************************************************************** //* OTHER FUNCTIONS ***************************************************** //*********************************************************************** @Override public String toString() { return this.toJSON(); } }
mit
dimejy2/vogaNew
src/view/GUIToolBar.java
4290
package view; //import inputs.InputRestart; //import inputs.InputSaveLoad; import java.nio.file.Path; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Orientation; import javafx.scene.control.Button; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.TabPane; import javafx.scene.control.ToolBar; import javafx.scene.layout.FlowPane; import layout.LayoutPane; public class GUIToolBar { private int SCREEN_WIDTH = 1280; private int SCREEN_LENGTH = 720; public TabPane environment = new TabPane(); protected ToolBar toolBar; protected LoadNSave saver; /* * this class creates the toolBar and the tabPane used for the Scene */ public void edit(FlowPane root, SceneManager s) { saver = new LoadNSave(); toolBar = new ToolBar(); MenuBar mainMenu = new MenuBar(); Menu file = new Menu("File"); Menu edit = new Menu("Edit"); Menu launch = new Menu("Launch"); MenuItem openFile = new MenuItem("Open File"); openFile.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // Path b = saver.read(); // InputSaveLoad load = new InputSaveLoad(b, false); // ((LayoutPane) s.getTab().getContent()).notify(load); } }); MenuItem saveFile = new MenuItem("Save File"); saveFile.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // Path b = saver.write(); // InputSaveLoad save = new InputSaveLoad(b, true); // ((LayoutPane) s.getTab().getContent()).notify(save); } }); MenuItem restart = new MenuItem("Restart"); restart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // InputRestart restart = new InputRestart(true); // ((LayoutPane) s.getTab().getContent()).notify(restart); } }); MenuItem pause = new MenuItem("Pause"); pause.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { } }); MenuItem play = new MenuItem("Play"); play.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { } }); MenuItem newTab = new MenuItem("New Tab"); newTab.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // if (s.isAuthoringScene) { // s.createAuthoringEnvironment(); // } else{ // s.createPlayingEnvironment(); // } } }); Button switcher = new Button("Switch Environment"); switcher.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { s.switchScene(); } }); MenuItem playing = new MenuItem("Start with Play Environment"); playing.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(s.playing.isEmpty()){ s.environments.getTabs().clear(); s.createEnvironment("Playing"); } } }); MenuItem authoring = new MenuItem("Start with Authoring Environment"); authoring.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(s.authoring.isEmpty()){ s.environments.getTabs().clear(); s.createEnvironment("Authoring"); } } }); MenuItem previous = new MenuItem("Previous"); MenuItem switching = new MenuItem("Switch"); switching.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { s.switchScene(); } }); MenuItem forward = new MenuItem("forward"); file.getItems().addAll(openFile, saveFile, restart, pause, play, newTab); edit.getItems().addAll(previous, forward); launch.getItems().addAll(playing, authoring, switching); mainMenu.getMenus().addAll(file, edit, launch); toolBar.getItems().addAll(mainMenu); toolBar.getItems().addAll(switcher); toolBar.setPrefWidth(SCREEN_WIDTH); root.setOrientation(Orientation.VERTICAL); root.getChildren().addAll(toolBar); } public void createTab(FlowPane root) { root.getChildren().addAll(environment); } public TabPane getTab() { return environment; } public ToolBar getToolBar() { return toolBar; } }
mit
Juffik/JavaRush-1
src/com/javarush/test/level04/lesson16/home03/Solution.java
940
package com.javarush.test.level04.lesson16.home03; /* Посчитать сумму чисел Вводить с клавиатуры числа и считать их сумму. Если пользователь ввел -1, вывести на экран сумму и завершить программу. -1 должно учитываться в сумме. */ import java.io.BufferedReader; import java.io.InputStreamReader; public class Solution { public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); int sum=0; for (; true; ) { String s = buffer.readLine(); int number = Integer.parseInt(s); if(number==-1) { sum=sum+number; System.out.println(sum); break; } sum=sum+number; } } }
mit
plumer/codana
tomcat_files/6.0.0/FileUpload.java
3189
/* * Copyright 2001-2006 The Apache Software Foundation. * * 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.apache.tomcat.util.http.fileupload; /** * <p>High level API for processing file uploads.</p> * * <p>This class handles multiple files per single HTML widget, sent using * <code>multipart/mixed</code> encoding type, as specified by * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. Use {@link * #parseRequest(HttpServletRequest)} to acquire a list of {@link * org.apache.tomcat.util.http.fileupload.FileItem}s associated with a given HTML * widget.</p> * * <p>How the data for individual parts is stored is determined by the factory * used to create them; a given part may be in memory, on disk, or somewhere * else.</p> * * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a> * @author <a href="mailto:dlr@collab.net">Daniel Rall</a> * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @author <a href="mailto:jmcnally@collab.net">John McNally</a> * @author <a href="mailto:martinc@apache.org">Martin Cooper</a> * @author Sean C. Sullivan * * @version $Id: FileUpload.java,v 1.23 2003/06/24 05:45:43 martinc Exp $ */ public class FileUpload extends FileUploadBase { // ----------------------------------------------------------- Data members /** * The factory to use to create new form items. */ private FileItemFactory fileItemFactory; // ----------------------------------------------------------- Constructors /** * Constructs an instance of this class which uses the default factory to * create <code>FileItem</code> instances. * * @see #FileUpload(FileItemFactory) */ public FileUpload() { super(); } /** * Constructs an instance of this class which uses the supplied factory to * create <code>FileItem</code> instances. * * @see #FileUpload() */ public FileUpload(FileItemFactory fileItemFactory) { super(); this.fileItemFactory = fileItemFactory; } // ----------------------------------------------------- Property accessors /** * Returns the factory class used when creating file items. * * @return The factory class for new file items. */ public FileItemFactory getFileItemFactory() { return fileItemFactory; } /** * Sets the factory class to use when creating file items. * * @param factory The factory class for new file items. */ public void setFileItemFactory(FileItemFactory factory) { this.fileItemFactory = factory; } }
mit
victorpm5/paytrack
app/src/androidTest/java/dev/paytrack/paytrack/ApplicationTest.java
352
package dev.paytrack.paytrack; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
AncientMariner/BowlingGame
src/main/java/org/xander/bowlingEngine/Roll.java
2778
package org.xander.bowlingEngine; import utils.VerifyPointsAreInGameRulesRange; public class Roll { public static final int MAX_KNOCKED_DOWN_PINS = 10; private static final int singleBonus = 1; private static final int doubleBonus = 2; private static final int tripleBonus = 3; public static boolean consecutiveStrike; private final VerifyPointsAreInGameRulesRange verifyPointsAreInGameRulesRange; private final Calculation calculation; public Roll(Frame frame) { calculation = frame.getCalculation(); this.verifyPointsAreInGameRulesRange = new VerifyPointsAreInGameRulesRange(); } void ordinaryRollFromFirstToNinthFrame(int firstRollKnockedDownPins, int secondRollKnockedDownPins) { verifyPointsAreInGameRulesRange.verifyPointsAreInGameRulesRangeForNonTenthFrame(firstRollKnockedDownPins + secondRollKnockedDownPins); if (consecutiveStrike == true) { Frame.bonusForFirstRoll = tripleBonus; } if (firstRollKnockedDownPins + secondRollKnockedDownPins < MAX_KNOCKED_DOWN_PINS) { openFrameRoll(firstRollKnockedDownPins, secondRollKnockedDownPins); } else { frameRollWithBonus(firstRollKnockedDownPins, secondRollKnockedDownPins); } } private void frameRollWithBonus(int firstRollKnockedDownPins, int secondRollKnockedDownPins) { if (firstRollKnockedDownPins == MAX_KNOCKED_DOWN_PINS) { strike(); } else { spare(firstRollKnockedDownPins, secondRollKnockedDownPins); } } private void openFrameRoll(int firstRollKnockedDownPins, int secondRollKnockedDownPins) { calculation.calculateScore(firstRollKnockedDownPins, secondRollKnockedDownPins); Frame.bonusForFirstRoll = singleBonus; Frame.bonusForSecondRoll = singleBonus; consecutiveStrike = false; } private void spare(int firstRollKnockedDownPins, int secondRollKnockedDownPins) { calculation.calculateScore(firstRollKnockedDownPins, secondRollKnockedDownPins); Frame.bonusForFirstRoll = doubleBonus; Frame.bonusForSecondRoll = singleBonus; consecutiveStrike = false; } private void strike() { Frame.strikesPerGameNumber++; calculation.calculateScore(MAX_KNOCKED_DOWN_PINS, 0); if (Frame.bonusForFirstRoll == doubleBonus || Frame.bonusForSecondRoll == doubleBonus) { consecutiveStrike = true; } Frame.bonusForFirstRoll = doubleBonus; Frame.bonusForSecondRoll = doubleBonus; if (Frame.strikesPerGameNumber == 9) { Frame.setGameTotalScore(270); } } }
mit
shaunmahony/seqcode
src/edu/psu/compbio/seqcode/gse/ewok/verbs/binding/BindingScanGenerator.java
1541
/* * Created on Dec 5, 2006 * * TODO * * To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package edu.psu.compbio.seqcode.gse.ewok.verbs.binding; import edu.psu.compbio.seqcode.gse.datasets.binding.*; import edu.psu.compbio.seqcode.gse.datasets.general.Region; import edu.psu.compbio.seqcode.gse.ewok.nouns.*; import edu.psu.compbio.seqcode.gse.ewok.verbs.*; import edu.psu.compbio.seqcode.gse.utils.iterators.EmptyIterator; import java.sql.SQLException; import java.util.*; public class BindingScanGenerator implements Expander<Region,BindingEvent> { private BindingScanLoader loader; private LinkedList<BindingScan> scans; public BindingScanGenerator(BindingScanLoader l, BindingScan s) { loader = l; scans = new LinkedList<BindingScan>(); scans.add(s); } public BindingScanGenerator(BindingScanLoader l) { loader = l; scans = new LinkedList<BindingScan>(); } public void addBindingScan(BindingScan bs) { scans.addLast(bs); } public Iterator<BindingEvent> execute(Region a) { LinkedList<BindingEvent> evts = new LinkedList<BindingEvent>(); for(BindingScan scan : scans) { try { Collection<BindingEvent> events = loader.loadEvents(scan, a); evts.addAll(events); } catch (SQLException e) { e.printStackTrace(); } } return evts.iterator(); } }
mit
selvasingh/azure-sdk-for-java
sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/ApiCreateOrUpdateParameter.java
18268
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.apimanagement.v2019_12_01; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; /** * API Create or Update Parameters. */ @JsonFlatten public class ApiCreateOrUpdateParameter { /** * Description of the API. May include HTML formatting tags. */ @JsonProperty(value = "properties.description") private String description; /** * Collection of authentication settings included into this API. */ @JsonProperty(value = "properties.authenticationSettings") private AuthenticationSettingsContract authenticationSettings; /** * Protocols over which API is made available. */ @JsonProperty(value = "properties.subscriptionKeyParameterNames") private SubscriptionKeyParameterNamesContract subscriptionKeyParameterNames; /** * Type of API. Possible values include: 'http', 'soap'. */ @JsonProperty(value = "properties.type") private ApiType apiType; /** * Describes the Revision of the Api. If no value is provided, default * revision 1 is created. */ @JsonProperty(value = "properties.apiRevision") private String apiRevision; /** * Indicates the Version identifier of the API if the API is versioned. */ @JsonProperty(value = "properties.apiVersion") private String apiVersion; /** * Indicates if API revision is current api revision. */ @JsonProperty(value = "properties.isCurrent") private Boolean isCurrent; /** * Indicates if API revision is accessible via the gateway. */ @JsonProperty(value = "properties.isOnline", access = JsonProperty.Access.WRITE_ONLY) private Boolean isOnline; /** * Description of the Api Revision. */ @JsonProperty(value = "properties.apiRevisionDescription") private String apiRevisionDescription; /** * Description of the Api Version. */ @JsonProperty(value = "properties.apiVersionDescription") private String apiVersionDescription; /** * A resource identifier for the related ApiVersionSet. */ @JsonProperty(value = "properties.apiVersionSetId") private String apiVersionSetId; /** * Specifies whether an API or Product subscription is required for * accessing the API. */ @JsonProperty(value = "properties.subscriptionRequired") private Boolean subscriptionRequired; /** * API identifier of the source API. */ @JsonProperty(value = "properties.sourceApiId") private String sourceApiId; /** * API name. Must be 1 to 300 characters long. */ @JsonProperty(value = "properties.displayName") private String displayName; /** * Absolute URL of the backend service implementing this API. Cannot be * more than 2000 characters long. */ @JsonProperty(value = "properties.serviceUrl") private String serviceUrl; /** * Relative URL uniquely identifying this API and all of its resource paths * within the API Management service instance. It is appended to the API * endpoint base URL specified during the service instance creation to form * a public URL for this API. */ @JsonProperty(value = "properties.path", required = true) private String path; /** * Describes on which protocols the operations in this API can be invoked. */ @JsonProperty(value = "properties.protocols") private List<Protocol> protocols; /** * Version set details. */ @JsonProperty(value = "properties.apiVersionSet") private ApiVersionSetContractDetails apiVersionSet; /** * Content value when Importing an API. */ @JsonProperty(value = "properties.value") private String value; /** * Format of the Content in which the API is getting imported. Possible * values include: 'wadl-xml', 'wadl-link-json', 'swagger-json', * 'swagger-link-json', 'wsdl', 'wsdl-link', 'openapi', 'openapi+json', * 'openapi-link', 'openapi+json-link'. */ @JsonProperty(value = "properties.format") private ContentFormat format; /** * Criteria to limit import of WSDL to a subset of the document. */ @JsonProperty(value = "properties.wsdlSelector") private ApiCreateOrUpdatePropertiesWsdlSelector wsdlSelector; /** * Type of Api to create. * * `http` creates a SOAP to REST API * * `soap` creates a SOAP pass-through API. Possible values include: * 'SoapToRest', 'SoapPassThrough'. */ @JsonProperty(value = "properties.apiType") private SoapApiType soapApiType; /** * Get description of the API. May include HTML formatting tags. * * @return the description value */ public String description() { return this.description; } /** * Set description of the API. May include HTML formatting tags. * * @param description the description value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withDescription(String description) { this.description = description; return this; } /** * Get collection of authentication settings included into this API. * * @return the authenticationSettings value */ public AuthenticationSettingsContract authenticationSettings() { return this.authenticationSettings; } /** * Set collection of authentication settings included into this API. * * @param authenticationSettings the authenticationSettings value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withAuthenticationSettings(AuthenticationSettingsContract authenticationSettings) { this.authenticationSettings = authenticationSettings; return this; } /** * Get protocols over which API is made available. * * @return the subscriptionKeyParameterNames value */ public SubscriptionKeyParameterNamesContract subscriptionKeyParameterNames() { return this.subscriptionKeyParameterNames; } /** * Set protocols over which API is made available. * * @param subscriptionKeyParameterNames the subscriptionKeyParameterNames value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withSubscriptionKeyParameterNames(SubscriptionKeyParameterNamesContract subscriptionKeyParameterNames) { this.subscriptionKeyParameterNames = subscriptionKeyParameterNames; return this; } /** * Get type of API. Possible values include: 'http', 'soap'. * * @return the apiType value */ public ApiType apiType() { return this.apiType; } /** * Set type of API. Possible values include: 'http', 'soap'. * * @param apiType the apiType value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiType(ApiType apiType) { this.apiType = apiType; return this; } /** * Get describes the Revision of the Api. If no value is provided, default revision 1 is created. * * @return the apiRevision value */ public String apiRevision() { return this.apiRevision; } /** * Set describes the Revision of the Api. If no value is provided, default revision 1 is created. * * @param apiRevision the apiRevision value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiRevision(String apiRevision) { this.apiRevision = apiRevision; return this; } /** * Get indicates the Version identifier of the API if the API is versioned. * * @return the apiVersion value */ public String apiVersion() { return this.apiVersion; } /** * Set indicates the Version identifier of the API if the API is versioned. * * @param apiVersion the apiVersion value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiVersion(String apiVersion) { this.apiVersion = apiVersion; return this; } /** * Get indicates if API revision is current api revision. * * @return the isCurrent value */ public Boolean isCurrent() { return this.isCurrent; } /** * Set indicates if API revision is current api revision. * * @param isCurrent the isCurrent value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withIsCurrent(Boolean isCurrent) { this.isCurrent = isCurrent; return this; } /** * Get indicates if API revision is accessible via the gateway. * * @return the isOnline value */ public Boolean isOnline() { return this.isOnline; } /** * Get description of the Api Revision. * * @return the apiRevisionDescription value */ public String apiRevisionDescription() { return this.apiRevisionDescription; } /** * Set description of the Api Revision. * * @param apiRevisionDescription the apiRevisionDescription value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiRevisionDescription(String apiRevisionDescription) { this.apiRevisionDescription = apiRevisionDescription; return this; } /** * Get description of the Api Version. * * @return the apiVersionDescription value */ public String apiVersionDescription() { return this.apiVersionDescription; } /** * Set description of the Api Version. * * @param apiVersionDescription the apiVersionDescription value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiVersionDescription(String apiVersionDescription) { this.apiVersionDescription = apiVersionDescription; return this; } /** * Get a resource identifier for the related ApiVersionSet. * * @return the apiVersionSetId value */ public String apiVersionSetId() { return this.apiVersionSetId; } /** * Set a resource identifier for the related ApiVersionSet. * * @param apiVersionSetId the apiVersionSetId value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiVersionSetId(String apiVersionSetId) { this.apiVersionSetId = apiVersionSetId; return this; } /** * Get specifies whether an API or Product subscription is required for accessing the API. * * @return the subscriptionRequired value */ public Boolean subscriptionRequired() { return this.subscriptionRequired; } /** * Set specifies whether an API or Product subscription is required for accessing the API. * * @param subscriptionRequired the subscriptionRequired value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withSubscriptionRequired(Boolean subscriptionRequired) { this.subscriptionRequired = subscriptionRequired; return this; } /** * Get aPI identifier of the source API. * * @return the sourceApiId value */ public String sourceApiId() { return this.sourceApiId; } /** * Set aPI identifier of the source API. * * @param sourceApiId the sourceApiId value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withSourceApiId(String sourceApiId) { this.sourceApiId = sourceApiId; return this; } /** * Get aPI name. Must be 1 to 300 characters long. * * @return the displayName value */ public String displayName() { return this.displayName; } /** * Set aPI name. Must be 1 to 300 characters long. * * @param displayName the displayName value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withDisplayName(String displayName) { this.displayName = displayName; return this; } /** * Get absolute URL of the backend service implementing this API. Cannot be more than 2000 characters long. * * @return the serviceUrl value */ public String serviceUrl() { return this.serviceUrl; } /** * Set absolute URL of the backend service implementing this API. Cannot be more than 2000 characters long. * * @param serviceUrl the serviceUrl value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withServiceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; return this; } /** * Get relative URL uniquely identifying this API and all of its resource paths within the API Management service instance. It is appended to the API endpoint base URL specified during the service instance creation to form a public URL for this API. * * @return the path value */ public String path() { return this.path; } /** * Set relative URL uniquely identifying this API and all of its resource paths within the API Management service instance. It is appended to the API endpoint base URL specified during the service instance creation to form a public URL for this API. * * @param path the path value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withPath(String path) { this.path = path; return this; } /** * Get describes on which protocols the operations in this API can be invoked. * * @return the protocols value */ public List<Protocol> protocols() { return this.protocols; } /** * Set describes on which protocols the operations in this API can be invoked. * * @param protocols the protocols value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withProtocols(List<Protocol> protocols) { this.protocols = protocols; return this; } /** * Get version set details. * * @return the apiVersionSet value */ public ApiVersionSetContractDetails apiVersionSet() { return this.apiVersionSet; } /** * Set version set details. * * @param apiVersionSet the apiVersionSet value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withApiVersionSet(ApiVersionSetContractDetails apiVersionSet) { this.apiVersionSet = apiVersionSet; return this; } /** * Get content value when Importing an API. * * @return the value value */ public String value() { return this.value; } /** * Set content value when Importing an API. * * @param value the value value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withValue(String value) { this.value = value; return this; } /** * Get format of the Content in which the API is getting imported. Possible values include: 'wadl-xml', 'wadl-link-json', 'swagger-json', 'swagger-link-json', 'wsdl', 'wsdl-link', 'openapi', 'openapi+json', 'openapi-link', 'openapi+json-link'. * * @return the format value */ public ContentFormat format() { return this.format; } /** * Set format of the Content in which the API is getting imported. Possible values include: 'wadl-xml', 'wadl-link-json', 'swagger-json', 'swagger-link-json', 'wsdl', 'wsdl-link', 'openapi', 'openapi+json', 'openapi-link', 'openapi+json-link'. * * @param format the format value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withFormat(ContentFormat format) { this.format = format; return this; } /** * Get criteria to limit import of WSDL to a subset of the document. * * @return the wsdlSelector value */ public ApiCreateOrUpdatePropertiesWsdlSelector wsdlSelector() { return this.wsdlSelector; } /** * Set criteria to limit import of WSDL to a subset of the document. * * @param wsdlSelector the wsdlSelector value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withWsdlSelector(ApiCreateOrUpdatePropertiesWsdlSelector wsdlSelector) { this.wsdlSelector = wsdlSelector; return this; } /** * Get type of Api to create. * `http` creates a SOAP to REST API * `soap` creates a SOAP pass-through API. Possible values include: 'SoapToRest', 'SoapPassThrough'. * * @return the soapApiType value */ public SoapApiType soapApiType() { return this.soapApiType; } /** * Set type of Api to create. * `http` creates a SOAP to REST API * `soap` creates a SOAP pass-through API. Possible values include: 'SoapToRest', 'SoapPassThrough'. * * @param soapApiType the soapApiType value to set * @return the ApiCreateOrUpdateParameter object itself. */ public ApiCreateOrUpdateParameter withSoapApiType(SoapApiType soapApiType) { this.soapApiType = soapApiType; return this; } }
mit
rootulp/school
cs102/PATEL10/SquaresStable/ui/ControlPanel.java
370
package ui; import util.Score; import util.Clock; import javax.swing.*; public interface ControlPanel { public void setButtonPanel(JPanel buttonPanel); public void setScorePanel(JPanel scorePanel); public void setGameScore(Score squares); public void setMatchScore(Score games); public void setProgress(Clock clock); public int getGames(); }
mit
klaskoski/become-a-full-stack-developer-with-spring-aws-and-stripe
src/main/java/com/training/fullstack/backend/service/SmtpEmailService.java
804
package com.training.fullstack.backend.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; /** * Real implementation of an email service. * * Created by tedonema on 22/03/2016. */ public class SmtpEmailService extends AbstractEmailService { /** The application logger */ private static final Logger LOG = LoggerFactory.getLogger(SmtpEmailService.class); @Autowired private MailSender mailSender; @Override public void sendGenericEmailMessage(SimpleMailMessage message) { LOG.debug("Sending email for: {}", message); mailSender.send(message); LOG.info("Email sent."); } }
mit
tobciu/NotifyMyAndroidLib
src/main/java/de/tobj/nma/client/request/IContentType.java
106
package de.tobj.nma.client.request; public interface IContentType { public abstract String getValue(); }
mit
fujibee/hudson
core/src/main/java/hudson/model/FingerprintMap.java
4180
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import hudson.Util; import hudson.util.KeyedDataStorage; import java.io.File; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; /** * Cache of {@link Fingerprint}s. * * <p> * This implementation makes sure that no two {@link Fingerprint} objects * lie around for the same hash code, and that unused {@link Fingerprint} * will be adequately GC-ed to prevent memory leak. * * @author Kohsuke Kawaguchi * @see Hudson#getFingerprintMap() */ public final class FingerprintMap extends KeyedDataStorage<Fingerprint,FingerprintParams> { /** * @deprecated * Some old version of Hudson incorrectly serialized this information to the disk. * So we need this field to be here for such configuration to be read correctly. * This field is otherwise no longer in use. */ private transient ConcurrentHashMap<String,Object> core = new ConcurrentHashMap<String,Object>(); /** * Returns true if there's some data in the fingerprint database. */ public boolean isReady() { return new File( Hudson.getInstance().getRootDir(),"fingerprints").exists(); } /** * @param build * set to non-null if {@link Fingerprint} to be created (if so) * will have this build as the owner. Otherwise null, to indicate * an owner-less build. */ public Fingerprint getOrCreate(AbstractBuild build, String fileName, byte[] md5sum) throws IOException { return getOrCreate(build,fileName, Util.toHexString(md5sum)); } public Fingerprint getOrCreate(AbstractBuild build, String fileName, String md5sum) throws IOException { return super.getOrCreate(md5sum, new FingerprintParams(build,fileName)); } protected Fingerprint get(String md5sum, boolean createIfNotExist, FingerprintParams createParams) throws IOException { // sanity check if(md5sum.length()!=32) return null; // illegal input md5sum = md5sum.toLowerCase(); return super.get(md5sum,createIfNotExist,createParams); } private byte[] toByteArray(String md5sum) { byte[] data = new byte[16]; for( int i=0; i<md5sum.length(); i+=2 ) data[i/2] = (byte)Integer.parseInt(md5sum.substring(i,i+2),16); return data; } protected Fingerprint create(String md5sum, FingerprintParams createParams) throws IOException { return new Fingerprint(createParams.build, createParams.fileName, toByteArray(md5sum)); } protected Fingerprint load(String key) throws IOException { return Fingerprint.load(toByteArray(key)); } } class FingerprintParams { /** * Null if the build isn't claiming to be the owner. */ final AbstractBuild build; final String fileName; public FingerprintParams(AbstractBuild build, String fileName) { this.build = build; this.fileName = fileName; assert fileName!=null; } }
mit
InnovateUKGitHub/innovation-funding-service
common/ifs-rest-api-service/src/main/java/org/innovateuk/ifs/questionnaire/config/service/QuestionnaireOptionRestServiceImpl.java
955
package org.innovateuk.ifs.questionnaire.config.service; import org.innovateuk.ifs.crud.AbstractIfsCrudRestServiceImpl; import org.innovateuk.ifs.questionnaire.resource.QuestionnaireOptionResource; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Service; import java.util.List; @Service public class QuestionnaireOptionRestServiceImpl extends AbstractIfsCrudRestServiceImpl<QuestionnaireOptionResource, Long> implements QuestionnaireOptionRestService { @Override protected String getBaseUrl() { return "/questionnaire-option"; } @Override protected Class<QuestionnaireOptionResource> getResourceClass() { return QuestionnaireOptionResource.class; } @Override protected ParameterizedTypeReference<List<QuestionnaireOptionResource>> getListTypeReference() { return new ParameterizedTypeReference<List<QuestionnaireOptionResource>>() {}; } }
mit
bkahlert/signature-generator
signaturegenerator/src/main/java/com/bkahlert/devel/signaturegenerator/model/ConfigFactory.java
338
package com.bkahlert.devel.signaturegenerator.model; import java.io.File; import java.io.IOException; import com.bkahlert.devel.signaturegenerator.persistence.ConfigSerializer; public class ConfigFactory { public static IConfig readFromFile(File configFile) throws IOException { return new ConfigSerializer().read(configFile); } }
mit
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/model/ThreadStatus.java
6792
/* * The MIT License * * Copyright (c) 2014 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.olivergondza.dumpling.model; import java.lang.Thread.State; import java.util.Arrays; import java.util.List; import java.util.concurrent.locks.LockSupport; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * Thread status. * * More detailed version of {@link java.lang.Thread.State}. * * @author ogondza */ public enum ThreadStatus { NEW ("NEW", State.NEW), RUNNABLE ("RUNNABLE", State.RUNNABLE), SLEEPING ("TIMED_WAITING (sleeping)", State.TIMED_WAITING), /** * Thread in {@link Object#wait()}. * * @see java.lang.Thread.State#WAITING */ IN_OBJECT_WAIT ("WAITING (on object monitor)", State.WAITING), /** * Thread in {@link Object#wait(long)}. * * @see java.lang.Thread.State#TIMED_WAITING */ IN_OBJECT_WAIT_TIMED("TIMED_WAITING (on object monitor)", State.TIMED_WAITING), /** * Thread in {@link LockSupport#park()}. * * @see java.lang.Thread.State#WAITING */ PARKED ("WAITING (parking)", State.WAITING), /** * Thread in {@link LockSupport#parkNanos}. * * @see java.lang.Thread.State#TIMED_WAITING */ PARKED_TIMED ("TIMED_WAITING (parking)", State.TIMED_WAITING), BLOCKED ("BLOCKED (on object monitor)", State.BLOCKED), TERMINATED ("TERMINATED", State.TERMINATED), /** * Runtime factory was not able to determine thread state. * * This can happen for service threads in threaddump. */ UNKNOWN ("UNKNOWN", null); /** * Description used in thread dump. */ private final @Nonnull String name; /** * Matching java.lang.Thread.State. */ private final State state; ThreadStatus(@Nonnull String name, State state) { this.name = name; this.state = state; } public @Nonnull String getName() { return name; } public @CheckForNull State getState() { return state; } /** * Newly create thread * * @see java.lang.Thread.State#NEW */ public boolean isNew() { return this == NEW; } /** * Thread that is runnable / running. * * @see java.lang.Thread.State#RUNNABLE */ public boolean isRunnable() { return this == RUNNABLE; } /** * Thread in {@link Thread#sleep(long)} or {@link Thread#sleep(long, int)} waiting to be notified. * * @see java.lang.Thread.State#TIMED_WAITING */ public boolean isSleeping() { return this == SLEEPING; } /** * Thread in {@link Object#wait()} or {@link Object#wait(long)}. * * @see java.lang.Thread.State#WAITING * @see java.lang.Thread.State#TIMED_WAITING */ public boolean isWaiting() { return this == IN_OBJECT_WAIT || this == IN_OBJECT_WAIT_TIMED; } /** * Thread in {@link LockSupport#park()} or {@link LockSupport#parkNanos}. * * @see java.lang.Thread.State#WAITING * @see java.lang.Thread.State#TIMED_WAITING */ public boolean isParked() { return this == PARKED || this == PARKED_TIMED; } /** * Thread (re-)entering a synchronization block. * * @see java.lang.Thread.State#BLOCKED */ public boolean isBlocked() { return this == BLOCKED; } /** * Thread that terminated execution. * * @see java.lang.Thread.State#TERMINATED */ public boolean isTerminated() { return this == TERMINATED; } public static @Nonnull ThreadStatus fromString(String title) { try { @SuppressWarnings("null") final @Nonnull ThreadStatus value = Enum.valueOf(ThreadStatus.class, title); return value; } catch (IllegalArgumentException ex) { for (ThreadStatus value: values()) { if (value.getName().equals(title)) return value; } throw ex; } } public static @Nonnull ThreadStatus fromState(@Nonnull Thread.State state, @CheckForNull StackTraceElement head) { switch (state) { case NEW: return NEW; case RUNNABLE: return RUNNABLE; case BLOCKED: return BLOCKED; case WAITING: return waitingState(false, head); // Not exact case TIMED_WAITING: return waitingState(true, head); // Not exact case TERMINATED: return TERMINATED; default: return UNKNOWN; } } private static @Nonnull ThreadStatus waitingState(boolean timed, @CheckForNull StackTraceElement head) { if (head == null) return ThreadStatus.UNKNOWN; if ("sleep".equals(head.getMethodName()) && "java.lang.Thread".equals(head.getClassName())) return SLEEPING; if ("wait".equals(head.getMethodName()) && "java.lang.Object".equals(head.getClassName())) { return timed ? IN_OBJECT_WAIT_TIMED : IN_OBJECT_WAIT; } if ("park".equals(head.getMethodName()) && UNSAFE.contains(head.getClassName())) { return timed ? PARKED_TIMED : PARKED; } throw new AssertionError("Unable to infer ThreadStatus from WAITING state in " + head); } public static final List<String> UNSAFE = Arrays.asList( "sun.misc.Unsafe", // hotspot JDK 8 and older "jdk.internal.misc.Unsafe" // hotspot JDK 9 ); }
mit
pfreiberg/knparser
src/main/java/cz/pfreiberg/knparser/exporter/oracleloaderfile/KrajeOracleLoaderFileExporter.java
859
package cz.pfreiberg.knparser.exporter.oracleloaderfile; import java.util.List; import cz.pfreiberg.knparser.domain.nemovitosti.Kraje; public class KrajeOracleLoaderFileExporter extends OracleLoaderFileExporter { private final static String name = "KRAJE"; public KrajeOracleLoaderFileExporter(List<Kraje> kraje, String characterSet, String output, String prefix) { super(kraje, characterSet, output, prefix, name); } @Override public String makeControlFile(String controlFile) { controlFile = super.insertColumn(controlFile, "KOD"); controlFile = super.insertVarcharColumn(controlFile, "NAZEV", "20"); controlFile = super.insertDateColumn(controlFile, "PLATNOST_OD"); controlFile = super.insertDateColumn(controlFile, "PLATNOST_DO"); controlFile = super.end(controlFile); return controlFile; } }
mit
tilosp/robotremote
app/src/main/java/de/tilosp/robotremote/SettingsActivity.java
403
package de.tilosp.robotremote; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); } }
mit
sliechti/feedrdr
src/main/java/feedreader/config/FeedAppConfig.java
5255
package feedreader.config; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.reflect.FieldUtils; /** * TODO: Implement. The class could/should be moved to store and have an init * method, like the other store classes. When the class is loaded it restores * the values from the db to the field variables. * * Question: What happens when you have 4 tomcats running? * * Field variables here are not final, because: * * The values will be loaded from the database. * * The values in the database will be saved from the admin panel. * * The admin panel will save to the database and override the values here. * */ public class FeedAppConfig { public static String APP_NAME = "FeedRdr"; public static String APP_DOMAIN = "http://feedrdr.co"; public static String APP_VERSION = "v1.1"; /** set by {@link FeedAppConfig} */ public static String APP_NAME_URL = "feedrdr.co"; public static String BASE_APP_URL = "/feedreader"; public static String BASE_APP_URL_EMAIL = "http://feedrdr.co"; public static String BASE_API_URL = BASE_APP_URL + "/api"; public static String BASE_ADMIN_URL = "/venus"; public static String DOWNLOAD_XML_PATH = ""; public static List<String> SUPPORTED_LANGS = Arrays.asList("en"); // Move to context config. AUtoConfig for PROD and DEV. public static int DELAY_CHECK_FORGOT_PASSWORD = 15; public static int DELAY_CHECK_NEW_USERS_EMAIL = 15; public static int DEFAULT_LOG_LEVEL = 2; public static String DEFAULT_LOCALE = Locale.US.toString(); public static String DEFAULT_TIMEZONE = "GMT"; public static String DEFAULT_PROFILE_COLOR = "CACACA"; public static String DEFAULT_PROFILE_NAME = "DEFAULT"; public static int DEFAULT_READER_ARTICLES_PER_PAGE = 10; public static int DEFAULT_READER_NEWS_LINE_TITLE_LEN = 100; public static int DEFAULT_API_FETCH_ARTICLES = 15; public static String DEFAULT_API_SORT_PUBLICATION_DATE = "DESC"; public static String DEFAULT_API_SORT_STREAM_GROUP_LIST = "DESC"; public static String DEFAULT_API_SORT_USER_SUBSCRIPTIONS_LIST = "ASC"; public static String DEFAULT_API_SORT_PROFILES = "ASC"; public static boolean XML_GATHER_INFO = false; public static boolean DOWNLOAD_XML_FILES = false; public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); public static String FETCH_USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0"; /* * This should be changed to whatever interval is defined in the source. * Check RSS/Atom/RDF channel header. */ public static int FETCH_SOURCE_WAIT_INTERVAL_IN_SECS = 60 * 20; public static int FETCH_CONNECTION_TIMEOUT = 5000; public static int FETCH_READ_TIMEOUT = 5000; public static int FETCH_RETRY_AMOUNT = 10; public static String FETCH_ALLOWED_IMAGE_EXTENSIONS = ".*\\.jp.*g.*|.*\\.png.*|.*\\.gif.*"; public static int MAX_PROFILES_COUNT = 10; public static int DEFAULT_API_MAX_CONTENT_LEN = 250; public static int MAX_REG_EMAILS_PER_RUN = 10; public static int MAX_FORGOTTEN_EMAILS_PER_RUN = 1; public static String MAIL_FETCHER_EMAIL = "mailer@feedrdr.co"; public static String MAIL_BCC_ADDRESS = "steven@feedrdr.co"; public static String MAIL_REG_FROM = "mailer@feedrdr.co"; public static String MAIL_FETCHER_TO = "steven@feedrdr.co"; public static boolean FETCH_FORCE_DELETE = false; public static long DELAY_FETCH_IN_S = 3; public static long DELAY_VALIDATE_IN_S = 3; public static int FETCH_SEND_STATUS_EVERY_MINUTES = 60 * 4; // 4 times a // day. public static boolean DEBUG_EMAIL = false; public static final int USER_0_VAL = 0; public static int USER_0_MAX_DAYS_BACK = -8; public static final int USER_1_VAL = 1; public static int USER_1_MAX_DAYS_BACK = -15; public static final int USER_2_VAL = 2; public static int USER_2_MAX_DAYS_BACK = -31; public static final int DEFAULT_USER_VAL = USER_0_VAL; public static long CACHE_UNREAD_TIME = 60 * 30 * 1000; // 30 min. public static long MAX_TIME_GO_BACK = (60 * 60 * 4 * 1000); // 4h, it // assumes it // takes less // than 4h to // loop over all // feedsources. public static String printAllFields() throws Exception { List<Field> fields = FieldUtils.getAllFieldsList(FeedAppConfig.class); StringBuilder sb = new StringBuilder(); for (Field f : fields) { sb.append(f.getName()).append("=[").append(FieldUtils.readStaticField(f)).append("] "); } return sb.toString(); } }
mit
Azure/azure-sdk-for-java
sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/implementation/JobsImpl.java
1709
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.recoveryservicesbackup.implementation; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.recoveryservicesbackup.fluent.JobsClient; import com.azure.resourcemanager.recoveryservicesbackup.models.Jobs; import com.fasterxml.jackson.annotation.JsonIgnore; public final class JobsImpl implements Jobs { @JsonIgnore private final ClientLogger logger = new ClientLogger(JobsImpl.class); private final JobsClient innerClient; private final com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager serviceManager; public JobsImpl( JobsClient innerClient, com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public void export(String vaultName, String resourceGroupName) { this.serviceClient().export(vaultName, resourceGroupName); } public Response<Void> exportWithResponse( String vaultName, String resourceGroupName, String filter, Context context) { return this.serviceClient().exportWithResponse(vaultName, resourceGroupName, filter, context); } private JobsClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager manager() { return this.serviceManager; } }
mit
UTN-FRRe/programacioncompetitiva
src/Unidad3/Guerra/MainMap.java
1273
import java.util.*; import java.io.*; public class MainMap { public static void add(Map<Integer,Integer> s, int x) { if (!s.containsKey(x)) { s.put(x,1); } else { s.put(x,s.get(x)+1); } } public static void erase(Map<Integer,Integer> s, int x) { if (s.get(x) == 1) { s.remove(x); } else { s.put(x,s.get(x)-1); } } public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader (new InputStreamReader(System.in))); int n; n = in.nextInt(); SortedMap<Integer,Integer> x = new TreeMap<Integer,Integer>(), y = new TreeMap<Integer,Integer>(); for (int i=0; i<n; ++i) { add(x,in.nextInt()); } for (int i=0; i<n; ++i) { add(y,in.nextInt()); } int r=0; for (Map.Entry<Integer,Integer> e : y.entrySet()) { for (int k=0; k < e.getValue(); ++k) { SortedMap<Integer,Integer> m = x.headMap(e.getKey()); if (!m.isEmpty()) { r++; erase(x, m.lastKey()); } } } System.out.println(r); } }
mit
kremnev8/AdvancedSpaceStaion-mod
src/main/java/gloomyfolken/hooklib/asm/HookPriority.java
123
package gloomyfolken.hooklib.asm; public enum HookPriority { HIGHEST, HIGH, NORMAL, LOW, LOWEST }
mit
eaglesakura/andriders-central-engine-v3
app/src/main/java/com/eaglesakura/andriders/central/data/base/BaseCalculator.java
568
package com.eaglesakura.andriders.central.data.base; import com.eaglesakura.andriders.util.Clock; public abstract class BaseCalculator { /** * 受け取ったデータが無効となるデフォルト時刻 */ public static final long DATA_TIMEOUT_MS = 1000 * 15; private final Clock mClock; public BaseCalculator(Clock clock) { mClock = clock; } /** * 現在時刻を取得する */ protected long now() { return mClock.now(); } protected Clock getClock() { return mClock; } }
mit
persey86/my_study
src/prove/Read(Write) to file/RewriteOneToTwo.java
1272
package com.javarush.test.level09.lesson11.bonus01; /* Нужно исправить программу, чтобы компилировалась и работала Задача: Программа вводит два имени файла. И копирует первый файл на место заданное вторым именем. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String sourceFileName = reader.readLine(); String destinationFileName = reader.readLine(); java.io.FileInputStream fileInputStream = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream(destinationFileName); int count = 0; while (fileInputStream.available()>0) { int data = fileInputStream.read(); fileOutputStream.write(data); count++; } System.out.println("Скопировано байт " + count); fileInputStream.close(); fileOutputStream.close(); } }
mit
JCThePants/NucleusFramework
tests/src/com/jcwhatever/nucleus/storage/serialize/DataFieldSerializerTest.java
5593
package com.jcwhatever.nucleus.storage.serialize; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.jcwhatever.v1_8_R3.BukkitTester; import com.jcwhatever.nucleus.storage.IDataNode; import com.jcwhatever.nucleus.storage.MemoryDataNode; import com.jcwhatever.nucleus.utils.coords.SyncLocation; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.inventory.ItemStack; import org.junit.Test; /** * Tests {@link DataFieldSerializer}. */ public class DataFieldSerializerTest { private TestClass getTestClass() { TestClass test = new TestClass(); test.str1 = null; test.str2 = "str"; test.b = false; test.b2 = 1; test.s = 2; test.i = 3; test.l = 4L; test.f = 5f; test.d = 6D; test.location = new Location(null, 1, 2, 3); test.itemStack = new ItemStack(Material.GRASS); test.itemStackArray = new ItemStack[] { new ItemStack(Material.HARD_CLAY), new ItemStack(Material.DEAD_BUSH) }; test.serializable.s = "modified"; test.testEnum = TestEnum.CONSTANT2; return test; } @Test public void testSerialize() throws Exception { TestClass test = getTestClass(); MemoryDataNode node = new MemoryDataNode(BukkitTester.mockPlugin("test")); DataFieldSerializer.serialize(test, node); assertEquals(null, node.getString("str1")); assertEquals("str", node.getString("str2")); assertEquals(false, node.getBoolean("b")); assertEquals(1, node.getInteger("b2")); assertEquals(2, node.getInteger("s")); assertEquals(3, node.getInteger("i")); assertEquals(4L, node.getInteger("l")); assertEquals(5f, node.getDouble("f"), 0.0f); assertEquals(6D, node.getDouble("d"), 0.0D); assertEquals(new SyncLocation((World) null, 1, 2, 3), node.getLocation("location")); assertArrayEquals(new ItemStack[]{new ItemStack(Material.GRASS)}, node.getItemStacks("itemStack")); assertArrayEquals(new ItemStack[]{ new ItemStack(Material.HARD_CLAY), new ItemStack(Material.DEAD_BUSH)}, node.getItemStacks("itemStackArray")); assertEquals("modified", node.getString("serializable.s")); assertEquals(TestEnum.CONSTANT2, node.getEnum("testEnum", TestEnum.class)); assertEquals(false, node.hasNode("nonData1")); assertEquals(false, node.hasNode("nonData2")); assertEquals(false, node.hasNode("nonData3")); assertEquals(false, node.hasNode("nonData4")); } @Test public void testDeserializeInto() throws Exception { MemoryDataNode node = new MemoryDataNode(BukkitTester.mockPlugin("test")); DataFieldSerializer.serialize(getTestClass(), node); TestClass test = new TestClass(); DataFieldSerializer.deserializeInto(test, node); assertEquals("", test.str1); assertEquals("str", test.str2); assertEquals(false, test.b); assertEquals(1, test.b2); assertEquals(2, test.s); assertEquals(3, test.i); assertEquals(4L, test.l); assertEquals(5f, test.f, 0.0f); assertEquals(6D, test.d, 0.0D); assertEquals(new SyncLocation((World) null, 1, 2, 3), test.location); assertEquals(new ItemStack(Material.GRASS), test.itemStack); assertArrayEquals(new ItemStack[]{ new ItemStack(Material.HARD_CLAY), new ItemStack(Material.DEAD_BUSH)}, test.itemStackArray); assertEquals("modified", test.serializable.s); assertEquals(TestEnum.CONSTANT2, test.testEnum); assertEquals(true, test.nonData1); assertEquals(13, test.nonData2); assertEquals(14.0f, test.nonData3, 0.0f); assertEquals(new Location(null, 5, 4, 3), test.nonData4); } private static class TestClass { private boolean nonData1 = true; private long nonData2 = 13; private Float nonData3 = 14.0f; private Location nonData4 = new Location(null, 5, 4, 3); @DataField private String str1 = ""; @DataField private String str2 = null; @DataField private boolean b = true; @DataField private byte b2 = 10; @DataField private short s = 11; @DataField private int i = 12; @DataField private long l = 13; @DataField private float f = 14.0f; @DataField private double d = 15.0D; @DataField private Location location = new Location(null, 5, 4, 3); @DataField private ItemStack itemStack = new ItemStack(Material.WOOD); @DataField private ItemStack[] itemStackArray = new ItemStack[] { new ItemStack(Material.PAPER) }; @DataField private SerializableClass serializable = new SerializableClass(); @DataField private TestEnum testEnum = TestEnum.CONSTANT1; } private static class SerializableClass implements IDataNodeSerializable { private String s = "orig"; @Override public void serialize(IDataNode dataNode) { dataNode.set("s", s); } @Override public void deserialize(IDataNode dataNode) throws DeserializeException { s = dataNode.getString("s"); } } private enum TestEnum { CONSTANT1, CONSTANT2 } }
mit
Aichifan/MiniWms
src/main/java/ndm/miniwms/service/impl/IStockInEntriesServiceImpl.java
1376
package ndm.miniwms.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import ndm.miniwms.dao.StockInEntriesMapper; import ndm.miniwms.pojo.StockInEntries; import ndm.miniwms.service.IStockInEntriesService; @Service("stockInEntries") public class IStockInEntriesServiceImpl implements IStockInEntriesService{ @Resource private StockInEntriesMapper stockInEntriesMapper; @Override public List<StockInEntries> all() { return this.stockInEntriesMapper.all(); } @Override public int delById(Integer id) { return this.stockInEntriesMapper.delById(id); } @Override public int update(StockInEntries stockInEntries) { return this.stockInEntriesMapper.update(stockInEntries); } @Override public int add(StockInEntries stockInEntries) { return this.stockInEntriesMapper.add(stockInEntries); } @Override public StockInEntries selectById(Integer id) { return this.stockInEntriesMapper.selectById(id); } @Override public List<StockInEntries> selectTab() { return this.stockInEntriesMapper.selectTab(); } @Override public List<StockInEntries> selectItem(Integer itemId) { return this.stockInEntriesMapper.selectItem(itemId); } @Override public int updateQuantity(StockInEntries stockInEntries) { return this.stockInEntriesMapper.updateQuantity(stockInEntries); } }
mit
navalev/azure-sdk-for-java
sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessagingFactory.java
33004
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.eventhubs.impl; import com.microsoft.azure.eventhubs.CommunicationException; import com.microsoft.azure.eventhubs.ConnectionStringBuilder; import com.microsoft.azure.eventhubs.EventHubException; import com.microsoft.azure.eventhubs.ITokenProvider; import com.microsoft.azure.eventhubs.ManagedIdentityTokenProvider; import com.microsoft.azure.eventhubs.OperationCancelledException; import com.microsoft.azure.eventhubs.ProxyConfiguration; import com.microsoft.azure.eventhubs.RetryPolicy; import com.microsoft.azure.eventhubs.TimeoutException; import com.microsoft.azure.eventhubs.TransportType; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.transport.ErrorCondition; import org.apache.qpid.proton.engine.BaseHandler; import org.apache.qpid.proton.engine.Connection; import org.apache.qpid.proton.engine.EndpointState; import org.apache.qpid.proton.engine.Event; import org.apache.qpid.proton.engine.Handler; import org.apache.qpid.proton.engine.HandlerException; import org.apache.qpid.proton.engine.Link; import org.apache.qpid.proton.engine.Session; import org.apache.qpid.proton.reactor.Reactor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.channels.UnresolvedAddressException; import java.time.Duration; import java.time.Instant; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Abstracts all amqp related details and exposes AmqpConnection object * Manages connection life-cycle */ public final class MessagingFactory extends ClientEntity implements AmqpConnection, SessionProvider, SchedulerProvider { public static final Duration DefaultOperationTimeout = Duration.ofSeconds(60); private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(MessagingFactory.class); private final String hostName; private final CompletableFuture<Void> closeTask; private final ConnectionHandler connectionHandler; private final LinkedList<Link> registeredLinks; private final Object reactorLock; private final Object cbsChannelCreateLock; private final Object mgmtChannelCreateLock; private final ITokenProvider tokenProvider; private final ReactorFactory reactorFactory; private Reactor reactor; private ReactorDispatcher reactorDispatcher; private Connection connection; private CBSChannel cbsChannel; private ManagementChannel mgmtChannel; private Duration operationTimeout; private RetryPolicy retryPolicy; private CompletableFuture<MessagingFactory> open; private CompletableFuture<?> openTimer; private CompletableFuture<?> closeTimer; private String reactorCreationTime; // used when looking at Java dumps, do not remove MessagingFactory(final String hostname, final Duration operationTimeout, final TransportType transportType, final ITokenProvider tokenProvider, final RetryPolicy retryPolicy, final ScheduledExecutorService executor, final ReactorFactory reactorFactory, final ProxyConfiguration proxyConfiguration) { super(StringUtil.getRandomString("MF"), null, executor); if (StringUtil.isNullOrWhiteSpace(hostname)) { throw new IllegalArgumentException("Endpoint hostname cannot be null or empty"); } Objects.requireNonNull(operationTimeout, "Operation timeout cannot be null."); Objects.requireNonNull(transportType, "Transport type cannot be null."); Objects.requireNonNull(tokenProvider, "Token provider cannot be null."); Objects.requireNonNull(retryPolicy, "Retry policy cannot be null."); Objects.requireNonNull(executor, "Executor cannot be null."); Objects.requireNonNull(reactorFactory, "Reactor factory cannot be null."); this.hostName = hostname; this.reactorFactory = reactorFactory; this.operationTimeout = operationTimeout; this.retryPolicy = retryPolicy; this.connectionHandler = ConnectionHandler.create(transportType, this, this.getClientId(), proxyConfiguration); this.tokenProvider = tokenProvider; this.registeredLinks = new LinkedList<>(); this.reactorLock = new Object(); this.cbsChannelCreateLock = new Object(); this.mgmtChannelCreateLock = new Object(); this.closeTask = new CompletableFuture<>(); } public static CompletableFuture<MessagingFactory> createFromConnectionString(final String connectionString, final ScheduledExecutorService executor) throws IOException { return createFromConnectionString(connectionString, null, executor, null); } public static CompletableFuture<MessagingFactory> createFromConnectionString( final String connectionString, final RetryPolicy retryPolicy, final ScheduledExecutorService executor, final ProxyConfiguration proxyConfiguration) throws IOException { return createFromConnectionString(connectionString, retryPolicy, executor, null, proxyConfiguration); } public static CompletableFuture<MessagingFactory> createFromConnectionString( final String connectionString, final RetryPolicy retryPolicy, final ScheduledExecutorService executor, final ReactorFactory reactorFactory, final ProxyConfiguration proxyConfiguration) throws IOException { final ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); ITokenProvider tokenProvider = null; if (!StringUtil.isNullOrWhiteSpace(csb.getSharedAccessSignature())) { tokenProvider = new SharedAccessSignatureTokenProvider(csb.getSharedAccessSignature()); } else if (!StringUtil.isNullOrWhiteSpace(csb.getSasKey())) { tokenProvider = new SharedAccessSignatureTokenProvider(csb.getSasKeyName(), csb.getSasKey()); } else if ((csb.getAuthentication() != null) && csb.getAuthentication().equalsIgnoreCase(ConnectionStringBuilder.MANAGED_IDENTITY_AUTHENTICATION)) { tokenProvider = new ManagedIdentityTokenProvider(); } else { throw new IllegalArgumentException("Connection string must specify a Shared Access Signature, Shared Access Key, or Managed Identity"); } final MessagingFactoryBuilder builder = new MessagingFactoryBuilder(csb.getEndpoint().getHost(), tokenProvider, executor) .setOperationTimeout(csb.getOperationTimeout()) .setTransportType(csb.getTransportType()) .setRetryPolicy(retryPolicy) .setReactorFactory(reactorFactory) .setProxyConfiguration(proxyConfiguration); return builder.build(); } public static class MessagingFactoryBuilder { // These parameters must always be specified by the caller private final String hostname; private final ITokenProvider tokenProvider; private final ScheduledExecutorService executor; // Optional parameters with defaults private Duration operationTimeout = DefaultOperationTimeout; private TransportType transportType = TransportType.AMQP; private RetryPolicy retryPolicy = RetryPolicy.getDefault(); private ReactorFactory reactorFactory = new ReactorFactory(); private ProxyConfiguration proxyConfiguration; public MessagingFactoryBuilder(final String hostname, final ITokenProvider tokenProvider, final ScheduledExecutorService executor) { if (StringUtil.isNullOrWhiteSpace(hostname)) { throw new IllegalArgumentException("Endpoint hostname cannot be null or empty"); } this.hostname = hostname; this.tokenProvider = Objects.requireNonNull(tokenProvider); this.executor = Objects.requireNonNull(executor); } public MessagingFactoryBuilder setOperationTimeout(Duration operationTimeout) { if (operationTimeout != null) { this.operationTimeout = operationTimeout; } return this; } public MessagingFactoryBuilder setTransportType(TransportType transportType) { if (transportType != null) { this.transportType = transportType; } return this; } public MessagingFactoryBuilder setRetryPolicy(RetryPolicy retryPolicy) { if (retryPolicy != null) { this.retryPolicy = retryPolicy; } return this; } public MessagingFactoryBuilder setReactorFactory(ReactorFactory reactorFactory) { if (reactorFactory != null) { this.reactorFactory = reactorFactory; } return this; } public MessagingFactoryBuilder setProxyConfiguration(ProxyConfiguration proxyConfiguration) { this.proxyConfiguration = proxyConfiguration; return this; } public CompletableFuture<MessagingFactory> build() throws IOException { final MessagingFactory messagingFactory = new MessagingFactory(this.hostname, this.operationTimeout, this.transportType, this.tokenProvider, this.retryPolicy, this.executor, this.reactorFactory, this.proxyConfiguration); return MessagingFactory.factoryStartup(messagingFactory); } } private static CompletableFuture<MessagingFactory> factoryStartup(MessagingFactory messagingFactory) throws IOException { messagingFactory.createConnection(); final Timer timer = new Timer(messagingFactory); messagingFactory.openTimer = timer.schedule( new Runnable() { @Override public void run() { if (!messagingFactory.open.isDone()) { messagingFactory.open.completeExceptionally(new TimeoutException("Opening MessagingFactory timed out.")); messagingFactory.getReactor().stop(); } } }, messagingFactory.getOperationTimeout()); // if scheduling messagingfactory openTimer fails - notify user and stop messagingFactory.openTimer.handleAsync( (unUsed, exception) -> { if (exception != null && !(exception instanceof CancellationException)) { messagingFactory.open.completeExceptionally(exception); messagingFactory.getReactor().stop(); } return null; }, messagingFactory.executor); return messagingFactory.open; } @Override public String getHostName() { return this.hostName; } private Reactor getReactor() { synchronized (this.reactorLock) { return this.reactor; } } public ReactorDispatcher getReactorDispatcher() { synchronized (this.reactorLock) { return this.reactorDispatcher; } } public ITokenProvider getTokenProvider() { return this.tokenProvider; } private void createConnection() throws IOException { this.open = new CompletableFuture<>(); this.startReactor(new ReactorHandlerWithConnection()); } private void startReactor(final ReactorHandler reactorHandler) throws IOException { final Reactor newReactor = this.reactorFactory.create(reactorHandler, this.connectionHandler.getMaxFrameSize(), this.getClientId()); synchronized (this.reactorLock) { this.reactor = newReactor; this.reactorDispatcher = new ReactorDispatcher(newReactor); reactorHandler.unsafeSetReactorDispatcher(this.reactorDispatcher); } this.reactorCreationTime = Instant.now().toString(); executor.execute(new RunReactor(newReactor, executor)); } public CBSChannel getCBSChannel() { synchronized (this.cbsChannelCreateLock) { if (this.cbsChannel == null) { this.cbsChannel = new CBSChannel(this, this, this.getClientId(), this.executor); } } return this.cbsChannel; } public ManagementChannel getManagementChannel() { synchronized (this.mgmtChannelCreateLock) { if (this.mgmtChannel == null) { this.mgmtChannel = new ManagementChannel(this, this, this.getClientId(), this.executor); } } return this.mgmtChannel; } @Override public Session getSession(final String path, final Consumer<Session> onRemoteSessionOpen, final BiConsumer<ErrorCondition, Exception> onRemoteSessionOpenError) { if (this.getIsClosingOrClosed()) { onRemoteSessionOpenError.accept(null, new OperationCancelledException("underlying messagingFactory instance is closed")); return null; } if (TRACE_LOGGER.isInfoEnabled()) { TRACE_LOGGER.info( String.format(Locale.US, "messagingFactory[%s], hostName[%s], getting a session.", getClientId(), getHostName())); } if (this.connection == null || this.connection.getLocalState() == EndpointState.CLOSED || this.connection.getRemoteState() == EndpointState.CLOSED) { this.connection = this.getReactor().connectionToHost( this.connectionHandler.getRemoteHostName(), this.connectionHandler.getRemotePort(), this.connectionHandler); } final Session session = this.connection.session(); BaseHandler.setHandler(session, new SessionHandler(path, onRemoteSessionOpen, onRemoteSessionOpenError, this.operationTimeout, this.getClientId())); session.open(); return session; } public Duration getOperationTimeout() { return this.operationTimeout; } public RetryPolicy getRetryPolicy() { return this.retryPolicy; } @Override public void onOpenComplete(Exception exception) { if (exception == null) { this.open.complete(this); // if connection creation is in progress and then msgFactory.close call came thru if (this.getIsClosingOrClosed()) { this.connection.close(); } } else { this.open.completeExceptionally(exception); } if (this.openTimer != null) { this.openTimer.cancel(false); } } @Override public void onConnectionError(ErrorCondition error) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "onConnectionError messagingFactory[%s], hostname[%s], error[%s]", this.getClientId(), this.hostName, error != null ? error.getDescription() : "n/a")); } if (!this.open.isDone()) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "onConnectionError messagingFactory[%s], hostname[%s], open hasn't complete, stopping the reactor", this.getClientId(), this.hostName)); } this.getReactor().stop(); this.onOpenComplete(ExceptionUtil.toException(error)); } else { final Connection oldConnection = this.connection; final List<Link> oldRegisteredLinksCopy = new LinkedList<>(this.registeredLinks); final List<Link> closedLinks = new LinkedList<>(); for (Link link : oldRegisteredLinksCopy) { if (link.getLocalState() != EndpointState.CLOSED) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "onConnectionError messagingFactory[%s], hostname[%s], closing link [%s]", this.getClientId(), this.hostName, link.getName())); } link.setCondition(error); link.close(); closedLinks.add(link); } } // if proton-j detects transport error - onConnectionError is invoked, but, the connection state is not set to closed // in connection recreation we depend on currentConnection state to evaluate need for recreation if (oldConnection.getLocalState() != EndpointState.CLOSED) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "onConnectionError messagingFactory[%s], hostname[%s], closing current connection", this.getClientId(), this.hostName)); } // this should ideally be done in Connectionhandler // - but, since proton doesn't automatically emit close events // for all child objects (links & sessions) we are doing it here oldConnection.setCondition(error); oldConnection.close(); } for (Link link : closedLinks) { final Handler handler = BaseHandler.getHandler(link); if (handler instanceof BaseLinkHandler) { final BaseLinkHandler linkHandler = (BaseLinkHandler) handler; linkHandler.processOnClose(link, error); } } } if (this.getIsClosingOrClosed() && !this.closeTask.isDone()) { this.getReactor().stop(); } } private void onReactorError(Exception cause) { if (!this.open.isDone()) { this.onOpenComplete(cause); } else { if (this.getIsClosingOrClosed()) { return; } TRACE_LOGGER.warn(String.format(Locale.US, "onReactorError messagingFactory[%s], hostName[%s], error[%s]", this.getClientId(), this.getHostName(), cause.getMessage())); final Connection oldConnection = this.connection; final List<Link> oldRegisteredLinksCopy = new LinkedList<>(this.registeredLinks); try { TRACE_LOGGER.info(String.format(Locale.US, "onReactorError messagingFactory[%s], hostName[%s], message[%s]", this.getClientId(), this.getHostName(), "starting new reactor")); this.startReactor(new ReactorHandlerWithConnection()); } catch (IOException e) { TRACE_LOGGER.error(String.format(Locale.US, "messagingFactory[%s], hostName[%s], error[%s]", this.getClientId(), this.getHostName(), ExceptionUtil.toStackTraceString(e, "Re-starting reactor failed with error"))); // TODO: stop retrying on the error after multiple attempts. this.onReactorError(cause); } // when the instance of the reactor itself faults - Connection and Links will not be cleaned up even after the // below .close() calls (local closes). // But, we still need to change the states of these to Closed - so that subsequent retries - will // treat the links and connection as closed and re-establish them and continue running on new Reactor instance. ErrorCondition errorCondition = new ErrorCondition(Symbol.getSymbol("messagingfactory.onreactorerror"), cause.getMessage()); if (oldConnection.getLocalState() != EndpointState.CLOSED) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "onReactorError: messagingFactory[%s], hostname[%s], closing current connection", this.getClientId(), this.hostName)); } oldConnection.setCondition(errorCondition); oldConnection.close(); } for (final Link link : oldRegisteredLinksCopy) { if (link.getLocalState() != EndpointState.CLOSED) { link.setCondition(errorCondition); link.close(); } final Handler handler = BaseHandler.getHandler(link); if (handler instanceof BaseLinkHandler) { final BaseLinkHandler linkHandler = (BaseLinkHandler) handler; linkHandler.processOnClose(link, cause); } } } } @Override protected CompletableFuture<Void> onClose() { if (!this.getIsClosed()) { final Timer timer = new Timer(this); this.closeTimer = timer.schedule(new Runnable() { @Override public void run() { if (!closeTask.isDone()) { closeTask.completeExceptionally(new TimeoutException("Closing MessagingFactory timed out.")); getReactor().stop(); } } }, operationTimeout); if (this.closeTimer.isCompletedExceptionally()) { this.closeTask.completeExceptionally(ExceptionUtil.getExceptionFromCompletedFuture(this.closeTimer)); } else { try { this.scheduleOnReactorThread(new CloseWork()); } catch (IOException | RejectedExecutionException schedulerException) { this.closeTask.completeExceptionally(schedulerException); } } } return this.closeTask; } @Override public void registerForConnectionError(Link link) { this.registeredLinks.add(link); } @Override public void deregisterForConnectionError(Link link) { this.registeredLinks.remove(link); } public void scheduleOnReactorThread(final DispatchHandler handler) throws IOException, RejectedExecutionException { this.getReactorDispatcher().invoke(handler); } public void scheduleOnReactorThread(final int delay, final DispatchHandler handler) throws IOException, RejectedExecutionException { this.getReactorDispatcher().invoke(delay, handler); } public static class ReactorFactory { public Reactor create(final ReactorHandler reactorHandler, final int maxFrameSize, final String name) throws IOException { return ProtonUtil.reactor(reactorHandler, maxFrameSize, name); } } private class CloseWork extends DispatchHandler { @Override public void onEvent() { final ReactorDispatcher dispatcher = getReactorDispatcher(); synchronized (cbsChannelCreateLock) { if (cbsChannel != null) { cbsChannel.close( dispatcher, new OperationResult<Void, Exception>() { @Override public void onComplete(Void result) { if (TRACE_LOGGER.isInfoEnabled()) { TRACE_LOGGER.info( String.format(Locale.US, "messagingFactory[%s], hostName[%s], info[%s]", getClientId(), getHostName(), "cbsChannel closed")); } } @Override public void onError(Exception error) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], cbsChannelCloseError[%s]", getClientId(), getHostName(), error.getMessage())); } } }); } } synchronized (mgmtChannelCreateLock) { if (mgmtChannel != null) { mgmtChannel.close( dispatcher, new OperationResult<Void, Exception>() { @Override public void onComplete(Void result) { if (TRACE_LOGGER.isInfoEnabled()) { TRACE_LOGGER.info( String.format(Locale.US, "messagingFactory[%s], hostName[%s], info[%s]", getClientId(), getHostName(), "mgmtChannel closed")); } } @Override public void onError(Exception error) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], mgmtChannelCloseError[%s]", getClientId(), getHostName(), error.getMessage())); } } }); } } if (connection != null && connection.getRemoteState() != EndpointState.CLOSED && connection.getLocalState() != EndpointState.CLOSED) { connection.close(); } } } private class RunReactor implements Runnable { private final Reactor rctr; private final ScheduledExecutorService executor; volatile boolean hasStarted; RunReactor(final Reactor reactor, final ScheduledExecutorService executor) { this.rctr = reactor; this.executor = executor; this.hasStarted = false; } public void run() { boolean reScheduledReactor = false; try { if (!this.hasStarted) { if (TRACE_LOGGER.isInfoEnabled()) { TRACE_LOGGER.info(String.format(Locale.US, "messagingFactory[%s], hostName[%s], info[%s]", getClientId(), getHostName(), "starting reactor instance.")); } this.rctr.start(); this.hasStarted = true; } if (!Thread.interrupted() && this.rctr.process()) { try { this.executor.execute(this); reScheduledReactor = true; } catch (RejectedExecutionException exception) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], error[%s]", getClientId(), getHostName(), ExceptionUtil.toStackTraceString(exception, "scheduling reactor failed because the executor has been shut down"))); } this.rctr.attachments().set(RejectedExecutionException.class, RejectedExecutionException.class, exception); } return; } if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], message[%s]", getClientId(), getHostName(), "stopping the reactor because thread was interrupted or the reactor has no more events to process.")); } this.rctr.stop(); } catch (HandlerException handlerException) { Throwable cause = handlerException.getCause(); if (cause == null) { cause = handlerException; } if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], error[%s]", getClientId(), getHostName(), ExceptionUtil.toStackTraceString(handlerException, "Unhandled exception while processing events in reactor, report this error."))); } final String message = !StringUtil.isNullOrEmpty(cause.getMessage()) ? cause.getMessage() : !StringUtil.isNullOrEmpty(handlerException.getMessage()) ? handlerException.getMessage() : "Reactor encountered unrecoverable error"; final EventHubException sbException; if (cause instanceof UnresolvedAddressException) { sbException = new CommunicationException( String.format(Locale.US, "%s. This is usually caused by incorrect hostname or network configuration. Check correctness of namespace information. %s", message, ExceptionUtil.getTrackingIDAndTimeToLog()), cause); } else { sbException = new EventHubException( true, String.format(Locale.US, "%s, %s", message, ExceptionUtil.getTrackingIDAndTimeToLog()), cause); } MessagingFactory.this.onReactorError(sbException); } finally { if (reScheduledReactor) { return; } if (getIsClosingOrClosed() && !closeTask.isDone()) { this.rctr.free(); closeTask.complete(null); if (closeTimer != null) { closeTimer.cancel(false); } } else { scheduleCompletePendingTasks(); } } } private void scheduleCompletePendingTasks() { this.executor.schedule(new Runnable() { @Override public void run() { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], message[%s]", getClientId(), getHostName(), "Processing all pending tasks and closing old reactor.")); } try { rctr.stop(); rctr.process(); } catch (HandlerException e) { if (TRACE_LOGGER.isWarnEnabled()) { TRACE_LOGGER.warn(String.format(Locale.US, "messagingFactory[%s], hostName[%s], error[%s]", getClientId(), getHostName(), ExceptionUtil.toStackTraceString(e, "scheduleCompletePendingTasks - exception occurred while processing events."))); } } finally { rctr.free(); } } }, MessagingFactory.this.getOperationTimeout().getSeconds(), TimeUnit.SECONDS); } } private class ReactorHandlerWithConnection extends ReactorHandler { ReactorHandlerWithConnection() { super(getClientId()); } @Override public void onReactorInit(Event e) { super.onReactorInit(e); final Reactor r = e.getReactor(); connection = r.connectionToHost( connectionHandler.getRemoteHostName(), connectionHandler.getRemotePort(), connectionHandler); } } }
mit
ltearno/hexa.tools
hexa.binding/src/main/java/fr/lteconsulting/hexa/databinding/propertyadapters/ObjectPropertyAdapter.java
1778
package fr.lteconsulting.hexa.databinding.propertyadapters; import fr.lteconsulting.hexa.client.tools.Action2; import fr.lteconsulting.hexa.databinding.properties.Properties; import fr.lteconsulting.hexa.databinding.properties.PropertyChangedEvent; import fr.lteconsulting.hexa.databinding.properties.PropertyChangedHandler; /** * A PropertyAdapter implementation which is able to work with an object's field or property * * To access the object's property, first the adapter tries to find a getter/setter. Then, if no * access method is found, the adapter works with the object's field value directly. * * @author Arnaud * */ public class ObjectPropertyAdapter implements PropertyAdapter, PropertyChangedHandler { private final Object source; private final String sourceProperty; private Action2<PropertyAdapter, Object> callback; private Object cookie; public ObjectPropertyAdapter( Object source, String sourceProperty ) { this.source = source; this.sourceProperty = sourceProperty; } @Override public Object registerPropertyChanged( Action2<PropertyAdapter, Object> callback, Object cookie ) { if( source == null ) return null; this.callback = callback; this.cookie = cookie; return Properties.register( source, sourceProperty, this ); } @Override public void removePropertyChangedHandler( Object registration ) { Properties.removeHandler( registration ); } @Override public Object getValue() { return Properties.getValue( source, sourceProperty ); } @Override public void setValue( Object value ) { Properties.setValue( source, sourceProperty, value ); } @Override public void onPropertyChanged( PropertyChangedEvent event ) { if( callback == null ) return; callback.exec( this, cookie ); } }
mit
Jumper456/Chessboard
src/net/yotvoo/chessGUI/ChessboardGUIController.java
877
package net.yotvoo.chessGUI; import javafx.scene.control.TextArea; import net.yotvoo.chessnet.ClientGUI; import net.yotvoo.chessnet.ServerGUI; public class ChessboardGUIController implements ClientGUI, ServerGUI { TextArea chatTextArea; public ChessboardGUIController(TextArea textArea) { chatTextArea = textArea; } @Override public void append(String textStr) { chatTextArea.appendText("\n" + textStr); } @Override public void connectionFailed() { chatTextArea.appendText("\nBłąd - Połączenie zostało przerwane lub nie udało się go nawiązać."); } @Override public void appendEvent(String eventStr) { chatTextArea.appendText("\n event: " + eventStr); } @Override public void appendRoom(String roomStr) { chatTextArea.appendText("\n room: " + roomStr); } }
mit
nfl/glitr
src/main/java/com/nfl/glitr/registry/type/GraphQLObjectTypeFactory.java
7757
package com.nfl.glitr.registry.type; import com.nfl.glitr.annotation.GlitrDeprecated; import com.nfl.glitr.annotation.GlitrDescription; import com.nfl.glitr.annotation.GlitrQueryComplexity; import com.nfl.glitr.registry.TypeRegistry; import com.nfl.glitr.registry.schema.GlitrFieldDefinition; import com.nfl.glitr.registry.schema.GlitrMetaDefinition; import com.nfl.glitr.util.ReflectionUtil; import graphql.schema.*; import org.apache.commons.lang3.tuple.Pair; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.stream.Collectors; import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_FORMULA_KEY; import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_IGNORE_KEY; import static graphql.Scalars.GraphQLBoolean; import static graphql.schema.FieldCoordinates.coordinates; import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition; import static graphql.schema.GraphQLObjectType.newObject; /** * Factory implementation for the creation of {@link GraphQLObjectType} */ public class GraphQLObjectTypeFactory implements DelegateTypeFactory { public static final String UNUSED_FIELDS_DEAD_OBJECT = "unused_fields_dead_object"; private final TypeRegistry typeRegistry; private final GraphQLCodeRegistry.Builder codeRegistryBuilder; public GraphQLObjectTypeFactory(TypeRegistry typeRegistry, GraphQLCodeRegistry.Builder codeRegistryBuilder) { this.typeRegistry = typeRegistry; this.codeRegistryBuilder = codeRegistryBuilder; } @Override public GraphQLOutputType create(Class clazz) { return createObjectType(clazz); } /** * Creates the {@link GraphQLObjectType} dynamically for pretty much any pojo class with public accessors * * @param clazz class to be introspected * @return {@link GraphQLObjectType} object exposed via graphQL */ private GraphQLObjectType createObjectType(Class clazz) { Map<String, Pair<Method, Class>> methods = ReflectionUtil.getMethodMap(clazz); // add extra methods from outside the inspected class coming from an override object typeRegistry.addExtraMethodsToTheSchema(clazz, methods); List<GraphQLFieldDefinition> fields = methods.values().stream() .map(pair -> getGraphQLFieldDefinition(clazz, pair)) .collect(Collectors.toList()); if (fields.isEmpty()) { codeRegistryBuilder.dataFetcher(coordinates(clazz.getSimpleName(), UNUSED_FIELDS_DEAD_OBJECT), DataFetcherFactories.useDataFetcher(env -> false)); // GraphiQL doesn't like objects with no fields, so add an unused field to be safe. fields.add(newFieldDefinition() .name(UNUSED_FIELDS_DEAD_OBJECT) .type(GraphQLBoolean) .build()); } // implemented interfaces List<GraphQLInterfaceType> graphQLInterfaceTypes = retrieveInterfacesForType(clazz); // extended abstract classes List<GraphQLInterfaceType> graphQLAbstractClassTypes = retrieveAbstractClassesForType(clazz); graphQLInterfaceTypes.addAll(graphQLAbstractClassTypes); GraphQLObjectType.Builder builder = newObject() .name(clazz.getSimpleName()) .description(ReflectionUtil.getDescriptionFromAnnotatedElement(clazz)) .withInterfaces(graphQLInterfaceTypes.toArray(new GraphQLInterfaceType[0])) .fields(fields); // relay is enabled, add Node interface implementation if one of the eligible methods is named getId if (typeRegistry.getNodeInterface() != null && methods.keySet().stream().anyMatch(name -> name.equals("getId")) && !typeRegistry.isExplicitRelayNodeScanEnabled()) { builder.withInterface(typeRegistry.getNodeInterface()); } return builder.build(); } /** * Look up and inspect abstract class extended by a specific class * * @param clazz being inspected * @return list of {@link GraphQLInterfaceType} */ public List<GraphQLInterfaceType> retrieveAbstractClassesForType(Class clazz) { List<GraphQLInterfaceType> abstractClasses = new ArrayList<>(); LinkedList<Class> queue = new LinkedList<>(); queue.add(clazz); while (!queue.isEmpty()) { Class aClass = queue.poll().getSuperclass(); if (aClass == null) { continue; } if (Modifier.isAbstract(aClass.getModifiers())) { abstractClasses.add((GraphQLInterfaceType) typeRegistry.lookupOutput(aClass)); queue.add(aClass); } } return abstractClasses; } /** * Look up and inspect interfaces implemented by a specific class * * @param clazz being inspected * @return list of {@link GraphQLInterfaceType} */ public List<GraphQLInterfaceType> retrieveInterfacesForType(Class clazz) { List<GraphQLInterfaceType> interfaceTypes = new ArrayList<>(); LinkedList<Class> queue = new LinkedList<>(); queue.add(clazz); while (!queue.isEmpty()) { Class aClass = queue.poll(); Class<?>[] interfacesForClass = aClass.getInterfaces(); queue.addAll(Arrays.asList(interfacesForClass)); for (Class interfaceClass: interfacesForClass) { GraphQLInterfaceType graphQLInterfaceType = (GraphQLInterfaceType) typeRegistry.lookupOutput(interfaceClass); interfaceTypes.add(graphQLInterfaceType); } } return interfaceTypes; } private GraphQLFieldDefinition getGraphQLFieldDefinition(Class clazz, Pair<Method, Class> pair) { // GraphQL Field Name Method method = pair.getLeft(); String name = ReflectionUtil.sanitizeMethodName(method.getName()); // DataFetcher Class declaringClass = pair.getRight(); List<DataFetcher> fetchers = typeRegistry.retrieveDataFetchers(clazz, declaringClass, method); DataFetcher dataFetcher = TypeRegistry.createDataFetchersFromDataFetcherList(fetchers, declaringClass, name); String description = ReflectionUtil.getDescriptionFromAnnotatedElement(method); if (description != null && description.equals(GlitrDescription.DEFAULT_DESCRIPTION)) { description = ReflectionUtil.getDescriptionFromAnnotatedField(clazz, method); } Optional<GlitrQueryComplexity> glitrQueryComplexity = ReflectionUtil.getAnnotationOfMethodOrField(clazz, method, GlitrQueryComplexity.class); Set<GlitrMetaDefinition> metaDefinitions = new HashSet<>(); glitrQueryComplexity.ifPresent(queryComplexity -> { metaDefinitions.add(new GlitrMetaDefinition(COMPLEXITY_FORMULA_KEY, queryComplexity.value())); metaDefinitions.add(new GlitrMetaDefinition(COMPLEXITY_IGNORE_KEY, queryComplexity.ignore())); }); Optional<GlitrDeprecated> glitrDeprecated = ReflectionUtil.getAnnotationOfMethodOrField(clazz, method, GlitrDeprecated.class); codeRegistryBuilder.dataFetcher(coordinates(clazz.getSimpleName(), name), dataFetcher); return newFieldDefinition() .name(name) .description(description) .type(typeRegistry.retrieveGraphQLOutputType(declaringClass, method)) .arguments(typeRegistry.retrieveArguments(declaringClass, method)) .definition(new GlitrFieldDefinition(name, metaDefinitions)) // TODO: static value .deprecate(glitrDeprecated.map(GlitrDeprecated::value).orElse(null)) .build(); } }
mit
vangulo-trulia/dozer-rets-client
src/test/java/org/realtors/rets/common/metadata/attrib/AttrPlaintextTest.java
800
package org.realtors.rets.common.metadata.attrib; import org.realtors.rets.common.metadata.AttrType; public class AttrPlaintextTest extends AttrTypeTest { public void testPlaintext() throws Exception { AttrType parser = new AttrPlaintext(0, 10); assertEquals(String.class, parser.getType()); String[] good = { "%17a", "!%@$", "90785", ")!(*%! ", "" }; String[] bad = { "\r\n", "\t", new String(new char[] { (char) 7 }) }; for (int i = 0; i < good.length; i++) { String s = good[i]; assertEquals(s, parser.parse(s,true)); } for (int i = 0; i < bad.length; i++) { String s = bad[i]; assertParseException(parser, s); } AttrType parser2 = new AttrPlaintext(10, 20); assertParseException(parser2, "1"); assertParseException(parser2, "123456789012345678901"); } }
mit
juqian/Slithice
Slithice/src/jqian/util/ui/PictureViewer.java
12276
/** * Swing UI to show a picture * * TODO: * 1. ±ß½çûÓд¦ÀíºÃ * 2. zoom mechanism * 3. drag */ package jqian.util.ui; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class PictureViewer extends JFrame { private static final long serialVersionUID = 3546242586537550622L; private javax.swing.JPanel jContentPane = null; private final int MAX_HEIGHT; private final int MAX_WIDTH; protected String _path; protected String _title; public PictureViewer(String title,String path) { super(); this._title = title; this._path = path; Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); MAX_HEIGHT = screenSize.height - 65; MAX_WIDTH = screenSize.width; initialize(); } public PictureViewer(String path,int maxHeight,int maxWidth) { super(); this._path = path; this.MAX_HEIGHT = maxHeight; this.MAX_WIDTH = maxWidth; initialize(); } private void initialize() { File file=new File(_path); JPanel imgPanel = new ScrollImgPanel(file); Dimension dimension = imgPanel.getPreferredSize(); int height = (int)dimension.getHeight(); height = height > MAX_HEIGHT? MAX_HEIGHT: height; int width = (int)dimension.getWidth(); width =width > MAX_WIDTH? MAX_WIDTH:width; this.setContentPane(getJContentPane()); jContentPane.setLayout(new FlowLayout()); jContentPane.add(imgPanel); jContentPane.setPreferredSize(new Dimension(width,height)); this.pack(); this.setTitle(_title); //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ //jContentPane.getToolkit(). PictureViewer.this.dispose();//.setVisible(false); } }); } /** * This method initializes jContentPane * @return javax.swing.JPanel */ private javax.swing.JPanel getJContentPane() { if(jContentPane == null) { jContentPane = new javax.swing.JPanel(); jContentPane.setLayout(new java.awt.BorderLayout()); } return jContentPane; } public void display(){ setVisible(true); } public static void main(String[] args) throws Exception{ PictureViewer cgView = new PictureViewer("test","./output/img/sdg.dot.jpg"); cgView.setVisible(true); while(true){ Thread.sleep(1000); } } } class ScrollImgPanel extends JPanel{ private static final long serialVersionUID = -5412696500498137404L; private ScrollableImgPanel img=null; private int MAX_HEIGHT; private int MAX_WIDTH; private void setDiemension(){ Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); MAX_HEIGHT = screenSize.height - 70; MAX_WIDTH = screenSize.width - 10; } //constructors public ScrollImgPanel(Image image) { setDiemension(); img = new ScrollableImgPanel(image); initialize(); } public ScrollImgPanel(File file) { try{ setDiemension(); img = new ScrollableImgPanel(ImageIO.read(file)); }catch(IOException ex) { ex.printStackTrace(System.err); } initialize(); } public ScrollImgPanel(String string) { setDiemension(); URL url = null; try { url = new URL(string); }catch (MalformedURLException ex) { } Image image = Toolkit.getDefaultToolkit().getImage(url); MediaTracker tracker = new MediaTracker(this); tracker.addImage(image, 0); try { tracker.waitForID(0); } catch (InterruptedException ie) { } img = new ScrollableImgPanel(image); initialize(); } public ScrollImgPanel(ImageIcon icon) { setDiemension(); img = new ScrollableImgPanel(icon.getImage()); initialize(); } public ScrollImgPanel(URL url) { setDiemension(); ImageIcon icon = new ImageIcon(url); img = new ScrollableImgPanel(icon.getImage()); initialize(); } private void initialize(){ JScrollPane imgScrollPane = new JScrollPane(img); Dimension dimension = img.getPreferredSize(); this.setBorder(BorderFactory.createEmptyBorder()); int height = (int)dimension.getHeight()+5; if(height> MAX_HEIGHT){ height=MAX_HEIGHT; } int width = (int)dimension.getWidth()+5; if(width > MAX_WIDTH){ width=MAX_WIDTH; } dimension=new Dimension(width,height); imgScrollPane.setPreferredSize(dimension); imgScrollPane.setViewportBorder( BorderFactory.createLineBorder(Color.black)); add(imgScrollPane); this.setPreferredSize(dimension); } public class ScrollableImgPanel extends JPanel implements Scrollable,MouseMotionListener { private Image image = null; private int maxUnitIncrement = 1; private Dimension preferredDimension; private static final long serialVersionUID = -5374829869279840507L; public ScrollableImgPanel(Image image){ this.image = image; int height = image.getHeight(null); int width = image.getWidth(null); preferredDimension = new Dimension(width,height); maxUnitIncrement = 1; //Let the user scroll by dragging to outside the window. setAutoscrolls(true); //enable synthetic drag events addMouseMotionListener(this); //handle mouse drags } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; if (image != null) { g2d.drawImage(image, 0, 0, this); } /* float zoom=0; if (image != null) { int iw = image.getWidth(this); int ih = image.getHeight(this); int siw = (int) Math.ceil( (float) iw * zoom); int sih = (int) Math.ceil( (float) ih * zoom); // int siw = (int) ( (float) iw * zoom); // int sih = (int) ( (float) ih * zoom); Dimension sz = this.getSize(); int ofx = (sz.width - siw) / 2; int ofy = (sz.height - sih) / 2; g.drawImage(image, ofx, ofy, ofx + siw, ofy + sih, 0, 0, iw, ih, this); // g.drawImage(img,1,1,img.getWidth(this),img.getHeight(this),this); }*/ } //Methods required by the MouseMotionListener interface: public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { //The user is dragging us, so scroll! Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1); scrollRectToVisible(r); } public Dimension getPreferredSize() { //return super.getPreferredSize(); return preferredDimension; } public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { //Get the current position. int currentPosition = 0; if (orientation == SwingConstants.HORIZONTAL) { currentPosition = visibleRect.x; } else { currentPosition = visibleRect.y; } //Return the number of pixels between currentPosition //and the nearest tick mark in the indicated direction. if (direction < 0) { int newPosition = currentPosition - (currentPosition / maxUnitIncrement) * maxUnitIncrement; return (newPosition == 0) ? maxUnitIncrement : newPosition; } else { return ((currentPosition / maxUnitIncrement) + 1) * maxUnitIncrement - currentPosition; } } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { if (orientation == SwingConstants.HORIZONTAL) { return visibleRect.width - maxUnitIncrement; } else { return visibleRect.height - maxUnitIncrement; } } public boolean getScrollableTracksViewportWidth() { return false; } public boolean getScrollableTracksViewportHeight() { return false; } public void setMaxUnitIncrement(int pixels) { maxUnitIncrement = pixels; } /* * public ScrollImgPanel(JPanel panel){ super(new BorderLayout()); //Put * the drawing area in a scroll pane. JScrollPane scroller = new * JScrollPane(panel); scroller.setPreferredSize(new * Dimension(200,200)); //Lay out this demo. add(scroller, * BorderLayout.CENTER); } */ } /* * import java.awt.*; // import java.awt.event.WindowAdapter; // import java.awt.event.WindowEvent; // import java.awt.MediaTracker; import javax.swing.*; import javax.swing.border.*; public class ImagePanel extends JPanel { private Image img; float zoom; public ImagePanel() { } public ImagePanel(Image image) { img=image; try{ jbInit(); } catch(Exception ex){ ex.printStackTrace(); } } public void setImage(Image image){ img=image; try{ jbInit(); } catch(Exception ex){ ex.printStackTrace(); } } public void paint(Graphics g){ super.paint(g); if (img != null) { int iw = img.getWidth(this); int ih = img.getHeight(this); int siw = (int) Math.ceil( (float) iw * zoom); int sih = (int) Math.ceil( (float) ih * zoom); // int siw = (int) ( (float) iw * zoom); // int sih = (int) ( (float) ih * zoom); Dimension sz = this.getSize(); int ofx = (sz.width - siw) / 2; int ofy = (sz.height - sih) / 2; g.drawImage(img, ofx, ofy, ofx + siw, ofy + sih, 0, 0, iw, ih, this); // g.drawImage(img,1,1,img.getWidth(this),img.getHeight(this),this); } } public void setBorder(Border border){ super.setBorder(border); } private void jbInit() throws Exception { int PanelHeight=this.getHeight()-2; // 2±ßBorderµÄ¿í¶È int PanelWidth=this.getWidth()-2; int ImageHeight=img.getHeight(this); int ImageWidth=img.getWidth(this); int WidthDifferenceValue,HeightDifferenceValue; float HeightZoom=0,WidthZoom=0; WidthDifferenceValue=ImageWidth-PanelWidth; HeightDifferenceValue=ImageHeight-PanelHeight; if(WidthDifferenceValue>0) WidthZoom=(float)PanelWidth/ImageWidth; else if(WidthDifferenceValue==0) WidthZoom=1; else if(WidthDifferenceValue<0) WidthZoom=(float)ImageWidth/PanelWidth; if(HeightDifferenceValue>0) HeightZoom=(float)PanelHeight/ImageHeight; else if(HeightDifferenceValue==0) HeightZoom=1; else if(HeightDifferenceValue<0) HeightZoom=(float)ImageHeight/PanelHeight; if(HeightZoom>=WidthZoom) zoom=WidthZoom; else zoom=HeightZoom; } public float ZoomRate(){ return zoom; } public int ZoomPercent(){ float zoomRatePercent=zoom*100; return (int)zoomRatePercent; } } */ }
mit
ztmark/leetcode
src/main/java/io/github/ztmark/lintcode/medium/_70BSTLevelOrder2.java
1689
package io.github.ztmark.lintcode.medium; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Queue; /** * Author: Mark * Date : 2018/2/26 */ public class _70BSTLevelOrder2 { public class TreeNode { public int val; public TreeNode left, right; public TreeNode(int val) { this.val = val; this.left = this.right = null; } } /* * @param root: A tree * @return: buttom-up level order a list of lists of integer */ public List<List<Integer>> levelOrderBottom(TreeNode root) { if (root == null) { return Collections.emptyList(); } Queue<TreeNode> levelNode = new ArrayDeque<>(); Queue<TreeNode> tmp = new ArrayDeque<>(); ArrayDeque<List<Integer>> result = new ArrayDeque<>(); levelNode.offer(root); while (!levelNode.isEmpty()) { List<Integer> level = new ArrayList<>(); while (!levelNode.isEmpty()) { final TreeNode node = levelNode.poll(); level.add(node.val); if (node.left != null) { tmp.offer(node.left); } if (node.right != null) { tmp.offer(node.right); } } result.push(level); Queue<TreeNode> tq = levelNode; levelNode = tmp; tmp = tq; } List<List<Integer>> newResult = new ArrayList<>(); while (!result.isEmpty()) { newResult.add(result.pop()); } return newResult; } }
mit
Dyndrilliac/AotB-TD
src/com/games/aotb/ProgressBar.java
3313
package com.games.aotb; import org.andengine.entity.primitive.Line; import org.andengine.entity.primitive.Rectangle; import org.andengine.opengl.vbo.VertexBufferObjectManager; public class ProgressBar extends Rectangle { private static final float FRAME_LINE_WIDTH = 5.0f; private final Line[] frameLines = new Line[4]; private Rectangle progressRectangle = null; private float maxValue = 0.0f; private float currentValue = 0.0f; public ProgressBar( final float x, final float y, final float width, final float height, final float maxValue, final float startValue, final VertexBufferObjectManager vbom) { super(x, y, width, height, vbom); this.progressRectangle = new Rectangle(0, 0, width, height, vbom); this.setMax(maxValue); this.setProgress(startValue); // Define top line. this.frameLines[0] = new Line(0, 0, 0 + width, 0, ProgressBar.FRAME_LINE_WIDTH, vbom); // Define right line. this.frameLines[1] = new Line(0 + width, 0, 0 + width, 0 + height, ProgressBar.FRAME_LINE_WIDTH, vbom); // Define bottom line. this.frameLines[2] = new Line(0 + width, 0 + height, 0, 0 + height, ProgressBar.FRAME_LINE_WIDTH, vbom); // Define left line. this.frameLines[3] = new Line(0, 0 + height, 0, 0, ProgressBar.FRAME_LINE_WIDTH, vbom); // Draw progress. this.attachChild(this.progressRectangle); // Draw lines. for (Line frameLine: this.frameLines) { this.attachChild(frameLine); } } public ProgressBar clone(final Enemy returnEnemy) { final ProgressBar returnProgressBar = new ProgressBar(this.getX(), this.getY(), this.getWidth(), this.getHeight(), this.maxValue, this.currentValue, this.getVertexBufferObjectManager()); // Fix progressRectangle. returnProgressBar.progressRectangle.setColor(this.progressRectangle.getColor()); // Fix frame lines. for (int i = 0; i < this.frameLines.length; i++) { returnProgressBar.frameLines[i].setColor(this.frameLines[i].getColor()); } // Fix back color. returnProgressBar.setColor(this.getColor()); // Attach it to the enemy. returnEnemy.attachChild(returnProgressBar); return returnProgressBar; } public float getMax() { return this.maxValue; } public float getProgress() { return this.currentValue; } public ProgressBar setBackColor(final float red, final float green, final float blue, final float alpha) { this.setColor(red, green, blue, alpha); return this; } public ProgressBar setFrameColor(final float red, final float green, final float blue, final float alpha) { for (Line frameLine: this.frameLines) { frameLine.setColor(red, green, blue, alpha); } return this; } public ProgressBar setMax(final float maxValue) { this.maxValue = maxValue; return this; } public ProgressBar setProgress(final float progress) { this.currentValue = progress; if (this.currentValue < 0) { this.currentValue = 0; } else if (this.currentValue > this.maxValue) { this.currentValue = this.maxValue; } this.progressRectangle.setWidth((this.getWidth() * progress) / this.maxValue); return this; } public ProgressBar setProgressColor(final float red, final float green, final float blue, final float alpha) { this.progressRectangle.setColor(red, green, blue, alpha); return this; } }
mit
rtornero/NeverNote
app/src/main/java/com/nevernote/presenters/NeverNoteCreatePresenterImpl.java
5144
/* The MIT License (MIT) Copyright (c) 2015 Roberto Tornero Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.nevernote.presenters; import android.text.TextUtils; import com.evernote.client.android.EvernoteSession; import com.evernote.client.android.EvernoteUtil; import com.evernote.client.android.asyncclient.EvernoteCallback; import com.evernote.client.android.asyncclient.EvernoteNoteStoreClient; import com.evernote.edam.type.Note; import com.evernote.edam.type.Notebook; import com.nevernote.views.NeverNoteCreateView; import java.util.List; /** * Created by Roberto on 26/7/15. * * Implementation of {@link NeverNoteCreatePresenter}. It has a {@link NeverNoteCreateView} instance * to notify the view with the changes in the model, in this case, when the new note has been created. */ public class NeverNoteCreatePresenterImpl implements NeverNoteCreatePresenter { /** * The view interface to be notified by the presenter */ private NeverNoteCreateView createView; /** * The recently created Note */ private Note note; /** * */ private String selectedGuid; /** * Evernote's callback that gets called when the creation process has finished. */ private EvernoteCallback<Note> createNoteCallback = new EvernoteCallback<Note>() { @Override public void onSuccess(Note result) { //We save our new Note for later and notify the view note = result; createView.hideProgressBar(); createView.enableButtons(); createView.onNoteCreated(); } @Override public void onException(Exception exception) { //If an error occurred, notify the view createView.hideProgressBar(); createView.enableButtons(); createView.onError(exception); } }; private EvernoteCallback<List<Notebook>> notebooksListCallback = new EvernoteCallback<List<Notebook>>() { @Override public void onSuccess(List<Notebook> notebooks) { if (! notebooks.isEmpty()) createView.onNotebooksRetrieved(notebooks); } @Override public void onException(Exception e) {} }; public NeverNoteCreatePresenterImpl(NeverNoteCreateView createView){ setCreateView(createView); } @Override public void createNote(String title, String content) { /* Field validation for title and content of the new note, notify the view if these are not correct. */ if (title.isEmpty() || content.isEmpty()){ createView.titleOrContentEmpty(); return; } //New note instance with the desired title and content final Note note = new Note(); note.setTitle(title); note.setContent(EvernoteUtil.NOTE_PREFIX + content + EvernoteUtil.NOTE_SUFFIX); //If notebook selection was available, take the guid of the user's choice if (!TextUtils.isEmpty(selectedGuid)) note.setNotebookGuid(selectedGuid); createView.showProgressBar(); createView.disableButtons(); /* Get a handler to the EvernoteNoteStoreClient and send the entered details of the new note. This operation is processed asynchronously. */ final EvernoteNoteStoreClient noteStoreClient = EvernoteSession.getInstance().getEvernoteClientFactory().getNoteStoreClient(); noteStoreClient.createNoteAsync(note, createNoteCallback); } @Override public void retrieveNotebooks() { final EvernoteNoteStoreClient noteStoreClient = EvernoteSession.getInstance().getEvernoteClientFactory().getNoteStoreClient(); noteStoreClient.listNotebooksAsync(notebooksListCallback); } @Override public void setSelectedNotebookGuid(String guid) { this.selectedGuid = guid; } @Override public void setCreateView(NeverNoteCreateView createView) { this.createView = createView; } @Override public Note getNote() { return note; } }
mit
zerohours/tareamoviles
src/sv/ues/fia/moviles/controlador/AlumnoMenuActivity.java
1399
package sv.ues.fia.moviles.controlador; import android.os.Bundle; import android.app.ListActivity; import android.content.Intent; import android.graphics.Color; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class AlumnoMenuActivity extends ListActivity { String[] menu = { "Insertar Registro", "Consultar Registro", "Actualizar Registro", "Eliminar Registro" }; String[] activities = { "AlumnoInsertarActivity", "AlumnoConsultarActivity", "AlumnoActualizarActivity", "AlumnoEliminarActivity" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView listView = getListView(); listView.setBackgroundColor(Color.rgb(0, 0, 255)); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); String nombreValue = activities[position]; l.getChildAt(position).setBackgroundColor(Color.rgb(128, 128, 255)); try { Class<?> clase = Class.forName("sv.ues.fia.moviles.controlador.alumno." + nombreValue); Intent inte = new Intent(this, clase); this.startActivity(inte); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
mit
bcvictor/BitcoinRandomnessBeacon
src/main/java/info/blockchain/api/receive/Receive.java
1916
package info.blockchain.api.receive; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import info.blockchain.api.APIException; import info.blockchain.api.HttpClient; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * This class reflects the functionality necessary for using the receive-payments-api v2. * Passing on a xPUB, callbackUrl and the apiCode will return an address for receiving a payment. * <p> * Upon receiving a payment on this address, the merchant will be notified using the callback URL. */ public class Receive { /** * Calls the receive-payments-api v2 and returns an address for the payment. * * @param xPUB Destination address where the payment should be sent * @param callbackUrl Callback URI that will be called upon payment * @param apiCode Blockchain.info API code for the receive-payments v2 API (different from normal API key) * @return An instance of the ReceiveV2Response class * @throws APIException If the server returns an error */ public static ReceiveResponse receive (String xPUB, String callbackUrl, String apiCode) throws APIException, IOException { if (apiCode == null || Objects.equals(apiCode, "")) { throw new APIException("No API Code provided.."); } Map<String, String> params = new HashMap<String, String>(); params.put("xpub", xPUB); params.put("callback", callbackUrl); params.put("key", apiCode); String response = HttpClient.getInstance().get("https://api.blockchain.info/", "v2/receive", params); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(response).getAsJsonObject(); return new ReceiveResponse(obj.get("index").getAsInt(), obj.get("address").getAsString(), obj.get("callback").getAsString()); } }
mit
vickychijwani/Material-Design-Companion
app/src/main/java/me/vickychijwani/material/demos/XmlOnlyFragment.java
578
package me.vickychijwani.material.demos; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public abstract class XmlOnlyFragment extends Fragment { @LayoutRes public abstract int getLayoutId(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(getLayoutId(), container, false); } }
mit
vimeo/turnstile-android
turnstile/src/main/java/com/vimeo/turnstile/database/TaskCache.java
13038
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016 Vimeo * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vimeo.turnstile.database; import android.content.Context; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; import com.vimeo.turnstile.BaseTask; import com.vimeo.turnstile.Serializer; import com.vimeo.turnstile.utils.TaskLogger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * The disk backed cache which represents the {@link T} task list. * This class is responsible for persistence and task access. * <p/> * Created by kylevenn on 2/22/16. */ public final class TaskCache<T extends BaseTask> { private static final int NOT_FOUND = -1; @NonNull private final ConcurrentHashMap<String, T> mTaskMap = new ConcurrentHashMap<>(); @NonNull private final TaskDatabase<T> mDatabase; private final Handler mMainThread = new Handler(Looper.getMainLooper()); private final Comparator<T> mTimeComparator = new Comparator<T>() { @Override public int compare(T lhs, T rhs) { // Newest to oldest (highest timestamp to lowest timestamp) return compareLongs(rhs.getCreatedTimeMillis(), lhs.getCreatedTimeMillis()); } }; private final Comparator<T> mReverseTimeComparator = new Comparator<T>() { @Override public int compare(T lhs, T rhs) { // Oldest to newest (lowest timestamp to highest timestamp) return compareLongs(lhs.getCreatedTimeMillis(), rhs.getCreatedTimeMillis()); } }; private static int compareLongs(long lhs, long rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } @WorkerThread public TaskCache(@NonNull Context context, @NonNull String taskName, @NonNull Serializer<T> serializer) { mDatabase = new TaskDatabase<>(context, taskName, serializer); List<T> tasks = mDatabase.getAllTasks(); for (T task : tasks) { mTaskMap.put(task.getId(), task); } } /** * Gets all the tasks held in the cache. * * @return a non-null map of all the tasks * in the map, mapped to their ids. */ @NonNull public Map<String, T> getTasks() { return mTaskMap; } /** * Gets all tasks held in the map and returns * them in a list sorted by the time they were * created, sorted newest to oldest. * * @return A non-null list tasks in the cache, * sorted by date. */ @NonNull public List<T> getDateOrderedTaskList() { return getOrderedTaskList(mTimeComparator); } /** * Gets all tasks held in the map and returns * them in a list sorted by the time they were * created, sorted oldest to newest. * * @return A non-null list tasks in the cache, * sorted by date. */ @NonNull public List<T> getDateReverseOrderedTaskList() { return getOrderedTaskList(mReverseTimeComparator); } /** * Gets all the tasks held in the map and returns them * in a list sorted using the specified comparator. * * @param comparator a user-defined comparator to sort the tasks by * @return A non-null list tasks in the cache, * sorted by the specified comparator. */ @NonNull public List<T> getOrderedTaskList(@NonNull Comparator<T> comparator) { List<T> taskList = new ArrayList<>(mTaskMap.values()); Collections.sort(taskList, comparator); return taskList; } // <editor-fold desc="Task Logic"> /** * Gets a list of all tasks that need to be run, * as specified by the task itself in the * {@link BaseTask#shouldRun()} method. * * @return A non-null list of the tasks that * should be run, may be empty if no tasks need * to be run. */ @NonNull public List<T> getTasksToRun() { // Get all the tasks that are ready to be run that aren't of type error // Don't included failed uploads since that will require user action // TODO: Eventually we'll query for not paused as well List<T> taskList = new ArrayList<>(); for (T task : mTaskMap.values()) { if (task.shouldRun()) { taskList.add(task); } } return taskList; } // </editor-fold> // ----------------------------------------------------------------------------------------------------- // Map Helpers // ----------------------------------------------------------------------------------------------------- // <editor-fold desc="Map Helpers"> /** * Adds a task to the cache. * * @param task the task to add to the * cache, must not be null. */ private void put(@NonNull T task) { mTaskMap.put(task.getId(), task); } /** * Adds a task to the cache if it is * not already there. This differs from * {@link #put(BaseTask)} in that this * method will not replace the current * task in the cache if one with the * same id exists. * * @param task the task to add to the * cache, must not be null. */ private void putIfAbsent(@NonNull T task) { mTaskMap.putIfAbsent(task.getId(), task); } /** * Gets the task in the cache with * the specified id. * * @param taskId the id of the task to * retrieve. * @return the task with the specified * id, may be null if the specified * task is not in the cache or if the * id passed is null. */ @Nullable public T get(@Nullable String taskId) { if (taskId == null) { return null; } return mTaskMap.get(taskId); } /** * Determines if the cache has a task * with the specified id. * * @param id the id to check. * @return true if the cache contains * the id, false otherwise. */ public boolean containsTask(@NonNull String id) { return mTaskMap.get(id) != null; } // </editor-fold> // ----------------------------------------------------------------------------------------------------- // Main Thread CRUD // ----------------------------------------------------------------------------------------------------- // <editor-fold desc="Main Thread CRUD"> /** * Only used for the first time we're committing the task * to the database. This will only try to add the task if * it's not already in there. It will voice as a success * if it already exists. * * @param task the task to insert, must not be null. * @param callback the callback that will be notified of * success or failure of insertion into * the cache. * @return false if the task was invalid, true otherwise. */ public boolean insert(@NonNull final T task, @Nullable final TaskCallback callback) { if (task.getId() == null) { if (callback != null) { mMainThread.post(new Runnable() { @Override public void run() { callback.onFailure(new Exception("Task passed with null ID. Won't insert.")); } }); } return false; } // Only put in this new task if there isn't one already in there. putIfAbsent(task); TaskDatabase.execute(new Runnable() { @Override public void run() { try { insertToDatabase(task); if (callback == null) { return; } mMainThread.post(new Runnable() { @Override public void run() { callback.onSuccess(); } }); } catch (final Exception e) { if (callback == null) { return; } // Let's catch any exception from the commit and log it // A failed commit is a very bad thing mMainThread.post(new Runnable() { @Override public void run() { callback.onFailure(e); } }); } } }); return true; } /** * Update or insert the task into the database * and into the cache (if it doesn't already exist). * This method asynchronously communicates with * the database so it can be called without blocking * the calling thread. * * @param task the task to update or insert into * the database. Must not be null. */ public void upsert(@NonNull final T task) { if (task.getId() == null) { TaskLogger.getLogger().e("Task passed to upsert without an ID."); return; } // This will replace the current task in the cache (or 'put' it if it's not there) put(task); TaskDatabase.execute(new Runnable() { @Override public void run() { mDatabase.upsert(task); } }); } /** * Removes the task with the specified id from * the task and from the database. This method * asynchronously communicates with the database * so it can be called without blocking the calling * thread. * * @param taskId the id of the task to remove * from the cache. Must not be * null. */ public void remove(@NonNull final String taskId) { // This will replace the current task in the cache (or 'put' it if it's not there) mTaskMap.remove(taskId); TaskDatabase.execute(new Runnable() { @Override public void run() { mDatabase.remove(taskId); } }); } /** * Removes all tasks from the cache * and the database. This method * asynchronously communicates with * the database so it can be called * without blocking the calling thread. */ public void removeAll() { mTaskMap.clear(); TaskDatabase.execute(new Runnable() { @Override public void run() { mDatabase.removeAll(); } }); } // </editor-fold> // ----------------------------------------------------------------------------------------------------- // Worker Thread CRUD // ----------------------------------------------------------------------------------------------------- // <editor-fold desc="Worker Thread CRUD"> /** * Insert the task into the database. * This should be done on a background thread. */ @WorkerThread private void insertToDatabase(@NonNull T task) { if (task.getId() == null) { TaskLogger.getLogger().e("Task passed to insertToDatabase without an ID."); return; } // This insert has an OR IGNORE clause. That means if we try to insert a value that already exists, // it wont work (returns -1). This happens in the case where our initial commit fails but the upload finishes // and that 'complete' commit succeeds (and then we try to commit again). long insertId = mDatabase.insert(task); if (insertId == NOT_FOUND) { TaskLogger.getLogger().d("Task already exists in database"); } } // </editor-fold> }
mit
LionsWrath/SistemaHistogene
src/Principal/ConsultarTemplate.java
5825
package Principal; /** * * @author Caio */ public abstract class ConsultarTemplate extends javax.swing.JFrame { public javax.swing.JButton jButton1; public javax.swing.JButton jButton2; public javax.swing.JButton jButton3; public javax.swing.JButton jButton4; public javax.swing.JButton jButton5; public javax.swing.JLabel jLabel2; public javax.swing.JScrollPane jScrollPane1; public javax.swing.JList listapacientes; public javax.swing.JTextField nome; public javax.swing.JLabel titulo; public ConsultarTemplate() { initComponents(); this.nome.setDocument(new LengthRestrictedDocument(40)); } public void initComponents() { titulo = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); nome = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); listapacientes = new javax.swing.JList(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); titulo.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N titulo.setText("Consultar X"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("Nome:"); jButton1.setText("Procurar"); jScrollPane1.setViewportView(listapacientes); jButton2.setText("Visualizar"); jButton3.setText("Sair"); jButton4.setText("Alterar"); jButton5.setText("Excluir"); jButton3.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jButton2) .addGap(18, 18, 18) .addComponent(jButton4) .addGap(18, 18, 18) .addComponent(jButton5) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1)) .addGap(28, 28, 28) .addComponent(jButton3))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(142, 142, 142) .addComponent(titulo) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(titulo) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton4) .addComponent(jButton5) .addComponent(jButton3)) .addContainerGap(18, Short.MAX_VALUE)) ); pack(); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { this.dispose(); } public void setTitulo(){ this.titulo.setText("Consultar"); } }
mit
NPException42/GameAnalyticsAPI
src/main/java/de/npe/gameanalytics/events/GAEvent.java
1247
/** * (C) 2015 NPException */ package de.npe.gameanalytics.events; import de.npe.gameanalytics.Analytics; import de.npe.gameanalytics.Analytics.KeyPair; import de.npe.gameanalytics.util.JSON; /** * Base event class. Contains values that are mandatory for all event types. * * @author NPException */ public abstract class GAEvent implements JSON.JSONObject { public final transient KeyPair keyPair; private final String userID; private final String sessionID; private final String build; GAEvent(Analytics an) { keyPair = an.keyPair(); userID = an.getUserID(); sessionID = an.getSessionID(); build = an.build(); } public abstract String category(); @Override public void toJSON(StringBuilder sb) { sb.append("\"user_id\":\"").append(JSON.escape(userID)).append("\","); sb.append("\"session_id\":\"").append(JSON.escape(sessionID)).append("\","); sb.append("\"build\":\"").append(JSON.escape(build)).append("\""); } private transient String toString; @Override public String toString() { if (toString == null) { StringBuilder sb = new StringBuilder(); sb.append('{'); toJSON(sb); sb.append('}'); sb.append(" + ").append(keyPair); toString = sb.toString(); } return toString; } }
mit
lawrizs/ARROWHEAD_VME
aggregator-core/src/main/java/org/arrowhead/wp5/agg/impl/grouper/FSubgrpBuilderWgtBounded.java
17117
package org.arrowhead.wp5.agg.impl.grouper; /*- * #%L * ARROWHEAD::WP5::Aggregator Core * %% * Copyright (C) 2016 The ARROWHEAD Consortium * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import org.arrowhead.wp5.agg.api.ChangeRecOfFlexOffer; import org.arrowhead.wp5.agg.api.ChangeType; import org.arrowhead.wp5.agg.impl.common.AggParamAbstracter; import org.arrowhead.wp5.agg.impl.common.ChangeRecOfGroup; import org.arrowhead.wp5.agg.impl.common.ChangeTracker; import org.arrowhead.wp5.agg.impl.common.FGroup; import org.arrowhead.wp5.agg.impl.common.IteratorTransforming; import org.arrowhead.wp5.core.entities.FlexOffer; /** * An implementation of the incremental sub-group builder. It partitions a super group to subgroups * so that total weights of all subgroup falls into specified weight range. * * @author Laurynas Siksnys (siksnys@cs.aau.dk), AAU * */ public class FSubgrpBuilderWgtBounded implements IFSubgrpBuilder { private AggParamAbstracter aggParAbstracter; private BinPackingParams binPackerParams = null; // Non-aggregated flex-offers list and its changes private LinkedHashSet<FlexOffer> foNotAggregated = new LinkedHashSet<FlexOffer> (); private ChangeTracker<FlexOffer, ChangeRecOfFlexOffer> foNotAggregatedChanges = null; // A hash map of group to sub-group private HashMap<FGroup, FSubGroupList> subgroupHash = new HashMap<FGroup, FSubGroupList>(); public double getWeightMin() { return this.aggParAbstracter.getWeightMinValue(); } public double getWeightMax() { return this.aggParAbstracter.getWeightMaxValue(); } @Override public void resetChanges() { this.foNotAggregatedChanges.clearChanges(); } @Override public void foClear() { this.foNotAggregated.clear(); this.foNotAggregatedChanges.clearChanges(); this.subgroupHash.clear(); } public FSubgrpBuilderWgtBounded(AggParamAbstracter aggParAbstracter, BinPackingParams params) { assert(params!=null): "Correct bin packing parameters must be provided"; this.aggParAbstracter = aggParAbstracter; this.binPackerParams = params; // Create change tracker this.foNotAggregatedChanges = new ChangeTracker<FlexOffer, ChangeRecOfFlexOffer>( ChangeRecOfFlexOffer.getFactory()); } // Bin packing attributes/methods private enum PackingStatus { psCanPack, psMaxExceeded, psMinUncreached }; private double getFOweight(FlexOffer f) { return this.aggParAbstracter.getWeightDlg().getWeight(f); } private double addTwoWeights(double weight1, double weight2) { return this.aggParAbstracter.getWeightDlg().addTwoWeights(weight1, weight2); } private double getZeroWeight() { return this.aggParAbstracter.getWeightDlg().getZeroWeight(); } private class PackingResult { public PackingStatus status; public FSubGroup subgroup = null; } private double calcFlexOfferTotalWeight(Collection<FlexOffer> fo) { double sumWeight = this.getZeroWeight(); for(FlexOffer f : fo) sumWeight = addTwoWeights(sumWeight, this.getFOweight(f)); return sumWeight; } // The actual bin-packing public void allocateFosToGroups (Iterable<FlexOffer> newFos, FSubGroupList foGrps, List<FlexOffer> nonAggregatedFOs, ChangeTracker<FGroup, ChangeRecOfGroup> changeTracker) { // Sort the original flex-offer list based on weights List<FlexOffer> sortedFOlist = new LinkedList<FlexOffer>(); for(FlexOffer f: newFos) sortedFOlist.add(f); Collections.sort(sortedFOlist, new Comparator<FlexOffer>(){ @Override public int compare(FlexOffer f1, FlexOffer f2) { return (getFOweight(f1) > getFOweight(f2) ? 0 : 1); } }); // Step 1 - get rid of flex-offers that can't be packed anywhere while (sortedFOlist.size()>0 && (this.getFOweight(sortedFOlist.get(0))>this.getWeightMax())) { if (nonAggregatedFOs!=null) nonAggregatedFOs.add(sortedFOlist.get(0)); sortedFOlist.remove(0); } // Step 2 - pack flex-offers to existing groups, if possible if (this.binPackerParams.isUpsizeAllowed() && tryPackingToExistingGroups(sortedFOlist, foGrps, changeTracker)) return; else { // Step 3 - packing of all flex-offers is not possible, generate new // groups FSubGroupList newGrps = new FSubGroupList(foGrps.getSuperGroup()); PackingResult pr; // First, check if minimum condition can be reached // Second, pack flex-offers into new groups while ((calcFlexOfferTotalWeight(sortedFOlist) >= this.getWeightMin()) && (pr = packIntoValidSubgroup(sortedFOlist, 0, this.getZeroWeight())).status == PackingStatus.psCanPack) { newGrps.add(pr.subgroup); sortedFOlist.removeAll(pr.subgroup.getFlexOfferList()); // Track changes if requested if (changeTracker != null) changeTracker.incUpdateChange(pr.subgroup, ChangeType.ctAdded); } // Try to distribute the remaining flex-offers to the old and new // flex-offer groups for (FlexOffer f : sortedFOlist) { // Loops through the new groups for (FSubGroup sg : newGrps) if (this.addTwoWeights(sg.getGroupWeight(this.aggParAbstracter), this.getFOweight(f)) <= this.getWeightMax()) { sg.addFlexOffer(f); break; } // Loops through the old groups, if upsizing is allowed if (this.binPackerParams.isUpsizeAllowed()) for (FSubGroup sg : foGrps) if (this.addTwoWeights(sg.getGroupWeight(this.aggParAbstracter), this.getFOweight(f)) <= this.getWeightMax()) { sg.addFlexOffer(f); if (changeTracker != null) changeTracker.incUpdateChange(sg, ChangeType.ctUpsized) .foWasAdded(f); break; } // If the flex-offer does not fit anywhere, add it to the non // bin packed list if (nonAggregatedFOs != null) nonAggregatedFOs.add(f); } // Merge two groups for(FSubGroup g : newGrps) { foGrps.add(g); if (changeTracker != null) changeTracker.incUpdateChange(g, ChangeType.ctAdded); } } } private boolean tryPackingToExistingGroups(Collection<FlexOffer> sortedFL, FSubGroupList foGrps, ChangeTracker<FGroup, ChangeRecOfGroup> changeTracker) { if (foGrps.size() == 0) return false; double [] weights = new double[foGrps.size()]; double sumMax = this.getZeroWeight(); double sumGrpWgt = this.getZeroWeight(); for(int i = 0; i< foGrps.size(); i++) { weights [i] = foGrps.get(i).getGroupWeight(this.aggParAbstracter); sumMax = this.addTwoWeights(sumMax, this.getWeightMax()); sumGrpWgt = this.addTwoWeights(sumGrpWgt, weights[i]); } double flWeight = this.getZeroWeight(); for (FlexOffer f : sortedFL) flWeight = this.addTwoWeights(flWeight, this.getFOweight(f)); //emptySpace -= this.getFOweight(f); if (sumMax < this.addTwoWeights(sumGrpWgt, flWeight)) return false; // Can't fit flex-offers into existing groups // Otherwise, try to add to existing groups List<FlexOffer> copyOfFL = new LinkedList<FlexOffer>(sortedFL); FSubGroup [] grpSupplements = new FSubGroup[weights.length]; for(int i = weights.length-1; i>=0; i--) { PackingResult pr = this.packIntoValidSubgroup(copyOfFL, 0, weights[i]); if (pr.status == PackingStatus.psCanPack) { copyOfFL.removeAll(pr.subgroup.getFlexOfferList()); grpSupplements[i] = pr.subgroup; } else grpSupplements[i] = null; if (copyOfFL.size() == 0) break; } // Packing succeeded, let's reset changes to existing groups if (copyOfFL.size() == 0) { for(int i = 0; i< weights.length; i++) if (grpSupplements[i] != null) { foGrps.get(i).addFlexOffers(grpSupplements[i]); if (changeTracker!=null) { ChangeRecOfGroup c = changeTracker.incUpdateChange(foGrps.get(i), ChangeType.ctUpsized); for (FlexOffer f : grpSupplements[i]) c.foWasAdded(f); } } return true; } else return false; } private PackingResult packIntoValidSubgroup(List<FlexOffer> sortedFL, int foIndex, double runningWeight) { if (runningWeight > this.getWeightMax()) { PackingResult pr = new PackingResult(); pr.status = PackingStatus.psMaxExceeded; return pr; } // Find the next item that fits while(foIndex < sortedFL.size() && (this.addTwoWeights(runningWeight, this.getFOweight(sortedFL.get(foIndex))) > this.getWeightMax())) foIndex++; // If not found if (foIndex >= sortedFL.size()) { PackingResult pr = new PackingResult(); pr.status = runningWeight<this.getWeightMin() ? PackingStatus.psMinUncreached : PackingStatus.psMaxExceeded; return pr; } PackingResult pr = null; do { double sumWeight = this.addTwoWeights(runningWeight, this.getFOweight(sortedFL.get(foIndex))); if (sumWeight >= this.getWeightMin()) { // Already found solution, but try to refine it pr = new PackingResult(); pr.status = PackingStatus.psCanPack; pr.subgroup = new FSubGroup(); pr.subgroup.addFlexOffer(sortedFL.get(foIndex)); // Tries to fill the group as max as possible if (this.binPackerParams.isForceFillMaximally()) { PackingResult pr2 = packIntoValidSubgroup(sortedFL, foIndex + 1, sumWeight); if (pr2.status == PackingStatus.psCanPack) { pr.subgroup.addFlexOffers(pr2.subgroup); } } } else { pr = packIntoValidSubgroup(sortedFL, foIndex + 1, sumWeight); if (pr.status == PackingStatus.psCanPack) { pr.subgroup.addFlexOffer(sortedFL.get(foIndex)); } } } while ((pr.status != PackingStatus.psCanPack) && (this.binPackerParams.isEagerBinPacking() && (++ foIndex) < sortedFL.size())); return pr; } public Iterator<ChangeRecOfFlexOffer> getNonAggregatedFOchanges() { return this.foNotAggregatedChanges.iterator(); } public Iterator<ChangeRecOfFlexOffer> getNonAggregatedFoAll() { return new IteratorTransforming<FlexOffer, ChangeRecOfFlexOffer>(this.foNotAggregated.iterator()) { @Override public ChangeRecOfFlexOffer apply(FlexOffer f) { ChangeRecOfFlexOffer cf = new ChangeRecOfFlexOffer(f); cf.setChangeType(FSubgrpBuilderWgtBounded.this.foNotAggregatedChanges.getChange(f)); return cf; } }; } // inGroup - Input group; protected FSubGroupList incSubGroupsAddNew(FGroup addedGroup, ChangeTracker<FGroup, ChangeRecOfGroup> changeTracker) { FSubGroupList sgl = new FSubGroupList(addedGroup); // Update a non-aggregated flex-offer list List<FlexOffer> nonAggregatedFOs = new ArrayList<FlexOffer>(); try { this.allocateFosToGroups(addedGroup, sgl, nonAggregatedFOs, changeTracker); for (FlexOffer f : nonAggregatedFOs) { // Adds non aggregated // flex-offers into the // global list this.foNotAggregated.add(f); this.foNotAggregatedChanges.incUpdateChange(f, ChangeType.ctAdded); } } finally { nonAggregatedFOs.clear(); } return sgl; } protected void incSubGroupsMaintain(FSubGroupList grpList, ChangeTracker<FGroup, ChangeRecOfGroup> changeTracker) { // Fill hash of flex-offers LinkedHashSet<FlexOffer> foSet = new LinkedHashSet<FlexOffer>(); final List<FSubGroup> grpsToRebuild = new ArrayList<FSubGroup>(); List<FlexOffer> nonAggregatedFOs = new ArrayList<FlexOffer>(); try { for (FlexOffer f : grpList.getSuperGroup()) foSet.add(f); // Make a list of changes subgroups for (FSubGroup g : grpList) for (int i = g.getFlexOfferList().size() - 1; i >= 0; i--) { FlexOffer f = g.getFlexOfferList().get(i); // The flex-offer was deleted from a subgroup if (foSet.contains(f)) foSet.remove(f); // foNonBinPackedHs will contain // non-added // flex-offers. else { // Try to take the flex-offer from the group out, and // check if no constraints are violated // Verify this - after the abstraction is made if (g.getGroupWeight(this.aggParAbstracter) >= this.addTwoWeights(this.getFOweight(f), this.getWeightMin())) { g.getFlexOfferList().remove(i); changeTracker.incUpdateChange(g, ChangeType.ctDownsized).foWasRemoved(f); } else { grpsToRebuild.add(g); changeTracker.incUpdateChange(g, ChangeType.ctDeleted); } } } // Remove old groups grpList.removeAll(grpsToRebuild); // Prepare a list of flex-offers, that needs to be packed to the // subgroups for (FSubGroup g : grpsToRebuild) foSet.addAll(g.getFlexOfferList()); if (foSet.size() > 0) { // Allocate non-bin packed flex-offers to new or existing groups this.allocateFosToGroups(foSet, grpList, nonAggregatedFOs, changeTracker); // Update the non-aggregated flex-offer list for (FlexOffer f : nonAggregatedFOs) { if (!this.foNotAggregated.contains(f)) { this.foNotAggregated.add(f); this.foNotAggregatedChanges .incUpdateChange(f, ChangeType.ctAdded); } foSet.remove(f); } for (FlexOffer f : foSet) if (this.foNotAggregated.contains(f)) { this.foNotAggregated.remove(f); this.foNotAggregatedChanges .incUpdateChange(f, ChangeType.ctDeleted); } } } finally { nonAggregatedFOs.clear(); foSet.clear(); grpsToRebuild.clear(); nonAggregatedFOs.clear(); } } protected void incSubGroupsRemoveAll(FSubGroupList sgs, ChangeTracker<FGroup, ChangeRecOfGroup> gct) { for (FSubGroup g : sgs) { for (FlexOffer f : g) if (this.foNotAggregated.contains(f)) { this.foNotAggregated.remove(f); this.foNotAggregatedChanges .incUpdateChange(f, ChangeType.ctDeleted); } gct.incUpdateChange(g, ChangeType.ctDeleted); } sgs.clear(); } // The main method that converts group changes into sub-group changes @Override public Iterator<ChangeRecOfGroup> updateSingleGroup( ChangeRecOfGroup changedSuperGroup) { FSubGroupList sgs; ChangeTracker<FGroup, ChangeRecOfGroup> gct = new ChangeTracker<FGroup, ChangeRecOfGroup>( ChangeRecOfGroup.getFactory()); switch (changedSuperGroup.getChangeType()) { case ctAdded: sgs = this.incSubGroupsAddNew(changedSuperGroup.getGroup(), gct); this.subgroupHash.put(changedSuperGroup.getGroup(), sgs); break; case ctDeleted: sgs = this.subgroupHash.get(changedSuperGroup.getGroup()); if (sgs != null) { this.incSubGroupsRemoveAll(sgs, gct); this.subgroupHash.remove(changedSuperGroup.getGroup()); // Remove from subgroup hash } break; default: // All other cases sgs = this.subgroupHash.get(changedSuperGroup.getGroup()); if (sgs != null) this.incSubGroupsMaintain(sgs, gct); break; } return gct.iterator(); } public final static class BinPackingParams { private boolean eagerBinPacking = true; // If true, it tries all possible combinations to fill the bin private boolean upsizeAllowed = true; // If true, flex-offers are allowed to be added to existing group. // Otherwise, a new group is created every time private boolean forceFillMaximally = true; /** * @return the eagerBinPacking */ public boolean isEagerBinPacking() { return eagerBinPacking; } /** * @param eagerBinPacking the eagerBinPacking to set */ public void setEagerBinPacking(boolean eagerBinPacking) { this.eagerBinPacking = eagerBinPacking; } public boolean isUpsizeAllowed() { return this.upsizeAllowed; } public void setUpsizeAllowed(boolean upsizeAllowed) { this.upsizeAllowed = upsizeAllowed; } /** * @return the forceFillMaximally */ public boolean isForceFillMaximally() { return forceFillMaximally; } /** * @param forceFillMaximally the forceFillMaximally to set */ public void setForceFillMaximally(boolean forceFillMaximally) { this.forceFillMaximally = forceFillMaximally; } } }
mit
bing-ads-sdk/BingAds-Java-SDK
proxies/com/microsoft/bingads/v12/customermanagement/ApiFault_Exception.java
1128
package com.microsoft.bingads.v12.customermanagement; import javax.xml.ws.WebFault; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.1 * */ @WebFault(name = "ApiFault", targetNamespace = "https://bingads.microsoft.com/Customer/v12") public class ApiFault_Exception extends Exception { /** * Java type that goes as soapenv:Fault detail element. * */ private ApiFault faultInfo; /** * * @param faultInfo * @param message */ public ApiFault_Exception(String message, ApiFault faultInfo) { super(message); this.faultInfo = faultInfo; } /** * * @param faultInfo * @param cause * @param message */ public ApiFault_Exception(String message, ApiFault faultInfo, Throwable cause) { super(message, cause); this.faultInfo = faultInfo; } /** * * @return * returns fault bean: com.microsoft.bingads.v12.customermanagement.ApiFault */ public ApiFault getFaultInfo() { return faultInfo; } }
mit
dreamhead/moco
moco-runner/src/test/java/com/github/dreamhead/moco/MocoRedirectStandaloneTest.java
1015
package com.github.dreamhead.moco; import org.junit.Test; import java.io.IOException; import static com.github.dreamhead.moco.helper.RemoteTestUtils.remoteUrl; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class MocoRedirectStandaloneTest extends AbstractMocoStandaloneTest { @Test public void should_redirect_to_expected_url() throws IOException { runWithConfiguration("redirect.json"); assertThat(helper.get(remoteUrl("/redirect")), is("foo")); } @Test public void should_redirect_to_expected_url_with_template() throws IOException { runWithConfiguration("redirect.json"); assertThat(helper.get(remoteUrl("/redirect-with-template")), is("foo")); } @Test public void should_redirect_to_expected_url_with_path_resource() throws IOException { runWithConfiguration("redirect.json"); assertThat(helper.get(remoteUrl("/redirect-with-path-resource")), is("foo")); } }
mit
openforis/calc
calc-core/src/generated/java/org/openforis/calc/persistence/jooq/tables/WorkspaceSettingsTable.java
3770
/** * This class is generated by jOOQ */ package org.openforis.calc.persistence.jooq.tables; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import org.openforis.calc.metadata.WorkspaceSettings.VIEW_STEPS; import org.openforis.calc.persistence.jooq.CalcSchema; import org.openforis.calc.persistence.jooq.Keys; import org.openforis.calc.persistence.jooq.WorkspaceSettingsViewStepsConverter; import org.openforis.calc.persistence.jooq.tables.records.WorkspaceSettingsRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.6.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class WorkspaceSettingsTable extends TableImpl<WorkspaceSettingsRecord> { private static final long serialVersionUID = 1130824638; /** * The reference instance of <code>calc.workspace_settings</code> */ public static final WorkspaceSettingsTable WORKSPACE_SETTINGS = new WorkspaceSettingsTable(); /** * The class holding records for this type */ @Override public Class<WorkspaceSettingsRecord> getRecordType() { return WorkspaceSettingsRecord.class; } /** * The column <code>calc.workspace_settings.id</code>. */ public final TableField<WorkspaceSettingsRecord, Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false).defaulted(true), this, ""); /** * The column <code>calc.workspace_settings.workspace_id</code>. */ public final TableField<WorkspaceSettingsRecord, Long> WORKSPACE_ID = createField("workspace_id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>calc.workspace_settings.view_steps</code>. */ public final TableField<WorkspaceSettingsRecord, VIEW_STEPS> VIEW_STEPS = createField("view_steps", org.jooq.impl.SQLDataType.VARCHAR.nullable(false), this, "", new WorkspaceSettingsViewStepsConverter()); /** * Create a <code>calc.workspace_settings</code> table reference */ public WorkspaceSettingsTable() { this("workspace_settings", null); } /** * Create an aliased <code>calc.workspace_settings</code> table reference */ public WorkspaceSettingsTable(String alias) { this(alias, WORKSPACE_SETTINGS); } private WorkspaceSettingsTable(String alias, Table<WorkspaceSettingsRecord> aliased) { this(alias, aliased, null); } private WorkspaceSettingsTable(String alias, Table<WorkspaceSettingsRecord> aliased, Field<?>[] parameters) { super(alias, CalcSchema.CALC, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Identity<WorkspaceSettingsRecord, Long> getIdentity() { return Keys.IDENTITY_WORKSPACE_SETTINGS; } /** * {@inheritDoc} */ @Override public UniqueKey<WorkspaceSettingsRecord> getPrimaryKey() { return Keys.WORKSPACE_SETTINGS_PKEY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<WorkspaceSettingsRecord>> getKeys() { return Arrays.<UniqueKey<WorkspaceSettingsRecord>>asList(Keys.WORKSPACE_SETTINGS_PKEY); } /** * {@inheritDoc} */ @Override public List<ForeignKey<WorkspaceSettingsRecord, ?>> getReferences() { return Arrays.<ForeignKey<WorkspaceSettingsRecord, ?>>asList(Keys.WORKSPACE_SETTINGS__WORKSPACE_SETTINGS_WORKSPACEC_FKEY); } /** * {@inheritDoc} */ @Override public WorkspaceSettingsTable as(String alias) { return new WorkspaceSettingsTable(alias, this); } /** * Rename this table */ public WorkspaceSettingsTable rename(String name) { return new WorkspaceSettingsTable(name, null); } }
mit
vaginessa/android-store-google-play
src/com/soomla/store/billing/google/GooglePlayIabService.java
25456
/* * Copyright (C) 2012 Soomla Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.soomla.store.billing.google; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.*; import android.os.Process; import android.text.TextUtils; import com.soomla.SoomlaApp; import com.soomla.SoomlaConfig; import com.soomla.SoomlaUtils; import com.soomla.data.KeyValueStorage; import com.soomla.store.SoomlaStore; import com.soomla.store.billing.IIabService; import com.soomla.store.billing.IabCallbacks; import com.soomla.store.billing.IabException; import com.soomla.store.billing.IabHelper; import com.soomla.store.billing.IabInventory; import com.soomla.store.billing.IabPurchase; import com.soomla.store.billing.IabResult; import com.soomla.store.billing.IabSkuDetails; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * This is the Google Play plugin implementation of IIabService. * * see parent for more docs. */ public class GooglePlayIabService implements IIabService { public static final String VERSION = "1.0.3"; public GooglePlayIabService() { configVerifyPurchases(null); // we reset it every run } /** * see parent */ @Override public void initializeBillingService(final IabCallbacks.IabInitListener iabListener) { // Set up helper for the first time, querying and synchronizing inventory startIabHelper(new OnIabSetupFinishedListener(iabListener)); } /** * see parent */ @Override public void startIabServiceInBg(IabCallbacks.IabInitListener iabListener) { keepIabServiceOpen = true; startIabHelper(new OnIabSetupFinishedListener(iabListener)); } /** * see parent */ @Override public void stopIabServiceInBg(IabCallbacks.IabInitListener iabListener) { keepIabServiceOpen = false; stopIabHelper(iabListener); } /** * see parent */ @Override public void restorePurchasesAsync(IabCallbacks.OnRestorePurchasesListener restorePurchasesListener) { mHelper.restorePurchasesAsync(new RestorePurchasesFinishedListener(restorePurchasesListener)); } /** * see parent */ @Override public void fetchSkusDetailsAsync(List<String> skus, IabCallbacks.OnFetchSkusDetailsListener fetchSkusDetailsListener) { mHelper.fetchSkusDetailsAsync(skus, new FetchSkusDetailsFinishedListener(fetchSkusDetailsListener)); } /** * see parent */ @Override public boolean isIabServiceInitialized() { return mHelper != null; } /** * see parent */ @Override public void consume(IabPurchase purchase) throws IabException { mHelper.consume(purchase); } /** * see parent */ @Override public void consumeAsync(IabPurchase purchase, final IabCallbacks.OnConsumeListener consumeListener) { mHelper.consumeAsync(purchase, new GoogleIabHelper.OnConsumeFinishedListener() { @Override public void onConsumeFinished(IabPurchase purchase, IabResult result) { if (result.isSuccess()) { consumeListener.success(purchase); } else { consumeListener.fail(result.getMessage()); } } }); } /** * Sets the public key for Google Play IAB Service. * This function MUST be called once when the application loads and after SoomlaStore * initializes. * * @param publicKey the public key from the developer console. */ public void setPublicKey(String publicKey) { SharedPreferences prefs = SoomlaApp.getAppContext(). getSharedPreferences(SoomlaConfig.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); if (publicKey != null && publicKey.length() != 0) { edit.putString(PUBLICKEY_KEY, publicKey); } else if (prefs.getString(PUBLICKEY_KEY, "").length() == 0) { String err = "publicKey is null or empty. Can't initialize store!!"; SoomlaUtils.LogError(TAG, err); } edit.commit(); } @Override public void configVerifyPurchases(Map<String, Object> config) { KeyValueStorage.deleteKeyValue(VERIFY_PURCHASES_KEY); KeyValueStorage.deleteKeyValue(VERIFY_CLIENT_ID_KEY); KeyValueStorage.deleteKeyValue(VERIFY_CLIENT_SECRET_KEY); KeyValueStorage.deleteKeyValue(VERIFY_REFRESH_TOKEN_KEY); if (config != null) { try { checkStringConfigItem(config, "clientId"); checkStringConfigItem(config, "clientSecret"); checkStringConfigItem(config, "refreshToken"); } catch (IllegalArgumentException e) { SoomlaUtils.LogError(TAG, e.getMessage()); return; } Boolean verifyOnServerFailure = (Boolean) config.get("verifyOnServerFailure"); if (verifyOnServerFailure == null) { verifyOnServerFailure = false; } KeyValueStorage.setValue(VERIFY_CLIENT_ID_KEY, (String) config.get("clientId")); KeyValueStorage.setValue(VERIFY_CLIENT_SECRET_KEY, (String) config.get("clientSecret")); KeyValueStorage.setValue(VERIFY_REFRESH_TOKEN_KEY, (String) config.get("refreshToken")); KeyValueStorage.setValue(VERIFY_ON_SERVER_FAILURE, verifyOnServerFailure.toString()); KeyValueStorage.setValue(VERIFY_PURCHASES_KEY, "yes"); } } public void setAccessToken(String token) { KeyValueStorage.setValue(VERIFY_ACCESS_TOKEN_KEY, token); } public String getAccessToken() { return KeyValueStorage.getValue(VERIFY_ACCESS_TOKEN_KEY); } /** * see parent */ @Override public void launchPurchaseFlow(String sku, final IabCallbacks.OnPurchaseListener purchaseListener, String extraData) { SharedPreferences prefs = SoomlaApp.getAppContext(). getSharedPreferences(SoomlaConfig.PREFS_NAME, Context.MODE_PRIVATE); String publicKey = prefs.getString(PUBLICKEY_KEY, ""); if (publicKey.length() == 0 || publicKey.equals("[YOUR PUBLIC KEY FROM THE MARKET]")) { SoomlaUtils.LogError(TAG, "You didn't provide a public key! You can't make purchases. the key: " + publicKey); throw new IllegalStateException(); } try { final Intent intent = new Intent(SoomlaApp.getAppContext(), IabActivity.class); intent.putExtra(SKU, sku); intent.putExtra(EXTRA_DATA, extraData); mSavedOnPurchaseListener = purchaseListener; if (SoomlaApp.getAppContext() instanceof Activity) { Activity activity = (Activity) SoomlaApp.getAppContext(); activity.startActivity(intent); } else { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); SoomlaApp.getAppContext().startActivity(intent); } } catch(Exception e){ String msg = "(launchPurchaseFlow) Error purchasing item " + e.getMessage(); SoomlaUtils.LogError(TAG, msg); purchaseListener.fail(msg); } } /*==================== Private Utility Methods ====================*/ /** * Create a new IAB helper and set it up. * * @param onIabSetupFinishedListener is a callback that lets users to add their own implementation for when the Iab is started */ private synchronized void startIabHelper(OnIabSetupFinishedListener onIabSetupFinishedListener) { if (isIabServiceInitialized()) { SoomlaUtils.LogDebug(TAG, "The helper is started. Just running the post start function."); if (onIabSetupFinishedListener != null && onIabSetupFinishedListener.getIabInitListener() != null) { onIabSetupFinishedListener.getIabInitListener().success(true); } return; } SoomlaUtils.LogDebug(TAG, "Creating IAB helper."); mHelper = new GoogleIabHelper(); SoomlaUtils.LogDebug(TAG, "IAB helper Starting setup."); mHelper.startSetup(onIabSetupFinishedListener); } /** * Dispose of the helper to prevent memory leaks */ private synchronized void stopIabHelper(IabCallbacks.IabInitListener iabInitListener) { if (keepIabServiceOpen) { String msg = "Not stopping Google Service b/c the user run 'startIabServiceInBg'. Keeping it open."; if (iabInitListener != null) { iabInitListener.fail(msg); } else { SoomlaUtils.LogDebug(TAG, msg); } return; } if (mHelper == null) { String msg = "Tried to stop Google Service when it was null."; if (iabInitListener != null) { iabInitListener.fail(msg); } else { SoomlaUtils.LogDebug(TAG, msg); } return; } if (!mHelper.isAsyncInProgress()) { SoomlaUtils.LogDebug(TAG, "Stopping Google Service"); mHelper.dispose(); mHelper = null; if (iabInitListener != null) { iabInitListener.success(true); } } else { String msg = "Cannot stop Google Service during async process. Will be stopped when async operation is finished."; if (iabInitListener != null) { iabInitListener.fail(msg); } else { SoomlaUtils.LogDebug(TAG, msg); } } } private static boolean shouldVerifyPurchases() { return !TextUtils.isEmpty(KeyValueStorage.getValue(VERIFY_PURCHASES_KEY)); } /** * Async method - safe to run on ui thread. * Verifies purchases using the soomla server. */ private void verifyPurchases(final List<IabPurchase> purchases, final VerifyPurchasesFinishedListener listener) { new Thread(new Runnable() { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); for (IabPurchase purchase : purchases) { SoomlaGpVerification sv = new SoomlaGpVerification(purchase, KeyValueStorage.getValue(VERIFY_CLIENT_ID_KEY), KeyValueStorage.getValue(VERIFY_CLIENT_SECRET_KEY), KeyValueStorage.getValue(VERIFY_REFRESH_TOKEN_KEY), Boolean.parseBoolean(KeyValueStorage.getValue(VERIFY_ON_SERVER_FAILURE))); sv.verifyPurchase(); } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { listener.finished(); } }); } }).start(); } /** * Callback for verify purchases. */ public interface VerifyPurchasesFinishedListener { /** * Celled to notify that a verify purchases operation completed. */ public void finished(); } /** * Handle Restore Purchases processes */ private class RestorePurchasesFinishedListener implements IabHelper.RestorePurchasessFinishedListener { private IabCallbacks.OnRestorePurchasesListener mRestorePurchasesListener; public RestorePurchasesFinishedListener(IabCallbacks.OnRestorePurchasesListener restorePurchasesListener) { this.mRestorePurchasesListener = restorePurchasesListener; } @Override public void onRestorePurchasessFinished(IabResult result, IabInventory inventory) { SoomlaUtils.LogDebug(TAG, "Restore Purchases succeeded"); if (result.getResponse() == IabResult.BILLING_RESPONSE_RESULT_OK && mRestorePurchasesListener != null) { // fetching owned items List<String> itemSkus = inventory.getAllOwnedSkus(IabHelper.ITEM_TYPE_INAPP); final List<IabPurchase> purchases = new ArrayList<IabPurchase>(); for (String sku : itemSkus) { IabPurchase purchase = inventory.getPurchase(sku); purchases.add(purchase); } if (shouldVerifyPurchases()) { verifyPurchases(purchases, new VerifyPurchasesFinishedListener() { @Override public void finished() { restorePurchasessFinished(purchases); } }); } else { restorePurchasessFinished(purchases); } } else { SoomlaUtils.LogError(TAG, "Either mRestorePurchasesListener==null OR Restore purchases error: " + result.getMessage()); if (this.mRestorePurchasesListener != null) this.mRestorePurchasesListener.fail(result.getMessage()); stopIabHelper(null); } } private void restorePurchasessFinished(List<IabPurchase> purchases) { mRestorePurchasesListener.success(purchases); stopIabHelper(null); } } /** * Handle Fetch Skus Details processes */ private class FetchSkusDetailsFinishedListener implements IabHelper.FetchSkusDetailsFinishedListener { private IabCallbacks.OnFetchSkusDetailsListener mFetchSkusDetailsListener; public FetchSkusDetailsFinishedListener(IabCallbacks.OnFetchSkusDetailsListener fetchSkusDetailsListener) { this.mFetchSkusDetailsListener = fetchSkusDetailsListener; } @Override public void onFetchSkusDetailsFinished(IabResult result, IabInventory inventory) { SoomlaUtils.LogDebug(TAG, "Restore Purchases succeeded"); if (result.getResponse() == IabResult.BILLING_RESPONSE_RESULT_OK && mFetchSkusDetailsListener != null) { // @lassic (May 1st): actually, here (query finished) it only makes sense to get the details // of the SKUs we already queried for List<String> skuList = inventory.getAllQueriedSkus(false); List<IabSkuDetails> skuDetails = new ArrayList<IabSkuDetails>(); for (String sku : skuList) { IabSkuDetails skuDetail = inventory.getSkuDetails(sku); if (skuDetail != null) { skuDetails.add(skuDetail); } } this.mFetchSkusDetailsListener.success(skuDetails); } else { SoomlaUtils.LogError(TAG, "Wither mFetchSkusDetailsListener==null OR Fetching details error: " + result.getMessage()); if (this.mFetchSkusDetailsListener != null) this.mFetchSkusDetailsListener.fail(result.getMessage()); } stopIabHelper(null); } } /** * Handle setup billing service process */ private class OnIabSetupFinishedListener implements IabHelper.OnIabSetupFinishedListener { private IabCallbacks.IabInitListener mIabInitListener; public IabCallbacks.IabInitListener getIabInitListener() { return mIabInitListener; } public OnIabSetupFinishedListener(IabCallbacks.IabInitListener iabListener) { this.mIabInitListener = iabListener; } @Override public void onIabSetupFinished(IabResult result) { SoomlaUtils.LogDebug(TAG, "IAB helper Setup finished."); if (result.isFailure()) { if (mIabInitListener != null) mIabInitListener.fail(result.getMessage()); return; } if (mIabInitListener != null) mIabInitListener.success(false); } } /** * Handle setup billing purchase process */ private static class OnIabPurchaseFinishedListener implements IabHelper.OnIabPurchaseFinishedListener { public OnIabPurchaseFinishedListener() { } @Override public void onIabPurchaseFinished(IabResult result, final IabPurchase purchase) { /** * Wait to see if the purchase succeeded, then start the consumption process. */ SoomlaUtils.LogDebug(TAG, "IabPurchase finished: " + result + ", purchase: " + purchase); GooglePlayIabService.getInstance().mWaitingServiceResponse = false; if (result.getResponse() == IabResult.BILLING_RESPONSE_RESULT_OK) { if (shouldVerifyPurchases()) { GooglePlayIabService.getInstance().verifyPurchases(Arrays.asList(purchase), new VerifyPurchasesFinishedListener() { @Override public void finished() { purchaseFinishedSuccessfully(purchase); } }); } else { purchaseFinishedSuccessfully(purchase); } return; } else if (result.getResponse() == IabResult.BILLING_RESPONSE_RESULT_USER_CANCELED) { GooglePlayIabService.getInstance().mSavedOnPurchaseListener.cancelled(purchase); } else if (result.getResponse() == IabResult.BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED) { GooglePlayIabService.getInstance().mSavedOnPurchaseListener.alreadyOwned(purchase); } else { GooglePlayIabService.getInstance().mSavedOnPurchaseListener.fail(result.getMessage()); } purchaseFinished(); } private void purchaseFinishedSuccessfully(IabPurchase purchase) { GooglePlayIabService.getInstance().mSavedOnPurchaseListener.success(purchase); purchaseFinished(); } private void purchaseFinished() { GooglePlayIabService.getInstance().mSavedOnPurchaseListener = null; GooglePlayIabService.getInstance().stopIabHelper(null); } } /** * Android In-App Billing v3 requires an activity to receive the result of the billing process. * This activity's job is to do just that, it also contains the white/green IAB window. * Please do NOT start it on your own. */ public static class IabActivity extends Activity { private boolean mInProgressDestroy = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String productId = intent.getStringExtra(SKU); String payload = intent.getStringExtra(EXTRA_DATA); try { OnIabPurchaseFinishedListener onIabPurchaseFinishedListener = new OnIabPurchaseFinishedListener(); GooglePlayIabService.getInstance().mHelper.launchPurchaseFlow(this, productId, onIabPurchaseFinishedListener, payload); GooglePlayIabService.getInstance().mWaitingServiceResponse = true; } catch (IllegalStateException e) { mInProgressDestroy = true; finish(); } catch (Exception e) { SoomlaUtils.LogDebug(TAG, "MSG: " + e.getMessage()); finish(); String msg = "Error purchasing item " + e.getMessage(); SoomlaUtils.LogError(TAG, msg); GooglePlayIabService.getInstance().mWaitingServiceResponse = false; if (GooglePlayIabService.getInstance().mSavedOnPurchaseListener != null) { GooglePlayIabService.getInstance().mSavedOnPurchaseListener.fail(msg); GooglePlayIabService.getInstance().mSavedOnPurchaseListener = null; } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { SoomlaUtils.LogDebug(TAG, "onActivityResult 1"); if (!GooglePlayIabService.getInstance().mHelper.handleActivityResult(requestCode, resultCode, data)) { SoomlaUtils.LogDebug(TAG, "onActivityResult 2"); super.onActivityResult(requestCode, resultCode, data); } SoomlaUtils.LogDebug(TAG, "onActivityResult 3"); finish(); } @Override protected void onPause() { super.onPause(); } boolean firstTime = true; @Override protected void onResume() { SoomlaUtils.LogDebug(TAG, "onResume 1"); super.onResume(); firstTime = false; } @Override protected void onStop() { super.onStop(); } @Override protected void onStart() { SoomlaUtils.LogDebug(TAG, "onStart 1"); super.onStart(); if (!firstTime && SoomlaApp.getAppContext() instanceof Activity) { SoomlaUtils.LogDebug(TAG, "onStart 2"); onActivityResult(10001, Activity.RESULT_CANCELED, null); Intent tabIntent = new Intent(this, ((Activity) SoomlaApp.getAppContext()).getClass()); tabIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); SoomlaUtils.LogDebug(TAG, "onStart 3"); startActivity(tabIntent); } SoomlaUtils.LogDebug(TAG, "onStart 4"); } @Override protected void onDestroy() { SoomlaUtils.LogDebug(TAG, "onDestroy 1"); if (!mInProgressDestroy && GooglePlayIabService.getInstance().mWaitingServiceResponse) { SoomlaUtils.LogDebug(TAG, "onDestroy 2"); GooglePlayIabService.getInstance().mWaitingServiceResponse = false; String err = "IabActivity is destroyed during purchase."; SoomlaUtils.LogError(TAG, err); // we're letting the helper take care of closing so there won't be any async process stuck in it. onActivityResult(10001, Activity.RESULT_CANCELED, null); // if (GooglePlayIabService.getInstance().mSavedOnPurchaseListener != null) { // SoomlaUtils.LogDebug(TAG, "onDestroy 3"); // GooglePlayIabService.getInstance().mSavedOnPurchaseListener.fail(err); // GooglePlayIabService.getInstance().mSavedOnPurchaseListener = null; // } } SoomlaUtils.LogDebug(TAG, "onDestroy 4"); super.onDestroy(); } } private void checkStringConfigItem(Map<String, Object> config, String key) { Object strToCheck = config.get(key); if (strToCheck == null || !(strToCheck instanceof String) || TextUtils.isEmpty((String) strToCheck)) { throw new IllegalArgumentException("Please, provide value for " + key); } } public static GooglePlayIabService getInstance() { return (GooglePlayIabService) SoomlaStore.getInstance().getInAppBillingService(); } /* Private Members */ private static final String TAG = "SOOMLA GooglePlayIabService"; private GoogleIabHelper mHelper; private boolean keepIabServiceOpen = false; private boolean mWaitingServiceResponse = false; public static final String PUBLICKEY_KEY = "PO#SU#SO#GU"; public static final String VERIFY_PURCHASES_KEY = "soomla.verification.verifyPurchases"; public static final String VERIFY_ON_SERVER_FAILURE = "soomla.verification.verifyOnServerFailure"; public static final String VERIFY_REFRESH_TOKEN_KEY = "soomla.verification.refreshToken"; public static final String VERIFY_CLIENT_ID_KEY = "soomla.verification.clientId"; public static final String VERIFY_CLIENT_SECRET_KEY = "soomla.verification.clientSecret"; public static final String VERIFY_ACCESS_TOKEN_KEY = "soomla.verification.accessToken"; private static final String SKU = "ID#sku"; private static final String EXTRA_DATA = "ID#extraData"; private IabCallbacks.OnPurchaseListener mSavedOnPurchaseListener = null; /** * When set to true, this removes the need to verify purchases when there's no signature. * This is useful while you are in development and testing stages of your game. * * WARNING: Do NOT publish your app with this set to true!!! */ public static boolean AllowAndroidTestPurchases = false; }
mit
ExilantTechnologies/ExilityCore-5.0.0
foundation/com/exilant/exility/core/Pages.java
5149
/* ******************************************************************************************************* Copyright (c) 2015 EXILANT Technologies Private Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************************************** */ package com.exilant.exility.core; import java.util.HashMap; import java.util.List; import java.util.Map; import com.exilant.exility.ide.FieldDetails; /*** * Class that manages instances of Page component. However, unlike other such * components, Pages are not cached for re-use, as we do not intend to use this * at run time. At design time, it is required that we use the latest version * always, rather than use cached ones. * * @author Exilant Technologies * */ public class Pages { /** * all fields */ public static final int FIELD_FILTER_ALL = 0; /** * fields that are sent to server on a form submit. Note that it is possible * that a programmer could send any field thru script, that is normally not * sent automatically by exility. We use the logic, any input field (that is * not marked as doNotSendToServer), and output fields marked as * toBeSentToServer */ public static final int FIELD_FILTER_SENT_TO_SERVER = 1; /** * get page from its persistent state * * @param folderName * @param pageName * @return page instance, null if it is not found or could not be parsed */ public static Page getPage(String folderName, String pageName) { String resourceName = pageName; if (folderName != null) { resourceName = folderName + '/' + pageName; } resourceName = "page." + resourceName; Object o = ResourceManager.loadResource(resourceName, Page.class); if (o == null) { Spit.out(pageName + " Could not be loaded. Possible that that the XML is in error. Lok at log file."); return null; } if (o instanceof Page == false) { // it is likely to be include panel.. Spit.out(pageName + " is not a page. It is proably an include panel..."); return null; } Page page = (Page) o; if (pageName.equals(page.name) == false) { Spit.out("File " + pageName + ".xml has a page named " + page.name + ". Page name MUST match name of the file."); return null; } return page; } /** * save this instance into its persistent form * * @param thisPage */ public static void savePage(Page thisPage) { String fileName = "page/" + ((thisPage.module != null) ? (thisPage.module + '.') : "") + thisPage.name; ResourceManager.saveResource(fileName, thisPage); } static AbstractPanel getPanel(String panelName) { Spit.out("Going to load panel with file name = " + "page." + panelName + ".xml"); Object o = ResourceManager.loadResource("page/" + panelName, AbstractPanel.class); if (o != null) { return (AbstractPanel) o; } Spit.out(panelName + " could not be loaded"); return null; } /** * * @param filterType * FIELD_FILTER_ALL, FIELD_FILTER_SENT_TO_SERVER are implemented * @return list of fields with details for each page */ public static Map<String, List<FieldDetails>> getFields(int filterType) { String[] names = ResourceManager.getResourceList("page", ".xml"); int nbrPagesScanned = 0; Map<String, List<FieldDetails>> fields = new HashMap<String, List<FieldDetails>>(); for (String pageName : names) { Page page = Pages.getPage(null, pageName); if (page != null) { page.addAllFields(fields, filterType); } } Spit.out(nbrPagesScanned + " pages scanned for filtering field information"); /* * consolidate data from different pages for each field and populate * fields in the first occurrence */ for (String fieldName : fields.keySet()) { List<FieldDetails> details = fields.get(fieldName); int nbrPages = details.size(); FieldDetails firstOne = details.get(0); firstOne.nbrUsageAcrossResources = nbrPages; if (nbrPages > 1) { for (int i = 1; i < nbrPages; i++) { FieldDetails thisOne = details.get(i); firstOne.commaSeparatedResourceNames += ',' + thisOne.resourceName; } } } return fields; } }
mit
oysteing/jira-mailqueue
src/main/java/net/gisnas/jira/rest/MailQueueStatusModel.java
435
package net.gisnas.jira.rest; import javax.xml.bind.annotation.*; import com.atlassian.mail.queue.MailQueue; @XmlRootElement(name = "mailQueue") @XmlAccessorType(XmlAccessType.FIELD) public class MailQueueStatusModel { int size; int errorSize; public MailQueueStatusModel() { } public MailQueueStatusModel(MailQueue mailQueue) { size = mailQueue.size(); errorSize = mailQueue.errorSize(); } }
mit
caijiang/goods
goods-core/src/main/java/me/jiangcai/goods/core/service/impl/StockManageServiceImpl.java
953
/* * 版权所有:蒋才 * (c) Copyright Cai Jiang * 2013-2017. All rights reserved. */ package me.jiangcai.goods.core.service.impl; import me.jiangcai.goods.Goods; import me.jiangcai.goods.stock.StockManageService; import me.jiangcai.goods.stock.StockService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; /** * @author CJ */ @Service public class StockManageServiceImpl implements StockManageService { @Autowired private ApplicationContext applicationContext; @Override public StockService stockService(Goods goods) { return applicationContext.getBeansOfType(StockService.class).values().stream() .filter(stockService -> stockService.support(goods)) .findFirst() .orElseThrow(() -> new IllegalStateException("没有支持的库存服务")); } }
mit
svetliub/FinalExam_ProgrammingBasics_07.05.2017
p02_ToyShop.java
1114
package final_exam_2017_05_07; import java.util.Scanner; public class p02_ToyShop { public static void main(String[] args) { Scanner console = new Scanner(System.in); double priceTrip = Double.parseDouble(console.nextLine()); int puzzle = Integer.parseInt(console.nextLine()); int doll = Integer.parseInt(console.nextLine()); int bears = Integer.parseInt(console.nextLine()); int minions = Integer.parseInt(console.nextLine()); int trucks = Integer.parseInt(console.nextLine()); int totalQuantity = puzzle + doll + bears + minions + trucks; double totalPrice = puzzle * 2.6 + doll * 3 + bears * 4.1 + minions * 8.2 + trucks * 2; if (totalQuantity >= 50){ totalPrice = totalPrice * 0.75; } totalPrice = totalPrice * 0.9; if (totalPrice >= priceTrip){ System.out.printf("Yes! %.2f lv left.", (totalPrice - priceTrip)); } else { System.out.printf("Not enough money! %.2f lv needed.", (priceTrip - totalPrice)); } } }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/java/io/FileWriter.java
4378
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1996, 2001. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.io; /** * Convenience class for writing character files. The constructors of this * class assume that the default character encoding and the default byte-buffer * size are acceptable. To specify these values yourself, construct an * OutputStreamWriter on a FileOutputStream. * * <p>Whether or not a file is available or may be created depends upon the * underlying platform. Some platforms, in particular, allow a file to be * opened for writing by only one <tt>FileWriter</tt> (or other file-writing * object) at a time. In such situations the constructors in this class * will fail if the file involved is already open. * * <p><code>FileWriter</code> is meant for writing streams of characters. * For writing streams of raw bytes, consider using a * <code>FileOutputStream</code>. * * @see OutputStreamWriter * @see FileOutputStream * * @author Mark Reinhold * @since JDK1.1 */ public class FileWriter extends OutputStreamWriter { /** * Constructs a FileWriter object given a file name. * * @param fileName String The system-dependent filename. * @throws IOException if the named file exists but is a directory rather * than a regular file, does not exist but cannot be * created, or cannot be opened for any other reason */ public FileWriter(String fileName) throws IOException { super(new FileOutputStream(fileName)); } /** * Constructs a FileWriter object given a file name with a boolean * indicating whether or not to append the data written. * * @param fileName String The system-dependent filename. * @param append boolean if <code>true</code>, then data will be written * to the end of the file rather than the beginning. * @throws IOException if the named file exists but is a directory rather * than a regular file, does not exist but cannot be * created, or cannot be opened for any other reason */ public FileWriter(String fileName, boolean append) throws IOException { super(new FileOutputStream(fileName, append)); } /** * Constructs a FileWriter object given a File object. * * @param file a File object to write to. * @throws IOException if the file exists but is a directory rather than * a regular file, does not exist but cannot be created, * or cannot be opened for any other reason */ public FileWriter(File file) throws IOException { super(new FileOutputStream(file)); } /** * Constructs a FileWriter object given a File object. If the second * argument is <code>true</code>, then bytes will be written to the end * of the file rather than the beginning. * * @param file a File object to write to * @param append if <code>true</code>, then bytes will be written * to the end of the file rather than the beginning * @throws IOException if the file exists but is a directory rather than * a regular file, does not exist but cannot be created, * or cannot be opened for any other reason * @since 1.4 */ public FileWriter(File file, boolean append) throws IOException { super(new FileOutputStream(file, append)); } /** * Constructs a FileWriter object associated with a file descriptor. * * @param fd FileDescriptor object to write to. */ public FileWriter(FileDescriptor fd) { super(new FileOutputStream(fd)); } }
mit
nishant304/hacker-news-client
app/src/main/java/com/hn/nishant/nvhn/events/UpdateEvent.java
543
package com.hn.nishant.nvhn.events; import java.util.List; /** * Created by nishant on 06.04.17. */ public class UpdateEvent { private List<Long> updatedItems; public List<Integer> getRanks() { return ranks; } public void setRanks(List<Integer> ranks) { this.ranks = ranks; } private List<Integer> ranks; public List<Long> getUpdatedItems() { return updatedItems; } public void setUpdatedItems(List<Long> updatedItems) { this.updatedItems = updatedItems; } }
mit
Azure/azure-sdk-for-java
sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/src/main/java/com/azure/resourcemanager/mobilenetwork/models/ProvisioningState.java
1907
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.mobilenetwork.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for ProvisioningState. */ public final class ProvisioningState extends ExpandableStringEnum<ProvisioningState> { /** Static value Unknown for ProvisioningState. */ public static final ProvisioningState UNKNOWN = fromString("Unknown"); /** Static value Succeeded for ProvisioningState. */ public static final ProvisioningState SUCCEEDED = fromString("Succeeded"); /** Static value Accepted for ProvisioningState. */ public static final ProvisioningState ACCEPTED = fromString("Accepted"); /** Static value Deleting for ProvisioningState. */ public static final ProvisioningState DELETING = fromString("Deleting"); /** Static value Failed for ProvisioningState. */ public static final ProvisioningState FAILED = fromString("Failed"); /** Static value Canceled for ProvisioningState. */ public static final ProvisioningState CANCELED = fromString("Canceled"); /** Static value Deleted for ProvisioningState. */ public static final ProvisioningState DELETED = fromString("Deleted"); /** * Creates or finds a ProvisioningState from its string representation. * * @param name a name to look for. * @return the corresponding ProvisioningState. */ @JsonCreator public static ProvisioningState fromString(String name) { return fromString(name, ProvisioningState.class); } /** @return known ProvisioningState values. */ public static Collection<ProvisioningState> values() { return values(ProvisioningState.class); } }
mit
tmtsoftware/es-perftest
mbsuite-addons/src/org/tmt/addons/ospl/osplData/MsgTypeSupport.java
2454
package org.tmt.addons.ospl.osplData; import org.opensplice.dds.dcps.Utilities; public class MsgTypeSupport extends org.opensplice.dds.dcps.TypeSupportImpl implements DDS.TypeSupportOperations { private static java.lang.String idl_type_name = "org.tmt.addons.ospl.osplData::Msg"; private static java.lang.String idl_key_list = "userID"; private long copyCache; public MsgTypeSupport() { super("org.tmt.addons.ospl.osplData/MsgDataReaderImpl", "org.tmt.addons.ospl.osplData/MsgDataReaderViewImpl", "org.tmt.addons.ospl.osplData/MsgDataWriterImpl", "(Lorg.tmt.addons.ospl.osplData/MsgTypeSupport;)V", "null", "null"); int success = 0; try { success = org.opensplice.dds.dcps.FooTypeSupportImpl.Alloc( this, idl_type_name, idl_key_list, org.tmt.addons.ospl.osplData.MsgMetaHolder.metaDescriptor); } catch (UnsatisfiedLinkError ule) { /* * JNI library is not loaded if no instance of the * DomainParticipantFactory exists. */ DDS.DomainParticipantFactory f = DDS.DomainParticipantFactory.get_instance(); if (f != null) { success = org.opensplice.dds.dcps.FooTypeSupportImpl.Alloc( this, idl_type_name, idl_key_list, org.tmt.addons.ospl.osplData.MsgMetaHolder.metaDescriptor); } } if (success == 0) { throw Utilities.createException( Utilities.EXCEPTION_TYPE_NO_MEMORY, "Could not allocate MsgTypeSupport." ); } } protected void finalize() throws Throwable { try { org.opensplice.dds.dcps.FooTypeSupportImpl.Free(this); } catch(Throwable t){ } finally{ super.finalize(); } } public long get_copyCache() { return copyCache; } public int register_type( DDS.DomainParticipant participant, java.lang.String type_name) { return org.opensplice.dds.dcps.FooTypeSupportImpl.registerType( this, participant, type_name); } public String get_type_name() { return idl_type_name; } }
mit
lotaris/rox-client-java
rox-client-java/src/main/java/com/lotaris/rox/common/model/v1/Payload.java
1215
package com.lotaris.rox.common.model.v1; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.lotaris.rox.common.model.RoxPayload; import com.lotaris.rox.commons.optimize.Optimizer; import com.lotaris.rox.commons.optimize.v1.PayloadOptimizer; /** * Root element to store a list of test runs * * @author Laurent Preost, laurent.prevost@lotaris.com */ @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) public class Payload implements RoxPayload { private static final String API_VERSION = "v1"; @JsonProperty @JsonUnwrapped private TestRun testRun; @Override public String getVersion() { return API_VERSION; } @Override public Optimizer getOptimizer() { return new PayloadOptimizer(); } public TestRun getTestRun() { return testRun; } public void setTestRun(TestRun testRun) { this.testRun = testRun; } @Override public String toString() { StringBuilder sb = new StringBuilder("TestRuns: ["); sb.append(testRun); return "Payload: [" + sb.toString().replaceAll(", $", "]") + "]"; } }
mit
pepm99/Project-Arnold
Project_Arnold/app/src/main/java/com/example/aoc/project_arnold/Database/DBHelper.java
2299
package com.example.aoc.project_arnold.Database; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.example.aoc.project_arnold.Activities.AddTrainingActivity; import com.example.aoc.project_arnold.Activities.MainActivity; import java.io.IOException; public class DBHelper extends SQLiteOpenHelper { static final String DB_NAME="Exercises"; static final int DB_CURRENT_VERSION = 1; protected SQLiteDatabase db; protected static String tableActivity = "activity"; public DBHelper(Context context) { super(context, DB_NAME, null, DB_CURRENT_VERSION); open(); } //Когато се опитаме да използваме базата но тя не е създадена Инициализация на базата данни @Override public void onCreate(SQLiteDatabase db) { Log.d("D1","Before Create DB"); StringBuilder sb = new StringBuilder(); try { do{ sb.append(AddTrainingActivity.DB_CREATE_TXT.readLine().toString()); }while (AddTrainingActivity.DB_CREATE_TXT.readLine()!=null); AddTrainingActivity.DB_CREATE_TXT.close(); } catch (IOException e) { e.printStackTrace(); } Log.d("D1",sb.toString()); db.execSQL(sb.toString());//Изпълняваме sql за създаване на базата данни заявката е изнесена в ресурси Log.d("D1","Created DB"); AddTrainingActivity.edit.putInt(AddTrainingActivity.traningCountInt,0); AddTrainingActivity.edit.commit(); } //Когато базата дани вече е създадена и има нова версия примерно да добавим нови полета @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void open() throws SQLException{ // Метод за отваряне на базата данни db=getWritableDatabase(); } public void close(){ //Метод за затваряне на базата данни db.close(); } }
mit
pfgray/lmsrest
lms-api/src/main/java/net/paulgray/lmsrest/discussion/DiscussionBoard.java
1688
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.paulgray.lmsrest.discussion; import java.util.Date; import net.paulgray.lmsrest.course.Course; /** * * @author pfgray */ public class DiscussionBoard { protected String id; protected String title; protected String description; protected Date lastEdited; protected Boolean available; protected Date endDate; protected Course course; public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getStartDate() { return lastEdited; } public void setStartDate(Date startDate) { this.lastEdited = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getLastEdited() { return lastEdited; } public void setLastEdited(Date lastEdited) { this.lastEdited = lastEdited; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } }
mit
latinojoel/healthtracker
src/main/java/com/latinojoel/health/dao/impl/UserDaoImpl.java
1496
package com.latinojoel.health.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import com.latinojoel.health.dao.AbstractDao; import com.latinojoel.health.dao.UserDao; import com.latinojoel.health.model.HypertensionRecord; import com.latinojoel.health.model.User; @Repository("userDao") public class UserDaoImpl extends AbstractDao<Integer, User> implements UserDao { public void save(User user) { final Session session = getSession(); final Transaction trans = session.beginTransaction(); persist(user); trans.commit(); } public User findById(int id) { return getByKey(id); } public User findByEmail(String email) { final Session session = getSession(); final Transaction trans = session.beginTransaction(); final Criteria crit = getSession().createCriteria(User.class); crit.add(Restrictions.eq("email", email)); final User user = (User) crit.uniqueResult(); trans.commit(); return user; } public List<User> getUsers() { final Session session = getSession(); final Transaction trans = session.beginTransaction(); final List<User> list = session.createCriteria(User.class).addOrder(Order.desc("email")).list(); trans.commit(); return list; } }
mit
AmethystAir/ExtraCells2
src/main/scala/extracells/part/PartFluidInterface.java
33698
package extracells.part; import io.netty.buffer.ByteBuf; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; import net.minecraftforge.fluids.IFluidTank; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; import appeng.api.implementations.ICraftingPatternItem; import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.networking.crafting.ICraftingProvider; import appeng.api.networking.crafting.ICraftingProviderHelper; import appeng.api.networking.events.MENetworkCraftingPatternChange; import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.security.MachineSource; import appeng.api.networking.storage.IStorageGrid; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; import appeng.api.parts.IPart; import appeng.api.parts.IPartCollisionHelper; import appeng.api.parts.IPartRenderHelper; import appeng.api.parts.PartItemStack; import appeng.api.storage.IMEMonitor; import appeng.api.storage.IStorageMonitorable; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.api.IFluidInterface; import extracells.api.crafting.IFluidCraftingPatternDetails; import extracells.container.ContainerFluidInterface; import extracells.container.IContainerListener; import extracells.crafting.CraftingPattern; import extracells.crafting.CraftingPattern2; import extracells.gui.GuiFluidInterface; import extracells.network.packet.other.IFluidSlotPartOrBlock; import extracells.registries.ItemEnum; import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.EmptyMeItemMonitor; import extracells.util.ItemUtils; import extracells.util.PermissionUtil; public class PartFluidInterface extends PartECBase implements IFluidHandler, IFluidInterface, IFluidSlotPartOrBlock, ITileStorageMonitorable, IStorageMonitorable, IGridTickable, ICraftingProvider { private class FluidInterfaceInventory implements IInventory { private ItemStack[] inv = new ItemStack[9]; @Override public void closeInventory() {} @Override public ItemStack decrStackSize(int slot, int amt) { ItemStack stack = getStackInSlot(slot); if (stack != null) { if (stack.stackSize <= amt) { setInventorySlotContents(slot, null); } else { stack = stack.splitStack(amt); if (stack.stackSize == 0) { setInventorySlotContents(slot, null); } } } PartFluidInterface.this.update = true; return stack; } @Override public String getInventoryName() { return "inventory.fluidInterface"; } @Override public int getInventoryStackLimit() { return 1; } @Override public int getSizeInventory() { return this.inv.length; } @Override public ItemStack getStackInSlot(int slot) { return this.inv[slot]; } @Override public ItemStack getStackInSlotOnClosing(int slot) { return null; } @Override public boolean hasCustomInventoryName() { return false; } @Override public boolean isItemValidForSlot(int slot, ItemStack stack) { if (stack.getItem() instanceof ICraftingPatternItem) { IGridNode n = getGridNode(); World w; if (n == null) { w = getClientWorld(); } else { w = n.getWorld(); } if (w == null) return false; ICraftingPatternDetails details = ((ICraftingPatternItem) stack .getItem()).getPatternForItem(stack, w); return details != null; } return false; } @Override public boolean isUseableByPlayer(EntityPlayer player) { return true; } @Override public void markDirty() {} @Override public void openInventory() {} public void readFromNBT(NBTTagCompound tagCompound) { NBTTagList tagList = tagCompound.getTagList("Inventory", 10); for (int i = 0; i < tagList.tagCount(); i++) { NBTTagCompound tag = tagList.getCompoundTagAt(i); byte slot = tag.getByte("Slot"); if (slot >= 0 && slot < this.inv.length) { this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); } } } @Override public void setInventorySlotContents(int slot, ItemStack stack) { this.inv[slot] = stack; if (stack != null && stack.stackSize > getInventoryStackLimit()) { stack.stackSize = getInventoryStackLimit(); } PartFluidInterface.this.update = true; } public void writeToNBT(NBTTagCompound tagCompound) { NBTTagList itemList = new NBTTagList(); for (int i = 0; i < this.inv.length; i++) { ItemStack stack = this.inv[i]; if (stack != null) { NBTTagCompound tag = new NBTTagCompound(); tag.setByte("Slot", (byte) i); stack.writeToNBT(tag); itemList.appendTag(tag); } } tagCompound.setTag("Inventory", itemList); } } List<IContainerListener> listeners = new ArrayList<IContainerListener>(); private List<ICraftingPatternDetails> patternHandlers = new ArrayList<ICraftingPatternDetails>(); private HashMap<ICraftingPatternDetails, IFluidCraftingPatternDetails> patternConvert = new HashMap<ICraftingPatternDetails, IFluidCraftingPatternDetails>(); private List<IAEItemStack> requestedItems = new ArrayList<IAEItemStack>(); private List<IAEItemStack> removeList = new ArrayList<IAEItemStack>(); public final FluidInterfaceInventory inventory = new FluidInterfaceInventory(); private boolean update = false; private List<IAEStack> export = new ArrayList<IAEStack>(); private List<IAEStack> removeFromExport = new ArrayList<IAEStack>(); private List<IAEStack> addToExport = new ArrayList<IAEStack>(); private IAEItemStack toExport = null; private final Item encodedPattern = AEApi.instance().items().itemEncodedPattern .item(); private FluidTank tank = new FluidTank(10000) { @Override public FluidTank readFromNBT(NBTTagCompound nbt) { if (!nbt.hasKey("Empty")) { FluidStack fluid = FluidStack.loadFluidStackFromNBT(nbt); setFluid(fluid); } else { setFluid(null); } return this; } }; private int fluidFilter = -1; public boolean doNextUpdate = false; private boolean needBreake = false; private int tickCount = 0; @Override public int cableConnectionRenderTo() { return 3; } @Override public boolean canDrain(ForgeDirection from, Fluid fluid) { FluidStack tankFluid = this.tank.getFluid(); return tankFluid != null && tankFluid.getFluid() == fluid; } @Override public boolean canFill(ForgeDirection from, Fluid fluid) { return this.tank.fill(new FluidStack(fluid, 1), false) > 0; } @Override public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { FluidStack tankFluid = this.tank.getFluid(); if (resource == null || tankFluid == null || tankFluid.getFluid() != resource.getFluid()) return null; return drain(from, resource.amount, doDrain); } @Override public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { FluidStack drained = this.tank.drain(maxDrain, doDrain); if (drained != null) getHost().markForUpdate(); this.doNextUpdate = true; return drained; } @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { if (resource == null) return 0; if ((this.tank.getFluid() == null || this.tank.getFluid().getFluid() == resource .getFluid()) && resource.getFluid() == FluidRegistry .getFluid(this.fluidFilter)) { int added = this.tank.fill(resource.copy(), doFill); if (added == resource.amount) { this.doNextUpdate = true; return added; } added += fillToNetwork(new FluidStack(resource.getFluid(), resource.amount - added), doFill); this.doNextUpdate = true; return added; } int filled = 0; filled += fillToNetwork(resource, doFill); if (filled < resource.amount) filled += this.tank.fill(new FluidStack(resource.getFluidID(), resource.amount - filled), doFill); if (filled > 0) getHost().markForUpdate(); this.doNextUpdate = true; return filled; } public int fillToNetwork(FluidStack resource, boolean doFill) { IGridNode node = getGridNode(ForgeDirection.UNKNOWN); if (node == null || resource == null) return 0; IGrid grid = node.getGrid(); if (grid == null) return 0; IStorageGrid storage = grid.getCache(IStorageGrid.class); if (storage == null) return 0; IAEFluidStack notRemoved; FluidStack copy = resource.copy(); if (doFill) { notRemoved = storage.getFluidInventory().injectItems( AEApi.instance().storage().createFluidStack(resource), Actionable.MODULATE, new MachineSource(this)); } else { notRemoved = storage.getFluidInventory().injectItems( AEApi.instance().storage().createFluidStack(resource), Actionable.SIMULATE, new MachineSource(this)); } if (notRemoved == null) return resource.amount; return (int) (resource.amount - notRemoved.getStackSize()); } private void forceUpdate() { getHost().markForUpdate(); for (IContainerListener listener : this.listeners) { if (listener != null) listener.updateContainer(); } this.doNextUpdate = false; } @Override public void getBoxes(IPartCollisionHelper bch) { bch.addBox(2, 2, 14, 14, 14, 16); bch.addBox(5, 5, 12, 11, 11, 14); } @Override public Object getClientGuiElement(EntityPlayer player) { return new GuiFluidInterface(player, this, getSide()); } @SideOnly(Side.CLIENT) private World getClientWorld() { return Minecraft.getMinecraft().theWorld; } @Override public void getDrops(List<ItemStack> drops, boolean wrenched) { for (int i = 0; i < this.inventory.getSizeInventory(); i++) { ItemStack pattern = this.inventory.getStackInSlot(i); if (pattern != null) drops.add(pattern); } } @Override public Fluid getFilter(ForgeDirection side) { return FluidRegistry.getFluid(this.fluidFilter); } @Override public IMEMonitor<IAEFluidStack> getFluidInventory() { if (getGridNode(ForgeDirection.UNKNOWN) == null) return null; IGrid grid = getGridNode(ForgeDirection.UNKNOWN).getGrid(); if (grid == null) return null; IStorageGrid storage = grid.getCache(IStorageGrid.class); if (storage == null) return null; return storage.getFluidInventory(); } @Override public IFluidTank getFluidTank(ForgeDirection side) { return this.tank; } @Override public IMEMonitor<IAEItemStack> getItemInventory() { return new EmptyMeItemMonitor(); } @Override public ItemStack getItemStack(PartItemStack type) { ItemStack is = new ItemStack(ItemEnum.PARTITEM.getItem(), 1, PartEnum.getPartID(this)); if (type != PartItemStack.Break) { is.setTagCompound(writeFilter(new NBTTagCompound())); } return is; } @Override public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src) { return this; } @Override public IInventory getPatternInventory() { return this.inventory; } @Override public double getPowerUsage() { return 1.0D; } @Override public Object getServerGuiElement(EntityPlayer player) { return new ContainerFluidInterface(player, this); } @Override public FluidTankInfo[] getTankInfo(ForgeDirection from) { return new FluidTankInfo[] { this.tank.getInfo() }; } @Override public TickingRequest getTickingRequest(IGridNode node) { return new TickingRequest(1, 40, false, false); } @Override public List<String> getWailaBodey(NBTTagCompound tag, List<String> list) { FluidStack fluid = null; int id = -1; int amount = 0; if (tag.hasKey("fluidID") && tag.hasKey("amount")) { id = tag.getInteger("fluidID"); amount = tag.getInteger("amount"); } if (id != -1) fluid = new FluidStack(id, amount); if (fluid == null) { list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + StatCollector .translateToLocal("extracells.tooltip.empty1")); list.add(StatCollector .translateToLocal("extracells.tooltip.amount") + ": 0mB / 10000mB"); } else { list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + fluid.getLocalizedName()); list.add(StatCollector .translateToLocal("extracells.tooltip.amount") + ": " + fluid.amount + "mB / 10000mB"); } return list; } @Override public NBTTagCompound getWailaTag(NBTTagCompound tag) { if (this.tank.getFluid() == null || this.tank.getFluid().getFluid() == null) tag.setInteger("fluidID", -1); else tag.setInteger("fluidID", this.tank.getFluid().getFluidID()); tag.setInteger("amount", this.tank.getFluidAmount()); return tag; } @Override public void initializePart(ItemStack partStack) { if (partStack.hasTagCompound()) { readFilter(partStack.getTagCompound()); } } @Override public boolean isBusy() { return !this.export.isEmpty(); } private ItemStack makeCraftingPatternItem(ICraftingPatternDetails details) { if (details == null) return null; NBTTagList in = new NBTTagList(); NBTTagList out = new NBTTagList(); for (IAEItemStack s : details.getInputs()) { if (s == null) in.appendTag(new NBTTagCompound()); else in.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); } for (IAEItemStack s : details.getOutputs()) { if (s == null) out.appendTag(new NBTTagCompound()); else out.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); } NBTTagCompound itemTag = new NBTTagCompound(); itemTag.setTag("in", in); itemTag.setTag("out", out); itemTag.setBoolean("crafting", details.isCraftable()); ItemStack pattern = new ItemStack(this.encodedPattern); pattern.setTagCompound(itemTag); return pattern; } @Override public boolean onActivate(EntityPlayer player, Vec3 pos) { if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { return super.onActivate(player, pos); } return false; } @Override public void provideCrafting(ICraftingProviderHelper craftingTracker) { this.patternHandlers = new ArrayList<ICraftingPatternDetails>(); this.patternConvert.clear(); for (ItemStack currentPatternStack : this.inventory.inv) { if (currentPatternStack != null && currentPatternStack.getItem() != null && currentPatternStack.getItem() instanceof ICraftingPatternItem) { ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack .getItem(); if (currentPattern != null && currentPattern.getPatternForItem( currentPatternStack, getGridNode().getWorld()) != null) { IFluidCraftingPatternDetails pattern = new CraftingPattern2( currentPattern.getPatternForItem( currentPatternStack, getGridNode() .getWorld())); this.patternHandlers.add(pattern); ItemStack is = makeCraftingPatternItem(pattern); if (is == null) continue; ICraftingPatternDetails p = ((ICraftingPatternItem) is .getItem()).getPatternForItem(is, getGridNode() .getWorld()); this.patternConvert.put(p, pattern); craftingTracker.addCraftingOption(this, p); } } } } private void pushItems() { for (IAEStack s : this.removeFromExport) { this.export.remove(s); } this.removeFromExport.clear(); for (IAEStack s : this.addToExport) { this.export.add(s); } this.addToExport.clear(); if (getGridNode().getWorld() == null || this.export.isEmpty()) return; ForgeDirection dir = getSide(); TileEntity tile = getGridNode().getWorld().getTileEntity( getGridNode().getGridBlock().getLocation().x + dir.offsetX, getGridNode().getGridBlock().getLocation().y + dir.offsetY, getGridNode().getGridBlock().getLocation().z + dir.offsetZ); if (tile != null) { IAEStack stack0 = this.export.iterator().next(); IAEStack stack = stack0.copy(); if (stack instanceof IAEItemStack && tile instanceof IInventory) { if (tile instanceof ISidedInventory) { ISidedInventory inv = (ISidedInventory) tile; for (int i : inv.getAccessibleSlotsFromSide(dir .getOpposite().ordinal())) { if (inv.canInsertItem(i, ((IAEItemStack) stack) .getItemStack(), dir.getOpposite().ordinal())) { if (inv.getStackInSlot(i) == null) { inv.setInventorySlotContents(i, ((IAEItemStack) stack).getItemStack()); this.removeFromExport.add(stack0); return; } else if (ItemUtils.areItemEqualsIgnoreStackSize( inv.getStackInSlot(i), ((IAEItemStack) stack).getItemStack())) { int max = inv.getInventoryStackLimit(); int current = inv.getStackInSlot(i).stackSize; int outStack = (int) stack.getStackSize(); if (max == current) continue; if (current + outStack <= max) { ItemStack s = inv.getStackInSlot(i).copy(); s.stackSize = s.stackSize + outStack; inv.setInventorySlotContents(i, s); this.removeFromExport.add(stack0); return; } else { ItemStack s = inv.getStackInSlot(i).copy(); s.stackSize = max; inv.setInventorySlotContents(i, s); this.removeFromExport.add(stack0); stack.setStackSize(outStack - max + current); this.addToExport.add(stack); return; } } } } } else { IInventory inv = (IInventory) tile; for (int i = 0; i < inv.getSizeInventory(); i++) { if (inv.isItemValidForSlot(i, ((IAEItemStack) stack).getItemStack())) { if (inv.getStackInSlot(i) == null) { inv.setInventorySlotContents(i, ((IAEItemStack) stack).getItemStack()); this.removeFromExport.add(stack0); return; } else if (ItemUtils.areItemEqualsIgnoreStackSize( inv.getStackInSlot(i), ((IAEItemStack) stack).getItemStack())) { int max = inv.getInventoryStackLimit(); int current = inv.getStackInSlot(i).stackSize; int outStack = (int) stack.getStackSize(); if (max == current) continue; if (current + outStack <= max) { ItemStack s = inv.getStackInSlot(i).copy(); s.stackSize = s.stackSize + outStack; inv.setInventorySlotContents(i, s); this.removeFromExport.add(stack0); return; } else { ItemStack s = inv.getStackInSlot(i).copy(); s.stackSize = max; inv.setInventorySlotContents(i, s); this.removeFromExport.add(stack0); stack.setStackSize(outStack - max + current); this.addToExport.add(stack); return; } } } } } } else if (stack instanceof IAEFluidStack && tile instanceof IFluidHandler) { IFluidHandler handler = (IFluidHandler) tile; IAEFluidStack fluid = (IAEFluidStack) stack; if (handler.canFill(dir.getOpposite(), fluid.copy().getFluid())) { int amount = handler.fill(dir.getOpposite(), fluid .getFluidStack().copy(), false); if (amount == 0) return; if (amount == fluid.getStackSize()) { handler.fill(dir.getOpposite(), fluid.getFluidStack() .copy(), true); this.removeFromExport.add(stack0); } else { IAEFluidStack f = fluid.copy(); f.setStackSize(f.getStackSize() - amount); FluidStack fl = fluid.getFluidStack().copy(); fl.amount = amount; handler.fill(dir.getOpposite(), fl, true); this.removeFromExport.add(stack0); this.addToExport.add(f); return; } } } } } @Override public boolean pushPattern(ICraftingPatternDetails patDetails, InventoryCrafting table) { if (isBusy() || !this.patternConvert.containsKey(patDetails)) return false; ICraftingPatternDetails patternDetails = this.patternConvert .get(patDetails); if (patternDetails instanceof CraftingPattern) { CraftingPattern patter = (CraftingPattern) patternDetails; HashMap<Fluid, Long> fluids = new HashMap<Fluid, Long>(); for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { if (fluids.containsKey(stack.getFluid())) { Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); fluids.remove(stack.getFluid()); fluids.put(stack.getFluid(), amount); } else { fluids.put(stack.getFluid(), stack.getStackSize()); } } IGrid grid = getGridNode().getGrid(); if (grid == null) return false; IStorageGrid storage = grid.getCache(IStorageGrid.class); if (storage == null) return false; for (Fluid fluid : fluids.keySet()) { Long amount = fluids.get(fluid); IAEFluidStack extractFluid = storage.getFluidInventory() .extractItems( AEApi.instance() .storage() .createFluidStack( new FluidStack(fluid, (int) (amount + 0))), Actionable.SIMULATE, new MachineSource(this)); if (extractFluid == null || extractFluid.getStackSize() != amount) { return false; } } for (Fluid fluid : fluids.keySet()) { Long amount = fluids.get(fluid); IAEFluidStack extractFluid = storage.getFluidInventory() .extractItems( AEApi.instance() .storage() .createFluidStack( new FluidStack(fluid, (int) (amount + 0))), Actionable.MODULATE, new MachineSource(this)); this.export.add(extractFluid); } for (IAEItemStack s : patter.getCondensedInputs()) { if (s == null) continue; if (s.getItem() == ItemEnum.FLUIDPATTERN.getItem()) { this.toExport = s.copy(); continue; } this.export.add(s); } } return true; } public void readFilter(NBTTagCompound tag) { if (tag.hasKey("filter")) this.fluidFilter = tag.getInteger("filter"); } @Override public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); if (data.hasKey("tank")) this.tank.readFromNBT(data.getCompoundTag("tank")); if (data.hasKey("filter")) this.fluidFilter = data.getInteger("filter"); if (data.hasKey("inventory")) this.inventory.readFromNBT(data.getCompoundTag("inventory")); if (data.hasKey("export")) readOutputFromNBT(data.getCompoundTag("export")); } @Override public boolean readFromStream(ByteBuf data) throws IOException { super.readFromStream(data); NBTTagCompound tag = ByteBufUtils.readTag(data); if (tag.hasKey("tank")) this.tank.readFromNBT(tag.getCompoundTag("tank")); if (tag.hasKey("filter")) this.fluidFilter = tag.getInteger("filter"); if (tag.hasKey("inventory")) this.inventory.readFromNBT(tag.getCompoundTag("inventory")); return true; } private void readOutputFromNBT(NBTTagCompound tag) { this.addToExport.clear(); this.removeFromExport.clear(); this.export.clear(); int i = tag.getInteger("remove"); for (int j = 0; j < i; j++) { if (tag.getBoolean("remove-" + j + "-isItem")) { IAEItemStack s = AEApi .instance() .storage() .createItemStack( ItemStack.loadItemStackFromNBT(tag .getCompoundTag("remove-" + j))); s.setStackSize(tag.getLong("remove-" + j + "-amount")); this.removeFromExport.add(s); } else { IAEFluidStack s = AEApi .instance() .storage() .createFluidStack( FluidStack.loadFluidStackFromNBT(tag .getCompoundTag("remove-" + j))); s.setStackSize(tag.getLong("remove-" + j + "-amount")); this.removeFromExport.add(s); } } i = tag.getInteger("add"); for (int j = 0; j < i; j++) { if (tag.getBoolean("add-" + j + "-isItem")) { IAEItemStack s = AEApi .instance() .storage() .createItemStack( ItemStack.loadItemStackFromNBT(tag .getCompoundTag("add-" + j))); s.setStackSize(tag.getLong("add-" + j + "-amount")); this.addToExport.add(s); } else { IAEFluidStack s = AEApi .instance() .storage() .createFluidStack( FluidStack.loadFluidStackFromNBT(tag .getCompoundTag("add-" + j))); s.setStackSize(tag.getLong("add-" + j + "-amount")); this.addToExport.add(s); } } i = tag.getInteger("export"); for (int j = 0; j < i; j++) { if (tag.getBoolean("export-" + j + "-isItem")) { IAEItemStack s = AEApi .instance() .storage() .createItemStack( ItemStack.loadItemStackFromNBT(tag .getCompoundTag("export-" + j))); s.setStackSize(tag.getLong("export-" + j + "-amount")); this.export.add(s); } else { IAEFluidStack s = AEApi .instance() .storage() .createFluidStack( FluidStack.loadFluidStackFromNBT(tag .getCompoundTag("export-" + j))); s.setStackSize(tag.getLong("export-" + j + "-amount")); this.export.add(s); } } } public void registerListener(IContainerListener listener) { this.listeners.add(listener); } public void removeListener(IContainerListener listener) { this.listeners.remove(listener); } @SideOnly(Side.CLIENT) @Override public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { Tessellator ts = Tessellator.instance; IIcon side = TextureManager.BUS_SIDE.getTexture(); rh.setTexture(side, side, side, TextureManager.INTERFACE.getTextures()[0], side, side); rh.setBounds(2, 2, 14, 14, 14, 16); rh.renderInventoryBox(renderer); rh.renderInventoryFace(TextureManager.INTERFACE.getTextures()[0], ForgeDirection.SOUTH, renderer); rh.setTexture(side); rh.setBounds(5, 5, 12, 11, 11, 14); rh.renderInventoryBox(renderer); } @SideOnly(Side.CLIENT) @Override public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { Tessellator ts = Tessellator.instance; IIcon side = TextureManager.BUS_SIDE.getTexture(); rh.setTexture(side, side, side, TextureManager.INTERFACE.getTextures()[0], side, side); rh.setBounds(2, 2, 14, 14, 14, 16); rh.renderBlock(x, y, z, renderer); ts.setBrightness(20971520); rh.renderFace(x, y, z, TextureManager.INTERFACE.getTextures()[0], ForgeDirection.SOUTH, renderer); rh.setTexture(side); rh.setBounds(5, 5, 12, 11, 11, 14); rh.renderBlock(x, y, z, renderer); } @Override public void setFilter(ForgeDirection side, Fluid fluid) { if (fluid == null) { this.fluidFilter = -1; this.doNextUpdate = true; return; } this.fluidFilter = fluid.getID(); this.doNextUpdate = true; } @Override public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { setFilter(ForgeDirection.getOrientation(_index), _fluid); } @Override public void setFluidTank(ForgeDirection side, FluidStack fluid) { this.tank.setFluid(fluid); this.doNextUpdate = true; } @Override public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { if (this.doNextUpdate) forceUpdate(); IGrid grid = node.getGrid(); if (grid == null) return TickRateModulation.URGENT; IStorageGrid storage = grid.getCache(IStorageGrid.class); if (storage == null) return TickRateModulation.URGENT; pushItems(); if (this.toExport != null) { storage.getItemInventory().injectItems(this.toExport, Actionable.MODULATE, new MachineSource(this)); this.toExport = null; } if (this.update) { this.update = false; if (getGridNode() != null && getGridNode().getGrid() != null) { getGridNode().getGrid() .postEvent( new MENetworkCraftingPatternChange(this, getGridNode())); } } if (this.tank.getFluid() != null && FluidRegistry.getFluid(this.fluidFilter) != this.tank .getFluid().getFluid()) { FluidStack s = this.tank.drain(125, false); if (s != null) { IAEFluidStack notAdded = storage.getFluidInventory() .injectItems( AEApi.instance().storage() .createFluidStack(s.copy()), Actionable.SIMULATE, new MachineSource(this)); if (notAdded != null) { int toAdd = (int) (s.amount - notAdded.getStackSize()); storage.getFluidInventory().injectItems( AEApi.instance() .storage() .createFluidStack( this.tank.drain(toAdd, true)), Actionable.MODULATE, new MachineSource(this)); this.doNextUpdate = true; this.needBreake = false; } else { storage.getFluidInventory().injectItems( AEApi.instance() .storage() .createFluidStack( this.tank.drain(s.amount, true)), Actionable.MODULATE, new MachineSource(this)); this.doNextUpdate = true; this.needBreake = false; } } } if ((this.tank.getFluid() == null || this.tank.getFluid().getFluid() == FluidRegistry .getFluid(this.fluidFilter)) && FluidRegistry.getFluid(this.fluidFilter) != null) { IAEFluidStack extracted = storage.getFluidInventory().extractItems( AEApi.instance() .storage() .createFluidStack( new FluidStack(FluidRegistry .getFluid(this.fluidFilter), 125)), Actionable.SIMULATE, new MachineSource(this)); if (extracted == null) return TickRateModulation.URGENT; int accepted = this.tank.fill(extracted.getFluidStack(), false); if (accepted == 0) return TickRateModulation.URGENT; this.tank .fill(storage .getFluidInventory() .extractItems( AEApi.instance() .storage() .createFluidStack( new FluidStack( FluidRegistry .getFluid(this.fluidFilter), accepted)), Actionable.MODULATE, new MachineSource(this)).getFluidStack(), true); this.doNextUpdate = true; this.needBreake = false; } return TickRateModulation.URGENT; } public NBTTagCompound writeFilter(NBTTagCompound tag) { if (FluidRegistry.getFluid(this.fluidFilter) == null) return null; tag.setInteger("filter", this.fluidFilter); return tag; } private NBTTagCompound writeOutputToNBT(NBTTagCompound tag) { int i = 0; for (IAEStack s : this.removeFromExport) { if (s != null) { tag.setBoolean("remove-" + i + "-isItem", s.isItem()); NBTTagCompound data = new NBTTagCompound(); if (s.isItem()) { ((IAEItemStack) s).getItemStack().writeToNBT(data); } else { ((IAEFluidStack) s).getFluidStack().writeToNBT(data); } tag.setTag("remove-" + i, data); tag.setLong("remove-" + i + "-amount", s.getStackSize()); } i++; } tag.setInteger("remove", this.removeFromExport.size()); i = 0; for (IAEStack s : this.addToExport) { if (s != null) { tag.setBoolean("add-" + i + "-isItem", s.isItem()); NBTTagCompound data = new NBTTagCompound(); if (s.isItem()) { ((IAEItemStack) s).getItemStack().writeToNBT(data); } else { ((IAEFluidStack) s).getFluidStack().writeToNBT(data); }; tag.setTag("add-" + i, data); tag.setLong("add-" + i + "-amount", s.getStackSize()); } i++; } tag.setInteger("add", this.addToExport.size()); i = 0; for (IAEStack s : this.export) { if (s != null) { tag.setBoolean("export-" + i + "-isItem", s.isItem()); NBTTagCompound data = new NBTTagCompound(); if (s.isItem()) { ((IAEItemStack) s).getItemStack().writeToNBT(data); } else { ((IAEFluidStack) s).getFluidStack().writeToNBT(data); } tag.setTag("export-" + i, data); tag.setLong("export-" + i + "-amount", s.getStackSize()); } i++; } tag.setInteger("export", this.export.size()); return tag; } @Override public void writeToNBT(NBTTagCompound data) { writeToNBTWithoutExport(data); NBTTagCompound tag = new NBTTagCompound(); writeOutputToNBT(tag); data.setTag("export", tag); } public void writeToNBTWithoutExport(NBTTagCompound data) { super.writeToNBT(data); data.setTag("tank", this.tank.writeToNBT(new NBTTagCompound())); data.setInteger("filter", this.fluidFilter); NBTTagCompound inventory = new NBTTagCompound(); this.inventory.writeToNBT(inventory); data.setTag("inventory", inventory); } @Override public void writeToStream(ByteBuf data) throws IOException { super.writeToStream(data); NBTTagCompound tag = new NBTTagCompound(); tag.setTag("tank", this.tank.writeToNBT(new NBTTagCompound())); tag.setInteger("filter", this.fluidFilter); NBTTagCompound inventory = new NBTTagCompound(); this.inventory.writeToNBT(inventory); tag.setTag("inventory", inventory); ByteBufUtils.writeTag(data, tag); } }
mit
kercos/TreeGrammars
TreeGrammars/src/tdg/reranking/Reranker_EisnerA.java
10161
package tdg.reranking; import java.io.*; import java.util.*; import pos.WsjPos; import settings.Parameters; import tdg.TDNode; import tdg.corpora.DepCorpus; import tdg.corpora.WsjD; import util.*; import util.file.FileUtil; public class Reranker_EisnerA extends Reranker_ProbModel{ private static boolean printTables = false; int SLP_type_parent, SLP_type_daughter; //0: same postag //1: same lex //2: same lexpostag //3: mix public Reranker_EisnerA(File goldFile, File parsedFile, int nBest, ArrayList<TDNode> trainingCorpus, int uk_limit, int SLP_type_parent, int SLP_type_daughter, int limitTestToFirst, boolean addEOS, boolean countEmptyDaughters, boolean markTerminalNodes, boolean LR) { super(goldFile, parsedFile, nBest, trainingCorpus, uk_limit, limitTestToFirst, addEOS, countEmptyDaughters, markTerminalNodes, printTables, LR); this.SLP_type_parent = SLP_type_parent; this.SLP_type_daughter = SLP_type_daughter; updateCondFreqTables(); } /** * Recursively increase the frequency of the current node and L/R children in the table, * with presence and absence of links. For each node the rules to be stored are: * * - head + left + ld1 | head + left + nl1 * head + left + nl2 * ... * head + left + nl_last * - head + left + ld2 * - ... * - head + left + ld_last * * - head + right + rd1 | head + right + nr1 * head + right + nr2 * ... * head + right + nr_last * - head + right + rd2 * - ... * - head + right + rd_last * * * * @param fragmentSet * @param SLP_type */ public void updateCondFreqTables(TDNode t) { TDNode[] structure = t.getStructureArray(); for(TDNode thisNode : structure) { String headTag = thisNode.lexPosTag(SLP_type_parent) + "_"; String dir = left; for(TDNode otherNode : structure) { if (otherNode==thisNode) { dir = right; continue; } String condKey = headTag + dir + otherNode.lexPosTag(SLP_type_daughter); Utility.increaseInTableInteger(condFreqTable, condKey, 1); } if (thisNode.leftDaughters!=null) { for(TDNode ld : thisNode.leftDaughters) { String key = headTag + left + ld.lexPosTag(SLP_type_daughter); Utility.increaseInTableInteger(freqTable, key, 1); } } if (thisNode.rightDaughters!=null) { for(TDNode rd : thisNode.rightDaughters) { String key = headTag + right + rd.lexPosTag(SLP_type_daughter); Utility.increaseInTableInteger(freqTable, key, 1); } } } } public double getProb(TDNode thisNode) { String headTag = thisNode.lexPosTag(SLP_type_parent) + "_"; double prob = 1f; if (thisNode.leftDaughters!=null) { for(TDNode ld : thisNode.leftDaughters) { String key = headTag + left + ld.lexPosTag(SLP_type_daughter); prob *= Utility.getCondProb(freqTable, condFreqTable, key, key) * getProb(ld); } } if (thisNode.rightDaughters!=null) { for(TDNode rd : thisNode.rightDaughters) { String key = headTag + right + rd.lexPosTag(SLP_type_daughter); prob *= Utility.getCondProb(freqTable, condFreqTable, key, key) * getProb(rd); } } return prob; } public void updateKeyCondKeyLog(TDNode thisNode, Vector<String> keyCondKeyLog) { String headTag = thisNode.lexPosTag(SLP_type_parent) + "_"; if (thisNode.leftDaughters!=null) { for(TDNode ld : thisNode.leftDaughters) { String key = headTag + left + ld.lexPosTag(SLP_type_daughter); keyCondKeyLog.add(key); updateKeyCondKeyLog(ld, keyCondKeyLog); } } if (thisNode.rightDaughters!=null) { for(TDNode rd : thisNode.rightDaughters) { String key = headTag + right + rd.lexPosTag(SLP_type_daughter); keyCondKeyLog.add(key); updateKeyCondKeyLog(rd, keyCondKeyLog); } } } /* * Toy Sentence */ public static void main1(String[] args) { int uk_limit = -1; int LL_tr = 40; int LL_ts = 40; int nBest = 10; int limitTestSetToFirst = 10000; String toySentence = Parameters.corpusPath + "ToyGrammar/toySentence"; Parameters.outputPath = Parameters.resultsPath + "Reranker/" + FileUtil.dateTimeString() + "/"; File outputPathFile = new File(Parameters.outputPath); outputPathFile.mkdirs(); Parameters.logFile = new File(Parameters.outputPath + "Log"); File trainingFile = new File (toySentence); File testFile = new File (toySentence); ArrayList<TDNode> training = DepCorpus.readTreebankFromFileMST(trainingFile, LL_tr, false, true); ArrayList<TDNode> test = DepCorpus.readTreebankFromFileMST(testFile, LL_ts, false, true); File outputTestGold = new File(Parameters.outputPath + "toySentence.ulab"); DepCorpus.toFileMSTulab(outputTestGold, test, false); File parsedFile = new File(toySentence); boolean addEOS = true; boolean countEmptyDaughters = false; boolean markTerminalNodes = false; boolean LR = true; int SLP_type_parent = 0; int SLP_type_daughter = 0; //0: same postag //1: same lex //2: same lexpostag //3: mix String parameters = "RerankerLR1LProb" + "\n" + "LL_tr\t" + LL_tr + "\n" + "LL_ts\t" + LL_ts + "\n" + "UK_limit\t" + uk_limit + "\n" + "Asdd EOS\t" + addEOS + "\n" + "nBest\t" + nBest + "\n" + "Training File\t" + trainingFile + "\n" + "Test File\t" + testFile + "\n" + "Parsed File\t" + parsedFile + "\n" + "Training Size\t" + training.size() + "\n" + "Test Size\t" + test.size() + "\n" + "SLP_type_parent\t" + SLP_type_parent + "\n" + "SLP_type_daughter\t" + SLP_type_daughter + "\n" + "Use LR direction\t" + LR + "\n"; FileUtil.appendReturn(parameters, Parameters.logFile); System.out.println(parameters); FileUtil.appendReturn(parameters, Parameters.logFile); System.out.println(parameters); new Reranker_EisnerA(outputTestGold, parsedFile, nBest, training, uk_limit, SLP_type_parent, SLP_type_daughter, limitTestSetToFirst, addEOS, countEmptyDaughters, markTerminalNodes, LR).runToyGrammar(); } public static void mainWsj(int section, int nBest) { TDNode.posAnalyzer = new WsjPos(); int uk_limit = -1; int LL_tr = 40; int LL_ts = 40; boolean till11_21 = false; boolean mxPos = false; int limitTestSetToFirst = 10000; boolean includeGoldInNBest = false; int order = 2; String MSTver = "0.5"; int depType = 2; //"MST", "COLLINS97", "COLLINS99", "COLLINS99Arg", "COLLINS99Ter", "COLLINS99ArgTer" String withGold = includeGoldInNBest ? "_withGold" : ""; String baseDepDir = depTypeBase[depType]; String corpusName = wsjDepTypeName[depType] + "_sec" + section; String parsedFileBase = Parameters.resultsPath + "Reranker/Parsed/" + "MST_" + MSTver + "_" + order + "order/" + ((mxPos) ? "mxPOS/" : "goldPOS/") + corpusName + "/" + corpusName + "_nBest" + nBest + "/"; Parameters.outputPath = parsedFileBase + "Reranker_EisnerA/" + //"Reranker/" + FileUtil.dateTimeString() + "/"; File outputPathFile = new File(Parameters.outputPath); outputPathFile.mkdirs(); Parameters.logFile = new File(Parameters.outputPath + "Log"); String trSec = till11_21 ? "02-11" : "02-21"; File trainingFile = new File (baseDepDir + "wsj-" + trSec + ".ulab"); File testFile = new File (baseDepDir + "wsj-" + section + ((mxPos) ? ".mxpost" : "") + ".ulab"); ArrayList<TDNode> training = DepCorpus.readTreebankFromFileMST(trainingFile, LL_tr, false, true); ArrayList<TDNode> test = DepCorpus.readTreebankFromFileMST(testFile, LL_ts, false, true); //training = new ArrayList<TDNode> (training.subList(0, 100)); File outputTestGold = new File(Parameters.outputPath + wsjDepTypeName[depType] + "." + section + ".gold.ulab"); //File outputTtraining = new File(Parameters.outputPath + depTypeName[depType] + trSec + ".ulab"); DepCorpus.toFileMSTulab(outputTestGold, test, false); //DepCorpus.toFileMSTulab(outputTtraining, training, false); File parsedFile = new File(parsedFileBase + "tr" + trSec + "_LLtr" + LL_tr + "_LLts" + LL_ts + "_nBest" + nBest + withGold); //tr02-11_LLtr10_LLts10_nBest100.ulab if(!parsedFile.exists()) { System.out.println("NBest file not found: " + parsedFile); makeNBestWsj(LL_tr, LL_ts, nBest, till11_21, depType, mxPos, order, MSTver); } boolean addEOS = true; boolean countEmptyDaughters = false; boolean markTerminalNodes = false; boolean LR = true; int SLP_type_parent = 0; int SLP_type_daughter = 0; //0: same postag //1: same lex //2: same lexpostag //3: mix String parameters = "Eisner A" + "\n" + "LL_tr\t" + LL_tr + "\n" + "LL_ts\t" + LL_ts + "\n" + "UK_limit\t" + uk_limit + "\n" + "Asdd EOS\t" + addEOS + "\n" + "nBest\t" + nBest + "\n" + "Training File\t" + trainingFile + "\n" + "Test File\t" + testFile + "\n" + "Parsed File\t" + parsedFile + "\n" + "Training Size\t" + training.size() + "\n" + "Test Size\t" + test.size() + "\n" + "SLP_type_parent\t" + SLP_type_parent + "\n" + "SLP_type_daughter\t" + SLP_type_daughter + "\n" + "Use LR direction\t" + LR + "\n"; FileUtil.appendReturn(parameters, Parameters.logFile); System.out.println(parameters); new Reranker_EisnerA(outputTestGold, parsedFile, nBest, training, uk_limit, SLP_type_parent, SLP_type_daughter, limitTestSetToFirst, addEOS, countEmptyDaughters, markTerminalNodes, LR).reranking(); File rerankedFileConll = new File(Parameters.outputPath+ "reranked.ulab"); selectRerankedFromFileUlab(parsedFile, rerankedFileConll, Reranker.rerankedIndexes); } @Override public Number getScore(TDNode t) { // TODO Auto-generated method stub return null; } @Override public int compareTo(Number a, Number b) { // TODO Auto-generated method stub return 0; } public static void main(String args[]) { int[] kBest = new int[]{2,3,4,5,6,7,8,9,10,100,1000}; //,15,20,25,50,150,200,250,500,750}; for(int k : kBest) { mainWsj(22, k); } } }
mit
savageboy74/SavageCore
src/main/java/tv/savageboy74/savagecore/common/SavageCore.java
4885
package tv.savageboy74.savagecore.common; /* * SavageCore.java * Copyright (C) 2014 - 2015 Savage - github.com/savageboy74 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; import tv.savageboy74.savagecore.common.config.ConfigHandler; import tv.savageboy74.savagecore.common.core.command.CommandHandler; import tv.savageboy74.savagecore.common.proxy.CommonProxy; import tv.savageboy74.savagecore.common.util.LogHelper; import tv.savageboy74.savagecore.common.util.SavageCoreProps; import tv.savageboy74.savagecore.common.util.UpdateChecker; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.common.MinecraftForge; import java.io.IOException; @Mod(modid = SavageCoreProps.MOD_ID, version = SavageCoreProps.VERSION, guiFactory = SavageCoreProps.GUI_FACTORY_CLASS, dependencies = SavageCoreProps.DEPENDENCIES) public class SavageCore { @Mod.Instance(SavageCoreProps.MOD_ID) public static SavageCore instance; @SidedProxy(clientSide = SavageCoreProps.CLIENT_PROXY, serverSide = SavageCoreProps.SERVER_PROXY) public static CommonProxy proxy; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { ConfigHandler.init(event.getSuggestedConfigurationFile()); MinecraftForge.EVENT_BUS.register(new ConfigHandler()); MinecraftForge.EVENT_BUS.register(this); if (ConfigHandler.checkForUpdates) { try { LogHelper.info(SavageCoreProps.MOD_NAME, "Checking For Updates..."); UpdateChecker.checkForUpdates(); } catch (IOException e) { e.printStackTrace(); } } LogHelper.info(SavageCoreProps.MOD_NAME, "Pre-Initialization Complete."); } @Mod.EventHandler public void init(FMLInitializationEvent event) { LogHelper.info(SavageCoreProps.MOD_NAME, "Initialization Complete."); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { LogHelper.info(SavageCoreProps.MOD_NAME, "Post-Initialization Complete."); } @Mod.EventHandler public void serverStarting(FMLServerStartingEvent event) { CommandHandler.initCommands(event); } @SubscribeEvent public void checkUpdate(PlayerEvent.PlayerLoggedInEvent event) { if (ConfigHandler.checkForUpdates) { if (SavageCoreProps.OUTDATED) { EnumChatFormatting darkRed = EnumChatFormatting.DARK_RED; EnumChatFormatting aqua = EnumChatFormatting.AQUA; EnumChatFormatting darkGreen = EnumChatFormatting.DARK_GREEN; EnumChatFormatting reset = EnumChatFormatting.RESET; EnumChatFormatting green = EnumChatFormatting.GREEN; String name = SavageCoreProps.MOD_NAME; String outdatedText = aqua + "[" + name + "] " + reset + "This version of " + green + name + reset + " is" + darkRed + " outdated!"; String versionText = "Current Version: " + darkRed + SavageCoreProps.VERSION + reset + " Newest Version: " + darkGreen + SavageCoreProps.NEWVERSION; event.player.addChatComponentMessage(new ChatComponentText(outdatedText)); event.player.addChatComponentMessage(new ChatComponentText(versionText)); } } } }
mit
DeveloperTommy/CodeU
Technical_Exercises/Session3/Tommy/Query.java
883
import java.sql.*; import java.util.Iterator; import java.util.LinkedList; public class Query implements Iterable<String> { //It seems like we will need to create an iterator for Query as well to get its next. Timestamp stamp; String list; int numWords; public Query() { list = ""; numWords = 0; } public void add(String input) { //Does not seem like we can use string builder. list += (" " + input); numWords++; } public Iterator<String> iterator() { return new MyIterator(); } private class MyIterator implements Iterator<String> { int current = 0; String[] words = list.split("\\s+"); public boolean hasNext() { return current <= numWords; } public String next() { current++; return words[current-1]; } public void remove() { throw new UnsupportedOperationException("Not implemented"); } } }
mit
Stooshy/MyWind
SOWindWizard/src/application/gui/SettingsDlg.java
1816
package application.gui; import application.model.UserData; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.KeyCode; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; public class SettingsDlg { public SettingsDlg(Stage primaryStage, UserData data) { Stage dialog = new Stage(StageStyle.TRANSPARENT); dialog.initModality(Modality.WINDOW_MODAL); dialog.initOwner(primaryStage); HBox hb = new HBox(); Label lb = new Label(); String text = "Windfactor:"; DoubleInputControl dic = new DoubleInputControl(); dic.setValue(data.getUserFactor()); lb.setText(text); lb.setId("textnormal"); hb.setId("modal-dialog"); Button bt = new Button("X"); bt.setOnKeyReleased(event -> { if (event.getCode().equals(KeyCode.ESCAPE) || (event.getCode().equals(KeyCode.F1))) { data.setUserFactor(dic.getValue()); primaryStage.getScene().getRoot().setEffect(null); dialog.close(); } }); bt.setOnMouseClicked(event -> { data.setUserFactor(dic.getValue()); primaryStage.getScene().getRoot().setEffect(null); dialog.close(); }); hb.getChildren().add(lb); hb.setAlignment(Pos.CENTER); hb.getChildren().add(dic); hb.setAlignment(Pos.CENTER); hb.getChildren().add(bt); lb.requestFocus(); dialog.setScene(new Scene(hb, Color.TRANSPARENT)); dialog.getScene().getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm()); dialog.setX(primaryStage.getX()); dialog.setY(primaryStage.getY()); dialog.setWidth(200); dialog.setHeight(200); dialog.show(); } }
mit
jakobehmsen/duro
eclipse/src/duro/runtime/LazyCloneProcess.java
1335
package duro.runtime; import java.util.List; import duro.runtime.InteractionHistory.Interaction; public class LazyCloneProcess extends Process { /** * */ private static final long serialVersionUID = 1L; private LocalizableProcess protoOrInstance; public LazyCloneProcess(LocalizableProcess protoOrInstance) { this.protoOrInstance = protoOrInstance; } @Override public void resume(List<Interaction> playedInstructions) { // TODO Auto-generated method stub } @Override public Object getCallable(Processor processor, int selectorCode, int arity) { return protoOrInstance.getCallable(processor, selectorCode, arity); } @Override public Process lookup(int selectorCode) { return protoOrInstance.lookup(selectorCode); } @Override public boolean isDefined(int code) { return protoOrInstance.isDefined(code); } @Override public String[] getNames() { return protoOrInstance.getNames(); } @Override public void define(int selectorCode, Process value) { protoOrInstance = protoOrInstance.getAsLocal(); protoOrInstance.define(selectorCode, value); } @Override public void defineProto(int selectorCode, Process value) { protoOrInstance = protoOrInstance.getAsLocal(); protoOrInstance.define(selectorCode, value); } @Override public Process getEnvironment() { return this; } }
mit
hovsepm/azure-sdk-for-java
mediaservices/resource-manager/v2018_30_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_30_30_preview/implementation/OperationsInner.java
14055
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2018_30_30_preview.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.management.mediaservices.v2018_30_30_preview.ApiErrorException; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in Operations. */ public class OperationsInner { /** The Retrofit service to perform REST calls. */ private OperationsService service; /** The service client containing this operation class. */ private AzureMediaServicesImpl client; /** * Initializes an instance of OperationsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public OperationsInner(Retrofit retrofit, AzureMediaServicesImpl client) { this.service = retrofit.create(OperationsService.class); this.client = client; } /** * The interface defining all the services for Operations to be * used by Retrofit to perform actually REST calls. */ interface OperationsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.Operations list" }) @GET("providers/Microsoft.Media/operations") Observable<Response<ResponseBody>> list(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.Operations listNext" }) @GET Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * List Operations. * Lists all the Media Services operations. * * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ApiErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;OperationInner&gt; object if successful. */ public PagedList<OperationInner> list() { ServiceResponse<Page<OperationInner>> response = listSinglePageAsync().toBlocking().single(); return new PagedList<OperationInner>(response.body()) { @Override public Page<OperationInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * List Operations. * Lists all the Media Services operations. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<OperationInner>> listAsync(final ListOperationCallback<OperationInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(), new Func1<String, Observable<ServiceResponse<Page<OperationInner>>>>() { @Override public Observable<ServiceResponse<Page<OperationInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * List Operations. * Lists all the Media Services operations. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;OperationInner&gt; object */ public Observable<Page<OperationInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<OperationInner>>, Page<OperationInner>>() { @Override public Page<OperationInner> call(ServiceResponse<Page<OperationInner>> response) { return response.body(); } }); } /** * List Operations. * Lists all the Media Services operations. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;OperationInner&gt; object */ public Observable<ServiceResponse<Page<OperationInner>>> listWithServiceResponseAsync() { return listSinglePageAsync() .concatMap(new Func1<ServiceResponse<Page<OperationInner>>, Observable<ServiceResponse<Page<OperationInner>>>>() { @Override public Observable<ServiceResponse<Page<OperationInner>>> call(ServiceResponse<Page<OperationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * List Operations. * Lists all the Media Services operations. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;OperationInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<OperationInner>>> listSinglePageAsync() { if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.list(this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<OperationInner>>>>() { @Override public Observable<ServiceResponse<Page<OperationInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<OperationInner>> result = listDelegate(response); return Observable.just(new ServiceResponse<Page<OperationInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<OperationInner>> listDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<OperationInner>, ApiErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<OperationInner>>() { }.getType()) .registerError(ApiErrorException.class) .build(response); } /** * List Operations. * Lists all the Media Services operations. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ApiErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;OperationInner&gt; object if successful. */ public PagedList<OperationInner> listNext(final String nextPageLink) { ServiceResponse<Page<OperationInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<OperationInner>(response.body()) { @Override public Page<OperationInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * List Operations. * Lists all the Media Services operations. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<OperationInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<OperationInner>> serviceFuture, final ListOperationCallback<OperationInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<OperationInner>>>>() { @Override public Observable<ServiceResponse<Page<OperationInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * List Operations. * Lists all the Media Services operations. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;OperationInner&gt; object */ public Observable<Page<OperationInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<OperationInner>>, Page<OperationInner>>() { @Override public Page<OperationInner> call(ServiceResponse<Page<OperationInner>> response) { return response.body(); } }); } /** * List Operations. * Lists all the Media Services operations. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;OperationInner&gt; object */ public Observable<ServiceResponse<Page<OperationInner>>> listNextWithServiceResponseAsync(final String nextPageLink) { return listNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<OperationInner>>, Observable<ServiceResponse<Page<OperationInner>>>>() { @Override public Observable<ServiceResponse<Page<OperationInner>>> call(ServiceResponse<Page<OperationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * List Operations. * Lists all the Media Services operations. * ServiceResponse<PageImpl<OperationInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;OperationInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<OperationInner>>> listNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<OperationInner>>>>() { @Override public Observable<ServiceResponse<Page<OperationInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<OperationInner>> result = listNextDelegate(response); return Observable.just(new ServiceResponse<Page<OperationInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<OperationInner>> listNextDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<OperationInner>, ApiErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<OperationInner>>() { }.getType()) .registerError(ApiErrorException.class) .build(response); } }
mit
comger/migrant-android
android_app/src/com/comger/migrant/AppError.java
1931
/** * AppError.java * @user comger * @mail comger@gmail.com * 2013-7-11 */ package com.comger.migrant; import java.lang.Thread.UncaughtExceptionHandler; import android.util.Log; /** * @author comger * */ public class AppError extends Throwable implements UncaughtExceptionHandler { private final static boolean Debug = false;//是否保存错误日志 private static final long serialVersionUID = 1L; private String mFailingUrl; private Exception e = null; @SuppressWarnings("rawtypes") private Class cls = null; /** 系统默认的UncaughtException处理类 */ private Thread.UncaughtExceptionHandler mDefaultHandler; /** * 简单异常信息提示 * @param message */ public AppError(String message){ super(message); this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); } /** * 请求服务失败,无法接连网络 * @param message * @param e * @param failingUrl */ public AppError(String message, Exception e, String failingUrl){ super(message); this.e = e; this.cls = e.getClass(); mFailingUrl = failingUrl; Log.i("AppError", "when open url "+failingUrl + " error is:"+ message); } /** * 请求服务出错 * @param message * @param failingUrl 接口地址 */ public AppError(String message, String failingUrl) { super(message); mFailingUrl = failingUrl; Log.i("AppError", "when open url "+failingUrl + " error is:"+ message); } @Override public void uncaughtException(Thread thread, Throwable ex) { // TODO Auto-generated method stub } public Exception getException(){ return this.e; } @SuppressWarnings("rawtypes") public Class getExceptionClass(){ return this.cls; } public String getFailingUrl(){ return mFailingUrl; } }
mit
ksbobrov/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactModificationTests.java
1253
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.generators.ContactDataGenerator; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.Contacts; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class ContactModificationTests extends TestBase { @BeforeMethod public void ensurePreconditions() { app.goTo().homePage(); if (app.db().contacts().isEmpty()) { app.contacts().create(ContactDataGenerator.getDefaultContactData()); } } @Test public void testContactModification() { Contacts before = app.db().contacts(); ContactData oldContactData = before.iterator().next(); ContactData newContactData = ContactDataGenerator.getDefaultModifiedData().withId(oldContactData.getId()); app.contacts().modify(newContactData); assertThat(app.contacts().count(), equalTo(before.size())); Contacts after = app.db().contacts(); assertThat(after, equalTo(before.without(oldContactData).withAdded(newContactData))); verifyContactListInUI(); } }
mit
CS2103JAN2017-W14-B3/main
src/test/java/guitests/ClearCommandTest.java
1053
//@@author A0146809W package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.doit.logic.commands.ClearCommand; import seedu.doit.logic.commands.DeleteCommand; public class ClearCommandTest extends TaskManagerGuiTest { @Test public void clear() { // verify a non-empty list can be cleared assertAllPanelsMatch(this.td.getTypicalTasks()); assertClearCommandSuccess(); // verify other commands can work after a clear command this.commandBox.runCommand(this.td.hoon.getAddCommand()); assertTrue(this.taskListPanel.isListMatching(this.td.hoon)); this.commandBox.runCommand(DeleteCommand.COMMAND_WORD + " 1"); assertListSize(0); // verify clear command works when the list is empty assertClearCommandSuccess(); } public void assertClearCommandSuccess() { this.commandBox.runCommand(ClearCommand.COMMAND_WORD); assertListSize(0); assertResultMessage("All tasks has been cleared!"); } }
mit
abertschi/aspectj-archive-maven-plugin
src/main/java/ch/abertschi/aspectj/Utils.java
1262
package ch.abertschi.aspectj; import java.io.File; /** * @author Andrin Bertsch * @since 2015-05 */ public class Utils { private Utils() { } public static void mkdirIfNotExists(String directory) { File buildDir = new File(directory); if (!buildDir.exists()) { buildDir.mkdir(); } } public static File getFile(File base, String suffix) { File archiveFile = new File(base, suffix); if (!archiveFile.exists()) { throw new RuntimeException("Specified deployable doesnt exist: " + base.getAbsolutePath() + " name: " + suffix); } return archiveFile; } public static String getPathWithoutFilename(String path) { int index = path.lastIndexOf("/"); if (index == 0) { return "/"; } else { return path.substring(0, index); } } public static String getFilename(String path) { String result; String[] split = path.split("/"); if (split.length > 1) { result = split[split.length - 1]; } else { result = split[0]; } return result; } }
mit
thandile/msf_communique
app/src/main/java/com/example/msf/msf/Presenters/AdverseEvents/Types/AdverserEventInteractor.java
1221
package com.example.msf.msf.Presenters.AdverseEvents.Types; import com.example.msf.msf.API.Auth; import com.example.msf.msf.API.Interface; import com.example.msf.msf.API.Models.AdverseEvent; import com.example.msf.msf.API.Models.AdverseEventType; import com.example.msf.msf.LoginActivity; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * Created by Thandile on 2016/11/04. */ public class AdverserEventInteractor implements Callback<List<AdverseEventType>> { private OnAdverseEventInteractorFinishedListener listener; public AdverserEventInteractor(OnAdverseEventInteractorFinishedListener listener) { this.listener = listener; } public void loadRecentAdverseEvents(){ Interface communicatorInterface = Auth.getInterface(LoginActivity.username, LoginActivity.password); communicatorInterface.getAdverseEventType(this); } @Override public void success(List<AdverseEventType> adverseEvents, Response response) { listener.onNetworkSuccess(adverseEvents, response); } @Override public void failure(RetrofitError error) { listener.onNetworkFailure(error); } }
mit
wknishio/variable-terminal
src/nat/net/sbbi/upnp/ServicesEventing.java
17717
/******************************************************************************* * ============================================================================ * The Apache Software License, Version 1.1 * ============================================================================ * * Copyright (C) 2002 The Apache Software Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by SuperBonBon Industries (http://www.sbbi.net/)." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "UPNPLib" and "SuperBonBon Industries" must not be * used to endorse or promote products derived from this software without * prior written permission. For written permission, please contact * info@sbbi.net. * * 5. Products derived from this software may not be called * "SuperBonBon Industries", nor may "SBBI" appear in their name, * without prior written permission of SuperBonBon Industries. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT,INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * on behalf of SuperBonBon Industries. For more information on * SuperBonBon Industries, please see <http://www.sbbi.net/>. *******************************************************************************/ package net.sbbi.upnp; import java.text.MessageFormat; import java.util.*; import java.io.*; import java.net.*; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import net.sbbi.upnp.services.UPNPService; import org.apache.commons.logging.*; import org.xml.sax.InputSource; /** * This class can be used with the ServiceEventHandler interface * to recieve notifications about state variables changes on * a given UPNP service. * @author <a href="mailto:superbonbon@sbbi.net">SuperBonBon</a> * @version 1.0 */ public class ServicesEventing implements Runnable { private final static Log log = LogFactory.getLog( ServicesEventing.class ); private final static ServicesEventing singleton = new ServicesEventing(); private boolean inService = false; private boolean daemon = true; private int daemonPort = 9999; private ServerSocket server = null; private List registered = new ArrayList(); private ServicesEventing() { } public final static ServicesEventing getInstance() { return singleton; } /** * Set the listeniner thread as a daemon, default to true. * Only works when no more objects are registered. * @param daemon the new thread type. */ public void setDaemon( boolean daemon ) { this.daemon = daemon; } /** * Sets the listener thread port, default to 9999. * Only works when no more objects are registered. * @param daemonPort the new listening port */ public void setDaemonPort( int daemonPort ) { this.daemonPort = daemonPort; } /** * Register state variable events notification for a device service * @param service the service to register with * @param handler the registrant object * @param subscriptionDuration subscription time in seconds, -1 for infinite time * @return the subscription duration returned by the device, 0 for an infinite duration or -1 if no subscription done * @throws IOException if some IOException error happens during coms with the device */ public int register( UPNPService service, ServiceEventHandler handler, int subscriptionDuration ) throws IOException { ServiceEventSubscription sub = registerEvent( service, handler, subscriptionDuration ); if ( sub != null ) { return sub.getDurationTime(); } return -1; } /** * Register state variable events notification for a device service * @param service the service to register with * @param handler the registrant object * @param subscriptionDuration subscription time in seconds, -1 for infinite time * @return an ServiceEventSubscription object instance containing all the required info or null if no subscription done * @throws IOException if some IOException error happens during coms with the device */ public ServiceEventSubscription registerEvent( UPNPService service, ServiceEventHandler handler, int subscriptionDuration ) throws IOException { URL eventingLoc = service.getEventSubURL(); if ( eventingLoc != null ) { if ( !inService ) startServicesEventingThread(); String duration = Integer.toString( subscriptionDuration ); if ( subscriptionDuration == -1 ) { duration = "infinite"; } Subscription sub = lookupSubscriber( service, handler ); if ( sub != null ) { // allready registered let's try to unregister it unRegister( service, handler ); } StringBuffer packet = new StringBuffer( 64 ); packet.append( "SUBSCRIBE " ).append( eventingLoc.getFile() ).append( " HTTP/1.1\r\n" ); packet.append( "HOST: " ).append( eventingLoc.getHost() ).append( ":" ).append( eventingLoc.getPort() ).append( "\r\n" ); packet.append( "CALLBACK: <http://" ).append( "{0}:" ).append( daemonPort ).append( "" ).append( eventingLoc.getFile() ).append( ">\r\n" ); packet.append( "NT: upnp:event\r\n" ); packet.append( "Connection: close\r\n" ); packet.append( "TIMEOUT: Second-" ).append( duration ).append( "\r\n\r\n" ); Socket skt = new Socket( eventingLoc.getHost(), eventingLoc.getPort() ); skt.setSoTimeout( 30000 ); // 30 secs timeout according to the specs MessageFormat packetFormat = new MessageFormat(packet.toString()); String message = packetFormat.format( new Object[]{skt.getLocalAddress().getHostAddress()} ); if ( log.isDebugEnabled() ) log.debug( message ); OutputStream out = skt.getOutputStream(); out.write( message.getBytes() ); out.flush(); InputStream in = skt.getInputStream(); StringBuffer data = new StringBuffer(); int readen = 0; byte[] buffer = new byte[256]; while ( ( readen = in.read( buffer ) ) != -1 ) { data.append( new String( buffer, 0, readen ) ); } in.close(); out.close(); skt.close(); if ( log.isDebugEnabled() ) log.debug( data.toString() ); if ( data.toString().trim().length() > 0 ) { HttpResponse resp = new HttpResponse( data.toString() ); if ( resp.getHeader().startsWith( "HTTP/1.1 200 OK" ) ) { String sid = resp.getHTTPHeaderField( "SID" ); String actualTimeout = resp.getHTTPHeaderField( "TIMEOUT" ); int durationTime = 0; // actualTimeout = Second-xxx or Second-infinite if ( !actualTimeout.equalsIgnoreCase( "Second-infinite" ) ) { durationTime = Integer.parseInt( actualTimeout.substring( 7 ) ); } sub = new Subscription(); sub.handler = handler; sub.sub = new ServiceEventSubscription( service.getServiceType(), service.getServiceId(), service.getEventSubURL(), sid, skt.getInetAddress(), durationTime ); synchronized( registered ) { registered.add( sub ); } return sub.sub; } } } return null; } private Subscription lookupSubscriber( UPNPService service, ServiceEventHandler handler ) { synchronized( registered ) { for ( Iterator i = registered.iterator(); i.hasNext(); ) { Subscription sub = (Subscription)i.next(); if ( sub.handler == handler && sub.sub.getServiceId().hashCode() == service.getServiceId().hashCode() && sub.sub.getServiceType().hashCode() == service.getServiceType().hashCode() && sub.sub.getServiceURL().equals( service.getEventSubURL() ) ) { return sub; } } } return null; } private Subscription lookupSubscriber( String sid, InetAddress deviceIp ) { synchronized( registered ) { for ( Iterator i = registered.iterator(); i.hasNext(); ) { Subscription sub = (Subscription)i.next(); if ( sub.sub.getSID().equals( sid ) && sub.sub.getDeviceIp().equals( deviceIp ) ) { return sub; } } } return null; } private Subscription lookupSubscriber( String sid ) { synchronized( registered ) { for ( Iterator i = registered.iterator(); i.hasNext(); ) { Subscription sub = (Subscription)i.next(); if ( sub.sub.getSID().equals( sid ) ) { return sub; } } } return null; } /** * Unregisters events notifications from a service * @param service the service that need to be unregistered * @param handler the handler that registered for this service * @return true if unregistered false otherwise ( the given handler never registred for the given service ) * @throws IOException if some IOException error happens during coms with the device */ public boolean unRegister( UPNPService service, ServiceEventHandler handler ) throws IOException { URL eventingLoc = service.getEventSubURL(); if ( eventingLoc != null ) { Subscription sub = lookupSubscriber( service, handler ); if ( sub != null ) { synchronized( registered ) { registered.remove( sub ); } if ( registered.size() == 0 ) { stopServicesEventingThread(); } StringBuffer packet = new StringBuffer( 64 ); packet.append( "UNSUBSCRIBE " ).append( eventingLoc.getFile() ).append( " HTTP/1.1\r\n" ); packet.append( "HOST: " ).append( eventingLoc.getHost() ).append( ":" ).append( eventingLoc.getPort() ).append( "\r\n" ); packet.append( "SID: " ).append( sub.sub.getSID() ).append( "\r\n\r\n" ); Socket skt = new Socket( eventingLoc.getHost(), eventingLoc.getPort() ); skt.setSoTimeout( 30000 ); // 30 secs timeout according to the specs if ( log.isDebugEnabled() ) log.debug( packet ); OutputStream out = skt.getOutputStream(); out.write( packet.toString().getBytes() ); out.flush(); InputStream in = skt.getInputStream(); StringBuffer data = new StringBuffer(); int readen = 0; byte[] buffer = new byte[256]; while ( ( readen = in.read( buffer ) ) != -1 ) { data.append( new String( buffer, 0, readen ) ); } in.close(); out.close(); skt.close(); if ( log.isDebugEnabled() ) log.debug( data.toString() ); if ( data.toString().trim().length() > 0 ) { HttpResponse resp = new HttpResponse( data.toString() ); if ( resp.getHeader().startsWith( "HTTP/1.1 200 OK" ) ) { return true; } } } } return false; } private void startServicesEventingThread() { synchronized( singleton ) { if ( !inService ) { Thread deamon = new Thread( singleton, "ServicesEventing daemon" ); deamon.setDaemon( daemon ); inService = true; deamon.start(); } } } private void stopServicesEventingThread() { synchronized( singleton ) { inService = false; try { server.close(); } catch ( IOException ex ) { // should not happen } } } public void run() { // only the deamon thread is allowed to call such method if ( !Thread.currentThread().getName().equals( "ServicesEventing daemon" ) ) { System.out.println("ABORTING THREAD LAUNCH: NAME INCORRECT"); return; } try { server = new ServerSocket( daemonPort ); } catch ( IOException ex ) { log.error( "Error during daemon server socket on port " + daemonPort + " creation", ex ); return; } while ( inService ) { try { Socket skt = server.accept(); Thread handler = new Thread( new RequestProcessor( skt ) , "RequestProcessor"); handler.start(); } catch ( Exception e ) { if ( inService ) { log.error( "IO Exception during UPNP messages listening thread", e ); e.printStackTrace(); } } } } private class Subscription { private ServiceEventSubscription sub = null; private ServiceEventHandler handler = null; } private class RequestProcessor implements Runnable { private Socket client; private RequestProcessor( Socket client ) { this.client = client; } public void run() { try { client.setSoTimeout( 30000 ); InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream(); int readen = 0; StringBuffer data = new StringBuffer(); byte[] buffer = new byte[256]; boolean EOF = false; while ( !EOF && ( readen = in.read( buffer ) ) != -1 ) { data.append( new String( buffer, 0, readen , "UTF-8") ); final String endToken = "</e:propertyset>"; String lastBytes = data.substring(data.length()-endToken.length(), data.length()); // avoid a strange behaviour with some impls.. the -1 is never reached and a sockettimeout occurs // and a 0 byte is sent as the last byte // // Also avoid a strange behavior where the final read would delay for 5 seconds even though // all data has been delivered and the other side went bye-bye. if ( data.charAt( data.length()-1 ) == (char)0 || endToken.equals(lastBytes)) { EOF = true; } } String packet = data.toString(); if ( packet.trim().length() > 0 ) { if ( packet.indexOf( (char)0 ) != -1 ) packet = packet.replace( (char)0, ' ' ); HttpResponse resp = new HttpResponse( packet ); if ( resp.getHeader().startsWith( "NOTIFY" ) ) { String sid = resp.getHTTPHeaderField( "SID" ); InetAddress deviceIp = client.getInetAddress(); String postURL = resp.getHTTPHeaderField( "SID" ); Subscription subscription = null; if ( sid != null && postURL != null ) { subscription = lookupSubscriber( sid, deviceIp ); if ( subscription == null ) { // not found maybe that the IP is not the same subscription = lookupSubscriber( sid ); } } if ( subscription != null ) { // respond ok out.write( "HTTP/1.1 200 OK\r\n".getBytes() ); } else { // unknown sid respond ko out.write( "HTTP/1.1 412 Precondition Failed\r\n".getBytes() ); } out.flush(); in.close(); out.close(); client.close(); if ( subscription != null ) { // let's parse it SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating( false ); saxParFact.setNamespaceAware( true ); SAXParser parser = saxParFact.newSAXParser(); ServiceEventMessageParser msgParser = new ServiceEventMessageParser(); StringReader stringReader = new StringReader( resp.getBody() ); InputSource src = new InputSource( stringReader ); parser.parse( src, msgParser ); Map changedStateVars = msgParser.getChangedStateVars(); for ( Iterator i = changedStateVars.keySet().iterator(); i.hasNext(); ) { String stateVarName = (String)i.next(); String stateVarNewVal = (String)changedStateVars.get( stateVarName ); subscription.handler.handleStateVariableEvent( stateVarName, stateVarNewVal ); } } } } } catch ( IOException ioEx ) { log.error( "IO Exception during client processing thread", ioEx ); } catch( Exception ex ) { log.error( "Unexpected error during client processing thread", ex ); } } } }
mit
healthGuide/android-app
app/src/main/java/rkapoors/healthguide/doctorvisit.java
649
package rkapoors.healthguide; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class doctorvisit extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_doctorvisit); setTitle("visit to doctor"); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if(actionBar!=null){ actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onSupportNavigateUp(){ finish(); return true; } }
mit
marktreble/f3f-timer
aFileChooser/src/main/java/com/ipaulpro/afilechooser/FileChooserActivity.java
6437
/* * Copyright (C) 2013 Paul Burke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ipaulpro.afilechooser; import android.app.ActionBar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import androidx.core.app.FragmentActivity; import androidx.core.app.FragmentManager; import androidx.core.app.FragmentManager.BackStackEntry; import androidx.core.app.FragmentManager.OnBackStackChangedListener; import androidx.core.app.FragmentTransaction; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.io.File; /** * Main Activity that handles the FileListFragments * * @version 2013-06-25 * @author paulburke (ipaulpro) */ public class FileChooserActivity extends FragmentActivity implements OnBackStackChangedListener, FileListFragment.Callbacks { public static final String PATH = "path"; public static final String EXTERNAL_BASE_PATH = Environment .getExternalStorageDirectory().getAbsolutePath(); private static final boolean HAS_ACTIONBAR = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; private FragmentManager mFragmentManager; private BroadcastReceiver mStorageListener = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, R.string.storage_removed, Toast.LENGTH_LONG).show(); finishWithResult(null); } }; private String mPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mFragmentManager = getSupportFragmentManager(); mFragmentManager.addOnBackStackChangedListener(this); if (savedInstanceState == null) { mPath = EXTERNAL_BASE_PATH; addFragment(); } else { mPath = savedInstanceState.getString(PATH); } setTitle(mPath); } @Override protected void onPause() { super.onPause(); unregisterStorageListener(); } @Override protected void onResume() { super.onResume(); registerStorageListener(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(PATH, mPath); } @Override public void onBackStackChanged() { int count = mFragmentManager.getBackStackEntryCount(); if (count > 0) { BackStackEntry fragment = mFragmentManager.getBackStackEntryAt(count - 1); mPath = fragment.getName(); } else { mPath = EXTERNAL_BASE_PATH; } setTitle(mPath); if (HAS_ACTIONBAR) invalidateOptionsMenu(); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (HAS_ACTIONBAR) { boolean hasBackStack = mFragmentManager.getBackStackEntryCount() > 0; ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(hasBackStack); actionBar.setHomeButtonEnabled(hasBackStack); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mFragmentManager.popBackStack(); return true; } return super.onOptionsItemSelected(item); } /** * Add the initial Fragment with given path. */ private void addFragment() { FileListFragment fragment = FileListFragment.newInstance(mPath); mFragmentManager.beginTransaction() .add(android.R.id.content, fragment).commit(); } /** * "Replace" the existing Fragment with a new one using given path. We're * really adding a Fragment to the back stack. * * @param file The file (directory) to display. */ private void replaceFragment(File file) { mPath = file.getAbsolutePath(); FileListFragment fragment = FileListFragment.newInstance(mPath); mFragmentManager.beginTransaction() .replace(android.R.id.content, fragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .addToBackStack(mPath).commit(); } /** * Finish this Activity with a result code and URI of the selected file. * * @param file The file selected. */ private void finishWithResult(File file) { if (file != null) { Uri uri = Uri.fromFile(file); setResult(RESULT_OK, new Intent().setData(uri)); finish(); } else { setResult(RESULT_CANCELED); finish(); } } /** * Called when the user selects a File * * @param file The file that was selected */ @Override public void onFileSelected(File file) { if (file != null) { if (file.isDirectory()) { replaceFragment(file); } else { finishWithResult(file); } } else { Toast.makeText(FileChooserActivity.this, R.string.error_selecting_file, Toast.LENGTH_SHORT).show(); } } /** * Register the external storage BroadcastReceiver. */ private void registerStorageListener() { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_REMOVED); registerReceiver(mStorageListener, filter); } /** * Unregister the external storage BroadcastReceiver. */ private void unregisterStorageListener() { unregisterReceiver(mStorageListener); } }
mit
b0443301/CPE_Java
CPE23621/src/main.java
2137
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); for (int i = 1;; i++) {// ¥i¥H§ï¦¨while(scanner.hasNextInt())¥i¬O­n¥[¤@­Ói++µ¹¥¦­p¼Æ Boolean isSequence = true;// ¹w³]°O¿ý¬O¤£¬OB2-Sequence(¹L¤TÃöªº·§©À,¥u­n¦pªG¸g¹L¥H¤U§PÂ_ÁÙ¬O·Ltrue¤F¸Ü,¥¦´N¬OB2-Sequence) int input = scanner.nextInt();// ¥u¦³Åª¤Jinputªº­È int[] arrInput = new int[input];// ¶}¤@­Óint°}¦C¦sŪ¤Jªº­ÈEX:1 2 4 8 for (int j = 0; j < input; j++) {// §âŪ¤Jªº°}¦C­È¦s¤U¨Ó arrInput[j] = scanner.nextInt(); } scanner.nextLine();// Ū¤F/n¥y¤l³Ì«á³£¦³¤@­Ó±×½un scanner.nextLine();// ŪªÅ¥Õ¨º¦æ // input = InputCalc(input); // main test = new main(); for (int j = 0; j < input - 1; j++) {// Àˬd¿é¤Jªº­È¬O§_¬°»¼¼W¼Æ¦C if (arrInput[j] >= arrInput[j + 1]) {// ¦pªG«e­±ªº¤H¤ñ«á­±ªº¤H¤j isSequence = false;// §â¥¦°O¿ý¦¨¿ù»~ªº } } // int[] note = new int[10000]; if (isSequence) { ArrayList<Integer> List = new ArrayList<Integer>(); for (int j = 0; j < input; j++) {// ¥Ø«e¦Û¤vªº­È for (int k = j; k < input; k++) {// ¦Û¤v¸ò¦Û¤v¤£¯à¬Û¥[k=j+1,³oÃD¬O¦Û¤v¤£¯à¸ò«e­±ªº¤H¬Û¥[(­n¸ò±q¶¶§Ç¦b¦Û¤v¤§«áªº¤H¬Û¥[),§Ú«á­±ªº¤Hªº­È List.add(arrInput[j] + arrInput[k]); } } Collections.sort(List);// ±Æ§Ç±q¤p±Æ¨ì¤j // Collections.reverse(List);¥ý¤p±Æ¨ì¤j¤§«á¦A¤ÏÂàÅܦ¨¥Ñ¤jÅܤp for (int j = 0; j < List.size() - 1; j++) {// ¥Î¤@­Ófor°j°é±Æ if (List.get(j) == List.get(j + 1)) {// ¦pªG«e­±¥[ªº­È¸ò«á­±¬Ûµ¥ªº¸Ü,¤£»Ý­n¥[isSequence // = // true¬O¦]¬°¥u­n§PÂ_falseªº±ø¥ó,; isSequence = false;// ¬ö¿ý¦¨¿ù»~ªº break; } } } if (isSequence) {// ¦pªGisSequence¬°true¤F¸Ü System.out.println("Case #" + i + " It is a B2-Sequence"); System.out.println(); } else {// ¦pªGisSequence¬°false¤F¸Ü System.out.println("Case #" + i + " It is not a B2-Sequence"); System.out.println(); } } } static int InputCalc(int i) { return i * i; } } // if (arrInput[j] > arrInput[j + 1]) { // // }
mit
Jartreg/bangou
src/main/java/me/jartreg/bangou/App.java
6007
package me.jartreg.bangou; import javafx.application.Application; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.binding.StringBinding; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import me.jartreg.bangou.generators.IrregularCasesGenerator; import me.jartreg.bangou.generators.HiraganaGenerator; import me.jartreg.bangou.generators.KanjiGenerator; import me.jartreg.bangou.generators.RoumajiGenerator; public class App extends Application { private TextField numberInput; private ChoiceBox<String> formatBox; private CheckBox spacedCheckBox; private Text outputText = new Text(); private ComboBox<String> fontBox; private Button copyButton; private double fontSize; @Override public void start(Stage primaryStage) throws Exception { setupControls(); setupBindings(); Pane root = setupLayout(); Scene scene = new Scene(root, Region.USE_PREF_SIZE, 350); primaryStage.setTitle("Bangō"); primaryStage.setScene(scene); primaryStage.setMinWidth(500); primaryStage.setMinHeight(300); primaryStage.show(); } private void setupControls() { numberInput = new TextField(); numberInput.setPromptText("Enter a number"); spacedCheckBox = new CheckBox("Add spaces to improve readability"); spacedCheckBox.setSelected(true); formatBox = new ChoiceBox<>(FXCollections.observableArrayList("Rōmaji", "Hiragana", "Kanji")); formatBox.getSelectionModel().select(0); formatBox.setTooltip(new Tooltip("Writing system")); fontSize = Font.getDefault().getSize() * 2.5; fontBox = new ComboBox<>(FXCollections.observableArrayList(Font.getFamilies())); fontBox.getSelectionModel().select(Font.getDefault().getName()); fontBox.setTooltip(new Tooltip("Font")); copyButton = new Button("Copy"); copyButton.setMinWidth(70); copyButton.setOnAction(event -> { // copy the number to the clipboard ClipboardContent content = new ClipboardContent(); content.putString(outputText.getText()); Clipboard.getSystemClipboard().setContent(content); }); } private Pane setupLayout() { GridPane grid = new GridPane(); grid.setPadding(new Insets(10)); grid.setHgap(10); grid.setVgap(10); // first row grid.add(numberInput, 0, 0); numberInput.setMaxWidth(Region.USE_PREF_SIZE); GridPane.setHgrow(numberInput, Priority.SOMETIMES); grid.add(formatBox, 1, 0); grid.add(spacedCheckBox, 2, 0); // second row (middle) grid.add(outputText, 0, 1, GridPane.REMAINING, 1); GridPane.setVgrow(outputText, Priority.ALWAYS); // fill the remaining vertical space outputText.wrappingWidthProperty().bind( // wrap the text when it overflows the grid's width Bindings.createDoubleBinding( // text width = grid width - padding left and right () -> grid.getLayoutBounds().getWidth() - 20, grid.layoutBoundsProperty() ) ); // last row grid.add(fontBox, 0, 2, 2, 1); grid.add(copyButton, 2, 2); GridPane.setHalignment(copyButton, HPos.RIGHT); return grid; } private void setupBindings() { // The generator depends on the selected output Binding<TextGenerator> generator = Bindings.createObjectBinding(() -> { switch (formatBox.getSelectionModel().getSelectedItem()) { case "Hiragana": return new HiraganaGenerator(spacedCheckBox.isSelected()); case "Kanji": return new KanjiGenerator(); default: //Rōmaji return new RoumajiGenerator(spacedCheckBox.isSelected()); } }, formatBox.getSelectionModel().selectedItemProperty() ); // only Rōmaji and Hiragana support spacing spacedCheckBox.disableProperty().bind( Bindings.createBooleanBinding( () -> !(generator.getValue() instanceof IrregularCasesGenerator), generator ) ); spacedCheckBox.selectedProperty().addListener(observable -> { TextGenerator gen = generator.getValue(); if (gen instanceof IrregularCasesGenerator) ((IrregularCasesGenerator) gen).setSpaced(spacedCheckBox.isSelected()); }); // true when there's an error SimpleBooleanProperty error = new SimpleBooleanProperty(false); // update the text when the input, the generator or the spacing has changed StringBinding numberText = Bindings.createStringBinding( () -> { int[] digits; try { digits = Utilities.getDigits(numberInput.getText().trim()); } catch (NumberFormatException e) { error.set(true); return "This is not a valid number"; } String number = null; try { if (digits.length > 0) number = generator.getValue().generateNumber(digits); } catch (IllegalArgumentException e) { error.set(true); return e.getMessage(); } error.set(false); // success return number; }, numberInput.textProperty(), generator, spacedCheckBox.selectedProperty() ); outputText.textProperty().bind( Bindings.when(Bindings.isEmpty(numberText)) .then("Enter a number") .otherwise(numberText) ); outputText.fillProperty().bind( Bindings.when(error) .then((Paint) Color.RED) .otherwise(outputText.getFill()) ); // disabled when there's an error or no text at all copyButton.disableProperty().bind(error.or(Bindings.isEmpty(numberText))); outputText.fontProperty().bind( Bindings.createObjectBinding( () -> new Font(fontBox.getSelectionModel().getSelectedItem(), fontSize), fontBox.getSelectionModel().selectedItemProperty() ) ); } }
mit
alanmtz1503/InCense
src/edu/incense/android/sensor/SmsSensor.java
1994
package edu.incense.android.sensor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import edu.incense.android.datatask.data.BatteryStateData; import edu.incense.android.datatask.data.SmsData; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.util.Log; public class SmsSensor extends Sensor{ static final String ACTION_RECEIVED ="android.provider.Telephony.SMS_RECEIVED"; static final String ACTION_SENT ="android.provider.Telephony.SMS_SENT"; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); public SmsSensor(Context context) { super(context); setName("Sms"); } @Override public synchronized void start() { // TODO Auto-generated method stub super.start(); IntentFilter smsReceived = new IntentFilter(ACTION_RECEIVED); getContext().registerReceiver(batteryStateReceiver, smsReceived); IntentFilter smsSent = new IntentFilter(ACTION_SENT); getContext().registerReceiver(batteryStateReceiver, smsSent); } @Override public synchronized void stop() { // TODO Auto-generated method stub super.stop(); getContext().unregisterReceiver(batteryStateReceiver); } BroadcastReceiver batteryStateReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_RECEIVED)){ smsReceived(); }else if(intent.getAction().equals(ACTION_SENT)){ smsSent(); } } }; public void smsReceived() { currentData = new SmsData("SmsReceived"); Log.i("softSensing", "smsReceived "+date); } public void smsSent() { currentData = new SmsData("SmsSent"); Log.i("softSensing", "smsSent "+date); } }
mit
fvasquezjatar/fermat-unused
DMP/plugin/world/fermat-dmp-plugin-world-blockchain-info-bitdubai/src/test/java/com/bitdubai/fermat_dmp_plugin/layer/world/blockchain_info/developer/bitdubai/version_1/structure/api_v_1/wallet/GetAddressesTest.java
1093
package com.bitdubai.fermat_dmp_plugin.layer.world.blockchain_info.developer.bitdubai.version_1.structure.api_v_1.wallet; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; /** * Created by leon on 5/6/15. */ @RunWith(MockitoJUnitRunner.class) public class GetAddressesTest extends TestCase { String apiCode = "91c646ef-c3fd-4dd0-9dc9-eba5c5600549"; Wallet wallet; @Before public void setUp() { wallet = new Wallet("7a9dc256-0e67-441f-886a-c4364fec9369", "Blockchain91-"); wallet.setApiCode(apiCode); } @Test public void testGetBalance_NotNull() { List<Address> addresses = new ArrayList<>(); try { addresses = wallet.listAddresses(0); } catch (Exception e) { System.out.println(e); } for (Address address : addresses){ System.out.println("i'm an address: "+address.getAddress()); } } }
mit
Esilen/GCBatch
gcbatch/gcbatch_core/src/main/java/gcbatch/task/comm/FileCompress.java
2790
package gcbatch.task.comm; import gcbatch.base.exception.BusinessException; import gcbatch.task.SyncTask; import gcbatch.task.Task; import gcbatch.task.annotations.TaskInput; import gcbatch.utils.CompressUtil; import gcbatch.utils.FileUtil; import gcbatch.utils.StringUtil; import java.util.Arrays; /** * 文件压缩、解压组件 * * <pre> * modify by tiankai on 2016-8-2 * fix->1. * 2. * </pre> */ public class FileCompress extends SyncTask { /** * TASK 输入参数 */ @TaskInput(Name = "zipFileName") public String inZipFileName; @TaskInput(Name = "targetFileNames", description = "可以不送,解压缩或压缩所有", mustInput = false) public String[] inTargetFileNames; @TaskInput(Name = "targetFileName", description = "可以不送,解压缩或压缩所有", mustInput = false) public String inTargetFileName; @TaskInput(Name = "sourceDir") public String inSourceDir; @TaskInput(Name = "targetDir", evalStr = "${sourceDir}") public String inTargetDir; @TaskInput(Name = "cmpressType") public String inCmpressType; @TaskInput(Name = "action") public String inAction; @TaskInput(Name = "deleteSource", mustInput = false) public Boolean deleteSource = false; @Override protected void doExecute() throws Exception { int count = 0; if(!inSourceDir.endsWith("/")) { inSourceDir += "/"; } if(!inTargetDir.endsWith("/")) { inTargetDir += "/"; } if(inTargetFileNames == null || inTargetFileNames.length == 0) { if(StringUtil.isEmpty(inTargetFileName)) { inTargetFileNames = null; } else { inTargetFileNames = new String[] { inTargetFileName }; } } log.info("源路径:" + inSourceDir); log.info("目标路径:" + inTargetDir); log.info("目标文件:" + Arrays.toString(inTargetFileNames)); if("zip".equals(inCmpressType)) { if("decompress".equals(inAction)) { try { log.info("解压缩文件:" + inZipFileName); if(inTargetFileNames == null) count = CompressUtil.unzipAllFiles(inSourceDir + inZipFileName, inTargetDir); else count = CompressUtil.unzipFiles(inSourceDir + inZipFileName, inTargetDir, inTargetFileNames); } catch (Exception e) { throw new BusinessException("-20", "FileCompress作业执行异常!", e); } if(inTargetFileNames != null && count != inTargetFileNames.length) this.setResult(Task.TASK_RETURNCODE_INVALID_EXEC, "解压到文件:" + count + " expect: " + inTargetFileNames.length); if(this.deleteSource) FileUtil.deleteFile(inSourceDir + inZipFileName, true); } else { throw new BusinessException("-20", "不支持此动作!"); } } else { throw new BusinessException("-20", "不支持此压缩格式!"); } this.setResult("0", "共处理[" + count + "]个文件."); } }
mit