code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
package com.onkiup.minedroid;
import com.onkiup.minedroid.gui.resources.*;
import com.onkiup.minedroid.gui.MineDroid;
/**
* This class is auto generated.
* Manually made changes will be discarded.
**/
public final class R {
final static String MODID = "minedroid";
public final static class id {
public final static int message = 268435456;
public final static int hint = 268435457;
public final static int test = 268435458;
public final static int text = 268435459;
public final static int debug = 268435460;
public final static int close = 268435461;
public final static int edit = 268435462;
public final static int edit_multiline = 268435463;
public final static int progress = 268435464;
public final static int list = 268435465;
}
public final static class string {
public final static ValueLink cancel = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Cancel") });
public final static ValueLink test_window = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Minedroid Test") });
public final static ValueLink test = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "test") });
public final static ValueLink alert_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "click or press Y to dismiss") });
public final static ValueLink confirm_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "press Y/N to respond") });
public final static ValueLink ok = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Ok") });
public final static ValueLink close = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "close") });
}
public final static class layout {
public final static ResourceLink minedroid_test = new ResourceLink(MODID, "layouts", "minedroid_test.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink alert = new ResourceLink(MODID, "layouts", "alert.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink holder_string = new ResourceLink(MODID, "layouts", "holder_string.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink config_main = new ResourceLink(MODID, "layouts", "config_main.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink confirm = new ResourceLink(MODID, "layouts", "confirm.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
}
public final static class drawable {
public final static ResourceLink shadow = new ResourceLink(MODID, "drawables", "shadow.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink check = new ResourceLink(MODID, "drawables", "check.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink scroll = new ResourceLink(MODID, "drawables", "scroll.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_overlay = new ResourceLink(MODID, "drawables", "bg_overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_checkbox = new ResourceLink(MODID, "drawables", "bg_checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink fg_progress_view = new ResourceLink(MODID, "drawables", "fg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_edit_text = new ResourceLink(MODID, "drawables", "bg_edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink overlay = new ResourceLink(MODID, "drawables", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_button = new ResourceLink(MODID, "drawables", "bg_button.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_progress_view = new ResourceLink(MODID, "drawables", "bg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
}
public final static class ninepatch {
public final static ResourceLink panel = new ResourceLink(MODID, "ninepatches", "panel", new EnvParams[] { new EnvParams(null, null, null, null)});
}
public final static class style {
public final static Style focus = new Style(new ResourceLink(MODID, "styles", "focus.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout");
public final static Style content_view = new Style(new ResourceLink(MODID, "styles", "content_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view");
public final static Style relative_layout = new Style(new ResourceLink(MODID, "styles", "relative_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group");
public final static Style checkbox = new Style(new ResourceLink(MODID, "styles", "checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style entity_view = new Style(new ResourceLink(MODID, "styles", "entity_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style edit_text = new Style(new ResourceLink(MODID, "styles", "edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view");
public final static Style view_group = new Style(new ResourceLink(MODID, "styles", "view_group.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style scroll_view = new Style(new ResourceLink(MODID, "styles", "scroll_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style overlay = new Style(new ResourceLink(MODID, "styles", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style progress_view = new Style(new ResourceLink(MODID, "styles", "progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style text = new Style(new ResourceLink(MODID, "styles", "text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style theme = new Style(new ResourceLink(MODID, "styles", "theme.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style text_view = new Style(new ResourceLink(MODID, "styles", "text_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style list_view = new Style(new ResourceLink(MODID, "styles", "list_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout");
public final static Style button = new Style(new ResourceLink(MODID, "styles", "button.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view");
public final static Style view = new Style(new ResourceLink(MODID, "styles", "view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style linear_layout = new Style(new ResourceLink(MODID, "styles", "linear_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group");
}
} | chedim/minedriod | src/main/java/com/onkiup/minedroid/R.java | Java | gpl-2.0 | 7,740 |
package thesis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import termo.component.Compound;
import termo.eos.Cubic;
import termo.eos.EquationsOfState;
import termo.eos.alpha.Alphas;
import termo.matter.Mixture;
import termo.matter.Substance;
import termo.phase.Phase;
import compounds.CompoundReader;
public class CubicFileGenerator extends FileGenerator {
Substance substance;
public CubicFileGenerator(){
CompoundReader reader = new CompoundReader();
Compound heptane = reader.getCompoundByExactName("N-heptane");
substance = new Substance(EquationsOfState.vanDerWaals()
,Alphas.getVanDerWaalsIndependent()
,heptane,Phase.VAPOR);
}
public void cubicEquationPressureVolumeTemperatureFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion Temperatura");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 60;
double pass = (max_volume- min_volume)/n;
int nt =20;
double min_temperature = 150;
double max_temperature = 400;
double tempPass = (max_temperature - min_temperature)/nt;
for(int j = 0; j < nt; j++){
double temperature = min_temperature + tempPass *j ;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure = calculatePressure(volume, temperature);
writer.println(" "+ volume + " " + temperature + " " + pressure);
}
writer.println();
}
writer.close();
}
public double calculatePressure(double volume, double temperature){
return substance.calculatePressure(temperature,volume);
//parametros de van der waals para el heptano
// double a = 3107000.0;
//double b = 0.2049;
// return cubic.calculatePressure(temperature, volume,a,b);
}
public void cubicEquationPressureVolumeFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 100;
double pass = (max_volume- min_volume)/n;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure =calculatePressure(volume, 300);
writer.println(" "+ volume + " " + pressure);
}
writer.close();
}
public void cubicEquationCompresibilitiFactorFiles(String folderName) throws FileNotFoundException, UnsupportedEncodingException{
File directory = new File(folderName);
if(!directory.exists()){
directory.mkdir();
}
Cubic cubic = EquationsOfState.vanDerWaals();
double min_reducedPressure = 0.1;
double max_reducedPressure= 7;
double pressurepass =( max_reducedPressure- min_reducedPressure)/ 100;
double min_reducedTemperature= 1 ;
double max_reducedTemperature=2;
double criticalTemperature = 540.2;
double criticalPressure = 2.74000E+06;
double a = 3107000.0;
double b = 0.2049;
PrintWriter writer= new PrintWriter(folderName + "pz_temp.dat", "UTF-8");
writer.println(" p z rt");
for(double reducedTemperature = min_reducedTemperature; reducedTemperature <= max_reducedTemperature; reducedTemperature +=0.1){
for(double reducedPressure = min_reducedPressure ; reducedPressure <= max_reducedPressure; reducedPressure+= pressurepass){
double temperature = criticalTemperature * reducedTemperature;
double pressure = criticalPressure * reducedPressure;
// double A =cubic.get_A(temperature, pressure, a);
// double B = cubic.get_B(temperature, pressure, b);
substance.setPressure(pressure);
substance.setTemperature(temperature);
double z = substance.calculateCompresibilityFactor();
//double z =cubic.calculateCompresibilityFactor(A, B, Phase.LIQUID);
writer.println(" " + reducedPressure + " " + z + " " + reducedTemperature);
}
writer.println();
}
writer.close();
}
}
| HugoRedon/thesis-examples | src/main/java/thesis/CubicFileGenerator.java | Java | gpl-2.0 | 4,031 |
package sergio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.GregorianCalendar;
//Ejercicio Metodos 18
//Realiza una clase llamada milibreria que contenga al menos cinco de los metodos realizados.
//Usalas de 3 formas diferentes
//Autor: Sergio Tobal
//Fecha: 12-02-2012
public class EjerMetods18 {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in));
int numsend=10,edad;
char nombre;
boolean nombreceive;
String msgname = null;
System.out.println("Dame tu inicial:");
nombre=lectura.readLine().charAt(0);
nombreceive=EsMayus(nombre);
if (nombreceive==true) {
msgname="MAYUSCULAS";
} else if (nombreceive==false) {
msgname="minusculas";
}
EsPerfecto(numsend);
System.out.println("Tu primer numero perfecto es "+numsend+" porque tienes "+(edad=ObtenerEdad())+" años, y tu inicial esta escrita en "+msgname);
}
private static boolean EsPerfecto(int numsend) {
int perfect=0;
for (int i = 1; i < numsend; i++) {
if (numsend % i == 0) {
perfect += i;
}
}
if (perfect == numsend) {
return true;
}else {
return false;
}
}
private static int ObtenerEdad()throws NumberFormatException, IOException{
BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in));
int year,month,day;
System.out.println("Dime tu dia de nacimiento: ");
day=Integer.parseInt(lectura.readLine());
System.out.println("Dime tu mes de nacimiento: ");
month=Integer.parseInt(lectura.readLine());
System.out.println("Dime tu año de nacimiento: ");
year=Integer.parseInt(lectura.readLine());
Calendar cal = new GregorianCalendar(year, month, day);
Calendar now = new GregorianCalendar();
int edad = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)) || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
edad--;
}
return edad;
}
private static int Factorial(int num) {
int factorial=1;
// Va multiplicando el numero del usuario por 1 hasta que el numero llega ha cero y retorna
// la multiplicacion de todos los numeros
while (num!=0) {
factorial=factorial*num;
num--;
}
return factorial;
}
private static boolean ValFecha(int day, int month) {
if ((day>=1 && day<=31) && (month>=1 && month<=12)) {
return true;
}else {
return false;
}
}
private static boolean EsMayus(char nombre) {
boolean opt=true;
// La funcion isUpperCase comprueba que el contenido de num sea mayuscula
if (Character.isUpperCase(nombre) == true) {
opt=true;
// La funcion isLowerCase comprueba que el contenido de num sea minuscula
} else if(Character.isLowerCase(nombre) == true){
opt=false;
}
return opt;
}
}
| set92/Small-Programs | Java/CFGS/Interfaces-Ejercicios/Ejercicios propuestos de metodos/sergio/EjerMetods18.java | Java | gpl-2.0 | 3,147 |
/**
* jBorZoi - An Elliptic Curve Cryptography Library
*
* Copyright (C) 2003 Dragongate Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.dragongate_technologies.borZoi;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Elliptic Curve Private Keys consisting of two member variables: dp,
* the EC domain parameters and s, the private key which must
* be kept secret.
* @author <a href="http://www.dragongate-technologies.com">Dragongate Technologies Ltd.</a>
* @version 0.90
*/
public class ECPrivKey {
/**
* The EC Domain Parameters
*/
public ECDomainParameters dp;
/**
* The Private Key
*/
public BigInteger s;
/**
* Generate a random private key with ECDomainParameters dp
*/
public ECPrivKey(ECDomainParameters dp) {
this.dp = (ECDomainParameters) dp.clone();
SecureRandom rnd = new SecureRandom();
s = new BigInteger(dp.m, rnd);
s = s.mod(dp.r);
}
/**
* Generate a private key with ECDomainParameters dp
* and private key s
*/
public ECPrivKey(ECDomainParameters dp, BigInteger s) {
this.dp = dp;
this.s = s;
}
public String toString() {
String str = new String("dp: ").concat(dp.toString()).concat("\n");
str = str.concat("s: ").concat(s.toString()).concat("\n");
return str;
}
protected Object clone() {
return new ECPrivKey(dp, s);
}
}
| HateBreed/old-codes-from-studies | cryptoclient_in_java/com/dragongate_technologies/borZoi/ECPrivKey.java | Java | gpl-2.0 | 2,027 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
/**
* An {@code AtomicMarkableReference} maintains an object reference
* along with a mark bit, that can be updated atomically.
*
* <p>Implementation note: This implementation maintains markable
* references by creating internal objects representing "boxed"
* [reference, boolean] pairs.
*
* @since 1.5
* @author Doug Lea
* @param <V> The type of object referred to by this reference
*/
public class AtomicMarkableReference<V> {
private static class Pair<T> {
final T reference;
final boolean mark;
private Pair(T reference, boolean mark) {
this.reference = reference;
this.mark = mark;
}
static <T> Pair<T> of(T reference, boolean mark) {
return new Pair<T>(reference, mark);
}
}
private volatile Pair<V> pair;
/**
* Creates a new {@code AtomicMarkableReference} with the given
* initial values.
*
* @param initialRef the initial reference
* @param initialMark the initial mark
*/
public AtomicMarkableReference(V initialRef, boolean initialMark) {
pair = Pair.of(initialRef, initialMark);
}
/**
* Returns the current value of the reference.
*
* @return the current value of the reference
*/
public V getReference() {
return pair.reference;
}
/**
* Returns the current value of the mark.
*
* @return the current value of the mark
*/
public boolean isMarked() {
return pair.mark;
}
/**
* Returns the current values of both the reference and the mark.
* Typical usage is {@code boolean[1] holder; ref = v.get(holder); }.
*
* @param markHolder an array of size of at least one. On return,
* {@code markholder[0]} will hold the value of the mark.
* @return the current value of the reference
*/
public V get(boolean[] markHolder) {
Pair<V> pair = this.pair;
markHolder[0] = pair.mark;
return pair.reference;
}
/**
* Atomically sets the value of both the reference and mark
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current mark is equal to the expected mark.
*
* <p><a href="package-summary.html#weakCompareAndSet">May fail
* spuriously and does not provide ordering guarantees</a>, so is
* only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedMark the expected value of the mark
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean weakCompareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
return compareAndSet(expectedReference, newReference,
expectedMark, newMark);
}
/**
* Atomically sets the value of both the reference and mark
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current mark is equal to the expected mark.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedMark the expected value of the mark
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean compareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
expectedMark == current.mark &&
((newReference == current.reference &&
newMark == current.mark) ||
casPair(current, Pair.of(newReference, newMark)));
}
/**
* Unconditionally sets the value of both the reference and mark.
*
* @param newReference the new value for the reference
* @param newMark the new value for the mark
*/
public void set(V newReference, boolean newMark) {
Pair<V> current = pair;
if (newReference != current.reference || newMark != current.mark)
this.pair = Pair.of(newReference, newMark);
}
/**
* Atomically sets the value of the mark to the given update value
* if the current reference is {@code ==} to the expected
* reference. Any given invocation of this operation may fail
* (return {@code false}) spuriously, but repeated invocation
* when the current value holds the expected value and no other
* thread is also attempting to set the value will eventually
* succeed.
*
* @param expectedReference the expected value of the reference
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean attemptMark(V expectedReference, boolean newMark) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
(newMark == current.mark ||
casPair(current, Pair.of(expectedReference, newMark)));
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
// private static final long pairOffset =
// objectFieldOffset(UNSAFE, "pair", AtomicMarkableReference.class);
private boolean casPair(Pair<V> cmp, Pair<V> val) {
return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val);
}
public static volatile long pairOffset;
static {
try {
pairOffset = 0;
UNSAFE.registerStaticFieldOffset(
AtomicMarkableReference.class.getDeclaredField("pairOffset"),
AtomicMarkableReference.class.getDeclaredField("pair"));
} catch (Exception ex) { throw new Error(ex); }
}
}
| upenn-acg/REMIX | jvm-remix/openjdk/jdk/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java | Java | gpl-2.0 | 7,816 |
package edu.stanford.nlp.time;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Map;
import java.util.regex.Pattern;
import edu.stanford.nlp.util.Pair;
import org.w3c.dom.Element;
/**
* Stores one TIMEX3 expression. This class is used for both TimeAnnotator and
* GUTimeAnnotator for storing information for TIMEX3 tags.
*
* <p>
* Example text with TIMEX3 annotation:<br>
* <code>In Washington <TIMEX3 tid="t1" TYPE="DATE" VAL="PRESENT_REF"
* temporalFunction="true" valueFromFunction="tf1"
* anchorTimeID="t0">today</TIMEX3>, the Federal Aviation Administration
* released air traffic control tapes from the night the TWA Flight eight
* hundred went down.
* </code>
* <p>
* <br>
* TIMEX3 specification:
* <br>
* <pre><code>
* attributes ::= tid type [functionInDocument] [beginPoint] [endPoint]
* [quant] [freq] [temporalFunction] (value | valueFromFunction)
* [mod] [anchorTimeID] [comment]
*
* tid ::= ID
* {tid ::= TimeID
* TimeID ::= t<integer>}
* type ::= 'DATE' | 'TIME' | 'DURATION' | 'SET'
* beginPoint ::= IDREF
* {beginPoint ::= TimeID}
* endPoint ::= IDREF
* {endPoint ::= TimeID}
* quant ::= CDATA
* freq ::= Duration
* functionInDocument ::= 'CREATION_TIME' | 'EXPIRATION_TIME' | 'MODIFICATION_TIME' |
* 'PUBLICATION_TIME' | 'RELEASE_TIME'| 'RECEPTION_TIME' |
* 'NONE' {default, if absent, is 'NONE'}
* temporalFunction ::= 'true' | 'false' {default, if absent, is 'false'}
* {temporalFunction ::= boolean}
* value ::= Duration | Date | Time | WeekDate | WeekTime | Season | PartOfYear | PaPrFu
* valueFromFunction ::= IDREF
* {valueFromFunction ::= TemporalFunctionID
* TemporalFunctionID ::= tf<integer>}
* mod ::= 'BEFORE' | 'AFTER' | 'ON_OR_BEFORE' | 'ON_OR_AFTER' |'LESS_THAN' | 'MORE_THAN' |
* 'EQUAL_OR_LESS' | 'EQUAL_OR_MORE' | 'START' | 'MID' | 'END' | 'APPROX'
* anchorTimeID ::= IDREF
* {anchorTimeID ::= TimeID}
* comment ::= CDATA
* </code></pre>
*
* <p>
* References
* <br>
* Guidelines: <a href="http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf">
* http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf</a>
* <br>
* Specifications: <a href="http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3">
* http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3</a>
* <br>
* XSD: <a href="http://www.timeml.org/timeMLdocs/TimeML.xsd">http://www.timeml.org/timeMLdocs/TimeML.xsd</a>
**/
public class Timex implements Serializable {
private static final long serialVersionUID = 385847729549981302L;
/**
* XML representation of the TIMEX tag
*/
private String xml;
/**
* TIMEX3 value attribute - Time value (given in extended ISO 8601 format).
*/
private String val;
/**
* Alternate representation for time value (not part of TIMEX3 standard).
* used when value of the time expression cannot be expressed as a standard TIMEX3 value.
*/
private String altVal;
/**
* Actual text that make up the time expression
*/
private String text;
/**
* TIMEX3 type attribute - Type of the time expression (DATE, TIME, DURATION, or SET)
*/
private String type;
/**
* TIMEX3 tid attribute - TimeID. ID to identify this time expression.
* Should have the format of {@code t<integer>}
*/
private String tid;
// TODO: maybe its easier if these are just strings...
/**
* TIMEX3 beginPoint attribute - integer indicating the TimeID of the begin time
* that anchors this duration/range (-1 is not present).
*/
private int beginPoint;
/**
* TIMEX3 beginPoint attribute - integer indicating the TimeID of the end time
* that anchors this duration/range (-1 is not present).
*/
private int endPoint;
/**
* Range begin/end/duration
* (this is not part of the timex standard and is typically null, available if sutime.includeRange is true)
*/
private Range range;
public static class Range implements Serializable {
private static final long serialVersionUID = 1L;
public String begin;
public String end;
public String duration;
public Range(String begin, String end, String duration) {
this.begin = begin;
this.end = end;
this.duration = duration;
}
}
public String value() {
return val;
}
public String altVal() {
return altVal;
}
public String text() {
return text;
}
public String timexType() {
return type;
}
public String tid() {
return tid;
}
public Range range() {
return range;
}
public Timex() {
}
public Timex(Element element) {
this.val = null;
this.beginPoint = -1;
this.endPoint = -1;
/*
* ByteArrayOutputStream os = new ByteArrayOutputStream(); Serializer ser =
* new Serializer(os, "UTF-8"); ser.setIndent(2); // this is the default in
* JDOM so let's keep the same ser.setMaxLength(0); // no line wrapping for
* content ser.write(new Document(element));
*/
init(element);
}
public Timex(String val) {
this(null, val);
}
public Timex(String type, String val) {
this.val = val;
this.type = type;
this.beginPoint = -1;
this.endPoint = -1;
this.xml = (val == null ? "<TIMEX3/>" : String.format("<TIMEX3 VAL=\"%s\" TYPE=\"%s\"/>", this.val, this.type));
}
public Timex(String type, String val, String altVal, String tid, String text, int beginPoint, int endPoint) {
this.type = type;
this.val = val;
this.altVal = altVal;
this.tid = tid;
this.text = text;
this.beginPoint = beginPoint;
this.endPoint = endPoint;
}
private void init(Element element) {
init(XMLUtils.nodeToString(element, false), element);
}
private void init(String xml, Element element) {
this.xml = xml;
this.text = element.getTextContent();
// Mandatory attributes
this.tid = XMLUtils.getAttribute(element, "tid");
this.val = XMLUtils.getAttribute(element, "VAL");
if (this.val == null) {
this.val = XMLUtils.getAttribute(element, "value");
}
this.altVal = XMLUtils.getAttribute(element, "alt_value");
this.type = XMLUtils.getAttribute(element, "type");
if (type == null) {
this.type = XMLUtils.getAttribute(element, "TYPE");
}
// if (this.type != null) {
// this.type = this.type.intern();
// }
// Optional attributes
String beginPoint = XMLUtils.getAttribute(element, "beginPoint");
this.beginPoint = (beginPoint == null || beginPoint.length() == 0)? -1 : Integer.parseInt(beginPoint.substring(1));
String endPoint = XMLUtils.getAttribute(element, "endPoint");
this.endPoint = (endPoint == null || endPoint.length() == 0)? -1 : Integer.parseInt(endPoint.substring(1));
// Optional range
String rangeStr = XMLUtils.getAttribute(element, "range");
if (rangeStr != null) {
if (rangeStr.startsWith("(") && rangeStr.endsWith(")")) {
rangeStr = rangeStr.substring(1, rangeStr.length()-1);
}
String[] parts = rangeStr.split(",");
this.range = new Range(parts.length > 0? parts[0]:"", parts.length > 1? parts[1]:"", parts.length > 2? parts[2]:"");
}
}
public int beginPoint() { return beginPoint; }
public int endPoint() { return endPoint; }
public String toString() {
return (this.xml != null) ? this.xml : this.val;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Timex timex = (Timex) o;
if (beginPoint != timex.beginPoint) {
return false;
}
if (endPoint != timex.endPoint) {
return false;
}
if (type != null ? !type.equals(timex.type) : timex.type != null) {
return false;
}
if (val != null ? !val.equals(timex.val) : timex.val != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = val != null ? val.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + beginPoint;
result = 31 * result + endPoint;
return result;
}
public Element toXmlElement() {
Element element = XMLUtils.createElement("TIMEX3");
if (tid != null) {
element.setAttribute("tid", tid);
}
if (value() != null) {
element.setAttribute("value", val);
}
if (altVal != null) {
element.setAttribute("altVal", altVal);
}
if (type != null) {
element.setAttribute("type", type);
}
if (beginPoint != -1) {
element.setAttribute("beginPoint", "t" + String.valueOf(beginPoint));
}
if (endPoint != -1) {
element.setAttribute("endPoint", "t" + String.valueOf(endPoint));
}
if (text != null) {
element.setTextContent(text);
}
return element;
}
// Used to create timex from XML (mainly for testing)
public static Timex fromXml(String xml) {
Element element = XMLUtils.parseElement(xml);
if ("TIMEX3".equals(element.getNodeName())) {
Timex t = new Timex();
// t.init(xml, element);
// Doesn't preserve original input xml
// Will reorder attributes of xml so can match xml of test timex and actual timex
// (for which we can't control the order of the attributes now we don't use nu.xom...)
t.init(element);
return t;
} else {
throw new IllegalArgumentException("Invalid timex xml: " + xml);
}
}
public static Timex fromMap(String text, Map<String, String> map) {
try {
Element element = XMLUtils.createElement("TIMEX3");
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() != null) {
element.setAttribute(entry.getKey(), entry.getValue());
}
}
element.setTextContent(text);
return new Timex(element);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Gets the Calendar matching the year, month and day of this Timex.
*
* @return The matching Calendar.
*/
public Calendar getDate() {
if (Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
int day = Integer.parseInt(this.val.substring(8, 10));
return makeCalendar(year, month, day);
} else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return makeCalendar(year, month, day);
}
throw new UnsupportedOperationException(String.format("%s is not a fully specified date", this));
}
/**
* Gets two Calendars, marking the beginning and ending of this Timex's range.
*
* @return The begin point and end point Calendars.
*/
public Pair<Calendar, Calendar> getRange() {
return this.getRange(null);
}
/**
* Gets two Calendars, marking the beginning and ending of this Timex's range.
*
* @param documentTime
* The time the document containing this Timex was written. (Not
* necessary for resolving all Timex expressions. This may be
* {@code null}, but then relative time expressions cannot be
* resolved.)
* @return The begin point and end point Calendars.
*/
public Pair<Calendar, Calendar> getRange(Timex documentTime) {
if (this.val == null) {
throw new UnsupportedOperationException("no value specified for " + this);
}
// YYYYMMDD or YYYYMMDDT... where the time is concatenated directly with the
// date
else if (val.length() >= 8 && Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val.substring(0, 8))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYY-MM-DD or YYYY-MM-DDT...
else if (val.length() >= 10 && Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val.substring(0, 10))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
int day = Integer.parseInt(this.val.substring(8, 10));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYYMMDDL+
else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d[A-Z]+", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYYMM or YYYYMMT...
else if (val.length() >= 6 && Pattern.matches("\\d\\d\\d\\d\\d\\d", this.val.substring(0, 6))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
Calendar begin = makeCalendar(year, month, 1);
int lastDay = begin.getActualMaximum(Calendar.DATE);
Calendar end = makeCalendar(year, month, lastDay);
return new Pair<>(begin, end);
}
// YYYY-MM or YYYY-MMT...
else if (val.length() >= 7 && Pattern.matches("\\d\\d\\d\\d-\\d\\d", this.val.substring(0, 7))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
Calendar begin = makeCalendar(year, month, 1);
int lastDay = begin.getActualMaximum(Calendar.DATE);
Calendar end = makeCalendar(year, month, lastDay);
return new Pair<>(begin, end);
}
// YYYY or YYYYT...
else if (val.length() >= 4 && Pattern.matches("\\d\\d\\d\\d", this.val.substring(0, 4))) {
int year = Integer.parseInt(this.val.substring(0, 4));
return new Pair<>(makeCalendar(year, 1, 1), makeCalendar(year, 12, 31));
}
// PDDY
if (Pattern.matches("P\\d+Y", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int yearRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.YEAR, yearRange);
return new Pair<>(start, end);
}
// in the past
else if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.YEAR, 0 - yearRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// PDDM
if (Pattern.matches("P\\d+M", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int monthRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.MONTH, monthRange);
return new Pair<>(start, end);
}
// in the past
if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.MONTH, 0 - monthRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// PDDD
if (Pattern.matches("P\\d+D", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int dayRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.DAY_OF_MONTH, dayRange);
return new Pair<>(start, end);
}
// in the past
if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.DAY_OF_MONTH, 0 - dayRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// YYYYSP
if (Pattern.matches("\\d+SP", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 2, 1);
Calendar end = makeCalendar(year, 4, 31);
return new Pair<>(start, end);
}
// YYYYSU
if (Pattern.matches("\\d+SU", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 5, 1);
Calendar end = makeCalendar(year, 7, 31);
return new Pair<>(start, end);
}
// YYYYFA
if (Pattern.matches("\\d+FA", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 8, 1);
Calendar end = makeCalendar(year, 10, 31);
return new Pair<>(start, end);
}
// YYYYWI
if (Pattern.matches("\\d+WI", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 11, 1);
Calendar end = makeCalendar(year + 1, 1, 29);
return new Pair<>(start, end);
}
// YYYYWDD
if (Pattern.matches("\\d\\d\\d\\dW\\d+", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int week = Integer.parseInt(this.val.substring(5));
int startDay = (week - 1) * 7;
int endDay = startDay + 6;
Calendar start = makeCalendar(year, startDay);
Calendar end = makeCalendar(year, endDay);
return new Pair<>(start, end);
}
// PRESENT_REF
if (this.val.equals("PRESENT_REF")) {
Calendar rc = documentTime.getDate(); // todo: This case doesn't check for documentTime being null and will NPE
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
return new Pair<>(start, end);
}
throw new RuntimeException(String.format("unknown value \"%s\" in %s", this.val, this));
}
private static Calendar makeCalendar(int year, int month, int day) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(year, month - 1, day, 0, 0, 0);
return date;
}
private static Calendar makeCalendar(int year, int dayOfYear) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(Calendar.YEAR, year);
date.set(Calendar.DAY_OF_YEAR, dayOfYear);
return date;
}
private static Calendar copyCalendar(Calendar c) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c
.get(Calendar.MINUTE), c.get(Calendar.SECOND));
return date;
}
}
| rupenp/CoreNLP | src/edu/stanford/nlp/time/Timex.java | Java | gpl-2.0 | 19,256 |
/*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2007-2016 Minnesota Department of Transportation
* Copyright (C) 2014 AHMCT, University of California
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package us.mn.state.dot.tms.server.comm;
import us.mn.state.dot.tms.DeviceRequest;
import us.mn.state.dot.tms.server.CameraImpl;
/**
* CameraPoller is an interface for pollers which can send camera control
* messages.
*
* @author Douglas Lau
* @author Travis Swanston
*/
public interface CameraPoller {
/** Send a PTZ camera move command */
void sendPTZ(CameraImpl c, float p, float t, float z);
/** Send a store camera preset command */
void sendStorePreset(CameraImpl c, int preset);
/** Send a recall camera preset command */
void sendRecallPreset(CameraImpl c, int preset);
/** Send a device request
* @param c The CameraImpl object.
* @param r The desired DeviceRequest. */
void sendRequest(CameraImpl c, DeviceRequest r);
}
| CA-IRIS/mn-iris | src/us/mn/state/dot/tms/server/comm/CameraPoller.java | Java | gpl-2.0 | 1,437 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest10564")
public class BenchmarkTest10564 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar = new Test().doSomething(param);
Object[] obj = { "a", "b"};
response.getWriter().printf(java.util.Locale.US,bar,obj);
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest10564.java | Java | gpl-2.0 | 2,498 |
package com.nilsonmassarenti.app.currencyfair.model;
/**
* This class is to manager URL of Rest.
* @author nilsonmassarenti - nilsonmassarenti@gmail.com
* @version 0.1
* Last update: 03-Mar-2015 12:20 am
*/
public class CurrencyFairURI {
public static final String DUMMY_BP = "/rest/currencyfair/dummy";
public static final String GET_CURRENCY_FAIR = "/rest/currencyfair/get/{id}";
public static final String GET_ALL_CURRENCY_FAIR = "/rest/currencyfairs";
public static final String CREATE_CURRENCY_FAIR = "/rest/currencyfair/create";
public static final String DELETE_CURRENCY_FAIR = "/rest/currencyfair/delete/{id}";
}
| nilsonmassarenti/currencyfair | currencyfair/src/main/java/com/nilsonmassarenti/app/currencyfair/model/CurrencyFairURI.java | Java | gpl-2.0 | 632 |
package com.javarush.task.task11.task1109;
/*
Как кошка с собакой
*/
public class Solution {
public static void main(String[] args) {
Cat cat = new Cat("Vaska", 5);
Dog dog = new Dog("Sharik", 4);
cat.isDogNear(dog);
dog.isCatNear(cat);
}
public static class Cat {
private String name;
private int speed;
public Cat(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isDogNear(Dog dog) {
return this.speed > dog.getSpeed();
}
}
public static class Dog {
private String name;
private int speed;
public Dog(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isCatNear(Cat cat) {
return this.speed > cat.getSpeed();
}
}
} | biblelamp/JavaExercises | JavaRushTasks/2.JavaCore/src/com/javarush/task/task11/task1109/Solution.java | Java | gpl-2.0 | 1,210 |
/*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.activation;
import java.io.IOException;
/**
* JavaBeans components that are Activation Framework aware implement
* this interface to find out which command verb they're being asked
* to perform, and to obtain the DataHandler representing the
* data they should operate on. JavaBeans that don't implement
* this interface may be used as well. Such commands may obtain
* the data using the Externalizable interface, or using an
* application-specific method.<p>
*
* @since 1.6
*/
public interface CommandObject {
/**
* Initialize the Command with the verb it is requested to handle
* and the DataHandler that describes the data it will
* operate on. <b>NOTE:</b> it is acceptable for the caller
* to pass <i>null</i> as the value for <code>DataHandler</code>.
*
* @param verb The Command Verb this object refers to.
* @param dh The DataHandler.
*/
public void setCommandContext(String verb, DataHandler dh)
throws IOException;
}
| TheTypoMaster/Scaper | openjdk/jaxws/drop_included/jaf_src/src/javax/activation/CommandObject.java | Java | gpl-2.0 | 2,259 |
package edu.xored.tracker;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Issue {
private String hash;
private String summary;
private String description;
private User author;
private Status status;
private LocalDateTime createdDateTime;
@JsonIgnore
private List<Comment> comments = new ArrayList<>();
public Issue() {
}
public Issue(String hash, String summary, String description, Status status) {
this.hash = hash;
this.summary = summary;
this.description = description;
this.status = status;
this.createdDateTime = LocalDateTime.now();
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public LocalDateTime getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(LocalDateTime createdDateTime) {
this.createdDateTime = createdDateTime;
}
public List<Comment> getComments() {
return Collections.unmodifiableList(comments);
}
public void addComment(Comment comment) {
if (comment != null) {
comments.add(comment);
}
}
public void addComments(Collection<Comment> comments) {
if (comments != null) {
this.comments.addAll(comments);
}
}
public Issue updateIssue(Issue other) {
if (other.getSummary() != null) {
setSummary(other.getSummary());
}
if (other.getDescription() != null) {
setDescription(other.getDescription());
}
if (other.getAuthor() != null) {
setAuthor(other.getAuthor());
}
if (other.getStatus() != null) {
setStatus(other.getStatus());
}
if (other.getCreatedDateTime() != null) {
setCreatedDateTime(other.getCreatedDateTime());
}
if (other.getComments() != null) {
addComments(other.getComments());
}
return this;
}
public enum Status {
OPEN, RESOLVED;
}
}
| edu-xored/tracker-web | src/main/java/edu/xored/tracker/Issue.java | Java | gpl-2.0 | 2,861 |
final class Class3_Sub28_Sub2 extends Class3_Sub28 {
private static Class94 aClass94_3541 = Class3_Sub4.buildString("yellow:");
static int anInt3542;
private static Class94 aClass94_3543 = Class3_Sub4.buildString("Loading config )2 ");
static Class94 aClass94_3544 = aClass94_3541;
Class140_Sub2 aClass140_Sub2_3545;
static Class94 aClass94_3546 = aClass94_3543;
static Class94 aClass94_3547 = Class3_Sub4.buildString("Speicher wird zugewiesen)3");
static Class94 aClass94_3548 = aClass94_3541;
public static void method534(int var0) {
try {
aClass94_3546 = null;
aClass94_3548 = null;
aClass94_3543 = null;
int var1 = 101 % ((-29 - var0) / 45);
aClass94_3544 = null;
aClass94_3547 = null;
aClass94_3541 = null;
} catch (RuntimeException var2) {
throw Class44.method1067(var2, "bk.B(" + var0 + ')');
}
}
static final void method535(byte var0, int var1) {
try {
Class151.aFloatArray1934[0] = (float)Class3_Sub28_Sub15.method633(255, var1 >> 16) / 255.0F;
Class151.aFloatArray1934[1] = (float)Class3_Sub28_Sub15.method633(var1 >> 8, 255) / 255.0F;
Class151.aFloatArray1934[2] = (float)Class3_Sub28_Sub15.method633(255, var1) / 255.0F;
Class3_Sub18.method383(-32584, 3);
Class3_Sub18.method383(-32584, 4);
if(var0 != 56) {
method535((byte)127, 99);
}
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.A(" + var0 + ',' + var1 + ')');
}
}
static final Class75_Sub3 method536(byte var0, Class3_Sub30 var1) {
try {
if(var0 != 54) {
method534(117);
}
return new Class75_Sub3(var1.method787((byte)25), var1.method787((byte)73), var1.method787((byte)114), var1.method787((byte)33), var1.method787((byte)78), var1.method787((byte)91), var1.method787((byte)120), var1.method787((byte)113), var1.method794((byte)115), var1.method803((byte)-64));
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.C(" + var0 + ',' + (var1 != null?"{...}":"null") + ')');
}
}
Class3_Sub28_Sub2(Class140_Sub2 var1) {
try {
this.aClass140_Sub2_3545 = var1;
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.<init>(" + (var1 != null?"{...}":"null") + ')');
}
}
}
| Lmctruck30/RiotScape-Client | src/Class3_Sub28_Sub2.java | Java | gpl-2.0 | 2,501 |
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iucn.whp.dbservice.service.persistence;
import com.iucn.whp.dbservice.model.benefit_rating_lkp;
import com.liferay.portal.service.persistence.BasePersistence;
/**
* The persistence interface for the benefit_rating_lkp service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author alok.sen
* @see benefit_rating_lkpPersistenceImpl
* @see benefit_rating_lkpUtil
* @generated
*/
public interface benefit_rating_lkpPersistence extends BasePersistence<benefit_rating_lkp> {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. Always use {@link benefit_rating_lkpUtil} to access the benefit_rating_lkp persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this interface.
*/
/**
* Caches the benefit_rating_lkp in the entity cache if it is enabled.
*
* @param benefit_rating_lkp the benefit_rating_lkp
*/
public void cacheResult(
com.iucn.whp.dbservice.model.benefit_rating_lkp benefit_rating_lkp);
/**
* Caches the benefit_rating_lkps in the entity cache if it is enabled.
*
* @param benefit_rating_lkps the benefit_rating_lkps
*/
public void cacheResult(
java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> benefit_rating_lkps);
/**
* Creates a new benefit_rating_lkp with the primary key. Does not add the benefit_rating_lkp to the database.
*
* @param id the primary key for the new benefit_rating_lkp
* @return the new benefit_rating_lkp
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp create(long id);
/**
* Removes the benefit_rating_lkp with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp that was removed
* @throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp remove(long id)
throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException,
com.liferay.portal.kernel.exception.SystemException;
public com.iucn.whp.dbservice.model.benefit_rating_lkp updateImpl(
com.iucn.whp.dbservice.model.benefit_rating_lkp benefit_rating_lkp,
boolean merge)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the benefit_rating_lkp with the primary key or throws a {@link com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException} if it could not be found.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp
* @throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp findByPrimaryKey(
long id)
throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException,
com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the benefit_rating_lkp with the primary key or returns <code>null</code> if it could not be found.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp, or <code>null</code> if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp fetchByPrimaryKey(
long id) throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns all the benefit_rating_lkps.
*
* @return the benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll()
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns a range of all the benefit_rating_lkps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of benefit_rating_lkps
* @param end the upper bound of the range of benefit_rating_lkps (not inclusive)
* @return the range of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll(
int start, int end)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns an ordered range of all the benefit_rating_lkps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of benefit_rating_lkps
* @param end the upper bound of the range of benefit_rating_lkps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll(
int start, int end,
com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Removes all the benefit_rating_lkps from the database.
*
* @throws SystemException if a system exception occurred
*/
public void removeAll()
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the number of benefit_rating_lkps.
*
* @return the number of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public int countAll()
throws com.liferay.portal.kernel.exception.SystemException;
} | iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/service/persistence/benefit_rating_lkpPersistence.java | Java | gpl-2.0 | 6,928 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.model.dataitem;
import android.content.ContentValues;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
import com.android.contacts.model.RawContact;
/**
* Represents a sip address data item, wrapping the columns in
* {@link ContactsContract.CommonDataKinds.SipAddress}.
*/
public class SipAddressDataItem extends DataItem {
/* package */ SipAddressDataItem(RawContact rawContact, ContentValues values) {
super(rawContact, values);
}
public String getSipAddress() {
return getContentValues().getAsString(SipAddress.SIP_ADDRESS);
}
/**
* Value is one of SipAddress.TYPE_*
*/
public int getType() {
return getContentValues().getAsInteger(SipAddress.TYPE);
}
public String getLabel() {
return getContentValues().getAsString(SipAddress.LABEL);
}
}
| rex-xxx/mt6572_x201 | packages/apps/Contacts/src/com/android/contacts/model/dataitem/SipAddressDataItem.java | Java | gpl-2.0 | 1,543 |
package speiger.src.api.common.recipes.squezingCompressor.parts;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType;
import speiger.src.api.common.recipes.util.RecipeHardness;
import speiger.src.api.common.recipes.util.Result;
public class SqueezerRecipe implements INormalRecipe
{
ItemStack recipeInput;
Result[] result;
public SqueezerRecipe(ItemStack par1, Result...par2)
{
recipeInput = par1;
result = par2;
}
@Override
public ItemStack getItemInput()
{
return recipeInput;
}
@Override
public FluidStack[] getFluidInput()
{
return null;
}
@Override
public Result[] getResults()
{
return result;
}
@Override
public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world)
{
if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize)
{
return true;
}
return false;
}
@Override
public EnumRecipeType getRecipeType()
{
return EnumRecipeType.Sqeezing;
}
@Override
public void runResult(ItemStack input, FluidTank first, FluidTank second, World world)
{
input.stackSize -= recipeInput.stackSize;
}
@Override
public RecipeHardness getComplexity()
{
return RecipeHardness.Extrem_Easy;
}
}
| TinyModularThings/TinyModularThings | src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java | Java | gpl-2.0 | 1,458 |
package gof.structure.proxy;
public class ProxySubject extends Subject {
private RealSubject realSubject;
public ProxySubject(){
}
/* (non-Javadoc)
* @see gof.structure.proxy.Subject#request()
*
* Subject subject = new ProxySubject();
* subject.request();
*/
@Override
public void request() {
preRequest();
if(realSubject == null){
realSubject = new RealSubject();
}
realSubject.request();
postRequest();
}
private void preRequest(){
}
private void postRequest(){
}
}
| expleeve/GoF23 | src/gof/structure/proxy/ProxySubject.java | Java | gpl-2.0 | 560 |
// Wildebeest Migration Framework
// Copyright © 2013 - 2018, Matheson Ventures Pte Ltd
//
// This file is part of Wildebeest
//
// Wildebeest is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License v2 as published by the Free
// Software Foundation.
//
// Wildebeest 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
// Wildebeest. If not, see http://www.gnu.org/licenses/gpl-2.0.html
package co.mv.wb.plugin.generaldatabase.dom;
import co.mv.wb.Asserts;
import co.mv.wb.InvalidReferenceException;
import co.mv.wb.LoaderFault;
import co.mv.wb.ModelExtensions;
import co.mv.wb.PluginBuildException;
import co.mv.wb.Resource;
import co.mv.wb.fixture.Fixtures;
import co.mv.wb.impl.ResourceTypeServiceBuilder;
import co.mv.wb.plugin.base.dom.DomPlugins;
import co.mv.wb.plugin.base.dom.DomResourceLoader;
import co.mv.wb.plugin.generaldatabase.AnsiSqlCreateDatabaseMigration;
import co.mv.wb.plugin.generaldatabase.AnsiSqlDropDatabaseMigration;
import co.mv.wb.plugin.generaldatabase.AnsiSqlTableDoesNotExistAssertion;
import co.mv.wb.plugin.generaldatabase.AnsiSqlTableExistsAssertion;
import co.mv.wb.plugin.postgresql.PostgreSqlConstants;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.Optional;
import java.util.UUID;
/**
* Unit tests for the DOM persistence services for ANSI SQL plugins.
*
* @since 4.0
*/
public class AnsiSqlDomServiceUnitTests
{
@Test
public void ansiSqlCreateDatabaseMigrationLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID migrationId = UUID.randomUUID();
UUID toStateId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.migration("AnsiSqlCreateDatabase", migrationId, null, toStateId.toString())
.render();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size());
AnsiSqlCreateDatabaseMigration mT = ModelExtensions.as(
resource.getMigrations().get(0),
AnsiSqlCreateDatabaseMigration.class);
Assert.assertNotNull(
"resourceWithPlugin.resource.migrations[0] expected to be of type AnsiSqlCreateDatabaseMigration",
mT);
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].id",
migrationId,
mT.getMigrationId());
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].fromStateId",
Optional.empty(),
mT.getFromState());
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].toStateId",
Optional.of(toStateId.toString()),
mT.getToState());
}
@Test
public void ansiSqlDropDatabaseMigrationLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID migrationId = UUID.randomUUID();
String toState = UUID.randomUUID().toString();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.migration("AnsiSqlDropDatabase", migrationId, null, toState.toString())
.render();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size());
AnsiSqlDropDatabaseMigration mT = ModelExtensions.as(
resource.getMigrations().get(0),
AnsiSqlDropDatabaseMigration.class);
Assert.assertNotNull("resource.migrations[0] expected to be of type AnsiSqlDropDatabaseMigration", mT);
Assert.assertEquals(
"resource.migrations[0].id",
migrationId,
mT.getMigrationId());
Assert.assertEquals(
"resource.migrations[0].fromState",
Optional.empty(),
mT.getFromState());
Assert.assertEquals(
"resource.migrations[0].toState",
Optional.of(toState),
mT.getToState());
}
@Test
public void ansiSqlTableExistsAssertionLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID assertionId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.state(UUID.randomUUID(), null)
.assertion("AnsiSqlTableExists", assertionId)
.appendInnerXml("<schemaName>sch</schemaName>")
.appendInnerXml("<tableName>tbl</tableName>")
.build();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.states.size", 1, resource.getStates().size());
Assert.assertEquals(
"resource.states[0].assertions.size",
1,
resource.getStates().get(0).getAssertions().size());
AnsiSqlTableExistsAssertion assertionT = ModelExtensions.as(
resource.getStates().get(0).getAssertions().get(0),
AnsiSqlTableExistsAssertion.class);
Assert.assertNotNull("Expected to be an AnsiSqlTableExistsAssertion", assertionT);
Asserts.assertAnsiSqlTableExistsAssertion(
assertionId,
"sch",
"tbl",
assertionT,
"resource.states[0].assertions[0]");
}
@Test
public void ansiSqlTableDoesNotExistAssertionLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID assertionId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.state(UUID.randomUUID(), null)
.assertion("AnsiSqlTableDoesNotExist", assertionId)
.appendInnerXml("<schemaName>sch</schemaName>")
.appendInnerXml("<tableName>tbl</tableName>")
.build();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.states.size", 1, resource.getStates().size());
Assert.assertEquals(
"resource.states[0].assertions.size",
1,
resource.getStates().get(0).getAssertions().size());
AnsiSqlTableDoesNotExistAssertion assertionT = ModelExtensions.as(
resource.getStates().get(0).getAssertions().get(0),
AnsiSqlTableDoesNotExistAssertion.class);
Assert.assertNotNull("Expected to be an AnsiSqlTableDoesNotExistAssertion", assertionT);
Asserts.assertAnsiSqlTableDoesNotExistAssertion(
assertionId,
"sch",
"tbl",
assertionT,
"resource.states[0].assertions[0]");
}
}
| zendigitalstudios/wildebeest | MV.Wildebeest.Core/source/test/java/co/mv/wb/plugin/generaldatabase/dom/AnsiSqlDomServiceUnitTests.java | Java | gpl-2.0 | 7,441 |
package app.toonido.mindorks.toonido;
import android.app.Application;
import com.parse.Parse;
/**
* Created by janisharali on 30/09/15.
*/
public class ToonidoApp extends Application {
@Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
Parse.initialize(this, ToonidoConstants.PARSE_APPLICATION_ID, ToonidoConstants.PARSE_CLIENT_KEY);
}
}
| mindorks/Toonido | Toonido/app/src/main/java/app/toonido/mindorks/toonido/ToonidoApp.java | Java | gpl-2.0 | 451 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androidtweak.inputmethod.myanmar;
import android.content.Context;
import com.androidtweak.inputmethod.keyboard.ProximityInfo;
public class SynchronouslyLoadedUserBinaryDictionary extends UserBinaryDictionary {
public SynchronouslyLoadedUserBinaryDictionary(final Context context, final String locale) {
this(context, locale, false);
}
public SynchronouslyLoadedUserBinaryDictionary(final Context context, final String locale,
final boolean alsoUseMoreRestrictiveLocales) {
super(context, locale, alsoUseMoreRestrictiveLocales);
}
@Override
public synchronized void getWords(final WordComposer codes,
final CharSequence prevWordForBigrams, final WordCallback callback,
final ProximityInfo proximityInfo) {
syncReloadDictionaryIfRequired();
getWordsInner(codes, prevWordForBigrams, callback, proximityInfo);
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
syncReloadDictionaryIfRequired();
return isValidWordInner(word);
}
}
| soeminnminn/MyanmarIME | src/com/androidtweak/inputmethod/myanmar/SynchronouslyLoadedUserBinaryDictionary.java | Java | gpl-2.0 | 1,712 |
package com.atux.bean.consulta;
import com.atux.comun.FilterBaseLocal;
/**
* Created by MATRIX-JAVA on 27/11/2014.
*/
public class UnidadFlt extends FilterBaseLocal {
public static final String PICK = "PICK";
public UnidadFlt(String unidad) {
this.unidad = unidad;
}
public UnidadFlt() {
}
private String unidad;
private String coUnidad;
public String getUnidad() {
return unidad;
}
public void setUnidad(String unidad) {
this.unidad = unidad;
}
public String getCoUnidad() {
return coUnidad;
}
public void setCoUnidad(String coUnidad) {
this.coUnidad = coUnidad;
}
}
| AlanGuerraQuispe/SisAtuxVenta | atux-domain/src/main/java/com/atux/bean/consulta/UnidadFlt.java | Java | gpl-2.0 | 719 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
public abstract class PResource extends Node
{
// Empty body
}
| kompics/kola | src/main/java/se/sics/kola/node/PResource.java | Java | gpl-2.0 | 164 |
package uq.androidhack.flashspeak;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import uq.androidhack.flashspeak.interfaces.TargetFileListener;
import uq.androidhack.flashspeak.interfaces.TrialFileListener;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link VisualisationFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link VisualisationFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class VisualisationFragment extends Fragment implements TargetFileListener,TrialFileListener{
private OnFragmentInteractionListener mListener;
//Here is your URL defined
String url = "http://vprbbc.streamguys.net/vprbbc24.mp3";
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment VisualisationFragment.
*/
public static VisualisationFragment newInstance() {
VisualisationFragment fragment = new VisualisationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public VisualisationFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_visualisation, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onFileChange(String uri) {
File file = new File (uri);
ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation);
ogAudioSampleImageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));
}
@Override
public void onRecording(URI uri) {
ImageView targetAudioSampleImageView = (ImageView)getView().findViewById(R.id.usersAudioSampleVisualisation);
targetAudioSampleImageView.setImageResource(android.R.color.transparent);
}
@Override
public void onFinishProcessing(String b) {
Log.i("VISUALIZER", "in HERE!");
ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation);
//ogAudioSampleImageView.setImageURI(new URI(b));
new DownloadImageTask(ogAudioSampleImageView).execute(b);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Bitmap uri);
}
}
| andyepx/flashspeak | app/src/main/java/uq/androidhack/flashspeak/VisualisationFragment.java | Java | gpl-2.0 | 5,028 |
package jrpsoft;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import java.util.Random;
public class Fantasma extends Actor {
protected static final int FANTASMA_SPEED = 1;
public boolean up, down, right, left;
static Boolean[] dir = new Boolean[4];
int avazarA = 0;
Random random;
public Fantasma(Point puntoIncio, Color colorPrincipal) {
super(puntoIncio, colorPrincipal);
random = new Random();
}
public Point getPoint() {
return p;
}
public void paint(Graphics2D g2) {
g2.setColor(color);
Point pixelPoint = Director.getPxOfCell(p);
Ellipse2D fantasma = new Ellipse2D.Float(pixelPoint.x, pixelPoint.y,
diametro, diametro);
g2.fill(fantasma);
g2.fill(new Ellipse2D.Float(pixelPoint.x - 1, pixelPoint.y + 12, diametro / 2, diametro / 2));
g2.fill(new Ellipse2D.Float(pixelPoint.x + 5, pixelPoint.y + 12, diametro / 2, diametro / 2));
g2.fill(new Ellipse2D.Float(pixelPoint.x + 11, pixelPoint.y + 12, diametro / 2, diametro / 2));
}
public void mover(Pacman pacman, Tablero tablero) {
/*
* System.out.println("ee "+(random.nextInt(5)));
* if(random.nextInt(5)==0){ avanzar((random.nextInt(4)+1),tablero); }
*/
// avazarA=movAleatorio(tablero);
//System.err.println(p);
// avazarA=0;
Astar.getAstar().getPath(p, pacman.p);
Point nextPoint=Astar.getAstar().getNextPoint();
avanzar(getDirToPoint(nextPoint), tablero);
}
/*@SuppressWarnings("unused")
private int movAleatorio(Tablero tablero) {
Point aux = (Point) p.clone();
int randDir = 0;
do {
aux = reverseTranslateDir(aux, randDir);
randDir = random.nextInt(4) + 1;
translateDir(aux, randDir);
// System.out.print("\nwhiling"+randDir+" px:"+aux.x+" py:"+aux.y);
} while (!tablero.isWalkable(aux));
return randDir;
}*/
private void avanzar(int dir, Tablero tablero) {
p=translateDir(p,dir);
/*Point anterior = (Point) p.clone();
translateDir(p, dir);
if (!tablero.isWalkable(p)) {
p = anterior;
}*/
}
public Point translateDir(Point p, int dir) {
switch (dir) {
case DUP:
p.y += UP;
break;
case DDOWN:
p.y += DOWN;
break;
case DLEFT:
p.x += LEFT;
break;
case DRIGHT:
p.x += RIGHT;
break;
default:
break;
}
return p;
}
/*
public Point reverseTranslateDir(Point p, int dir) {
switch (dir) {
case DUP:
p.y -= UP;
break;
case DDOWN:
p.y -= DOWN;
break;
case DLEFT:
p.x -= LEFT;
break;
case DRIGHT:
p.x -= RIGHT;
break;
default:
break;
}
return p;
}
*/
}
| jesusnoseq/JComococos | src/jrpsoft/Fantasma.java | Java | gpl-2.0 | 2,570 |
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package freenet.clients.http;
////import org.tanukisoftware.wrapper.WrapperManager;
import freenet.client.filter.HTMLFilter;
import freenet.client.filter.LinkFilterExceptionProvider;
import freenet.clients.http.FProxyFetchInProgress.REFILTER_POLICY;
import freenet.clients.http.PageMaker.THEME;
import freenet.clients.http.bookmark.BookmarkManager;
import freenet.clients.http.updateableelements.PushDataManager;
import freenet.config.EnumerableOptionCallback;
import freenet.config.InvalidConfigValueException;
import freenet.config.NodeNeedRestartException;
import freenet.config.SubConfig;
import freenet.crypt.SSL;
import freenet.io.AllowedHosts;
import freenet.io.NetworkInterface;
import freenet.io.SSLNetworkInterface;
import freenet.keys.FreenetURI;
import freenet.l10n.NodeL10n;
import freenet.node.Node;
import freenet.node.NodeClientCore;
import freenet.node.PrioRunnable;
import freenet.node.SecurityLevelListener;
import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL;
import freenet.node.SecurityLevels.PHYSICAL_THREAT_LEVEL;
import freenet.node.useralerts.UserAlertManager;
import freenet.pluginmanager.FredPluginL10n;
import freenet.support.*;
import freenet.support.Logger.LogLevel;
import freenet.support.api.*;
import freenet.support.io.ArrayBucketFactory;
import freenet.support.io.NativeThread;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
/**
* The Toadlet (HTTP) Server
*
* Provide a HTTP server for FProxy
*/
public final class SimpleToadletServer implements ToadletContainer, Runnable, LinkFilterExceptionProvider {
/** List of urlPrefix / Toadlet */
private final LinkedList<ToadletElement> toadlets;
private static class ToadletElement {
public ToadletElement(Toadlet t2, String urlPrefix, String menu, String name) {
t = t2;
prefix = urlPrefix;
this.menu = menu;
this.name = name;
}
Toadlet t;
String prefix;
String menu;
String name;
}
// Socket / Binding
private final int port;
private String bindTo;
private String allowedHosts;
private NetworkInterface networkInterface;
private boolean ssl = false;
public static final int DEFAULT_FPROXY_PORT = 8888;
// ACL
private final AllowedHosts allowedFullAccess;
private boolean publicGatewayMode;
private final boolean wasPublicGatewayMode;
// Theme
private THEME cssTheme;
private File cssOverride;
private boolean sendAllThemes;
private boolean advancedModeEnabled;
private final PageMaker pageMaker;
// Control
private Thread myThread;
private final Executor executor;
private final Random random;
private BucketFactory bf;
private volatile NodeClientCore core;
// HTTP Option
private boolean doRobots;
private boolean enablePersistentConnections;
private boolean enableInlinePrefetch;
private boolean enableActivelinks;
private boolean enableExtendedMethodHandling;
// Something does not really belongs to here
volatile static boolean isPanicButtonToBeShown; // move to QueueToadlet ?
volatile static boolean noConfirmPanic;
public BookmarkManager bookmarkManager; // move to WelcomeToadlet / BookmarkEditorToadlet ?
private volatile boolean fProxyJavascriptEnabled; // ugh?
private volatile boolean fProxyWebPushingEnabled; // ugh?
private volatile boolean fproxyHasCompletedWizard; // hmmm..
private volatile boolean disableProgressPage;
private int maxFproxyConnections;
private int fproxyConnections;
private boolean finishedStartup;
/** The PushDataManager handles all the pushing tasks*/
public PushDataManager pushDataManager;
/** The IntervalPusherManager handles interval pushing*/
public IntervalPusherManager intervalPushManager;
private static volatile boolean logMINOR;
static {
Logger.registerLogThresholdCallback(new LogThresholdCallback(){
@Override
public void shouldUpdate(){
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
}
});
}
// Config Callbacks
private class FProxySSLCallback extends BooleanCallback {
@Override
public Boolean get() {
return ssl;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
if (get().equals(val))
return;
if(!SSL.available()) {
throw new InvalidConfigValueException("Enable SSL support before use ssl with Fproxy");
}
ssl = val;
throw new InvalidConfigValueException("Cannot change SSL on the fly, please restart freenet");
}
@Override
public boolean isReadOnly() {
return true;
}
}
private static class FProxyPassthruMaxSizeNoProgress extends LongCallback {
@Override
public Long get() {
return FProxyToadlet.MAX_LENGTH_NO_PROGRESS;
}
@Override
public void set(Long val) throws InvalidConfigValueException {
if (get().equals(val))
return;
FProxyToadlet.MAX_LENGTH_NO_PROGRESS = val;
}
}
private static class FProxyPassthruMaxSizeProgress extends LongCallback {
@Override
public Long get() {
return FProxyToadlet.MAX_LENGTH_WITH_PROGRESS;
}
@Override
public void set(Long val) throws InvalidConfigValueException {
if (get().equals(val))
return;
FProxyToadlet.MAX_LENGTH_WITH_PROGRESS = val;
}
}
private class FProxyPortCallback extends IntCallback {
@Override
public Integer get() {
return port;
}
@Override
public void set(Integer newPort) throws NodeNeedRestartException {
if(port != newPort) {
throw new NodeNeedRestartException("Port cannot change on the fly");
}
}
}
private class FProxyBindtoCallback extends StringCallback {
@Override
public String get() {
return bindTo;
}
@Override
public void set(String bindTo) throws InvalidConfigValueException {
String oldValue = get();
if(!bindTo.equals(oldValue)) {
String[] failedAddresses = networkInterface.setBindTo(bindTo, false);
if(failedAddresses == null) {
SimpleToadletServer.this.bindTo = bindTo;
} else {
// This is an advanced option for reasons of reducing clutter,
// but it is expected to be used by regular users, not devs.
// So we translate the error messages.
networkInterface.setBindTo(oldValue, false);
throw new InvalidConfigValueException(l10n("couldNotChangeBindTo", "failedInterfaces", Arrays.toString(failedAddresses)));
}
}
}
}
private class FProxyAllowedHostsCallback extends StringCallback {
@Override
public String get() {
return networkInterface.getAllowedHosts();
}
@Override
public void set(String allowedHosts) throws InvalidConfigValueException {
if (!allowedHosts.equals(get())) {
try {
networkInterface.setAllowedHosts(allowedHosts);
} catch(IllegalArgumentException e) {
throw new InvalidConfigValueException(e);
}
}
}
}
private class FProxyCSSNameCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
return cssTheme.code;
}
@Override
public void set(String CSSName) throws InvalidConfigValueException {
if((CSSName.indexOf(':') != -1) || (CSSName.indexOf('/') != -1))
throw new InvalidConfigValueException(l10n("illegalCSSName"));
cssTheme = THEME.themeFromName(CSSName);
pageMaker.setTheme(cssTheme);
NodeClientCore core = SimpleToadletServer.this.core;
if (core.node.pluginManager != null)
core.node.pluginManager.setFProxyTheme(cssTheme);
}
@Override
public String[] getPossibleValues() {
return THEME.possibleValues;
}
}
private class FProxyCSSOverrideCallback extends StringCallback {
@Override
public String get() {
return (cssOverride == null ? "" : cssOverride.toString());
}
@Override
public void set(String val) throws InvalidConfigValueException {
NodeClientCore core = SimpleToadletServer.this.core;
if(core == null) return;
if(val.equals(get()) || val.equals(""))
cssOverride = null;
else {
File tmp = new File(val.trim());
if(!core.allowUploadFrom(tmp))
throw new InvalidConfigValueException(l10n("cssOverrideNotInUploads", "filename", tmp.toString()));
else if(!tmp.canRead() || !tmp.isFile())
throw new InvalidConfigValueException(l10n("cssOverrideCantRead", "filename", tmp.toString()));
File parent = tmp.getParentFile();
// Basic sanity check.
// Prevents user from specifying root dir.
// They can still shoot themselves in the foot, but only when developing themes/using custom themes.
// Because of the .. check above, any malicious thing cannot break out of the dir anyway.
if(parent.getParentFile() == null)
throw new InvalidConfigValueException(l10n("cssOverrideCantUseRootDir", "filename", parent.toString()));
cssOverride = tmp;
}
if(cssOverride == null)
pageMaker.setOverride(null);
else {
pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName());
}
}
}
private class FProxyEnabledCallback extends BooleanCallback {
@Override
public Boolean get() {
synchronized(SimpleToadletServer.this) {
return myThread != null;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
if (get().equals(val))
return;
synchronized(SimpleToadletServer.this) {
if(val) {
// Start it
myThread = new Thread(SimpleToadletServer.this, "SimpleToadletServer");
} else {
myThread.interrupt();
myThread = null;
SimpleToadletServer.this.notifyAll();
return;
}
}
createFproxy();
myThread.setDaemon(true);
myThread.start();
}
}
private static class FProxyAdvancedModeEnabledCallback extends BooleanCallback {
private final SimpleToadletServer ts;
FProxyAdvancedModeEnabledCallback(SimpleToadletServer ts){
this.ts = ts;
}
@Override
public Boolean get() {
return ts.isAdvancedModeEnabled();
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
ts.setAdvancedMode(val);
}
}
private static class FProxyJavascriptEnabledCallback extends BooleanCallback {
private final SimpleToadletServer ts;
FProxyJavascriptEnabledCallback(SimpleToadletServer ts){
this.ts = ts;
}
@Override
public Boolean get() {
return ts.isFProxyJavascriptEnabled();
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
if (get().equals(val))
return;
ts.enableFProxyJavascript(val);
}
}
private static class FProxyWebPushingEnabledCallback extends BooleanCallback{
private final SimpleToadletServer ts;
FProxyWebPushingEnabledCallback(SimpleToadletServer ts){
this.ts=ts;
}
@Override
public Boolean get() {
return ts.isFProxyWebPushingEnabled();
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if (get().equals(val))
return;
ts.enableFProxyWebPushing(val);
}
}
private boolean haveCalledFProxy = false;
// FIXME factor this out to a global helper class somehow?
private class ReFilterCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String[] getPossibleValues() {
REFILTER_POLICY[] possible = REFILTER_POLICY.values();
String[] ret = new String[possible.length];
for(int i=0;i<possible.length;i++)
ret[i] = possible[i].name();
return ret;
}
@Override
public String get() {
return refilterPolicy.name();
}
@Override
public void set(String val) throws InvalidConfigValueException,
NodeNeedRestartException {
refilterPolicy = REFILTER_POLICY.valueOf(val);
}
};
public void createFproxy() {
NodeClientCore core = this.core;
Node node = core.node;
synchronized(this) {
if(haveCalledFProxy) return;
haveCalledFProxy = true;
}
pushDataManager=new PushDataManager(getTicker());
intervalPushManager=new IntervalPusherManager(getTicker(), pushDataManager);
bookmarkManager = new BookmarkManager(core, publicGatewayMode());
try {
FProxyToadlet.maybeCreateFProxyEtc(core, node, node.config, this);
} catch (IOException e) {
Logger.error(this, "Could not start fproxy: "+e, e);
System.err.println("Could not start fproxy:");
e.printStackTrace();
}
}
public void setCore(NodeClientCore core) {
this.core = core;
}
/**
* Create a SimpleToadletServer, using the settings from the SubConfig (the fproxy.*
* config).
*/
public SimpleToadletServer(SubConfig fproxyConfig, BucketFactory bucketFactory, Executor executor, Node node) throws IOException, InvalidConfigValueException {
this.executor = executor;
this.core = null; // setCore() will be called later.
this.random = new Random();
int configItemOrder = 0;
fproxyConfig.register("enabled", true, configItemOrder++, true, true, "SimpleToadletServer.enabled", "SimpleToadletServer.enabledLong",
new FProxyEnabledCallback());
boolean enabled = fproxyConfig.getBoolean("enabled");
fproxyConfig.register("ssl", false, configItemOrder++, true, true, "SimpleToadletServer.ssl", "SimpleToadletServer.sslLong",
new FProxySSLCallback());
fproxyConfig.register("port", DEFAULT_FPROXY_PORT, configItemOrder++, true, true, "SimpleToadletServer.port", "SimpleToadletServer.portLong",
new FProxyPortCallback(), false);
fproxyConfig.register("bindTo", NetworkInterface.DEFAULT_BIND_TO, configItemOrder++, true, true, "SimpleToadletServer.bindTo", "SimpleToadletServer.bindToLong",
new FProxyBindtoCallback());
fproxyConfig.register("css", "clean-dropdown", configItemOrder++, false, false, "SimpleToadletServer.cssName", "SimpleToadletServer.cssNameLong",
new FProxyCSSNameCallback());
fproxyConfig.register("CSSOverride", "", configItemOrder++, true, false, "SimpleToadletServer.cssOverride", "SimpleToadletServer.cssOverrideLong",
new FProxyCSSOverrideCallback());
fproxyConfig.register("sendAllThemes", false, configItemOrder++, true, false, "SimpleToadletServer.sendAllThemes", "SimpleToadletServer.sendAllThemesLong",
new BooleanCallback() {
@Override
public Boolean get() {
return sendAllThemes;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
sendAllThemes = val;
}
});
sendAllThemes = fproxyConfig.getBoolean("sendAllThemes");
fproxyConfig.register("advancedModeEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.advancedMode", "SimpleToadletServer.advancedModeLong",
new FProxyAdvancedModeEnabledCallback(this));
fproxyConfig.register("enableExtendedMethodHandling", false, configItemOrder++, true, false, "SimpleToadletServer.enableExtendedMethodHandling", "SimpleToadletServer.enableExtendedMethodHandlingLong",
new BooleanCallback() {
@Override
public Boolean get() {
return enableExtendedMethodHandling;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if(get().equals(val)) return;
enableExtendedMethodHandling = val;
}
});
fproxyConfig.register("javascriptEnabled", true, configItemOrder++, true, false, "SimpleToadletServer.enableJS", "SimpleToadletServer.enableJSLong",
new FProxyJavascriptEnabledCallback(this));
fproxyConfig.register("webPushingEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.enableWP", "SimpleToadletServer.enableWPLong", new FProxyWebPushingEnabledCallback(this));
fproxyConfig.register("hasCompletedWizard", false, configItemOrder++, true, false, "SimpleToadletServer.hasCompletedWizard", "SimpleToadletServer.hasCompletedWizardLong",
new BooleanCallback() {
@Override
public Boolean get() {
return fproxyHasCompletedWizard;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if(get().equals(val)) return;
fproxyHasCompletedWizard = val;
}
});
fproxyConfig.register("disableProgressPage", false, configItemOrder++, true, false, "SimpleToadletServer.disableProgressPage", "SimpleToadletServer.disableProgressPageLong",
new BooleanCallback() {
@Override
public Boolean get() {
return disableProgressPage;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
disableProgressPage = val;
}
});
fproxyHasCompletedWizard = fproxyConfig.getBoolean("hasCompletedWizard");
fProxyJavascriptEnabled = fproxyConfig.getBoolean("javascriptEnabled");
fProxyWebPushingEnabled = fproxyConfig.getBoolean("webPushingEnabled");
disableProgressPage = fproxyConfig.getBoolean("disableProgressPage");
enableExtendedMethodHandling = fproxyConfig.getBoolean("enableExtendedMethodHandling");
fproxyConfig.register("showPanicButton", false, configItemOrder++, true, true, "SimpleToadletServer.panicButton", "SimpleToadletServer.panicButtonLong",
new BooleanCallback(){
@Override
public Boolean get() {
return SimpleToadletServer.isPanicButtonToBeShown;
}
@Override
public void set(Boolean value) {
if(value == SimpleToadletServer.isPanicButtonToBeShown) return;
else SimpleToadletServer.isPanicButtonToBeShown = value;
}
});
fproxyConfig.register("noConfirmPanic", false, configItemOrder++, true, true, "SimpleToadletServer.noConfirmPanic", "SimpleToadletServer.noConfirmPanicLong",
new BooleanCallback() {
@Override
public Boolean get() {
return SimpleToadletServer.noConfirmPanic;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if(val == SimpleToadletServer.noConfirmPanic) return;
else SimpleToadletServer.noConfirmPanic = val;
}
});
fproxyConfig.register("publicGatewayMode", false, configItemOrder++, true, true, "SimpleToadletServer.publicGatewayMode", "SimpleToadletServer.publicGatewayModeLong", new BooleanCallback() {
@Override
public Boolean get() {
return publicGatewayMode;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if(publicGatewayMode == val) return;
publicGatewayMode = val;
throw new NodeNeedRestartException(l10n("publicGatewayModeNeedsRestart"));
}
});
wasPublicGatewayMode = publicGatewayMode = fproxyConfig.getBoolean("publicGatewayMode");
// This is OFF BY DEFAULT because for example firefox has a limit of 2 persistent
// connections per server, but 8 non-persistent connections per server. We need 8 conns
// more than we need the efficiency gain of reusing connections - especially on first
// install.
fproxyConfig.register("enablePersistentConnections", false, configItemOrder++, true, false, "SimpleToadletServer.enablePersistentConnections", "SimpleToadletServer.enablePersistentConnectionsLong",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(SimpleToadletServer.this) {
return enablePersistentConnections;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
synchronized(SimpleToadletServer.this) {
enablePersistentConnections = val;
}
}
});
enablePersistentConnections = fproxyConfig.getBoolean("enablePersistentConnections");
// Off by default.
// I had hoped it would yield a significant performance boost to bootstrap performance
// on browsers with low numbers of simultaneous connections. Unfortunately the bottleneck
// appears to be that the node does very few local requests compared to external requests
// (for anonymity's sake).
fproxyConfig.register("enableInlinePrefetch", false, configItemOrder++, true, false, "SimpleToadletServer.enableInlinePrefetch", "SimpleToadletServer.enableInlinePrefetchLong",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(SimpleToadletServer.this) {
return enableInlinePrefetch;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
synchronized(SimpleToadletServer.this) {
enableInlinePrefetch = val;
}
}
});
enableInlinePrefetch = fproxyConfig.getBoolean("enableInlinePrefetch");
fproxyConfig.register("enableActivelinks", false, configItemOrder++, false, false, "SimpleToadletServer.enableActivelinks", "SimpleToadletServer.enableActivelinksLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableActivelinks;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
enableActivelinks = val;
}
});
enableActivelinks = fproxyConfig.getBoolean("enableActivelinks");
fproxyConfig.register("passthroughMaxSize", FProxyToadlet.MAX_LENGTH_NO_PROGRESS, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSize", "SimpleToadletServer.passthroughMaxSizeLong", new FProxyPassthruMaxSizeNoProgress(), true);
FProxyToadlet.MAX_LENGTH_NO_PROGRESS = fproxyConfig.getLong("passthroughMaxSize");
fproxyConfig.register("passthroughMaxSizeProgress", FProxyToadlet.MAX_LENGTH_WITH_PROGRESS, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSizeProgress", "SimpleToadletServer.passthroughMaxSizeProgressLong", new FProxyPassthruMaxSizeProgress(), true);
FProxyToadlet.MAX_LENGTH_WITH_PROGRESS = fproxyConfig.getLong("passthroughMaxSizeProgress");
System.out.println("Set fproxy max length to "+FProxyToadlet.MAX_LENGTH_NO_PROGRESS+" and max length with progress to "+FProxyToadlet.MAX_LENGTH_WITH_PROGRESS+" = "+fproxyConfig.getLong("passthroughMaxSizeProgress"));
fproxyConfig.register("allowedHosts", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedHosts", "SimpleToadletServer.allowedHostsLong",
new FProxyAllowedHostsCallback());
fproxyConfig.register("allowedHostsFullAccess", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedFullAccess",
"SimpleToadletServer.allowedFullAccessLong",
new StringCallback() {
@Override
public String get() {
return allowedFullAccess.getAllowedHosts();
}
@Override
public void set(String val) throws InvalidConfigValueException {
try {
allowedFullAccess.setAllowedHosts(val);
} catch(IllegalArgumentException e) {
throw new InvalidConfigValueException(e);
}
}
});
allowedFullAccess = new AllowedHosts(fproxyConfig.getString("allowedHostsFullAccess"));
fproxyConfig.register("doRobots", false, configItemOrder++, true, false, "SimpleToadletServer.doRobots", "SimpleToadletServer.doRobotsLong",
new BooleanCallback() {
@Override
public Boolean get() {
return doRobots;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
doRobots = val;
}
});
doRobots = fproxyConfig.getBoolean("doRobots");
// We may not know what the overall thread limit is yet so just set it to 100.
fproxyConfig.register("maxFproxyConnections", 100, configItemOrder++, true, false, "SimpleToadletServer.maxFproxyConnections", "SimpleToadletServer.maxFproxyConnectionsLong",
new IntCallback() {
@Override
public Integer get() {
synchronized(SimpleToadletServer.this) {
return maxFproxyConnections;
}
}
@Override
public void set(Integer val) {
synchronized(SimpleToadletServer.this) {
maxFproxyConnections = val;
SimpleToadletServer.this.notifyAll();
}
}
}, false);
maxFproxyConnections = fproxyConfig.getInt("maxFproxyConnections");
fproxyConfig.register("metaRefreshSamePageInterval", 1, configItemOrder++, true, false, "SimpleToadletServer.metaRefreshSamePageInterval", "SimpleToadletServer.metaRefreshSamePageIntervalLong",
new IntCallback() {
@Override
public Integer get() {
return HTMLFilter.metaRefreshSamePageMinInterval;
}
@Override
public void set(Integer val)
throws InvalidConfigValueException,
NodeNeedRestartException {
if(val < -1) throw new InvalidConfigValueException("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n
HTMLFilter.metaRefreshSamePageMinInterval = val;
}
}, false);
HTMLFilter.metaRefreshSamePageMinInterval = Math.max(-1, fproxyConfig.getInt("metaRefreshSamePageInterval"));
fproxyConfig.register("metaRefreshRedirectInterval", 1, configItemOrder++, true, false, "SimpleToadletServer.metaRefreshRedirectInterval", "SimpleToadletServer.metaRefreshRedirectIntervalLong",
new IntCallback() {
@Override
public Integer get() {
return HTMLFilter.metaRefreshRedirectMinInterval;
}
@Override
public void set(Integer val)
throws InvalidConfigValueException,
NodeNeedRestartException {
if(val < -1) throw new InvalidConfigValueException("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n
HTMLFilter.metaRefreshRedirectMinInterval = val;
}
}, false);
HTMLFilter.metaRefreshRedirectMinInterval = Math.max(-1, fproxyConfig.getInt("metaRefreshRedirectInterval"));
fproxyConfig.register("refilterPolicy", "RE_FILTER",
configItemOrder++, true, false, "SimpleToadletServer.refilterPolicy", "SimpleToadletServer.refilterPolicyLong", new ReFilterCallback());
this.refilterPolicy = REFILTER_POLICY.valueOf(fproxyConfig.getString("refilterPolicy"));
// Network seclevel not physical seclevel because bad filtering can cause network level anonymity breaches.
SimpleToadletServer.isPanicButtonToBeShown = fproxyConfig.getBoolean("showPanicButton");
SimpleToadletServer.noConfirmPanic = fproxyConfig.getBoolean("noConfirmPanic");
this.bf = bucketFactory;
port = fproxyConfig.getInt("port");
bindTo = fproxyConfig.getString("bindTo");
String cssName = fproxyConfig.getString("css");
if((cssName.indexOf(':') != -1) || (cssName.indexOf('/') != -1))
throw new InvalidConfigValueException("CSS name must not contain slashes or colons!");
cssTheme = THEME.themeFromName(cssName);
pageMaker = new PageMaker(cssTheme, node);
if(!fproxyConfig.getOption("CSSOverride").isDefault()) {
cssOverride = new File(fproxyConfig.getString("CSSOverride"));
pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName());
} else {
cssOverride = null;
pageMaker.setOverride(null);
}
this.advancedModeEnabled = fproxyConfig.getBoolean("advancedModeEnabled");
toadlets = new LinkedList<ToadletElement>();
if(SSL.available()) {
ssl = fproxyConfig.getBoolean("ssl");
}
this.allowedHosts=fproxyConfig.getString("allowedHosts");
if(!enabled) {
Logger.normal(SimpleToadletServer.this, "Not starting FProxy as it's disabled");
System.out.println("Not starting FProxy as it's disabled");
} else {
maybeGetNetworkInterface();
myThread = new Thread(this, "SimpleToadletServer");
myThread.setDaemon(true);
}
// Register static toadlet and startup toadlet
StaticToadlet statictoadlet = new StaticToadlet();
register(statictoadlet, null, "/static/", false, false);
// "Freenet is starting up..." page, to be removed at #removeStartupToadlet()
startupToadlet = new StartupToadlet(statictoadlet);
register(startupToadlet, null, "/", false, false);
}
public StartupToadlet startupToadlet;
public void removeStartupToadlet() {
// setCore() must have been called first. It is in fact called much earlier on.
synchronized(this) {
unregister(startupToadlet);
// Ready to be GCed
startupToadlet = null;
// Not in the navbar.
}
}
private void maybeGetNetworkInterface() throws IOException {
if (this.networkInterface!=null) return;
if(ssl) {
this.networkInterface = SSLNetworkInterface.create(port, this.bindTo, allowedHosts, executor, true);
} else {
this.networkInterface = NetworkInterface.create(port, this.bindTo, allowedHosts, executor, true);
}
}
@Override
public boolean doRobots() {
return doRobots;
}
@Override
public boolean publicGatewayMode() {
return wasPublicGatewayMode;
}
public void start() {
if(myThread != null) try {
maybeGetNetworkInterface();
myThread.start();
Logger.normal(this, "Starting FProxy on "+bindTo+ ':' +port);
System.out.println("Starting FProxy on "+bindTo+ ':' +port);
} catch (IOException e) {
Logger.error(this, "Could not bind network port for FProxy?", e);
}
}
public void finishStart() {
core.node.securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel,
NETWORK_THREAT_LEVEL newLevel) {
// At LOW, we do ACCEPT_OLD.
// Otherwise we do RE_FILTER.
// But we don't change it unless it changes from LOW to not LOW.
if(newLevel == NETWORK_THREAT_LEVEL.LOW && newLevel != oldLevel) {
refilterPolicy = REFILTER_POLICY.ACCEPT_OLD;
} else if(oldLevel == NETWORK_THREAT_LEVEL.LOW && newLevel != oldLevel) {
refilterPolicy = REFILTER_POLICY.RE_FILTER;
}
}
});
core.node.securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<PHYSICAL_THREAT_LEVEL> () {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
if(newLevel != oldLevel && newLevel == PHYSICAL_THREAT_LEVEL.LOW) {
isPanicButtonToBeShown = false;
} else if(newLevel != oldLevel) {
isPanicButtonToBeShown = true;
}
}
});
synchronized(this) {
finishedStartup = true;
}
}
@Override
public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, boolean fullOnly) {
register(t, menu, urlPrefix, atFront, null, null, fullOnly, null, null);
}
@Override
public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb) {
register(t, menu, urlPrefix, atFront, name, title, fullOnly, cb, null);
}
@Override
public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb, FredPluginL10n l10n) {
ToadletElement te = new ToadletElement(t, urlPrefix, menu, name);
synchronized(toadlets) {
if(atFront) toadlets.addFirst(te);
else toadlets.addLast(te);
t.container = this;
}
if (menu != null && name != null) {
pageMaker.addNavigationLink(menu, urlPrefix, name, title, fullOnly, cb, l10n);
}
}
public void registerMenu(String link, String name, String title, FredPluginL10n plugin) {
pageMaker.addNavigationCategory(link, name, title, plugin);
}
@Override
public void unregister(Toadlet t) {
ToadletElement e = null;
synchronized(toadlets) {
for(Iterator<ToadletElement> i=toadlets.iterator();i.hasNext();) {
e = i.next();
if(e.t == t) {
i.remove();
break;
}
}
}
if(e != null && e.t == t) {
if(e.menu != null && e.name != null) {
pageMaker.removeNavigationLink(e.menu, e.name);
}
}
}
public StartupToadlet getStartupToadlet() {
return startupToadlet;
}
@Override
public boolean fproxyHasCompletedWizard() {
return fproxyHasCompletedWizard;
}
@Override
public Toadlet findToadlet(URI uri) throws PermanentRedirectException {
String path = uri.getPath();
// Show the wizard until dismissed by the user (See bug #2624)
NodeClientCore core = this.core;
if(core != null && core.node != null && !fproxyHasCompletedWizard) {
//If the user has not completed the wizard, only allow access to the wizard and static
//resources. Anything else redirects to the first page of the wizard.
if (!(path.startsWith(FirstTimeWizardToadlet.TOADLET_URL) ||
path.startsWith(StaticToadlet.ROOT_URL) ||
path.startsWith(ExternalLinkToadlet.PATH) ||
path.equals("/favicon.ico"))) {
try {
throw new PermanentRedirectException(new URI(null, null, null, -1, FirstTimeWizardToadlet.TOADLET_URL, uri.getQuery(), null));
} catch(URISyntaxException e) { throw new Error(e); }
}
}
synchronized(toadlets) {
for(ToadletElement te: toadlets) {
if(path.startsWith(te.prefix))
return te.t;
if(te.prefix.length() > 0 && te.prefix.charAt(te.prefix.length()-1) == '/') {
if(path.equals(te.prefix.substring(0, te.prefix.length()-1))) {
URI newURI;
try {
newURI = new URI(te.prefix);
} catch (URISyntaxException e) {
throw new Error(e);
}
throw new PermanentRedirectException(newURI);
}
}
}
}
return null;
}
@Override
public void run() {
boolean finishedStartup = false;
while(true) {
synchronized(this) {
while(fproxyConnections > maxFproxyConnections) {
try {
wait();
} catch (InterruptedException e) {
// Ignore
}
}
if((!finishedStartup) && this.finishedStartup)
finishedStartup = true;
if(myThread == null) return;
}
Socket conn = networkInterface.accept();
//if (WrapperManager.hasShutdownHookBeenTriggered())
//return;
if(conn == null)
continue; // timeout
if(logMINOR)
Logger.minor(this, "Accepted connection");
SocketHandler sh = new SocketHandler(conn, finishedStartup);
sh.start();
}
}
public class SocketHandler implements PrioRunnable {
Socket sock;
final boolean finishedStartup;
public SocketHandler(Socket conn, boolean finishedStartup) {
this.sock = conn;
this.finishedStartup = finishedStartup;
}
void start() {
if(finishedStartup)
executor.execute(this, "HTTP socket handler@"+hashCode());
else
new Thread(this).start();
synchronized(SimpleToadletServer.this) {
fproxyConnections++;
}
}
@Override
public void run() {
freenet.support.Logger.OSThread.logPID(this);
if(logMINOR) Logger.minor(this, "Handling connection");
try {
ToadletContextImpl.handle(sock, SimpleToadletServer.this, pageMaker, getUserAlertManager(), bookmarkManager);
} catch (Throwable t) {
System.err.println("Caught in SimpleToadletServer: "+t);
t.printStackTrace();
Logger.error(this, "Caught in SimpleToadletServer: "+t, t);
} finally {
synchronized(SimpleToadletServer.this) {
fproxyConnections--;
SimpleToadletServer.this.notifyAll();
}
}
if(logMINOR) Logger.minor(this, "Handled connection");
}
@Override
public int getPriority() {
return NativeThread.HIGH_PRIORITY-1;
}
}
@Override
public THEME getTheme() {
return this.cssTheme;
}
public UserAlertManager getUserAlertManager() {
NodeClientCore core = this.core;
if(core == null) return null;
return core.alerts;
}
public void setCSSName(THEME theme) {
this.cssTheme = theme;
}
@Override
public synchronized boolean sendAllThemes() {
return this.sendAllThemes;
}
@Override
public synchronized boolean isAdvancedModeEnabled() {
return this.advancedModeEnabled;
}
@Override
public void setAdvancedMode(boolean enabled) {
synchronized(this) {
if(advancedModeEnabled == enabled) return;
advancedModeEnabled = enabled;
}
core.node.config.store();
}
@Override
public synchronized boolean isFProxyJavascriptEnabled() {
return this.fProxyJavascriptEnabled;
}
public synchronized void enableFProxyJavascript(boolean b){
fProxyJavascriptEnabled = b;
}
@Override
public synchronized boolean isFProxyWebPushingEnabled() {
return this.fProxyWebPushingEnabled;
}
public synchronized void enableFProxyWebPushing(boolean b){
fProxyWebPushingEnabled = b;
}
@Override
public String getFormPassword() {
if(core == null) return "";
return core.formPassword;
}
@Override
public boolean isAllowedFullAccess(InetAddress remoteAddr) {
return this.allowedFullAccess.allowed(remoteAddr);
}
private static String l10n(String key, String pattern, String value) {
return NodeL10n.getBase().getString("SimpleToadletServer."+key, pattern, value);
}
private static String l10n(String key) {
return NodeL10n.getBase().getString("SimpleToadletServer."+key);
}
@Override
public HTMLNode addFormChild(HTMLNode parentNode, String target, String id) {
HTMLNode formNode =
parentNode.addChild("div")
.addChild("form", new String[] { "action", "method", "enctype", "id", "accept-charset" },
new String[] { target, "post", "multipart/form-data", id, "utf-8"} );
formNode.addChild("input", new String[] { "type", "name", "value" },
new String[] { "hidden", "formPassword", getFormPassword() });
return formNode;
}
public void setBucketFactory(BucketFactory tempBucketFactory) {
this.bf = tempBucketFactory;
}
public boolean isEnabled() {
return myThread != null;
}
public BookmarkManager getBookmarks() {
return bookmarkManager;
}
public FreenetURI[] getBookmarkURIs() {
if(bookmarkManager == null) return new FreenetURI[0];
return bookmarkManager.getBookmarkURIs();
}
@Override
public boolean enablePersistentConnections() {
return enablePersistentConnections;
}
@Override
public boolean enableInlinePrefetch() {
return enableInlinePrefetch;
}
@Override
public boolean enableExtendedMethodHandling() {
return enableExtendedMethodHandling;
}
@Override
public synchronized boolean allowPosts() {
return !(bf instanceof ArrayBucketFactory);
}
@Override
public synchronized BucketFactory getBucketFactory() {
return bf;
}
@Override
public boolean enableActivelinks() {
return enableActivelinks;
}
@Override
public boolean disableProgressPage() {
return disableProgressPage;
}
@Override
public PageMaker getPageMaker() {
return pageMaker;
}
public Ticker getTicker(){
return core.node.getTicker();
}
public NodeClientCore getCore(){
return core;
}
private REFILTER_POLICY refilterPolicy;
@Override
public REFILTER_POLICY getReFilterPolicy() {
return refilterPolicy;
}
@Override
public File getOverrideFile() {
return cssOverride;
}
@Override
public String getURL() {
return getURL(null);
}
@Override
public String getURL(String host) {
StringBuffer sb = new StringBuffer();
if(ssl)
sb.append("https");
else
sb.append("http");
sb.append("://");
if(host == null)
host = "127.0.0.1";
sb.append(host);
sb.append(":");
sb.append(this.port);
sb.append("/");
return sb.toString();
}
@Override
public boolean isSSL() {
return ssl;
}
//
// LINKFILTEREXCEPTIONPROVIDER METHODS
//
/**
* {@inheritDoc}
*/
@Override
public boolean isLinkExcepted(URI link) {
Toadlet toadlet = null;
try {
toadlet = findToadlet(link);
} catch (PermanentRedirectException pre1) {
/* ignore. */
}
if (toadlet instanceof LinkFilterExceptedToadlet) {
return ((LinkFilterExceptedToadlet) toadlet).isLinkExcepted(link);
}
return false;
}
@Override
public long generateUniqueID() {
// FIXME increment a counter?
return random.nextLong();
}
}
| deepstupid/fred | src/freenet/clients/http/SimpleToadletServer.java | Java | gpl-2.0 | 39,516 |
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @summary Spliterator traversing and splitting tests
* @library ../stream/bootlib
* @build java.base/java.util.SpliteratorOfIntDataBuilder
* java.base/java.util.SpliteratorTestHelper
* @run testng SpliteratorTraversingAndSplittingTest
* @bug 8020016 8071477 8072784 8169838
*/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.nio.CharBuffer;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.SpliteratorOfIntDataBuilder;
import java.util.SpliteratorTestHelper;
import java.util.Spliterators;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class SpliteratorTraversingAndSplittingTest extends SpliteratorTestHelper {
private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42);
private static final String LOW = new String(new char[] {Character.MIN_LOW_SURROGATE});
private static final String HIGH = new String(new char[] {Character.MIN_HIGH_SURROGATE});
private static final String HIGH_LOW = HIGH + LOW;
private static final String CHAR_HIGH_LOW = "A" + HIGH_LOW;
private static final String HIGH_LOW_CHAR = HIGH_LOW + "A";
private static final String CHAR_HIGH_LOW_CHAR = "A" + HIGH_LOW + "A";
private static final List<String> STRINGS = generateTestStrings();
private static List<String> generateTestStrings() {
List<String> strings = new ArrayList<>();
for (int n : Arrays.asList(1, 2, 3, 16, 17)) {
strings.add(generate("A", n));
strings.add(generate(LOW, n));
strings.add(generate(HIGH, n));
strings.add(generate(HIGH_LOW, n));
strings.add(generate(CHAR_HIGH_LOW, n));
strings.add(generate(HIGH_LOW_CHAR, n));
strings.add(generate(CHAR_HIGH_LOW_CHAR, n));
}
return strings;
}
private static String generate(String s, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
private static class SpliteratorDataBuilder<T> {
List<Object[]> data;
List<T> exp;
Map<T, T> mExp;
SpliteratorDataBuilder(List<Object[]> data, List<T> exp) {
this.data = data;
this.exp = exp;
this.mExp = createMap(exp);
}
Map<T, T> createMap(List<T> l) {
Map<T, T> m = new LinkedHashMap<>();
for (T t : l) {
m.put(t, t);
}
return m;
}
void add(String description, Collection<?> expected, Supplier<Spliterator<?>> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator<?>> s) {
add(description, exp, s);
}
void addCollection(Function<Collection<T>, ? extends Collection<T>> c) {
add("new " + c.apply(Collections.<T>emptyList()).getClass().getName() + ".spliterator()",
() -> c.apply(exp).spliterator());
}
void addList(Function<Collection<T>, ? extends List<T>> l) {
addCollection(l);
addCollection(l.andThen(list -> list.subList(0, list.size())));
}
void addMap(Function<Map<T, T>, ? extends Map<T, T>> m) {
String description = "new " + m.apply(Collections.<T, T>emptyMap()).getClass().getName();
addMap(m, description);
}
void addMap(Function<Map<T, T>, ? extends Map<T, T>> m, String description) {
add(description + ".keySet().spliterator()", () -> m.apply(mExp).keySet().spliterator());
add(description + ".values().spliterator()", () -> m.apply(mExp).values().spliterator());
add(description + ".entrySet().spliterator()", mExp.entrySet(), () -> m.apply(mExp).entrySet().spliterator());
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] spliteratorDataProvider;
@DataProvider(name = "Spliterator<Integer>")
public static Object[][] spliteratorDataProvider() {
if (spliteratorDataProvider != null) {
return spliteratorDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
List<Integer> exp = listIntRange(size);
SpliteratorDataBuilder<Integer> db = new SpliteratorDataBuilder<>(data, exp);
// Direct spliterator methods
db.add("Spliterators.spliterator(Collection, ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Spliterators.spliterator(Iterator, ...)",
() -> Spliterators.spliterator(exp.iterator(), exp.size(), 0));
db.add("Spliterators.spliteratorUnknownSize(Iterator, ...)",
() -> Spliterators.spliteratorUnknownSize(exp.iterator(), 0));
db.add("Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Spliterator ), ...)",
() -> Spliterators.spliterator(Spliterators.iterator(exp.spliterator()), exp.size(), 0));
db.add("Spliterators.spliterator(T[], ...)",
() -> Spliterators.spliterator(exp.toArray(new Integer[0]), 0));
db.add("Arrays.spliterator(T[], ...)",
() -> Arrays.spliterator(exp.toArray(new Integer[0])));
class SpliteratorFromIterator extends Spliterators.AbstractSpliterator<Integer> {
Iterator<Integer> it;
SpliteratorFromIterator(Iterator<Integer> it, long est) {
super(est, Spliterator.SIZED);
this.it = it;
}
@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
if (action == null)
throw new NullPointerException();
if (it.hasNext()) {
action.accept(it.next());
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractSpliterator()",
() -> new SpliteratorFromIterator(exp.iterator(), exp.size()));
// Collections
// default method implementations
class AbstractCollectionImpl extends AbstractCollection<Integer> {
Collection<Integer> c;
AbstractCollectionImpl(Collection<Integer> c) {
this.c = c;
}
@Override
public Iterator<Integer> iterator() {
return c.iterator();
}
@Override
public int size() {
return c.size();
}
}
db.addCollection(
c -> new AbstractCollectionImpl(c));
class AbstractListImpl extends AbstractList<Integer> {
List<Integer> l;
AbstractListImpl(Collection<Integer> c) {
this.l = new ArrayList<>(c);
}
@Override
public Integer get(int index) {
return l.get(index);
}
@Override
public int size() {
return l.size();
}
}
db.addCollection(
c -> new AbstractListImpl(c));
class AbstractSetImpl extends AbstractSet<Integer> {
Set<Integer> s;
AbstractSetImpl(Collection<Integer> c) {
this.s = new HashSet<>(c);
}
@Override
public Iterator<Integer> iterator() {
return s.iterator();
}
@Override
public int size() {
return s.size();
}
}
db.addCollection(
c -> new AbstractSetImpl(c));
class AbstractSortedSetImpl extends AbstractSet<Integer> implements SortedSet<Integer> {
SortedSet<Integer> s;
AbstractSortedSetImpl(Collection<Integer> c) {
this.s = new TreeSet<>(c);
}
@Override
public Iterator<Integer> iterator() {
return s.iterator();
}
@Override
public int size() {
return s.size();
}
@Override
public Comparator<? super Integer> comparator() {
return s.comparator();
}
@Override
public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) {
return s.subSet(fromElement, toElement);
}
@Override
public SortedSet<Integer> headSet(Integer toElement) {
return s.headSet(toElement);
}
@Override
public SortedSet<Integer> tailSet(Integer fromElement) {
return s.tailSet(fromElement);
}
@Override
public Integer first() {
return s.first();
}
@Override
public Integer last() {
return s.last();
}
@Override
public Spliterator<Integer> spliterator() {
return SortedSet.super.spliterator();
}
}
db.addCollection(
c -> new AbstractSortedSetImpl(c));
class IterableWrapper implements Iterable<Integer> {
final Iterable<Integer> it;
IterableWrapper(Iterable<Integer> it) {
this.it = it;
}
@Override
public Iterator<Integer> iterator() {
return it.iterator();
}
}
db.add("new Iterable.spliterator()",
() -> new IterableWrapper(exp).spliterator());
//
db.add("Arrays.asList().spliterator()",
() -> Spliterators.spliterator(Arrays.asList(exp.toArray(new Integer[0])), 0));
db.addList(ArrayList::new);
db.addList(LinkedList::new);
db.addList(Vector::new);
class AbstractRandomAccessListImpl extends AbstractList<Integer> implements RandomAccess {
Integer[] ia;
AbstractRandomAccessListImpl(Collection<Integer> c) {
this.ia = c.toArray(new Integer[c.size()]);
}
@Override
public Integer get(int index) {
return ia[index];
}
@Override
public int size() {
return ia.length;
}
}
db.addList(AbstractRandomAccessListImpl::new);
class RandomAccessListImpl implements List<Integer>, RandomAccess {
Integer[] ia;
List<Integer> l;
RandomAccessListImpl(Collection<Integer> c) {
this.ia = c.toArray(new Integer[c.size()]);
this.l = Arrays.asList(ia);
}
@Override
public Integer get(int index) {
return ia[index];
}
@Override
public Integer set(int index, Integer element) {
throw new UnsupportedOperationException();
}
@Override
public void add(int index, Integer element) {
throw new UnsupportedOperationException();
}
@Override
public Integer remove(int index) {
throw new UnsupportedOperationException();
}
@Override
public int indexOf(Object o) {
return l.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return Arrays.asList(ia).lastIndexOf(o);
}
@Override
public ListIterator<Integer> listIterator() {
return l.listIterator();
}
@Override
public ListIterator<Integer> listIterator(int index) {
return l.listIterator(index);
}
@Override
public List<Integer> subList(int fromIndex, int toIndex) {
return l.subList(fromIndex, toIndex);
}
@Override
public int size() {
return ia.length;
}
@Override
public boolean isEmpty() {
return size() != 0;
}
@Override
public boolean contains(Object o) {
return l.contains(o);
}
@Override
public Iterator<Integer> iterator() {
return l.iterator();
}
@Override
public Object[] toArray() {
return l.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return l.toArray(a);
}
@Override
public boolean add(Integer integer) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return l.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, Collection<? extends Integer> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
db.addList(RandomAccessListImpl::new);
db.addCollection(HashSet::new);
db.addCollection(LinkedHashSet::new);
db.addCollection(TreeSet::new);
db.addCollection(c -> { Stack<Integer> s = new Stack<>(); s.addAll(c); return s;});
db.addCollection(PriorityQueue::new);
db.addCollection(ArrayDeque::new);
db.addCollection(ConcurrentSkipListSet::new);
if (size > 0) {
db.addCollection(c -> {
ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(size);
abq.addAll(c);
return abq;
});
}
db.addCollection(PriorityBlockingQueue::new);
db.addCollection(LinkedBlockingQueue::new);
db.addCollection(LinkedTransferQueue::new);
db.addCollection(ConcurrentLinkedQueue::new);
db.addCollection(LinkedBlockingDeque::new);
db.addCollection(CopyOnWriteArrayList::new);
db.addCollection(CopyOnWriteArraySet::new);
if (size == 0) {
db.addCollection(c -> Collections.<Integer>emptySet());
db.addList(c -> Collections.<Integer>emptyList());
}
else if (size == 1) {
db.addCollection(c -> Collections.singleton(exp.get(0)));
db.addCollection(c -> Collections.singletonList(exp.get(0)));
}
{
Integer[] ai = new Integer[size];
Arrays.fill(ai, 1);
db.add(String.format("Collections.nCopies(%d, 1)", exp.size()),
Arrays.asList(ai),
() -> Collections.nCopies(exp.size(), 1).spliterator());
}
// Collections.synchronized/unmodifiable/checked wrappers
db.addCollection(Collections::unmodifiableCollection);
db.addCollection(c -> Collections.unmodifiableSet(new HashSet<>(c)));
db.addCollection(c -> Collections.unmodifiableSortedSet(new TreeSet<>(c)));
db.addList(c -> Collections.unmodifiableList(new ArrayList<>(c)));
db.addMap(Collections::unmodifiableMap);
db.addMap(m -> Collections.unmodifiableSortedMap(new TreeMap<>(m)));
db.addCollection(Collections::synchronizedCollection);
db.addCollection(c -> Collections.synchronizedSet(new HashSet<>(c)));
db.addCollection(c -> Collections.synchronizedSortedSet(new TreeSet<>(c)));
db.addList(c -> Collections.synchronizedList(new ArrayList<>(c)));
db.addMap(Collections::synchronizedMap);
db.addMap(m -> Collections.synchronizedSortedMap(new TreeMap<>(m)));
db.addCollection(c -> Collections.checkedCollection(c, Integer.class));
db.addCollection(c -> Collections.checkedQueue(new ArrayDeque<>(c), Integer.class));
db.addCollection(c -> Collections.checkedSet(new HashSet<>(c), Integer.class));
db.addCollection(c -> Collections.checkedSortedSet(new TreeSet<>(c), Integer.class));
db.addList(c -> Collections.checkedList(new ArrayList<>(c), Integer.class));
db.addMap(c -> Collections.checkedMap(c, Integer.class, Integer.class));
db.addMap(m -> Collections.checkedSortedMap(new TreeMap<>(m), Integer.class, Integer.class));
// Maps
db.addMap(HashMap::new);
db.addMap(m -> {
// Create a Map ensuring that for large sizes
// buckets will contain 2 or more entries
HashMap<Integer, Integer> cm = new HashMap<>(1, m.size() + 1);
// Don't use putAll which inflates the table by
// m.size() * loadFactor, thus creating a very sparse
// map for 1000 entries defeating the purpose of this test,
// in addition it will cause the split until null test to fail
// because the number of valid splits is larger than the
// threshold
for (Map.Entry<Integer, Integer> e : m.entrySet())
cm.put(e.getKey(), e.getValue());
return cm;
}, "new java.util.HashMap(1, size + 1)");
db.addMap(LinkedHashMap::new);
db.addMap(IdentityHashMap::new);
db.addMap(WeakHashMap::new);
db.addMap(m -> {
// Create a Map ensuring that for large sizes
// buckets will be consist of 2 or more entries
WeakHashMap<Integer, Integer> cm = new WeakHashMap<>(1, m.size() + 1);
for (Map.Entry<Integer, Integer> e : m.entrySet())
cm.put(e.getKey(), e.getValue());
return cm;
}, "new java.util.WeakHashMap(1, size + 1)");
// @@@ Descending maps etc
db.addMap(TreeMap::new);
db.addMap(ConcurrentHashMap::new);
db.addMap(ConcurrentSkipListMap::new);
if (size == 0) {
db.addMap(m -> Collections.<Integer, Integer>emptyMap());
}
else if (size == 1) {
db.addMap(m -> Collections.singletonMap(exp.get(0), exp.get(0)));
}
}
return spliteratorDataProvider = data.toArray(new Object[0][]);
}
private static List<Integer> listIntRange(int upTo) {
List<Integer> exp = new ArrayList<>();
for (int i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
@Test(dataProvider = "Spliterator<Integer>")
public void testNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null));
}
@Test(dataProvider = "Spliterator<Integer>")
public void testForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testForEach(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testTryAdvance(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testMixedTraverseAndSplit(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitAfterFullTraversal(s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitOnce(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitSixDeep(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitUntilNull(exp, s, UnaryOperator.identity());
}
//
private static class SpliteratorOfIntCharDataBuilder {
List<Object[]> data;
String s;
List<Integer> expChars;
List<Integer> expCodePoints;
SpliteratorOfIntCharDataBuilder(List<Object[]> data, String s) {
this.data = data;
this.s = s;
this.expChars = transform(s, false);
this.expCodePoints = transform(s, true);
}
static List<Integer> transform(String s, boolean toCodePoints) {
List<Integer> l = new ArrayList<>();
if (!toCodePoints) {
for (int i = 0; i < s.length(); i++) {
l.add((int) s.charAt(i));
}
}
else {
for (int i = 0; i < s.length();) {
char c1 = s.charAt(i++);
int cp = c1;
if (Character.isHighSurrogate(c1) && i < s.length()) {
char c2 = s.charAt(i);
if (Character.isLowSurrogate(c2)) {
i++;
cp = Character.toCodePoint(c1, c2);
}
}
l.add(cp);
}
}
return l;
}
void add(String description, Function<String, CharSequence> f) {
description = description.replace("%s", s);
{
Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).chars().spliterator();
data.add(new Object[]{description + ".chars().spliterator()", expChars, supplier});
}
{
Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).codePoints().spliterator();
data.add(new Object[]{description + ".codePoints().spliterator()", expCodePoints, supplier});
}
}
}
static Object[][] spliteratorOfIntDataProvider;
@DataProvider(name = "Spliterator.OfInt")
public static Object[][] spliteratorOfIntDataProvider() {
if (spliteratorOfIntDataProvider != null) {
return spliteratorOfIntDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
int exp[] = arrayIntRange(size);
SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder(data, listIntRange(size));
db.add("Spliterators.spliterator(int[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(int[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfInt, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfInt, ...)",
() -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class IntSpliteratorFromArray extends Spliterators.AbstractIntSpliterator {
int[] a;
int index = 0;
IntSpliteratorFromArray(int[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if (action == null)
throw new NullPointerException();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractIntAdvancingSpliterator()",
() -> new IntSpliteratorFromArray(exp));
}
// Class for testing default methods
class CharSequenceImpl implements CharSequence {
final String s;
public CharSequenceImpl(String s) {
this.s = s;
}
@Override
public int length() {
return s.length();
}
@Override
public char charAt(int index) {
return s.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return s.subSequence(start, end);
}
@Override
public String toString() {
return s;
}
}
for (String string : STRINGS) {
SpliteratorOfIntCharDataBuilder cdb = new SpliteratorOfIntCharDataBuilder(data, string);
cdb.add("\"%s\"", s -> s);
cdb.add("new CharSequenceImpl(\"%s\")", CharSequenceImpl::new);
cdb.add("new StringBuilder(\"%s\")", StringBuilder::new);
cdb.add("new StringBuffer(\"%s\")", StringBuffer::new);
cdb.add("CharBuffer.wrap(\"%s\".toCharArray())", s -> CharBuffer.wrap(s.toCharArray()));
}
return spliteratorOfIntDataProvider = data.toArray(new Object[0][]);
}
private static int[] arrayIntRange(int upTo) {
int[] exp = new int[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((IntConsumer) null));
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testTryAdvance(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testMixedTryAdvanceForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testMixedTraverseAndSplit(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitAfterFullTraversal(s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitOnce(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitSixDeep(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitUntilNull(exp, s, intBoxingConsumer());
}
//
private static class SpliteratorOfLongDataBuilder {
List<Object[]> data;
List<Long> exp;
SpliteratorOfLongDataBuilder(List<Object[]> data, List<Long> exp) {
this.data = data;
this.exp = exp;
}
void add(String description, List<Long> expected, Supplier<Spliterator.OfLong> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator.OfLong> s) {
add(description, exp, s);
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] spliteratorOfLongDataProvider;
@DataProvider(name = "Spliterator.OfLong")
public static Object[][] spliteratorOfLongDataProvider() {
if (spliteratorOfLongDataProvider != null) {
return spliteratorOfLongDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
long exp[] = arrayLongRange(size);
SpliteratorOfLongDataBuilder db = new SpliteratorOfLongDataBuilder(data, listLongRange(size));
db.add("Spliterators.spliterator(long[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(long[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfLong, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfLong, ...)",
() -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class LongSpliteratorFromArray extends Spliterators.AbstractLongSpliterator {
long[] a;
int index = 0;
LongSpliteratorFromArray(long[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(LongConsumer action) {
if (action == null)
throw new NullPointerException();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractLongAdvancingSpliterator()",
() -> new LongSpliteratorFromArray(exp));
}
return spliteratorOfLongDataProvider = data.toArray(new Object[0][]);
}
private static List<Long> listLongRange(int upTo) {
List<Long> exp = new ArrayList<>();
for (long i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
private static long[] arrayLongRange(int upTo) {
long[] exp = new long[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongNullPointerException(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((LongConsumer) null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((LongConsumer) null));
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testForEach(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongTryAdvance(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testTryAdvance(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongMixedTryAdvanceForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testMixedTryAdvanceForEach(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongMixedTraverseAndSplit(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testMixedTraverseAndSplit(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitAfterFullTraversal(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitAfterFullTraversal(s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitOnce(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitOnce(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitSixDeep(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitSixDeep(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitUntilNull(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitUntilNull(exp, s, longBoxingConsumer());
}
//
private static class SpliteratorOfDoubleDataBuilder {
List<Object[]> data;
List<Double> exp;
SpliteratorOfDoubleDataBuilder(List<Object[]> data, List<Double> exp) {
this.data = data;
this.exp = exp;
}
void add(String description, List<Double> expected, Supplier<Spliterator.OfDouble> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator.OfDouble> s) {
add(description, exp, s);
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] spliteratorOfDoubleDataProvider;
@DataProvider(name = "Spliterator.OfDouble")
public static Object[][] spliteratorOfDoubleDataProvider() {
if (spliteratorOfDoubleDataProvider != null) {
return spliteratorOfDoubleDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
double exp[] = arrayDoubleRange(size);
SpliteratorOfDoubleDataBuilder db = new SpliteratorOfDoubleDataBuilder(data, listDoubleRange(size));
db.add("Spliterators.spliterator(double[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(double[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfDouble, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfDouble, ...)",
() -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class DoubleSpliteratorFromArray extends Spliterators.AbstractDoubleSpliterator {
double[] a;
int index = 0;
DoubleSpliteratorFromArray(double[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(DoubleConsumer action) {
if (action == null)
throw new NullPointerException();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractDoubleAdvancingSpliterator()",
() -> new DoubleSpliteratorFromArray(exp));
}
return spliteratorOfDoubleDataProvider = data.toArray(new Object[0][]);
}
private static List<Double> listDoubleRange(int upTo) {
List<Double> exp = new ArrayList<>();
for (double i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
private static double[] arrayDoubleRange(int upTo) {
double[] exp = new double[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleNullPointerException(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((DoubleConsumer) null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((DoubleConsumer) null));
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testForEach(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleTryAdvance(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testTryAdvance(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleMixedTryAdvanceForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testMixedTryAdvanceForEach(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleMixedTraverseAndSplit(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testMixedTraverseAndSplit(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitAfterFullTraversal(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitAfterFullTraversal(s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitOnce(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitOnce(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitSixDeep(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitSixDeep(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitUntilNull(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitUntilNull(exp, s, doubleBoxingConsumer());
}
}
| dmlloyd/openjdk-modules | jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java | Java | gpl-2.0 | 44,814 |
/**
* ownCloud Android client application
*
* @author Mario Danic
* Copyright (C) 2017 Mario Danic
* Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2012-2016 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.fragment;
import android.animation.LayoutTransition;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.SearchOperation;
import com.owncloud.android.ui.ExtendedListView;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.activity.FolderPickerActivity;
import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
import com.owncloud.android.ui.activity.UploadFilesActivity;
import com.owncloud.android.ui.adapter.FileListListAdapter;
import com.owncloud.android.ui.adapter.LocalFileListAdapter;
import com.owncloud.android.ui.events.SearchEvent;
import org.greenrobot.eventbus.EventBus;
import org.parceler.Parcel;
import java.util.ArrayList;
import third_parties.in.srain.cube.GridViewWithHeaderAndFooter;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
public class ExtendedListFragment extends Fragment
implements OnItemClickListener, OnEnforceableRefreshListener, SearchView.OnQueryTextListener {
protected static final String TAG = ExtendedListFragment.class.getSimpleName();
protected static final String KEY_SAVED_LIST_POSITION = "SAVED_LIST_POSITION";
private static final String KEY_INDEXES = "INDEXES";
private static final String KEY_FIRST_POSITIONS = "FIRST_POSITIONS";
private static final String KEY_TOPS = "TOPS";
private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL";
private static final String KEY_EMPTY_LIST_MESSAGE = "EMPTY_LIST_MESSAGE";
private static final String KEY_IS_GRID_VISIBLE = "IS_GRID_VISIBLE";
protected SwipeRefreshLayout mRefreshListLayout;
private SwipeRefreshLayout mRefreshGridLayout;
protected SwipeRefreshLayout mRefreshEmptyLayout;
protected LinearLayout mEmptyListContainer;
protected TextView mEmptyListMessage;
protected TextView mEmptyListHeadline;
protected ImageView mEmptyListIcon;
protected ProgressBar mEmptyListProgress;
private FloatingActionsMenu mFabMain;
private FloatingActionButton mFabUpload;
private FloatingActionButton mFabMkdir;
private FloatingActionButton mFabUploadFromApp;
// Save the state of the scroll in browsing
private ArrayList<Integer> mIndexes;
private ArrayList<Integer> mFirstPositions;
private ArrayList<Integer> mTops;
private int mHeightCell = 0;
private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null;
protected AbsListView mCurrentListView;
private ExtendedListView mListView;
private View mListFooterView;
private GridViewWithHeaderAndFooter mGridView;
private View mGridFooterView;
private BaseAdapter mAdapter;
protected SearchView searchView;
private Handler handler = new Handler();
@Parcel
public enum SearchType {
NO_SEARCH,
REGULAR_FILTER,
FILE_SEARCH,
FAVORITE_SEARCH,
FAVORITE_SEARCH_FILTER,
VIDEO_SEARCH,
VIDEO_SEARCH_FILTER,
PHOTO_SEARCH,
PHOTOS_SEARCH_FILTER,
RECENTLY_MODIFIED_SEARCH,
RECENTLY_MODIFIED_SEARCH_FILTER,
RECENTLY_ADDED_SEARCH,
RECENTLY_ADDED_SEARCH_FILTER,
// not a real filter, but nevertheless
SHARED_FILTER
}
protected void setListAdapter(BaseAdapter listAdapter) {
mAdapter = listAdapter;
mCurrentListView.setAdapter(listAdapter);
mCurrentListView.invalidateViews();
}
protected AbsListView getListView() {
return mCurrentListView;
}
public FloatingActionButton getFabUpload() {
return mFabUpload;
}
public FloatingActionButton getFabUploadFromApp() {
return mFabUploadFromApp;
}
public FloatingActionButton getFabMkdir() {
return mFabMkdir;
}
public FloatingActionsMenu getFabMain() {
return mFabMain;
}
public void switchToGridView() {
if (!isGridEnabled()) {
mListView.setAdapter(null);
mRefreshListLayout.setVisibility(View.GONE);
mRefreshGridLayout.setVisibility(View.VISIBLE);
mCurrentListView = mGridView;
setListAdapter(mAdapter);
}
}
public void switchToListView() {
if (isGridEnabled()) {
mGridView.setAdapter(null);
mRefreshGridLayout.setVisibility(View.GONE);
mRefreshListLayout.setVisibility(View.VISIBLE);
mCurrentListView = mListView;
setListAdapter(mAdapter);
}
}
public boolean isGridEnabled() {
return (mCurrentListView != null && mCurrentListView.equals(mGridView));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
final MenuItem item = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
final Handler handler = new Handler();
DisplayMetrics displaymetrics = new DisplayMetrics();
Activity activity;
if ((activity = getActivity()) != null) {
activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
if (getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE) {
searchView.setMaxWidth((int) (width * 0.4));
} else {
if (activity instanceof FolderPickerActivity) {
searchView.setMaxWidth((int) (width * 0.8));
} else {
searchView.setMaxWidth((int) (width * 0.7));
}
}
}
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, final boolean hasFocus) {
if (hasFocus) {
mFabMain.collapse();
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (getActivity() != null && !(getActivity() instanceof FolderPickerActivity)) {
setFabEnabled(!hasFocus);
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
getCurrentOwnCloudAccount(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) {
BottomNavigationView bottomNavigationView = (BottomNavigationView) getActivity().
findViewById(R.id.bottom_navigation_view);
if (hasFocus) {
bottomNavigationView.setVisibility(View.GONE);
} else {
bottomNavigationView.setVisibility(View.VISIBLE);
}
}
}
}
}, 100);
}
});
final View mSearchEditFrame = searchView
.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int oldVisibility = -1;
@Override
public void onGlobalLayout() {
int currentVisibility = mSearchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility == View.VISIBLE) {
setEmptyListMessage(SearchType.REGULAR_FILTER);
} else {
setEmptyListMessage(SearchType.NO_SEARCH);
}
oldVisibility = currentVisibility;
}
}
});
LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);
searchBar.setLayoutTransition(new LayoutTransition());
}
public boolean onQueryTextChange(final String query) {
if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT)
instanceof ExtendedListFragment){
performSearch(query, false);
return true;
} else {
return false;
}
}
@Override
public boolean onQueryTextSubmit(String query) {
if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT)
instanceof ExtendedListFragment){
performSearch(query, true);
return true;
} else {
return false;
}
}
private void performSearch(final String query, boolean isSubmit) {
handler.removeCallbacksAndMessages(null);
if (!TextUtils.isEmpty(query)) {
int delay = 500;
if (isSubmit) {
delay = 0;
}
if (mAdapter != null && mAdapter instanceof FileListListAdapter) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AccountUtils.hasSearchSupport(AccountUtils.
getCurrentOwnCloudAccount(MainApp.getAppContext()))) {
EventBus.getDefault().post(new SearchEvent(query, SearchOperation.SearchType.FILE_SEARCH,
SearchEvent.UnsetType.NO_UNSET));
} else {
FileListListAdapter fileListListAdapter = (FileListListAdapter) mAdapter;
fileListListAdapter.getFilter().filter(query);
}
}
}, delay);
} else if (mAdapter != null && mAdapter instanceof LocalFileListAdapter) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter;
localFileListAdapter.filter(query);
}
}, delay);
}
if (searchView != null && delay == 0) {
searchView.clearFocus();
}
} else {
Activity activity;
if ((activity = getActivity()) != null) {
if (activity instanceof FileDisplayActivity) {
((FileDisplayActivity) activity).refreshListOfFilesFragment(true);
} else if (activity instanceof UploadFilesActivity) {
LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter;
localFileListAdapter.filter(query);
} else if (activity instanceof FolderPickerActivity) {
((FolderPickerActivity) activity).refreshListOfFilesFragment(true);
}
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log_OC.d(TAG, "onCreateView");
View v = inflater.inflate(R.layout.list_fragment, null);
setupEmptyList(v);
mListView = (ExtendedListView) (v.findViewById(R.id.list_root));
mListView.setOnItemClickListener(this);
mListFooterView = inflater.inflate(R.layout.list_footer, null, false);
mGridView = (GridViewWithHeaderAndFooter) (v.findViewById(R.id.grid_root));
mGridView.setNumColumns(GridView.AUTO_FIT);
mGridView.setOnItemClickListener(this);
mGridFooterView = inflater.inflate(R.layout.list_footer, null, false);
// Pull-down to refresh layout
mRefreshListLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_list);
mRefreshGridLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_grid);
mRefreshEmptyLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_empty);
onCreateSwipeToRefresh(mRefreshListLayout);
onCreateSwipeToRefresh(mRefreshGridLayout);
onCreateSwipeToRefresh(mRefreshEmptyLayout);
mListView.setEmptyView(mRefreshEmptyLayout);
mGridView.setEmptyView(mRefreshEmptyLayout);
mFabMain = (FloatingActionsMenu) v.findViewById(R.id.fab_main);
mFabUpload = (FloatingActionButton) v.findViewById(R.id.fab_upload);
mFabMkdir = (FloatingActionButton) v.findViewById(R.id.fab_mkdir);
mFabUploadFromApp = (FloatingActionButton) v.findViewById(R.id.fab_upload_from_app);
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
getCurrentOwnCloudAccount(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams();
final float scale = v.getResources().getDisplayMetrics().density;
BottomNavigationView bottomNavigationView = (BottomNavigationView)
v.findViewById(R.id.bottom_navigation_view);
// convert the DP into pixel
int pixel = (int) (32 * scale + 0.5f);
layoutParams.setMargins(0, 0, pixel / 2, bottomNavigationView.getMeasuredHeight() + pixel * 2);
}
mCurrentListView = mListView; // list by default
if (savedInstanceState != null) {
if (savedInstanceState.getBoolean(KEY_IS_GRID_VISIBLE, false)) {
switchToGridView();
}
int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION);
if (isGridEnabled()) {
Log_OC.v(TAG, "Setting grid position " + referencePosition);
mGridView.setSelection(referencePosition);
} else {
Log_OC.v(TAG, "Setting and centering around list position " + referencePosition);
mListView.setAndCenterSelection(referencePosition);
}
}
return v;
}
protected void setupEmptyList(View view) {
mEmptyListContainer = (LinearLayout) view.findViewById(R.id.empty_list_view);
mEmptyListMessage = (TextView) view.findViewById(R.id.empty_list_view_text);
mEmptyListHeadline = (TextView) view.findViewById(R.id.empty_list_view_headline);
mEmptyListIcon = (ImageView) view.findViewById(R.id.empty_list_icon);
mEmptyListProgress = (ProgressBar) view.findViewById(R.id.empty_list_progress);
}
/**
* {@inheritDoc}
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES);
mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS);
mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS);
mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL);
setMessageForEmptyList(savedInstanceState.getString(KEY_EMPTY_LIST_MESSAGE));
} else {
mIndexes = new ArrayList<>();
mFirstPositions = new ArrayList<>();
mTops = new ArrayList<>();
mHeightCell = 0;
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log_OC.d(TAG, "onSaveInstanceState()");
savedInstanceState.putBoolean(KEY_IS_GRID_VISIBLE, isGridEnabled());
savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition());
savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes);
savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions);
savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops);
savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell);
savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText());
}
/**
* Calculates the position of the item that will be used as a reference to
* reposition the visible items in the list when the device is turned to
* other position.
*
* The current policy is take as a reference the visible item in the center
* of the screen.
*
* @return The position in the list of the visible item in the center of the
* screen.
*/
protected int getReferencePosition() {
if (mCurrentListView != null) {
return (mCurrentListView.getFirstVisiblePosition() +
mCurrentListView.getLastVisiblePosition()) / 2;
} else {
return 0;
}
}
/*
* Restore index and position
*/
protected void restoreIndexAndTopPosition() {
if (mIndexes.size() > 0) {
// needs to be checked; not every browse-up had a browse-down before
int index = mIndexes.remove(mIndexes.size() - 1);
final int firstPosition = mFirstPositions.remove(mFirstPositions.size() - 1);
int top = mTops.remove(mTops.size() - 1);
Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: "
+ top + "; index: " + index);
if (mCurrentListView != null && mCurrentListView.equals(mListView)) {
if (mHeightCell * index <= mListView.getHeight()) {
mListView.setSelectionFromTop(firstPosition, top);
} else {
mListView.setSelectionFromTop(index, 0);
}
} else {
if (mHeightCell * index <= mGridView.getHeight()) {
mGridView.setSelection(firstPosition);
//mGridView.smoothScrollToPosition(firstPosition);
} else {
mGridView.setSelection(index);
//mGridView.smoothScrollToPosition(index);
}
}
}
}
/*
* Save index and top position
*/
protected void saveIndexAndTopPosition(int index) {
mIndexes.add(index);
int firstPosition = mCurrentListView.getFirstVisiblePosition();
mFirstPositions.add(firstPosition);
View view = mCurrentListView.getChildAt(0);
int top = (view == null) ? 0 : view.getTop();
mTops.add(top);
// Save the height of a cell
mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// to be @overriden
}
@Override
public void onRefresh() {
if (searchView != null) {
searchView.onActionViewCollapsed();
Activity activity;
if ((activity = getActivity()) != null && activity instanceof FileDisplayActivity) {
FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity;
fileDisplayActivity.setDrawerIndicatorEnabled(fileDisplayActivity.isDrawerIndicatorAvailable());
}
}
mRefreshListLayout.setRefreshing(false);
mRefreshGridLayout.setRefreshing(false);
mRefreshEmptyLayout.setRefreshing(false);
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
public void setOnRefreshListener(OnEnforceableRefreshListener listener) {
mOnRefreshListener = listener;
}
/**
* Disables swipe gesture.
*
* Sets the 'enabled' state of the refresh layouts contained in the fragment.
*
* When 'false' is set, prevents user gestures but keeps the option to refresh programatically,
*
* @param enabled Desired state for capturing swipe gesture.
*/
public void setSwipeEnabled(boolean enabled) {
mRefreshListLayout.setEnabled(enabled);
mRefreshGridLayout.setEnabled(enabled);
mRefreshEmptyLayout.setEnabled(enabled);
}
/**
* Sets the 'visibility' state of the FAB contained in the fragment.
*
* When 'false' is set, FAB visibility is set to View.GONE programmatically,
*
* @param enabled Desired visibility for the FAB.
*/
public void setFabEnabled(boolean enabled) {
if (enabled) {
mFabMain.setVisibility(View.VISIBLE);
} else {
mFabMain.setVisibility(View.GONE);
}
}
/**
* Set message for empty list view.
*/
public void setMessageForEmptyList(String message) {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListMessage.setText(message);
}
}
/**
* displays an empty list information with a headline, a message and an icon.
*
* @param headline the headline
* @param message the message
* @param icon the icon to be shown
*/
public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListHeadline.setText(headline);
mEmptyListMessage.setText(message);
mEmptyListIcon.setImageResource(icon);
mEmptyListIcon.setVisibility(View.VISIBLE);
mEmptyListProgress.setVisibility(View.GONE);
}
}
});
}
public void setEmptyListMessage(final SearchType searchType) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (searchType == SearchType.NO_SEARCH) {
setMessageForEmptyList(
R.string.file_list_empty_headline,
R.string.file_list_empty,
R.drawable.ic_list_empty_folder
);
} else if (searchType == SearchType.FILE_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty, R.drawable.ic_search_light_grey);
} else if (searchType == SearchType.FAVORITE_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_favorite_headline,
R.string.file_list_empty_favorites_filter_list, R.drawable.ic_star_light_grey);
} else if (searchType == SearchType.VIDEO_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos,
R.string.file_list_empty_text_videos, R.drawable.ic_list_empty_video);
} else if (searchType == SearchType.PHOTO_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos,
R.string.file_list_empty_text_photos, R.drawable.ic_list_empty_image);
} else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_modified, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.RECENTLY_ADDED_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_added, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.REGULAR_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_search,
R.string.file_list_empty_search, R.drawable.ic_search_light_grey);
} else if (searchType == SearchType.FAVORITE_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_favorites_filter, R.drawable.ic_star_light_grey);
} else if (searchType == SearchType.VIDEO_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos,
R.string.file_list_empty_text_videos_filter, R.drawable.ic_list_empty_video);
} else if (searchType == SearchType.PHOTOS_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos,
R.string.file_list_empty_text_photos_filter, R.drawable.ic_list_empty_image);
} else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_modified_filter, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.RECENTLY_ADDED_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_added_filter, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.SHARED_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_shared_headline,
R.string.file_list_empty_shared, R.drawable.ic_list_empty_shared);
}
}
});
}
/**
* Set message for empty list view.
*/
public void setEmptyListLoadingMessage() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListHeadline.setText(R.string.file_list_loading);
mEmptyListMessage.setText("");
mEmptyListIcon.setVisibility(View.GONE);
mEmptyListProgress.setVisibility(View.VISIBLE);
}
}
});
}
/**
* Get the text of EmptyListMessage TextView.
*
* @return String empty text view text-value
*/
public String getEmptyViewText() {
return (mEmptyListContainer != null && mEmptyListMessage != null) ? mEmptyListMessage.getText().toString() : "";
}
protected void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) {
// Colors in animations
refreshLayout.setColorSchemeResources(R.color.color_accent, R.color.primary, R.color.primary_dark);
refreshLayout.setOnRefreshListener(this);
}
@Override
public void onRefresh(boolean ignoreETag) {
mRefreshListLayout.setRefreshing(false);
mRefreshGridLayout.setRefreshing(false);
mRefreshEmptyLayout.setRefreshing(false);
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
protected void setChoiceMode(int choiceMode) {
mListView.setChoiceMode(choiceMode);
mGridView.setChoiceMode(choiceMode);
}
protected void setMultiChoiceModeListener(AbsListView.MultiChoiceModeListener listener) {
mListView.setMultiChoiceModeListener(listener);
mGridView.setMultiChoiceModeListener(listener);
}
/**
* TODO doc
* To be called before setAdapter, or GridViewWithHeaderAndFooter will throw an exception
*
* @param enabled flag if footer should be shown/calculated
*/
protected void setFooterEnabled(boolean enabled) {
if (enabled) {
if (mGridView.getFooterViewCount() == 0 && mGridView.isCorrectAdapter()) {
if (mGridFooterView.getParent() != null) {
((ViewGroup) mGridFooterView.getParent()).removeView(mGridFooterView);
}
mGridView.addFooterView(mGridFooterView, null, false);
}
mGridFooterView.invalidate();
if (mListView.getFooterViewsCount() == 0) {
if (mListFooterView.getParent() != null) {
((ViewGroup) mListFooterView.getParent()).removeView(mListFooterView);
}
mListView.addFooterView(mListFooterView, null, false);
}
mListFooterView.invalidate();
} else {
mGridView.removeFooterView(mGridFooterView);
mListView.removeFooterView(mListFooterView);
}
}
/**
* set the list/grid footer text.
*
* @param text the footer text
*/
protected void setFooterText(String text) {
if (text != null && text.length() > 0) {
((TextView) mListFooterView.findViewById(R.id.footerText)).setText(text);
((TextView) mGridFooterView.findViewById(R.id.footerText)).setText(text);
setFooterEnabled(true);
} else {
setFooterEnabled(false);
}
}
}
| aleister09/android | src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java | Java | gpl-2.0 | 31,646 |
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test SetDontInlineMethodTest
* @compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI CompilerWhiteBoxTest.java
* @compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI SetDontInlineMethodTest.java
* @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SetDontInlineMethodTest
* @author igor.ignatyev@oracle.com
*/
public class SetDontInlineMethodTest extends CompilerWhiteBoxTest {
public static void main(String[] args) throws Exception {
new SetDontInlineMethodTest().runTest();
}
protected void test() throws Exception {
if (WHITE_BOX.setDontInlineMethod(METHOD, true)) {
throw new RuntimeException("on start " + METHOD
+ " must be inlineable");
}
if (!WHITE_BOX.setDontInlineMethod(METHOD, true)) {
throw new RuntimeException("after first change to true " + METHOD
+ " must be not inlineable");
}
if (!WHITE_BOX.setDontInlineMethod(METHOD, false)) {
throw new RuntimeException("after second change to true " + METHOD
+ " must be still not inlineable");
}
if (WHITE_BOX.setDontInlineMethod(METHOD, false)) {
throw new RuntimeException("after first change to false" + METHOD
+ " must be inlineable");
}
if (WHITE_BOX.setDontInlineMethod(METHOD, false)) {
throw new RuntimeException("after second change to false " + METHOD
+ " must be inlineable");
}
}
}
| karianna/jdk8_tl | hotspot/test/compiler/whitebox/SetDontInlineMethodTest.java | Java | gpl-2.0 | 2,613 |
/*
* $Id$
*/
package edu.jas.gbufd;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//import junit.framework.Test;
//import junit.framework.TestCase;
//import junit.framework.TestSuite;
import edu.jas.arith.BigRational;
import edu.jas.arith.ModInteger;
import edu.jas.arith.ModIntegerRing;
import edu.jas.gb.GroebnerBase;
import edu.jas.poly.ExpVector;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.GenPolynomialTokenizer;
import edu.jas.poly.Monomial;
import edu.jas.poly.OrderedPolynomialList;
import edu.jas.poly.PolyUtil;
import edu.jas.poly.PolynomialList;
/**
* Groebner base FGLM examples. Without JUnit.
* @author Jan Suess.
*/
public class GroebnerBaseFGLMExamples /*extends TestCase*/ {
/**
* main
*/
public static void main(String[] args) {
//BasicConfigurator.configure();
//junit.textui.TestRunner.run(suite());
GroebnerBaseFGLMExamples ex = new GroebnerBaseFGLMExamples();
ex.testC5();
/*
ex.xtestFiveVarsOrder();
ex.xtestCAP();
ex.xtestAUX();
ex.xtestModC5();
ex.xtestC6();
ex.xtestIsaac();
ex.xtestNiermann();
ex.ytestWalkS7();
ex.ytestCassouMod1();
ex.ytestOmdi1();
ex.ytestLamm1();
ex.xtestEquilibrium();
ex.xtestTrinks2();
ex.xtestHairerRungeKutta_1();
*/
}
/*
* Constructs a <CODE>GroebnerBaseFGLMExamples</CODE> object.
* @param name String.
public GroebnerBaseFGLMExamples(String name) {
super(name);
}
*/
/*
* suite.
public static Test suite() {
TestSuite suite = new TestSuite(GroebnerBaseFGLMExamples.class);
return suite;
}
*/
//field Q
String all = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM | Time L";
String grad = "Zahlbereich | Ordnung | Elements G | bitHeight G | Deg G | Time G | vDim";
String lex = "Zahlbereich | Ordnung | Elements L | bitHeight L | Deg L | Time L";
String fglm = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM";
//MOD 1831
String modAll = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM | Time L";
String modGrad = "Zahlbereich | Ordnung | Elements G | Deg G | Time G";
String modfglm = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM";
/*
@Override
protected void setUp() {
System.out.println("Setup");
}
@Override
protected void tearDown() {
System.out.println("Tear Down");
}
*/
//Test with five variables and different variable orders
public void xtestFiveVarsOrder() {
String polynomials = "( "
+ " (v^8*x*y*z), ( w^3*x - 2*v), ( 4*x*y - 2 + y), ( 3*y^5 - 3 + z ), ( 8*y^2*z^2 + x * y^6 )"
+ ") ";
String[] order = new String[] { "v", "w", "x", "y", "z" };
//String order1 = shuffle(order);
String order2 = shuffle(order);
//String order3 = shuffle(order);
//String order4 = shuffle(order);
//String order5 = shuffle(order);
//String order6 = "(z,w,v,y,x)"; //langsam
//String order7 = "(v,z,w,y,x)"; //langsam
//String order8 = "(w,z,v,x,y)"; //langsam
/*
String erg1 = testGeneral(order1, polynomials);
String erg2 = testGeneral(order2, polynomials);
String erg3 = testGeneral(order3, polynomials);
String erg4 = testGeneral(order4, polynomials);
String erg5 = testGeneral(order5, polynomials);
*/
String ergM13 = modAll(order2, polynomials, 13);
String ergM7 = modAll(order2, polynomials, 7);
/*
String ergOnlyL_1 = testOnlyLex(order1, polynomials);
String ergOnlyL_2 = testOnlyLex(order2, polynomials);
String ergOnlyL_3 = testOnlyLex(order3, polynomials);
String ergOnlyL_4 = testOnlyLex(order4, polynomials);
String ergOnlyL_5 = testOnlyLex(order5, polynomials);
String erg6 = testGeneral(order6, polynomials);
String erg7 = testGeneral(order7, polynomials);
String erg8 = testGeneral(order8, polynomials);
*/
//langsam: (z,w,v,y,x), (v,z,w,y,x)
/*
System.out.println(categoryLex);
System.out.println(ergOnlyL_1);
System.out.println(ergOnlyL_2);
System.out.println(ergOnlyL_3);
System.out.println(ergOnlyL_4);
System.out.println(ergOnlyL_5);
System.out.println(category);
System.out.println(erg6);
System.out.println(erg7);
System.out.println(erg8);
System.out.println(erg1);
System.out.println(erg2);
System.out.println(erg3);
System.out.println(erg4);
System.out.println(erg5);
*/
System.out.println(all);
System.out.println("Mod 13");
System.out.println(ergM13);
System.out.println("Mod 7");
System.out.println(ergM7);
}
//===================================================================
//Examples taken from "Efficient Computation of Zero-Dimensional Gröbner Bases by Change of Ordering",
// 1994, Faugere, Gianni, Lazard, Mora (FGLM)
//===================================================================
public void xtestCAP() {
String polynomials = "( " + " (y^2*z + 2*x*y*t - 2*x - z),"
+ "(-x^3*z + 4*x*y^2*z + 4*x^2*y*t + 2*y^3*t + 4*x^2 - 10*y^2 + 4*x*z - 10*y*t + 2),"
+ "(2*y*z*t + x*t^2 - x - 2*z),"
+ "(-x*z^3 + 4*y*z^2*t + 4*x*z*t^2 + 2*y*t^3 + 4*x*z + 4*z^2 - 10*y*t -10*t^2 + 2)"
+ ") ";
String orderINV = "(x,y,z,t)";
String orderL = "(t,z,y,x)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void xtestAUX() {
String polynomials = "( " + " (a^2*b*c + a*b^2*c + a*b*c^2 + a*b*c + a*b + a*c + b*c),"
+ "(a^2*b^2*c + a*b^2*c^2 + a^2*b*c + a*b*c + b*c + a + c ),"
+ "(a^2*b^2*c^2 + a^2*b^2*c + a*b^2*c + a*b*c + a*c + c + 1)" + ") ";
String orderINV = "(a,b,c)";
String orderL = "(c,b,a)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void testC5() {
String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e),"
+ "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e),"
+ "(a*b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") ";
String orderINV = "(a,b,c,d,e)";
String orderL = "(e,d,c,b,a)";
//Tests
String erg_deg = grad(orderINV, polynomials);
//System.out.println(grad);
//System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(grad);
System.out.println(erg_deg);
System.out.println("");
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void xtestModC5() {
String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e),"
+ "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e),"
+ "(b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") ";
String orderINV = "(a,b,c,d,e)";
String orderL = "(e,d,c,b,a)";
//Tests
String erg_deg = grad(orderL, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String ergOnlyFGLM_1 = fglm(orderINV, polynomials);
System.out.println(fglm);
System.out.println(ergOnlyFGLM_1);
//Tests MODULO
String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831);
System.out.println(modGrad);
System.out.println(ergOnlyG_1);
String erg1 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(erg1);
*/
}
public void xtestC6() {
String polynomials = "( " + " (a + b + c + d + e + f)," + "(a*b + b*c + c*d + d*e + e*f + a*f),"
+ "(a*b*c + b*c*d + c*d*e + d*e*f + a*e*f + a*b*f),"
+ "(a*b*c*d + b*c*d*e + c*d*e*f + a*d*e*f + a*b*e*f + a*b*c*f),"
+ "(a*b*c*d*e + b*c*d*e*f + a*c*d*e*f + a*b*d*e*f + a*b*c*e*f + a*b*c*d*f),"
+ "(a*b*c*d*e*f - 1)" + ") ";
String orderINV = "(a,b,c,d,e,f)";
String orderL = "(f,e,d,c,b,a)";
//Tests
/*
String erg2 = modAll(orderINV, polynomials, 1831);
System.out.println(modAll);
System.out.println(erg2);
String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831);
System.out.println(modGrad);
System.out.println(ergOnlyG_1);
String erg1 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(erg1);
*/
}
//===================================================================
//Examples taken from "Der FGLM-Algorithmus: verallgemeinert und implementiert in SINGULAR", 1997, Wichmann
//===================================================================
public void xtestIsaac() {
String polynomials = "( "
+ " (8*w^2 + 5*w*x - 4*w*y + 2*w*z + 3*w + 5*x^2 + 2*x*y - 7*x*z - 7*x + 7*y^2 -8*y*z - 7*y + 7*z^2 - 8*z + 8),"
+ "(3*w^2 - 5*w*x - 3*w*y - 6*w*z + 9*w + 4*x^2 + 2*x*y - 2*x*z + 7*x + 9*y^2 + 6*y*z + 5*y + 7*z^2 + 7*z + 5),"
+ "(-2*w^2 + 9*w*x + 9*w*y - 7*w*z - 4*w + 8*x^2 + 9*x*y - 3*x*z + 8*x + 6*y^2 - 7*y*z + 4*y - 6*z^2 + 8*z + 2),"
+ "(7*w^2 + 5*w*x + 3*w*y - 5*w*z - 5*w + 2*x^2 + 9*x*y - 7*x*z + 4*x -4*y^2 - 5*y*z + 6*y - 4*z^2 - 9*z + 2)"
+ ") ";
String orderINV = "(w,x,y,z)";
String orderL = "(z,y,x,w)";
//Tests
String erg_deg = grad(orderL, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String erg3 = all(orderINV, polynomials);
System.out.println(all);
System.out.println(erg3);
String ergOnlyLex_1 = lex(orderINV, polynomials);
String ergOnlyLex_2 = lex(orderL, polynomials);
System.out.println(lex);
System.out.println(ergOnlyLex_1);
System.out.println(ergOnlyLex_2);
String ergOnlyFGLM_1 = fglm(orderINV, polynomials);
String ergOnlyFGLM_2 = fglm(orderL, polynomials);
System.out.println(fglm);
System.out.println(ergOnlyFGLM_1);
System.out.println(ergOnlyFGLM_2);
String ergm1 = modAll(orderINV, polynomials, 2147464751);
String ergm2 = modAll(orderL, polynomials, 2147464751);
System.out.println(modAll);
System.out.println(ergm1);
System.out.println(ergm2);
*/
}
public void xtestNiermann() {
String polynomials = "( " + " (x^2 + x*y^2*z - 2*x*y + y^4 + y^2 + z^2),"
+ "(-x^3*y^2 + x*y^2*z + x*y*z^3 - 2*x*y + y^4)," + "(-2*x^2*y + x*y^4 + y*z^4 - 3)"
+ ") ";
String orderINV = "(x,y,z)";
String orderL = "(z,y,x)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String erg1 = fglm(orderINV, polynomials);
String erg2 = fglm(orderL, polynomials);
System.out.println(fglm);
System.out.println(erg1);
System.out.println(erg2);
*/
String ergm1 = modfglm(orderINV, polynomials, 1831);
String ergm2 = modfglm(orderL, polynomials, 2147464751);
System.out.println(modfglm);
System.out.println(ergm1);
System.out.println(ergm2);
}
public void ytestWalkS7() {
String polynomials = "( " + " (2*g*b + 2*f*c + 2*e*d + a^2 + a),"
+ "(2*g*c + 2*f*d + e^2 + 2*b*a + b)," + "(2*g*d + 2*f*e + 2*c*a + c + b^2),"
+ "(2*g*e + f^2 + 2*d*a + d + 2*c*b)," + "(2*g*f + 2*e*a + e + 2*d*b + c^2),"
+ "(g^2 + 2*f*a + f + 2*e*b + 2*d*c)," + "(2*g*a + g + 2*f*b + 2*e*c + d^2)" + ") ";
String orderINV = "(a,b,c,d,e,f,g)";
String orderL = "(g,f,e,d,c,b,a)";
//Tests
//String ergm1 = modAll(orderINV, polynomials, 2147464751);
//String ergm2 = modfglm(orderL, polynomials, 1831);
//System.out.println(modfglm);
//System.out.println(ergm1);
//System.out.println(ergm2);
String erg2 = fglm(orderL, polynomials);
System.out.println(fglm);
System.out.println(erg2);
}
public void ytestCassouMod1() {
String polynomials = "( "
+ " (15*a^4*b*c^2 + 6*a^4*b^3 + 21*a^4*b^2*c - 144*a^2*b - 8*a^2*b^2*d - 28*a^2*b*c*d - 648*a^2*c + 36*c^2*d + 9*a^4*c^3 - 120),"
+ "(30*b^3*a^4*c - 32*c*d^2*b - 720*c*a^2*b - 24*b^3*a^2*d - 432*b^2*a^2 + 576*d*b - 576*c*d + 16*b*a^2*c^2*d + 16*c^2*d^2 + 16*d^2*b^2 + 9*b^4*a^4 + 5184 + 39*c^2*a^4*b^2 + 18*c^3*a^4*b - 432*c^2*a^2 + 24*c^3*a^2*d - 16*b^2*a^2*c*d - 240*b),"
+ "(216*c*a^2*b - 162*c^2*a^2 - 81*b^2*a^2 + 5184 + 1008*d*b - 1008*c*d + 15*b^2*a^2*c*d - 15*b^3*a^2*d - 80*c*d^2*b + 40*c^2*d^2 + 40*d^2*b^2),"
+ "(261 + 4*c*a^2*b - 3*c^2*a^2 - 4*b^2*a^2 + 22*d*b - 22*c*d)" + ") ";
String orderINV = "(a,b,c,d)";
String orderL = "(d,c,b,a)";
//Tests
String ergm1 = modfglm(orderL, polynomials, 1831);
String ergm2 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(ergm1);
System.out.println(ergm2);
}
public void ytestOmdi1() {
String polynomials = "( " + " (a + c + v + 2*x - 1)," + "(a*b + c*u + 2*v*w + 2*x*y + 2*x*z -2/3),"
+ "(a*b^2 + c*u^2 + 2*v*w^2 + 2*x*y^2 + 2*x*z^2 - 2/5),"
+ "(a*b^3 + c*u^3 + 2*v*w^3 + 2*x*y^3 + 2*x*z^3 - 2/7),"
+ "(a*b^4 + c*u^4 + 2*v*w^4 + 2*x*y^4 + 2*x*z^4 - 2/9)," + "(v*w^2 + 2*x*y*z - 1/9),"
+ "(v*w^4 + 2*x*y^2*z^2 - 1/25)," + "(v*w^3 + 2*x*y*z^2 + x*y^2*z - 1/15),"
+ "(v*w^4 + x*y*z^3 + x*y^3*z -1/21)" + ") ";
String orderINV = "(a,b,c,u,v,w,x,y,z)";
String orderL = "(z,y,x,w,v,u,c,b,a)";
//Tests
String erg_deg = grad(orderL, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String ergm1 = modfglm(orderL, polynomials, 1831);
String ergm2 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(ergm1);
System.out.println(ergm2);
*/
}
public void ytestLamm1() {
String polynomials = "( "
+ " (45*x^8 + 3*x^7 + 39*x^6 + 30*x^5 + 13*x^4 + 41*x^3 + 5*x^2 + 46*x + 7),"
+ "(49*x^7*y + 35*x*y^7 + 37*x*y^6 + 9*y^7 + 4*x^6 + 6*y^6 + 27*x^3*y^2 + 20*x*y^4 + 31*x^4 + 33*x^2*y + 24*x^2 + 49*y + 43)"
+ ") ";
String orderINV = "(x,y)";
String orderL = "(y,x)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
//===================================================================
//Examples taken from "Some Examples for Solving Systems of Algebraic Equations by Calculating Gröbner Bases", 1984, Boege, Gebauer, Kredel
//===================================================================
public void xtestEquilibrium() {
String polynomials = "( "
+ " (y^4 - 20/7*z^2),"
+ "(z^2*x^4 + 7/10*z*x^4 + 7/48*x^4 - 50/27*z^2 - 35/27*z - 49/216),"
+ "(x^5*y^3 + 7/5*z^4*y^3 + 609/1000 *z^3*y^3 + 49/1250*z^2*y^3 - 27391/800000*z*y^3 - 1029/160000*y^3 + 3/7*z^5*x*y^2 +"
+ "3/5*z^6*x*y^2 + 63/200*z^3*x*y^2 + 147/2000*z^2*x*y^2 + 4137/800000*z*x*y^2 - 7/20*z^4*x^2*y - 77/125*z^3*x^2*y"
+ "- 23863/60000*z^2*x^2*y - 1078/9375*z*x^2*y - 24353/1920000*x^2*y - 3/20*z^4*x^3 - 21/100*z^3*x^3"
+ "- 91/800*z^2*x^3 - 5887/200000*z*x^3 - 343/128000*x^3)" + ") ";
String order = "(x,y,z)";
//Tests
String ergOnlyG_1 = grad(order, polynomials);
System.out.println(grad);
System.out.println(ergOnlyG_1);
}
public void xtestTrinks2() {
String polynomials = "( " + " (45*p + 35*s - 165*b - 36)," + "(35*p + 40*z + 25*t - 27*s),"
+ "(15*w + 25*p*s + 30*z - 18*t - 165*b^2)," + "(-9*w + 15*p*t + 20*z*s),"
+ "(w*p + 2*z*t - 11*b^3)," + "(99*w - 11*s*b + 3*b^2),"
+ "(b^2 + 33/50*b + 2673/10000)" + ") ";
String order1 = "(b,s,t,z,p,w)";
String order2 = "(s,b,t,z,p,w)";
String order3 = "(s,t,b,z,p,w)";
String order4 = "(s,t,z,p,b,w)";
String order5 = "(s,t,z,p,w,b)";
String order6 = "(s,z,p,w,b,t)";
String order7 = "(p,w,b,t,s,z)";
String order8 = "(z,w,b,s,t,p)";
String order9 = "(t,z,p,w,b,s)";
String order10 = "(z,p,w,b,s,t)";
String order11 = "(p,w,b,s,t,z)";
String order12 = "(w,b,s,t,z,p)";
//Tests
String erg_1 = all(order1, polynomials);
String erg_2 = all(order2, polynomials);
String erg_3 = all(order3, polynomials);
String erg_4 = all(order4, polynomials);
String erg_5 = all(order5, polynomials);
String erg_6 = all(order6, polynomials);
String erg_7 = all(order7, polynomials);
String erg_8 = all(order8, polynomials);
String erg_9 = all(order9, polynomials);
String erg_10 = all(order10, polynomials);
String erg_11 = all(order11, polynomials);
String erg_12 = all(order12, polynomials);
System.out.println(all);
System.out.println(erg_1);
System.out.println(erg_2);
System.out.println(erg_3);
System.out.println(erg_4);
System.out.println(erg_5);
System.out.println(erg_6);
System.out.println(erg_7);
System.out.println(erg_8);
System.out.println(erg_9);
System.out.println(erg_10);
System.out.println(erg_11);
System.out.println(erg_12);
}
public void xtestHairerRungeKutta_1() {
String polynomials = "( " + " (a-f),(b-h-g),(e+d+c-1),(d*a+c*b-1/2),(d*a^2+c*b^2-1/3),(c*g*a-1/6)"
+ ") ";
String[] order = new String[] { "a", "b", "c", "d", "e", "f", "g", "h" };
String order1 = shuffle(order);
String order2 = shuffle(order);
String order3 = shuffle(order);
String order4 = shuffle(order);
String order5 = shuffle(order);
// langsam (e,d,h,c,g,a,f,b), (h,d,b,e,c,g,a,f) um die 120
// sehr langsam (e,h,d,c,g,b,a,f) um die 1000
// sehr schnell (g,b,f,h,c,d,a,e), (h,c,a,g,d,f,e,b) 1 millisec
String ergOnlyG_1 = grad(order1, polynomials);
System.out.println(grad);
System.out.println(ergOnlyG_1);
String ergOnlyL_1 = lex(order1, polynomials);
String ergOnlyL_2 = lex(order2, polynomials);
String ergOnlyL_3 = lex(order3, polynomials);
String ergOnlyL_4 = lex(order4, polynomials);
String ergOnlyL_5 = lex(order5, polynomials);
System.out.println(lex);
System.out.println(ergOnlyL_1);
System.out.println(ergOnlyL_2);
System.out.println(ergOnlyL_3);
System.out.println(ergOnlyL_4);
System.out.println(ergOnlyL_5);
//String ergGeneral = all(order, polynomials);
//System.out.println(all);
//System.out.println(ergGeneral);
}
//=================================================================================================
//Internal methods
//=================================================================================================
@SuppressWarnings("unchecked")
public String all(String order, String polynomials) {
GroebnerBaseFGLM<BigRational> IdealObjectFGLM;
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Grad = order + " G " + polynomials;
String polynomials_Lex = order + " L " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG);
PolynomialList<BigRational> G = null;
Reader sourceL = new StringReader(polynomials_Lex);
GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL);
PolynomialList<BigRational> L = null;
try {
G = (PolynomialList<BigRational>) parserG.nextPolynomialSet();
L = (PolynomialList<BigRational>) parserL.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + G);
System.out.println("Input " + L);
//Computation of the Groebnerbase with Buchberger w.r.t INVLEX
long buchberger_Lex = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GL = gb.GB(L.list);
buchberger_Lex = System.currentTimeMillis() - buchberger_Lex;
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG);
//PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL);
IdealObjectFGLM = new GroebnerBaseFGLM<BigRational>(); //GGG);
//IdealObjectLex = new GroebnerBaseSeq<BigRational>(GLL);
long tconv = System.currentTimeMillis();
List<GenPolynomial<BigRational>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG);
OrderedPolynomialList<BigRational> o2 = new OrderedPolynomialList<BigRational>(
resultFGLM.get(0).ring, resultFGLM);
//List<GenPolynomial<BigRational>> resultBuchberger = GL;
OrderedPolynomialList<BigRational> o3 = new OrderedPolynomialList<BigRational>(GL.get(0).ring, GL);
int grad_numberOfElements = GG.size();
int lex_numberOfElements = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); // IdealObjectFGLM.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GL); // IdealObjectLex.maxDegreeOfGB();
int grad_height = bitHeight(GG);
int lex_height = bitHeight(resultFGLM);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
System.out.println("Groebnerbase Buchberger (INVLEX) " + o3);
String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |"
+ lex_numberOfElements + " |" + grad_height + " |" + lex_height
+ " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |"
+ buchberger_Grad + " |" + tconv + " |" + buchberger_Lex;
//assertEquals(o2, o3);
if (! o2.equals(o3) ) {
throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3);
}
return erg;
}
@SuppressWarnings("unchecked")
public String fglm(String order, String polynomials) {
GroebnerBaseFGLM<BigRational> IdealObjectGrad;
//GroebnerBaseAbstract<BigRational> IdealObjectLex;
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Grad = order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG);
PolynomialList<BigRational> G = null;
try {
G = (PolynomialList<BigRational>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG);
IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG);
long tconv = System.currentTimeMillis();
List<GenPolynomial<BigRational>> resultFGLM = IdealObjectGrad.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
//PolynomialList<BigRational> LLL = new PolynomialList<BigRational>(G.ring, resultFGLM);
//IdealObjectLex = new GroebnerBaseSeq<BigRational>(); //LLL);
OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG);
OrderedPolynomialList<BigRational> o2 = new OrderedPolynomialList<BigRational>(
resultFGLM.get(0).ring, resultFGLM);
int grad_numberOfElements = GG.size();
int lex_numberOfElements = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); //IdealObjectGrad.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(resultFGLM); //IdealObjectLex.maxDegreeOfGB();
int grad_height = bitHeight(GG);
int lex_height = bitHeight(resultFGLM);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |"
+ lex_numberOfElements + " |" + grad_height + " |" + lex_height + " |"
+ grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad
+ " |" + tconv;
return erg;
}
@SuppressWarnings("unchecked")
public String grad(String order, String polynomials) {
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Grad = order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG);
PolynomialList<BigRational> G = null;
try {
G = (PolynomialList<BigRational>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG);
OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG);
GroebnerBaseFGLM<BigRational> IdealObjectGrad;
IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG);
long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); //IdealObjectGrad.maxDegreeOfGB();
List<GenPolynomial<BigRational>> reducedTerms = IdealObjectGrad.redTerms(GG);
OrderedPolynomialList<BigRational> o4 = new OrderedPolynomialList<BigRational>(
reducedTerms.get(0).ring, reducedTerms);
int grad_numberOfReducedElements = reducedTerms.size();
int grad_numberOfElements = GG.size();
int grad_height = bitHeight(GG);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Reduced Terms" + o4);
String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + grad_height + " |"
+ grad_maxPolyGrad + " |" + buchberger_Grad + " |"
+ grad_numberOfReducedElements;
return erg;
}
@SuppressWarnings("unchecked")
public String lex(String order, String polynomials) {
//GroebnerBaseAbstract<BigRational> IdealObjectLex;
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Lex = order + " L " + polynomials;
Reader sourceL = new StringReader(polynomials_Lex);
GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL);
PolynomialList<BigRational> L = null;
try {
L = (PolynomialList<BigRational>) parserL.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + L);
//Computation of the Groebnerbase with Buchberger w.r.t INVLEX
long buchberger_Lex = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GL = gb.GB(L.list);
buchberger_Lex = System.currentTimeMillis() - buchberger_Lex;
//PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL);
//IdealObjectLex = new GroebnerBaseAbstract<BigRational>(GLL);
OrderedPolynomialList<BigRational> o3 = new OrderedPolynomialList<BigRational>(GL.get(0).ring, GL);
int lex_numberOfElements = GL.size();
long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GL); //IdealObjectLex.maxDegreeOfGB();
int lexHeigth = bitHeight(GL);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbase Buchberger (INVLEX) " + o3);
String erg = "BigRational" + order + "|" + lex_numberOfElements + " |" + lexHeigth + " |"
+ lex_maxPolyGrad + " |" + buchberger_Lex;
return erg;
}
@SuppressWarnings("unchecked")
public String modAll(String order, String polynomials, Integer m) {
GroebnerBaseFGLM<ModInteger> IdealObjectFGLM;
//GroebnerBaseAbstract<ModInteger> IdealObjectLex;
ModIntegerRing ring = new ModIntegerRing(m);
GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring);
String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials;
String polynomials_Lex = "Mod " + ring.modul + " " + order + " L " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG);
PolynomialList<ModInteger> G = null;
Reader sourceL = new StringReader(polynomials_Lex);
GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL);
PolynomialList<ModInteger> L = null;
try {
G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet();
L = (PolynomialList<ModInteger>) parserL.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("G= " + G);
System.out.println("L= " + L);
//Computation of the Groebnerbase with Buchberger w.r.t INVLEX
long buchberger_Lex = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GL = gb.GB(L.list);
buchberger_Lex = System.currentTimeMillis() - buchberger_Lex;
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG);
//PolynomialList<ModInteger> GLL = new PolynomialList<ModInteger>(L.ring, GL);
IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG);
//IdealObjectLex = new GroebnerBaseAbstract<ModInteger>(GLL);
long tconv = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG);
OrderedPolynomialList<ModInteger> o2 = new OrderedPolynomialList<ModInteger>(resultFGLM.get(0).ring,
resultFGLM);
List<GenPolynomial<ModInteger>> resultBuchberger = GL;
OrderedPolynomialList<ModInteger> o3 = new OrderedPolynomialList<ModInteger>(
resultBuchberger.get(0).ring, resultBuchberger);
int grad_numberOfElements = GG.size();
int lex_numberOfElements = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GL); //IdealObjectLex.maxDegreeOfGB();
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
System.out.println("Groebnerbase Buchberger (INVLEX) " + o3);
String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |"
+ lex_numberOfElements + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad
+ " |" + buchberger_Grad + " |" + tconv + " |" + buchberger_Lex;
//assertEquals(o2, o3);
if (! o2.equals(o3) ) {
throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3);
}
return erg;
}
@SuppressWarnings("unchecked")
public String modGrad(String order, String polynomials, Integer m) {
//GroebnerBaseFGLM<ModInteger> IdealObjectFGLM;
ModIntegerRing ring = new ModIntegerRing(m);
GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring);
String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG);
PolynomialList<ModInteger> G = null;
try {
G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("G= " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG);
//IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG);
OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG);
int grad_numberOfElements = GG.size();
long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB();
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |"
+ grad_maxPolyGrad + " |" + buchberger_Grad;
return erg;
}
@SuppressWarnings("unchecked")
public String modfglm(String order, String polynomials, Integer m) {
GroebnerBaseFGLM<ModInteger> IdealObjectFGLM;
//GroebnerBaseAbstract<ModInteger> IdealObjectLex;
ModIntegerRing ring = new ModIntegerRing(m);
GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring);
String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG);
PolynomialList<ModInteger> G = null;
try {
G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("G= " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG);
IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG);
long tconv = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
//PolynomialList<ModInteger> LLL = new PolynomialList<ModInteger>(G.ring, resultFGLM);
//IdealObjectLex = new GroebnerBaseAbstract<ModInteger>(LLL);
OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG);
OrderedPolynomialList<ModInteger> o2 = new OrderedPolynomialList<ModInteger>(resultFGLM.get(0).ring,
resultFGLM);
int grad_numberOfElements = GG.size();
int lex_numberOfElements = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(resultFGLM); //IdealObjectLex.maxDegreeOfGB();
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |"
+ lex_numberOfElements + " |" + grad_maxPolyGrad + " |"
+ lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv;
return erg;
}
/**
* Method shuffle returns a random permutation of a string of variables.
*/
public String shuffle(String[] tempOrder) {
Collections.shuffle(Arrays.asList(tempOrder));
StringBuffer ret = new StringBuffer("(");
ret.append(ExpVector.varsToString(tempOrder));
ret.append(")");
return ret.toString();
}
/**
* Method bitHeight returns the bitlength of the greatest number
* occurring during the computation of a Groebner base.
*/
public int bitHeight(List<GenPolynomial<BigRational>> list) {
BigInteger denom = BigInteger.ONE;
BigInteger num = BigInteger.ONE;
for (GenPolynomial<BigRational> g : list) {
for (Monomial<BigRational> m : g) {
BigRational bi = m.coefficient();
BigInteger i = bi.denominator().abs();
BigInteger j = bi.numerator().abs();
if (i.compareTo(denom) > 0)
denom = i;
if (j.compareTo(num) > 0)
num = j;
}
}
int erg;
if (denom.compareTo(num) > 0) {
erg = denom.bitLength();
} else {
erg = num.bitLength();
}
return erg;
}
}
| breandan/java-algebra-system | src/edu/jas/gbufd/GroebnerBaseFGLMExamples.java | Java | gpl-2.0 | 44,052 |
/*
* TrxFormController.java
*
* Created on Jan 9, 2010 8:22:32 PM
*
* Copyright (c) 2002 - 2010 : Swayam Inc.
*
* P R O P R I E T A R Y & C O N F I D E N T I A L
*
* The copyright of this document is vested in Swayam Inc. without
* whose prior written permission its contents must not be published,
* adapted or reproduced in any form or disclosed or
* issued to any third party.
*/
package com.swayam.ims.webapp.controller.trx;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
*
* @author paawak
*/
public abstract class TrxFormController implements Controller {
final TrxModeIndicator modeIndicator;
private String formView;
public TrxFormController(TrxModeIndicator modeIndicator) {
this.modeIndicator = modeIndicator;
}
public final void setFormView(String formView) {
this.formView = formView;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView modelNView = new ModelAndView(formView);
modelNView.addObject("isPurchaseMode", modeIndicator.isPurchaseMode());
return modelNView;
}
}
| paawak/blog | code/SpringMVCWithFlex/ims-web/src/main/java/com/swayam/ims/webapp/controller/trx/TrxFormController.java | Java | gpl-2.0 | 1,332 |
package com.moon.threadlocal;
import org.junit.Test;
/**
* Created by Paul on 2017/2/12.
*/
public class SequenceA implements Sequence{
private static int number=0;
@Override
public int getNumber(){
number=number+1;
return number;
}
}
| linpingchuan/misc | java/framework/src/test/java/com/moon/threadlocal/SequenceA.java | Java | gpl-2.0 | 272 |
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.nodes.builtin.base;
import static com.oracle.truffle.r.nodes.builtin.CastBuilder.Predef.stringValue;
import static com.oracle.truffle.r.runtime.RError.Message.MUST_BE_NONNULL_STRING;
import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE;
import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Fallback;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.r.nodes.attributes.RemoveAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SetAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetClassAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetDimAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetRowNamesAttributeNode;
import com.oracle.truffle.r.nodes.builtin.RBuiltinNode;
import com.oracle.truffle.r.nodes.builtin.base.UpdateAttrNodeGen.InternStringNodeGen;
import com.oracle.truffle.r.nodes.unary.CastIntegerNode;
import com.oracle.truffle.r.nodes.unary.CastIntegerNodeGen;
import com.oracle.truffle.r.nodes.unary.CastListNode;
import com.oracle.truffle.r.nodes.unary.CastToVectorNode;
import com.oracle.truffle.r.nodes.unary.CastToVectorNodeGen;
import com.oracle.truffle.r.nodes.unary.GetNonSharedNode;
import com.oracle.truffle.r.runtime.RError;
import com.oracle.truffle.r.runtime.RError.Message;
import com.oracle.truffle.r.runtime.RRuntime;
import com.oracle.truffle.r.runtime.Utils;
import com.oracle.truffle.r.runtime.builtins.RBuiltin;
import com.oracle.truffle.r.runtime.data.RAttributable;
import com.oracle.truffle.r.runtime.data.RDataFactory;
import com.oracle.truffle.r.runtime.data.RNull;
import com.oracle.truffle.r.runtime.data.RShareable;
import com.oracle.truffle.r.runtime.data.RStringVector;
import com.oracle.truffle.r.runtime.data.model.RAbstractContainer;
import com.oracle.truffle.r.runtime.data.model.RAbstractIntVector;
import com.oracle.truffle.r.runtime.data.model.RAbstractVector;
@RBuiltin(name = "attr<-", kind = PRIMITIVE, parameterNames = {"x", "which", "value"}, behavior = PURE)
public abstract class UpdateAttr extends RBuiltinNode.Arg3 {
@Child private UpdateNames updateNames;
@Child private UpdateDimNames updateDimNames;
@Child private CastIntegerNode castInteger;
@Child private CastToVectorNode castVector;
@Child private CastListNode castList;
@Child private SetClassAttributeNode setClassAttrNode;
@Child private SetRowNamesAttributeNode setRowNamesAttrNode;
@Child private SetAttributeNode setGenAttrNode;
@Child private SetDimAttributeNode setDimNode;
@Child private InternStringNode intern = InternStringNodeGen.create();
public abstract static class InternStringNode extends Node {
public abstract String execute(String value);
@Specialization(limit = "3", guards = "value == cachedValue")
protected static String internCached(@SuppressWarnings("unused") String value,
@SuppressWarnings("unused") @Cached("value") String cachedValue,
@Cached("intern(value)") String interned) {
return interned;
}
@Specialization(replaces = "internCached")
protected static String intern(String value) {
return Utils.intern(value);
}
}
static {
Casts casts = new Casts(UpdateAttr.class);
// Note: cannot check 'attributability' easily because atomic values, e.g int, are not
// RAttributable.
casts.arg("x");
casts.arg("which").defaultError(MUST_BE_NONNULL_STRING, "name").mustBe(stringValue()).asStringVector().findFirst();
}
private RAbstractContainer updateNames(RAbstractContainer container, Object o) {
if (updateNames == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
updateNames = insert(UpdateNamesNodeGen.create());
}
return (RAbstractContainer) updateNames.executeStringVector(container, o);
}
private RAbstractContainer updateDimNames(RAbstractContainer container, Object o) {
if (updateDimNames == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
updateDimNames = insert(UpdateDimNamesNodeGen.create());
}
return updateDimNames.executeRAbstractContainer(container, o);
}
private RAbstractIntVector castInteger(RAbstractVector vector) {
if (castInteger == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
castInteger = insert(CastIntegerNodeGen.create(true, false, false));
}
return (RAbstractIntVector) castInteger.doCast(vector);
}
private RAbstractVector castVector(Object value) {
if (castVector == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
castVector = insert(CastToVectorNodeGen.create(false));
}
return (RAbstractVector) castVector.doCast(value);
}
@Specialization
protected RNull updateAttr(@SuppressWarnings("unused") RNull nullTarget, @SuppressWarnings("unused") String attrName, @SuppressWarnings("unused") RNull nullAttrVal) {
return RNull.instance;
}
@Specialization
protected RAbstractContainer updateAttr(RAbstractContainer container, String name, RNull value,
@Cached("create()") RemoveAttributeNode removeAttrNode,
@Cached("create()") GetNonSharedNode nonShared) {
String internedName = intern.execute(name);
RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize();
// the name is interned, so identity comparison is sufficient
if (internedName == RRuntime.DIM_ATTR_KEY) {
if (setDimNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setDimNode = insert(SetDimAttributeNode.create());
}
setDimNode.setDimensions(result, null);
} else if (internedName == RRuntime.NAMES_ATTR_KEY) {
return updateNames(result, value);
} else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) {
return updateDimNames(result, value);
} else if (internedName == RRuntime.CLASS_ATTR_KEY) {
if (setClassAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setClassAttrNode = insert(SetClassAttributeNode.create());
}
setClassAttrNode.reset(result);
return result;
} else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) {
if (setRowNamesAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create());
}
setRowNamesAttrNode.setRowNames(result, null);
} else if (result.getAttributes() != null) {
removeAttrNode.execute(result, internedName);
}
return result;
}
@TruffleBoundary
protected static RStringVector convertClassAttrFromObject(Object value) {
if (value instanceof RStringVector) {
return (RStringVector) value;
} else if (value instanceof String) {
return RDataFactory.createStringVector((String) value);
} else {
throw RError.error(RError.SHOW_CALLER, RError.Message.SET_INVALID_CLASS_ATTR);
}
}
@Specialization(guards = "!isRNull(value)")
protected RAbstractContainer updateAttr(RAbstractContainer container, String name, Object value,
@Cached("create()") GetNonSharedNode nonShared) {
String internedName = intern.execute(name);
RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize();
// the name is interned, so identity comparison is sufficient
if (internedName == RRuntime.DIM_ATTR_KEY) {
RAbstractIntVector dimsVector = castInteger(castVector(value));
if (dimsVector.getLength() == 0) {
throw error(RError.Message.LENGTH_ZERO_DIM_INVALID);
}
if (setDimNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setDimNode = insert(SetDimAttributeNode.create());
}
setDimNode.setDimensions(result, dimsVector.materialize().getDataCopy());
} else if (internedName == RRuntime.NAMES_ATTR_KEY) {
return updateNames(result, value);
} else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) {
return updateDimNames(result, value);
} else if (internedName == RRuntime.CLASS_ATTR_KEY) {
if (setClassAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setClassAttrNode = insert(SetClassAttributeNode.create());
}
setClassAttrNode.execute(result, convertClassAttrFromObject(value));
return result;
} else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) {
if (setRowNamesAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create());
}
setRowNamesAttrNode.setRowNames(result, castVector(value));
} else {
// generic attribute
if (setGenAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setGenAttrNode = insert(SetAttributeNode.create());
}
setGenAttrNode.execute(result, internedName, value);
}
return result;
}
/**
* All other, non-performance centric, {@link RAttributable} types.
*/
@Fallback
@TruffleBoundary
protected Object updateAttr(Object obj, Object name, Object value) {
assert name instanceof String : "casts should not pass anything but String";
Object object = obj;
if (object instanceof RShareable) {
object = ((RShareable) object).getNonShared();
}
String internedName = intern.execute((String) name);
if (object instanceof RAttributable) {
RAttributable attributable = (RAttributable) object;
if (value == RNull.instance) {
attributable.removeAttr(internedName);
} else {
attributable.setAttr(internedName, value);
}
return object;
} else if (RRuntime.isForeignObject(obj)) {
throw RError.error(this, Message.OBJ_CANNOT_BE_ATTRIBUTED);
} else if (obj == RNull.instance) {
throw RError.error(this, Message.SET_ATTRIBUTES_ON_NULL);
} else {
throw RError.nyi(this, "object cannot be attributed: ");
}
}
}
| akunft/fastr | com.oracle.truffle.r.nodes.builtin/src/com/oracle/truffle/r/nodes/builtin/base/UpdateAttr.java | Java | gpl-2.0 | 12,281 |
package com.yao.app.java.nio.pipe;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
public class Test {
public static void main(String[] args) {
try {
Pipe pipe = Pipe.open();
Thread t1 = new Thread(new MessageOutput(pipe));
Thread t2 = new Thread(new MessageInput(pipe));
t2.start();
Thread.sleep(1000);
t1.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MessageOutput implements Runnable {
private Pipe pipe;
public MessageOutput(Pipe pipe) {
this.pipe = pipe;
}
@Override
public void run() {
try {
String message = "hello world,libailugo";
ByteBuffer buf = ByteBuffer.wrap(message.getBytes());
Pipe.SinkChannel channel = pipe.sink();
int count = channel.write(buf);
channel.close();
System.out.println("send message:" + message + ",length:"
+ count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class MessageInput implements Runnable {
private Pipe pipe;
public MessageInput(Pipe pipe) {
this.pipe = pipe;
}
@Override
public void run() {
try {
Pipe.SourceChannel channel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(10);
StringBuilder sb = new StringBuilder();
int count = channel.read(buf);
while (count > 0) {
// 此处会导致错误
// sb.append(new String(buf.array()));
sb.append(new String(buf.array(), 0, count));
buf.clear();
count = channel.read(buf);
}
channel.close();
System.out.println("recieve message:" + sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| yaolei313/hello-world | utils/src/main/java/com/yao/app/java/nio/pipe/Test.java | Java | gpl-2.0 | 2,218 |
package com.oa.bean;
public class FeedBackInfo {
private Long id;
private String feedbackinfo;
private String userid;
private String date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFeedbackinfo() {
return feedbackinfo;
}
public void setFeedbackinfo(String feedbackinfo) {
this.feedbackinfo = feedbackinfo;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| yiyuweier/OA-project | src/com/oa/bean/FeedBackInfo.java | Java | gpl-2.0 | 617 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest17998")
public class BenchmarkTest17998 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> names = request.getParameterNames();
if (names.hasMoreElements()) {
param = names.nextElement(); // just grab first element
}
String bar = doSomething(param);
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar),false);
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = "safe!";
java.util.HashMap<String,Object> map37923 = new java.util.HashMap<String,Object>();
map37923.put("keyA-37923", "a_Value"); // put some stuff in the collection
map37923.put("keyB-37923", param.toString()); // put it in a collection
map37923.put("keyC", "another_Value"); // put some stuff in the collection
bar = (String)map37923.get("keyB-37923"); // get it back out
bar = (String)map37923.get("keyA-37923"); // get safe value back out
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest17998.java | Java | gpl-2.0 | 2,474 |
package adamros.mods.transducers.item;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import adamros.mods.transducers.Transducers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
public class ItemElectricEngine extends ItemBlock
{
public ItemElectricEngine(int par1)
{
super(par1);
setHasSubtypes(true);
setMaxDamage(0);
setUnlocalizedName("itemElectricEngine");
setCreativeTab(Transducers.tabTransducers);
}
@Override
public int getMetadata(int meta)
{
return meta;
}
@Override
public String getUnlocalizedName(ItemStack is)
{
String suffix;
switch (is.getItemDamage())
{
case 0:
suffix = "lv";
break;
case 1:
suffix = "mv";
break;
case 2:
suffix = "hv";
break;
case 3:
suffix = "ev";
break;
default:
suffix = "lv";
break;
}
return getUnlocalizedName() + "." + suffix;
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4)
{
super.addInformation(par1ItemStack, par2EntityPlayer, par3List, par4);
String type;
switch (par1ItemStack.getItemDamage())
{
case 0:
type = "lv";
break;
case 1:
type = "mv";
break;
case 2:
type = "hv";
break;
case 3:
type = "ev";
break;
default:
type = "lv";
break;
}
par3List.add(StatCollector.translateToLocal("tip.electricEngine." + type).trim());
}
}
| adamros/Transducers | adamros/mods/transducers/item/ItemElectricEngine.java | Java | gpl-2.0 | 2,146 |
package lambda;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Esempio extends JFrame {
public Esempio()
{
init();
}
private void init() {
BorderLayout b=new BorderLayout();
this.setLayout(b);
JButton button=new JButton("Ok");
this.add(button,BorderLayout.SOUTH);
this.setSize(400, 300);
this.setVisible(true);
ActionListener l=new Azione();
button.addActionListener(( e) -> System.out.println("ciao"));
}
public static void main(String[] args) {
Esempio e=new Esempio();
}
}
| manuelgentile/MAP | java8/java8_lambda/src/main/java/lambda/Esempio.java | Java | gpl-2.0 | 663 |
/*
You may freely copy, distribute, modify and use this class as long
as the original author attribution remains intact. See message
below.
Copyright (C) 1998-2006 Christian Pesch. All Rights Reserved.
*/
package slash.carcosts;
import slash.gui.model.AbstractModel;
/**
* An CurrencyModel holds a Currency and provides get and set
* methods for it.
*
* @author Christian Pesch
*/
public class CurrencyModel extends AbstractModel {
/**
* Construct a new CurrencyModel.
*/
public CurrencyModel() {
this(Currency.getCurrency("DM"));
}
/**
* Construct a new CurrencyModel.
*/
public CurrencyModel(Currency value) {
setValue(value);
}
/**
* Get the Currency value that is holded by the model.
*/
public Currency getValue() {
return value;
}
/**
* Set the Currency value to hold.
*/
public void setValue(Currency newValue) {
if (value != newValue) {
this.value = newValue;
fireStateChanged();
}
}
public String toString() {
return "CurrencyModel(" + value + ")";
}
private Currency value;
}
| cpesch/CarCosts | car-costs/src/main/java/slash/carcosts/CurrencyModel.java | Java | gpl-2.0 | 1,184 |
/**
* Ядро булевой логики
*/
/**
* @author Алексей Кляузер <drum@pisem.net>
* Ядро булевой логики
*/
package org.deneblingvo.booleans.core; | AlexAbak/ReversibleComputing | package/src/org/deneblingvo/booleans/core/package-info.java | Java | gpl-2.0 | 192 |
package de.superioz.moo.network.client;
import de.superioz.moo.network.server.NetworkServer;
import lombok.Getter;
import de.superioz.moo.api.collection.UnmodifiableList;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* The hub for storing the client connections
*
* @see MooClient
*/
public final class ClientManager {
/**
* It is only necessary to only have one ClientHub instance so this is the static access for this
* class after it has been initialised by the network server
*/
@Getter
private static ClientManager instance;
/**
* The connected {@link MooClient}'s by the type of them
*/
private ConcurrentMap<ClientType, Map<InetSocketAddress, MooClient>> clientsByType = new ConcurrentHashMap<>();
/**
* The ram usage of every daemon (as socketaddress) as percent
*/
@Getter
private Map<InetSocketAddress, Integer> daemonRamUsage = new HashMap<>();
/**
* The netty server the clients are connected to
*/
private NetworkServer netServer;
public ClientManager(NetworkServer netServer) {
instance = this;
this.netServer = netServer;
for(ClientType clientType : ClientType.values()) {
clientsByType.put(clientType, new HashMap<>());
}
}
/**
* Updates the ramUsage of a daemon
*
* @param address The address of the daemon/server
* @param ramUsage The ramUsage in per cent
*/
public void updateRamUsage(InetSocketAddress address, int ramUsage) {
Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON);
if(!daemonClients.containsKey(address)) return;
daemonRamUsage.put(address, ramUsage);
}
/**
* Gets the best available daemon where the ram usage is the lowest
*
* @return The client
*/
public MooClient getBestDaemon() {
Map<InetSocketAddress, MooClient> daemonClients = clientsByType.get(ClientType.DAEMON);
if(daemonClients.isEmpty()) return null;
int lowesRamUsage = -1;
MooClient lowestRamUsageClient = null;
for(InetSocketAddress address : daemonClients.keySet()) {
if(!daemonRamUsage.containsKey(address)) continue;
MooClient client = daemonClients.get(address);
int ramUsage = daemonRamUsage.get(address);
if((lowesRamUsage == -1 || lowesRamUsage > ramUsage)
&& !((lowesRamUsage = ramUsage) >= (Integer) netServer.getConfig().get("slots-ram-usage"))) {
lowestRamUsageClient = client;
}
}
return lowestRamUsageClient;
}
/**
* Adds a client to the hub
*
* @param cl The client
* @return The size of the map
*/
public int add(MooClient cl) {
Map<InetSocketAddress, MooClient> map = clientsByType.get(cl.getType());
map.put(cl.getAddress(), cl);
if(cl.getType() == ClientType.DAEMON) {
daemonRamUsage.put(cl.getAddress(), 0);
}
return map.size();
}
/**
* Removes a client from the hub
*
* @param address The address (the key)
* @return This
*/
public ClientManager remove(InetSocketAddress address) {
for(Map<InetSocketAddress, MooClient> m : clientsByType.values()) {
m.entrySet().removeIf(entry -> entry.getKey().equals(address));
}
return this;
}
public ClientManager remove(MooClient cl) {
return remove(cl.getAddress());
}
/**
* Gets a client from address
*
* @param address The address
* @return The client
*/
public MooClient get(InetSocketAddress address) {
MooClient client = null;
for(Map.Entry<ClientType, Map<InetSocketAddress, MooClient>> entry : clientsByType.entrySet()) {
if(entry.getValue().containsKey(address)) {
client = entry.getValue().get(address);
}
}
return client;
}
public boolean contains(InetSocketAddress address) {
return get(address) != null;
}
/**
* Get clients (from type)
*
* @param type The type
* @return The list of clients (unmodifiable)
*/
public UnmodifiableList<MooClient> getClients(ClientType type) {
Map<InetSocketAddress, MooClient> map = clientsByType.get(type);
return new UnmodifiableList<>(map.values());
}
/**
* Get all clients inside one list
*
* @return The list of clients
*/
public List<MooClient> getAll() {
List<MooClient> clients = new ArrayList<>();
for(ClientType clientType : ClientType.values()) {
clients.addAll(getClients(clientType));
}
return clients;
}
public UnmodifiableList<MooClient> getMinecraftClients() {
List<MooClient> clients = new ArrayList<>();
clients.addAll(getClients(ClientType.PROXY));
clients.addAll(getClients(ClientType.SERVER));
return new UnmodifiableList<>(clients);
}
public UnmodifiableList<MooClient> getServerClients() {
return getClients(ClientType.SERVER);
}
public UnmodifiableList<MooClient> getProxyClients() {
return getClients(ClientType.PROXY);
}
public UnmodifiableList<MooClient> getCustomClients() {
return getClients(ClientType.CUSTOM);
}
public UnmodifiableList<MooClient> getDaemonClients() {
return getClients(ClientType.DAEMON);
}
}
| Superioz/MooProject | network/src/main/java/de/superioz/moo/network/client/ClientManager.java | Java | gpl-2.0 | 5,716 |
package ch.hgdev.toposuite.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Useful static method for manipulating String.
*
* @author HGdev
*/
public class StringUtils {
public static final String UTF8_BOM = "\uFEFF";
/**
* This method assumes that the String contains a number.
*
* @param str A String.
* @return The String incremented by 1.
* @throws IllegalArgumentException Thrown if the input String does not end with a suitable
* number.
*/
public static String incrementAsNumber(String str) throws IllegalArgumentException {
if (str == null) {
throw new IllegalArgumentException("The input String must not be null!");
}
Pattern p = Pattern.compile("([0-9]+)$");
Matcher m = p.matcher(str);
if (!m.find()) {
throw new IllegalArgumentException(
"Invalid input argument! The input String must end with a valid number");
}
String number = m.group(1);
String prefix = str.substring(0, str.length() - number.length());
return prefix + String.valueOf(Integer.valueOf(number) + 1);
}
}
| hgdev-ch/toposuite-android | app/src/main/java/ch/hgdev/toposuite/utils/StringUtils.java | Java | gpl-2.0 | 1,224 |
package org.currconv.services.impl;
import java.util.List;
import org.currconv.dao.UserDao;
import org.currconv.entities.user.User;
import org.currconv.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao dao;
public void saveUser(User user) {
dao.saveUser(user);
}
public List<User> findAllUsers(){
return dao.findAllUsers();
}
public User findByUserName(String name){
return dao.findByUserName(name);
}
} | miguel-gr/currency-converter | src/main/java/org/currconv/services/impl/UserServiceImpl.java | Java | gpl-2.0 | 738 |
package com.debugtoday.htmldecoder.output;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import org.slf4j.Logger;
import com.debugtoday.htmldecoder.decoder.GeneralDecoder;
import com.debugtoday.htmldecoder.exception.GeneralException;
import com.debugtoday.htmldecoder.log.CommonLog;
import com.debugtoday.htmldecoder.output.object.FileOutputArg;
import com.debugtoday.htmldecoder.output.object.PaginationOutputArg;
import com.debugtoday.htmldecoder.output.object.TagFileOutputArg;
import com.debugtoday.htmldecoder.output.object.TagOutputArg;
import com.debugtoday.htmldecoder.output.object.TagWrapper;
import com.debugtoday.htmldecoder.output.object.TemplateFullTextWrapper;
/**
* base class for output relative to file output, i.g. article/article page/tag page/category page
* @author zydecx
*
*/
public class AbstractFileOutput implements Output {
private static final Logger logger = CommonLog.getLogger();
@Override
public String export(Object object) throws GeneralException {
// TODO Auto-generated method stub
return DONE;
}
/**
* @param file
* @param template
* @param arg
* @throws GeneralException
*/
public void writeToFile(File file, TemplateFullTextWrapper template, FileOutputArg arg) throws GeneralException {
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
throw new GeneralException("fail to create file[" + file.getAbsolutePath() + "]", e);
}
}
try (
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
) {
String formattedHead = "";
if (arg.getPageTitle() != null) {
formattedHead += "<title>" + arg.getPageTitle() + "</title>";
}
if (arg.getHead() != null) {
formattedHead += "\n" + arg.getHead();
}
String templateFullText = template.getFullText()
.replace(GeneralDecoder.formatPlaceholderRegex("head"), formattedHead);
if (arg.getBodyTitle() != null) {
templateFullText = templateFullText
.replace(GeneralDecoder.formatPlaceholderRegex("body_title"), arg.getBodyTitle());
}
if (arg.getBody() != null) {
templateFullText = templateFullText
.replace(GeneralDecoder.formatPlaceholderRegex("body"), arg.getBody());
}
if (arg.getPagination() != null) {
templateFullText = templateFullText
.replace(GeneralDecoder.formatPlaceholderRegex("pagination"), arg.getPagination());
}
pw.write(templateFullText);
} catch (FileNotFoundException | UnsupportedEncodingException e) {
throw new GeneralException("fail to write to file[" + file.getAbsolutePath() + "]", e);
}
}
/**
* used for tag page/category page output
* @param templateFullTextWrapper
* @param arg
* @throws GeneralException
*/
public void exportTagPage(TemplateFullTextWrapper templateFullTextWrapper, TagFileOutputArg arg) throws GeneralException {
List<TagWrapper> itemList = arg.getTagList();
int itemSize = itemList.size();
int pagination = arg.getPagination();
int pageSize = (int) Math.ceil(itemSize * 1.0 / pagination);
Output tagOutput = arg.getTagOutput();
Output paginationOutput = arg.getPaginationOutput();
for (int i = 1; i <= pageSize; i++) {
List<TagWrapper> subList = itemList.subList((i - 1) * pagination, Math.min(itemSize, i * pagination));
StringBuilder sb = new StringBuilder();
for (TagWrapper item : subList) {
String itemName = item.getName();
TagOutputArg tagArg = new TagOutputArg(itemName, arg.getRootUrl() + "/" + item.getName(), item.getArticleList().size());
sb.append(tagOutput.export(tagArg));
}
File file = new File(formatPageFilePath(arg.getRootFile().getAbsolutePath(), i));
FileOutputArg fileOutputArg = new FileOutputArg();
fileOutputArg.setBodyTitle(arg.getBodyTitle());
fileOutputArg.setBody(sb.toString());
fileOutputArg.setPageTitle(arg.getBodyTitle());
fileOutputArg.setPagination(paginationOutput.export(new PaginationOutputArg(arg.getRootUrl(), pageSize, i)));
writeToFile(file, templateFullTextWrapper, fileOutputArg);
}
}
protected String formatPageUrl(String rootUrl, int index) {
return PaginationOutput.formatPaginationUrl(rootUrl, index);
}
protected String formatPageFilePath(String rootPath, int index) {
return PaginationOutput.formatPaginationFilePath(rootPath, index);
}
}
| zydecx/htmldecoder | src/main/java/com/debugtoday/htmldecoder/output/AbstractFileOutput.java | Java | gpl-2.0 | 4,685 |
package com.networkprofiles.widget;
/** Service to refresh the widget **/
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.RemoteViews;
import com.networkprofiles.R;
import com.networkprofiles.utils.MyNetControll;
public class NPWidgetService extends Service {
private Boolean mobile;
private Boolean cell;
private Boolean gps;
private Boolean display;
private Boolean sound;
private int [] widgetIds;
private RemoteViews rv;
private AppWidgetManager wm;
private MyNetControll myController;
public void onCreate() {
wm = AppWidgetManager.getInstance(NPWidgetService.this);//this.getApplicationContext()
myController = new MyNetControll(NPWidgetService.this);
myController.myStart();
//rv = new RemoteViews(getPackageName(), R.layout.npwidgetwifi);
}
public int onStartCommand(Intent intent, int flags, int startId) {
// /** Check the state of the network devices and set the text for the text fields **/
// //set the TextView for 3G data
// if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED || telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTING) {
// rv.setTextViewText(R.id.textMobile, "3G data is ON");
// }
// if(telephonyManager.getDataState() == TelephonyManager.DATA_DISCONNECTED) {
// rv.setTextViewText(R.id.textMobile, "3G data is OFF");
// }
// //set the TextView for WiFi
// if(wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
// rv.setTextViewText(R.id.textWifi, "Wifi is ON");
// }
// if(wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLED || wifim.getWifiState() == WifiManager.WIFI_STATE_DISABLING) {
// rv.setTextViewText(R.id.textWifi, "Wifi is OFF");
// }
// //set the TextView for Bluetooth
// if(myBluetooth.getState() == BluetoothAdapter.STATE_ON || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_ON) {
// rv.setTextViewText(R.id.textBluetooth, "Bluetooth is ON");
// }
// if(myBluetooth.getState() == BluetoothAdapter.STATE_OFF || myBluetooth.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
// rv.setTextViewText(R.id.textBluetooth, "Bluetooth is Off");
// }
// //set the TextView for Cell voice
// if(Settings.System.getInt(NPWidgetService.this.getContentResolver(),
// Settings.System.AIRPLANE_MODE_ON, 0) == 0) {
// rv.setTextViewText(R.id.textCell, "Cell is ON");
// } else {
// rv.setTextViewText(R.id.textCell, "Cell is OFF");
// }
// //set the TextView for GPS
// locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
// if(locationProviders.contains("gps")) {
// rv.setTextViewText(R.id.textGps, "GPS is ON");
// } else {
// rv.setTextViewText(R.id.textGps, "GPS is OFF");
// }
/** Check which textView was clicked and switch the state of the corresponding device **/
widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mobile = intent.getBooleanExtra("mobile", false);
cell = intent.getBooleanExtra("cell", false);
gps = intent.getBooleanExtra("gps", false);
display = intent.getBooleanExtra("display", false);
sound = intent.getBooleanExtra("sound", false);
if(widgetIds.length > 0) {
if(mobile) {
rv = new RemoteViews(getPackageName(), R.layout.npwidgetmobiledata);
rv.setTextColor(R.id.textWidgetMobileData, Color.GREEN);
updateWidgets();
rv.setTextColor(R.id.textWidgetMobileData, Color.WHITE);
myController.mobileOnOff();
}
if(cell) {
rv = new RemoteViews(getPackageName(), R.layout.npwidgetcell);
rv.setTextColor(R.id.textWidgetCell, Color.GREEN);
if(Settings.System.getInt(NPWidgetService.this.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 0) {
myController.cellOff();
} else {
myController.cellOn();
}
if(Settings.System.getInt(NPWidgetService.this.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 0) {
rv.setTextViewText(R.id.textWidgetCell, "Cell ON");
} else {
rv.setTextViewText(R.id.textWidgetCell, "Cell OFF");
}
updateWidgets();
rv.setTextColor(R.id.textWidgetCell, Color.WHITE);
}
if(gps) {
rv = new RemoteViews(getPackageName(), R.layout.npwidgetgps);
rv.setTextColor(R.id.textWidgetGps, Color.GREEN);
updateWidgets();
rv.setTextColor(R.id.textWidgetGps, Color.WHITE);
myController.gpsOnOff();
}
if(display) {
rv = new RemoteViews(getPackageName(), R.layout.npwidgetdisplay);
rv.setTextColor(R.id.textWidgetDisplay, Color.GREEN);
updateWidgets();
rv.setTextColor(R.id.textWidgetDisplay, Color.WHITE);
myController.displayOnOff();
}
if(sound) {
rv = new RemoteViews(getPackageName(), R.layout.npwidgetsound);
rv.setTextColor(R.id.textViewWidgetSound, Color.GREEN);
updateWidgets();
rv.setTextColor(R.id.textViewWidgetSound, Color.WHITE);
myController.soundSettings();
}
}
updateWidgets();
stopSelf();
return 1;
}
public void onStart(Intent intent, int startId) {
}
public IBinder onBind(Intent arg0) {
return null;
}
private void updateWidgets() {
for(int id : widgetIds) {
wm.updateAppWidget(id, rv);
}
}
}//close class NPWidgetService | ektodorov/ShortcutsOfPower_Android | src/com/networkprofiles/widget/NPWidgetService.java | Java | gpl-2.0 | 5,416 |
package net.minecartrapidtransit.path.launcher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileStoreUtils {
private String version;
public FileStoreUtils(String versionFile) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(new File(getDataFilePath(versionFile))));
version = br.readLine();
br.close();
}
public String getVersionedFile(String filename, String type){
return String.format("%s-%s.%s", filename, version, type);
}
public boolean fileNeedsUpdating(String filename, String type) {
return(new File(getVersionedFile(filename, type)).exists());
}
public String getVersionedDataFilePath(String filename, String type){
return getDataFilePath(getVersionedFile(filename, type));
}
public static String getDataFolderPath(){
String os = System.getProperty("os.name").toLowerCase();
boolean windows = os.contains("windows");
boolean mac = os.contains("macosx");
if(windows){
return System.getenv("APPDATA") + "\\MRTPath2";
}else{
String home = System.getProperty("user.home");
if(mac){
return home + "/Library/Application Support/MRTPath2";
}else{ // Linux
return home + "/.mrtpath2";
}
}
}
public static String getDataFilePath(String file){
return getDataFolderPath() + File.separator + file.replace('/', File.separatorChar);
}
}
| MinecartRapidTransit/MRTPath2 | launcher/src/main/java/net/minecartrapidtransit/path/launcher/FileStoreUtils.java | Java | gpl-2.0 | 1,412 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.dialect.unique;
import org.hibernate.boot.Metadata;
import org.hibernate.dialect.Dialect;
import org.hibernate.mapping.UniqueKey;
/**
* Informix requires the constraint name to come last on the alter table.
*
* @author Brett Meyer
*/
public class InformixUniqueDelegate extends DefaultUniqueDelegate {
public InformixUniqueDelegate( Dialect dialect ) {
super( dialect );
}
// legacy model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata) {
// Do this here, rather than allowing UniqueKey/Constraint to do it.
// We need full, simplified control over whether or not it happens.
final String tableName = metadata.getDatabase().getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
uniqueKey.getTable().getQualifiedTableName(),
metadata.getDatabase().getJdbcEnvironment().getDialect()
);
final String constraintName = dialect.quote( uniqueKey.getName() );
return dialect.getAlterTableString( tableName )
+ " add constraint " + uniqueConstraintSql( uniqueKey ) + " constraint " + constraintName;
}
}
| lamsfoundation/lams | 3rdParty_sources/hibernate-core/org/hibernate/dialect/unique/InformixUniqueDelegate.java | Java | gpl-2.0 | 1,458 |
package kieranvs.avatar.bending.earth;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import kieranvs.avatar.Protection;
import kieranvs.avatar.bending.Ability;
import kieranvs.avatar.bending.AsynchronousAbility;
import kieranvs.avatar.bukkit.BlockBukkit;
import kieranvs.avatar.bukkit.Location;
import kieranvs.avatar.bukkit.Vector;
import kieranvs.avatar.util.AvatarDamageSource;
import kieranvs.avatar.util.BendingUtils;
public class EarthStream extends AsynchronousAbility {
private long interval = 200L;
private long risetime = 600L;
private ConcurrentHashMap<BlockBukkit, Long> movedBlocks = new ConcurrentHashMap<BlockBukkit, Long>();
private Location origin;
private Location location;
private Vector direction;
private int range;
private long time;
private boolean finished = false;
public EarthStream(EntityLivingBase user, Location location, Vector direction, int range) {
super(user, 2000);
this.time = System.currentTimeMillis();
this.range = range;
this.origin = location.clone();
this.location = location.clone();
this.direction = direction.clone();
this.direction.setY(0);
this.direction.normalize();
this.location.add(this.direction);
}
@Override
public void update() {
for (BlockBukkit block : movedBlocks.keySet()) {
long time = movedBlocks.get(block).longValue();
if (System.currentTimeMillis() > time + risetime) {
Protection.trySetBlock(user.worldObj, Blocks.air, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(),
block.getRelative(BlockBukkit.UP).getZ());
movedBlocks.remove(block);
}
}
if (finished) {
if (movedBlocks.isEmpty()) {
destroy();
}
else {
return;
}
}
if (System.currentTimeMillis() - time >= interval) {
time = System.currentTimeMillis();
location.add(direction);
if (location.distance(origin) > range) {
finished = true;
return;
}
BlockBukkit block = this.location.getBlock();
if (isMoveable(block)) {
moveBlock(block);
}
if (isMoveable(block.getRelative(BlockBukkit.DOWN))) {
moveBlock(block.getRelative(BlockBukkit.DOWN));
location = block.getRelative(BlockBukkit.DOWN).getLocation();
return;
}
if (isMoveable(block.getRelative(BlockBukkit.UP))) {
moveBlock(block.getRelative(BlockBukkit.UP));
location = block.getRelative(BlockBukkit.UP).getLocation();
return;
}
else {
finished = true;
}
return;
}
}
public void moveBlock(BlockBukkit block) {
// block.getRelative(Block.UP).breakNaturally();
//block.getRelative(Block.UP).setType(block.getType());
//movedBlocks.put(block, System.currentTimeMillis());
//damageEntities(block.getLocation());
//BendingUtils.damageEntities(block.getLocation(), 3.5F, AvatarDamageSource.earthbending, 3);
Protection.trySetBlock(user.worldObj, Blocks.dirt, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(),
block.getRelative(BlockBukkit.UP).getZ());
movedBlocks.put(block, System.currentTimeMillis());
}
public void damageEntities(Location loc) {
for (Object o : loc.getWorld().getLoadedEntityList()) {
if (o instanceof EntityLivingBase) {
EntityLivingBase e = (EntityLivingBase) o;
if (loc.distance(e) < 3.5) {
e.attackEntityFrom(AvatarDamageSource.earthbending, 3);
}
}
}
}
public static boolean isMoveable(BlockBukkit block) {
Block[] overwriteable = { Blocks.air, Blocks.sapling, Blocks.tallgrass, Blocks.deadbush, Blocks.yellow_flower, Blocks.red_flower, Blocks.brown_mushroom, Blocks.red_mushroom, Blocks.fire, Blocks.snow, Blocks.torch, Blocks.leaves, Blocks.cactus, Blocks.reeds, Blocks.web, Blocks.waterlily, Blocks.vine };
if (!Arrays.asList(overwriteable).contains(block.getRelative(BlockBukkit.UP).getType())) {
return false;
}
Block[] moveable = { Blocks.brick_block, Blocks.clay, Blocks.coal_ore, Blocks.cobblestone, Blocks.dirt, Blocks.grass, Blocks.gravel, Blocks.mossy_cobblestone, Blocks.mycelium, Blocks.nether_brick, Blocks.netherrack, Blocks.obsidian, Blocks.sand, Blocks.sandstone, Blocks.farmland, Blocks.soul_sand, Blocks.stone };
if (Arrays.asList(moveable).contains(block.getType())) {
return true;
}
return false;
}
}
| kieranvs/Blockbender | Blockbender/src/kieranvs/avatar/bending/earth/EarthStream.java | Java | gpl-2.0 | 4,514 |
package org.erc.qmm.mq;
import java.util.EventListener;
/**
* The listener interface for receiving messageReaded events.
* The class that is interested in processing a messageReaded
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addMessageReadedListener<code> method. When
* the messageReaded event occurs, that object's appropriate
* method is invoked.
*
* @see MessageReadedEvent
*/
public interface MessageReadedListener extends EventListener {
/**
* Message readed.
*
* @param message the message
*/
void messageReaded(JMQMessage message);
}
| dubasdey/MQQueueMonitor | src/main/java/org/erc/qmm/mq/MessageReadedListener.java | Java | gpl-2.0 | 659 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ext.flac;
import android.os.Handler;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.audio.AudioProcessor;
import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.audio.SimpleDecoderAudioRenderer;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.ExoMediaCrypto;
import com.google.android.exoplayer2.util.MimeTypes;
/**
* Decodes and renders audio using the native Flac decoder.
*/
public class LibflacAudioRenderer extends SimpleDecoderAudioRenderer {
private static final int NUM_BUFFERS = 16;
public LibflacAudioRenderer() {
this(null, null);
}
/**
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param audioProcessors Optional {@link AudioProcessor}s that will process audio before output.
*/
public LibflacAudioRenderer(
Handler eventHandler,
AudioRendererEventListener eventListener,
AudioProcessor... audioProcessors) {
super(eventHandler, eventListener, audioProcessors);
}
@Override
protected int supportsFormatInternal(DrmSessionManager<ExoMediaCrypto> drmSessionManager,
Format format) {
if (!MimeTypes.AUDIO_FLAC.equalsIgnoreCase(format.sampleMimeType)) {
return FORMAT_UNSUPPORTED_TYPE;
} else if (!supportsOutput(format.channelCount, C.ENCODING_PCM_16BIT)) {
return FORMAT_UNSUPPORTED_SUBTYPE;
} else if (!supportsFormatDrm(drmSessionManager, format.drmInitData)) {
return FORMAT_UNSUPPORTED_DRM;
} else {
return FORMAT_HANDLED;
}
}
@Override
protected FlacDecoder createDecoder(Format format, ExoMediaCrypto mediaCrypto)
throws FlacDecoderException {
return new FlacDecoder(
NUM_BUFFERS, NUM_BUFFERS, format.maxInputSize, format.initializationData);
}
}
| CzBiX/Telegram | TMessagesProj/src/main/java/com/google/android/exoplayer2/ext/flac/LibflacAudioRenderer.java | Java | gpl-2.0 | 2,743 |
package org.mivotocuenta.client.service;
import org.mivotocuenta.server.beans.Conteo;
import org.mivotocuenta.shared.UnknownException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("servicegestionconteo")
public interface ServiceGestionConteo extends RemoteService {
Boolean insertarVoto(Conteo bean) throws UnknownException;
}
| jofrantoba/mivotocuenta | src/org/mivotocuenta/client/service/ServiceGestionConteo.java | Java | gpl-3.0 | 431 |
/**
* Copyright (C) 2007-2012 Hypertable, Inc.
*
* This file is part of Hypertable.
*
* Hypertable 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 any later version.
*
* Hypertable is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.hypertable.examples.PerformanceTest;
import java.nio.ByteBuffer;
import org.hypertable.AsyncComm.Serialization;
public class Result {
public int encodedLength() {
return 48;
}
public void encode(ByteBuffer buf) {
buf.putLong(itemsSubmitted);
buf.putLong(itemsReturned);
buf.putLong(requestCount);
buf.putLong(valueBytesReturned);
buf.putLong(elapsedMillis);
buf.putLong(cumulativeLatency);
}
public void decode(ByteBuffer buf) {
itemsSubmitted = buf.getLong();
itemsReturned = buf.getLong();
requestCount = buf.getLong();
valueBytesReturned = buf.getLong();
elapsedMillis = buf.getLong();
cumulativeLatency = buf.getLong();
}
public String toString() {
return new String("(items-submitted=" + itemsSubmitted + ", items-returned=" + itemsReturned +
"requestCount=" + requestCount + "value-bytes-returned=" + valueBytesReturned +
", elapsed-millis=" + elapsedMillis + ", cumulativeLatency=" + cumulativeLatency + ")");
}
public long itemsSubmitted = 0;
public long itemsReturned = 0;
public long requestCount = 0;
public long valueBytesReturned = 0;
public long elapsedMillis = 0;
public long cumulativeLatency = 0;
}
| deniskin82/hypertable | examples/java/org/hypertable/examples/PerformanceTest/Result.java | Java | gpl-3.0 | 2,057 |
/*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2016 Wandora Team
*
* 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/>.
*
*
*
*
* JoinDirective.java
*
* Created on 25. lokakuuta 2007, 11:38
*
*/
package org.wandora.query;
import org.wandora.topicmap.*;
import java.util.*;
/**
* @deprecated
*
* @author olli
*/
public class JoinDirective implements Directive {
private Directive query;
private Locator joinContext;
private Directive joinQuery;
/** Creates a new instance of JoinDirective */
public JoinDirective(Directive query,Directive joinQuery) {
this(query,(Locator)null,joinQuery);
}
public JoinDirective(Directive query,Locator joinContext,Directive joinQuery) {
this.query=query;
this.joinContext=joinContext;
this.joinQuery=joinQuery;
}
public JoinDirective(Directive query,String joinContext,Directive joinQuery) {
this(query,new Locator(joinContext),joinQuery);
}
public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException {
return query(context,null,null);
}
public ArrayList<ResultRow> query(QueryContext context,FilterDirective filter,Object filterParam) throws TopicMapException {
Topic contextTopic=context.getContextTopic();
TopicMap tm=contextTopic.getTopicMap();
ArrayList<ResultRow> inner=query.query(context);
ArrayList<ResultRow> res=new ArrayList<ResultRow>();
ArrayList<ResultRow> cachedJoin=null;
boolean useCache=!joinQuery.isContextSensitive();
for(ResultRow row : inner){
Topic t=null;
if(joinContext!=null){
Locator c=row.getPlayer(joinContext);
if(c==null) continue;
t=tm.getTopic(c);
}
else t=context.getContextTopic();
if(t==null) continue;
ArrayList<ResultRow> joinRes;
if(!useCache || cachedJoin==null){
joinRes=joinQuery.query(context.makeNewWithTopic(t));
if(useCache) cachedJoin=joinRes;
}
else joinRes=cachedJoin;
for(ResultRow joinRow : joinRes){
ResultRow joined=ResultRow.joinRows(row,joinRow);
if(filter!=null && !filter.includeRow(joined, contextTopic, tm, filterParam)) continue;
res.add(joined);
}
}
return res;
}
public boolean isContextSensitive(){
return query.isContextSensitive();
// note joinQuery gets context from query so it's sensitivity is same
// as that of query
}
}
| wandora-team/wandora | src/org/wandora/query/JoinDirective.java | Java | gpl-3.0 | 3,327 |
package cat.foixench.test.parcelable;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | gothalo/Android-2017 | 014-Parcelable/app/src/test/java/cat/foixench/test/parcelable/ExampleUnitTest.java | Java | gpl-3.0 | 406 |
package com.acgmodcrew.kip.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
/**
* Created by Malec on 05/03/2015.
*/
public class TileEntityRepositry extends TileEntity implements IInventory
{
private ItemStack[] inventory = new ItemStack[4];
@Override
public int getSizeInventory()
{
return 4;
}
@Override
public ItemStack getStackInSlot(int slot)
{
return inventory[slot];
}
@Override
public ItemStack decrStackSize(int slot, int p_70298_2_)
{
if (this.inventory[slot] != null)
{
ItemStack itemstack;
if (this.inventory[slot].stackSize <= p_70298_2_)
{
itemstack = this.inventory[slot];
this.inventory[slot] = null;
this.markDirty();
return itemstack;
}
else
{
itemstack = this.inventory[slot].splitStack(p_70298_2_);
if (this.inventory[slot].stackSize == 0)
{
this.inventory[slot] = null;
}
this.markDirty();
return itemstack;
}
}
else
{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int p_70304_1_)
{
return null;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemStack)
{
inventory[slot] = itemStack;
}
@Override
public String getInventoryName()
{
return "Repository";
}
@Override
public boolean hasCustomInventoryName()
{
return false;
}
@Override
public int getInventoryStackLimit()
{
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (worldObj == null)
{
return true;
}
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
return false;
}
return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
@Override
public void openInventory()
{
}
@Override
public void closeInventory()
{
}
@Override
public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_)
{
return false;
}
}
| ACGModCrew/kip | src/main/java/com/acgmodcrew/kip/tileentity/TileEntityRepositry.java | Java | gpl-3.0 | 2,563 |
package com.simplecity.amp_library.playback;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.RemoteControlClient;
import android.os.Bundle;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;
import android.util.Log;
import com.annimon.stream.Stream;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.cantrowitz.rxbroadcast.RxBroadcast;
import com.simplecity.amp_library.R;
import com.simplecity.amp_library.ShuttleApplication;
import com.simplecity.amp_library.androidauto.CarHelper;
import com.simplecity.amp_library.androidauto.MediaIdHelper;
import com.simplecity.amp_library.data.Repository;
import com.simplecity.amp_library.model.Song;
import com.simplecity.amp_library.playback.constants.InternalIntents;
import com.simplecity.amp_library.ui.screens.queue.QueueItem;
import com.simplecity.amp_library.ui.screens.queue.QueueItemKt;
import com.simplecity.amp_library.utils.LogUtils;
import com.simplecity.amp_library.utils.MediaButtonIntentReceiver;
import com.simplecity.amp_library.utils.SettingsManager;
import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import java.util.List;
import kotlin.Unit;
class MediaSessionManager {
private static final String TAG = "MediaSessionManager";
private Context context;
private MediaSessionCompat mediaSession;
private QueueManager queueManager;
private PlaybackManager playbackManager;
private PlaybackSettingsManager playbackSettingsManager;
private SettingsManager settingsManager;
private CompositeDisposable disposables = new CompositeDisposable();
private MediaIdHelper mediaIdHelper;
private static String SHUFFLE_ACTION = "ACTION_SHUFFLE";
MediaSessionManager(
Context context,
QueueManager queueManager,
PlaybackManager playbackManager,
PlaybackSettingsManager playbackSettingsManager,
SettingsManager settingsManager,
Repository.SongsRepository songsRepository,
Repository.AlbumsRepository albumsRepository,
Repository.AlbumArtistsRepository albumArtistsRepository,
Repository.GenresRepository genresRepository,
Repository.PlaylistsRepository playlistsRepository
) {
this.context = context.getApplicationContext();
this.queueManager = queueManager;
this.playbackManager = playbackManager;
this.settingsManager = settingsManager;
this.playbackSettingsManager = playbackSettingsManager;
mediaIdHelper = new MediaIdHelper((ShuttleApplication) context.getApplicationContext(), songsRepository, albumsRepository, albumArtistsRepository, genresRepository, playlistsRepository);
ComponentName mediaButtonReceiverComponent = new ComponentName(context.getPackageName(), MediaButtonIntentReceiver.class.getName());
mediaSession = new MediaSessionCompat(context, "Shuttle", mediaButtonReceiverComponent, null);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPause() {
playbackManager.pause(true);
}
@Override
public void onPlay() {
playbackManager.play();
}
@Override
public void onSeekTo(long pos) {
playbackManager.seekTo(pos);
}
@Override
public void onSkipToNext() {
playbackManager.next(true);
}
@Override
public void onSkipToPrevious() {
playbackManager.previous(false);
}
@Override
public void onSkipToQueueItem(long id) {
List<QueueItem> queueItems = queueManager.getCurrentPlaylist();
QueueItem queueItem = Stream.of(queueItems)
.filter(aQueueItem -> (long) aQueueItem.hashCode() == id)
.findFirst()
.orElse(null);
if (queueItem != null) {
playbackManager.setQueuePosition(queueItems.indexOf(queueItem));
}
}
@Override
public void onStop() {
playbackManager.stop(true);
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.e("MediaButtonReceiver", "OnMediaButtonEvent called");
MediaButtonIntentReceiver.handleIntent(context, mediaButtonEvent, playbackSettingsManager);
return true;
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
mediaIdHelper.getSongListForMediaId(mediaId, (songs, position) -> {
playbackManager.load((List<Song>) songs, position, true, 0);
return Unit.INSTANCE;
});
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressLint("CheckResult")
@Override
public void onPlayFromSearch(String query, Bundle extras) {
if (TextUtils.isEmpty(query)) {
playbackManager.play();
} else {
mediaIdHelper.handlePlayFromSearch(query, extras)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> {
if (!pair.getFirst().isEmpty()) {
playbackManager.load(pair.getFirst(), pair.getSecond(), true, 0);
} else {
playbackManager.pause(false);
}
},
error -> LogUtils.logException(TAG, "Failed to gather songs from search. Query: " + query, error)
);
}
}
@Override
public void onCustomAction(String action, Bundle extras) {
if (action.equals(SHUFFLE_ACTION)) {
queueManager.setShuffleMode(queueManager.shuffleMode == QueueManager.ShuffleMode.ON ? QueueManager.ShuffleMode.OFF : QueueManager.ShuffleMode.ON);
}
updateMediaSession(action);
}
});
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
//For some reason, MediaSessionCompat doesn't seem to pass all of the available 'actions' on as
//transport control flags for the RCC, so we do that manually
RemoteControlClient remoteControlClient = (RemoteControlClient) mediaSession.getRemoteControlClient();
if (remoteControlClient != null) {
remoteControlClient.setTransportControlFlags(
RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
| RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
| RemoteControlClient.FLAG_KEY_MEDIA_STOP);
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(InternalIntents.QUEUE_CHANGED);
intentFilter.addAction(InternalIntents.META_CHANGED);
intentFilter.addAction(InternalIntents.PLAY_STATE_CHANGED);
intentFilter.addAction(InternalIntents.POSITION_CHANGED);
disposables.add(RxBroadcast.fromBroadcast(context, intentFilter).subscribe(intent -> {
String action = intent.getAction();
if (action != null) {
updateMediaSession(intent.getAction());
}
}));
}
private void updateMediaSession(final String action) {
int playState = playbackManager.isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
long playbackActions = getMediaSessionActions();
QueueItem currentQueueItem = queueManager.getCurrentQueueItem();
PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder();
builder.setActions(playbackActions);
switch (queueManager.shuffleMode) {
case QueueManager.ShuffleMode.OFF:
builder.addCustomAction(
new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_on), R.drawable.ic_shuffle_off_circled).build());
break;
case QueueManager.ShuffleMode.ON:
builder.addCustomAction(
new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_off), R.drawable.ic_shuffle_on_circled).build());
break;
}
builder.setState(playState, playbackManager.getSeekPosition(), 1.0f);
if (currentQueueItem != null) {
builder.setActiveQueueItemId((long) currentQueueItem.hashCode());
}
PlaybackStateCompat playbackState = builder.build();
if (action.equals(InternalIntents.PLAY_STATE_CHANGED) || action.equals(InternalIntents.POSITION_CHANGED) || action.equals(SHUFFLE_ACTION)) {
mediaSession.setPlaybackState(playbackState);
} else if (action.equals(InternalIntents.META_CHANGED) || action.equals(InternalIntents.QUEUE_CHANGED)) {
if (currentQueueItem != null) {
MediaMetadataCompat.Builder metaData = new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, String.valueOf(currentQueueItem.getSong().id))
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentQueueItem.getSong().artistName)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, currentQueueItem.getSong().albumArtistName)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentQueueItem.getSong().albumName)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentQueueItem.getSong().name)
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, currentQueueItem.getSong().duration)
.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, (long) (queueManager.queuePosition + 1))
//Getting the genre is expensive.. let's not bother for now.
//.putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null)
.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, (long) (queueManager.getCurrentPlaylist().size()));
// If we're in car mode, don't wait for the artwork to load before setting session metadata.
if (CarHelper.isCarUiMode(context)) {
mediaSession.setMetadata(metaData.build());
}
mediaSession.setPlaybackState(playbackState);
mediaSession.setQueue(QueueItemKt.toMediaSessionQueueItems(queueManager.getCurrentPlaylist()));
mediaSession.setQueueTitle(context.getString(R.string.menu_queue));
if (settingsManager.showLockscreenArtwork() || CarHelper.isCarUiMode(context)) {
updateMediaSessionArtwork(metaData);
} else {
mediaSession.setMetadata(metaData.build());
}
}
}
}
private void updateMediaSessionArtwork(MediaMetadataCompat.Builder metaData) {
QueueItem currentQueueItem = queueManager.getCurrentQueueItem();
if (currentQueueItem != null) {
disposables.add(Completable.defer(() -> Completable.fromAction(() ->
Glide.with(context)
.load(currentQueueItem.getSong().getAlbum())
.asBitmap()
.override(1024, 1024)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
if (bitmap != null) {
metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap);
}
try {
mediaSession.setMetadata(metaData.build());
} catch (NullPointerException e) {
metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null);
mediaSession.setMetadata(metaData.build());
}
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
mediaSession.setMetadata(metaData.build());
}
})
))
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe()
);
}
}
private long getMediaSessionActions() {
return PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
| PlaybackStateCompat.ACTION_STOP
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
| PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM;
}
MediaSessionCompat.Token getSessionToken() {
return mediaSession.getSessionToken();
}
void setActive(boolean active) {
mediaSession.setActive(active);
}
void destroy() {
disposables.clear();
mediaSession.release();
}
} | timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/playback/MediaSessionManager.java | Java | gpl-3.0 | 15,327 |
/**
* Copyright 2017 Kaloyan Raev
*
* This file is part of chitanka4kindle.
*
* chitanka4kindle 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.
*
* chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>.
*/
package name.raev.kaloyan.kindle.chitanka.model.search.label;
public class Label {
private String slug;
private String name;
private int nrOfTexts;
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfTexts() {
return nrOfTexts;
}
public void setNumberOfTexts(int nrOfTexts) {
this.nrOfTexts = nrOfTexts;
}
}
| kaloyan-raev/chitanka4kindle | src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/label/Label.java | Java | gpl-3.0 | 1,251 |
/*
* Copyright (C) 2019 phramusca ( https://github.com/phramusca/ )
*
* 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 jamuz.process.book;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author phramusca ( https://github.com/phramusca/ )
*/
public class TableModelBookTest {
/**
*
*/
public TableModelBookTest() {
}
/**
*
*/
@BeforeClass
public static void setUpClass() {
}
/**
*
*/
@AfterClass
public static void tearDownClass() {
}
/**
*
*/
@Before
public void setUp() {
}
/**
*
*/
@After
public void tearDown() {
}
/**
* Test of isCellEditable method, of class TableModelBook.
*/
@Test
public void testIsCellEditable() {
System.out.println("isCellEditable");
int row = 0;
int col = 0;
TableModelBook instance = new TableModelBook();
boolean expResult = false;
boolean result = instance.isCellEditable(row, col);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of isCellEnabled method, of class TableModelBook.
*/
@Test
public void testIsCellEnabled() {
System.out.println("isCellEnabled");
int row = 0;
int col = 0;
TableModelBook instance = new TableModelBook();
boolean expResult = false;
boolean result = instance.isCellEnabled(row, col);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getBooks method, of class TableModelBook.
*/
@Test
public void testGetBooks() {
System.out.println("getBooks");
TableModelBook instance = new TableModelBook();
List<Book> expResult = null;
List<Book> result = instance.getBooks();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getFile method, of class TableModelBook.
*/
@Test
public void testGetFile() {
System.out.println("getFile");
int index = 0;
TableModelBook instance = new TableModelBook();
Book expResult = null;
Book result = instance.getFile(index);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getLengthAll method, of class TableModelBook.
*/
@Test
public void testGetLengthAll() {
System.out.println("getLengthAll");
TableModelBook instance = new TableModelBook();
long expResult = 0L;
long result = instance.getLengthAll();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getNbSelected method, of class TableModelBook.
*/
@Test
public void testGetNbSelected() {
System.out.println("getNbSelected");
TableModelBook instance = new TableModelBook();
int expResult = 0;
int result = instance.getNbSelected();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getRowCount method, of class TableModelBook.
*/
@Test
public void testGetRowCount() {
System.out.println("getRowCount");
TableModelBook instance = new TableModelBook();
int expResult = 0;
int result = instance.getRowCount();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getValueAt method, of class TableModelBook.
*/
@Test
public void testGetValueAt() {
System.out.println("getValueAt");
int rowIndex = 0;
int columnIndex = 0;
TableModelBook instance = new TableModelBook();
Object expResult = null;
Object result = instance.getValueAt(rowIndex, columnIndex);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setValueAt method, of class TableModelBook.
*/
@Test
public void testSetValueAt() {
System.out.println("setValueAt");
Object value = null;
int row = 0;
int col = 0;
TableModelBook instance = new TableModelBook();
instance.setValueAt(value, row, col);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of select method, of class TableModelBook.
*/
@Test
public void testSelect() {
System.out.println("select");
Book book = null;
boolean selected = false;
TableModelBook instance = new TableModelBook();
instance.select(book, selected);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getLengthSelected method, of class TableModelBook.
*/
@Test
public void testGetLengthSelected() {
System.out.println("getLengthSelected");
TableModelBook instance = new TableModelBook();
long expResult = 0L;
long result = instance.getLengthSelected();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getColumnClass method, of class TableModelBook.
*/
@Test
public void testGetColumnClass() {
System.out.println("getColumnClass");
int col = 0;
TableModelBook instance = new TableModelBook();
Class expResult = null;
Class result = instance.getColumnClass(col);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of clear method, of class TableModelBook.
*/
@Test
public void testClear() {
System.out.println("clear");
TableModelBook instance = new TableModelBook();
instance.clear();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of addRow method, of class TableModelBook.
*/
@Test
public void testAddRow() {
System.out.println("addRow");
Book file = null;
TableModelBook instance = new TableModelBook();
instance.addRow(file);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of removeRow method, of class TableModelBook.
*/
@Test
public void testRemoveRow() {
System.out.println("removeRow");
Book file = null;
TableModelBook instance = new TableModelBook();
instance.removeRow(file);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of loadThumbnails method, of class TableModelBook.
*/
@Test
public void testLoadThumbnails() {
System.out.println("loadThumbnails");
TableModelBook instance = new TableModelBook();
instance.loadThumbnails();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
| phramusca/JaMuz | test/jamuz/process/book/TableModelBookTest.java | Java | gpl-3.0 | 7,906 |
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.echopet.compat.nms.v1_14_R1.entity.type;
import com.dsh105.echopet.compat.api.entity.EntityPetType;
import com.dsh105.echopet.compat.api.entity.EntitySize;
import com.dsh105.echopet.compat.api.entity.IPet;
import com.dsh105.echopet.compat.api.entity.PetType;
import com.dsh105.echopet.compat.api.entity.SizeCategory;
import com.dsh105.echopet.compat.api.entity.type.nms.IEntityGiantPet;
import net.minecraft.server.v1_14_R1.EntityTypes;
import net.minecraft.server.v1_14_R1.World;
@EntitySize(width = 5.5F, height = 5.5F)
@EntityPetType(petType = PetType.GIANT)
public class EntityGiantPet extends EntityZombiePet implements IEntityGiantPet{
public EntityGiantPet(World world){
super(EntityTypes.GIANT, world);
}
public EntityGiantPet(World world, IPet pet){
super(EntityTypes.GIANT, world, pet);
}
@Override
public SizeCategory getSizeCategory(){
return SizeCategory.OVERSIZE;
}
}
| Borlea/EchoPet | modules/v1_14_R1/src/com/dsh105/echopet/compat/nms/v1_14_R1/entity/type/EntityGiantPet.java | Java | gpl-3.0 | 1,596 |
/*
* Copyright (C) 2006-2008 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.jlan.server.filesys;
import org.alfresco.jlan.server.SrvSession;
/**
* Transactional Filesystem Interface
*
* <p>Optional interface that a filesystem driver can implement to add support for transactions around filesystem calls.
*
* @author gkspencer
*/
public interface TransactionalFilesystemInterface {
/**
* Begin a read-only transaction
*
* @param sess SrvSession
*/
public void beginReadTransaction(SrvSession sess);
/**
* Begin a writeable transaction
*
* @param sess SrvSession
*/
public void beginWriteTransaction(SrvSession sess);
/**
* End an active transaction
*
* @param sess SrvSession
* @param tx Object
*/
public void endTransaction(SrvSession sess, Object tx);
}
| arcusys/Liferay-CIFS | source/java/org/alfresco/jlan/server/filesys/TransactionalFilesystemInterface.java | Java | gpl-3.0 | 1,957 |
/*
* This file is part of InTEL, the Interactive Toolkit for Engineering Learning.
* http://intel.gatech.edu
*
* InTEL 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.
*
* InTEL 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 InTEL. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package keyboard;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.system.DisplaySystem;
import edu.gatech.statics.application.StaticsApplication;
import edu.gatech.statics.exercise.Diagram;
import edu.gatech.statics.exercise.DiagramType;
import edu.gatech.statics.exercise.Schematic;
import edu.gatech.statics.math.Unit;
import edu.gatech.statics.math.Vector3bd;
import edu.gatech.statics.modes.description.Description;
import edu.gatech.statics.modes.equation.EquationDiagram;
import edu.gatech.statics.modes.equation.EquationMode;
import edu.gatech.statics.modes.equation.EquationState;
import edu.gatech.statics.modes.equation.worksheet.TermEquationMathState;
import edu.gatech.statics.modes.frame.FrameExercise;
import edu.gatech.statics.objects.Body;
import edu.gatech.statics.objects.DistanceMeasurement;
import edu.gatech.statics.objects.Force;
import edu.gatech.statics.objects.Point;
import edu.gatech.statics.objects.bodies.Bar;
import edu.gatech.statics.objects.bodies.Beam;
import edu.gatech.statics.objects.connectors.Connector2ForceMember2d;
import edu.gatech.statics.objects.connectors.Pin2d;
import edu.gatech.statics.objects.connectors.Roller2d;
import edu.gatech.statics.objects.representations.ModelNode;
import edu.gatech.statics.objects.representations.ModelRepresentation;
import edu.gatech.statics.tasks.Solve2FMTask;
import edu.gatech.statics.ui.AbstractInterfaceConfiguration;
import edu.gatech.statics.ui.windows.navigation.Navigation3DWindow;
import edu.gatech.statics.ui.windows.navigation.ViewConstraints;
import java.math.BigDecimal;
import java.util.Map;
/**
*
* @author Calvin Ashmore
*/
public class KeyboardExercise extends FrameExercise {
@Override
public AbstractInterfaceConfiguration createInterfaceConfiguration() {
AbstractInterfaceConfiguration ic = super.createInterfaceConfiguration();
ic.setNavigationWindow(new Navigation3DWindow());
ic.setCameraSpeed(.2f, 0.02f, .05f);
ViewConstraints vc = new ViewConstraints();
vc.setPositionConstraints(-2, 2, -1, 4);
vc.setZoomConstraints(0.5f, 1.5f);
vc.setRotationConstraints(-5, 5, 0, 5);
ic.setViewConstraints(vc);
return ic;
}
@Override
public Description getDescription() {
Description description = new Description();
description.setTitle("Keyboard Stand");
description.setNarrative(
"Kasiem Hill is in a music group comprised of Civil Engineering " +
"students from Georgia Tech, in which he plays the keyboard. " +
"For his birthday, he received a new keyboard, but it is much bigger " +
"(both in size and weight) than his last one, so he needs to buy a " +
"new keyboard stand. He finds one he really likes from a local " +
"dealer and is unsure if the connections will be able to support " +
"the weight of the new keyboard. He measures the dimensions of " +
"the stand and he wants to calculate how much force he can expect " +
"at each connection in the cross bar before he makes the investment.");
description.setProblemStatement(
"The stand can be modeled as a frame and is supported by two beams and a cross bar PQ. " +
"The supports at B and E are rollers and the floor is frictionless.");
description.setGoals(
"Find the force in PQ and define whether it is in tension or compression.");
description.addImage("keyboard/assets/keyboard 1.png");
description.addImage("keyboard/assets/keyboard 2.jpg");
description.addImage("keyboard/assets/keyboard 3.jpg");
return description;
}
@Override
public void initExercise() {
// setName("Keyboard Stand");
//
// setDescription(
// "This is a keyboard stand supported by two beams and a cross bar, PQ. " +
// "Find the force in PQ and define whether it is in tension or compression. " +
// "The supports at B and E are rollers, and the floor is frictionless.");
Unit.setSuffix(Unit.distance, " m");
Unit.setSuffix(Unit.moment, " N*m");
Unit.setDisplayScale(Unit.distance, new BigDecimal("10"));
getDisplayConstants().setMomentSize(0.5f);
getDisplayConstants().setForceSize(0.5f);
getDisplayConstants().setPointSize(0.5f);
getDisplayConstants().setCylinderRadius(0.5f);
//getDisplayConstants().setForceLabelDistance(1f);
//getDisplayConstants().setMomentLabelDistance(0f);
//getDisplayConstants().setMeasurementBarSize(0.1f);
// 10/21/2010 HOTFIX: THIS CORRECTS AN ISSUE IN WHICH OBSERVATION DIRECTION IS SET TO NULL IN EQUATIONS
for (Map<DiagramType, Diagram> diagramMap : getState().allDiagrams().values()) {
EquationDiagram eqDiagram = (EquationDiagram) diagramMap.get(EquationMode.instance.getDiagramType());
if(eqDiagram == null) continue;
EquationState.Builder builder = new EquationState.Builder(eqDiagram.getCurrentState());
TermEquationMathState.Builder xBuilder = new TermEquationMathState.Builder((TermEquationMathState) builder.getEquationStates().get("F[x]"));
xBuilder.setObservationDirection(Vector3bd.UNIT_X);
TermEquationMathState.Builder yBuilder = new TermEquationMathState.Builder((TermEquationMathState) builder.getEquationStates().get("F[y]"));
yBuilder.setObservationDirection(Vector3bd.UNIT_Y);
TermEquationMathState.Builder zBuilder = new TermEquationMathState.Builder((TermEquationMathState) builder.getEquationStates().get("M[p]"));
zBuilder.setObservationDirection(Vector3bd.UNIT_Z);
builder.putEquationState(xBuilder.build());
builder.putEquationState(yBuilder.build());
builder.putEquationState(zBuilder.build());
eqDiagram.pushState(builder.build());
eqDiagram.clearStateStack();
}
}
Point A, B, C, D, E, P, Q;
Pin2d jointC;
Connector2ForceMember2d jointP, jointQ;
Roller2d jointB, jointE;
Body leftLeg, rightLeg;
Bar bar;
@Override
public void loadExercise() {
Schematic schematic = getSchematic();
DisplaySystem.getDisplaySystem().getRenderer().setBackgroundColor(new ColorRGBA(.7f, .8f, .9f, 1.0f));
StaticsApplication.getApp().getCamera().setLocation(new Vector3f(0.0f, 0.0f, 65.0f));
A = new Point("A", "0", "6", "0");
D = new Point("D", "8", "6", "0");
B = new Point("B", "8", "0", "0");
E = new Point("E", "0", "0", "0");
C = new Point("C", "4", "3", "0");
P = new Point("P", "2.7", "4", "0");
Q = new Point("Q", "5.3", "4", "0");
leftLeg = new Beam("Left Leg", B, A);
bar = new Bar("Bar", P, Q);
rightLeg = new Beam("Right Leg", E, D);
jointC = new Pin2d(C);
jointP = new Connector2ForceMember2d(P, bar); //Pin2d(P);
jointQ = new Connector2ForceMember2d(Q, bar); //new Pin2d(Q);
jointB = new Roller2d(B);
jointE = new Roller2d(E);
jointB.setDirection(Vector3bd.UNIT_Y);
jointE.setDirection(Vector3bd.UNIT_Y);
DistanceMeasurement distance1 = new DistanceMeasurement(D, A);
distance1.setName("Measure AD");
distance1.createDefaultSchematicRepresentation(0.5f);
distance1.addPoint(E);
distance1.addPoint(B);
schematic.add(distance1);
DistanceMeasurement distance2 = new DistanceMeasurement(C, D);
distance2.setName("Measure CD");
distance2.createDefaultSchematicRepresentation(0.5f);
distance2.forceVertical();
distance2.addPoint(A);
schematic.add(distance2);
DistanceMeasurement distance3 = new DistanceMeasurement(C, Q);
distance3.setName("Measure CQ");
distance3.createDefaultSchematicRepresentation(1f);
distance3.forceVertical();
distance3.addPoint(P);
schematic.add(distance3);
DistanceMeasurement distance4 = new DistanceMeasurement(B, D);
distance4.setName("Measure BD");
distance4.createDefaultSchematicRepresentation(2.4f);
distance4.addPoint(A);
distance4.addPoint(E);
schematic.add(distance4);
Force keyboardLeft = new Force(A, Vector3bd.UNIT_Y.negate(), new BigDecimal(50));
keyboardLeft.setName("Keyboard Left");
leftLeg.addObject(keyboardLeft);
Force keyboardRight = new Force(D, Vector3bd.UNIT_Y.negate(), new BigDecimal(50));
keyboardRight.setName("Keyboard Right");
rightLeg.addObject(keyboardRight);
jointC.attach(leftLeg, rightLeg);
jointC.setName("Joint C");
jointP.attach(leftLeg, bar);
jointP.setName("Joint P");
jointQ.attach(bar, rightLeg);
jointQ.setName("Joint Q");
jointE.attachToWorld(rightLeg);
jointE.setName("Joint E");
jointB.attachToWorld(leftLeg);
jointB.setName("Joint B");
A.createDefaultSchematicRepresentation();
B.createDefaultSchematicRepresentation();
C.createDefaultSchematicRepresentation();
D.createDefaultSchematicRepresentation();
E.createDefaultSchematicRepresentation();
P.createDefaultSchematicRepresentation();
Q.createDefaultSchematicRepresentation();
keyboardLeft.createDefaultSchematicRepresentation();
keyboardRight.createDefaultSchematicRepresentation();
//leftLeg.createDefaultSchematicRepresentation();
//bar.createDefaultSchematicRepresentation();
//rightLeg.createDefaultSchematicRepresentation();
schematic.add(leftLeg);
schematic.add(bar);
schematic.add(rightLeg);
ModelNode modelNode = ModelNode.load("keyboard/assets/", "keyboard/assets/keyboard.dae");
float scale = .28f;
ModelRepresentation rep = modelNode.extractElement(leftLeg, "VisualSceneNode/stand/leg1");
rep.setLocalScale(scale);
rep.setModelOffset(new Vector3f(14f, 0, 0));
leftLeg.addRepresentation(rep);
rep.setSynchronizeRotation(false);
rep.setSynchronizeTranslation(false);
rep.setHoverLightColor(ColorRGBA.yellow);
rep.setSelectLightColor(ColorRGBA.yellow);
rep = modelNode.extractElement(rightLeg, "VisualSceneNode/stand/leg2");
rep.setLocalScale(scale);
rep.setModelOffset(new Vector3f(14f, 0, 0));
rightLeg.addRepresentation(rep);
rep.setSynchronizeRotation(false);
rep.setSynchronizeTranslation(false);
rep.setHoverLightColor(ColorRGBA.yellow);
rep.setSelectLightColor(ColorRGBA.yellow);
rep = modelNode.extractElement(bar, "VisualSceneNode/stand/middle_support");
rep.setLocalScale(scale);
rep.setModelOffset(new Vector3f(14f, 0, 0));
bar.addRepresentation(rep);
rep.setSynchronizeRotation(false);
rep.setSynchronizeTranslation(false);
rep.setHoverLightColor(ColorRGBA.yellow);
rep.setSelectLightColor(ColorRGBA.yellow);
rep = modelNode.getRemainder(schematic.getBackground());
schematic.getBackground().addRepresentation(rep);
rep.setLocalScale(scale);
rep.setModelOffset(new Vector3f(14f, 0, 0));
rep.setSynchronizeRotation(false);
rep.setSynchronizeTranslation(false);
addTask(new Solve2FMTask("Solve PQ", bar, jointP));
}
}
| jogjayr/InTEL-Project | exercises/Keyboard/src/keyboard/KeyboardExercise.java | Java | gpl-3.0 | 12,512 |
/*
* Transportr
*
* Copyright (c) 2013 - 2021 Torsten Grote
*
* 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 de.grobox.transportr.data.locations;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import de.grobox.transportr.data.DbTest;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.Point;
import de.schildbach.pte.dto.Product;
import static de.schildbach.pte.NetworkId.BVG;
import static de.schildbach.pte.NetworkId.DB;
import static de.schildbach.pte.dto.LocationType.ADDRESS;
import static de.schildbach.pte.dto.LocationType.ANY;
import static de.schildbach.pte.dto.LocationType.POI;
import static de.schildbach.pte.dto.LocationType.STATION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@RunWith(AndroidJUnit4.class)
public class FavoriteLocationTest extends DbTest {
private LocationDao dao;
@Before
@Override
public void createDb() throws Exception {
super.createDb();
dao = db.locationDao();
}
@Test
public void insertFavoriteLocation() throws Exception {
// no locations should exist
assertNotNull(getValue(dao.getFavoriteLocations(DB)));
// create a complete station location
Location loc1 = new Location(STATION, "stationId", Point.from1E6(23, 42), "place", "name", Product.ALL);
long uid1 = dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
// assert that location has been inserted and retrieved properly
List<FavoriteLocation> locations1 = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations1.size());
FavoriteLocation f1 = locations1.get(0);
assertEquals(uid1, f1.getUid());
assertEquals(DB, f1.getNetworkId());
assertEquals(loc1.type, f1.type);
assertEquals(loc1.id, f1.id);
assertEquals(loc1.getLatAs1E6(), f1.lat);
assertEquals(loc1.getLonAs1E6(), f1.lon);
assertEquals(loc1.place, f1.place);
assertEquals(loc1.name, f1.name);
assertEquals(loc1.products, f1.products);
// insert a second location in a different network
Location loc2 = new Location(ANY, null, Point.from1E6(1337, 0), null, null, Product.fromCodes("ISB".toCharArray()));
long uid2 = dao.addFavoriteLocation(new FavoriteLocation(BVG, loc2));
// assert that location has been inserted and retrieved properly
List<FavoriteLocation> locations2 = getValue(dao.getFavoriteLocations(BVG));
assertEquals(1, locations2.size());
FavoriteLocation f2 = locations2.get(0);
assertEquals(uid2, f2.getUid());
assertEquals(BVG, f2.getNetworkId());
assertEquals(loc2.type, f2.type);
assertEquals(loc2.id, f2.id);
assertEquals(loc2.getLatAs1E6(), f2.lat);
assertEquals(loc2.getLonAs1E6(), f2.lon);
assertEquals(loc2.place, f2.place);
assertEquals(loc2.name, f2.name);
assertEquals(loc2.products, f2.products);
}
@Test
public void replaceFavoriteLocation() throws Exception {
// create a complete station location
Location loc1 = new Location(STATION, "stationId", Point.from1E6(23, 42), "place", "name", Product.ALL);
long uid1 = dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
// retrieve favorite location
List<FavoriteLocation> locations1 = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations1.size());
FavoriteLocation f1 = locations1.get(0);
assertEquals(uid1, f1.getUid());
// change the favorite location and replace it in the DB
f1.place = "new place";
f1.name = "new name";
f1.products = null;
uid1 = dao.addFavoriteLocation(f1);
assertEquals(uid1, f1.getUid());
// retrieve favorite location again
List<FavoriteLocation> locations2 = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations2.size());
FavoriteLocation f2 = locations2.get(0);
// assert that same location was retrieved and data changed
assertEquals(f1.getUid(), f2.getUid());
assertEquals(f1.place, f2.place);
assertEquals(f1.name, f2.name);
assertEquals(f1.products, f2.products);
}
@Test
public void twoLocationsWithoutId() throws Exception {
Location loc1 = new Location(ADDRESS, null, Point.from1E6(23, 42), null, "name1", null);
Location loc2 = new Location(ADDRESS, null, Point.from1E6(0, 0), null, "name2", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
dao.addFavoriteLocation(new FavoriteLocation(DB, loc2));
assertEquals(2, getValue(dao.getFavoriteLocations(DB)).size());
}
@Test
public void twoLocationsWithSameId() throws Exception {
Location loc1 = new Location(ADDRESS, "test", Point.from1E6(23, 42), null, "name1", null);
Location loc2 = new Location(ADDRESS, "test", Point.from1E6(0, 0), null, "name2", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
dao.addFavoriteLocation(new FavoriteLocation(DB, loc2));
// second location should override first one and don't create a new one
List<FavoriteLocation> locations = getValue(dao.getFavoriteLocations(DB));
assertEquals(1, locations.size());
FavoriteLocation f = locations.get(0);
assertEquals(loc2.getLatAs1E6(), f.lat);
assertEquals(loc2.getLonAs1E6(), f.lon);
assertEquals(loc2.name, f.name);
}
@Test
public void twoLocationsWithSameIdDifferentNetworks() throws Exception {
Location loc1 = new Location(ADDRESS, "test", Point.from1E6(23, 42), null, "name1", null);
Location loc2 = new Location(ADDRESS, "test", Point.from1E6(0, 0), null, "name2", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
dao.addFavoriteLocation(new FavoriteLocation(BVG, loc2));
// second location should not override first one
assertEquals(1, getValue(dao.getFavoriteLocations(DB)).size());
assertEquals(1, getValue(dao.getFavoriteLocations(BVG)).size());
}
@Test
public void getFavoriteLocationByUid() throws Exception {
// insert a minimal location
Location l1 = new Location(STATION, "id", Point.from1E6(1, 1), "place", "name", null);
FavoriteLocation f1 = new FavoriteLocation(DB, l1);
long uid = dao.addFavoriteLocation(f1);
// retrieve by UID
FavoriteLocation f2 = dao.getFavoriteLocation(uid);
// assert that retrieval worked
assertNotNull(f2);
assertEquals(uid, f2.getUid());
assertEquals(DB, f2.getNetworkId());
assertEquals(l1.type, f2.type);
assertEquals(l1.id, f2.id);
assertEquals(l1.getLatAs1E6(), f2.lat);
assertEquals(l1.getLonAs1E6(), f2.lon);
assertEquals(l1.place, f2.place);
assertEquals(l1.name, f2.name);
assertEquals(l1.products, f2.products);
}
@Test
public void getFavoriteLocationByValues() {
// insert a minimal location
Location loc1 = new Location(ANY, null, Point.from1E6(0, 0), null, null, null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc1));
// assert the exists check works
assertNotNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, ADDRESS, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, "id", loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, 1, loc1.getLonAs1E6(), loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), 1, loc1.place, loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), "place", loc1.name));
assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, "name"));
// insert a maximal location
Location loc2 = new Location(STATION, "id", Point.from1E6(1, 1), "place", "name", null);
dao.addFavoriteLocation(new FavoriteLocation(DB, loc2));
// assert the exists check works
assertNotNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, POI, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, "oid", loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, 42, loc2.getLonAs1E6(), loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), 42, loc2.place, loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), "oplace", loc2.name));
assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, "oname"));
}
}
| grote/Transportr | app/src/androidTest/java/de/grobox/transportr/data/locations/FavoriteLocationTest.java | Java | gpl-3.0 | 9,335 |
/**
* Bukkit plugin which moves the mobs closer to the players.
* Copyright (C) 2016 Jakub "Co0sh" Sapalski
*
* 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 pl.betoncraft.hordes;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
/**
* Blocks the mobs from spawning in unwanted places.
*
* @author Jakub Sapalski
*/
public class Blocker implements Listener {
private Hordes plugin;
private Random rand = new Random();
/**
* Starts the blocker.
*
* @param plugin
* instance of the plugin
*/
public Blocker(Hordes plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onSpawn(CreatureSpawnEvent event) {
LivingEntity e = event.getEntity();
WorldSettings set = plugin.getWorlds().get(event.getEntity().getWorld().getName());
if (set == null) {
return;
}
if (!set.getEntities().contains(e.getType())) {
return;
}
if (!set.shouldExist(e)) {
event.setCancelled(true);
} else if (rand.nextDouble() > set.getRatio(e.getType())) {
event.setCancelled(true);
} else {
AttributeInstance maxHealth = e.getAttribute(Attribute.GENERIC_MAX_HEALTH);
maxHealth.setBaseValue(maxHealth.getBaseValue() * set.getHealth(e.getType()));
e.setHealth(e.getMaxHealth());
}
}
}
| Co0sh/Hordes | src/main/java/pl/betoncraft/hordes/Blocker.java | Java | gpl-3.0 | 2,168 |
package cn.com.jautoitx;
import org.apache.commons.lang3.StringUtils;
import com.sun.jna.platform.win32.WinDef.HWND;
/**
* Build window title base on Advanced Window Descriptions.
*
* @author zhengbo.wang
*/
public class TitleBuilder {
/**
* Build window title base on Advanced Window Descriptions.
*
* @param bys
* Selectors to build advanced window title.
* @return Returns advanced window title.
*/
public static String by(By... bys) {
StringBuilder title = new StringBuilder();
title.append('[');
String separator = "";
for (int i = 0; i < bys.length; i++) {
title.append(separator);
String strBy = bys[i].toAdvancedTitle();
if (!strBy.isEmpty()) {
title.append(strBy);
separator = "; ";
}
}
title.append(']');
return title.toString();
}
/**
* Build window title base on window title.
*
* @param title
* Window title.
* @return Returns advanced window title.
*/
public static String byTitle(String title) {
return by(By.title(title));
}
/**
* Build window title base on the internal window classname.
*
* @param className
* The internal window classname.
* @return Returns advanced window title.
*/
public static String byClassName(String className) {
return by(By.className(className));
}
/**
* Build window title base on window title using a regular expression.
*
* @param regexpTitle
* Window title using a regular expression.
* @return Returns advanced window title.
*/
public static String byRegexpTitle(String regexpTitle) {
return by(By.regexpTitle(regexpTitle));
}
/**
* Build window title base on window classname using a regular expression.
*
* @param regexpClassName
* Window classname using a regular expression.
* @return Returns advanced window title.
*/
public static String byRegexpClassName(String regexpClassName) {
return by(By.regexpClassName(regexpClassName));
}
/**
* Build window title base on window used in a previous AutoIt command.
*
* @return Returns advanced window title.
*/
public static String byLastWindow() {
return by(By.lastWindow());
}
/**
* Build window title base on currently active window.
*
* @return Returns advanced window title.
*/
public static String byActiveWindow() {
return by(By.activeWindow());
}
/**
* Build window title base on the position and size of a window. All
* parameters are optional.
*
* @param x
* Optional, the X coordinate of the window.
* @param y
* Optional, the Y coordinate of the window.
* @param width
* Optional, the width of the window.
* @param height
* Optional, the height of the window.
* @return Returns advanced window title.
*/
public static String byBounds(Integer x, Integer y, Integer width,
Integer height) {
return by(By.bounds(x, y, width, height));
}
/**
* Build window title base on the position of a window. All parameters are
* optional.
*
* @param x
* Optional, the X coordinate of the window.
* @param y
* Optional, the Y coordinate of the window.
* @return Returns advanced window title.
*/
public static String byPosition(Integer x, Integer y) {
return by(By.position(x, y));
}
/**
* Build window title base on the size of a window. All parameters are
* optional.
*
* @param width
* Optional, the width of the window.
* @param height
* Optional, the height of the window.
* @return Returns advanced window title.
*/
public static String bySize(Integer width, Integer height) {
return by(By.size(width, height));
}
/**
* Build window title base on the 1-based instance when all given properties
* match.
*
* @param instance
* The 1-based instance when all given properties match.
* @return Returns advanced window title.
*/
public static String byInstance(int instance) {
return by(By.instance(instance));
}
/**
* Build window title base on the handle address as returned by a method
* like Win.getHandle.
*
* @param handle
* The handle address as returned by a method like Win.getHandle.
* @return Returns advanced window title.
*/
public static String byHandle(String handle) {
return by(By.handle(handle));
}
/**
* Build window title base on the handle address as returned by a method
* like Win.getHandle_.
*
* @param hWnd
* The handle address as returned by a method like
* Win.getHandle_.
* @return Returns advanced window title.
*/
public static String byHandle(HWND hWnd) {
return by(By.handle(hWnd));
}
/**
* Selector to build advanced window title.
*
* @author zhengbo.wang
*/
public static abstract class By {
private final String property;
private final String value;
public By(final String property) {
this.property = property;
this.value = null;
}
public By(final String property, final String value) {
this.property = property;
this.value = StringUtils.defaultString(value);
}
/**
* @param title
* Window title.
* @return a By which locates window by the window title.
*/
public static By title(String title) {
return new ByTitle(title);
}
/**
* @param className
* The internal window classname.
* @return a By which locates window by the internal window classname.
*/
public static By className(String className) {
return new ByClass(className);
}
/**
* @param regexpTitle
* Window title using a regular expression.
* @return a By which locates window by the window title using a regular
* expression.
*/
public static By regexpTitle(String regexpTitle) {
return new ByRegexpTitle(regexpTitle);
}
/**
* @param regexpClassName
* Window classname using a regular expression.
* @return a By which locates window by the window classname using a
* regular expression.
*/
public static By regexpClassName(String regexpClassName) {
return new ByRegexpClass(regexpClassName);
}
/**
* @return a By which locates window used in a previous AutoIt command.
*/
public static By lastWindow() {
return new ByLast();
}
/**
* @return a By which locates currently active window.
*/
public static By activeWindow() {
return new ByActive();
}
/**
* All parameters are optional.
*
* @param x
* Optional, the X coordinate of the window.
* @param y
* Optional, the Y coordinate of the window.
* @param width
* Optional, the width of the window.
* @param height
* Optional, the height of the window.
* @return a By which locates window by the position and size of a
* window.
*/
public static By bounds(Integer x, Integer y, Integer width,
Integer height) {
return new ByBounds(x, y, width, height);
}
/**
* All parameters are optional.
*
* @param x
* Optional, the X coordinate of the window.
* @param y
* Optional, the Y coordinate of the window.
* @return a By which locates window by the position of a window.
*/
public static By position(Integer x, Integer y) {
return bounds(x, y, null, null);
}
/**
* All parameters are optional.
*
* @param width
* Optional, the width of the window.
* @param height
* Optional, the height of the window.
* @return a By which locates window by the size of a window.
*/
public static By size(Integer width, Integer height) {
return bounds(null, null, width, height);
}
/**
* @param instance
* The 1-based instance when all given properties match.
* @return a By which locates window by the instance when all given
* properties match.
*/
public static By instance(int instance) {
return new ByInstance(instance);
}
/**
* @param handle
* The handle address as returned by a method like
* Win.getHandle.
* @return a By which locates window by the handle address as returned
* by a method like Win.getHandle.
*/
public static By handle(String handle) {
return new ByHandle(handle);
}
/**
* @param hWnd
* The handle address as returned by a method like
* Win.getHandle_.
* @return a By which locates window by the handle address as returned
* by a method like Win.getHandle.
*/
public static By handle(HWND hWnd) {
return new ByHandle(hWnd);
}
public String toAdvancedTitle() {
StringBuilder advancedTitle = new StringBuilder();
advancedTitle.append(property);
if (value != null) {
advancedTitle.append(':');
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
advancedTitle.append(ch);
// Note: if a Value must contain a ";" it must be doubled.
if (ch == ';') {
advancedTitle.append(';');
}
}
}
return advancedTitle.toString();
}
@Override
public String toString() {
return "By." + property + ": " + value;
}
}
/**
* Window title.
*
* @author zhengbo.wang
*/
public static class ByTitle extends By {
public ByTitle(String title) {
super("TITLE", title);
}
}
/**
* The internal window classname.
*
* @author zhengbo.wang
*/
public static class ByClass extends By {
public ByClass(String clazz) {
super("CLASS", clazz);
}
}
/**
* Window title using a regular expression.
*
* @author zhengbo.wang
*/
public static class ByRegexpTitle extends By {
public ByRegexpTitle(String clazz) {
super("REGEXPTITLE", clazz);
}
}
/**
* Window classname using a regular expression.
*
* @author zhengbo.wang
*/
public static class ByRegexpClass extends By {
public ByRegexpClass(String regexpClass) {
super("REGEXPCLASS", regexpClass);
}
}
/**
* Last window used in a previous AutoIt command.
*
* @author zhengbo.wang
*/
public static class ByLast extends By {
public ByLast() {
super("LAST");
}
}
/**
* Currently active window.
*
* @author zhengbo.wang
*/
public static class ByActive extends By {
public ByActive() {
super("ACTIVE");
}
}
/**
* The position and size of a window.
*
* @author zhengbo.wang
*/
public static class ByBounds extends By {
private final Integer x;
private final Integer y;
private final Integer width;
private final Integer height;
public ByBounds(Integer x, Integer y, Integer width, Integer height) {
super("POSITION AND SIZE", String.format("%s \\ %s \\ %s \\ %s",
String.valueOf(x), String.valueOf(y),
String.valueOf(width), String.valueOf(height)));
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
@Override
public String toAdvancedTitle() {
// see http://www.autoitscript.com/forum/topic/90848-x-y-w-h/
StringBuilder advancedTitle = new StringBuilder();
if (x != null) {
advancedTitle.append("X:").append(x);
}
if (y != null) {
if (!advancedTitle.toString().isEmpty()) {
advancedTitle.append("\\");
}
advancedTitle.append("Y:").append(y);
}
if (width != null) {
if (!advancedTitle.toString().isEmpty()) {
advancedTitle.append("\\");
}
advancedTitle.append("W:").append(width);
}
if (height != null) {
if (!advancedTitle.toString().isEmpty()) {
advancedTitle.append("\\");
}
advancedTitle.append("H:").append(height);
}
return advancedTitle.toString();
}
}
/**
* The 1-based instance when all given properties match.
*
* @author zhengbo.wang
*/
public static class ByInstance extends By {
public ByInstance(int instance) {
super("INSTANCE", String.valueOf(instance));
}
}
/**
* The handle address as returned by a method like Win.getHandle or
* Win.getHandle_.
*
* @author zhengbo.wang
*/
public static class ByHandle extends By {
public ByHandle(String handle) {
super("HANDLE", handle);
}
public ByHandle(HWND hWnd) {
this(AutoItX.hwndToHandle(hWnd));
}
}
}
| Pheelbert/twitchplayclient | src/cn/com/jautoitx/TitleBuilder.java | Java | gpl-3.0 | 12,238 |
package me.vadik.instaclimb.view.adapter;
import android.content.Context;
import android.databinding.ViewDataBinding;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import me.vadik.instaclimb.databinding.RowLayoutRouteBinding;
import me.vadik.instaclimb.databinding.UserCardBinding;
import me.vadik.instaclimb.model.Route;
import me.vadik.instaclimb.model.User;
import me.vadik.instaclimb.view.adapter.abstr.AbstractRecyclerViewWithHeaderAdapter;
import me.vadik.instaclimb.viewmodel.RouteItemViewModel;
import me.vadik.instaclimb.viewmodel.UserViewModel;
/**
* User: vadik
* Date: 4/13/16
*/
public class UserRecyclerViewAdapter extends AbstractRecyclerViewWithHeaderAdapter<User, Route> {
public UserRecyclerViewAdapter(Context context, User user) {
super(context, user);
}
@Override
protected ViewDataBinding onCreateHeader(LayoutInflater inflater, ViewGroup parent) {
return UserCardBinding.inflate(inflater, parent, false);
}
@Override
protected ViewDataBinding onCreateItem(LayoutInflater inflater, ViewGroup parent) {
return RowLayoutRouteBinding.inflate(inflater, parent, false);
}
@Override
protected void onBindHeader(ViewDataBinding binding, User user) {
((UserCardBinding) binding).setUser(new UserViewModel(mContext, user));
}
@Override
protected void onBindItem(ViewDataBinding binding, Route route) {
((RowLayoutRouteBinding) binding).setRoute(new RouteItemViewModel(mContext, route));
}
} | sirekanyan/instaclimb | app/src/main/java/me/vadik/instaclimb/view/adapter/UserRecyclerViewAdapter.java | Java | gpl-3.0 | 1,531 |
package tencentcloud.constant;
/**
* @author fanwh
* @version v1.0
* @decription
* @create on 2017/11/10 16:09
*/
public class RegionConstants {
/**
* 北京
*/
public static final String PEKING = "ap-beijing";
/**
* 上海
*/
public static final String SHANGHAI = "ap-shanghai";
/**
* 香港
*/
public static final String HONGKONG = "ap-hongkong";
/**
* 多伦多
*/
public static final String TORONTO = "na-toronto";
/**
* 硅谷
*/
public static final String SILICON_VALLEY = "na-siliconvalley";
/**
* 新加坡
*/
public static final String SINGAPORE = "ap-singapore";
/**
* 上海金融
*/
public static final String SHANGHAI_FSI = "ap-shanghai-fsi";
/**
* 广州open专区
*/
public static final String GUANGZHOU_OPEN = "ap-guangzhou-open";
/**
* 深圳金融
*/
public static final String SHENZHEN_FSI = "ap-shenzhen-fsi";
}
| ghforlang/Working | Test/src/main/java/tencentcloud/constant/RegionConstants.java | Java | gpl-3.0 | 1,002 |
/* The following code was generated by JFlex 1.6.1 */
package com.jim_project.interprete.parser.previo;
import com.jim_project.interprete.parser.AnalizadorLexico;
/**
* This class is a scanner generated by
* <a href="http://www.jflex.de/">JFlex</a> 1.6.1
* from the specification file <tt>C:/Users/alber_000/Documents/NetBeansProjects/tfg-int-rpretes/jim/src/main/java/com/jim_project/interprete/parser/previo/lexico.l</tt>
*/
public class PrevioLex extends AnalizadorLexico {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int YYINITIAL = 0;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0
};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\11\0\1\3\1\2\1\51\1\3\1\1\22\0\1\3\1\16\1\0"+
"\1\5\1\0\1\20\2\0\3\20\1\15\1\20\1\14\1\0\1\20"+
"\1\10\11\7\2\0\1\13\1\17\3\0\3\6\1\50\1\42\1\24"+
"\1\30\1\40\1\23\2\4\1\41\1\4\1\47\1\31\1\44\3\4"+
"\1\32\2\4\1\37\1\11\1\12\1\11\1\20\1\0\1\20\3\0"+
"\3\6\1\46\1\36\1\22\1\25\1\34\1\21\2\4\1\35\1\4"+
"\1\45\1\26\1\43\3\4\1\27\2\4\1\33\1\11\1\12\1\11"+
"\12\0\1\51\u1fa2\0\1\51\1\51\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\udfe6\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\1\0\1\1\2\2\1\1\1\2\1\3\2\4\2\5"+
"\1\1\2\6\1\1\1\6\6\1\1\3\2\1\1\3"+
"\1\7\1\3\1\5\1\10\1\11\1\12\1\0\1\13"+
"\10\7\1\14\4\7\1\15\2\7\1\16\1\7\1\17"+
"\1\7\1\20";
private static int [] zzUnpackAction() {
int [] result = new int[55];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\52\0\124\0\52\0\176\0\250\0\322\0\374"+
"\0\52\0\u0126\0\176\0\u0150\0\u017a\0\u01a4\0\u01ce\0\52"+
"\0\u01f8\0\u0222\0\u024c\0\u0276\0\u02a0\0\u02ca\0\u02f4\0\u031e"+
"\0\u0348\0\u0372\0\176\0\u039c\0\u03c6\0\52\0\52\0\52"+
"\0\u03f0\0\176\0\u041a\0\u0444\0\u046e\0\u0498\0\u04c2\0\u04ec"+
"\0\u0516\0\u0540\0\52\0\u056a\0\u0594\0\u05be\0\u05e8\0\176"+
"\0\u0612\0\u063c\0\176\0\u0666\0\176\0\u0690\0\176";
private static int [] zzUnpackRowMap() {
int [] result = new int[55];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\2\1\3\2\4\1\5\1\6\1\7\1\10\1\11"+
"\1\12\1\13\1\14\1\15\1\16\1\17\1\2\1\20"+
"\1\21\1\5\1\22\1\5\1\23\2\5\1\24\2\5"+
"\1\25\1\5\1\26\1\27\1\30\1\5\1\31\1\32"+
"\3\5\1\7\1\5\1\7\55\0\1\4\53\0\1\33"+
"\1\0\1\33\2\0\2\33\6\0\30\33\1\0\1\6"+
"\1\3\1\4\47\6\4\0\1\33\1\0\1\33\1\34"+
"\1\0\2\33\6\0\30\33\10\0\2\10\45\0\1\33"+
"\1\0\1\33\1\35\1\0\2\33\6\0\30\33\15\0"+
"\1\36\51\0\1\37\52\0\1\40\53\0\1\41\36\0"+
"\1\33\1\0\1\33\2\0\2\33\6\0\1\33\1\42"+
"\26\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+
"\3\33\1\42\24\33\5\0\1\33\1\0\1\33\2\0"+
"\2\33\6\0\5\33\1\43\22\33\5\0\1\33\1\0"+
"\1\33\2\0\2\33\6\0\10\33\1\44\17\33\5\0"+
"\1\33\1\0\1\33\2\0\2\33\6\0\13\33\1\45"+
"\14\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+
"\5\33\1\46\22\33\5\0\1\33\1\0\1\33\1\34"+
"\1\0\2\33\6\0\24\33\1\47\3\33\5\0\1\33"+
"\1\0\1\33\2\0\2\33\6\0\17\33\1\50\10\33"+
"\5\0\1\33\1\0\1\33\2\0\2\33\6\0\10\33"+
"\1\51\17\33\5\0\1\33\1\0\1\33\1\34\1\0"+
"\2\33\6\0\26\33\1\52\1\33\10\0\2\34\50\0"+
"\2\35\44\0\1\41\4\0\1\53\45\0\1\33\1\0"+
"\1\33\2\0\2\33\6\0\6\33\1\54\21\33\5\0"+
"\1\33\1\0\1\33\2\0\2\33\6\0\11\33\1\55"+
"\16\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+
"\1\56\27\33\5\0\1\33\1\0\1\33\2\0\2\33"+
"\6\0\5\33\1\57\22\33\5\0\1\33\1\0\1\33"+
"\2\0\2\33\6\0\25\33\1\60\2\33\5\0\1\33"+
"\1\0\1\33\2\0\2\33\6\0\2\33\1\61\25\33"+
"\5\0\1\33\1\0\1\33\2\0\2\33\6\0\10\33"+
"\1\62\17\33\5\0\1\33\1\0\1\33\2\0\2\33"+
"\6\0\27\33\1\60\5\0\1\33\1\0\1\33\2\0"+
"\2\33\6\0\5\33\1\63\22\33\5\0\1\33\1\0"+
"\1\33\2\0\2\33\6\0\10\33\1\63\17\33\5\0"+
"\1\33\1\0\1\33\2\0\2\33\6\0\14\33\1\64"+
"\13\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+
"\22\33\1\65\5\33\5\0\1\33\1\0\1\33\2\0"+
"\2\33\6\0\20\33\1\66\7\33\5\0\1\33\1\0"+
"\1\33\2\0\2\33\6\0\23\33\1\65\4\33\5\0"+
"\1\33\1\0\1\33\2\0\2\33\6\0\15\33\1\67"+
"\12\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+
"\21\33\1\67\6\33\1\0";
private static int [] zzUnpackTrans() {
int [] result = new int[1722];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unknown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\1\0\1\11\1\1\1\11\4\1\1\11\6\1\1\11"+
"\15\1\3\11\1\0\11\1\1\11\14\1";
private static int [] zzUnpackAttribute() {
int [] result = new int[55];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** number of newlines encountered up to the start of the matched text */
private int yyline;
/** the number of characters up to the start of the matched text */
private int yychar;
/**
* the number of characters from the last newline up to the start of the
* matched text
*/
private int yycolumn;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
private boolean zzEOFDone;
/**
* The number of occupied positions in zzBuffer beyond zzEndRead.
* When a lead/high surrogate has been read from the input stream
* into the final zzBuffer position, this will have a value of 1;
* otherwise, it will have a value of 0.
*/
private int zzFinalHighSurrogate = 0;
/* user code: */
private PrevioParser yyparser;
/**
* Constructor de clase.
* @param r Referencia al lector de entrada.
* @param p Referencia al analizador sintáctico.
*/
public PrevioLex(java.io.Reader r, PrevioParser p) {
this(r);
yyparser = p;
}
/**
* Creates a new scanner
*
* @param in the java.io.Reader to read input from.
*/
public PrevioLex(java.io.Reader in) {
this.zzReader = in;
}
/**
* Unpacks the compressed character translation table.
*
* @param packed the packed character translation table
* @return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x110000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 184) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
*
* @exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) {
/* if not: blow it up */
char newBuffer[] = new char[zzBuffer.length*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
}
/* fill the buffer with new input */
int requested = zzBuffer.length - zzEndRead;
int numRead = zzReader.read(zzBuffer, zzEndRead, requested);
/* not supposed to occur according to specification of java.io.Reader */
if (numRead == 0) {
throw new java.io.IOException("Reader returned 0 characters. See JFlex examples for workaround.");
}
if (numRead > 0) {
zzEndRead += numRead;
/* If numRead == requested, we might have requested to few chars to
encode a full Unicode character. We assume that a Reader would
otherwise never return half characters. */
if (numRead == requested) {
if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) {
--zzEndRead;
zzFinalHighSurrogate = 1;
}
}
/* potentially more input available */
return false;
}
/* numRead < 0 ==> end of stream */
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
*
* Internal scan buffer is resized down to its initial length, if it has grown.
*
* @param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzFinalHighSurrogate = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Contains user EOF-code, which will be executed exactly once,
* when the end of file is reached
*/
private void zzDoEOF() throws java.io.IOException {
if (!zzEOFDone) {
zzEOFDone = true;
yyclose();
}
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/
public int yylex() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
// set up zzAction for empty match case:
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
}
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL) {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
zzDoEOF();
{ return 0; }
}
else {
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 1:
{ yyparser.programa().error().deCaracterNoReconocido(yytext());
}
case 17: break;
case 2:
{
}
case 18: break;
case 3:
{ yyparser.yylval = new PrevioParserVal(yytext());
return PrevioParser.ETIQUETA;
}
case 19: break;
case 4:
{ yyparser.yylval = new PrevioParserVal(yytext());
return PrevioParser.NUMERO;
}
case 20: break;
case 5:
{ yyparser.yylval = new PrevioParserVal(yytext());
return PrevioParser.VARIABLE;
}
case 21: break;
case 6:
{ return yycharat(0);
}
case 22: break;
case 7:
{ yyparser.yylval = new PrevioParserVal(yytext());
return PrevioParser.IDMACRO;
}
case 23: break;
case 8:
{ return PrevioParser.FLECHA;
}
case 24: break;
case 9:
{ return PrevioParser.DECREMENTO;
}
case 25: break;
case 10:
{ return PrevioParser.INCREMENTO;
}
case 26: break;
case 11:
{ return PrevioParser.IF;
}
case 27: break;
case 12:
{ return PrevioParser.DISTINTO;
}
case 28: break;
case 13:
{ return PrevioParser.END;
}
case 29: break;
case 14:
{ return PrevioParser.GOTO;
}
case 30: break;
case 15:
{ return PrevioParser.LOOP;
}
case 31: break;
case 16:
{ return PrevioParser.WHILE;
}
case 32: break;
default:
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}
| alberh/JIM | jim/src/main/java/com/jim_project/interprete/parser/previo/PrevioLex.java | Java | gpl-3.0 | 20,877 |
package visGrid.diagram.edit.parts;
import java.io.File;
import java.util.Collections;
import java.util.List;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.transaction.RunnableWithResult;
import org.eclipse.gef.AccessibleEditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.requests.DirectEditRequest;
import org.eclipse.gef.tools.DirectEditManager;
import org.eclipse.gmf.runtime.common.ui.services.parser.IParser;
import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus;
import org.eclipse.gmf.runtime.common.ui.services.parser.ParserEditStatus;
import org.eclipse.gmf.runtime.common.ui.services.parser.ParserOptions;
import org.eclipse.gmf.runtime.diagram.ui.editparts.CompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ITextAwareEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.LabelDirectEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry;
import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
import org.eclipse.gmf.runtime.notation.FontStyle;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.viewers.ICellEditorValidator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
/**
* @generated
*/
public class Series_reactorNameEditPart extends CompartmentEditPart implements
ITextAwareEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 5072;
/**
* @generated
*/
private DirectEditManager manager;
/**
* @generated
*/
private IParser parser;
/**
* @generated
*/
private List<?> parserElements;
/**
* @generated
*/
private String defaultText;
/**
* @generated
*/
public Series_reactorNameEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(
EditPolicy.SELECTION_FEEDBACK_ROLE,
new visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy());
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE,
new LabelDirectEditPolicy());
installEditPolicy(
EditPolicy.PRIMARY_DRAG_ROLE,
new visGrid.diagram.edit.parts.GridEditPart.NodeLabelDragPolicy());
}
/**
* @generated
*/
protected String getLabelTextHelper(IFigure figure) {
if (figure instanceof WrappingLabel) {
return ((WrappingLabel) figure).getText();
} else {
return ((Label) figure).getText();
}
}
/**
* @generated
*/
protected void setLabelTextHelper(IFigure figure, String text) {
if (figure instanceof WrappingLabel) {
((WrappingLabel) figure).setText(text);
} else {
((Label) figure).setText(text);
}
}
/**
* @generated
*/
protected Image getLabelIconHelper(IFigure figure) {
if (figure instanceof WrappingLabel) {
return ((WrappingLabel) figure).getIcon();
} else {
return ((Label) figure).getIcon();
}
}
/**
* @generated
*/
protected void setLabelIconHelper(IFigure figure, Image icon) {
if (figure instanceof WrappingLabel) {
((WrappingLabel) figure).setIcon(icon);
} else {
((Label) figure).setIcon(icon);
}
}
/**
* @generated
*/
public void setLabel(WrappingLabel figure) {
unregisterVisuals();
setFigure(figure);
defaultText = getLabelTextHelper(figure);
registerVisuals();
refreshVisuals();
}
/**
* @generated
*/
@SuppressWarnings("rawtypes")
protected List getModelChildren() {
return Collections.EMPTY_LIST;
}
/**
* @generated
*/
public IGraphicalEditPart getChildBySemanticHint(String semanticHint) {
return null;
}
/**
* @generated
*/
protected EObject getParserElement() {
return resolveSemanticElement();
}
/**
* @generated
*/
protected Image getLabelIcon() {
EObject parserElement = getParserElement();
if (parserElement == null) {
return null;
}
return visGrid.diagram.providers.VisGridElementTypes
.getImage(parserElement.eClass());
}
/**
* @generated
*/
protected String getLabelText() {
String text = null;
EObject parserElement = getParserElement();
if (parserElement != null && getParser() != null) {
text = getParser().getPrintString(
new EObjectAdapter(parserElement),
getParserOptions().intValue());
}
if (text == null || text.length() == 0) {
text = defaultText;
}
return text;
}
/**
* @generated
*/
public void setLabelText(String text) {
setLabelTextHelper(getFigure(), text);
Object pdEditPolicy = getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
if (pdEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) {
((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) pdEditPolicy)
.refreshFeedback();
}
Object sfEditPolicy = getEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE);
if (sfEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) {
((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) sfEditPolicy)
.refreshFeedback();
}
}
/**
* @generated
*/
public String getEditText() {
if (getParserElement() == null || getParser() == null) {
return ""; //$NON-NLS-1$
}
return getParser().getEditString(
new EObjectAdapter(getParserElement()),
getParserOptions().intValue());
}
/**
* @generated
*/
protected boolean isEditable() {
return getParser() != null;
}
/**
* @generated
*/
public ICellEditorValidator getEditTextValidator() {
return new ICellEditorValidator() {
public String isValid(final Object value) {
if (value instanceof String) {
final EObject element = getParserElement();
final IParser parser = getParser();
try {
IParserEditStatus valid = (IParserEditStatus) getEditingDomain()
.runExclusive(
new RunnableWithResult.Impl<IParserEditStatus>() {
public void run() {
setResult(parser
.isValidEditString(
new EObjectAdapter(
element),
(String) value));
}
});
return valid.getCode() == ParserEditStatus.EDITABLE ? null
: valid.getMessage();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
// shouldn't get here
return null;
}
};
}
/**
* @generated
*/
public IContentAssistProcessor getCompletionProcessor() {
if (getParserElement() == null || getParser() == null) {
return null;
}
return getParser().getCompletionProcessor(
new EObjectAdapter(getParserElement()));
}
/**
* @generated
*/
public ParserOptions getParserOptions() {
return ParserOptions.NONE;
}
/**
* @generated
*/
public IParser getParser() {
if (parser == null) {
parser = visGrid.diagram.providers.VisGridParserProvider
.getParser(
visGrid.diagram.providers.VisGridElementTypes.Series_reactor_2032,
getParserElement(),
visGrid.diagram.part.VisGridVisualIDRegistry
.getType(visGrid.diagram.edit.parts.Series_reactorNameEditPart.VISUAL_ID));
}
return parser;
}
/**
* @generated
*/
protected DirectEditManager getManager() {
if (manager == null) {
setManager(new TextDirectEditManager(this,
TextDirectEditManager.getTextCellEditorClass(this),
visGrid.diagram.edit.parts.VisGridEditPartFactory
.getTextCellEditorLocator(this)));
}
return manager;
}
/**
* @generated
*/
protected void setManager(DirectEditManager manager) {
this.manager = manager;
}
/**
* @generated
*/
protected void performDirectEdit() {
getManager().show();
}
/**
* @generated
*/
protected void performDirectEdit(Point eventLocation) {
if (getManager().getClass() == TextDirectEditManager.class) {
((TextDirectEditManager) getManager()).show(eventLocation
.getSWTPoint());
}
}
/**
* @generated
*/
private void performDirectEdit(char initialCharacter) {
if (getManager() instanceof TextDirectEditManager) {
((TextDirectEditManager) getManager()).show(initialCharacter);
} else {
performDirectEdit();
}
}
/**
* @generated
*/
protected void performDirectEditRequest(Request request) {
final Request theRequest = request;
try {
getEditingDomain().runExclusive(new Runnable() {
public void run() {
if (isActive() && isEditable()) {
if (theRequest
.getExtendedData()
.get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR) instanceof Character) {
Character initialChar = (Character) theRequest
.getExtendedData()
.get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR);
performDirectEdit(initialChar.charValue());
} else if ((theRequest instanceof DirectEditRequest)
&& (getEditText().equals(getLabelText()))) {
DirectEditRequest editRequest = (DirectEditRequest) theRequest;
performDirectEdit(editRequest.getLocation());
} else {
performDirectEdit();
}
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* @generated
*/
protected void refreshVisuals() {
super.refreshVisuals();
refreshLabel();
refreshFont();
refreshFontColor();
refreshUnderline();
refreshStrikeThrough();
refreshBounds();
}
/**
* @generated
*/
protected void refreshLabel() {
setLabelTextHelper(getFigure(), getLabelText());
setLabelIconHelper(getFigure(), getLabelIcon());
Object pdEditPolicy = getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
if (pdEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) {
((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) pdEditPolicy)
.refreshFeedback();
}
Object sfEditPolicy = getEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE);
if (sfEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) {
((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) sfEditPolicy)
.refreshFeedback();
}
}
/**
* @generated
*/
protected void refreshUnderline() {
FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle(
NotationPackage.eINSTANCE.getFontStyle());
if (style != null && getFigure() instanceof WrappingLabel) {
((WrappingLabel) getFigure()).setTextUnderline(style.isUnderline());
}
}
/**
* @generated
*/
protected void refreshStrikeThrough() {
FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle(
NotationPackage.eINSTANCE.getFontStyle());
if (style != null && getFigure() instanceof WrappingLabel) {
((WrappingLabel) getFigure()).setTextStrikeThrough(style
.isStrikeThrough());
}
}
/**
* @generated
*/
protected void refreshFont() {
FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle(
NotationPackage.eINSTANCE.getFontStyle());
if (style != null) {
FontData fontData = new FontData(style.getFontName(),
style.getFontHeight(), (style.isBold() ? SWT.BOLD
: SWT.NORMAL)
| (style.isItalic() ? SWT.ITALIC : SWT.NORMAL));
setFont(fontData);
}
}
/**
* @generated
*/
protected void setFontColor(Color color) {
getFigure().setForegroundColor(color);
}
/**
* @generated
*/
protected void addSemanticListeners() {
if (getParser() instanceof ISemanticParser) {
EObject element = resolveSemanticElement();
parserElements = ((ISemanticParser) getParser())
.getSemanticElementsBeingParsed(element);
for (int i = 0; i < parserElements.size(); i++) {
addListenerFilter(
"SemanticModel" + i, this, (EObject) parserElements.get(i)); //$NON-NLS-1$
}
} else {
super.addSemanticListeners();
}
}
/**
* @generated
*/
protected void removeSemanticListeners() {
if (parserElements != null) {
for (int i = 0; i < parserElements.size(); i++) {
removeListenerFilter("SemanticModel" + i); //$NON-NLS-1$
}
} else {
super.removeSemanticListeners();
}
}
/**
* @generated
*/
protected AccessibleEditPart getAccessibleEditPart() {
if (accessibleEP == null) {
accessibleEP = new AccessibleGraphicalEditPart() {
public void getName(AccessibleEvent e) {
e.result = getLabelTextHelper(getFigure());
}
};
}
return accessibleEP;
}
/**
* @generated
*/
private View getFontStyleOwnerView() {
return getPrimaryView();
}
/**
* @generated
*/
protected void addNotationalListeners() {
super.addNotationalListeners();
addListenerFilter("PrimaryView", this, getPrimaryView()); //$NON-NLS-1$
}
/**
* @generated
*/
protected void removeNotationalListeners() {
super.removeNotationalListeners();
removeListenerFilter("PrimaryView"); //$NON-NLS-1$
}
/**
* @generated
*/
protected void refreshBounds() {
int width = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE
.getSize_Width())).intValue();
int height = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE
.getSize_Height())).intValue();
Dimension size = new Dimension(width, height);
int x = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE
.getLocation_X())).intValue();
int y = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE
.getLocation_Y())).intValue();
Point loc = new Point(x, y);
((GraphicalEditPart) getParent()).setLayoutConstraint(this,
getFigure(), new Rectangle(loc, size));
}
/**
* @generated
*/
protected void handleNotificationEvent(Notification event) {
Object feature = event.getFeature();
if (NotationPackage.eINSTANCE.getSize_Width().equals(feature)
|| NotationPackage.eINSTANCE.getSize_Height().equals(feature)
|| NotationPackage.eINSTANCE.getLocation_X().equals(feature)
|| NotationPackage.eINSTANCE.getLocation_Y().equals(feature)) {
refreshBounds();
}
if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) {
Integer c = (Integer) event.getNewValue();
setFontColor(DiagramColorRegistry.getInstance().getColor(c));
} else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals(
feature)) {
refreshUnderline();
} else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough()
.equals(feature)) {
refreshStrikeThrough();
} else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals(
feature)
|| NotationPackage.eINSTANCE.getFontStyle_FontName().equals(
feature)
|| NotationPackage.eINSTANCE.getFontStyle_Bold()
.equals(feature)
|| NotationPackage.eINSTANCE.getFontStyle_Italic().equals(
feature)) {
refreshFont();
} else {
if (getParser() != null
&& getParser().isAffectingEvent(event,
getParserOptions().intValue())) {
refreshLabel();
}
if (getParser() instanceof ISemanticParser) {
ISemanticParser modelParser = (ISemanticParser) getParser();
if (modelParser.areSemanticElementsAffected(null, event)) {
removeSemanticListeners();
if (resolveSemanticElement() != null) {
addSemanticListeners();
}
refreshLabel();
}
}
}
super.handleNotificationEvent(event);
}
/**
* @generated
*/
protected IFigure createFigure() {
// Parent should assign one using setLabel() method
return null;
}
}
| mikesligo/visGrid | ie.tcd.gmf.visGrid.diagram/src/visGrid/diagram/edit/parts/Series_reactorNameEditPart.java | Java | gpl-3.0 | 16,066 |
package me.anthonybruno.soccerSim.reader;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
/**
* A class that parsers team PDF files into XML files.
*/
public class TeamPdfReader {
private static final Rectangle2D.Double firstTeamFirstPageRegion = new Rectangle2D.Double(0, 0, 330, 550);
private static final Rectangle2D.Double secondTeamFirstPageRegion = new Rectangle2D.Double(350, 0, 350, 550);
private final File file;
public TeamPdfReader(String fileName) {
this.file = new File(fileName);
}
public TeamPdfReader(File file) {
this.file = file;
}
// public String read() { //Using IText :(
// try {
// PdfReader pdfReader = new PdfReader(file.getAbsolutePath());
// PdfDocument pdfDocument = new PdfDocument(pdfReader);
//
// LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();
//
// PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy);
// parser.processPageContent(pdfDocument.getFirstPage());
// return strategy.getResultantText();
//
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
public void readAllTeamsToFiles() { //Using PDFBox
try {
PDFParser parser = new PDFParser(new RandomAccessFile(file, "r"));
parser.parse();
PDFTextStripperByArea pdfTextStripperByArea = new PDFTextStripperByArea();
pdfTextStripperByArea.addRegion("First", firstTeamFirstPageRegion);
pdfTextStripperByArea.addRegion("Second", secondTeamFirstPageRegion);
for (int i = 0; i < parser.getPDDocument().getNumberOfPages(); i++) {
pdfTextStripperByArea.extractRegions(parser.getPDDocument().getPage(i));
writeTeamToFile(pdfTextStripperByArea.getTextForRegion("First"), "teams");
writeTeamToFile(pdfTextStripperByArea.getTextForRegion("Second"), "teams");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeTeamToFile(String teamExtractedFromPDf, String saveDirectory) { //FIXME: Reduce size of method
if (teamExtractedFromPDf.isEmpty() || !teamExtractedFromPDf.contains(" ")) {
return; //reached a blank page
}
XmlWriter xmlWriter = new XmlWriter("UTF-8");
String text = teamExtractedFromPDf;
if (text.indexOf('\n') < text.indexOf(' ')) {
text = text.substring(text.indexOf('\n') + 1);
}
xmlWriter.createOpenTag("team");
if (text.startsWith(" ")) {
text = text.substring(text.indexOf('\n') + 1); //need this for El Salvador
}
String name = text.substring(0, text.indexOf(" "));
text = text.substring(text.indexOf(" ") + 1);
if (!Character.isDigit(text.charAt(0))) { //handles countries with two words in name
name += " " + text.substring(0, text.indexOf(" "));
}
xmlWriter.createTagWithValue("name", name);
for (int i = 0; i < 3; i++) { //skipping stuff we don't care about
text = moveToNextLine(text);
}
text = text.substring(text.indexOf(':') + 2);
String firstHalfAttempts = text.substring(0, text.indexOf(' '));
text = text.substring(text.indexOf(' ') + 1);
String secondHalfAttempts = text.substring(0, text.indexOf('\n'));
text = moveToNextLine(text);
xmlWriter.createTagWithValue("goalRating", text.substring(text.indexOf('-') + 1, text.indexOf('\n')));
text = moveToNextLine(text);
String[] defensiveAttempts = parseHalfValues(text);
text = defensiveAttempts[0];
String firstHalfDefensiveAttempts = defensiveAttempts[1];
String secondHalfDefensiveAttempts = defensiveAttempts[2];
String[] defensiveSOG = parseHalfValues(text);
text = defensiveSOG[0];
String firstHalfSOG = defensiveSOG[1];
String secondHalfSOG = defensiveSOG[2];
xmlWriter.createTagWithValue("formation", text.substring(text.indexOf(':') + 2, text.indexOf('\n')));
text = moveToNextLine(text);
text = text.substring(text.indexOf(':') + 2);
if (text.indexOf(' ') < text.indexOf('\n')) {
xmlWriter.createTagWithValue("strategy", text.substring(0, text.indexOf(' '))); //team has fair play score
} else {
xmlWriter.createTagWithValue("strategy", text.substring(0, text.indexOf("\n")));
}
text = moveToNextLine(text);
text = moveToNextLine(text);
parseHalfStats(xmlWriter, "halfStats", firstHalfAttempts, firstHalfDefensiveAttempts, firstHalfSOG);
parseHalfStats(xmlWriter, "halfStats", secondHalfAttempts, secondHalfDefensiveAttempts, secondHalfSOG);
xmlWriter.createOpenTag("players");
while (!text.startsWith("Goalies")) {
text = parsePlayer(xmlWriter, text);
}
text = moveToNextLine(text);
parseGoalies(xmlWriter, text);
xmlWriter.createCloseTag("players");
xmlWriter.createCloseTag("team");
File saveDir = new File(saveDirectory);
try {
saveDir.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (!saveDir.exists()) {
file.mkdir();
}
xmlWriter.writeToFile(new File("src/main/resources/teams/" + name + ".xml"));
}
private void parseGoalies(XmlWriter xmlWriter, String text) {
while (!text.isEmpty()) {
xmlWriter.createOpenTag("goalie");
String playerName = "";
do {
playerName += text.substring(0, text.indexOf(' '));
text = text.substring(text.indexOf(' ') + 1);
} while (!isNumeric(text.substring(0, text.indexOf(' '))));
xmlWriter.createTagWithValue("name", playerName);
xmlWriter.createTagWithValue("rating", text.substring(0, text.indexOf(' ')));
text = text.substring(text.indexOf(' ') + 1);
text = text.substring(text.indexOf(' ') + 1);
text = parsePlayerAttribute(xmlWriter, "injury", text);
createMultiplierTag(xmlWriter, text);
text = moveToNextLine(text);
xmlWriter.createCloseTag("goalie");
}
}
private boolean isNumeric(char c) {
return isNumeric(c + "");
}
private boolean isNumeric(String string) {
return string.matches("^[-+]?\\d+$");
}
private void createMultiplierTag(XmlWriter xmlWriter, String text) {
if (text.charAt(0) != '-') {
xmlWriter.createTagWithValue("multiplier", text.charAt(1) + "");
} else {
xmlWriter.createTagWithValue("multiplier", "0");
}
}
private String parsePlayer(XmlWriter xmlWriter, String text) {
xmlWriter.createOpenTag("player");
text = parsePlayerName(xmlWriter, text);
text = parsePlayerAttribute(xmlWriter, "shotRange", text);
text = parsePlayerAttribute(xmlWriter, "goal", text);
text = parsePlayerAttribute(xmlWriter, "injury", text);
createMultiplierTag(xmlWriter, text);
xmlWriter.createCloseTag("player");
text = moveToNextLine(text);
return text;
}
private String parsePlayerName(XmlWriter xmlWriter, String text) {
if (isNumeric(text.charAt(text.indexOf(' ') + 1))) {
return parsePlayerAttribute(xmlWriter, "name", text); //Player has single name
} else {
String playerName = text.substring(0, text.indexOf(' '));
text = text.substring(text.indexOf(' ') + 1);
while (!isNumeric(text.charAt(0))) {
playerName += ' ' + text.substring(0, text.indexOf(' '));
text = text.substring(text.indexOf(' ') + 1);
}
xmlWriter.createTagWithValue("name", playerName);
return text;
}
}
private String parsePlayerAttribute(XmlWriter xmlWriter, String tagName, String text) {
xmlWriter.createTagWithValue(tagName, text.substring(0, text.indexOf(' ')));
text = text.substring(text.indexOf(' ') + 1);
return text;
}
private String[] parseHalfValues(String text) {
text = text.substring(text.indexOf(':') + 2);
String firstHalf = text.substring(0, text.indexOf(' '));
text = text.substring(text.indexOf(' ') + 1);
String secondHalf = text.substring(0, text.indexOf('\n'));
text = moveToNextLine(text);
return new String[]{text, firstHalf, secondHalf};
}
private void parseHalfStats(XmlWriter xmlWriter, String halfName, String attempts, String defensiveAttempts, String defensiveShotsOnGoal) {
xmlWriter.createOpenTag(halfName);
xmlWriter.createTagWithValue("attempts", attempts);
xmlWriter.createTagWithValue("defensiveAttempts", defensiveAttempts);
xmlWriter.createTagWithValue("defensiveShotsOnGoal", defensiveShotsOnGoal);
xmlWriter.createCloseTag(halfName);
}
private String moveToNextLine(String text) {
return text.substring(text.indexOf("\n") + 1);
}
public static void main(String[] args) {
TeamPdfReader teamPdfReader = new TeamPdfReader("src/main/resources/ruleFiles/Cards1.pdf");
teamPdfReader.readAllTeamsToFiles();
teamPdfReader = new TeamPdfReader("src/main/resources/ruleFiles/Cards2.pdf");
teamPdfReader.readAllTeamsToFiles();
}
}
| AussieGuy0/soccerSim | src/main/java/me/anthonybruno/soccerSim/reader/TeamPdfReader.java | Java | gpl-3.0 | 9,771 |
/*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 org.b3log.symphony.service;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.event.Event;
import org.b3log.latke.event.EventException;
import org.b3log.latke.event.EventManager;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.Transaction;
import org.b3log.latke.repository.annotation.Transactional;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.Ids;
import org.b3log.symphony.event.EventTypes;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Liveness;
import org.b3log.symphony.model.Notification;
import org.b3log.symphony.model.Option;
import org.b3log.symphony.model.Pointtransfer;
import org.b3log.symphony.model.Reward;
import org.b3log.symphony.model.Role;
import org.b3log.symphony.model.Tag;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.NotificationRepository;
import org.b3log.symphony.repository.OptionRepository;
import org.b3log.symphony.repository.TagArticleRepository;
import org.b3log.symphony.repository.TagRepository;
import org.b3log.symphony.repository.UserRepository;
import org.b3log.symphony.util.Emotions;
import org.b3log.symphony.util.Symphonys;
import org.json.JSONObject;
/**
* Comment management service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 2.12.10.19, Feb 2, 2017
* @since 0.2.0
*/
@Service
public class CommentMgmtService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(CommentMgmtService.class.getName());
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* Option repository.
*/
@Inject
private OptionRepository optionRepository;
/**
* Tag repository.
*/
@Inject
private TagRepository tagRepository;
/**
* Tag-Article repository.
*/
@Inject
private TagArticleRepository tagArticleRepository;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Notification repository.
*/
@Inject
private NotificationRepository notificationRepository;
/**
* Event manager.
*/
@Inject
private EventManager eventManager;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Pointtransfer management service.
*/
@Inject
private PointtransferMgmtService pointtransferMgmtService;
/**
* Reward management service.
*/
@Inject
private RewardMgmtService rewardMgmtService;
/**
* Reward query service.
*/
@Inject
private RewardQueryService rewardQueryService;
/**
* Notification management service.
*/
@Inject
private NotificationMgmtService notificationMgmtService;
/**
* Liveness management service.
*/
@Inject
private LivenessMgmtService livenessMgmtService;
/**
* Removes a comment specified with the given comment id.
*
* @param commentId the given comment id
*/
@Transactional
public void removeComment(final String commentId) {
try {
final JSONObject comment = commentRepository.get(commentId);
if (null == comment) {
return;
}
final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
final JSONObject article = articleRepository.get(articleId);
article.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT) - 1);
// Just clear latest time and commenter name, do not get the real latest comment to update
article.put(Article.ARTICLE_LATEST_CMT_TIME, 0);
article.put(Article.ARTICLE_LATEST_CMTER_NAME, "");
articleRepository.update(articleId, article);
final String commentAuthorId = comment.optString(Comment.COMMENT_AUTHOR_ID);
final JSONObject commenter = userRepository.get(commentAuthorId);
commenter.put(UserExt.USER_COMMENT_COUNT, commenter.optInt(UserExt.USER_COMMENT_COUNT) - 1);
userRepository.update(commentAuthorId, commenter);
commentRepository.remove(comment.optString(Keys.OBJECT_ID));
final JSONObject commentCntOption = optionRepository.get(Option.ID_C_STATISTIC_CMT_COUNT);
commentCntOption.put(Option.OPTION_VALUE, commentCntOption.optInt(Option.OPTION_VALUE) - 1);
optionRepository.update(Option.ID_C_STATISTIC_CMT_COUNT, commentCntOption);
notificationRepository.removeByDataId(commentId);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Removes a comment error [id=" + commentId + "]", e);
}
}
/**
* A user specified by the given sender id thanks the author of a comment specified by the given comment id.
*
* @param commentId the given comment id
* @param senderId the given sender id
* @throws ServiceException service exception
*/
public void thankComment(final String commentId, final String senderId) throws ServiceException {
try {
final JSONObject comment = commentRepository.get(commentId);
if (null == comment) {
return;
}
if (Comment.COMMENT_STATUS_C_INVALID == comment.optInt(Comment.COMMENT_STATUS)) {
return;
}
final JSONObject sender = userRepository.get(senderId);
if (null == sender) {
return;
}
if (UserExt.USER_STATUS_C_VALID != sender.optInt(UserExt.USER_STATUS)) {
return;
}
final String receiverId = comment.optString(Comment.COMMENT_AUTHOR_ID);
final JSONObject receiver = userRepository.get(receiverId);
if (null == receiver) {
return;
}
if (UserExt.USER_STATUS_C_VALID != receiver.optInt(UserExt.USER_STATUS)) {
return;
}
if (receiverId.equals(senderId)) {
throw new ServiceException(langPropsService.get("thankSelfLabel"));
}
final int rewardPoint = Symphonys.getInt("pointThankComment");
if (rewardQueryService.isRewarded(senderId, commentId, Reward.TYPE_C_COMMENT)) {
return;
}
final String rewardId = Ids.genTimeMillisId();
if (Comment.COMMENT_ANONYMOUS_C_PUBLIC == comment.optInt(Comment.COMMENT_ANONYMOUS)) {
final boolean succ = null != pointtransferMgmtService.transfer(senderId, receiverId,
Pointtransfer.TRANSFER_TYPE_C_COMMENT_REWARD, rewardPoint, rewardId, System.currentTimeMillis());
if (!succ) {
throw new ServiceException(langPropsService.get("transferFailLabel"));
}
}
final JSONObject reward = new JSONObject();
reward.put(Keys.OBJECT_ID, rewardId);
reward.put(Reward.SENDER_ID, senderId);
reward.put(Reward.DATA_ID, commentId);
reward.put(Reward.TYPE, Reward.TYPE_C_COMMENT);
rewardMgmtService.addReward(reward);
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, receiverId);
notification.put(Notification.NOTIFICATION_DATA_ID, rewardId);
notificationMgmtService.addCommentThankNotification(notification);
livenessMgmtService.incLiveness(senderId, Liveness.LIVENESS_THANK);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Thanks a comment[id=" + commentId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Adds a comment with the specified request json object.
*
* @param requestJSONObject the specified request json object, for example, <pre>
* {
* "commentContent": "",
* "commentAuthorId": "",
* "commentOnArticleId": "",
* "commentOriginalCommentId": "", // optional
* "clientCommentId": "" // optional,
* "commentAuthorName": "" // If from client
* "commenter": {
* // User model
* },
* "commentIP": "", // optional, default to ""
* "commentUA": "", // optional, default to ""
* "commentAnonymous": int, // optional, default to 0 (public)
* "userCommentViewMode": int
* }
* </pre>, see {@link Comment} for more details
*
* @return generated comment id
* @throws ServiceException service exception
*/
public synchronized String addComment(final JSONObject requestJSONObject) throws ServiceException {
final long currentTimeMillis = System.currentTimeMillis();
final JSONObject commenter = requestJSONObject.optJSONObject(Comment.COMMENT_T_COMMENTER);
final String commentAuthorId = requestJSONObject.optString(Comment.COMMENT_AUTHOR_ID);
final boolean fromClient = requestJSONObject.has(Comment.COMMENT_CLIENT_COMMENT_ID);
final String articleId = requestJSONObject.optString(Comment.COMMENT_ON_ARTICLE_ID);
final String ip = requestJSONObject.optString(Comment.COMMENT_IP);
String ua = requestJSONObject.optString(Comment.COMMENT_UA);
final int commentAnonymous = requestJSONObject.optInt(Comment.COMMENT_ANONYMOUS);
final int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
if (currentTimeMillis - commenter.optLong(UserExt.USER_LATEST_CMT_TIME) < Symphonys.getLong("minStepCmtTime")
&& !Role.ROLE_ID_C_ADMIN.equals(commenter.optString(User.USER_ROLE))
&& !UserExt.DEFAULT_CMTER_ROLE.equals(commenter.optString(User.USER_ROLE))) {
LOGGER.log(Level.WARN, "Adds comment too frequent [userName={0}]", commenter.optString(User.USER_NAME));
throw new ServiceException(langPropsService.get("tooFrequentCmtLabel"));
}
final String commenterName = commenter.optString(User.USER_NAME);
JSONObject article = null;
try {
// check if admin allow to add comment
final JSONObject option = optionRepository.get(Option.ID_C_MISC_ALLOW_ADD_COMMENT);
if (!"0".equals(option.optString(Option.OPTION_VALUE))) {
throw new ServiceException(langPropsService.get("notAllowAddCommentLabel"));
}
final int balance = commenter.optInt(UserExt.USER_POINT);
if (Comment.COMMENT_ANONYMOUS_C_ANONYMOUS == commentAnonymous) {
final int anonymousPoint = Symphonys.getInt("anonymous.point");
if (balance < anonymousPoint) {
String anonymousEnabelPointLabel = langPropsService.get("anonymousEnabelPointLabel");
anonymousEnabelPointLabel
= anonymousEnabelPointLabel.replace("${point}", String.valueOf(anonymousPoint));
throw new ServiceException(anonymousEnabelPointLabel);
}
}
article = articleRepository.get(articleId);
if (!fromClient && !TuringQueryService.ROBOT_NAME.equals(commenterName)) {
int pointSum = Pointtransfer.TRANSFER_SUM_C_ADD_COMMENT;
// Point
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
if (articleAuthorId.equals(commentAuthorId)) {
pointSum = Pointtransfer.TRANSFER_SUM_C_ADD_SELF_ARTICLE_COMMENT;
}
if (balance - pointSum < 0) {
throw new ServiceException(langPropsService.get("insufficientBalanceLabel"));
}
}
} catch (final RepositoryException e) {
throw new ServiceException(e);
}
final int articleAnonymous = article.optInt(Article.ARTICLE_ANONYMOUS);
final Transaction transaction = commentRepository.beginTransaction();
try {
article.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT) + 1);
article.put(Article.ARTICLE_LATEST_CMTER_NAME, commenter.optString(User.USER_NAME));
if (Comment.COMMENT_ANONYMOUS_C_ANONYMOUS == commentAnonymous) {
article.put(Article.ARTICLE_LATEST_CMTER_NAME, UserExt.ANONYMOUS_USER_NAME);
}
article.put(Article.ARTICLE_LATEST_CMT_TIME, currentTimeMillis);
final String ret = Ids.genTimeMillisId();
final JSONObject comment = new JSONObject();
comment.put(Keys.OBJECT_ID, ret);
String content = requestJSONObject.optString(Comment.COMMENT_CONTENT).
replace("_esc_enter_88250_", "<br/>"); // Solo client escape
comment.put(Comment.COMMENT_AUTHOR_ID, commentAuthorId);
comment.put(Comment.COMMENT_ON_ARTICLE_ID, articleId);
if (fromClient) {
comment.put(Comment.COMMENT_CLIENT_COMMENT_ID, requestJSONObject.optString(Comment.COMMENT_CLIENT_COMMENT_ID));
// Appends original commenter name
final String authorName = requestJSONObject.optString(Comment.COMMENT_T_AUTHOR_NAME);
content += " <i class='ft-small'>by " + authorName + "</i>";
}
final String originalCmtId = requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCmtId);
if (StringUtils.isNotBlank(originalCmtId)) {
final JSONObject originalCmt = commentRepository.get(originalCmtId);
final int originalCmtReplyCnt = originalCmt.optInt(Comment.COMMENT_REPLY_CNT);
originalCmt.put(Comment.COMMENT_REPLY_CNT, originalCmtReplyCnt + 1);
commentRepository.update(originalCmtId, originalCmt);
}
content = Emotions.toAliases(content);
// content = StringUtils.trim(content) + " "; https://github.com/b3log/symphony/issues/389
content = content.replace(langPropsService.get("uploadingLabel", Locale.SIMPLIFIED_CHINESE), "");
content = content.replace(langPropsService.get("uploadingLabel", Locale.US), "");
comment.put(Comment.COMMENT_CONTENT, content);
comment.put(Comment.COMMENT_CREATE_TIME, System.currentTimeMillis());
comment.put(Comment.COMMENT_SHARP_URL, "/article/" + articleId + "#" + ret);
comment.put(Comment.COMMENT_STATUS, Comment.COMMENT_STATUS_C_VALID);
comment.put(Comment.COMMENT_IP, ip);
if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) {
LOGGER.log(Level.WARN, "UA is too long [" + ua + "]");
ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA);
}
comment.put(Comment.COMMENT_UA, ua);
comment.put(Comment.COMMENT_ANONYMOUS, commentAnonymous);
final JSONObject cmtCntOption = optionRepository.get(Option.ID_C_STATISTIC_CMT_COUNT);
final int cmtCnt = cmtCntOption.optInt(Option.OPTION_VALUE);
cmtCntOption.put(Option.OPTION_VALUE, String.valueOf(cmtCnt + 1));
articleRepository.update(articleId, article); // Updates article comment count, latest commenter name and time
optionRepository.update(Option.ID_C_STATISTIC_CMT_COUNT, cmtCntOption); // Updates global comment count
// Updates tag comment count and User-Tag relation
final String tagsString = article.optString(Article.ARTICLE_TAGS);
final String[] tagStrings = tagsString.split(",");
for (int i = 0; i < tagStrings.length; i++) {
final String tagTitle = tagStrings[i].trim();
final JSONObject tag = tagRepository.getByTitle(tagTitle);
tag.put(Tag.TAG_COMMENT_CNT, tag.optInt(Tag.TAG_COMMENT_CNT) + 1);
tag.put(Tag.TAG_RANDOM_DOUBLE, Math.random());
tagRepository.update(tag.optString(Keys.OBJECT_ID), tag);
}
// Updates user comment count, latest comment time
commenter.put(UserExt.USER_COMMENT_COUNT, commenter.optInt(UserExt.USER_COMMENT_COUNT) + 1);
commenter.put(UserExt.USER_LATEST_CMT_TIME, currentTimeMillis);
userRepository.update(commenter.optString(Keys.OBJECT_ID), commenter);
comment.put(Comment.COMMENT_GOOD_CNT, 0);
comment.put(Comment.COMMENT_BAD_CNT, 0);
comment.put(Comment.COMMENT_SCORE, 0D);
comment.put(Comment.COMMENT_REPLY_CNT, 0);
// Adds the comment
final String commentId = commentRepository.add(comment);
// Updates tag-article relation stat.
final List<JSONObject> tagArticleRels = tagArticleRepository.getByArticleId(articleId);
for (final JSONObject tagArticleRel : tagArticleRels) {
tagArticleRel.put(Article.ARTICLE_LATEST_CMT_TIME, currentTimeMillis);
tagArticleRel.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT));
tagArticleRepository.update(tagArticleRel.optString(Keys.OBJECT_ID), tagArticleRel);
}
transaction.commit();
if (!fromClient && Comment.COMMENT_ANONYMOUS_C_PUBLIC == commentAnonymous
&& Article.ARTICLE_ANONYMOUS_C_PUBLIC == articleAnonymous
&& !TuringQueryService.ROBOT_NAME.equals(commenterName)) {
// Point
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
if (articleAuthorId.equals(commentAuthorId)) {
pointtransferMgmtService.transfer(commentAuthorId, Pointtransfer.ID_C_SYS,
Pointtransfer.TRANSFER_TYPE_C_ADD_COMMENT, Pointtransfer.TRANSFER_SUM_C_ADD_SELF_ARTICLE_COMMENT,
commentId, System.currentTimeMillis());
} else {
pointtransferMgmtService.transfer(commentAuthorId, articleAuthorId,
Pointtransfer.TRANSFER_TYPE_C_ADD_COMMENT, Pointtransfer.TRANSFER_SUM_C_ADD_COMMENT,
commentId, System.currentTimeMillis());
}
livenessMgmtService.incLiveness(commentAuthorId, Liveness.LIVENESS_COMMENT);
}
// Event
final JSONObject eventData = new JSONObject();
eventData.put(Comment.COMMENT, comment);
eventData.put(Common.FROM_CLIENT, fromClient);
eventData.put(Article.ARTICLE, article);
eventData.put(UserExt.USER_COMMENT_VIEW_MODE, commentViewMode);
try {
eventManager.fireEventAsynchronously(new Event<JSONObject>(EventTypes.ADD_COMMENT_TO_ARTICLE, eventData));
} catch (final EventException e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
}
return ret;
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Adds a comment failed", e);
throw new ServiceException(e);
}
}
/**
* Updates the specified comment by the given comment id.
*
* @param commentId the given comment id
* @param comment the specified comment
* @throws ServiceException service exception
*/
public void updateComment(final String commentId, final JSONObject comment) throws ServiceException {
final Transaction transaction = commentRepository.beginTransaction();
try {
String content = comment.optString(Comment.COMMENT_CONTENT);
content = Emotions.toAliases(content);
content = StringUtils.trim(content) + " ";
content = content.replace(langPropsService.get("uploadingLabel", Locale.SIMPLIFIED_CHINESE), "");
content = content.replace(langPropsService.get("uploadingLabel", Locale.US), "");
comment.put(Comment.COMMENT_CONTENT, content);
commentRepository.update(commentId, comment);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates a comment[id=" + commentId + "] failed", e);
throw new ServiceException(e);
}
}
}
| gaozhenhong/symphony | src/main/java/org/b3log/symphony/service/CommentMgmtService.java | Java | gpl-3.0 | 22,223 |
/*
* Copyright (C) 2000 - 2011 TagServlet Ltd
*
* This file is part of Open BlueDragon (OpenBD) CFML Server Engine.
*
* OpenBD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* Free Software Foundation,version 3.
*
* OpenBD 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 OpenBD. If not, see http://www.gnu.org/licenses/
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with any of the JARS listed in the README.txt (or a modified version of
* (that library), containing parts covered by the terms of that JAR, the
* licensors of this Program grant you additional permission to convey the
* resulting work.
* README.txt @ http://www.openbluedragon.org/license/README.txt
*
* http://openbd.org/
*
* $Id: CronSetDirectory.java 1765 2011-11-04 07:55:52Z alan $
*/
package org.alanwilliamson.openbd.plugin.crontab;
import com.naryx.tagfusion.cfm.engine.cfArgStructData;
import com.naryx.tagfusion.cfm.engine.cfBooleanData;
import com.naryx.tagfusion.cfm.engine.cfData;
import com.naryx.tagfusion.cfm.engine.cfSession;
import com.naryx.tagfusion.cfm.engine.cfmRunTimeException;
import com.naryx.tagfusion.expression.function.functionBase;
public class CronSetDirectory extends functionBase {
private static final long serialVersionUID = 1L;
public CronSetDirectory(){ min = max = 1; setNamedParams( new String[]{ "directory" } ); }
public String[] getParamInfo(){
return new String[]{
"uri directory - will be created if not exists",
};
}
public java.util.Map getInfo(){
return makeInfo(
"system",
"Sets the URI directory that the cron tasks will run from. Calling this function will enable the crontab scheduler to start. This persists across server restarts",
ReturnType.BOOLEAN );
}
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
CronExtension.setRootPath( getNamedStringParam(argStruct, "directory", null ) );
return cfBooleanData.TRUE;
}
}
| OpenBD/openbd-core | src/org/alanwilliamson/openbd/plugin/crontab/CronSetDirectory.java | Java | gpl-3.0 | 2,444 |
package com.gentasaurus.ubahfood.inventory;
import com.gentasaurus.ubahfood.init.ModBlocks;
import com.gentasaurus.ubahfood.item.crafting.SCMCraftingManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.*;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class ContainerSCM extends Container
{
/** The crafting matrix inventory (3x3). */
public InventoryCrafting craftMatrix;
public IInventory craftResult;
private World worldObj;
private int posX;
private int posY;
private int posZ;
public ContainerSCM(InventoryPlayer invPlayer, World world, int x, int y, int z)
{
craftMatrix = new InventoryCrafting(this, 3, 1);
craftResult = new InventoryCraftResult();
worldObj = world;
posX = x;
posY = y;
posZ = z;
this.addSlotToContainer(new SlotSCM(invPlayer.player, craftMatrix, craftResult, 0, 124, 35));
int i;
int i1;
for (i = 0; i < 3; i++)
{
for (i1 = 0; i1 < 1; i1++)
{
this.addSlotToContainer(new Slot(this.craftMatrix, i1 + i * 1, 57 + i1 * 18, 17 + i * 18));
}
}
for (i = 0; i < 3; ++i)
{
for (i1 = 0; i1 < 9; ++i1)
{
this.addSlotToContainer(new Slot(invPlayer, i1 + i * 9 + 9, 8 + i1 * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i)
{
this.addSlotToContainer(new Slot(invPlayer, i, 8 + i * 18, 142));
}
this.onCraftMatrixChanged(craftMatrix);
}
/**
* Callback for when the crafting matrix is changed.
*/
public void onCraftMatrixChanged(IInventory p_75130_1_)
{
craftResult.setInventorySlotContents(0, SCMCraftingManager.getInstance().findMatchingRecipe(craftMatrix, worldObj));
}
/**
* Called when the container is closed.
*/
public void onContainerClosed(EntityPlayer p_75134_1_)
{
super.onContainerClosed(p_75134_1_);
if (!this.worldObj.isRemote)
{
for (int i = 0; i < 3; ++i)
{
ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);
if (itemstack != null)
{
p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false);
}
}
}
}
public boolean canInteractWith(EntityPlayer p_75145_1_)
{
return this.worldObj.getBlock(this.posX, this.posY, this.posZ) != ModBlocks.snowConeMachine ? false : p_75145_1_.getDistanceSq((double)this.posX + 0.5D, (double)this.posY + 0.5D, (double)this.posZ + 0.5D) <= 64.0D;
}
/**
* Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that.
*/
public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_)
{
return null;
}
public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_)
{
return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_);
}
} | gentasaurus/UbahFood | src/main/java/com/gentasaurus/ubahfood/inventory/ContainerSCM.java | Java | gpl-3.0 | 3,263 |
package org.epilot.ccf.codec;
import org.apache.mina.common.ByteBuffer;
import org.epilot.ccf.core.code.AbstractMessageEncode;
import org.epilot.ccf.core.protocol.Message;
import org.epilot.ccf.core.protocol.MessageBody;
import org.epilot.ccf.core.protocol.MessageHeader;
import org.epilot.ccf.core.util.ByteBufferDataHandle;
public class MessageEncode extends AbstractMessageEncode {
private String serviceName;
public MessageEncode(String serviceName) {
this.serviceName = serviceName;
}
protected void encodeMessage(GameMessageDataHandle messageDataHandle,Message message,ByteBuffer buffer) {
ByteBufferDataHandle byteBufferDataHandle =new ByteBufferDataHandle(buffer);
MessageHeader header = message.getHeader();
MessageBody body = message.getBody();
if(header ==null)//无消息头
{
return;
}
messageDataHandle.getHeaderBuffer(serviceName,header, byteBufferDataHandle);
if(body !=null)
{
messageDataHandle.getBodyBuffer(String.valueOf(header.getProtocolId()),body, byteBufferDataHandle);
}
}
@Override
protected void encodeMessage(DefaultMessageDataHandle messageDataHandle,
Message message, ByteBuffer buffer) {
}
}
| bozhbo12/demo-spring-server | spring-game/src/main/java/org/epilot/ccf/codec/MessageEncode.java | Java | gpl-3.0 | 1,193 |
package com.baeldung.iteratorguide;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorGuide {
public static void main(String[] args) {
List<String> items = new ArrayList<>();
items.add("ONE");
items.add("TWO");
items.add("THREE");
Iterator<String> iter = items.iterator();
while (iter.hasNext()) {
String next = iter.next();
System.out.println(next);
iter.remove();
}
ListIterator<String> listIterator = items.listIterator();
while(listIterator.hasNext()) {
String nextWithIndex = items.get(listIterator.nextIndex());
String next = listIterator.next();
if( "ONE".equals(next)) {
listIterator.set("SWAPPED");
}
}
listIterator.add("FOUR");
while(listIterator.hasPrevious()) {
String previousWithIndex = items.get(listIterator.previousIndex());
String previous = listIterator.previous();
System.out.println(previous);
}
listIterator.forEachRemaining(e -> {
System.out.println(e);
});
}
}
| Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/core-java-modules/core-java-collections/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java | Java | gpl-3.0 | 1,260 |
package com.tikaji.halocraft;
import com.tikaji.halocraft.common.handlers.ConfigurationHandler;
import com.tikaji.halocraft.common.proxy.IProxy;
import com.tikaji.halocraft.common.utility.Reference;
import com.tikaji.halocraft.common.utility.VersionChecker;
import net.minecraftforge.common.config.Configuration;
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;
/**
* Created by Jacob Williams on 6/17/2015.
*/
@Mod(modid = Reference.ModInfo.MOD_ID, name = Reference.ModInfo.MOD_NAME, version = Reference.ModInfo.VERSION)
public class HaloCraft
{
@Mod.Instance
public static HaloCraft INSTANCE;
public static boolean haveWarnedVersionIsOutOfDate = false;
@SidedProxy(clientSide = Reference.ModInfo.CLIENT_PROXY_CLASS, serverSide = Reference.ModInfo.SERVER_PROXY_CLASS)
public static IProxy proxy;
public static VersionChecker versionChecker;
public static String prependModID(String name)
{
return Reference.ModInfo.MOD_ID + ":" + name;
}
@Mod.EventHandler
public void initialize(FMLInitializationEvent event)
{
proxy.init();
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event)
{
proxy.postInit();
ConfigurationHandler.postInit();
}
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event)
{
ConfigurationHandler.init(new Configuration(event.getSuggestedConfigurationFile()));
proxy.preInit();
ConfigurationHandler.save();
}
}
| Tikaji/HaloCraft | src/main/java/com/tikaji/halocraft/HaloCraft.java | Java | gpl-3.0 | 1,665 |
package com.kraz.minehr.items;
import com.kraz.minehr.MineHr;
import com.kraz.minehr.reference.Reference;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemHoe;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class HorizonHoe extends ItemHoe {
public HorizonHoe() {
super(MineHr.HorizonToolMaterial);
}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister) {
this.itemIcon = iconRegister.registerIcon(Reference.MOD_ID + ":" + this.getUnlocalizedName().substring(5));
}
}
| npomroy/MineHr | src/main/java/com/kraz/minehr/items/HorizonHoe.java | Java | gpl-3.0 | 614 |
package com.taobao.api.response;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.internal.mapping.ApiField;
/**
* TOP API: taobao.logistics.consign.order.createandsend response.
*
* @author auto create
* @since 1.0, null
*/
public class LogisticsConsignOrderCreateandsendResponse extends TaobaoResponse {
private static final long serialVersionUID = 2877278252382584596L;
/**
* 是否成功
*/
@ApiField("is_success")
private Boolean isSuccess;
/**
* 订单ID
*/
@ApiField("order_id")
private Long orderId;
/**
* 结果描述
*/
@ApiField("result_desc")
private String resultDesc;
public Boolean getIsSuccess() {
return this.isSuccess;
}
public Long getOrderId() {
return this.orderId;
}
public String getResultDesc() {
return this.resultDesc;
}
public void setIsSuccess(Boolean isSuccess) {
this.isSuccess = isSuccess;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public void setResultDesc(String resultDesc) {
this.resultDesc = resultDesc;
}
}
| kuiwang/my-dev | src/main/java/com/taobao/api/response/LogisticsConsignOrderCreateandsendResponse.java | Java | gpl-3.0 | 1,165 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.voicecrystal.pixeldungeonlegends.actors.hero;
import com.watabou.utils.Bundle;
public enum HeroSubClass {
NONE( null, null ),
GLADIATOR( "gladiator",
"A successful attack with a melee weapon allows the _Gladiator_ to start a combo, " +
"in which every next successful hit inflicts more damage." ),
BERSERKER( "berserker",
"When severely wounded, the _Berserker_ enters a state of wild fury " +
"significantly increasing his damage output." ),
WARLOCK( "warlock",
"After killing an enemy the _Warlock_ consumes its soul. " +
"It heals his wounds and satisfies his hunger." ),
BATTLEMAGE( "battlemage",
"When fighting with a wand in his hands, the _Battlemage_ inflicts additional damage depending " +
"on the current number of charges. Every successful hit restores 1 charge to this wand." ),
ASSASSIN( "assassin",
"When performing a surprise attack, the _Assassin_ inflicts additional damage to his target." ),
FREERUNNER( "freerunner",
"The _Freerunner_ can move almost twice faster, than most of the monsters. When he " +
"is running, the Freerunner is much harder to hit. For that he must be unencumbered and not starving." ),
SNIPER( "sniper",
"_Snipers_ are able to detect weak points in an enemy's armor, " +
"effectively ignoring it when using a missile weapon." ),
WARDEN( "warden",
"Having a strong connection with forces of nature gives _Wardens_ an ability to gather dewdrops and " +
"seeds from plants. Also trampling a high grass grants them a temporary armor buff." );
private String title;
private String desc;
private HeroSubClass( String title, String desc ) {
this.title = title;
this.desc = desc;
}
public String title() {
return title;
}
public String desc() {
return desc;
}
private static final String SUBCLASS = "subClass";
public void storeInBundle( Bundle bundle ) {
bundle.put( SUBCLASS, toString() );
}
public static HeroSubClass restoreInBundle( Bundle bundle ) {
String value = bundle.getString( SUBCLASS );
try {
return valueOf( value );
} catch (Exception e) {
return NONE;
}
}
}
| Cerement/pixel-dungeon-legends | java/com/voicecrystal/pixeldungeonlegends/actors/hero/HeroSubClass.java | Java | gpl-3.0 | 2,845 |
/**General utility methods collection (not all self developed). */
package de.konradhoeffner.commons; | AKSW/cubeqa | src/main/java/de/konradhoeffner/commons/package-info.java | Java | gpl-3.0 | 101 |
package listener;
/**
* Created by pengshu on 2016/11/11.
*/
public class IndexManager implements EntryListener {
/**
* 博客文章被创建
*
* @param entryevent
*/
@Override
public void entryAdded(EntryEvent entryevent) {
System.out.println("IndexManager 处理 博客文章被创建事件。");
}
/**
* 博客文章被删除
*
* @param entryevent
*/
@Override
public void entryDeleted(EntryEvent entryevent) {
System.out.println("IndexManager 处理 博客文章被删除事件。");
}
/**
* 博客文章被修改
*
* @param entryevent
*/
@Override
public void entryModified(EntryEvent entryevent) {
System.out.println("IndexManager 处理 博客文章被修改事件。");
}
}
| gaoju9963/MyProject | user/src/main/java/listener/IndexManager.java | Java | gpl-3.0 | 819 |
package com.actelion.research.orbit.imageAnalysis.components.icons;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.Base64;
import java.util.Stack;
import javax.imageio.ImageIO;
import javax.swing.SwingUtilities;
import javax.swing.plaf.UIResource;
import org.pushingpixels.neon.api.icon.ResizableIcon;
import org.pushingpixels.neon.api.icon.ResizableIconUIResource;
/**
* This class has been automatically generated using <a
* href="https://github.com/kirill-grouchnikov/radiance">Photon SVG transcoder</a>.
*/
public class toggle_markup implements ResizableIcon {
private Shape shape = null;
private GeneralPath generalPath = null;
private Paint paint = null;
private Stroke stroke = null;
private Shape clip = null;
private Stack<AffineTransform> transformsStack = new Stack<>();
private void _paint0(Graphics2D g,float origAlpha) {
transformsStack.push(g.getTransform());
//
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
transformsStack.push(g.getTransform());
g.transform(new AffineTransform(1.0666667222976685f, 0.0f, 0.0f, 1.0666667222976685f, -0.0f, -0.0f));
// _0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
transformsStack.push(g.getTransform());
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -343.7007751464844f));
// _0_0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
transformsStack.push(g.getTransform());
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0_0
paint = new Color(255, 0, 255, 255);
stroke = new BasicStroke(25.0f,0,0,4.0f,null,0.0f);
shape = new Rectangle2D.Double(86.42857360839844, 424.5050964355469, 187.14285278320312, 205.0);
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(transformsStack.pop());
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
transformsStack.push(g.getTransform());
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0_1
paint = new Color(0, 255, 255, 255);
stroke = new BasicStroke(25.0f,0,0,4.0f,null,0.0f);
if (generalPath == null) {
generalPath = new GeneralPath();
} else {
generalPath.reset();
}
generalPath.moveTo(450.7143f, 462.36224f);
generalPath.lineTo(425.0f, 703.7908f);
generalPath.lineTo(236.42857f, 766.6479f);
generalPath.lineTo(96.42857f, 826.6479f);
generalPath.lineTo(84.28571f, 947.3622f);
generalPath.lineTo(412.85715f, 1023.0765f);
generalPath.lineTo(482.85715f, 902.3622f);
generalPath.lineTo(620.0f, 989.5051f);
generalPath.lineTo(637.8571f, 420.93365f);
generalPath.closePath();
shape = generalPath;
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(transformsStack.pop());
g.setTransform(transformsStack.pop());
g.setTransform(transformsStack.pop());
g.setTransform(transformsStack.pop());
}
@SuppressWarnings("unused")
private void innerPaint(Graphics2D g) {
float origAlpha = 1.0f;
Composite origComposite = g.getComposite();
if (origComposite instanceof AlphaComposite) {
AlphaComposite origAlphaComposite =
(AlphaComposite)origComposite;
if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) {
origAlpha = origAlphaComposite.getAlpha();
}
}
_paint0(g, origAlpha);
shape = null;
generalPath = null;
paint = null;
stroke = null;
clip = null;
transformsStack.clear();
}
/**
* Returns the X of the bounding box of the original SVG image.
*
* @return The X of the bounding box of the original SVG image.
*/
public static double getOrigX() {
return 75.46253967285156;
}
/**
* Returns the Y of the bounding box of the original SVG image.
*
* @return The Y of the bounding box of the original SVG image.
*/
public static double getOrigY() {
return 65.65621185302734;
}
/**
* Returns the width of the bounding box of the original SVG image.
*
* @return The width of the bounding box of the original SVG image.
*/
public static double getOrigWidth() {
return 618.7836303710938;
}
/**
* Returns the height of the bounding box of the original SVG image.
*
* @return The height of the bounding box of the original SVG image.
*/
public static double getOrigHeight() {
return 674.2141723632812;
}
/** The current width of this resizable icon. */
private int width;
/** The current height of this resizable icon. */
private int height;
/**
* Creates a new transcoded SVG image. This is marked as private to indicate that app
* code should be using the {@link #of(int, int)} method to obtain a pre-configured instance.
*/
private toggle_markup() {
this.width = (int) getOrigWidth();
this.height = (int) getOrigHeight();
}
@Override
public int getIconHeight() {
return height;
}
@Override
public int getIconWidth() {
return width;
}
@Override
public synchronized void setDimension(Dimension newDimension) {
this.width = newDimension.width;
this.height = newDimension.height;
}
@Override
public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.translate(x, y);
double coef1 = (double) this.width / getOrigWidth();
double coef2 = (double) this.height / getOrigHeight();
double coef = Math.min(coef1, coef2);
g2d.clipRect(0, 0, this.width, this.height);
g2d.scale(coef, coef);
g2d.translate(-getOrigX(), -getOrigY());
if (coef1 != coef2) {
if (coef1 < coef2) {
int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0);
g2d.translate(0, extraDy);
} else {
int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0);
g2d.translate(extraDx, 0);
}
}
Graphics2D g2ForInner = (Graphics2D) g2d.create();
innerPaint(g2ForInner);
g2ForInner.dispose();
g2d.dispose();
}
/**
* Returns a new instance of this icon with specified dimensions.
*
* @param width Required width of the icon
* @param height Required height of the icon
* @return A new instance of this icon with specified dimensions.
*/
public static ResizableIcon of(int width, int height) {
toggle_markup base = new toggle_markup();
base.width = width;
base.height = height;
return base;
}
/**
* Returns a new {@link UIResource} instance of this icon with specified dimensions.
*
* @param width Required width of the icon
* @param height Required height of the icon
* @return A new {@link UIResource} instance of this icon with specified dimensions.
*/
public static ResizableIconUIResource uiResourceOf(int width, int height) {
toggle_markup base = new toggle_markup();
base.width = width;
base.height = height;
return new ResizableIconUIResource(base);
}
/**
* Returns a factory that returns instances of this icon on demand.
*
* @return Factory that returns instances of this icon on demand.
*/
public static Factory factory() {
return toggle_markup::new;
}
}
| mstritt/orbit-image-analysis | src/main/java/com/actelion/research/orbit/imageAnalysis/components/icons/toggle_markup.java | Java | gpl-3.0 | 7,640 |
/*
Copyright 2012-2016 Michael Pozhidaev <michael.pozhidaev@gmail.com>
This file is part of LUWRAIN.
LUWRAIN 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.
LUWRAIN 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.
*/
package org.luwrain.core;
import java.util.*;
class ShortcutManager
{
class Entry
{
String name = "";
Shortcut shortcut;
Entry(String name, Shortcut shortcut)
{
NullCheck.notNull(name, "name");
NullCheck.notNull(shortcut, "shortcut");
if (name.trim().isEmpty())
throw new IllegalArgumentException("name may not be empty");
this.name = name;
this.shortcut = shortcut;
}
}
private final TreeMap<String, Entry> shortcuts = new TreeMap<String, Entry>();
boolean add(Shortcut shortcut)
{
NullCheck.notNull(shortcut, "shortcut");
final String name = shortcut.getName();
if (name == null || name.trim().isEmpty())
return false;
if (shortcuts.containsKey(name))
return false;
shortcuts.put(name, new Entry(name, shortcut));
return true;
}
Application[] prepareApp(String name, String[] args)
{
NullCheck.notNull(name, "name");
NullCheck.notNullItems(args, "args");
if (name.trim().isEmpty())
throw new IllegalArgumentException("name may not be empty");
if (!shortcuts.containsKey(name))
return null;
return shortcuts.get(name).shortcut.prepareApp(args);
}
String[] getShortcutNames()
{
final Vector<String> res = new Vector<String>();
for(Map.Entry<String, Entry> e: shortcuts.entrySet())
res.add(e.getKey());
String[] str = res.toArray(new String[res.size()]);
Arrays.sort(str);
return str;
}
void addBasicShortcuts()
{
add(new Shortcut(){
@Override public String getName()
{
return "registry";
}
@Override public Application[] prepareApp(String[] args)
{
Application[] res = new Application[1];
res[0] = new org.luwrain.app.registry.RegistryApp();
return res;
}
});
}
void addOsShortcuts(Luwrain luwrain, Registry registry)
{
NullCheck.notNull(luwrain, "luwrain");
NullCheck.notNull(registry, "registry");
registry.addDirectory(Settings.OS_SHORTCUTS_PATH);
for(String s: registry.getDirectories(Settings.OS_SHORTCUTS_PATH))
{
if (s.trim().isEmpty())
continue;
final OsCommands.OsShortcut shortcut = new OsCommands.OsShortcut(luwrain);
if (shortcut.init(Settings.createOsShortcut(registry, Registry.join(Settings.OS_SHORTCUTS_PATH, s))))
add(shortcut);
}
}
}
| rPman/luwrain | src/main/java/org/luwrain/core/ShortcutManager.java | Java | gpl-3.0 | 2,884 |
/*
* Copyright appNativa Inc. All Rights Reserved.
*
* This file is part of the Real-time Application Rendering Engine (RARE).
*
* RARE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.appnativa.rare.platform.swing.ui.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import com.appnativa.rare.Platform;
import com.appnativa.rare.iConstants;
import com.appnativa.rare.iPlatformAppContext;
import com.appnativa.rare.platform.swing.ui.util.SwingGraphics;
import com.appnativa.rare.ui.ColorUtils;
import com.appnativa.rare.ui.FontUtils;
import com.appnativa.rare.ui.UIColor;
import com.appnativa.rare.ui.UIDimension;
import com.appnativa.rare.ui.iPlatformIcon;
import com.appnativa.rare.ui.painter.iPainter;
import com.appnativa.rare.ui.painter.iPainterSupport;
import com.appnativa.rare.ui.painter.iPlatformComponentPainter;
import com.appnativa.util.CharArray;
import com.appnativa.util.XMLUtils;
public class RadioButtonView extends JRadioButton implements iPainterSupport, iView {
protected static iPlatformIcon deselectedIconDisabled_;
protected static iPlatformIcon deselectedIcon_;
protected static iPlatformIcon deselectedPressedIcon_;
protected static iPlatformIcon selectedIconDisabled_;
protected static iPlatformIcon selectedIcon_;
protected static iPlatformIcon selectedPressedIcon_;
private String originalText;
private boolean wordWrap;
public RadioButtonView() {
super();
initialize();
}
public RadioButtonView(Icon icon) {
super(icon);
initialize();
}
public RadioButtonView(String text) {
super(text);
initialize();
}
public RadioButtonView(String text, Icon icon) {
super(text, icon);
initialize();
}
AffineTransform transform;
protected SwingGraphics graphics;
private iPlatformComponentPainter componentPainter;
@Override
public boolean isOpaque() {
return ((componentPainter != null) && componentPainter.isBackgroundPaintEnabled())
? false
: super.isOpaque();
}
@Override
public void setTransformEx(AffineTransform tx) {
transform = tx;
}
@Override
public Color getForeground() {
Color c=super.getForeground();
if(c instanceof UIColor && !isEnabled()) {
c=((UIColor)c).getDisabledColor();
}
return c;
}
@Override
public AffineTransform getTransformEx() {
return transform;
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform tx = g2.getTransform();
if (transform != null) {
g2.transform(transform);
}
graphics = SwingGraphics.fromGraphics(g2, this, graphics);
super.paint(g2);
if (tx != null) {
g2.setTransform(tx);
}
graphics.clear();
}
@Override
protected void paintBorder(Graphics g) {
if (componentPainter == null) {
super.paintBorder(g);
}
}
@Override
protected void paintChildren(Graphics g) {
super.paintChildren(graphics.getGraphics());
iPlatformComponentPainter cp = getComponentPainter();
if (cp != null) {
float height = getHeight();
float width = getWidth();
cp.paint(graphics, 0, 0, width, height, iPainter.HORIZONTAL, true);
}
}
@Override
protected void paintComponent(Graphics g) {
graphics = SwingGraphics.fromGraphics(g, this, graphics);
iPlatformComponentPainter cp = getComponentPainter();
if (cp != null) {
float height = getHeight();
float width = getWidth();
cp.paint(graphics, 0, 0, width, height, iPainter.HORIZONTAL, false);
}
super.paintComponent(g);
}
@Override
public void setComponentPainter(iPlatformComponentPainter cp) {
componentPainter = cp;
}
@Override
public iPlatformComponentPainter getComponentPainter() {
return componentPainter;
}
@Override
public void getMinimumSize(UIDimension size, int maxWidth) {
Dimension d = getMinimumSize();
size.width = d.width;
size.height = d.height;
}
@Override
public void setText(String text) {
if (text == null) {
text = "";
}
originalText = text;
int len = text.length();
if (wordWrap && (len > 0) &&!text.startsWith("<html>")) {
CharArray ca = new CharArray(text.length() + 20);
ca.append("<html>");
XMLUtils.escape(text.toCharArray(), 0, len, true, ca);
ca.append("</html>");
text = ca.toString();
}
super.setText(text);
}
public void setWordWrap(boolean wordWrap) {
this.wordWrap = wordWrap;
}
@Override
public String getText() {
return originalText;
}
public boolean isWordWrap() {
return wordWrap;
}
protected void initialize() {
setOpaque(false);
setFont(FontUtils.getDefaultFont());
setForeground(ColorUtils.getForeground());
if (selectedIcon_ == null) {
iPlatformAppContext app = Platform.getAppContext();
if (ColorUtils.getForeground().isDarkColor()) {
selectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.light");
deselectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.light");
selectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.pressed.light");
deselectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.pressed.light");
selectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.disabled.light");
deselectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.disabled.light");
} else {
selectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.dark");
deselectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.dark");
selectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.pressed.dark");
deselectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.pressed.dark");
selectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.disabled.dark");
deselectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.disabled.dark");
}
}
setSelectedIcon(selectedIcon_);
setDisabledIcon(deselectedIconDisabled_);
setPressedIcon(deselectedPressedIcon_);
setIcon(deselectedIcon_);
setDisabledSelectedIcon(selectedIconDisabled_);
}
@Override
public Icon getDisabledIcon() {
Icon icon = super.getDisabledIcon();
if (icon == null) {
icon = getIcon();
if (icon instanceof iPlatformIcon) {
return ((iPlatformIcon) icon).getDisabledVersion();
}
}
return icon;
}
public Icon getDisabledSelectedIcon() {
Icon icon = super.getDisabledSelectedIcon();
if (icon == null) {
icon = getSelectedIcon();
if (icon == null) {
icon = getIcon();
}
if (icon instanceof iPlatformIcon) {
return ((iPlatformIcon) icon).getDisabledVersion();
}
}
return icon;
}
private static UIDimension size = new UIDimension();
@Override
public Dimension getPreferredSize() {
if (size == null) {
size = new UIDimension();
}
Number num = (Number) getClientProperty(iConstants.RARE_WIDTH_FIXED_VALUE);
int maxWidth = 0;
if ((num != null) && (num.intValue() > 0)) {
maxWidth = num.intValue();
}
getPreferredSize(size, maxWidth);
return new Dimension(size.intWidth(), size.intHeight());
}
@Override
public void getPreferredSize(UIDimension size, int maxWidth) {
Dimension d = super.getPreferredSize();
size.width = d.width;
size.height = d.height;
if (isFontSet() && getFont().isItalic()) {
if (getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) == null) {
size.width += 4;
}
}
}
}
| appnativa/rare | source/rare/swingx/com/appnativa/rare/platform/swing/ui/view/RadioButtonView.java | Java | gpl-3.0 | 8,918 |
package de.roskenet.simplecms.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import de.roskenet.simplecms.entity.Attribute;
public interface AttributeRepository extends PagingAndSortingRepository<Attribute, Integer> {
}
| roskenet/simple-cms | src/main/java/de/roskenet/simplecms/repository/AttributeRepository.java | Java | gpl-3.0 | 260 |
/**
*
* Copyright (C) 2004-2008 FhG Fokus
*
* This file is part of the FhG Fokus UPnP stack - an open source UPnP implementation
* with some additional features
*
* You can redistribute the FhG Fokus UPnP stack and/or modify it
* under the terms of the GNU General Public License Version 3 as published by
* the Free Software Foundation.
*
* For a license to use the FhG Fokus UPnP stack software under conditions
* other than those described here, or to purchase support for this
* software, please contact Fraunhofer FOKUS by e-mail at the following
* addresses:
* upnpstack@fokus.fraunhofer.de
*
* The FhG Fokus UPnP stack 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/>
* or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package de.fraunhofer.fokus.upnp.core;
import java.util.Hashtable;
import java.util.Vector;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import de.fraunhofer.fokus.upnp.util.SAXTemplateHandler;
/**
* This class is used to parse UPnPDoc messages.
*
* @author Alexander Koenig
*
*
*/
public class UPnPDocParser extends SAXTemplateHandler
{
/** Doc entries for the current service type */
private Vector currentDocEntryList = new Vector();
private boolean isAction = false;
private boolean isStateVariable = false;
private String currentServiceType = null;
private String currentArgumentName = null;
private String currentArgumentDescription = null;
private UPnPDocEntry currentDocEntry = null;
/** Hashtable containing the UPnP doc entry list for one service type */
private Hashtable docEntryFromServiceTypeTable = new Hashtable();
/*
* (non-Javadoc)
*
* @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processStartElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void processStartElement(String uri, String name, String name2, Attributes atts) throws SAXException
{
if (getTagCount() == 2)
{
for (int i = 0; i < atts.getLength(); i++)
{
if (atts.getQName(i).equalsIgnoreCase("serviceType"))
{
currentServiceType = atts.getValue(i);
currentDocEntryList = new Vector();
}
}
}
if (getTagCount() == 3 && currentServiceType != null)
{
isAction = getCurrentTag().equalsIgnoreCase("actionList");
isStateVariable = getCurrentTag().equalsIgnoreCase("serviceStateTable");
}
if (getTagCount() == 4 && currentServiceType != null)
{
currentDocEntry = new UPnPDocEntry(currentServiceType);
}
}
/*
* (non-Javadoc)
*
* @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processEndElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
public void processEndElement(String uri, String localName, String name) throws SAXException
{
if (getTagCount() == 6 && isAction && currentDocEntry != null && currentArgumentName != null &&
currentArgumentDescription != null)
{
currentDocEntry.addArgumentDescription(currentArgumentName, currentArgumentDescription);
currentArgumentName = null;
currentArgumentDescription = null;
}
if (getTagCount() == 4)
{
if (currentDocEntry != null && currentDocEntry.getActionName() != null && isAction)
{
// TemplateService.printMessage(" Add doc entry for action " +
// currentDocEntry.getActionName());
currentDocEntryList.add(currentDocEntry);
}
if (currentDocEntry != null && currentDocEntry.getStateVariableName() != null && isStateVariable)
{
// TemplateService.printMessage(" Add doc entry for state variable " +
// currentDocEntry.getStateVariableName());
currentDocEntryList.add(currentDocEntry);
}
currentDocEntry = null;
}
if (getTagCount() == 3)
{
isAction = false;
isStateVariable = false;
}
if (getTagCount() == 2)
{
// store list with doc entries for one service type
docEntryFromServiceTypeTable.put(currentServiceType, currentDocEntryList);
currentServiceType = null;
currentDocEntryList = null;
}
}
/*
* (non-Javadoc)
*
* @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processContentElement(java.lang.String)
*/
public void processContentElement(String content) throws SAXException
{
if (getTagCount() == 5 && currentDocEntry != null)
{
if (getCurrentTag().equalsIgnoreCase("name") && isAction)
{
currentDocEntry.setActionName(content.trim());
}
if (getCurrentTag().equalsIgnoreCase("name") && isStateVariable)
{
currentDocEntry.setStateVariableName(content.trim());
}
if (getCurrentTag().equalsIgnoreCase("description"))
{
currentDocEntry.setDescription(content.trim());
}
}
if (getTagCount() == 7 && currentDocEntry != null)
{
if (getCurrentTag().equalsIgnoreCase("name"))
{
currentArgumentName = content.trim();
}
if (getCurrentTag().equalsIgnoreCase("description"))
{
currentArgumentDescription = content.trim();
}
}
}
/**
* Retrieves the upnpDocEntryTable.
*
* @return The upnpDocEntryTable
*/
public Hashtable getDocEntryFormServiceTypeTable()
{
return docEntryFromServiceTypeTable;
}
}
| fraunhoferfokus/fokus-upnp | upnp-core/src/main/java/de/fraunhofer/fokus/upnp/core/UPnPDocParser.java | Java | gpl-3.0 | 5,855 |
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stt.data.jpa.service;
import com.stt.data.jpa.domain.City;
import com.stt.data.jpa.domain.Hotel;
import com.stt.data.jpa.domain.HotelSummary;
import com.stt.data.jpa.domain.RatingCount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import java.util.List;
interface HotelRepository extends Repository<Hotel, Long> {
Hotel findByCityAndName(City city, String name);
@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
+ "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")
Page<HotelSummary> findByCity(City city, Pageable pageable);
@Query("select r.rating as rating, count(r) as count "
+ "from Review r where r.hotel = ?1 group by r.rating order by r.rating DESC")
List<RatingCount> findRatingCounts(Hotel hotel);
}
| shitongtong/libraryManage | spring-boot-demo/data-jpa/src/main/java/com/stt/data/jpa/service/HotelRepository.java | Java | gpl-3.0 | 1,574 |
package net.joaopms.PvPUtilities.helper;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
public class ConfigHelper {
private static Configuration config;
public static void init(File file) {
config = new Configuration(file, true);
config.load();
initConfig();
config.save();
}
public static Configuration getConfig() {
return config;
}
private static void initConfig() {
config.get("overcastStatistics", "showOvercastLogo", true);
config.get("overcastStatistics", "showKills", true);
config.get("overcastStatistics", "showDeaths", true);
config.get("overcastStatistics", "showFriends", false);
config.get("overcastStatistics", "showKD", true);
config.get("overcastStatistics", "showKK", false);
config.get("overcastStatistics", "showServerJoins", false);
config.get("overcastStatistics", "showDaysPlayed", false);
config.get("overcastStatistics", "showRaindrops", false);
config.get("overcastStatistics", "overlayOpacity", 0.5F);
}
} | joaopms/PvPUtilities | src/main/java/net/joaopms/PvPUtilities/helper/ConfigHelper.java | Java | gpl-3.0 | 1,117 |
package com.bruce.android.knowledge.custom_view.scanAnimation;
/**
* @author zhenghao.qi
* @version 1.0
* @time 2015年11月09日14:45:32
*/
public class ScanAnimaitonStrategy implements IAnimationStrategy {
/**
* 起始X坐标
*/
private int startX;
/**
* 起始Y坐标
*/
private int startY;
/**
* 起始点到终点的Y轴位移。
*/
private int shift;
/**
* X Y坐标。
*/
private double currentX, currentY;
/**
* 动画开始时间。
*/
private long startTime;
/**
* 循环时间
*/
private long cyclePeriod;
/**
* 动画正在进行时值为true,反之为false。
*/
private boolean doing;
/**
* 进行动画展示的view
*/
private AnimationSurfaceView animationSurfaceView;
public ScanAnimaitonStrategy(AnimationSurfaceView animationSurfaceView, int shift, long cyclePeriod) {
this.animationSurfaceView = animationSurfaceView;
this.shift = shift;
this.cyclePeriod = cyclePeriod;
initParams();
}
public void start() {
startTime = System.currentTimeMillis();
doing = true;
}
/**
* 设置起始位置坐标
*/
private void initParams() {
int[] position = new int[2];
animationSurfaceView.getLocationInWindow(position);
this.startX = position[0];
this.startY = position[1];
}
/**
* 根据当前时间计算小球的X/Y坐标。
*/
public void compute() {
long intervalTime = (System.currentTimeMillis() - startTime) % cyclePeriod;
double angle = Math.toRadians(360 * 1.0d * intervalTime / cyclePeriod);
int y = (int) (shift / 2 * Math.cos(angle));
y = Math.abs(y - shift/2);
currentY = startY + y;
doing = true;
}
@Override
public boolean doing() {
return doing;
}
public double getX() {
return currentX;
}
public double getY() {
return currentY;
}
public void cancel() {
doing = false;
}
} | qizhenghao/Hello_Android | app/src/main/java/com/bruce/android/knowledge/custom_view/scanAnimation/ScanAnimaitonStrategy.java | Java | gpl-3.0 | 2,115 |
package de.jdellert.iwsa.sequence;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Symbol table for mapping IPA segments to integers for efficient internal
* representation. The first two integers are always used for special symbols: 0
* ~ #: the word boundary symbol 1 ~ -: the gap symbol
*
*/
public class PhoneticSymbolTable implements Serializable {
private static final long serialVersionUID = -8825447220839372572L;
private String[] idToSymbol;
private Map<String, Integer> symbolToID;
public PhoneticSymbolTable(Collection<String> symbols) {
this.idToSymbol = new String[symbols.size() + 2];
this.symbolToID = new TreeMap<String, Integer>();
idToSymbol[0] = "#";
idToSymbol[1] = "-";
symbolToID.put("#", 0);
symbolToID.put("-", 1);
int nextID = 2;
for (String symbol : symbols) {
idToSymbol[nextID] = symbol;
symbolToID.put(symbol, nextID);
nextID++;
}
}
public Integer toInt(String symbol) {
return symbolToID.get(symbol);
}
public String toSymbol(int id) {
return idToSymbol[id];
}
public int[] encode(String[] segments) {
int[] segmentIDs = new int[segments.length];
for (int idx = 0; idx < segments.length; idx++) {
segmentIDs[idx] = symbolToID.get(segments[idx]);
}
return segmentIDs;
}
public String[] decode(int[] segmentIDs) {
String[] segments = new String[segmentIDs.length];
for (int idx = 0; idx < segmentIDs.length; idx++) {
segments[idx] = idToSymbol[segmentIDs[idx]];
}
return segments;
}
public Set<String> getDefinedSymbols()
{
return new TreeSet<String>(symbolToID.keySet());
}
public int getSize() {
return idToSymbol.length;
}
public String toSymbolPair(int symbolPairID) {
return "(" + toSymbol(symbolPairID / idToSymbol.length) + "," + toSymbol(symbolPairID % idToSymbol.length) + ")";
}
public String toString()
{
StringBuilder line1 = new StringBuilder();
StringBuilder line2 = new StringBuilder();
for (int i = 0; i < idToSymbol.length; i++)
{
line1.append(i + "\t");
line2.append(idToSymbol[i] + "\t");
}
return line1 + "\n" + line2;
}
}
| jdellert/iwsa | src/de/jdellert/iwsa/sequence/PhoneticSymbolTable.java | Java | gpl-3.0 | 2,258 |
/*
* GNU LESSER GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*
* You can view LICENCE file for details.
*
* @author The Dragonet Team
*/
package org.dragonet.proxy.network.translator;
import java.util.Iterator;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.spacehq.mc.protocol.data.message.Message;
public final class MessageTranslator {
public static String translate(Message message) {
String ret = message.getFullText();
/*
* It is a JSON message?
*/
try {
/*
* Do not ask me why, but json strings has colors.
* Changing this allows colors in plain texts! yay!
*/
JSONObject jObject = null;
if (message.getFullText().startsWith("{") && message.getFullText().endsWith("}")) {
jObject = new JSONObject(message.getFullText());
} else {
jObject = new JSONObject(message.toJsonString());
}
/*
* Let's iterate!
*/
ret = handleKeyObject(jObject);
} catch (JSONException e) {
/*
* If any exceptions happens, then:
* * The JSON message is buggy or
* * It isn't a JSON message
*
* So, if any exceptions happens, we send the original message
*/
}
return ret;
}
public static String handleKeyObject(JSONObject jObject) throws JSONException {
String chatMessage = "";
Iterator<String> iter = jObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
if (key.equals("color")) {
String color = jObject.getString(key);
if (color.equals("light_purple")) {
chatMessage = chatMessage + "§d";
}
if (color.equals("blue")) {
chatMessage = chatMessage + "§9";
}
if (color.equals("aqua")) {
chatMessage = chatMessage + "§b";
}
if (color.equals("gold")) {
chatMessage = chatMessage + "§6";
}
if (color.equals("green")) {
chatMessage = chatMessage + "§a";
}
if (color.equals("white")) {
chatMessage = chatMessage + "§f";
}
if (color.equals("yellow")) {
chatMessage = chatMessage + "§e";
}
if (color.equals("gray")) {
chatMessage = chatMessage + "§7";
}
if (color.equals("red")) {
chatMessage = chatMessage + "§c";
}
if (color.equals("black")) {
chatMessage = chatMessage + "§0";
}
if (color.equals("dark_green")) {
chatMessage = chatMessage + "§2";
}
if (color.equals("dark_gray")) {
chatMessage = chatMessage + "§8";
}
if (color.equals("dark_red")) {
chatMessage = chatMessage + "§4";
}
if (color.equals("dark_blue")) {
chatMessage = chatMessage + "§1";
}
if (color.equals("dark_aqua")) {
chatMessage = chatMessage + "§3";
}
if (color.equals("dark_purple")) {
chatMessage = chatMessage + "§5";
}
}
if (key.equals("bold")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§l";
}
}
if (key.equals("italic")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§o";
}
}
if (key.equals("underlined")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§n";
}
}
if (key.equals("strikethrough")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§m";
}
}
if (key.equals("obfuscated")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§k";
}
}
if (key.equals("text")) {
/*
* We only need the text message from the JSON.
*/
String jsonMessage = jObject.getString(key);
chatMessage = chatMessage + jsonMessage;
continue;
}
if (jObject.get(key) instanceof JSONArray) {
chatMessage += handleKeyArray(jObject.getJSONArray(key));
}
if (jObject.get(key) instanceof JSONObject) {
chatMessage += handleKeyObject(jObject.getJSONObject(key));
}
} catch (JSONException e) {
}
}
return chatMessage;
}
public static String handleKeyArray(JSONArray jObject) throws JSONException {
String chatMessage = "";
JSONObject jsonObject = jObject.toJSONObject(jObject);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
/*
* We only need the text message from the JSON.
*/
if (key.equals("text")) {
String jsonMessage = jsonObject.getString(key);
chatMessage = chatMessage + jsonMessage;
continue;
}
if (jsonObject.get(key) instanceof JSONArray) {
handleKeyArray(jsonObject.getJSONArray(key));
}
if (jsonObject.get(key) instanceof JSONObject) {
handleKeyObject(jsonObject.getJSONObject(key));
}
} catch (JSONException e) {
}
}
return chatMessage;
}
}
| WeaveMN/DragonProxy | src/main/java/org/dragonet/proxy/network/translator/MessageTranslator.java | Java | gpl-3.0 | 7,266 |
/*
* LBFGS.java
*
* Copyright (C) 2016 Pavel Prokhorov (pavelvpster@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 org.interactiverobotics.ml.optimization;
import static org.interactiverobotics.ml.optimization.OptimizationResult.Status.*;
import org.apache.log4j.Logger;
import org.interactiverobotics.math.Vector;
import java.util.Objects;
/**
* Limited-memory BFGS.
*
* https://en.wikipedia.org/wiki/Limited-memory_BFGS
*
* Liu, D. C.; Nocedal, J. (1989). "On the Limited Memory Method for Large Scale Optimization".
* Mathematical Programming B. 45 (3): 503–528. doi:10.1007/BF01589116.
*
*/
public final class LBFGS extends AbstractOptimizer implements Optimizer {
private static final Logger LOG = Logger.getLogger(LBFGS.class);
public LBFGS(final OptimizableFunction function) {
this.function = Objects.requireNonNull(function);
}
private final OptimizableFunction function;
/**
* Maximum number of iterations.
*/
private int maxIterations = 100;
/**
* The number of corrections to approximate the inverse Hessian matrix.
*/
private int m = 6;
/**
* Epsilon for convergence test.
* Controls the accuracy of with which the solution is to be found.
*/
private double epsilon = 1.0E-5;
/**
* Distance (in iterations) to calculate the rate of decrease of the function.
* Used in delta convergence test.
*/
private int past = 3;
/**
* Minimum rate of decrease of the function.
* Used in delta convergence test.
*/
private double delta = 1.0E-5;
/**
* Maximum number of line search iterations.
*/
private int maxLineSearchIterations = 100;
/**
* Continue optimization if line search returns {@code MAX_ITERATION_REACHED}.
*/
private boolean continueOnMaxLineSearchIterations = false;
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public double getEpsilon() {
return epsilon;
}
public void setEpsilon(double epsilon) {
this.epsilon = epsilon;
}
public int getPast() {
return past;
}
public void setPast(int past) {
this.past = past;
}
public double getDelta() {
return delta;
}
public void setDelta(double delta) {
this.delta = delta;
}
public int getMaxLineSearchIterations() {
return maxLineSearchIterations;
}
public void setMaxLineSearchIterations(int maxLineSearchIterations) {
this.maxLineSearchIterations = maxLineSearchIterations;
}
public boolean isContinueOnMaxLineSearchIterations() {
return continueOnMaxLineSearchIterations;
}
public void setContinueOnMaxLineSearchIterations(boolean continueOnMaxLineSearchIterations) {
this.continueOnMaxLineSearchIterations = continueOnMaxLineSearchIterations;
}
@Override
public OptimizationResult optimize() {
LOG.debug("Limited-memory BFGS optimize...");
final BacktrackingLineSearch lineSearch = new BacktrackingLineSearch(function);
lineSearch.setMaxIterations(maxLineSearchIterations);
final State[] states = new State[m];
for (int i = 0; i < m; i ++) {
states[i] = new State();
}
int currentStateIndex = 0;
final double[] pastValues;
if (past > 0) {
pastValues = new double[past];
pastValues[0] = function.getValue();
} else {
pastValues = null;
}
Vector parameters = function.getParameters();
Vector gradient = function.getValueGradient();
final double initialGradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0);
LOG.debug("Initial gradient norm = " + initialGradientNorm);
if (initialGradientNorm <= epsilon) {
LOG.debug("Already minimized");
return new OptimizationResult(ALREADY_MINIMIZED, parameters, function.getValue(), 0);
}
Vector direction = gradient.copy().neg();
double step = Vector.dotProduct(direction, direction);
Vector prevParameters, prevGradient;
OptimizationResult.Status status = MAX_ITERATION_REACHED;
int iteration;
for (iteration = 1; iteration <= maxIterations; iteration ++) {
LOG.debug("Iteration " + iteration);
// save previous Parameters and Gradient
prevParameters = parameters.copy();
prevGradient = gradient.copy();
// search for optimal Step
LOG.debug("Direction: " + direction + " Step = " + step);
lineSearch.setDirection(direction);
lineSearch.setInitialStep(step);
final OptimizationResult lineSearchResult = lineSearch.optimize();
if (!lineSearchResult.hasConverged()) {
LOG.error("Line search not converged: " + lineSearchResult.getStatus());
final boolean continueOptimization =
(lineSearchResult.getStatus() == MAX_ITERATION_REACHED) && continueOnMaxLineSearchIterations;
if (!continueOptimization) {
// step back
function.setParameters(prevParameters);
status = lineSearchResult.getStatus();
break;
}
}
parameters = function.getParameters();
gradient = function.getValueGradient();
final double value = function.getValue();
final boolean stop = fireOptimizerStep(parameters, value, direction, iteration);
if (stop) {
LOG.debug("Stop");
status = STOP;
break;
}
// test for convergence
final double gradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0);
LOG.debug("Gradient norm = " + gradientNorm);
if (gradientNorm <= epsilon) {
LOG.debug("Success");
status = SUCCESS;
break;
}
// delta convergence test
if (past > 0) {
if (iteration > past) {
// relative improvement from the past
final double rate = (pastValues[iteration % past] - value) / value;
if (rate < delta) {
status = STOP;
break;
}
}
pastValues[iteration % past] = value;
}
// update S and Y
final State currentState = states[currentStateIndex];
currentState.s = parameters.copy().sub(prevParameters);
currentState.y = gradient.copy().sub(prevGradient);
final double ys = Vector.dotProduct(currentState.y, currentState.s);
final double yy = Vector.dotProduct(currentState.y, currentState.y);
currentState.ys = ys;
currentStateIndex = (currentStateIndex + 1) % m;
// update Direction
direction = gradient.copy();
int availableStates = Math.min(iteration, m);
LOG.debug("Available states = " + availableStates);
int j = currentStateIndex;
for (int i = 0; i < availableStates; i ++) {
j = (j + m - 1) % m;
final State t = states[j];
t.alpha = Vector.dotProduct(t.s, direction) / t.ys;
direction.sub(t.y.copy().scale(t.alpha));
}
direction.scale(ys / yy);
for (int i = 0; i < availableStates; i ++) {
final State t = states[j];
final double beta = Vector.dotProduct(t.y, direction) / t.ys;
direction.add(t.s.copy().scale(t.alpha - beta));
j = (j + 1) % m;
}
direction.neg();
step = 1.0;
}
final Vector finalParameters = function.getParameters();
final double finalValue = function.getValue();
LOG.debug("Status = " + status + " Final Value = " + finalValue + " Parameters: " + finalParameters
+ " Iteration = " + iteration);
return new OptimizationResult(status, finalParameters, finalValue, iteration);
}
private static class State {
public double alpha;
public Vector s;
public Vector y;
public double ys;
}
}
| pavelvpster/Math | src/main/java/org/interactiverobotics/ml/optimization/LBFGS.java | Java | gpl-3.0 | 9,413 |
package cn.bjsxt.oop.staticInitBlock;
public class Parent001 /*extends Object*/ {
static int aa;
static {
System.out.println(" 静态初始化Parent001");
aa=200;
}
}
| yangweijun213/Java | J2SE300/28_51OO/src/cn/bjsxt/oop/staticInitBlock/Parent001.java | Java | gpl-3.0 | 184 |
/*
* Copyright (C) 2018 Johan Dykstrom
*
* 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 se.dykstrom.jcc.common.ast;
import java.util.Objects;
/**
* Abstract base class for different types of jump statements, such as GOTO or GOSUB.
*
* @author Johan Dykstrom
*/
public abstract class AbstractJumpStatement extends AbstractNode implements Statement {
private final String jumpLabel;
protected AbstractJumpStatement(int line, int column, String jumpLabel) {
super(line, column);
this.jumpLabel = jumpLabel;
}
/**
* Returns the label to jump to.
*/
public String getJumpLabel() {
return jumpLabel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractJumpStatement that = (AbstractJumpStatement) o;
return Objects.equals(jumpLabel, that.jumpLabel);
}
@Override
public int hashCode() {
return Objects.hash(jumpLabel);
}
}
| dykstrom/jcc | src/main/java/se/dykstrom/jcc/common/ast/AbstractJumpStatement.java | Java | gpl-3.0 | 1,652 |
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of Contao.
*
* Contao is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* Contao 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 Contao. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.contao.manager;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.entity.Player;
import de.minestar.contao.core.Settings;
import de.minestar.contao.data.ContaoGroup;
import de.minestar.contao.data.User;
import de.minestar.core.MinestarCore;
import de.minestar.core.units.MinestarPlayer;
public class PlayerManager {
private Map<String, User> onlineUserMap = new HashMap<String, User>();
private Map<ContaoGroup, TreeSet<User>> groupMap = new HashMap<ContaoGroup, TreeSet<User>>();
public PlayerManager() {
for (ContaoGroup cGroup : ContaoGroup.values()) {
groupMap.put(cGroup, new TreeSet<User>());
}
}
public void addUser(User user) {
onlineUserMap.put(user.getMinecraftNickname().toLowerCase(), user);
groupMap.get(user.getGroup()).add(user);
}
public void removeUser(String userName) {
User user = onlineUserMap.remove(userName.toLowerCase());
groupMap.get(user.getGroup()).remove(user);
}
public User getUser(Player player) {
return getUser(player.getName());
}
public User getUser(String userName) {
return onlineUserMap.get(userName.toLowerCase());
}
public String getGroupAsString(ContaoGroup contaoGroup) {
Set<User> groupMember = groupMap.get(contaoGroup);
if (groupMember.isEmpty())
return null;
StringBuilder sBuilder = new StringBuilder();
// BUILD HEAD
sBuilder.append(Settings.getColor(contaoGroup));
sBuilder.append(contaoGroup.getDisplayName());
sBuilder.append('(');
sBuilder.append(getGroupSize(contaoGroup));
sBuilder.append(") : ");
// ADD USER
for (User user : groupMember) {
sBuilder.append(user.getMinecraftNickname());
sBuilder.append(", ");
}
// DELETE THE LAST COMMATA
sBuilder.delete(0, sBuilder.length() - 2);
return sBuilder.toString();
}
public int getGroupSize(ContaoGroup contaoGroup) {
return groupMap.get(contaoGroup).size();
}
public void changeGroup(User user, ContaoGroup newGroup) {
groupMap.get(user.getGroup()).remove(user);
groupMap.get(newGroup).add(user);
setGroup(user, newGroup);
}
public void setGroup(User user, ContaoGroup newGroup) {
MinestarPlayer mPlayer = MinestarCore.getPlayer(user.getMinecraftNickname());
if (mPlayer != null) {
mPlayer.setGroup(newGroup.getMinestarGroup());
}
}
public boolean canBeFree(User probeUser) {
// TODO: Implement requirements
return false;
}
}
| Minestar/Contao | src/main/java/de/minestar/contao/manager/PlayerManager.java | Java | gpl-3.0 | 3,520 |
package org.grovecity.drizzlesms.jobs.requirements;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.grovecity.drizzlesms.service.KeyCachingService;
import org.whispersystems.jobqueue.requirements.RequirementListener;
import org.whispersystems.jobqueue.requirements.RequirementProvider;
public class MasterSecretRequirementProvider implements RequirementProvider {
private final BroadcastReceiver newKeyReceiver;
private RequirementListener listener;
public MasterSecretRequirementProvider(Context context) {
this.newKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (listener != null) {
listener.onRequirementStatusChanged();
}
}
};
IntentFilter filter = new IntentFilter(KeyCachingService.NEW_KEY_EVENT);
context.registerReceiver(newKeyReceiver, filter, KeyCachingService.KEY_PERMISSION, null);
}
@Override
public void setListener(RequirementListener listener) {
this.listener = listener;
}
}
| DrizzleSuite/DrizzleSMS | src/org/grovecity/drizzlesms/jobs/requirements/MasterSecretRequirementProvider.java | Java | gpl-3.0 | 1,144 |
/*
* Copyright (C) 2017 Josua Frank
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package dfmaster.general;
import dfmaster.json.JSONValue;
import dfmaster.xml.XMLDocument;
import dfmaster.xml.XMLElement;
/**
* This is the abstract type for all data that can be created or parsed. This
* could be as example a {@link JSONValue}, a {@link XMLDocument} or a
* {@link XMLElement}
*
* @author Josua Frank
*/
public class AData {
}
| Sharknoon/dfMASTER | dfMASTER/src/main/java/dfmaster/general/AData.java | Java | gpl-3.0 | 1,113 |
package io.valhala.javamon.pokemon.skeleton;
import io.valhala.javamon.pokemon.Pokemon;
import io.valhala.javamon.pokemon.type.Type;
public abstract class Paras extends Pokemon {
public Paras() {
super("Paras", 35, 70, 55, 25, 55, true, 46,Type.BUG,Type.GRASS);
// TODO Auto-generated constructor stub
}
}
| mirgantrophy/Pokemon | src/io/valhala/javamon/pokemon/skeleton/Paras.java | Java | gpl-3.0 | 316 |
package de.unikiel.inf.comsys.neo4j.inference.sail;
/*
* #%L
* neo4j-sparql-extension
* %%
* Copyright (C) 2014 Niclas Hoyer
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import de.unikiel.inf.comsys.neo4j.inference.QueryRewriter;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.parser.ParsedBooleanQuery;
import org.openrdf.repository.sail.SailBooleanQuery;
import org.openrdf.repository.sail.SailRepositoryConnection;
/**
* A subclass of {@link SailBooleanQuery} with a public constructor to
* pass in a boolean query containing a tuple expression.
*
* The original constructor of {@link SailBooleanQuery} is protected, thus
* it is not possible to create a new boolean query from a parsed query
* that is used to create a query from a {@link TupleExpr}.
*
* @see QueryRewriter
*/
public class SailBooleanExprQuery extends SailBooleanQuery {
public SailBooleanExprQuery(ParsedBooleanQuery booleanQuery, SailRepositoryConnection sailConnection) {
super(booleanQuery, sailConnection);
}
}
| niclashoyer/neo4j-sparql-extension | src/main/java/de/unikiel/inf/comsys/neo4j/inference/sail/SailBooleanExprQuery.java | Java | gpl-3.0 | 1,670 |
package redsgreens.Pigasus;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
/**
* Handle events for all Player related events
* @author redsgreens
*/
public class PigasusPlayerListener implements Listener {
private final Pigasus plugin;
public PigasusPlayerListener(Pigasus instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event)
// catch player+entity events, looking for wand usage on an entity
{
Entity entity = event.getRightClicked();
// return if something not allowed was clicked
if(plugin.Config.getHoveringChance(entity) == -1) return;
Player player = event.getPlayer();
// return if the click was with something other than the wand
if(player.getItemInHand().getType() != plugin.Config.WandItem) return;
// check for permission
if(!plugin.isAuthorized(player, "wand") && !plugin.isAuthorized(player, "wand." + PigasusFlyingEntity.getType(entity).name().toLowerCase()))
{
if(plugin.Config.ShowErrorsInClient)
player.sendMessage("§cErr: " + plugin.Name + ": you don't have permission.");
return;
}
// checks passed, make this pig fly!
plugin.Manager.addEntity(entity);
}
}
| redsgreens/Pigasus | src/redsgreens/Pigasus/PigasusPlayerListener.java | Java | gpl-3.0 | 1,558 |
package fi.metatavu.edelphi.jsons.queries;
import java.util.Locale;
import fi.metatavu.edelphi.smvcj.SmvcRuntimeException;
import fi.metatavu.edelphi.smvcj.controllers.JSONRequestContext;
import fi.metatavu.edelphi.DelfoiActionName;
import fi.metatavu.edelphi.EdelfoiStatusCode;
import fi.metatavu.edelphi.dao.querydata.QueryReplyDAO;
import fi.metatavu.edelphi.dao.querylayout.QueryPageDAO;
import fi.metatavu.edelphi.dao.users.UserDAO;
import fi.metatavu.edelphi.domainmodel.actions.DelfoiActionScope;
import fi.metatavu.edelphi.domainmodel.querydata.QueryReply;
import fi.metatavu.edelphi.domainmodel.querylayout.QueryPage;
import fi.metatavu.edelphi.domainmodel.resources.Query;
import fi.metatavu.edelphi.domainmodel.resources.QueryState;
import fi.metatavu.edelphi.domainmodel.users.User;
import fi.metatavu.edelphi.i18n.Messages;
import fi.metatavu.edelphi.jsons.JSONController;
import fi.metatavu.edelphi.query.QueryPageHandler;
import fi.metatavu.edelphi.query.QueryPageHandlerFactory;
import fi.metatavu.edelphi.utils.ActionUtils;
import fi.metatavu.edelphi.utils.QueryDataUtils;
public class SaveQueryAnswersJSONRequestController extends JSONController {
public SaveQueryAnswersJSONRequestController() {
super();
setAccessAction(DelfoiActionName.ACCESS_PANEL, DelfoiActionScope.PANEL);
}
@Override
public void process(JSONRequestContext jsonRequestContext) {
UserDAO userDAO = new UserDAO();
QueryPageDAO queryPageDAO = new QueryPageDAO();
QueryReplyDAO queryReplyDAO = new QueryReplyDAO();
Long queryPageId = jsonRequestContext.getLong("queryPageId");
QueryPage queryPage = queryPageDAO.findById(queryPageId);
Query query = queryPage.getQuerySection().getQuery();
Messages messages = Messages.getInstance();
Locale locale = jsonRequestContext.getRequest().getLocale();
if (query.getState() == QueryState.CLOSED)
throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_CLOSED, messages.getText(locale, "exception.1027.cannotSaveReplyQueryClosed"));
if (query.getState() == QueryState.EDIT) {
if (!ActionUtils.hasPanelAccess(jsonRequestContext, DelfoiActionName.MANAGE_DELFOI_MATERIALS.toString()))
throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_IN_EDIT_STATE, messages.getText(locale, "exception.1028.cannotSaveReplyQueryInEditState"));
}
else {
User loggedUser = null;
if (jsonRequestContext.isLoggedIn())
loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId());
QueryReply queryReply = QueryDataUtils.findQueryReply(jsonRequestContext, loggedUser, query);
if (queryReply == null) {
throw new SmvcRuntimeException(EdelfoiStatusCode.UNKNOWN_REPLICANT, messages.getText(locale, "exception.1026.unknownReplicant"));
}
queryReplyDAO.updateLastModified(queryReply, loggedUser);
QueryDataUtils.storeQueryReplyId(jsonRequestContext.getRequest().getSession(), queryReply);
QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType());
queryPageHandler.saveAnswers(jsonRequestContext, queryPage, queryReply);
}
}
}
| Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/jsons/queries/SaveQueryAnswersJSONRequestController.java | Java | gpl-3.0 | 3,237 |
package org.craftercms.studio.api.dto;
public class UserTest {
public void testGetUserId() throws Exception {
}
public void testSetUserId() throws Exception {
}
public void testGetPassword() throws Exception {
}
public void testSetPassword() throws Exception {
}
}
| craftercms/studio3 | api/src/test/java/org/craftercms/studio/api/dto/UserTest.java | Java | gpl-3.0 | 305 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.