repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
surli/spinefm | spinefm-eclipseplugins-root/spinefm-core/src/fr/unice/spinefm/MSPLModel/impl/DEAssociationEndImplDelegate.java | 1094 | package fr.unice.spinefm.MSPLModel.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import fr.unice.spinefm.roassaltracer.RoassalTracer;
public class DEAssociationEndImplDelegate extends DEAssociationEndImpl {
private static int counter = 0;
public DEAssociationEndImplDelegate() {
super();
if (this.getId() == null || this.getId().equals("")) {
this.setId("DEAEnd_"+(counter++));
}
}
public void roassalTrace(Map<String, List<String>> buffer) {
if (this.getId() == null || this.getId().equals("")) {
this.setId("DEAEnd_"+(counter++));
}
if (!buffer.containsKey(RoassalTracer.ROASSAL_DEAEND))
buffer.put(RoassalTracer.ROASSAL_DEAEND, new ArrayList<String>());
RoassalTracer.callRoassalTracer(this.getLinkMultiplicity(), buffer);
String trace = RoassalTracer.ROASSAL_DEAEND+" id=\""+this.id+"\" apply_on=["+this.apply_on.getId()+"] linkMultiplicity=["+this.linkMultiplicity.getId()+"]";
buffer.get(RoassalTracer.ROASSAL_DEAEND).add(trace);
}
@Override
public String toString() {
return "DEAEnd "+this.getId();
}
}
| mit |
dvsa/motr-webapp | webapp/src/main/java/uk/gov/dvsa/motr/web/formatting/MakeModelFormatter.java | 1423 | package uk.gov.dvsa.motr.web.formatting;
import com.amazonaws.util.StringUtils;
import uk.gov.dvsa.motr.remote.vehicledetails.VehicleDetails;
public class MakeModelFormatter {
private static String UNKNOWN_VALUE = "UNKNOWN";
public static String getMakeModelString(String make, String model, String makeInFull) {
boolean makeValid = !StringUtils.isNullOrEmpty(make) && !make.equalsIgnoreCase(UNKNOWN_VALUE);
boolean modelValid = !StringUtils.isNullOrEmpty(model) && !model.equalsIgnoreCase(UNKNOWN_VALUE);
if (!makeValid && !modelValid) {
if (StringUtils.isNullOrEmpty(makeInFull)) {
return "";
}
return makeInFull.toUpperCase();
}
if (makeValid && !modelValid) {
return make.toUpperCase();
}
if (!makeValid && modelValid) {
return model.toUpperCase();
}
return (make + " " + model).toUpperCase();
}
public static String getMakeModelDisplayStringFromVehicleDetails(VehicleDetails vehicleDetails, String endDelimeter) {
String makeModel =
MakeModelFormatter.getMakeModelString(vehicleDetails.getMake(), vehicleDetails.getModel(), vehicleDetails.getMakeInFull());
if (endDelimeter == null) {
return makeModel;
}
return makeModel.equals("") ? makeModel : makeModel + endDelimeter;
}
}
| mit |
jtnord/jenkins | test/src/test/java/hudson/model/RunTest.java | 3005 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jorg Heymans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import junit.framework.TestCase;
import org.jvnet.hudson.test.HudsonTestCase;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class RunTest extends HudsonTestCase {
private List<? extends Run<?,?>.Artifact> createArtifactList(String... paths) throws Exception {
FreeStyleProject prj = createFreeStyleProject();
FreeStyleBuild r = prj.scheduleBuild2(0).get();
Run<FreeStyleProject,FreeStyleBuild>.ArtifactList list = r.new ArtifactList();
for (String p : paths) {
list.add(r.new Artifact(p,p,p,String.valueOf(p.length()),"n"+list.size())); // Assuming all test inputs don't need urlencoding
}
list.computeDisplayName();
return list;
}
public void testArtifactListDisambiguation1() throws Exception {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/j.xml");
assertEquals(a.get(0).getDisplayPath(),"c.xml");
assertEquals(a.get(1).getDisplayPath(),"g.xml");
assertEquals(a.get(2).getDisplayPath(),"j.xml");
}
public void testArtifactListDisambiguation2() throws Exception {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/g.xml");
assertEquals(a.get(0).getDisplayPath(),"c.xml");
assertEquals(a.get(1).getDisplayPath(),"f/g.xml");
assertEquals(a.get(2).getDisplayPath(),"i/g.xml");
}
public void testArtifactListDisambiguation3() throws Exception {
List<? extends Run<?, ?>.Artifact> a = createArtifactList("a.xml","a/a.xml");
assertEquals(a.get(0).getDisplayPath(),"a.xml");
assertEquals(a.get(1).getDisplayPath(),"a/a.xml");
}
}
| mit |
BookFrank/CodePlay | codeplay-container/src/main/java/com/tazine/container/collection/set/cases/stud/Client.java | 700 | package com.tazine.container.collection.set.cases.stud;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* @author frank
* @since 1.0.0
*/
public class Client {
public static void main(String[] args) {
Set<Student> set = new HashSet<>();
Student s1 = new Student(1, "kobe");
Student s2 = new Student(1, "james");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
set.add(s1);
System.out.println(set);
s1.setSno(2);
Iterator<Student> it = set.iterator();
System.out.println(s1.equals(it.next()));
set.add(s1);
System.out.println(set);
}
}
| mit |
LBNunes/uRPG | Game/src/main/java/game/RecipeWindow.java | 4468 | package game;
import game.ItemWindow.ItemOption;
import java.util.ArrayList;
import org.unbiquitous.uImpala.engine.asset.AssetManager;
import org.unbiquitous.uImpala.engine.asset.Text;
import org.unbiquitous.uImpala.engine.core.GameRenderers;
import org.unbiquitous.uImpala.engine.io.MouseSource;
import org.unbiquitous.uImpala.engine.io.Screen;
import org.unbiquitous.uImpala.util.Corner;
import org.unbiquitous.uImpala.util.observer.Event;
import org.unbiquitous.uImpala.util.observer.Observation;
import org.unbiquitous.uImpala.util.observer.Subject;
public class RecipeWindow extends SelectionWindow {
static final int WINDOW_WIDTH = 13;
static final int WINDOW_HEIGHT = 22;
static final int OPTION_OFFSET_X = 32;
static final int OPTION_OFFSET_Y = 32;
private ArrayList<Recipe> list;
public RecipeWindow(AssetManager assets, String frame, int x, int y, ArrayList<Recipe> list) {
super(assets, frame, x, y, WINDOW_WIDTH, WINDOW_HEIGHT);
mouse.connect(MouseSource.EVENT_BUTTON_DOWN, new Observation(this, "OnButtonDown"));
mouse.connect(MouseSource.EVENT_BUTTON_UP, new Observation(this, "OnButtonUp"));
this.list = list;
for (int i = 0; i < list.size(); ++i) {
Recipe r = list.get(i);
options.add(new RecipeOption(assets, i, i, x + OPTION_OFFSET_X, y + OPTION_OFFSET_Y,
WINDOW_WIDTH * this.frame.getWidth() / 3 - OPTION_OFFSET_X * 2,
(int) (this.frame.getHeight() * 1.0), r));
}
}
@Override
public void Swap(int index1, int index2) {
Option o1 = options.get(index1);
Option o2 = options.get(index2);
Recipe r1 = list.get(o1.originalIndex);
Recipe r2 = list.get(o2.originalIndex);
list.set(o1.originalIndex, r2);
list.set(o2.originalIndex, r1);
o1.index = index2;
o2.index = index1;
options.set(index2, o1);
options.set(index1, o2);
int oindex1 = o1.originalIndex;
o1.originalIndex = o2.originalIndex;
o2.originalIndex = oindex1;
}
public Recipe GetSelectedRecipe() {
if (selected == null) {
return null;
}
else {
return ((RecipeOption) selected).recipe;
}
}
@Override
protected void wakeup(Object... args) {
// TODO Auto-generated method stub
}
@Override
protected void destroy() {
// TODO Auto-generated method stub
}
@Override
public void OnButtonDown(Event event, Subject subject) {
super.OnButtonDown(event, subject);
}
@Override
public void OnButtonUp(Event event, Subject subject) {
super.OnButtonUp(event, subject);
}
private class RecipeOption extends ItemOption {
ArrayList<Text> components;
Recipe recipe;
public RecipeOption(AssetManager assets, int _index, int _originalIndex, int _baseX, int _baseY, int _w,
int _h, Recipe _recipe) {
super(assets, _index, _originalIndex, _baseX, _baseY, _w, _h, false, Item.GetItem(_recipe.itemID), 1, 0);
recipe = _recipe;
System.out.println("Recipe for item " + recipe.itemID + "(" + recipe.components.size() + " components)");
components = new ArrayList<Text>();
for (Integer component : recipe.components) {
Item i = Item.GetItem(component);
components.add(assets.newText("font/seguisb.ttf", i.GetName()));
}
}
@Override
public void Render(GameRenderers renderers, Screen screen) {
super.Render(renderers, screen);
int mx = screen.getMouse().getX();
int my = screen.getMouse().getY();
if (box.IsInside(mx, my)) {
int h = components.get(0).getHeight();
for (int i = 0; i < components.size(); ++i) {
components.get(i).render(screen, mx, my + i * h, Corner.TOP_LEFT);
}
}
}
@Override
public void CheckClick(int x, int y) {
if (box.IsInside(x, y)) {
selected = true;
}
}
}
}
| mit |
maoueh/kawa-fork | kawa/standard/define_autoload.java | 7247 | // Copyright (C) 2000 Per M.A. Bothner.
// This is free software; for terms and warranty disclaimer see ../../COPYING.
package kawa.standard;
import gnu.expr.*;
import gnu.lists.*;
import gnu.mapping.*;
import gnu.kawa.io.InPort;
import gnu.kawa.lispexpr.*;
import kawa.lang.*;
import java.io.File;
public class define_autoload extends Syntax
{
public static final define_autoload define_autoload
= new define_autoload("define-autoload", false);
public static final define_autoload define_autoloads_from_file
= new define_autoload("define-autoloads-from-file", true);
boolean fromFile;
public define_autoload (String name, boolean fromFile)
{
super(name);
this.fromFile = fromFile;
}
@Override
public boolean scanForDefinitions (Pair st, ScopeExp defs, Translator tr)
{
if (! (st.getCdr() instanceof Pair))
return super.scanForDefinitions(st, defs, tr);
Pair p = (Pair) st.getCdr();
if (fromFile)
{
for (;;)
{
/* #ifdef use:java.lang.CharSequence */
if (! (p.getCar() instanceof CharSequence))
break;
/* #else */
// if (! (p.getCar() instanceof String || p.getCar() instanceof CharSeq))
// break;
/* #endif */
if (! scanFile(p.getCar().toString(), defs, tr))
return false;
Object rest = p.getCdr();
if (rest == LList.Empty)
return true;
if (! (rest instanceof Pair))
break;
p = (Pair) p.getCdr();
}
tr.syntaxError("invalid syntax for define-autoloads-from-file");
return false;
}
Object names = p.getCar();
Object filename = null;
if (p.getCdr() instanceof Pair)
{
p = (Pair) p.getCdr();
filename = p.getCar();
return process(names, filename, defs, tr);
}
tr.syntaxError("invalid syntax for define-autoload");
return false;
}
public boolean scanFile(String filespec, ScopeExp defs, Translator tr)
{
if (filespec.endsWith(".el"))
;
File file = new File(filespec);
if (! file.isAbsolute())
file = new File(new File(tr.getFileName()).getParent(), filespec);
String filename = file.getPath();
int dot = filename.lastIndexOf('.');
Language language;
if (dot >= 0)
{
String extension = filename.substring(dot);
language = Language.getInstance(extension);
if (language == null)
{
tr.syntaxError("unknown extension for "+filename);
return true;
}
gnu.text.Lexer lexer;
/*
// Since (module-name ...) is not handled in this pass,
// we won't see it until its too late. FIXME.
ModuleExp module = tr.getModule();
String prefix = module == null ? null : module.getName();
System.err.println("module:"+module);
if (prefix == null)
prefix = kawa.repl.compilationPrefix;
else
{
int i = prefix.lastIndexOf('.');
if (i < 0)
prefix = null;
else
prefix = prefix.substring(0, i+1);
}
*/
String prefix = tr.classPrefix;
int extlen = extension.length();
int speclen = filespec.length();
String cname = filespec.substring(0, speclen - extlen);
while (cname.startsWith("../"))
{
int i = prefix.lastIndexOf('.', prefix.length() - 2);
if (i < 0)
{
tr.syntaxError("cannot use relative filename \"" + filespec
+ "\" with simple prefix \"" + prefix + "\"");
return false;
}
prefix = prefix.substring(0, i+1);
cname = cname.substring(3);
}
String classname = (prefix + cname).replace('/', '.');
try
{
InPort port = InPort.openFile(filename);
lexer = language.getLexer(port, tr.getMessages());
findAutoloadComments((LispReader) lexer, classname, defs, tr);
}
catch (Exception ex)
{
tr.syntaxError("error reading "+filename+": "+ex);
return true;
}
}
return true;
}
public static void findAutoloadComments (LispReader in, String filename,
ScopeExp defs, Translator tr)
throws java.io.IOException, gnu.text.SyntaxException
{
boolean lineStart = true;
String magic = ";;;###autoload";
int magicLength = magic.length();
mainLoop:
for (;;)
{
int ch = in.peek();
if (ch < 0)
return;
if (ch == '\n' || ch == '\r')
{
in.read();
lineStart = true;
continue;
}
if (lineStart && ch == ';')
{
int i = 0;
for (;;)
{
if (i == magicLength)
break;
ch = in.read();
if (ch < 0)
return;
if (ch == '\n' || ch == '\r')
{
lineStart = true;
continue mainLoop;
}
if (i < 0 || ch == magic.charAt(i++))
continue;
i = -1; // No match.
}
if (i > 0)
{
Object form = in.readObject();
if (form instanceof Pair)
{
Pair pair = (Pair) form;
Object value = null;
String name = null;
Object car = pair.getCar();
String command
= car instanceof String ? car.toString()
: car instanceof Symbol ? ((Symbol) car).getName()
: null;
if (command == "defun")
{
name = ((Pair)pair.getCdr()).getCar().toString();
value = new AutoloadProcedure(name, filename,
tr.getLanguage());
}
else
tr.error('w', "unsupported ;;;###autoload followed by: "
+ pair.getCar());
if (value != null)
{
Declaration decl = defs.getDefine(name, tr);
Expression ex = new QuoteExp(value);
decl.setFlag(Declaration.IS_CONSTANT);
decl.noteValue(ex);
}
}
lineStart = false;
continue;
}
}
lineStart = false;
in.skip();
if (ch == '#')
{
if (in.peek() == '|')
{
in.skip();
in.readNestedComment('#', '|');
continue;
}
}
if (Character.isWhitespace ((char)ch))
;
else
{
Object skipped = in.readObject(ch);
if (skipped == Sequence.eofValue)
return;
}
}
}
public static boolean process(Object names, Object filename,
ScopeExp defs, Translator tr)
{
if (names instanceof Pair)
{
Pair p = (Pair) names;
return (process(p.getCar(), filename, defs, tr)
&& process(p.getCdr(), filename, defs, tr));
}
if (names == LList.Empty)
return true;
String fn;
int len;
/*
if (names == "*" && filename instanceof String
&& (len = (fn = (String) filename).length()) > 2
&& fn.charAt(0) == '<' && fn.charAt(len-1) == '>')
{
fn = fn.substring(1, len-1);
try
{
Class fclass = Class.forName(fn);
Object instance = require.find(ctype, env);
...;
}
catch (ClassNotFoundException ex)
{
tr.syntaxError("class <"+fn+"> not found");
return false;
}
}
*/
if (names instanceof String || names instanceof Symbol)
{
String name = names.toString();
Declaration decl = defs.getDefine(name, tr);
if (filename instanceof SimpleSymbol
&& (len = (fn = filename.toString()).length()) > 2
&& fn.charAt(0) == '<' && fn.charAt(len-1) == '>')
filename = fn.substring(1, len-1);
Object value = new AutoloadProcedure(name, filename.toString(),
tr.getLanguage());
Expression ex = new QuoteExp(value);
decl.setFlag(Declaration.IS_CONSTANT);
decl.noteValue(ex);
return true;
}
return false;
}
public Expression rewriteForm (Pair form, Translator tr)
{
return null;
}
}
| mit |
vitaly-chibrikov/harbour_java_2017_05 | L11.1/src/main/java/space/harbour/l111/ehcache/EhcacheHelper.java | 1571 | package space.harbour.l111.ehcache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
/**
* Created by tully.
*/
public class EhcacheHelper {
static final int MAX_ENTRIES = 10;
static final int LIFE_TIME_SEC = 1;
static final int IDLE_TIME_SEC = 1;
static Cache createLifeCache(CacheManager manager, String name) {
CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES);
configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.timeToLiveSeconds(LIFE_TIME_SEC);
Cache cache = new Cache(configuration);
manager.addCache(cache);
return cache;
}
static Cache createIdleCache(CacheManager manager, String name) {
CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES);
configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.timeToIdleSeconds(IDLE_TIME_SEC);
Cache cache = new Cache(configuration);
manager.addCache(cache);
return cache;
}
static Cache createEternalCache(CacheManager manager, String name) {
CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES);
configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.eternal(true);
Cache cache = new Cache(configuration);
manager.addCache(cache);
return cache;
}
}
| mit |
AlterRS/Deobfuscator | deps/alterrs/jode/expr/UnaryOperator.java | 1963 | /* UnaryOperator Copyright (C) 1998-2002 Jochen Hoenicke.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, 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 Lesser General Public License
* along with this program; see the file COPYING.LESSER. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: UnaryOperator.java,v 2.13.4.2 2002/05/28 17:34:06 hoenicke Exp $
*/
package alterrs.jode.expr;
import alterrs.jode.decompiler.Options;
import alterrs.jode.decompiler.TabbedPrintWriter;
import alterrs.jode.type.Type;
public class UnaryOperator extends Operator {
public UnaryOperator(Type type, int op) {
super(type, op);
initOperands(1);
}
public int getPriority() {
return 700;
}
public Expression negate() {
if (getOperatorIndex() == LOG_NOT_OP) {
if (subExpressions != null)
return subExpressions[0];
else
return new NopOperator(Type.tBoolean);
}
return super.negate();
}
public void updateSubTypes() {
subExpressions[0].setType(Type.tSubType(type));
}
public void updateType() {
updateParentType(Type.tSuperType(subExpressions[0].getType()));
}
public boolean opEquals(Operator o) {
return (o instanceof UnaryOperator) && o.operatorIndex == operatorIndex;
}
public void dumpExpression(TabbedPrintWriter writer)
throws java.io.IOException {
writer.print(getOperatorString());
if ((Options.outputStyle & Options.GNU_SPACING) != 0)
writer.print(" ");
subExpressions[0].dumpExpression(writer, 700);
}
}
| mit |
YMonnier/TrailsCommunity | app/android/TrailsCommunity/app/src/main/java/fr/univ_tln/trailscommunity/utilities/validators/DateValidator.java | 1060 | package fr.univ_tln.trailscommunity.utilities.validators;
import java.util.Calendar;
/**
* Project TrailsCommunity.
* Package fr.univ_tln.trailscommunity.utilities.validators.
* File DateValidator.java.
* Created by Ysee on 26/11/2016 - 15:54.
* www.yseemonnier.com
* https://github.com/YMonnier
*/
public class DateValidator {
/**
* Test if the calendar date is not a past date.
* @param calendar calendar for validation.
* @return true if time calendar in millisecond is
* greater than current system time.
*/
public static boolean validate(Calendar calendar) {
Calendar currentCalendar = Calendar.getInstance();
if (currentCalendar == null)
return false;
currentCalendar.setTimeInMillis(System.currentTimeMillis());
return calendar.get(Calendar.YEAR) >= currentCalendar.get(Calendar.YEAR)
&& calendar.get(Calendar.MONTH) >= currentCalendar.get(Calendar.MONTH)
&& calendar.get(Calendar.DATE) >= currentCalendar.get(Calendar.DATE);
}
}
| mit |
Inbot/inbot-utils | src/main/java/io/inbot/utils/maps/RichMultiMap.java | 578 | package io.inbot.utils.maps;
import java.util.Collection;
import java.util.function.Supplier;
public interface RichMultiMap<K, V> extends RichMap<K,Collection<V>> {
Supplier<Collection<V>> supplier();
default Collection<V> putValue(K key, V value) {
Collection<V> collection = getOrCreate(key, supplier());
collection.add(value);
return collection;
}
@SuppressWarnings("unchecked")
default void putValue(Entry<K,V>...entries) {
for(Entry<K, V> e: entries) {
putValue(e.getKey(),e.getValue());
}
}
} | mit |
smartlogic/smartchat-android | SmartChat/src/main/java/io/smartlogic/smartchat/hypermedia/HalSmsVerification.java | 482 | package io.smartlogic.smartchat.hypermedia;
import com.fasterxml.jackson.annotation.JsonProperty;
public class HalSmsVerification {
@JsonProperty("verification_code")
private String verificationCode;
@JsonProperty("verification_phone_number")
private String verificationPhoneNumber;
public String getVerificationCode() {
return verificationCode;
}
public String getVerificationPhoneNumber() {
return verificationPhoneNumber;
}
}
| mit |
bcvsolutions/CzechIdMng | Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/rest/lookup/AbstractFormProjectionLookup.java | 5497 | package eu.bcvsolutions.idm.core.api.rest.lookup;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.GenericTypeResolver;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.core.api.domain.Codeable;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.dto.BaseDto;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormProjectionDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto;
import eu.bcvsolutions.idm.core.eav.api.service.FormService;
/**
* Find {@link IdmFormProjectionDto} by uuid identifier or by {@link Codeable} identifier.
*
* @author Radek Tomiška
* @param <T> dto
* @since 11.0.0
*/
public abstract class AbstractFormProjectionLookup<DTO extends BaseDto> implements FormProjectionLookup<DTO> {
@Autowired private ObjectMapper mapper;
//
private final Class<?> domainType;
/**
* Creates a new {@link AbstractFormProjectionLookup} instance discovering the supported type from the generics signature.
*/
public AbstractFormProjectionLookup() {
this.domainType = GenericTypeResolver.resolveTypeArgument(getClass(), FormProjectionLookup.class);
}
/*
* (non-Javadoc)
* @see org.springframework.plugin.core.Plugin#supports(java.lang.Object)
*/
@Override
public boolean supports(Class<?> delimiter) {
return domainType.equals(delimiter);
}
@Override
public IdmFormDefinitionDto lookupBasicFieldsDefinition(DTO dto) {
return getBasicFieldsDefinition(dto);
}
@Override
public IdmFormDefinitionDto lookupFormDefinition(DTO dto, IdmFormDefinitionDto formDefinition) {
return getFormDefinition(dto, formDefinition);
}
/**
* Construct basic fields form definition.
*
* @param dto basic fields owner
* @return basic fields form definition
*/
protected IdmFormDefinitionDto getBasicFieldsDefinition(DTO dto) {
return getFormDefinition(dto, null); // null ~ basicFileds ~ without form definition
}
/**
* Get overriden / configured form definition by projection.
* @param dto projection owner
* @param formDefinition form definition to load
* @return overriden form definition
*
* @since 12.0.0
*/
protected IdmFormDefinitionDto getFormDefinition(DTO dto, IdmFormDefinitionDto formDefinition) {
IdmFormProjectionDto formProjection = lookupProjection(dto);
if (formProjection == null) {
return null;
}
String formValidations = formProjection.getFormValidations();
if (StringUtils.isEmpty(formValidations)) {
return null;
}
//
if (formDefinition == null) { // ~ basic fields
formDefinition = new IdmFormDefinitionDto();
formDefinition.setCode(FormService.FORM_DEFINITION_CODE_BASIC_FIELDS);
}
IdmFormDefinitionDto overridenDefinition = new IdmFormDefinitionDto(); // clone ~ prevent to change input (e.g. cache can be modified)
overridenDefinition.setId(formDefinition.getId());
overridenDefinition.setCode(formDefinition.getCode());
// transform form attributes from json
try {
List<IdmFormAttributeDto> attributes = mapper.readValue(formValidations, new TypeReference<List<IdmFormAttributeDto>>() {});
attributes
.stream()
.filter(attribute -> Objects.equals(attribute.getFormDefinition(), overridenDefinition.getId()))
.forEach(attribute -> {
if (attribute.getId() == null) {
// we need artificial id to find attributes in definition / instance
attribute.setId(UUID.randomUUID());
}
overridenDefinition.addFormAttribute(attribute);
});
//
return overridenDefinition;
} catch (IOException ex) {
throw new ResultCodeException(
CoreResultCode.FORM_PROJECTION_WRONG_VALIDATION_CONFIGURATION,
ImmutableMap.of("formProjection", formProjection.getCode()),
ex
);
}
}
/**
* Add value, if it's filled into filled values.
*
* @param filledValues filled values
* @param formDefinition fields form definition (e.g. basic fields form definition)
* @param attributeCode attribute code
* @param attributeValue attribute value
*/
protected void appendAttributeValue(
List<IdmFormValueDto> filledValues,
IdmFormDefinitionDto formDefinition,
String attributeCode,
Serializable attributeValue) {
if (attributeValue == null) {
return;
}
IdmFormAttributeDto attribute = formDefinition.getMappedAttributeByCode(attributeCode);
if (attribute == null) {
return;
}
if (attribute.getPersistentType() == null) {
if (attributeValue instanceof UUID) {
attribute.setPersistentType(PersistentType.UUID);
} else if (attributeValue instanceof LocalDate) {
attribute.setPersistentType(PersistentType.DATE);
} else {
// TODO: support other persistent types (unused now)
attribute.setPersistentType(PersistentType.TEXT);
}
}
//
IdmFormValueDto value = new IdmFormValueDto(attribute);
value.setValue(attributeValue);
filledValues.add(value);
}
} | mit |
carlos-sancho-ramirez/android-java-langbook | bitstream/src/main/java/sword/bitstream/DiffSupplierCreator.java | 135 | package sword.bitstream;
public interface DiffSupplierCreator<T> {
FunctionWithIOException<T, T> create(InputBitStream stream);
}
| mit |
feihua666/feihua-jdbc-api | src/main/java/feihua/jdbc/api/dao/InsertDao.java | 1498 | package feihua.jdbc.api.dao;
import feihua.jdbc.api.pojo.BasePo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by feihua on 2015/6/29.
* 增
*/
public interface InsertDao<PO extends BasePo,PK> extends BaseDao<PO,PK> {
/**
* 创建(增加)数据,自动生成id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insert(PO entity);
/**
* 创建(增加)数据,请指定id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insertWithPrimaryKey(PO entity);
/**
* 创建(增加)数据,自动生成id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insertSelective(PO entity);
/**
* 创建(增加)数据,请指定id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insertSelectiveWithPrimaryKey(PO entity);
/**
* 批量插入,自动生成id
* @param entities
* @return
*/
public int insertBatch(@Param("entities") List<PO> entities);
/**
* 批量插入,请指定id
* @param entities
* @return
*/
public int insertBatchWithPrimaryKey(@Param("entities") List<PO> entities);
}
| mit |
kotlin-cloud/kotlin-is-not-like-java | code/butterknife.java | 316 | //usage
class MyActivity extends Activity {
@Bind(R.id.text)
TextView someText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
}
}
//implementation:
//https://github.com/JakeWharton/butterknife
//tons of code | mit |
bemisguided/atreus | src/main/java/org/atreus/impl/core/mappings/entities/builders/SimpleFieldComponentBuilder.java | 3523 | /**
* The MIT License
*
* Copyright (c) 2014 Martin Crawford and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.atreus.impl.core.mappings.entities.builders;
import org.atreus.core.annotations.AtreusField;
import org.atreus.impl.core.Environment;
import org.atreus.impl.core.mappings.BaseFieldEntityMetaComponentBuilder;
import org.atreus.impl.core.mappings.entities.meta.MetaEntityImpl;
import org.atreus.impl.core.mappings.entities.meta.StaticMetaSimpleFieldImpl;
import org.atreus.impl.util.ObjectUtils;
import java.lang.reflect.Field;
/**
* Simple field meta field builder.
*
* @author Martin Crawford
*/
public class SimpleFieldComponentBuilder extends BaseFieldEntityMetaComponentBuilder {
// Constants ---------------------------------------------------------------------------------------------- Constants
// Instance Variables ---------------------------------------------------------------------------- Instance Variables
// Constructors ---------------------------------------------------------------------------------------- Constructors
public SimpleFieldComponentBuilder(Environment environment) {
super(environment);
}
// Public Methods ------------------------------------------------------------------------------------ Public Methods
@Override
public boolean handleField(MetaEntityImpl metaEntity, Field field) {
// Assumption is this is the last field builder to be called and therefore a simple field
// Create the static field
StaticMetaSimpleFieldImpl metaField = createStaticMetaSimpleField(metaEntity, field, null);
// Check for a field annotation
AtreusField fieldAnnotation = field.getAnnotation(AtreusField.class);
if (fieldAnnotation != null) {
String fieldColumn = fieldAnnotation.value();
if (ObjectUtils.isNotNullOrEmpty(fieldColumn)) {
metaField.setColumn(fieldColumn);
}
}
// Resolve the type strategy
resolveTypeStrategy(metaEntity, metaField, field);
// Add the field to the meta entity
metaEntity.addField(metaField);
return true;
}
// Protected Methods ------------------------------------------------------------------------------ Protected Methods
// Private Methods ---------------------------------------------------------------------------------- Private Methods
// Getters & Setters ------------------------------------------------------------------------------ Getters & Setters
} // end of class | mit |
jazzbom/JBSC | src/main/java/com/jbsc/service/iface/CompanyService.java | 226 | package com.jbsc.service.iface;
import com.jbsc.domain.Company;
public interface CompanyService {
Company saveCompany(Company co);
Company loadCompanyById(Integer id);
Company loadCompanyByContactId(Integer id);
}
| mit |
zalando/intellij-swagger | src/main/java/org/zalando/intellij/swagger/documentation/openapi/OpenApiDocumentationProvider.java | 3876 | package org.zalando.intellij.swagger.documentation.openapi;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import java.util.Optional;
import java.util.stream.Stream;
import org.jetbrains.annotations.Nullable;
import org.zalando.intellij.swagger.documentation.ApiDocumentProvider;
import org.zalando.intellij.swagger.file.OpenApiFileType;
import org.zalando.intellij.swagger.index.openapi.OpenApiIndexService;
import org.zalando.intellij.swagger.traversal.path.openapi.PathResolver;
import org.zalando.intellij.swagger.traversal.path.openapi.PathResolverFactory;
public class OpenApiDocumentationProvider extends ApiDocumentProvider {
@Nullable
@Override
public String getQuickNavigateInfo(
final PsiElement targetElement, final PsiElement originalElement) {
Optional<PsiFile> psiFile =
Optional.ofNullable(targetElement).map(PsiElement::getContainingFile);
final Optional<VirtualFile> maybeVirtualFile = psiFile.map(PsiFile::getVirtualFile);
final Optional<Project> maybeProject = psiFile.map(PsiFile::getProject);
return maybeVirtualFile
.flatMap(
virtualFile -> {
final Project project = maybeProject.get();
final Optional<OpenApiFileType> maybeFileType =
ServiceManager.getService(OpenApiIndexService.class)
.getFileType(project, virtualFile);
return maybeFileType.map(
openApiFileType -> {
final PathResolver pathResolver =
PathResolverFactory.fromOpenApiFileType(openApiFileType);
if (pathResolver.childOfSchema(targetElement)) {
return handleSchemaReference(targetElement, originalElement);
} else if (pathResolver.childOfResponse(targetElement)) {
return handleResponseReference(targetElement);
} else if (pathResolver.childOfParameters(targetElement)) {
return handleParameterReference(targetElement);
} else if (pathResolver.childOfExample(targetElement)) {
return handleExampleReference(targetElement);
} else if (pathResolver.childOfRequestBody(targetElement)) {
return handleRequestBodyReference(targetElement);
} else if (pathResolver.childOfHeader(targetElement)) {
return handleHeaderReference(targetElement);
} else if (pathResolver.childOfLink(targetElement)) {
return handleLinkReference(targetElement);
}
return null;
});
})
.orElse(null);
}
private String handleLinkReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleHeaderReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleRequestBodyReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleExampleReference(final PsiElement targetElement) {
final Optional<String> summary = getUnquotedFieldValue(targetElement, "summary");
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(summary, description));
}
}
| mit |
jamilr/fashionScraper | src/main/java/org/fscraper/helpers/ScraperHelper.java | 1389 | package org.fscraper.helpers;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.SocketTimeoutException;
/**
* @author Jamil Rzayev March 2015
*/
public class ScraperHelper {
private static Logger logger = LoggerFactory.getLogger(ScraperHelper.class.getSimpleName());
private static final Integer TIMEOUT = 40000;
private static final String AGENT = "Mozilla";
public static Document loadHTMLDocument(String url) {
Document document;
try {
Connection connection = Jsoup.connect(url);
document = connection
.timeout(TIMEOUT)
.userAgent(AGENT)
.get();
} catch(SocketTimeoutException socEx) {
logger.error(socEx.getMessage(), socEx);
document = null;
} catch (HttpStatusException httpEx) {
logger.error(httpEx.getMessage(), httpEx);
document = null;
}catch (IOException ex) {
logger.error(ex.getMessage(), ex);
document = null;
} catch (Exception httEx) {
logger.error(httEx.getMessage());
document = null;
}
return document;
}
}
| mit |
mzipay/CharacterEncodingTranslator | src/main/java/net/ninthtest/CharacterEncodingTranslator.java | 22210 | /*
* Copyright (c) 2010 Matthew Zipay <mattz@ninthtest.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package net.ninthtest;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnmappableCharacterException;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.SwingWorker.StateValue;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.ninthtest.nio.charset.CharsetTranslator;
import net.ninthtest.swing.util.DimensionHelper;
/**
* <code>CharacterEncodingTranslator</code> is a console and GUI front-end for
* {@link CharsetTranslator}.
*
* <p>
* <b>GUI usage:</b>
* </p>
*
* <pre>
* java[w] -jar cetrans.jar
* </pre>
*
* <p>
* <b>Console usage:</b>
* </p>
*
* <pre>
* java -jar cetrans.jar [-xmlcharref] source-filename source-encoding target-filename target-encoding
* </pre>
*
* @author mattz
* @version 2.0.1
*/
public class CharacterEncodingTranslator {
/** The command-line usage message. */
public static final String USAGE =
"CONSOLE USAGE:\n"
+ "\tjava -jar cetrans.jar [-xmlcharref] <source-filename>"
+ " <source-encoding> <target-filename> <target-encoding>\n"
+ "GUI USAGE:\n"
+ "\tjava[w] -jar cetrans.jar\n";
/** The current application SemVer version string. */
public static final String VERSION = "2.0.1";
private static final ResourceBundle RESOURCES =
ResourceBundle.getBundle("cetrans");
private static final int TEXT_SIZE = 59;
private static final String DEFAULT_TARGET_ENCODING = "UTF-8";
private final JTextField inTextField = new JTextField();
private final JButton inButton = new JButton();
private final JComboBox<String> inCharsets = new JComboBox<String>();
private final JButton translateButton = new JButton();
private final JCheckBox xmlCharRefPref = new JCheckBox();
private final JTextField outTextField = new JTextField();
private final JButton outButton = new JButton();
private final JComboBox<String> outCharsets = new JComboBox<String>();
private final JFileChooser fileChooser = new JFileChooser();
private final JMenuBar menuBar = new JMenuBar();
/**
* Builds the GUI components for the <i>Character Encoding Translator</i>
* application.
*/
public CharacterEncodingTranslator() {
JFrame frame = new JFrame(RESOURCES.getString("frame.title"));
initializeComponents();
doLayout(frame.getContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
/*
* Configures the user interface Swing components.
*/
private void initializeComponents() {
FileNameExtensionFilter csvFilter = new FileNameExtensionFilter(
RESOURCES.getString("filter.description.csv"), "csv");
fileChooser.addChoosableFileFilter(csvFilter);
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter(
RESOURCES.getString("filter.description.txt"), "txt");
fileChooser.addChoosableFileFilter(txtFilter);
fileChooser.setFileFilter(csvFilter);
inTextField.setColumns(TEXT_SIZE);
inButton.setText(RESOURCES.getString("button.text.open"));
inButton.setMnemonic(KeyEvent.VK_O);
inButton.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent event) {
if (JFileChooser.APPROVE_OPTION
== fileChooser.showOpenDialog(inTextField)) {
inTextField.setText(
fileChooser.getSelectedFile().getAbsolutePath());
}
}
});
final String[] availableCharsets =
Charset.availableCharsets().keySet().toArray(new String[0]);
inCharsets.setModel(
new DefaultComboBoxModel<String>(availableCharsets));
inCharsets.setName("inCharsets");
inCharsets.setSelectedItem(Charset.defaultCharset().name());
inCharsets.setEditable(false);
translateButton.setText(RESOURCES.getString("button.text.translate"));
translateButton.setName("translateButton");
translateButton.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == translateButton) {
final File inFile = new File(inTextField.getText());
final File outFile = new File(outTextField.getText());
if (filesAreAcceptable(inFile, outFile)) {
final String inEncoding =
(String) inCharsets.getSelectedItem();
final String outEncoding =
(String) outCharsets.getSelectedItem();
try {
translate(
inFile, inEncoding, outFile, outEncoding);
} catch (IOException ex) {
JOptionPane.showMessageDialog(
translateButton, ex.getLocalizedMessage(),
ex.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
}
}
}
}
});
xmlCharRefPref.setText(
RESOURCES.getString("checkbox.text.use_xml_charref"));
xmlCharRefPref.setName("xmlCharRefPref");
outTextField.setColumns(TEXT_SIZE);
outButton.setText(RESOURCES.getString("button.text.save"));
outButton.setMnemonic(KeyEvent.VK_S);
outButton.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent e) {
if (JFileChooser.APPROVE_OPTION
== fileChooser.showSaveDialog(outTextField)) {
outTextField.setText(
fileChooser.getSelectedFile().getAbsolutePath());
}
}
});
outCharsets.setModel(
new DefaultComboBoxModel<String>(availableCharsets));
outCharsets.setName("outCharsets");
outCharsets.setSelectedItem(DEFAULT_TARGET_ENCODING);
outCharsets.setEditable(false);
JMenu help = new JMenu(RESOURCES.getString("menu.help.text"));
JMenuItem about = new JMenuItem(
RESOURCES.getString("about.label") + '\u2026');
about.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null,
MessageFormat.format(
RESOURCES.getString("about.message"),
CharacterEncodingTranslator.VERSION),
RESOURCES.getString("about.label"),
JOptionPane.INFORMATION_MESSAGE);
}
});
help.add(about);
menuBar.add(help);
}
/*
* Applies the GUI layout for the application.
*/
private void doLayout(final Container container) {
DimensionHelper.normalizeWidth(inTextField, outTextField);
DimensionHelper.normalizeWidth(inCharsets, outCharsets);
DimensionHelper.normalizeWidth(inButton, outButton);
DimensionHelper.normalizeHeight(inTextField, inButton, inCharsets,
translateButton, outTextField, outButton, outCharsets);
FlowLayout inLayout = new FlowLayout(FlowLayout.LEFT, 5, 10);
inLayout.setAlignOnBaseline(true);
JPanel inPanel = new JPanel(inLayout);
inPanel.add(inTextField);
inPanel.add(inButton);
inPanel.add(inCharsets);
FlowLayout translateLayout = new FlowLayout(FlowLayout.CENTER, 5, 10);
translateLayout.setAlignOnBaseline(true);
JPanel translatePanel = new JPanel(translateLayout);
translatePanel.add(translateButton);
translatePanel.add(xmlCharRefPref);
FlowLayout outLayout = new FlowLayout(FlowLayout.LEFT, 5, 10);
outLayout.setAlignOnBaseline(true);
JPanel outPanel = new JPanel(outLayout);
outPanel.add(outTextField);
outPanel.add(outButton);
outPanel.add(outCharsets);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
container.add(inPanel);
container.add(translatePanel);
container.add(outPanel);
}
/*
* Ensures that the specified input and output files are reasonable before
* attempting the translation.
*/
private boolean filesAreAcceptable(File inFile, File outFile) {
if (inFile.getPath().isEmpty()) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.choose_input"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (outFile.getPath().isEmpty()) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.choose_output"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (outFile.equals(inFile)) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.same_input_output"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (!inFile.canRead()) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.input_notfound"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (outFile.exists()) {
return (JOptionPane.YES_OPTION
== JOptionPane.showConfirmDialog(translateButton,
RESOURCES.getString("yesno.message.output_exists"),
RESOURCES.getString("yesno.title.user_input"),
JOptionPane.YES_NO_OPTION));
}
return true;
}
/*
* Performs the translation in a background thread.
*/
private void translate(final File inFile, final String inEncoding,
final File outFile, final String outEncoding)
throws FileNotFoundException {
final ProgressMonitorInputStream monitorStream =
new ProgressMonitorInputStream(translateButton,
RESOURCES.getString("monitor.message.translating"),
new FileInputStream(inFile));
monitorStream.getProgressMonitor().setNote(
inFile.getName() + " \u2192 " + outFile.getName());
final FileOutputStream outStream = new FileOutputStream(outFile);
final SwingWorker<Boolean, Void> task =
new SwingWorker<Boolean, Void>() {
@SuppressWarnings("synthetic-access")
@Override
protected Boolean doInBackground() throws Exception {
CharsetTranslator translator =
new CharsetTranslator(inEncoding, outEncoding);
translator.useXMLCharRefReplacement(
xmlCharRefPref.isSelected());
translator.translate(monitorStream, outStream);
return true;
}
};
task.addPropertyChangeListener(new PropertyChangeListener() {
@SuppressWarnings("synthetic-access")
@Override
public void propertyChange(PropertyChangeEvent event) {
/*
* Swing is not thread-safe, so it is possible that the task is
* actually DONE when the state property is only reporting a
* change from PENDING to STARTED (for a relatively small input
* file, this will almost certainly be the case); to ensure
* that this block is only entered once, both the task state
* _and_ the state property value must be DONE
*/
if ("state".equals(event.getPropertyName())
&& (StateValue.DONE == event.getNewValue())
&& (StateValue.DONE == task.getState())) {
/*
* testing on both Max OS X and Windows 7 shows that
* neither the task nor the monitor actually report being
* canceled when the progress IS canceled; since we can't
* rely on this approach, we need to check explicitly for
* an InterruptedIOException (yuck)
*/
try {
if (task.get()) {
JOptionPane.showMessageDialog(
translateButton,
RESOURCES
.getString("info.message.success"),
RESOURCES
.getString("info.title.translated"),
JOptionPane.INFORMATION_MESSAGE);
}
} catch (ExecutionException ex) {
handleExecutionException(ex);
} catch (InterruptedException ex) {
/*
* should never happen since we're only here if the
* task state is DONE
*/
assert false;
}
translateButton.setText(
RESOURCES.getString("button.text.translate"));
translateButton.setEnabled(true);
}
}
});
task.execute();
translateButton.setEnabled(false);
translateButton.setText(
RESOURCES.getString("monitor.message.translating"));
}
/*
* Displays an appropriate dialog message based on the cause of a failed
* translation.
*/
private final void handleExecutionException(ExecutionException ex) {
Throwable cause = ex.getCause();
if (cause instanceof InterruptedIOException) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.canceled"),
RESOURCES.getString("warning.title.canceled"),
JOptionPane.WARNING_MESSAGE);
} else if (cause instanceof MalformedInputException) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("error.message.malformed"),
RESOURCES.getString("error.title.failed"),
JOptionPane.ERROR_MESSAGE);
} else if (cause instanceof UnmappableCharacterException) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("error.message.unmappable"),
RESOURCES.getString("error.title.failed"),
JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("error.message.other"),
RESOURCES.getString("error.title.failed"),
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Launches <i>Character Encoding Translator</i> as a GUI or console
* application.
*
* <p>
* Without command-line arguments, the application runs as a GUI. With
* command-line arguments, the application runs on the console.
* </p>
*
* <p>
* To run on the console, provide the following positional arguments:
* </p>
*
* <dl>
* <dt><b>"-xmlcharref"</b></dt>
* <dd>(optional) the literal flag "-xmlcharref" enables XML character
* reference replacement</dd>
* <dt><i>source-filename</i></dt>
* <dd>(required) the path to the input file</dd>
* <dt><i>source-encoding</i></dt>
* <dd>(required) the character encoding of the input file</dd>
* <dt><i>target-filename</i></dt>
* <dd>(required) the path to the output file</dd>
* <dt><i>target-encoding</i></dt>
* <dd>(required) the desired character encoding of the output file</dd>
* </dl>
*
* @param args the command-line arguments
* @throws ClassNotFoundException if the L&F class name is not found on
* the CLASSPATH
* @throws InstantiationException if the L&F class cannot be
* instantiated
* @throws IllegalAccessException if the current user does not have
* permission to access the L&F class
* @throws UnsupportedLookAndFeelException if the L&F class name is not
* recognized
*/
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, UnsupportedLookAndFeelException {
switch (args.length) {
case 0:
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@SuppressWarnings("unused")
@Override
public void run() {
new CharacterEncodingTranslator();
}
});
break;
case 4:
/* falls through */
case 5:
boolean useXmlCharRef = "-xmlcharref".equals(args[0]);
int i = useXmlCharRef ? 1 : 0;
String sourceFilename = args[i++];
String sourceEncoding = args[i++];
String targetFilename = args[i++];
String targetEncoding = args[i++];
InputStream sourceStream = null;
OutputStream targetStream = null;
int status = 0;
try {
sourceStream = new FileInputStream(sourceFilename);
targetStream = new FileOutputStream(targetFilename);
(new CharsetTranslator(sourceEncoding, targetEncoding))
.translate(sourceStream, targetStream);
} catch (Exception ex) {
System.err.println(ex.toString());
status = 1;
} finally {
if (targetStream != null) {
try {
targetStream.close();
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
if (sourceStream != null) {
try {
sourceStream.close();
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
}
System.exit(status);
break;
default:
System.err.println(USAGE);
System.exit(1);
}
}
}
| mit |
przodownikR1/springBatchBootJavaConfigkata | src/main/java/pl/java/scalatech/tasklet/HelloTasklet.java | 1393 | package pl.java.scalatech.tasklet;
import static org.springframework.batch.repeat.RepeatStatus.FINISHED;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class HelloTasklet implements Tasklet {
public RepeatStatus execute(final StepContribution sc, final ChunkContext context) throws Exception {
log.info("First simple task ..... execute !!! ");
log.info("+++ StepContext : jobParameters : {} , stepExecution : {} , stepName : {} ",context.getStepContext().getJobParameters(),context.getStepContext().getStepExecution(),context.getStepContext().getStepName());
ExecutionContext jobExecutionContext = context.getStepContext().getStepExecution().getJobExecution().getExecutionContext();
JobParameters jobParams = context.getStepContext().getStepExecution().getJobExecution().getJobParameters();
log.info("time : {}",jobParams.getDate("time"));
log.info("test : {}",jobParams.getString("test"));
return FINISHED;
}
} | mit |
zkkz/OrientalExpress | source/step/src/sse/ngts/common/plugin/step/business/QuoteCancel.java | 5629 | /*########################################################################
*# #
*# Copyright (c) 2014 by #
*# Shanghai Stock Exchange (SSE), Shanghai, China #
*# All rights reserved. #
*# #
*########################################################################
*/
package sse.ngts.common.plugin.step.business;
import sse.ngts.common.plugin.step.*;
import sse.ngts.common.plugin.step.field.*;
public class QuoteCancel extends Message {
private static final long serialVersionUID = 20130819;
public static final String MSGTYPE = "Z";
public QuoteCancel() {
super();
getHeader().setField(new MsgType(MSGTYPE));
}
public QuoteCancel(int[] fieldOrder) {
super(fieldOrder);
getHeader().setField(new MsgType(MSGTYPE));
}
public void set(OrderQty value) {
setField(value);
}
public OrderQty get(OrderQty value) throws FieldNotFound {
getField(value);
return value;
}
public OrderQty getOrderQty() throws FieldNotFound {
OrderQty value = new OrderQty();
getField(value);
return value;
}
public boolean isSet(OrderQty field) {
return isSetField(field);
}
public boolean isSetOrderQty() {
return isSetField(OrderQty.FIELD);
}
public void set(OrigClOrdID value) {
setField(value);
}
public OrigClOrdID get(OrigClOrdID value) throws FieldNotFound {
getField(value);
return value;
}
public OrigClOrdID getOrigClOrdID() throws FieldNotFound {
OrigClOrdID value = new OrigClOrdID();
getField(value);
return value;
}
public boolean isSet(OrigClOrdID field) {
return isSetField(field);
}
public boolean isSetOrigClOrdID() {
return isSetField(OrigClOrdID.FIELD);
}
public void set(SecurityID value) {
setField(value);
}
public SecurityID get(SecurityID value) throws FieldNotFound {
getField(value);
return value;
}
public SecurityID getSecurityID() throws FieldNotFound {
SecurityID value = new SecurityID();
getField(value);
return value;
}
public boolean isSet(SecurityID field) {
return isSetField(field);
}
public boolean isSetSecurityID() {
return isSetField(SecurityID.FIELD);
}
public void set(Side value) {
setField(value);
}
public Side get(Side value) throws FieldNotFound {
getField(value);
return value;
}
public Side getSide() throws FieldNotFound {
Side value = new Side();
getField(value);
return value;
}
public boolean isSet(Side field) {
return isSetField(field);
}
public boolean isSetSide() {
return isSetField(Side.FIELD);
}
public void set(Text value) {
setField(value);
}
public Text get(Text value) throws FieldNotFound {
getField(value);
return value;
}
public Text getText() throws FieldNotFound {
Text value = new Text();
getField(value);
return value;
}
public boolean isSet(Text field) {
return isSetField(field);
}
public boolean isSetText() {
return isSetField(Text.FIELD);
}
public void set(TradeDate value) {
setField(value);
}
public TradeDate get(TradeDate value) throws FieldNotFound {
getField(value);
return value;
}
public TradeDate getTradeDate() throws FieldNotFound {
TradeDate value = new TradeDate();
getField(value);
return value;
}
public boolean isSet(TradeDate field) {
return isSetField(field);
}
public boolean isSetTradeDate() {
return isSetField(TradeDate.FIELD);
}
public void set(QuoteID value) {
setField(value);
}
public QuoteID get(QuoteID value) throws FieldNotFound {
getField(value);
return value;
}
public QuoteID getQuoteID() throws FieldNotFound {
QuoteID value = new QuoteID();
getField(value);
return value;
}
public boolean isSet(QuoteID field) {
return isSetField(field);
}
public boolean isSetQuoteID() {
return isSetField(QuoteID.FIELD);
}
public void set(OrderQty2 value) {
setField(value);
}
public OrderQty2 get(OrderQty2 value) throws FieldNotFound {
getField(value);
return value;
}
public OrderQty2 getOrderQty2() throws FieldNotFound {
OrderQty2 value = new OrderQty2();
getField(value);
return value;
}
public boolean isSet(OrderQty2 field) {
return isSetField(field);
}
public boolean isSetOrderQty2() {
return isSetField(OrderQty2.FIELD);
}
public void set(NoPartyIDs value) {
setField(value);
}
public NoPartyIDs get(NoPartyIDs value) throws FieldNotFound {
getField(value);
return value;
}
public NoPartyIDs getNoPartyIDs() throws FieldNotFound {
NoPartyIDs value = new NoPartyIDs();
getField(value);
return value;
}
public boolean isSet(NoPartyIDs field) {
return isSetField(field);
}
public boolean isSetNoPartyIDs() {
return isSetField(NoPartyIDs.FIELD);
}
}
| mit |
a2ndrade/k-intellij-plugin | src/main/java/com/appian/intellij/k/KSymbolicReference.java | 2654 | package com.appian.intellij.k;
import java.util.Collection;
import java.util.Collections;
import org.jetbrains.annotations.NotNull;
import com.appian.intellij.k.psi.KElementFactory;
import com.appian.intellij.k.psi.KNamespaceDeclaration;
import com.appian.intellij.k.psi.KSymbol;
import com.appian.intellij.k.psi.KUserId;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
public final class KSymbolicReference extends KReferenceBase {
KSymbolicReference(KSymbol element, TextRange textRange) {
super(element, textRange, false);
}
@NotNull
@Override
Collection<KUserId> resolve0(boolean stopAfterFirstMatch) {
final String referenceName = myElement.getText().substring(1);
return resolve00(referenceName, stopAfterFirstMatch);
}
@NotNull
private Collection<KUserId> resolve00(String referenceName, boolean stopAfterFirstMatch) {
final VirtualFile sameFile = myElement.getContainingFile().getOriginalFile().getVirtualFile();
if (sameFile == null || sameFile.getCanonicalPath() == null) {
return Collections.emptyList();
}
final PsiElement context = myElement.getContext();
if (context instanceof KNamespaceDeclaration) {
return Collections.emptyList();
}
final Project project = myElement.getProject();
final String fqn;
if (KUtil.isAbsoluteId(referenceName)) {
fqn = referenceName;
} else {
final String currentNs = KUtil.getCurrentNamespace(myElement);
fqn = KUtil.generateFqn(currentNs, referenceName);
}
final KUtil.ExactGlobalAssignmentMatcher matcher = new KUtil.ExactGlobalAssignmentMatcher(fqn);
return findDeclarations(project, sameFile, stopAfterFirstMatch, matcher);
}
@Override
public PsiElement handleElementRename(@NotNull final String newName) throws IncorrectOperationException {
final KUserId declaration = (KUserId)resolve();
final String newEffectiveName = getNewNameForUsage(declaration, myElement, newName);
final ASTNode keyNode = myElement.getNode().getFirstChildNode();
KSymbol property = KElementFactory.createKSymbol(myElement.getProject(), toSymbolicName(newEffectiveName));
ASTNode newKeyNode = property.getFirstChild().getNode();
myElement.getNode().replaceChild(keyNode, newKeyNode);
KUserIdCache.getInstance().remove(myElement);
return myElement;
}
private String toSymbolicName(String name) {
return name.charAt(0) == '`' ? name : "`" + name;
}
}
| mit |
StoyanVitanov/SoftwareUniversity | Java DB Fundamentals/Hibernate/Java Overview/OOP Principles/Lab/CarShop/Interfaces/Car.java | 152 | package Lab.CarShop.Interfaces;
public interface Car {
int tires = 4;
String getModel();
String getColor();
int getHorsePower();
}
| mit |
mrajian/xinyuan | xinyuan-parent/xinyuan-pub-parent/xinyuan-pub-dao/src/main/java/com/xinyuan/pub/business/bi/dao/BiLiLandPlanDao.java | 391 | package com.xinyuan.pub.business.bi.dao;
import com.xinyuan.pub.model.business.bi.po.BiLiLandPlan;
import java.util.List;
/**
* @author liangyongjian
* @desc 新增土地数据表 Dao层接口
* @create 2018-06-22 23:47
**/
public interface BiLiLandPlanDao {
/**
* 获取全部的新增土地数据
* @return
*/
List<BiLiLandPlan> getAllBiLiLandPlanInfo();
}
| mit |
kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/InsupdInstallmentsPlan.java | 2811 |
package ru.lanbilling.webservice.wsdl;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="isInsert" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="val" type="{urn:api3}soapInstallmentsPlan"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"isInsert",
"val"
})
@XmlRootElement(name = "insupdInstallmentsPlan")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class InsupdInstallmentsPlan {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected long isInsert;
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected SoapInstallmentsPlan val;
/**
* Gets the value of the isInsert property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public long getIsInsert() {
return isInsert;
}
/**
* Sets the value of the isInsert property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setIsInsert(long value) {
this.isInsert = value;
}
/**
* Gets the value of the val property.
*
* @return
* possible object is
* {@link SoapInstallmentsPlan }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public SoapInstallmentsPlan getVal() {
return val;
}
/**
* Sets the value of the val property.
*
* @param value
* allowed object is
* {@link SoapInstallmentsPlan }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setVal(SoapInstallmentsPlan value) {
this.val = value;
}
}
| mit |
matiasmasca/111mil | PracticoMayor/src/practicomayor/PracticoMayor.java | 272 |
package practicomayor;
import vista.PracticoMayorVista;
public class PracticoMayor {
public static void main(String[] args) {
PracticoMayorVista miVentana = new PracticoMayorVista();
miVentana.setVisible(true);
}
}
| mit |
IoT-Ticket/IoT-JavaClient | src/main/java/com/iotticket/api/v1/model/ProcessValues.java | 639 | package com.iotticket.api.v1.model;
import com.google.gson.annotations.SerializedName;
import com.iotticket.api.v1.model.Datanode.DatanodeRead;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
public class ProcessValues {
@SerializedName("href")
private URI Uri;
@SerializedName("datanodeReads")
private Collection<DatanodeRead> datanodeReads = new ArrayList<DatanodeRead>();
public URI getUri() {
return Uri;
}
public void setUri(URI uri) {
Uri = uri;
}
public Collection<DatanodeRead> getDatanodeReads() {
return datanodeReads;
}
}
| mit |
caelum/tubaina | src/main/java/br/com/caelum/tubaina/parser/html/desktop/SingleHtmlGenerator.java | 4139 | package br.com.caelum.tubaina.parser.html.desktop;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import br.com.caelum.tubaina.Book;
import br.com.caelum.tubaina.Chapter;
import br.com.caelum.tubaina.TubainaBuilderData;
import br.com.caelum.tubaina.TubainaException;
import br.com.caelum.tubaina.io.HtmlResourceManipulatorFactory;
import br.com.caelum.tubaina.io.ResourceManipulatorFactory;
import br.com.caelum.tubaina.io.TubainaHtmlDir;
import br.com.caelum.tubaina.io.TubainaHtmlIO;
import br.com.caelum.tubaina.parser.Parser;
import br.com.caelum.tubaina.parser.html.referencereplacer.ReferenceParser;
import br.com.caelum.tubaina.parser.html.referencereplacer.ReferenceReplacer;
import br.com.caelum.tubaina.parser.html.referencereplacer.SingleHtmlChapterReferenceReplacer;
import br.com.caelum.tubaina.parser.html.referencereplacer.SingleHtmlSectionReferenceReplacer;
import br.com.caelum.tubaina.template.FreemarkerProcessor;
import br.com.caelum.tubaina.util.Utilities;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
public class SingleHtmlGenerator implements Generator {
private final Parser parser;
private final File templateDir;
private Configuration cfg;
private List<String> ifdefs;
public SingleHtmlGenerator(Parser parser, TubainaBuilderData data) {
this.parser = parser;
this.templateDir = new File(data.getTemplateDir(), "singlehtml/");
this.ifdefs = data.getIfdefs();
configureFreemarker();
}
public void generate(Book book, File outputDir) throws IOException {
StringBuffer bookContent = generateHeader(book);
bookContent.append(new SingleHtmlTOCGenerator(book, cfg).generateTOC());
ResourceManipulatorFactory htmlResourceManipulatorFactory = new HtmlResourceManipulatorFactory();
TubainaHtmlDir bookRoot = new TubainaHtmlIO(templateDir, htmlResourceManipulatorFactory).createTubainaDir(outputDir, book);
for (Chapter c : book.getChapters()) {
StringBuffer chapterContent = generateChapter(book, c);
bookContent.append(chapterContent);
if (!c.getResources().isEmpty()) {
bookRoot.cd(Utilities.toDirectoryName(null, c.getTitle()))
.writeResources(c.getResources());
}
}
bookContent = resolveReferencesOf(bookContent);
bookContent.append(generateFooter());
bookRoot.writeIndex(bookContent);
}
private StringBuffer resolveReferencesOf(StringBuffer bookContent) {
List<ReferenceReplacer> replacers = new ArrayList<ReferenceReplacer>();
replacers.add(new SingleHtmlSectionReferenceReplacer());
replacers.add(new SingleHtmlChapterReferenceReplacer());
ReferenceParser referenceParser = new ReferenceParser(replacers);
bookContent = new StringBuffer(referenceParser.replaceReferences(bookContent.toString()));
return bookContent;
}
private StringBuffer generateHeader(Book book) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("booktitle", book.getName());
return new FreemarkerProcessor(cfg).process(map, "book-header.ftl");
}
private StringBuffer generateChapter(Book book, Chapter chapter) {
StringBuffer chapterContent = new SingleHtmlChapterGenerator(parser, cfg, ifdefs).generateSingleHtmlChapter(book, chapter);
return fixPaths(chapter, chapterContent);
}
private StringBuffer fixPaths(Chapter chapter, StringBuffer chapterContent) {
String chapterName = Utilities.toDirectoryName(null, chapter.getTitle());
return new StringBuffer(chapterContent.toString().replace("$$RELATIVE$$", chapterName));
}
private StringBuffer generateFooter() {
return new FreemarkerProcessor(cfg).process(new HashMap<String, Object>(), "book-footer.ftl");
}
private void configureFreemarker() {
cfg = new Configuration();
try {
cfg.setDefaultEncoding("UTF-8");
cfg.setDirectoryForTemplateLoading(templateDir);
} catch (IOException e) {
throw new TubainaException("Couldn't load freemarker template for Single HTML mode", e);
}
cfg.setObjectWrapper(new BeansWrapper());
}
}
| mit |
andrewwiik/Lab14avst | Lab14avst.java | 771 |
// Lab14avst.java
// Lab14a
// Student starting version
import java.awt.*;
import java.applet.*;
import java.util.ArrayList;
public class Lab14avst extends Applet {
public void paint(Graphics g) {
drawGrid(g);
Shape square = new Shape1Square();
Shape triangle = new Shape2Triangle();
Shape octagon = new Shape3Octagon();
Shape circle = new Shape4Circle();
ArrayList<Shape> shapes = new ArrayList<Shape>();
shapes.add(square);
shapes.add(triangle);
shapes.add(octagon);
shapes.add(circle);
for (Shape shape : shapes) {
shape.drawShape(g);
shape.displayName(g);
shape.displayNumSides(g);
}
}
public void drawGrid(Graphics g) {
g.drawRect(10, 10, 800, 600);
g.drawLine(10, 300, 810, 300);
g.drawLine(410, 10, 410, 610);
}
}
| mit |
zhaiwh8312/plan | java/plan/src/com/convenient/plan/service/PlanIndexService.java | 320 | package com.convenient.plan.service;
import net.sf.json.JSONArray;
public interface PlanIndexService {
/**
* 获取所有项目的计划,并以JSONArray的格式返回
* @return
* @throws RuntimeException
* @throws Exception
*/
public JSONArray getAllProjectPlan() throws RuntimeException, Exception;
}
| mit |
ivanyu/btree | src/main/java/me/ivanyu/simplekv/types/KeyComparator.java | 483 | package me.ivanyu.simplekv.types;
import java.util.Comparator;
public class KeyComparator implements Comparator<Key> {
public static final KeyComparator INSTANCE = new KeyComparator();
@Override
public int compare(Key k1, Key k2) {
if (k1 == null)
throw new NullPointerException("k1 can't be null");
if (k2 == null)
throw new NullPointerException("k2 can't be null");
return k1.keyValue.compareTo(k2.keyValue);
}
}
| mit |
nab-velocity/android-sdk | VelocityLibrary/src/com/velocity/model/transactions/query/response/ScoreThreshold.java | 666 | package com.velocity.model.transactions.query.response;
import com.velocity.gson.annotations.SerializedName;
/**
* This class holds the data for ScoreThreshold
*
* @author ranjitk
*
*/
public class ScoreThreshold {
/* Attribute for ScoreThreshold value exists or not. */
@SerializedName("Nillable")
private boolean nillable;
@SerializedName("Value")
private String value;
public boolean isNillable() {
return nillable;
}
public void setNillable(boolean nillable) {
this.nillable = nillable;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| mit |
zkastl/AcmeCourierService | AcmeCourierSystem/src/view/EmployeeManagement.java | 4397 | package view;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.UUID;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import controller.EnterKeyListenerForButtons;
import controller.MandatoryStringCellEditor;
import controller.TableValidator;
import controller.UsernameCellEditor;
import main.CourierSystem;
import model.Employee;
import model.EmployeeRole;
import net.miginfocom.swing.MigLayout;
public class EmployeeManagement extends Container {
private static final long serialVersionUID = 1L;
private JTable table;
private EmployeeTableModel employeeTable;
public EmployeeManagement() {
employeeTable = new EmployeeTableModel();
setLayout(new MigLayout("", "[grow][50%][grow][10]", "[25][40][5][grow][][20]"));
JLabel lblEmployeeManagement = new JLabel("Employee Management");
lblEmployeeManagement.setFont(new Font("Tahoma", Font.BOLD, 16));
add(lblEmployeeManagement, "cell 0 0 3 1,alignx center,aligny center");
JButton btnAddEmployee = new JButton("Add Employee");
add(btnAddEmployee, "cell 0 1,alignx center");
btnAddEmployee.addKeyListener(new EnterKeyListenerForButtons(btnAddEmployee));
JButton btnRemoveEmployee = new JButton("Remove Employee");
add(btnRemoveEmployee, "cell 1 1,alignx center");
btnRemoveEmployee.addKeyListener(new EnterKeyListenerForButtons(btnRemoveEmployee));
JButton btnSaveChanges = new JButton("Save Changes");
add(btnSaveChanges, "cell 2 1");
btnSaveChanges.addKeyListener(new EnterKeyListenerForButtons(btnSaveChanges));
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, "cell 0 3 3 1,grow");
table = new JTable(employeeTable);
table.setCellSelectionEnabled(true);
scrollPane.setViewportView(table);
table.setColumnSelectionAllowed(true);
table.getColumnModel().getColumn(1).setCellEditor(new MandatoryStringCellEditor(new JTextField()));
table.getColumnModel().getColumn(3).setCellEditor(new UsernameCellEditor(new JTextField()));
JComboBox<EmployeeRole> roleComboBox = new JComboBox<EmployeeRole>();
roleComboBox.addItem(EmployeeRole.Administrator);
roleComboBox.addItem(EmployeeRole.Courier);
roleComboBox.addItem(EmployeeRole.OrderTaker);
table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(roleComboBox));
JLabel lblNewLabel = new JLabel(" ");
add(lblNewLabel, "cell 0 4");
btnAddEmployee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
employeeTable.addRow(new Employee());
btnAddEmployee.setEnabled(false);
}
});
btnRemoveEmployee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.getCellEditor() != null)
table.getCellEditor().cancelCellEditing();
int selectedRow = table.getSelectedRow();
System.out.println("Selected Row: " + selectedRow);
Employee employee = employeeTable.employees.get(selectedRow);
if (employee.id != 0) {
if (!CourierSystem.currentUser.equals(employee)) {
employee.ArchiveEmployee();
saveAction();
}
else {
JOptionPane.showMessageDialog(btnRemoveEmployee, "You cannot delete yourself.");
}
}
employeeTable.removeRow(selectedRow);
btnAddEmployee.setEnabled(true);
}
});
btnSaveChanges.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveAction();
btnAddEmployee.setEnabled(true);
}
});
}
private void saveAction() {
if (!TableValidator.isValid(table))
return;
try {
UUID uuid = UUID.randomUUID();
CourierSystem.Employees = new HashMap<String, Employee>();
for (Employee emp : employeeTable.employees) {
if (emp.userName == "" && emp.role == EmployeeRole.Courier) {
emp.userName = "courier" + uuid.toString();
}
CourierSystem.Employees.put(emp.name, emp);
}
CourierSystem.UpdateEmployees();
} catch (Exception e1) {
e1.printStackTrace();
} finally {
employeeTable.refresh();
}
}
}
| mit |
saibot94/city-graph-pIII | src/city/test1/Station.java | 433 | package city.test1;
/**
* @author chris Class representing one of the many possible stations found in
* an intersection.
*/
public class Station {
private String name;
public Station(String name) {
this.name = name;
}
/**
*
* @return Returns the station name.
*/
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.name;
}
}
| mit |
iMartinezMateu/gamecraft | gamecraft-sonar-manager/src/main/java/com/gamecraft/config/AsyncConfiguration.java | 1786 | package com.gamecraft.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final JHipsterProperties jHipsterProperties;
public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
executor.setThreadNamePrefix("gamecraftsonarmanager-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
| mit |
wwesantos/Java-Design-Patterns | FACTORY/Eagle.java | 263 | public class Eagle implements Animal {
/**
* Constructor with package access only
* Only classes in the same package can instantiate it, like the AnimalFactory
*/
Eagle(){}
@Override
public void move() {
System.out.println("Eagle flying...");
}
}
| mit |
lany/phototagger | src/com/drew/metadata/exif/KyoceraMakernoteDescriptor.java | 2815 | /*
* Copyright 2002-2011 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.metadata.exif;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.TagDescriptor;
/**
* Provides human-readable string representations of tag values stored in a <code>KyoceraMakernoteDirectory</code>.
* <p/>
* Some information about this makernote taken from here:
* http://www.ozhiker.com/electronics/pjmt/jpeg_info/kyocera_mn.html
* <p/>
* Most manufacturer's MakerNote counts the "offset to data" from the first byte
* of TIFF header (same as the other IFD), but Kyocera (along with Fujifilm) counts
* it from the first byte of MakerNote itself.
*
* @author Drew Noakes http://drewnoakes.com
*/
public class KyoceraMakernoteDescriptor extends TagDescriptor<KyoceraMakernoteDirectory>
{
public KyoceraMakernoteDescriptor(@NotNull KyoceraMakernoteDirectory directory)
{
super(directory);
}
@Nullable
public String getDescription(int tagType)
{
switch (tagType) {
case KyoceraMakernoteDirectory.TAG_KYOCERA_PRINT_IMAGE_MATCHING_INFO:
return getPrintImageMatchingInfoDescription();
case KyoceraMakernoteDirectory.TAG_KYOCERA_PROPRIETARY_THUMBNAIL:
return getProprietaryThumbnailDataDescription();
default:
return super.getDescription(tagType);
}
}
@Nullable
public String getPrintImageMatchingInfoDescription()
{
byte[] bytes = _directory.getByteArray(KyoceraMakernoteDirectory.TAG_KYOCERA_PRINT_IMAGE_MATCHING_INFO);
if (bytes==null)
return null;
return "(" + bytes.length + " bytes)";
}
@Nullable
public String getProprietaryThumbnailDataDescription()
{
byte[] bytes = _directory.getByteArray(KyoceraMakernoteDirectory.TAG_KYOCERA_PROPRIETARY_THUMBNAIL);
if (bytes==null)
return null;
return "(" + bytes.length + " bytes)";
}
}
| mit |
thomasjbarry/Image-Craft | tzk.imagecraft/src/tzk/image/tool/Fill.java | 11078 | /* The MIT License (MIT)
Copyright (c) 2014 Thomas James Barry, Zachary Y. Gateley, Kenneth Drew Gonzales
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package tzk.image.tool;
import java.awt.event.MouseEvent;
import tzk.image.ui.*;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.SwingUtilities;
/**
* Fill allows users to paint a whole area of the same color, with a
* single color.
*
* Contributers: Thomas James Barry/ thomasbarry92@gmail.com /5076942
* Zachary Gateley/ zach.cykic@gmail.com /5415772
* K Drew Gonzales/ drewgonzales360@gmail.com /5470602
*/
public class Fill extends SimpleTool {
public Fill(ImageCraft iC) {
super(iC);
imageCraft = iC;
super.setButton(imageCraft.jFill);
}
/**
* Bucket fill.
* If the pixel clicked on is a different color than the current color
* from ImageCraft (primaryColor for left mouse button, secondaryColor
* for right mouse button), change color of this pixel and all adjacent
* pixels of the same color to the current color.
* @param evt
*/
@Override
public void mousePressed(MouseEvent evt) {
// Get the color that we're working with
// Left button clicked: use primary color
// Right button clicked: use secondary color
Color toColor = imageCraft.getPaintColor(!SwingUtilities.isRightMouseButton(evt));
// The point clicked on
// These integers variables will be reused in our loop
int x = evt.getX();
int y = evt.getY();
// The current, visible BufferedImage canvas area
BufferedImage image = imageCraft.drawingArea.getCurrentDrawing();
// This is the color that we will paint over.
// Second parameter of Color constructor keeps alpha channel
Color fromColor = new Color(image.getRGB(x, y), true);
// Make sure that we clicked on a color that is not the color to paint with
if (toColor.equals(fromColor)) {
// If it is the same color, do nothing.
System.out.println("Cannot fill. Clicked same color.");
System.out.println("toColor: "+toColor);
System.out.println("fromColor: "+fromColor);
return;
}
// FILL
// Create stack of coordinate points to fill
// Each coordinate takes up two elements, x on even number, y on odd number
// For each coordinate in the stack, pull the pen up. Go upwards until
// the color is no longer threshold distance from fromColor.
// Then put the pen down and start drawing downwards until the color
// is no longer threshold distance from fromColor.
// On the way down, check left and right. If the side color is
// threshold distance from fromColor, add that point to the stack,
// if a point on that unbroken line segment has not already been
// added to the stack.
ArrayList<Integer> stack = new ArrayList<>();
stack.add(x);
stack.add(y);
// Create a new BufferedImage object
// This will be sent to SimpleHistory constructor
BufferedImage fillImage = imageCraft.newBlankImage();
Graphics fillGraphics = fillImage.getGraphics();
// The graphics object of the BufferedImage itself
Graphics imageGraphics = image.getGraphics();
// Set the color of the graphics object to our paint color
fillGraphics.setColor(toColor);
imageGraphics.setColor(toColor);
// This will represent the pixel being checked
Color color;
// colorDistance from fromColor that passes as a pixel to be painted
// Maybe we can let the user select this?
int threshold = 50;
// Whether we need to check the left side or the right side
boolean checkLeft, checkRight;
// Draw the line segment once, not once per pixel
// This remembers where to start drawing the line
int yTop;
// Remember image width and height since they are used within the loop
int width = image.getWidth();
int height = image.getHeight();
// Loop through each coordinate in the stack
while (stack.size() > 0) {
// Get x, y coordinates, the first two elements in the stack
x = stack.remove(0);
y = stack.remove(0);
yTop = y;
// Go to top of line, pen up (not painting)
while (y > 0) {
color = new Color(image.getRGB(x, y - 1), true);
if (colorDistance(color, fromColor) > threshold) {
break;
}
y--;
}
// Reset booleans to true. We want to start checking the sides
// of our line immediately
checkLeft = true;
checkRight = true;
// Start painting downwards, checking left and right as we go
while (y < height) {
color = new Color(image.getRGB(x, y), true);
// Hit a barrier. Stop.
if (colorDistance(color, fromColor) > threshold) {
break;
}
// Check left
// Only check up until the left side of the image
if (x > 0) {
color = new Color(image.getRGB(x - 1, y), true);
// If color.equals(toColor), then we have already painted
// this pixel
if (!color.equals(toColor) &&
colorDistance(color, fromColor) <= threshold) {
// If we haven't seen a pixel on the left side that we
// want to fill yet, be vigilant
if (checkLeft) {
// We have a match!
// Add coordinates to stack
stack.add(x - 1);
stack.add(y);
// Stop looking on the left side
checkLeft = false;
}
}
// Otherwise, when we see something that we do *not* want
// to fill, start being vigilant again for a pixel to fill
else {
checkLeft = true;
}
}
// Check right
// Only check up to the right side of the image
if (x < width - 1) {
color = new Color(image.getRGB(x + 1, y), true);
// If color.equals(toColor), then we have already painted
// this pixel
if (!color.equals(toColor) &&
colorDistance(color, fromColor) <= threshold) {
// If we haven't seen a pixel on the right side that we
// want to fill yet, be vigilant
if (checkRight) {
// We have a match!
// Add coordinates to stack
stack.add(x + 1);
stack.add(y);
// Stop looking on the right side
checkRight = false;
}
}
// Otherwise, when we see something that we do *not* want
// to fill, start being vigilant again for a pixel to fill
else {
checkRight = true;
}
}
// Increment row, get new color for condition and loop
y++;
}
// Draw the column's line in both the action image
// and the currentImage. We need it
fillGraphics.drawLine(x, yTop, x, y - 1);
imageGraphics.drawLine(x, yTop, x, y - 1);
}
// Draw our final image
imageCraft.drawingArea.getGraphics().drawImage(image, 0, 0, null);
imageCraft.drawingArea.getGraphics().drawImage(fillImage, 0, 0, null);
// Create new history object in layer
imageCraft.currentLayer.addHistory(fillImage, "Fill");
}
/**
* Do nothing. Fill only works on mousePressed.
* @param evt
*/
@Override
public void mouseDragged(MouseEvent evt) {
}
/**
* Do nothing. Fill only works on mousePressed.
*
* @param evt
*/
@Override
public void mouseReleased(MouseEvent evt) {
}
/**
* Checks the length of the distance between two colors in RGBA four space.
* This method plots out the coordinates of the channels of two colors
* passed as parameters into four space and calculates the length
* of the line segment connecting the two points.
*
* @param color1
* @param color2
* @return
*/
private int colorDistance(Color color1, Color color2) {
int r1 = color1.getRed();
int g1 = color1.getGreen();
int b1 = color1.getBlue();
int a1 = color1.getAlpha();
int r2 = color2.getRed();
int g2 = color2.getGreen();
int b2 = color2.getBlue();
int a2 = color2.getAlpha();
return (int) Math.sqrt(Math.pow(r2 - r1, 2) + Math.pow(g2 - g1, 2) + Math.pow(b2 - b1, 2) + Math.pow(a2 - a1, 2));
}
// Variables declaration
private final ImageCraft imageCraft;
// End of variables declaration
}
| mit |
clusterpoint/java-client-api | src/com/clusterpoint/api/request/CPSPartialReplaceRequest.java | 1298 | package com.clusterpoint.api.request;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Node;
/**
* The CPSPartialReplaceRequest class is a wrapper for the CPSModifyRequest class for the partial-replace command
* @see com.clusterpoint.api.response.CPSModifyResponse
*/
public class CPSPartialReplaceRequest extends CPSModifyRequest {
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
*/
public CPSPartialReplaceRequest() {
super("partial-replace");
}
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
* @param id document id
* @param document replaceable document contents
*/
public CPSPartialReplaceRequest(String id, String document) {
super("partial-replace");
Map<String, String> map = new HashMap<String, String>();
map.put(id, document);
this.setDocuments(map);
}
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
* @param document replaceable document content with document id in it
*/
public CPSPartialReplaceRequest(String document) {
super("partial-replace", document);
}
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
* @param document Document as DOM Node
*/
public CPSPartialReplaceRequest(Node document) {
super("partial-replace", document);
}
}
| mit |
jackwickham/authenticator | app/src/main/java/net/jackw/authenticator/Totp.java | 1847 | package net.jackw.authenticator;
public class Totp extends HotpGenerator {
private int interval = 30;
private String cachedCode;
private long cachedSeed = 0;
private static final int DEFAULT_INTERVAL = 30;
public Totp (byte[] secret) {
super(secret);
this.interval = DEFAULT_INTERVAL;
}
public Totp (byte[] secret, HashAlgorithm hashAlgorithm, int length, int interval) {
super(secret, hashAlgorithm, length);
if (interval < 10 || interval > 180) {
throw new IllegalArgumentException("Interval must be between 10 and 180 seconds");
}
this.interval = interval;
}
public Totp (String extra) throws CodeGeneratorConstructionException {
super(extra);
try {
this.interval = Integer.parseInt(extra.split(",")[3]);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
throw new CodeGeneratorConstructionException("Extra string was invalid", e);
}
}
@Override
public String generateCode() {
// Convert the time in milliseconds to the number of 30s intervals since the epoch
long seed = TimeProvider.getInstance().now() / (interval * 1000);
return generateHotp(seed);
}
@Override
public String getExtra () {
String result = super.getExtra();
result += "," + Long.toString(interval);
return result;
}
@Override
public Type getType () {
return Type.TOTP;
}
@Override
public String getCodeForDisplay () {
// Check if the code needs regenerating
if (cachedSeed != TimeProvider.getInstance().now() / (interval * 1000)) {
cachedCode = generateCode();
cachedSeed = TimeProvider.getInstance().now() / (interval * 1000);
}
return cachedCode;
}
public float getTimeRemainingFraction () {
return (TimeProvider.getInstance().now() % (interval * 1000)) / (interval * 1000.0f);
}
public void setInterval (int interval) {
this.interval = interval;
}
}
| mit |
jemmele06/BattleBots | src/World.java | 187 | /**
* World interface that represents the entire play area.
*/
public interface World {
public boolean contains(Bot bot);
public int getHeight();
public int getWidth();
}
| mit |
haducloc/appslandia-plum | src/test/java/com/appslandia/plum/web/HstsBuilderTest.java | 908 | package com.appslandia.plum.web;
import org.junit.Assert;
import org.junit.Test;
public class HstsBuilderTest {
@Test
public void testHstsBuilder_includeSubDomains() {
HstsBuilder hsts = new HstsBuilder();
hsts.includeSubDomains(true);
Assert.assertTrue(hsts.toString().contains("includeSubDomains"));
}
@Test
public void testHstsBuilder_maxAge() {
HstsBuilder hsts = new HstsBuilder();
hsts.maxAge(100_000);
Assert.assertTrue(hsts.toString().contains("max-age=100000"));
}
@Test
public void testHstsBuilder_preload() {
HstsBuilder hsts = new HstsBuilder();
hsts.preload();
Assert.assertTrue(hsts.toString().contains("preload"));
}
@Test
public void testHstsBuilder_all() {
HstsBuilder hsts = new HstsBuilder();
hsts.maxAge(100000).includeSubDomains(true).preload();
Assert.assertTrue(hsts.toString().contains("max-age=100000; includeSubDomains; preload"));
}
}
| mit |
herveyw/azure-sdk-for-java | azure/src/test/java/com/microsoft/azure/management/TestUtils.java | 6137 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management;
import com.microsoft.azure.management.compute.VirtualMachine;
import com.microsoft.azure.management.compute.DataDisk;
/**
* Test utilities.
*/
public final class TestUtils {
private TestUtils() {
}
/**
* Shows the virtual machine.
* @param resource virtual machine to show
*/
public static void print(VirtualMachine resource) {
StringBuilder storageProfile = new StringBuilder().append("\n\tStorageProfile: ");
if (resource.storageProfile().imageReference() != null) {
storageProfile.append("\n\t\tImageReference:");
storageProfile.append("\n\t\t\tPublisher: ").append(resource.storageProfile().imageReference().publisher());
storageProfile.append("\n\t\t\tOffer: ").append(resource.storageProfile().imageReference().offer());
storageProfile.append("\n\t\t\tSKU: ").append(resource.storageProfile().imageReference().sku());
storageProfile.append("\n\t\t\tVersion: ").append(resource.storageProfile().imageReference().version());
}
if (resource.storageProfile().osDisk() != null) {
storageProfile.append("\n\t\tOSDisk:");
storageProfile.append("\n\t\t\tOSType: ").append(resource.storageProfile().osDisk().osType());
storageProfile.append("\n\t\t\tName: ").append(resource.storageProfile().osDisk().name());
storageProfile.append("\n\t\t\tCaching: ").append(resource.storageProfile().osDisk().caching());
storageProfile.append("\n\t\t\tCreateOption: ").append(resource.storageProfile().osDisk().createOption());
storageProfile.append("\n\t\t\tDiskSizeGB: ").append(resource.storageProfile().osDisk().diskSizeGB());
if (resource.storageProfile().osDisk().image() != null) {
storageProfile.append("\n\t\t\tImage Uri: ").append(resource.storageProfile().osDisk().image().uri());
}
if (resource.storageProfile().osDisk().vhd() != null) {
storageProfile.append("\n\t\t\tVhd Uri: ").append(resource.storageProfile().osDisk().vhd().uri());
}
if (resource.storageProfile().osDisk().encryptionSettings() != null) {
storageProfile.append("\n\t\t\tEncryptionSettings: ");
storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled());
storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource
.storageProfile()
.osDisk()
.encryptionSettings()
.diskEncryptionKey().secretUrl());
storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource
.storageProfile()
.osDisk()
.encryptionSettings()
.keyEncryptionKey().keyUrl());
}
}
if (resource.storageProfile().dataDisks() != null) {
int i = 0;
for (DataDisk disk : resource.storageProfile().dataDisks()) {
storageProfile.append("\n\t\tDataDisk: #").append(i++);
storageProfile.append("\n\t\t\tName: ").append(disk.name());
storageProfile.append("\n\t\t\tCaching: ").append(disk.caching());
storageProfile.append("\n\t\t\tCreateOption: ").append(disk.createOption());
storageProfile.append("\n\t\t\tDiskSizeGB: ").append(disk.diskSizeGB());
storageProfile.append("\n\t\t\tLun: ").append(disk.lun());
if (disk.vhd().uri() != null) {
storageProfile.append("\n\t\t\tVhd Uri: ").append(disk.vhd().uri());
}
if (disk.image() != null) {
storageProfile.append("\n\t\t\tImage Uri: ").append(disk.image().uri());
}
}
}
StringBuilder osProfile = new StringBuilder().append("\n\tOSProfile: ");
osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName());
if (resource.osProfile().windowsConfiguration() != null) {
osProfile.append("\n\t\t\tWindowsConfiguration: ");
osProfile.append("\n\t\t\t\tProvisionVMAgent: ")
.append(resource.osProfile().windowsConfiguration().provisionVMAgent());
osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ")
.append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates());
osProfile.append("\n\t\t\t\tTimeZone: ")
.append(resource.osProfile().windowsConfiguration().timeZone());
}
if (resource.osProfile().linuxConfiguration() != null) {
osProfile.append("\n\t\t\tLinuxConfiguration: ");
osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ")
.append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication());
}
StringBuilder networkProfile = new StringBuilder().append("\n\tNetworkProfile: ");
for (String networkInterfaceId : resource.networkInterfaceIds()) {
networkProfile.append("\n\t\tId:").append(networkInterfaceId);
}
System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id())
.append("Name: ").append(resource.name())
.append("\n\tResource group: ").append(resource.resourceGroupName())
.append("\n\tRegion: ").append(resource.region())
.append("\n\tTags: ").append(resource.tags())
.append("\n\tHardwareProfile: ")
.append("\n\t\tSize: ").append(resource.size())
.append(storageProfile)
.append(osProfile)
.append(networkProfile)
.toString());
}
}
| mit |
yangyangv2/leet-code | problems/src/main/java/prob547/friend/circles/Solution.java | 1293 | package prob547.friend.circles;
/**
* Created by yanya04 on 2/20/2018.
*/
public class Solution {
private static class UFSet {
private int[] parents;
UFSet(int m){
this.parents = new int[m];
for(int i = 0; i < m; i ++){
parents[i] = i;
}
}
private int find(int p){
while(parents[p] != p){
parents[p] = parents[parents[p]];
p = parents[p];
}
return p;
}
boolean union(int i, int j){
int p1 = find(i);
int p2 = find(j);
if(p1 == p2) return false;
if(p1 < p2){
parents[p2] = p1;
} else {
parents[p1] = p2;
}
return true;
}
}
public int findCircleNum(int[][] M) {
if(M == null || M.length == 0) return 0;
int n = M.length;
int count = n;
UFSet set = new UFSet(n);
for(int i = 0; i < n; i ++){
for(int j = i + 1; j < n; j ++){
if(M[i][j] == 1){
if(set.union(i, j)){
count --;
}
}
}
}
return count;
}
} | mit |
StayHungryStayFoolish/stayhungrystayfoolish.github.com | JavaSE/src/main/java/basic/SubModifierDemo.java | 662 | package basic;
/**
* Created by bonismo
* 14/10/17 上午9:43
*/
public class SubModifierDemo extends ModifierDemo {
public SubModifierDemo() {
}
public static void main(String[] args) {
SubModifierDemo subModifierDemo = new SubModifierDemo();
System.out.println(subModifierDemo.i);
System.out.println(subModifierDemo.i1);
// private 子类继承了父类,依然不能调用父类的私有域、方法
System.out.println(subModifierDemo.i3);
System.out.println(subModifierDemo.name);
System.out.println(subModifierDemo.name1);
System.out.println(subModifierDemo.name3);
}
}
| mit |
zhqhzhqh/FbreaderJ | app/src/main/java/org/geometerplus/android/fbreader/OpenWebHelpAction.java | 1734 | /*
* Copyright (C) 2010-2015 FBReader.ORG Limited <contact@fbreader.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.net.Uri;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
class OpenWebHelpAction extends FBAndroidAction {
OpenWebHelpAction(FBReader baseActivity, FBReaderApp fbreader) {
super(baseActivity, fbreader);
}
@Override
protected void run(Object ... params) {
final String url = ZLResource.resource("links").getResource("faqPage").getValue();
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
new Thread(new Runnable() {
public void run() {
BaseActivity.runOnUiThread(new Runnable() {
public void run() {
try {
BaseActivity.startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
}
| mit |
noveris/HashTableDemo | HashTableDemo/src/edu/cpp/cs/cs240/prog_assgnmnt_5/Student.java | 1717 | /**
* CS 240: Introduction to Data Structures
* Professor: Edwin Rodríguez
*
* Programming Assignment #5
*
* Assignment #5 is meant to grant a thorough understanding of the hash table
* data structure, the hash functions used by hash tables, as well as the stack
* and queue data structures. Expected is an implementation of a hash table able
* to utilize different hash functions, an implementation of a 'scrambled' version
* of rotational hashing using a stack and a queue, and a simple program which
* uses a hash table as a registry of student records.
*
* Carlos Marquez
*/
package edu.cpp.cs.cs240.prog_assgnmnt_5;
public class Student implements Comparable<Student> {
private String ID;
private String name;
private String grade;
Student(String ID, String name, String grade) {
this.ID = ID;
this.name = name;
this.grade = grade;
}
public String getID() {
return this.ID;
}
public String getKey() {
return this.ID;
}
public String getName() {
return this.name;
}
public String getGrade() {
return this.grade;
}
@Override
public boolean equals(Object o) {
if (o.getClass() != String.class) { //if o is not a String (key not passed)
Student s = (Student) o;
if ((this.ID.equals(s.getID())) && (this.name.equals(s.getName())) && (this.grade.equals(s.getGrade()))) {
return true;
}
}
if (o.getClass() == String.class) { //a key was passed as argument
if (this.getID().equals(o)) {
return true;
}
}
return false;
}
@Override
public int compareTo(Student s) {
String ID1 = this.ID;
String ID2 = s.ID;
return ID1.compareTo(ID2);
}
} | mit |
Thaylles/Projeto_Corretor | src/controlador/ListaControlador.java | 630 | package controlador;
import java.util.ArrayList;
import java.util.HashMap;
import modelo.Palavras;
import modelo.Texto;
import persistencia.PalavrasDAO;
import persistencia.TextoDAO;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.TemplateViewRoute;
public class ListaControlador implements TemplateViewRoute {
private PalavrasDAO dao = new PalavrasDAO();
public ModelAndView handle(Request req, Response resp) {
ArrayList<Palavras> sinonimos = dao.findAll();
HashMap mapa = new HashMap();
mapa.put("sinonimos", sinonimos);
return new ModelAndView(mapa, "lista.html");
}
}
| mit |
mestachs/archeo4j | archeo4j-core/src/main/java/org/archeo4j/core/analyzer/ClassAnalyzer.java | 4707 | package org.archeo4j.core.analyzer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javassist.ByteArrayClassPath;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.annotation.Annotation;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
import org.archeo4j.core.model.AnalyzedAnnotation;
import org.archeo4j.core.model.AnalyzedClass;
import org.archeo4j.core.model.AnalyzedMethod;
public class ClassAnalyzer {
private AnalyzisConfig analyzisConfig;
public ClassAnalyzer(AnalyzisConfig analyzisConfig) {
this.analyzisConfig = analyzisConfig;
}
public AnalyzedClass analyzeCallsForClass(String className, byte[] classBytes, String location) {
if (!analyzisConfig.classFilter().test(className))
return null;
AnalyzedClass analyzedClass = new AnalyzedClass(className);
ClassPool cp = new ClassPool();
CtClass ctClass = parseClassByteCode(className, classBytes, cp);
analyzeClassAnnotations(analyzedClass, ctClass);
analyzeInterfaces(analyzedClass, ctClass);
try {
CtMethod[] methods = ctClass.getDeclaredMethods();
for (CtMethod ctMethod : methods) {
AnalyzedMethod method = analyzeMethodCalls(ctMethod);
analyzeMethodAnnotations(method, ctMethod);
analyzedClass.addAnalyzedMethod(method);
}
} catch (RuntimeException e) {
System.out.println("WARN !! failed to analyze " + className + " " + e.getMessage());
}
return analyzedClass;
}
private void analyzeInterfaces(AnalyzedClass analyzedClass, CtClass ctClass) {
analyzedClass.setInterfaceNames(Arrays.asList(ctClass.getClassFile2().getInterfaces()));
analyzedClass.setSuperClassName(ctClass.getClassFile2().getSuperclass());
}
private void analyzeClassAnnotations(AnalyzedClass analyzedClass, CtClass ctClass) {
List<AnalyzedAnnotation> annotations = new ArrayList<>();
for (Object o : ctClass.getClassFile2().getAttributes()) {
if (o instanceof AnnotationsAttribute) {
AnnotationsAttribute attribute = (AnnotationsAttribute) o;
for (Annotation analyzedAnnotation : attribute.getAnnotations()) {
annotations.add(new AnalyzedAnnotation(analyzedAnnotation.toString()));
}
}
}
analyzedClass.setAnnotations(annotations);
}
private void analyzeMethodAnnotations(AnalyzedMethod method, CtMethod ctMethod) {
List<AnalyzedAnnotation> annotations = new ArrayList<>();
for (Object o : ctMethod.getMethodInfo().getAttributes()) {
if (o instanceof AnnotationsAttribute) {
AnnotationsAttribute attribute = (AnnotationsAttribute) o;
annotations.add(new AnalyzedAnnotation(attribute.toString()));
}
}
method.setAnnotations(annotations);
}
private CtClass parseClassByteCode(String className, byte[] classBytes, ClassPool cp) {
cp.appendClassPath(new ByteArrayClassPath(className, classBytes));
CtClass ctClass;
try {
ctClass = cp.get(className);
} catch (NotFoundException e1) {
throw new RuntimeException(e1);
}
return ctClass;
}
private AnalyzedMethod analyzeMethodCalls(CtMethod ctMethod) {
final List<AnalyzedMethod> methodsCalled = new ArrayList<AnalyzedMethod>();
try {
ctMethod.instrument(new ExprEditor() {
@Override
public void edit(MethodCall m) throws CannotCompileException {
if (analyzisConfig.classFilter().test(m.getClassName())) {
methodsCalled.add(asAnalyzedMethod(m));
}
}
});
} catch (CannotCompileException e) {
throw new RuntimeException(e);
}
AnalyzedMethod method = asAnalyzedMethod(ctMethod);
method.setCalledMethods(methodsCalled);
return method;
}
private static AnalyzedMethod asAnalyzedMethod(CtMethod ctMethod) {
String params =
(ctMethod.getLongName().replace(ctMethod.getDeclaringClass().getName(), "").replace("."
+ ctMethod.getName(), ""));
return new AnalyzedMethod(ctMethod.getDeclaringClass().getName(), ctMethod.getName(),
ctMethod.getGenericSignature() != null ? ctMethod.getGenericSignature()
: ctMethod.getSignature(), params, ctMethod.getModifiers());
}
private static AnalyzedMethod asAnalyzedMethod(MethodCall m) {
return new AnalyzedMethod(m.getClassName(), m.getMethodName(), m.getSignature());
}
}
| mit |
DevipriyaSarkar/Popular-Movies | app/src/main/java/com/example/devipriya/popularmovies/application/AppController.java | 1341 | package com.example.devipriya.popularmovies.application;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
/**
* Created by Devipriya on 25-Oct-15.
*/
public class AppController extends Application {
private static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
| mit |
CS2103JAN2017-W09-B4/main | src/main/java/seedu/task/model/task/PriorityLevel.java | 1885 | package seedu.task.model.task;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Task's priority level in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidPriorityLevel(String)}
*/
public class PriorityLevel {
public static final String MESSAGE_PRIORITY_LEVEL_CONSTRAINTS = "Priority Levels should be indicated by an integer,"
+ " ranging from 1 to 4; with 1 being the highest priority and 4 being the lowest priority.";
public static final String PRIORITY_LEVEL_VALIDATION_REGEX = "[1-4]";
public final String value;
/**
* Validates given priority level.
*
* @throws IllegalValueException if given priority level string is invalid.
*/
public PriorityLevel(String priority) throws IllegalValueException {
//assert priority != null;
String trimmedPriority = priority.trim();
if (trimmedPriority.equals("")) {
this.value = trimmedPriority;
} else {
if (!isValidPriorityLevel(trimmedPriority)) {
throw new IllegalValueException(MESSAGE_PRIORITY_LEVEL_CONSTRAINTS);
}
this.value = trimmedPriority;
}
}
/**
* Returns if a given string is a valid priority level.
*/
public static boolean isValidPriorityLevel(String test) {
return test.matches(PRIORITY_LEVEL_VALIDATION_REGEX);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof PriorityLevel // instanceof handles nulls
&& this.value.equals(((PriorityLevel) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| mit |
ribasco/async-gamequery-lib | protocols/valve/dota2/webapi/src/main/java/com/ibasco/agql/protocols/valve/dota2/webapi/pojos/Dota2MatchHistory.java | 3519 | /*
* MIT License
*
* Copyright (c) 2018 Asynchronous Game Query Library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.ibasco.agql.protocols.valve.dota2.webapi.pojos;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.ArrayList;
import java.util.List;
public class Dota2MatchHistory {
@SerializedName("status")
@Expose
private int status;
@SerializedName("num_results")
@Expose
private int numResults;
@SerializedName("total_results")
@Expose
private int totalResults;
@SerializedName("results_remaining")
@Expose
private int resultsRemaining;
@SerializedName("matches")
@Expose
private List<Dota2MatchHistoryInfo> matches = new ArrayList<>();
/**
* @return The status
*/
public int getStatus() {
return status;
}
/**
* @param status
* The status
*/
public void setStatus(int status) {
this.status = status;
}
/**
* @return The numResults
*/
public int getNumResults() {
return numResults;
}
/**
* @param numResults
* The num_results
*/
public void setNumResults(int numResults) {
this.numResults = numResults;
}
/**
* @return The totalResults
*/
public int getTotalResults() {
return totalResults;
}
/**
* @param totalResults
* The total_results
*/
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
/**
* @return The resultsRemaining
*/
public int getResultsRemaining() {
return resultsRemaining;
}
/**
* @param resultsRemaining
* The results_remaining
*/
public void setResultsRemaining(int resultsRemaining) {
this.resultsRemaining = resultsRemaining;
}
/**
* @return The matches
*/
public List<Dota2MatchHistoryInfo> getMatches() {
return matches;
}
/**
* @param matches
* The matches
*/
public void setMatches(List<Dota2MatchHistoryInfo> matches) {
this.matches = matches;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.NO_CLASS_NAME_STYLE);
}
}
| mit |
miroha/2015.2 | Examples/structs/src/main/java/ru/mirea/oop/practice/set/SetImpl.java | 5357 | package ru.mirea.oop.practice.set;
import java.util.Iterator;
@SuppressWarnings("unchecked")
public final class SetImpl<E> implements ISet<E> {
private int size;
private final Node<E>[] table;
public SetImpl(int capacity) {
table = (Node<E>[]) new Node[capacity];
}
public SetImpl() {
this(256);
}
private int indexOf(E element) {
if (element == null)
return 0;
return (table.length - 1) & hash(element);
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(E element) {
int i = indexOf(element);
int hash = hash(element);
Node<E> it;
if ((it = table[i]) == null)
return false;
if (it.hash == hash && element != null && element.equals(it.item))
return true;
while (it != null) {
if (it.next == null) {
break;
}
if (it.hash == hash && element != null && element.equals(it.item))
return true;
it = it.next;
}
return false;
}
@Override
public void put(E element) {
int i = indexOf(element);
int hash = hash(element);
Node<E> it;
if ((it = table[i]) == null) {
table[i] = new Node<>(null, element, null);
size++;
} else {
Node<E> exists = null;
if (it.hash == hash && element != null && element.equals(it.item)) {
exists = it;
} else {
while (it != null) {
if ((exists = it.next) == null) {
it.next = new Node<>(it, element, null);
break;
}
if (exists.hash == hash && element != null && element.equals(exists.item))
break;
it = it.next;
}
}
if (exists == null) {
size++;
}
}
}
private static <E> int hash(E element) {
return element.hashCode();
}
@Override
public void remove(E element) {
int i = indexOf(element);
int hash = hash(element);
Node<E> it = table[i];
if (it != null) {
if (it.hash == hash && element != null && element.equals(it.item)) {
table[i] = it.next;
--size;
} else {
Node<E> next = it;
while (next != null) {
if (it.hash == hash && element != null && element.equals(it.item)) {
Node<E> itNext = it.next;
Node<E> itPrev = it.prev;
itPrev.next = itNext;
if (itNext != null)
itNext.prev = itPrev;
--size;
break;
}
next = next.next;
}
}
}
}
@Override
public void clear() {
for (int i = 0; i < table.length; ++i)
table[i] = null;
size = 0;
}
@Override
public Iterator<E> iterator() {
return new IteratorImpl2(table);
}
private static final class Node<E> {
final E item;
final int hash;
Node<E> next;
Node<E> prev;
private Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
this.hash = hash(element);
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ISet) {
throw new RuntimeException("Not implement yet");
}
return super.equals(obj);
}
private final class IteratorImpl2 implements Iterator<E> {
private final Node<E> [] table;
private int nextIndex;
private Iterator<E> next;
public IteratorImpl2(Node<E>[] table) {
this.table = table;
this.nextIndex = 0;
next = new IteratorImpl(table[0]);
}
@Override
public boolean hasNext() {
if (nextIndex >= table.length)
return false;
if (next.hasNext())
return true;
while (nextIndex < table.length) {
next = new IteratorImpl(table[nextIndex]);
if (next.hasNext())
return true;
nextIndex++;
}
return nextIndex < table.length;
}
@Override
public E next() {
return next.next();
}
}
private final class IteratorImpl implements Iterator<E> {
private int nextIndex = 0;
private Node<E> next;
private Node<E> returned;
private IteratorImpl(Node<E> next) {
this.next = next;
}
@Override
public boolean hasNext() {
return nextIndex < size && next != null;
}
@Override
public E next() {
returned = next;
next = next.next;
nextIndex++;
return returned.item;
}
}
}
| mit |
StayHungryStayFoolish/stayhungrystayfoolish.github.com | Shoping_Management_System/src/main/java/repositories/Control/GoodsControl.java | 8118 | package repositories.Control;
import repositories.model.Goods;
import repositories.util.DB;
import repositories.util.ScannerChoice;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created by bonismo
* 15/7/18 下午4:04
* <p>
* 数据库 Goods 表 数据操作
*/
public final class GoodsControl {
private Connection connection = null;
private PreparedStatement statement = null;
ResultSet resultSet = null;
/**
* 添加商品信息 到数据库 Goods 商品表
*
* @param goods 商品模型类的实例
* @return boolean
*/
public boolean addGoods(Goods goods) {
boolean flag = false;
String sqlAdd = "INSERT INTO db_shopping_management.goods VALUES (NULL , ?, ?, ?);";
connection = DB.getConnection();
statement = null;
try {
if (connection != null) {
statement = connection.prepareStatement(sqlAdd);
} else {
return false;
}
statement.setString(1, goods.getGoods_name());
statement.setDouble(2, goods.getGoods_price());
statement.setInt(3, goods.getGoods_num());
int rs = statement.executeUpdate();
if (rs > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(null, statement, connection);
}
return flag;
}
/**
* 商品信息更新 Goods 商品表
*
* @param key 更改商品的选项
* @param goods 商品模型类的实例
* @return boolean
*/
public boolean updateGoods(int key, Goods goods) {
boolean flag = false;
connection = DB.getConnection();
switch (key) {
case 1: // key = 1,更改商品名称
String updateName = "UPDATE db_shopping_management.goods SET goods_name = ? WHERE id = ?";
try {
if (connection != null) {
statement = connection.prepareStatement(updateName);
} else {
return false;
}
statement.setString(1, goods.getGoods_name());
statement.setInt(2, goods.getId());
int rs = statement.executeUpdate();
if (rs > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(null, statement, connection);
}
break;
case 2: // key = 2 ,更改商品价格
String updatePrice = "UPDATE db_shopping_management.goods SET goods_price = ? WHERE id = ?";
try {
if (connection != null) {
statement = connection.prepareStatement(updatePrice);
} else {
return false;
}
statement.setDouble(1, goods.getGoods_price());
statement.setInt(2, goods.getId());
int rs = statement.executeUpdate();
if (rs > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(null, statement, connection);
}
break;
case 3: // key = 3 ,更改商品数量
String updateNum = "UPDATE db_shopping_management.goods SET goods_num = ? WHERE id = ?";
try {
statement = connection.prepareStatement(updateNum);
statement.setInt(1, goods.getGoods_num());
statement.setInt(2, goods.getId());
int rs = statement.executeUpdate();
if (rs > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(null, statement, connection);
}
break;
default:
break;
}
return flag;
}
/**
* 删除商品信息 Goods 商品表
*
* @param id 商品表的 主键 ID
* @return boolean
*/
public boolean deleteGoods(int id) {
boolean flag = false;
connection = DB.getConnection();
String deleteId = "DELETE FROM db_shopping_management.goods WHERE id = ?";
try {
statement = connection.prepareStatement(deleteId);
statement.setInt(1, id);
int rs = statement.executeUpdate();
if (rs > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(null, statement, connection);
}
return flag;
}
/**
* 查询 方法重构
*
* @param goodsArrayList 商品信息集合容器
* @param query Mysql 查询语句
*/
public static void queryAll(ArrayList<Goods> goodsArrayList, String query) {
Connection connection = DB.getConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = connection.prepareStatement(query);
resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String goods_name = resultSet.getString("goods_name");
Double goods_price = resultSet.getDouble("goods_price");
int goods_num = resultSet.getInt("goods_num");
// 获取结果集,根据有参构造,传参
Goods goods = new Goods(id, goods_name, goods_price, goods_num);
// 将类信息添加到集合容器
goodsArrayList.add(goods);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(resultSet, statement, connection);
}
}
/**
* 查询商品信息
*
* @param key 查询选项
* @return ArrayList<Goods>
*/
public ArrayList<Goods> queryGoods(int key) {
ArrayList<Goods> goodsArrayList = new ArrayList<>();
connection = DB.getConnection();
switch (key) {
case 1: // 查询商品数量,默认升序
String selNum = "SELECT * FROM db_shopping_management.goods ORDER BY goods_num";
queryAll(goodsArrayList, selNum);
break;
case 2: // 查询商品价格,默认升序
String selPrice = "SELECT * FROM db_shopping_management.goods ORDER BY goods_price";
queryAll(goodsArrayList, selPrice);
break;
case 3: // 查询商品名字
String nameGet = ScannerChoice.scannerInfoString();
nameGet = "%" + nameGet + "%";
String sqlGoodsName = "SELECT * FROM db_shopping_management.goods WHERE goods.goods_name LIKE ?";
connection = DB.getConnection();
try {
statement = connection.prepareStatement(sqlGoodsName);
statement.setString(1, nameGet);
} catch (SQLException e) {
e.printStackTrace();
}
}
return goodsArrayList;
}
/**
* 显示商品所有信息
*
* @return ArrayList<Goods>
*/
public ArrayList<Goods> displayGoods() {
ArrayList<Goods> goodsArrayList = new ArrayList<>();
String query = "SELECT * FROM db_shopping_management.goods";
queryAll(goodsArrayList, query);
return goodsArrayList;
}
}
| mit |
venrad/Hive | udf/src/test/java/com/venk/hive/udf/AppTest.java | 645 | package com.venk.hive.udf;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| mit |
optimaize/webcrawler-verifier | src/main/java/com/optimaize/webcrawlerverifier/bots/GooglebotData.java | 1358 | package com.optimaize.webcrawlerverifier.bots;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Set;
/**
* Resources:
* http://en.wikipedia.org/wiki/Googlebot
* https://support.google.com/webmasters/answer/80553
*/
public class GooglebotData implements CrawlerData {
private static final Predicate<String> PREDICATE = new Predicate<String>() {
@Override
public boolean apply(String userAgent) {
if (userAgent.contains("Googlebot")) return true;
return false;
}
};
private static final ImmutableSet<String> HOSTNAMES = ImmutableSet.of("googlebot.com");
private static final GooglebotData INSTANCE = new GooglebotData();
public static GooglebotData getInstance() {
return INSTANCE;
}
private GooglebotData() {
}
@NotNull
@Override
public String getIdentifier() {
return "GOOGLEBOT";
}
@NotNull
@Override
public Predicate<String> getUserAgentChecker() {
return PREDICATE;
}
@NotNull
@Override
public Set<String> getIps() {
return Collections.emptySet();
}
@NotNull
@Override
public Set<String> getHostnames() {
return HOSTNAMES;
}
}
| mit |
relimited/HearthSim | src/test/java/com/hearthsim/test/spell/TestClaw.java | 4085 | package com.hearthsim.test.spell;
import com.hearthsim.card.Card;
import com.hearthsim.card.basic.spell.Claw;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.MinionMock;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class TestClaw {
private HearthTreeNode board;
private PlayerModel currentPlayer;
private PlayerModel waitingPlayer;
private static final byte mana = 2;
private static final byte attack0 = 5;
private static final byte health0 = 3;
private static final byte health1 = 7;
@Before
public void setup() throws HSException {
board = new HearthTreeNode(new BoardModel());
currentPlayer = board.data_.getCurrentPlayer();
waitingPlayer = board.data_.getWaitingPlayer();
Minion minion0_0 = new MinionMock("" + 0, mana, attack0, health0, attack0, health0, health0);
Minion minion0_1 = new MinionMock("" + 0, mana, attack0, (byte)(health1 - 1), attack0, health1, health1);
Minion minion1_0 = new MinionMock("" + 0, mana, attack0, health0, attack0, health0, health0);
Minion minion1_1 = new MinionMock("" + 0, mana, attack0, (byte)(health1 - 1), attack0, health1, health1);
board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, minion0_0);
board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, minion0_1);
board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion1_0);
board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion1_1);
Claw fb = new Claw();
currentPlayer.placeCardHand(fb);
currentPlayer.setMana((byte) 10);
currentPlayer.setMaxMana((byte) 10);
}
@Test
public void test2() throws HSException {
Card theCard = currentPlayer.getHand().get(0);
HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, 0, board);
assertFalse(ret == null);
assertEquals(currentPlayer.getHand().size(), 0);
assertEquals(currentPlayer.getNumMinions(), 2);
assertEquals(waitingPlayer.getNumMinions(), 2);
assertEquals(currentPlayer.getHero().getHealth(), 30);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getHero().getTotalAttack(), 2);
assertEquals(currentPlayer.getHero().getExtraAttackUntilTurnEnd(), 2);
assertEquals(currentPlayer.getHero().getArmor(), 2);
assertEquals(currentPlayer.getCharacter(1).getHealth(), health0);
assertEquals(currentPlayer.getCharacter(2).getHealth(), health1 - 1);
assertEquals(waitingPlayer.getCharacter(1).getHealth(), health0);
assertEquals(waitingPlayer.getCharacter(2).getHealth(), health1 - 1);
ret = currentPlayer.getHero().attack(PlayerSide.WAITING_PLAYER, 1, board, false);
assertFalse(ret == null);
assertEquals(currentPlayer.getNumMinions(), 2);
assertEquals(waitingPlayer.getNumMinions(), 2);
assertEquals(currentPlayer.getHero().getHealth(), 27);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getHero().getTotalAttack(), 2);
assertEquals(currentPlayer.getHero().getExtraAttackUntilTurnEnd(), 2);
assertEquals(currentPlayer.getHero().getArmor(), 0);
assertEquals(currentPlayer.getCharacter(1).getHealth(), health0);
assertEquals(currentPlayer.getCharacter(2).getHealth(), health1 - 1);
assertEquals(waitingPlayer.getCharacter(1).getHealth(), health0 - 2);
assertEquals(waitingPlayer.getCharacter(2).getHealth(), health1 - 1);
currentPlayer.getHero().endTurn(PlayerSide.CURRENT_PLAYER, board);
assertEquals(currentPlayer.getHero().getTotalAttack(), 0);
assertEquals(currentPlayer.getHero().getArmor(), 0);
}
}
| mit |
0xpr03/VocableTrainer | src/me/Aron/Heinecke/VocableTrainer/lib/CButton.java | 353 | package me.Aron.Heinecke.VocableTrainer.lib;
import java.awt.Font;
import javax.swing.JButton;
/**
* Cusom button with font handler
* @author aron
*
*/
public class CButton extends JButton {
private static final long serialVersionUID = 7603166773217229165L;
public CButton(String text, Font font){
super(text);
this.setFont(font);
}
}
| mit |
fred4jupiter/fredbet | src/main/java/de/fred4jupiter/fredbet/repository/ImageMetaDataRepository.java | 1690 | package de.fred4jupiter.fredbet.repository;
import de.fred4jupiter.fredbet.domain.AppUser;
import de.fred4jupiter.fredbet.domain.ImageGroup;
import de.fred4jupiter.fredbet.domain.ImageMetaData;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface ImageMetaDataRepository extends JpaRepository<ImageMetaData, Long> {
@Query("select a from ImageMetaData a where a.owner.username = :username and a.imageGroup.userProfileImageGroup = true")
ImageMetaData findImageMetaDataOfUserProfileImage(@Param("username") String username);
@Query("delete from ImageMetaData a where a.owner.id = :userId")
@Modifying
@Transactional
void deleteMetaDataByOwner(@Param("userId") Long userId);
ImageMetaData findByImageKey(String imageKey);
@Query("select a from ImageMetaData a where a.imageGroup.userProfileImageGroup = true")
List<ImageMetaData> loadImageMetaDataOfUserProfileImageSet();
@Query("select a from ImageMetaData a where a.imageGroup.userProfileImageGroup = false")
List<ImageMetaData> findImageMetaDataWithoutProfileImages();
@Query("select a from ImageMetaData a where a.owner.username = :username and a.imageGroup.userProfileImageGroup = false")
List<ImageMetaData> findImageMetaDataForUser(@Param("username") String username);
ImageMetaData findByOwnerAndImageGroup(AppUser owner, ImageGroup imageGroup);
}
| mit |
ControlSystemStudio/diirt | pvmanager/datasource-timecache/src/main/java/org/diirt/datasource/timecache/DataRequestThread.java | 4664 | /**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource.timecache;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.diirt.datasource.timecache.source.DataSource;
import org.diirt.datasource.timecache.util.CacheHelper;
import org.diirt.datasource.timecache.util.IntervalsList;
import org.diirt.util.time.TimeInterval;
/**
* Retrieves chunks from the specified {@link DataSource}, channel name and
* {@link TimeInterval}. Polls chunks from the source until the
* {@link Timestamp} of the last received {@link Data} is superior to the end of
* the defined {@link TimeInterval}.
* @author Fred Arnaud (Sopra Group) - ITER
*/
public class DataRequestThread extends Thread {
private static AtomicInteger idCounter = new AtomicInteger(0);
private final Integer requestID;
private final String channelName;
private final DataSource source;
private TimeInterval interval;
private Instant lastReceived;
private List<DataRequestListener> listeners;
public DataRequestThread(String channelName, DataSource source,
TimeInterval interval) throws Exception {
if (channelName == null || channelName.isEmpty() || source == null
|| interval == null)
throw new Exception("null or empty argument not allowed");
this.requestID = idCounter.getAndIncrement();
this.listeners = new ArrayList<DataRequestListener>();
this.channelName = channelName;
this.source = source;
this.interval = CacheHelper.arrange(interval);
this.lastReceived = this.interval.getStart();
}
/** {@inheritDoc} */
@Override
public void run() {
if (interval.getStart() == null) {
notifyComplete();
return;
}
DataChunk currentChunk = source.getData(channelName, interval.getStart());
boolean process = true;
while (process) {
if (currentChunk == null || currentChunk.isEmpty()
|| !CacheHelper.intersects(interval, currentChunk.getInterval())) {
process = false;
break;
} else {
lastReceived = currentChunk.getInterval().getEnd();
notifyNewData(currentChunk);
if (!currentChunk.isFull() || !interval.contains(lastReceived)) {
process = false;
break;
}
}
currentChunk = source.getData(channelName, lastReceived.plus(IntervalsList.minDuration));
}
notifyComplete();
}
// Notify the listeners that a new chunk is available
private void notifyNewData(DataChunk chunk) {
for (DataRequestListener l : listeners)
l.newData(chunk, this);
}
// Notify the listeners that the thread has finished requesting samples
private void notifyComplete() {
for (DataRequestListener l : listeners)
l.intervalComplete(this);
}
/** Add a {@link DataRequestListener}. */
public void addListener(DataRequestListener l) {
if (l != null)
listeners.add(l);
}
/** Remove a {@link DataRequestListener}. */
public void removeListener(DataRequestListener l) {
if (l != null)
listeners.remove(l);
}
public TimeInterval getInterval() {
return interval;
}
public void setInterval(TimeInterval interval) {
this.interval = interval;
}
public String getChannelName() {
return channelName;
}
public DataSource getSource() {
return source;
}
public Instant getLastReceived() {
return lastReceived;
}
public Integer getRequestID() {
return requestID;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((requestID == null) ? 0 : requestID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DataRequestThread other = (DataRequestThread) obj;
if (requestID == null) {
if (other.requestID != null)
return false;
} else if (!requestID.equals(other.requestID))
return false;
return true;
}
}
| mit |
HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/SessionFactory.java | 13171 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate;
import java.io.Serializable;
import java.sql.Connection;
import java.util.Map;
import java.util.Set;
import javax.naming.Referenceable;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.stat.Statistics;
/**
* The main contract here is the creation of {@link Session} instances. Usually
* an application has a single {@link SessionFactory} instance and threads
* servicing client requests obtain {@link Session} instances from this factory.
* <p/>
* The internal state of a {@link SessionFactory} is immutable. Once it is created
* this internal state is set. This internal state includes all of the metadata
* about Object/Relational Mapping.
* <p/>
* Implementors <strong>must</strong> be threadsafe.
*
* @see org.hibernate.cfg.Configuration
*
* @author Gavin King
* @author Steve Ebersole
*/
public interface SessionFactory extends Referenceable, Serializable {
public interface SessionFactoryOptions {
Interceptor getInterceptor();
EntityNotFoundDelegate getEntityNotFoundDelegate();
}
public SessionFactoryOptions getSessionFactoryOptions();
/**
* Obtain a {@link Session} builder.
*
* @return The session builder
*/
public SessionBuilder withOptions();
/**
* Open a {@link Session}.
* <p/>
* JDBC {@link Connection connection(s} will be obtained from the
* configured {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} as needed
* to perform requested work.
*
* @return The created session.
*
* @throws HibernateException Indicates a problem opening the session; pretty rare here.
*/
public Session openSession() throws HibernateException;
/**
* Obtains the current session. The definition of what exactly "current"
* means controlled by the {@link org.hibernate.context.spi.CurrentSessionContext} impl configured
* for use.
* <p/>
* Note that for backwards compatibility, if a {@link org.hibernate.context.spi.CurrentSessionContext}
* is not configured but JTA is configured this will default to the {@link org.hibernate.context.internal.JTASessionContext}
* impl.
*
* @return The current session.
*
* @throws HibernateException Indicates an issue locating a suitable current session.
*/
public Session getCurrentSession() throws HibernateException;
/**
* Obtain a {@link StatelessSession} builder.
*
* @return The stateless session builder
*/
public StatelessSessionBuilder withStatelessOptions();
/**
* Open a new stateless session.
*
* @return The created stateless session.
*/
public StatelessSession openStatelessSession();
/**
* Open a new stateless session, utilizing the specified JDBC
* {@link Connection}.
*
* @param connection Connection provided by the application.
*
* @return The created stateless session.
*/
public StatelessSession openStatelessSession(Connection connection);
/**
* Retrieve the {@link ClassMetadata} associated with the given entity class.
*
* @param entityClass The entity class
*
* @return The metadata associated with the given entity; may be null if no such
* entity was mapped.
*
* @throws HibernateException Generally null is returned instead of throwing.
*/
public ClassMetadata getClassMetadata(Class entityClass);
/**
* Retrieve the {@link ClassMetadata} associated with the given entity class.
*
* @param entityName The entity class
*
* @return The metadata associated with the given entity; may be null if no such
* entity was mapped.
*
* @throws HibernateException Generally null is returned instead of throwing.
* @since 3.0
*/
public ClassMetadata getClassMetadata(String entityName);
/**
* Get the {@link CollectionMetadata} associated with the named collection role.
*
* @param roleName The collection role (in form [owning-entity-name].[collection-property-name]).
*
* @return The metadata associated with the given collection; may be null if no such
* collection was mapped.
*
* @throws HibernateException Generally null is returned instead of throwing.
*/
public CollectionMetadata getCollectionMetadata(String roleName);
/**
* Retrieve the {@link ClassMetadata} for all mapped entities.
*
* @return A map containing all {@link ClassMetadata} keyed by the
* corresponding {@link String} entity-name.
*
* @throws HibernateException Generally empty map is returned instead of throwing.
*
* @since 3.0 changed key from {@link Class} to {@link String}.
*/
public Map<String,ClassMetadata> getAllClassMetadata();
/**
* Get the {@link CollectionMetadata} for all mapped collections
*
* @return a map from <tt>String</tt> to <tt>CollectionMetadata</tt>
*
* @throws HibernateException Generally empty map is returned instead of throwing.
*/
public Map getAllCollectionMetadata();
/**
* Retrieve the statistics fopr this factory.
*
* @return The statistics.
*/
public Statistics getStatistics();
/**
* Destroy this <tt>SessionFactory</tt> and release all resources (caches,
* connection pools, etc).
* <p/>
* It is the responsibility of the application to ensure that there are no
* open {@link Session sessions} before calling this method as the impact
* on those {@link Session sessions} is indeterminate.
* <p/>
* No-ops if already {@link #isClosed closed}.
*
* @throws HibernateException Indicates an issue closing the factory.
*/
public void close() throws HibernateException;
/**
* Is this factory already closed?
*
* @return True if this factory is already closed; false otherwise.
*/
public boolean isClosed();
/**
* Obtain direct access to the underlying cache regions.
*
* @return The direct cache access API.
*/
public Cache getCache();
/**
* Evict all entries from the second-level cache. This method occurs outside
* of any transaction; it performs an immediate "hard" remove, so does not respect
* any transaction isolation semantics of the usage strategy. Use with care.
*
* @param persistentClass The entity class for which to evict data.
*
* @throws HibernateException Generally will mean that either that
* 'persisttentClass' did not name a mapped entity or a problem
* communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#evictEntityRegion(Class)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evict(Class persistentClass) throws HibernateException;
/**
* Evict an entry from the second-level cache. This method occurs outside
* of any transaction; it performs an immediate "hard" remove, so does not respect
* any transaction isolation semantics of the usage strategy. Use with care.
*
* @param persistentClass The entity class for which to evict data.
* @param id The entity id
*
* @throws HibernateException Generally will mean that either that
* 'persisttentClass' did not name a mapped entity or a problem
* communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#containsEntity(Class, Serializable)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evict(Class persistentClass, Serializable id) throws HibernateException;
/**
* Evict all entries from the second-level cache. This method occurs outside
* of any transaction; it performs an immediate "hard" remove, so does not respect
* any transaction isolation semantics of the usage strategy. Use with care.
*
* @param entityName The entity name for which to evict data.
*
* @throws HibernateException Generally will mean that either that
* 'persisttentClass' did not name a mapped entity or a problem
* communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#evictEntityRegion(String)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evictEntity(String entityName) throws HibernateException;
/**
* Evict an entry from the second-level cache. This method occurs outside
* of any transaction; it performs an immediate "hard" remove, so does not respect
* any transaction isolation semantics of the usage strategy. Use with care.
*
* @param entityName The entity name for which to evict data.
* @param id The entity id
*
* @throws HibernateException Generally will mean that either that
* 'persisttentClass' did not name a mapped entity or a problem
* communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#evictEntity(String,Serializable)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evictEntity(String entityName, Serializable id) throws HibernateException;
/**
* Evict all entries from the second-level cache. This method occurs outside
* of any transaction; it performs an immediate "hard" remove, so does not respect
* any transaction isolation semantics of the usage strategy. Use with care.
*
* @param roleName The name of the collection role whose regions should be evicted
*
* @throws HibernateException Generally will mean that either that
* 'roleName' did not name a mapped collection or a problem
* communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#evictCollectionRegion(String)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evictCollection(String roleName) throws HibernateException;
/**
* Evict an entry from the second-level cache. This method occurs outside
* of any transaction; it performs an immediate "hard" remove, so does not respect
* any transaction isolation semantics of the usage strategy. Use with care.
*
* @param roleName The name of the collection role
* @param id The id of the collection owner
*
* @throws HibernateException Generally will mean that either that
* 'roleName' did not name a mapped collection or a problem
* communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#evictCollection(String,Serializable)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evictCollection(String roleName, Serializable id) throws HibernateException;
/**
* Evict any query result sets cached in the named query cache region.
*
* @param cacheRegion The named query cache region from which to evict.
*
* @throws HibernateException Since a not-found 'cacheRegion' simply no-ops,
* this should indicate a problem communicating with underlying cache impl.
*
* @deprecated Use {@link Cache#evictQueryRegion(String)} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evictQueries(String cacheRegion) throws HibernateException;
/**
* Evict any query result sets cached in the default query cache region.
*
* @throws HibernateException Indicate a problem communicating with
* underlying cache impl.
*
* @deprecated Use {@link Cache#evictQueryRegions} accessed through
* {@link #getCache()} instead.
*/
@Deprecated
public void evictQueries() throws HibernateException;
/**
* Obtain a set of the names of all filters defined on this SessionFactory.
*
* @return The set of filter names.
*/
public Set getDefinedFilterNames();
/**
* Obtain the definition of a filter by name.
*
* @param filterName The name of the filter for which to obtain the definition.
* @return The filter definition.
* @throws HibernateException If no filter defined with the given name.
*/
public FilterDefinition getFilterDefinition(String filterName) throws HibernateException;
/**
* Determine if this session factory contains a fetch profile definition
* registered under the given name.
*
* @param name The name to check
* @return True if there is such a fetch profile; false otherwise.
*/
public boolean containsFetchProfileDefinition(String name);
/**
* Retrieve this factory's {@link TypeHelper}
*
* @return The factory's {@link TypeHelper}
*/
public TypeHelper getTypeHelper();
}
| mit |
pipseq/semantic | src/main/org/pipseq/rdf/jena/aggregate/allSameList.java | 2906 | /*
* Copyright © 2015 www.pipseq.org
* @author rspates
*/
package org.pipseq.rdf.jena.aggregate;
import java.util.ArrayList;
import java.util.List;
import com.hp.hpl.jena.sparql.engine.binding.Binding;
import com.hp.hpl.jena.sparql.expr.Expr;
import com.hp.hpl.jena.sparql.expr.ExprEvalException;
import com.hp.hpl.jena.sparql.expr.ExprList;
import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.expr.aggregate.Accumulator;
import com.hp.hpl.jena.sparql.expr.aggregate.AccumulatorFactory;
import com.hp.hpl.jena.sparql.expr.aggregate.AggCustom;
import com.hp.hpl.jena.sparql.expr.aggregate.AggregateRegistry;
import com.hp.hpl.jena.sparql.function.FunctionEnv;
import com.hp.hpl.jena.sparql.graph.NodeConst;
/**
* allSameList
* For use as a filter function within a SPARQL query.
* The allSameList function accepts any number of parameters.
* If all the parameters are the same it returns true else false.
*/
public class allSameList implements Accumulator {
// Execution of a custom aggregate is with accumulators. One accumulator is
/** The my accumulator factory. */
// created for the factory for each group in a query execution.
static AccumulatorFactory myAccumulatorFactory = new AccumulatorFactory() {
@Override
public Accumulator createAccumulator(AggCustom agg) { return new allSameList(agg) ; }
} ;
/** The agg uri. */
/* Registration */
public static String aggUri = "java:org.pipseq.rdf.jena.aggregate.allSameList" ;
/**
* Register.
*/
public static void register(){
AggregateRegistry.register(aggUri, myAccumulatorFactory, NodeConst.nodeFalse);
}
private AggCustom agg ;
/**
* Instantiates a new all same list.
*
* @param agg the agg
*/
allSameList(AggCustom agg) { this.agg = agg ; }
/** The lnv. */
List<NodeValue> lnv = new ArrayList<NodeValue>();
/* (non-Javadoc)
* @see com.hp.hpl.jena.sparql.expr.aggregate.Accumulator#accumulate(com.hp.hpl.jena.sparql.engine.binding.Binding, com.hp.hpl.jena.sparql.function.FunctionEnv)
*/
@Override
public void accumulate(Binding binding, FunctionEnv functionEnv) {
ExprList exprList = agg.getExprList() ;
for(Expr expr: exprList) {
try {
NodeValue nv = expr.eval(binding, functionEnv) ;
// Evaluation succeeded.
lnv.add(nv);
} catch (ExprEvalException ex) {}
}
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.sparql.expr.aggregate.Accumulator#getValue()
*/
@Override
public NodeValue getValue() {
if (lnv.size() < 0)
return NodeValue.FALSE;
for (int i=1;i<lnv.size();i++){
if (!lnv.get(0).equals(lnv.get(i)))
return NodeValue.FALSE;
}
return NodeValue.TRUE; //lnv.get(0) ;
}
}
| mit |
wesleyegberto/javaee_projects | jcache-tests/src/main/java/com/github/wesleyegberto/jcachetests/cachestatistics/StatisticsResource.java | 3184 | package com.github.wesleyegberto.jcachetests.cachestatistics;
import java.lang.management.ManagementFactory;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import javax.cache.Cache;
import javax.ejb.Singleton;
import javax.inject.Inject;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.github.wesleyegberto.jcachetests.cdi.qualifiers.CustomCache;
import com.github.wesleyegberto.jcachetests.entity.Person;
@Path("statistics")
@Singleton
public class StatisticsResource {
private static AtomicInteger lastId = new AtomicInteger(0);
@Inject
@CustomCache
Cache<Integer, Person> peopleCache;
private ObjectName objectName;
private MBeanServer mBeanServer;
@PostConstruct
public void init() {
mBeanServer = ManagementFactory.getPlatformMBeanServer();
try {
String name = "javax.cache:type=CacheStatistics,CacheManager=\""
+ (peopleCache.getCacheManager().getURI().toString())
+ "\",Cache=\"" + peopleCache.getName() + "\"";
//System.out.println("Object name: " + name);
objectName = new ObjectName(name);
} catch(MalformedObjectNameException e) {
e.printStackTrace();
}
}
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public void create(@Valid @NotNull Person person) {
int newId = lastId.incrementAndGet();
person.setId(newId);
peopleCache.put(newId, person);
}
@GET
@Path("{id: \\d}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getById(@PathParam("id") int id) {
Person person = peopleCache.get(id);
if(person == null)
return Response.status(Status.NOT_FOUND).build();
return Response.ok(person).build();
}
@DELETE
@Path("{id: \\d}")
public void delete(@PathParam("id") int id) {
peopleCache.remove(id);
}
@GET
@Path("/hits")
public Response getCacheHits() {
try {
Object hits = mBeanServer.getAttribute(objectName, "CacheHits");
return Response.ok(hits).build();
} catch(AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e) {
return Response.serverError().entity(e.toString()).build();
}
}
@GET
@Path("/misses")
public Response getCacheMisses() {
try {
Object misses = mBeanServer.getAttribute(objectName, "CacheMisses");
return Response.ok(misses).build();
} catch(AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e) {
return Response.serverError().entity(e.toString()).build();
}
}
}
| mit |
MihirJayavant/Quiz | src/main/java/com/myapp2/mihir/quiz/MainActivity.java | 7020 | package com.myapp2.mihir.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity
{
TextView dispques;
RadioGroup rgroup;
RadioButton radio[]=new RadioButton[4];
Button next,quit,tryAgain;
QuizLogic q;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
try
{
displayQuestion();
setRadioOptions();
q.getCorrectAns();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void onStart()
{
super.onStart();
}
public void init()
{
try {
InputStream is= this.getResources().openRawResource(R.raw.question);
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
q=new QuizLogic(br);
} catch (Exception e) {
e.printStackTrace();
}
dispques=(TextView)findViewById(R.id.display_question);
rgroup=(RadioGroup)findViewById(R.id.answer_group);
next=(Button)findViewById(R.id.next_btn);
quit=(Button)findViewById(R.id.quit_btn);
tryAgain=(Button)findViewById(R.id.try_btn);
radio[0]=(RadioButton)findViewById(R.id.option1);
radio[1]=(RadioButton)findViewById(R.id.option2);
radio[2]=(RadioButton)findViewById(R.id.option3);
radio[3]=(RadioButton)findViewById(R.id.option4);
ButtonAction b=new ButtonAction(this);
next.setOnClickListener(b);
quit.setOnClickListener(b);
tryAgain.setOnClickListener(b);
}
private void displayQuestion()throws Exception
{
String s=q.getQuestion();
s=q.quesno+"."+s;
dispques.setText(s);
}
private void setRadioOptions()throws Exception
{
String s[]=new String[4];
for(int i=0;i<4;i++)
s[i] = q.getAns();
for(int i=0;i<4;i++)
radio[i].setText(s[i]);
}
private void makeInvisible()
{
next.setVisibility(View.GONE);
quit.setVisibility(View.GONE);
for(int i=0;i<4;i++)
radio[i].setVisibility(View.GONE);
}
private class ButtonAction implements View.OnClickListener
{
MainActivity m;
ButtonAction(MainActivity m)
{
this.m=m;
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.next_btn: nextAction();
break;
case R.id.quit_btn:
String s="You have given correction ans of "+(--q.quesno)+"/10 questions";
dispques.setText(s);
makeInvisible();
tryAgain.setVisibility(View.VISIBLE);
try
{
q.br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
break;
case R.id.try_btn:
clearAllToStartAgain();
try
{
displayQuestion();
setRadioOptions();
q.getCorrectAns();
}
catch (Exception e)
{
e.printStackTrace();
}
break;
}
}
public void nextAction()
{
boolean b[]=checkAns();
rgroup.clearCheck();
if(b[0])
{
if(b[1])
{
q.prize+=1000000;
try
{
if(q.quesno==10)
{
makeInvisible();
dispques.setText("You won the game");
q.br.close();
return;
}
displayQuestion();
setRadioOptions();
q.getCorrectAns();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
makeInvisible();
if(q.prize!=0)
q.prize-=1000000;
dispques.setText("You have given correction ans of "+(--q.quesno)+"/10 questions");
try
{
q.br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
tryAgain.setVisibility(View.VISIBLE);
}
}
}
private boolean[] checkAns()
{
boolean b[]=new boolean[2];
b[0]=false;
b[1]=false;
int a=3;
switch (rgroup.getCheckedRadioButtonId())
{
case R.id.option1: a--;
case R.id.option2: a--;
case R.id.option3: a--;
case R.id.option4: b[0]=true;
break;
default:return b;
}
if(Integer.parseInt(q.ans)==a)
{
b[1]=true;
}
return b;
}
void clearAllToStartAgain()
{
try
{
InputStream is= m.getResources().openRawResource(R.raw.question);
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
q=new QuizLogic(br);
} catch (Exception e) {
e.printStackTrace();
}
next.setVisibility(View.VISIBLE);
quit.setVisibility(View.VISIBLE);
for(int i=0;i<4;i++)
radio[i].setVisibility(View.VISIBLE);
rgroup.clearCheck();
tryAgain.setVisibility(View.GONE);
}
}
}
| mit |
szschaler/RigidBodies | uk.ac.kcl.inf.robotics.rigid_bodies.ui/xtend-gen/uk/ac/kcl/inf/robotics/ui/quickfix/RigidBodiesQuickfixProvider.java | 366 | /**
* generated by Xtext
*/
package uk.ac.kcl.inf.robotics.ui.quickfix;
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider;
/**
* Custom quickfixes.
*
* See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#quick-fixes
*/
@SuppressWarnings("all")
public class RigidBodiesQuickfixProvider extends DefaultQuickfixProvider {
}
| mit |
Team254/FRC-2015 | src/com/team254/frc2015/OperatorInterface.java | 6448 | package com.team254.frc2015;
import com.team254.frc2015.behavior.Commands;
import com.team254.lib.util.Latch;
import edu.wpi.first.wpilibj.Joystick;
import java.util.Optional;
public class OperatorInterface {
private Commands m_commands = new Commands();
Joystick leftStick = HardwareAdaptor.kLeftStick;
Joystick rightStick = HardwareAdaptor.kRightStick;
Joystick buttonBoard = HardwareAdaptor.kButtonBoard;
Latch horizontalCanLatch = new Latch();
Latch coopLatch = new Latch();
Latch verticalCanLatch = new Latch();
public void reset() {
m_commands = new Commands();
}
public Commands getCommands() {
// Left stick
if (leftStick.getRawButton(1)) {
m_commands.roller_request = Commands.RollerRequest.INTAKE;
} else if (leftStick.getRawButton(2)) {
m_commands.roller_request = Commands.RollerRequest.EXHAUST;
} else {
m_commands.roller_request = Commands.RollerRequest.NONE;
}
// Right stick
if (rightStick.getRawButton(2)) {
m_commands.intake_request = Commands.IntakeRequest.OPEN;
} else {
m_commands.intake_request = Commands.IntakeRequest.CLOSE;
}
// Button board
if (buttonBoard.getRawAxis(3) > 0.1) {
m_commands.elevator_mode = Commands.ElevatorMode.BOTTOM_CARRIAGE_MODE;
} else {
m_commands.elevator_mode = Commands.ElevatorMode.TOP_CARRIAGE_MODE;
}
if (buttonBoard.getRawButton(3)) {
m_commands.bottom_carriage_flapper_request = Commands.BottomCarriageFlapperRequest.OPEN;
} else {
m_commands.bottom_carriage_flapper_request = Commands.BottomCarriageFlapperRequest.CLOSE;
}
if (buttonBoard.getRawButton(8)) { // Bottom carriage jog up
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.bottom_jog = Optional.of(Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.bottom_jog = Optional.of(Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.bottom_jog = Optional.of(Constants.kElevatorJogFastPwm); // disable old man mode
}
} else if (buttonBoard.getRawButton(10)) { // Bottom carriage jog down
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.bottom_jog = Optional.of(-Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.bottom_jog = Optional.of(-Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.bottom_jog = Optional.of(-Constants.kElevatorJogMediumPwm);
}
} else {
m_commands.bottom_jog = Optional.empty();
}
if (buttonBoard.getRawButton(7)) { // top up
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.top_jog = Optional.of(Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.top_jog = Optional.of(Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.top_jog = Optional.of(Constants.kElevatorJogFastPwm); // disable old man mode
}
} else if (buttonBoard.getRawButton(9)) { // top down
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.top_jog = Optional.of(-Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.top_jog = Optional.of(-Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.top_jog = Optional.of(-Constants.kElevatorJogMediumPwm);
}
} else {
m_commands.top_jog = Optional.empty();
}
m_commands.cancel_current_routine = buttonBoard.getX() < 0; // Button 6
if (coopLatch.update(buttonBoard.getY() < 0)) { // Button 5
m_commands.preset_request = Commands.PresetRequest.COOP;
} else if (buttonBoard.getRawButton(5)) { // Button 2
m_commands.preset_request = Commands.PresetRequest.SCORE;
} else if (buttonBoard.getRawButton(4)) { // Button 1
//m_commands.preset_request = Commands.PresetRequest.CARRY_SQUEZE;
} else {
m_commands.preset_request = Commands.PresetRequest.NONE;
}
if (verticalCanLatch.update(buttonBoard.getRawButton(6))) { // Button 3
m_commands.vertical_can_grab_request = Commands.VerticalCanGrabberRequests.ACTIVATE;
} else {
m_commands.vertical_can_grab_request = Commands.VerticalCanGrabberRequests.NONE;
}
m_commands.top_carriage_claw_request = Commands.TopCarriageClawRequest.CLOSE;
if (buttonBoard.getRawButton(1)) {
m_commands.top_carriage_claw_request = Commands.TopCarriageClawRequest.OPEN;
}
if (horizontalCanLatch.update(buttonBoard.getRawButton(2))) {
m_commands.horizontal_can_grabber_request = Commands.HorizontalCanGrabberRequests.ACTIVATE;
} else {
m_commands.horizontal_can_grabber_request = Commands.HorizontalCanGrabberRequests.NONE;
}
m_commands.floor_load_mode = buttonBoard.getRawAxis(3) > 0.1;
m_commands.deploy_peacock = buttonBoard.getRawButton(11) && buttonBoard.getZ() < 0; // button 4;
if (buttonBoard.getZ() < 0) { // left motor peacock
if (buttonBoard.getRawButton(11)) {
m_commands.left_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_DOWN;
} else {
m_commands.left_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_UP;
}
} else {
m_commands.left_motor_peacock_requests = Commands.MotorPeacockRequests.NONE;
}
if (buttonBoard.getRawButton(4)) { // right motor peacock
if (buttonBoard.getRawButton(11)) {
m_commands.right_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_DOWN;
} else {
m_commands.right_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_UP;
}
} else {
m_commands.right_motor_peacock_requests = Commands.MotorPeacockRequests.NONE;
}
return m_commands;
}
}
| mit |
VerkhovtsovPavel/BSUIR_Labs | Labs/WT/WT-3/src/com/bsuir/wtlab3/source/Notepad.java | 490 | package com.bsuir.wtlab3.source;
import java.util.ArrayList;
import com.bsuir.wtlab3.entity.Note;
public class Notepad {
private ArrayList<Note> notes = new ArrayList<Note>();
private static Notepad instance;
public static Notepad getInstance(){
if(instance == null){
instance = new Notepad();
}
return instance;
}
private Notepad(){};
public ArrayList<Note> getNotes() {
return notes;
}
public boolean addNote(Note note){
return this.notes.add(note);
}
}
| mit |
Gamoholic/Applied-Energistics-2-API | parts/layers/LayerIEnergySink.java | 1448 | package appeng.api.parts.layers;
import ic2.api.energy.tile.IEnergySink;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import appeng.api.parts.IBusPart;
import appeng.api.parts.LayerBase;
public class LayerIEnergySink extends LayerBase implements IEnergySink
{
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction)
{
IBusPart part = getPart( direction );
if ( part instanceof IEnergySink )
return ((IEnergySink) part).acceptsEnergyFrom( emitter, direction );
return false;
}
@Override
public double demandedEnergyUnits()
{
// this is a flawed implementation, that requires a change to the IC2 API.
double maxRequired = 0;
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS)
{
IBusPart part = getPart( dir );
if ( part instanceof IEnergySink )
{
// use lower number cause ic2 deletes power it sends that isn't recieved.
maxRequired = Math.min( maxRequired, ((IEnergySink) part).demandedEnergyUnits() );
}
}
return maxRequired;
}
@Override
public double injectEnergyUnits(ForgeDirection directionFrom, double amount)
{
IBusPart part = getPart( directionFrom );
if ( part instanceof IEnergySink )
return ((IEnergySink) part).injectEnergyUnits( directionFrom, amount );
return amount;
}
@Override
public int getMaxSafeInput()
{
return Integer.MAX_VALUE; // no real options here...
}
}
| mit |
joelabr/Laborationer-Programmering-1 | asciifier/ASCIIfier.java | 5077 | package asciifier;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import javax.imageio.ImageIO;
/**
* A program that "ASCIIfies" a given input image using a given character/symbol.
* It takes an input image and creates a new image where all the pixels from the input
* image are drawn as the given character/symbol.
*
* @author Joel Abrahamsson
* @version %G%
*/
public class ASCIIfier
{
private BufferedImage input;
private BufferedImage output;
private Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 8);
private FontMetrics metrics;
private HashMap<Integer, Color> colors;
private char lastChar;
/**
* Creates a new ASCIIfier which uses the given image as input image when ASCIIfying.
*
* @param image the image to ASCIIfy.
*/
public ASCIIfier(BufferedImage image)
{
input = image;
metrics = input.createGraphics().getFontMetrics(font);
createColorMap();
}
/**
* Creates a HashMap of all colors in the input image.
*/
private void createColorMap()
{
colors = new HashMap<Integer, Color>();
if (input != null)
{
int height = input.getHeight(),
width = input.getWidth();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int color = input.getRGB(x, y);
if (!colors.containsKey(color))
colors.put(color, new Color(color));
}
}
}
}
/**
* Creates a new BufferedImage with the right dimensions.
*
* @param c the character to use as reference for image width and height
*/
private void createOutputImage(char c)
{
if (input != null)
{
int charWidth = metrics.charWidth(c),
charHeight = metrics.getAscent() + metrics.getDescent(),
charSize = Math.max(charWidth, charHeight),
width = charSize * input.getWidth(),
height = charSize * input.getHeight();
output = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
System.out.printf("Input (%d, %d); Output (%d, %d)\n", input.getWidth(), input.getHeight(),
output.getWidth(), output.getHeight());
}
}
/**
* Returns the processed image.
*
* @return the processed image
* @see BufferedImage
*/
public BufferedImage getProcessedImage()
{
return output;
}
/**
* ASCIIfies the input image using the given character.
*
* @param c the character to use to ASCIIfy the input image
*/
public void process(char c)
{
if (output == null || lastChar != c)
{
createOutputImage(c);
lastChar = c;
}
Graphics2D g = output.createGraphics();
int height = input.getHeight(),
width = input.getWidth(),
ascent = metrics.getAscent(),
charWidth = metrics.charWidth(c),
charHeight = ascent + metrics.getDescent(),
charSize = Math.max(charWidth, charHeight);
String s = Character.toString(c);
g.setFont(font);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
g.setColor(colors.get(input.getRGB(x, y)));
g.drawString(s, x * charSize, y * charSize + ascent);
}
}
g.dispose();
}
/**
* Changes the font to use to create the image.
*
* @param font the font to use
* @see Font
*/
public void setFont(Font font)
{
if (font != null && input != null)
{
this.font = font;
metrics = input.createGraphics().getFontMetrics(font);
if (lastChar != '\u0000')
createOutputImage(lastChar);
}
}
/**
* Changes the size of the current font.
*
* @param size the new font size
*/
public void setFontSize(float size)
{
setFont(font.deriveFont(size));
}
/**
* Usage:
* java ASCIIfier IMAGE CHARACTER [FONT SIZE]
*
* IMAGE - The input image.
* CHARACTER - The character to use when ASCIIfying.
* [FONT SIZE] - Optional, change the font size
*/
public static void main(String[] args)
{
if (args.length > 1)
{
try
{
BufferedImage image = ImageIO.read(new File(args[0]));
if (image != null)
{
ASCIIfier asciifier = new ASCIIfier(image);
if (args.length > 2)
{
float fontSize = Float.parseFloat(args[2]);
asciifier.setFontSize(fontSize);
}
asciifier.process(args[1].charAt(0));
ImageIO.write(asciifier.getProcessedImage(), "png", new File(args[0] + "_asciified.png"));
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}
else
{
System.out.println("Usage:");
System.out.println("java ASCIIfier IMAGE CHARACTER [FONT SIZE]");
}
}
}
| mit |
Herover/IP-VVH-LALN-MH-OCC | OOPD/uge5/Day.java | 867 | import java.util.HashMap;
/**
* Enum type med dage.
*/
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
/**
* Oversæt streng til enum type.
* Går ud fra at teksten er på dansk.
* @param streng med dag
*/
public static Day fromString(String day) {
if (day != null) {
/*for (Day d : Day.values()) {
if (d.name().equalsIgnoreCase(day)) {
return d;
}
}*/
switch(day.toLowerCase()) {
case "mandag": return Day.MONDAY;
case "tirsdag": return Day.TUESDAY;
case "onsdag": return Day.WEDNESDAY;
case "torsdag": return Day.THURSDAY;
case "fredag": return Day.FRIDAY;
case "lørdag": return Day.SATURDAY;
case "søndag": return Day.SUNDAY;
}
}
return null;
}
}
| mit |
SpecularStudio/ofQt | of_v0.9.0/examples/android/androidSwipeExample/srcJava/cc/openframeworks/androidSwipeExample/OFActivity.java | 2098 | package cc.openframeworks.androidSwipeExample;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import cc.openframeworks.OFAndroid;
public class OFActivity extends cc.openframeworks.OFActivity{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String packageName = getPackageName();
ofApp = new OFAndroid(packageName,this);
}
@Override
public void onDetachedFromWindow() {
}
@Override
protected void onPause() {
super.onPause();
ofApp.pause();
}
@Override
protected void onResume() {
super.onResume();
ofApp.resume();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (OFAndroid.keyDown(keyCode, event)) {
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (OFAndroid.keyUp(keyCode, event)) {
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
OFAndroid ofApp;
// Menus
// http://developer.android.com/guide/topics/ui/menus.html
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Create settings menu options from here, one by one or infalting an xml
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// This passes the menu option string to OF
// you can add additional behavior from java modifying this method
// but keep the call to OFAndroid so OF is notified of menu events
if(OFAndroid.menuItemSelected(item.getItemId())){
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu){
// This method is called every time the menu is opened
// you can add or remove menu options from here
return super.onPrepareOptionsMenu(menu);
}
}
| mit |
acromusashi/acromusashi-stream-ml | src/main/java/acromusashi/stream/ml/clustering/kmeans/entity/KmeansDataSet.java | 2184 | /**
* Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved.
* Please read the associated COPYRIGHTS file for more details.
*
* THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd.,
* WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDER BE LIABLE FOR ANY
* CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
package acromusashi.stream.ml.clustering.kmeans.entity;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* KMeansクラスタリングの学習モデルを保持するエンティティクラス
*
* @author kimura
*/
public class KmeansDataSet implements Serializable
{
/** シリアル */
private static final long serialVersionUID = 338231277453149972L;
/** 各クラスタの中心座標の行列を格納した配列 */
private double[][] centroids;
/** 各クラスタに分類された要素数 */
private long[] clusteredNum;
/**
* パラメータを指定せずにインスタンスを生成する。
*/
public KmeansDataSet()
{}
/**
* @return the centroids
*/
public double[][] getCentroids()
{
return this.centroids;
}
/**
* @param centroids the centroids to set
*/
public void setCentroids(double[][] centroids)
{
this.centroids = centroids;
}
/**
* @return the clusteredNum
*/
public long[] getClusteredNum()
{
return this.clusteredNum;
}
/**
* @param clusteredNum the clusteredNum to set
*/
public void setClusteredNum(long[] clusteredNum)
{
this.clusteredNum = clusteredNum;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
String result = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
return result;
}
}
| mit |
algoliareadmebot/algoliasearch-client-java-2 | algoliasearch-common/src/test/java/com/algolia/search/integration/async/AsyncIndicesTest.java | 3145 | package com.algolia.search.integration.async;
import com.algolia.search.AlgoliaObject;
import com.algolia.search.AsyncAlgoliaIntegrationTest;
import com.algolia.search.AsyncIndex;
import com.algolia.search.inputs.BatchOperation;
import com.algolia.search.inputs.batch.BatchDeleteIndexOperation;
import com.algolia.search.objects.Query;
import com.algolia.search.responses.SearchResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
abstract public class AsyncIndicesTest extends AsyncAlgoliaIntegrationTest {
private static List<String> indicesNames = Arrays.asList(
"index1",
"index2",
"index3",
"index4",
"index5",
"index6",
"index7"
);
@Before
@After
public void cleanUp() throws Exception {
List<BatchOperation> clean = indicesNames.stream().map(BatchDeleteIndexOperation::new).collect(Collectors.toList());
waitForCompletion(client.batch(clean));
}
@Test
public void getAllIndices() throws Exception {
assertThat(client.listIndices()).isNotNull();
AsyncIndex<AlgoliaObject> index = client.initIndex("index1", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index1");
}
@Test
public void deleteIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index2", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index2");
waitForCompletion(index.delete());
futureAssertThat(client.listIndices()).extracting("name").doesNotContain("index2");
}
@Test
public void moveIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index3", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index3");
waitForCompletion(index.moveTo("index4"));
futureAssertThat(client.listIndices()).extracting("name").doesNotContain("index3").contains("index4");
}
@Test
public void copyIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index5", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index5");
waitForCompletion(index.copyTo("index6"));
futureAssertThat(client.listIndices()).extracting("name").contains("index5", "index6");
}
@Test
public void clearIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index7", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
waitForCompletion(index.clear());
SearchResult<AlgoliaObject> results = index.search(new Query("")).get();
assertThat(results.getHits()).isEmpty();
}
}
| mit |
habibmasuro/XChange | xchange-justcoin/src/test/java/com/xeiam/xchange/justcoin/service/trade/JustcoinPostCreateResponseJsonTest.java | 2068 | /**
* Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.xeiam.xchange.justcoin.service.trade;
import static org.fest.assertions.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.justcoin.dto.PostCreateResponse;
import com.xeiam.xchange.justcoin.service.marketdata.JustcoinDepthTest;
/**
* @author jamespedwards42
*/
public class JustcoinPostCreateResponseJsonTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
final InputStream is = JustcoinDepthTest.class.getResourceAsStream("/trade/example-post-create-response-data.json");
// Use Jackson to parse it
final ObjectMapper mapper = new ObjectMapper();
final PostCreateResponse response = mapper.readValue(is, PostCreateResponse.class);
assertThat(response.getId()).isEqualTo("1895549");
}
}
| mit |
youribonnaffe/jsr223-nativeshell | src/test/java/jsr223/nativeshell/bash/BashScriptEngineFactoryTest.java | 987 | package jsr223.nativeshell.bash;
import org.junit.Test;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import static org.junit.Assert.assertNotNull;
public class BashScriptEngineFactoryTest {
@Test
public void testBashScriptEngineIsFound() {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
assertNotNull(scriptEngineManager.getEngineByExtension("sh"));
assertNotNull(scriptEngineManager.getEngineByName("bash"));
assertNotNull(scriptEngineManager.getEngineByMimeType("application/x-bash"));
assertNotNull(scriptEngineManager.getEngineByMimeType("application/x-sh"));
}
@Test
public void testBashScriptEngineVersions() {
ScriptEngine bashScriptEngine = new ScriptEngineManager().getEngineByExtension("sh");
assertNotNull(bashScriptEngine.getFactory().getEngineVersion());
assertNotNull(bashScriptEngine.getFactory().getLanguageVersion());
}
}
| mit |
bandwidthcom/java-bandwidth-iris | src/main/java/com/bandwidth/iris/sdk/model/TelephoneNumberSearchFilters.java | 1972 | package com.bandwidth.iris.sdk.model;
public class TelephoneNumberSearchFilters {
private String inAreaCode;
private String filterPattern;
private String inState;
private String inPostalCode;
private boolean isTollFree;
private int quantity = 5;
private boolean returnTelephoneNumberDetails = true;
private String inRateCenter;
private String inLata;
public boolean isReturnTelephoneNumberDetails() {
return returnTelephoneNumberDetails;
}
public void setReturnTelephoneNumberDetails(boolean returnTelephoneNumberDetails) {
this.returnTelephoneNumberDetails = returnTelephoneNumberDetails;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getInAreaCode() {
return inAreaCode;
}
public void setInAreaCode(String inAreaCode) {
this.inAreaCode = inAreaCode;
}
public String getFilterPattern() {
return filterPattern;
}
public void setFilterPattern(String filterPattern) {
this.filterPattern = filterPattern;
}
public String getInState() {
return inState;
}
public void setInState(String inState) {
this.inState = inState;
}
public String getInPostalCode() {
return inPostalCode;
}
public void setInPostalCode(String inPostalCode) {
this.inPostalCode = inPostalCode;
}
public boolean isTollFree() {
return isTollFree;
}
public void setTollFree(boolean isTollFree) {
this.isTollFree = isTollFree;
}
public String getInRateCenter() {
return inRateCenter;
}
public void setInRateCenter(String inRateCenter) {
this.inRateCenter = inRateCenter;
}
public String getInLata() {
return inLata;
}
public void setInLata(String inLata) {
this.inLata = inLata;
}
}
| mit |
maxalthoff/intro-to-java-exercises | 02/E2_13/E2_13.java | 1311 | /*
Suppose you save $100 each month into a savings account with the annual
interest rate 5%. Thus, the monthly interest rate is 0.05/12 = 0.00417.
After the first month, the value in the account becomes
100 * (1 + 0.00417) = 100.417
After the second month, the value in the account becomes
(100 + 100.417) * (1 + 0.00417) = 201.252
After the third month, the value in the account becomes
(100 * 201.252) * (1 + 0.00417) = 302.507
and so on.
Write a program that prompts the user to enter a monthly saving amount and
displays the account value after the sixth month.
*/
import java.util.Scanner;
public class E2_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the monthly saving amount: ");
double monthlySavingAmount = input.nextDouble();
double monthlyInterestRate = 0.05/12;
double accountValue = accountValue(monthlySavingAmount, monthlyInterestRate,
6);
System.out.printf("After the sixth month, the account value is $%.2f\n",
accountValue);
}
private static double accountValue(double savings, double rate, int months) {
double account = 0.0;
for (int i = 0; i < months; i++) {
account = (account + savings) * (1 + rate);
}
return account;
}
}
| mit |
knappa/CSC281S17 | LinearAlgebra.java | 6063 | import java.util.Arrays;
/**
* <code>LinearAlgebra</code> performs basic linear algebra routines.
*
* @author <a href="mailto:knapp@american.edu">Adam Knapp</a>
* @version 1.0
*/
@SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public class LinearAlgebra {
/**
* Adds two vectors
*
* @param vec1 <code>double</code> vector
* @param vec2 <code>double</code> vector
* @return a new <code>double</code> array containing the result of vector addition
* @throws IllegalArgumentException if vectors are not of the same length or are <code>null</code>
*/
public static double[] vecAdd(double[] vec1, double[] vec2) {
if (vec1 == null
|| vec2 == null
|| vec1.length != vec2.length) {
throw new IllegalArgumentException();
}
double[] result = new double[vec1.length];
for (int i = 0; i < vec1.length; i++) {
result[i] = vec1[i] + vec2[i];
}
return result;
}
/**
* performs scalar multiplication on a vector
*
* @param scalar <code>double</code> scalar
* @param vec <code>double</code> vector
* @return a new <code>double</code> array containing the result of scalar mult
* @throws IllegalArgumentException if <code>vec</code> is <code>null</code>
*/
public static double[] scalarMult(double scalar, double[] vec) {
if (vec == null) {
throw new IllegalArgumentException();
}
double[] result = new double[vec.length];
for (int i = 0; i < vec.length; i++) {
result[i] = scalar * vec[i];
}
return result;
}
/**
* adds two matrices
*
* @param mat1 <code>double</code> matrix
* @param mat2 <code>double</code> matrix
* @return a new <code>double</code> matrix, the result of matrix addition
* @throws IllegalArgumentException if matrices are wrong size or <code>null</code>
*/
public static double[][] matAdd(double[][] mat1, double[][] mat2) {
if (mat1 == null
|| mat2 == null
|| mat1.length != mat2.length
|| mat1[0].length != mat2[0].length)
throw new IllegalArgumentException();
double[][] result = new double[mat1.length][mat1[0].length];
for (int i = 0; i < mat1.length; i++) {
for (int j = 0; j < mat1[0].length; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
return result;
}
/**
* performs scalar multiplication on a matrix
*
* @param scalar a <code>double</code> scalar value
* @param mat a <code>double</code> matrix
* @return a new <code>double</code> matrix
* @throws IllegalArgumentException if <code>mat</code> is <code>null</code>
*/
public static double[][] scalarMult(double scalar, double[][] mat) {
if (mat == null) {
throw new IllegalArgumentException();
}
double[][] result = new double[mat.length][mat[0].length];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
result[i][j] = scalar * mat[i][j];
}
}
return result;
}
/**
* performs matrix-vector multiplication
*
* @param mat a <code>double</code> matrix
* @param vec a <code>double</code> vector
* @return a <code>double[]</code> vector, the result of multiplication
* @throws IllegalArgumentException if the number of columns of <code>mat</code> is not equal to the number of rows of
* <code>vec</code>, or either is <code>null</code>
*/
public static double[] matVecMult(double[][] mat, double[] vec) {
if (mat == null
|| vec == null
|| mat[0].length != vec.length)
throw new IllegalArgumentException();
double[] result = new double[mat.length];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < vec.length; j++) {
result[i] += mat[i][j] * vec[j];
}
}
return result;
}
/**
* performs matrix-matrix multiplication
*
* @param mat1 a <code>double</code> matrix
* @param mat2 a <code>double</code> matrix
* @return a <code>double[][]</code> matrix, the result of multiplication
* @throws IllegalArgumentException if the number of columns of <code>mat1</code> is not equal to the number of rows
* of <code>mat2</code>, or either is <code>null</code>
*/
public static double[][] matMatMult(double[][] mat1, double[][] mat2) {
if (mat1 == null
|| mat2 == null
|| mat1[0].length != mat2.length) {
throw new IllegalArgumentException();
}
int resultRows = mat1.length,
resultCols = mat2[0].length,
innerDimension = mat1[0].length;
double[][] result = new double[resultRows][resultCols];
for (int i = 0; i < resultRows; i++) {
for (int j = 0; j < resultCols; j++) {
for (int k = 0; k < innerDimension; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
return result;
}
/**
* Unit tests
*
* @param args ignored
*/
public static void main(String[] args) {
double[] vecA = {1.0, -1.0};
double[] vecB = {0.7071, 0.7071};
double[][] matA = {{0.7071, -0.7071}, {0.7071, 0.7071}};
double[][] matB = {{0.0, -1.0}, {1.0, 0.0}};
// should print: [1.7069999999999999, -0.29300000000000004]
System.out.println(Arrays.toString(vecAdd(vecA, vecB)));
// should print: [0.9999808199999999, 0.9999808199999999]
System.out.println(Arrays.toString(scalarMult(1.4142, vecB)));
// should print: [[0.7071, -1.7071], [1.7071, 0.7071]]
System.out.println(Arrays.deepToString(matAdd(matA, matB)));
// should print: [[-0.0, 1.0], [-1.0, -0.0]]
System.out.println(Arrays.deepToString(scalarMult(-1.0, matB)));
// should print: [1.1412, 0.0]
System.out.println(Arrays.toString(matVecMult(matA, vecA)));
// should print: [[-1.0, 0.0], [0.0, -1.0]]
double[][] matC = matMatMult(matB, matB);
System.out.println(Arrays.deepToString(matC));
// should print: [[1.0, 0.0], [0.0, 1.0]]
System.out.println(Arrays.deepToString(matMatMult(matC, matC)));
}
}
| mit |
SpongePowered/Sponge | src/accessors/java/org/spongepowered/common/accessor/world/entity/animal/SheepAccessor.java | 2016 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.accessor.world.entity.animal;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.common.UntransformedAccessorError;
import java.util.Map;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.world.entity.animal.Sheep;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.ItemLike;
@Mixin(Sheep.class)
public interface SheepAccessor {
@Accessor("DATA_WOOL_ID") static EntityDataAccessor<Byte> accessor$DATA_WOOL_ID() {
throw new UntransformedAccessorError();
}
@Accessor("ITEM_BY_DYE") static Map<DyeColor, ItemLike> accessor$ITEM_BY_DYE() {
throw new UntransformedAccessorError();
}
}
| mit |
CMPE277Shelter/shelterApp | Shelter/app/src/main/java/com/android/shelter/user/LoginActivity.java | 3544 | package com.android.shelter.user;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.android.shelter.HomeActivity;
import com.android.shelter.R;
import com.android.shelter.user.landlord.PostPropertyActivity;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.SignInButton;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;
private UserSessionManager mUserSessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserSessionManager = UserSessionManager.get(getApplicationContext());
mUserSessionManager.registerUserUpdateCallbacks(this, new IUserSessionUpdate() {
@Override
public void signInSuccessfull() {
Log.d(TAG, "Sign in successfull finsihing the activity");
Intent intent = getIntent();
if(intent.hasExtra(HomeActivity.EXTRA_SHOW_POST_PROPERTY) && intent.getBooleanExtra(HomeActivity.EXTRA_SHOW_POST_PROPERTY, false)){
Intent postProperty = PostPropertyActivity.newIntent(getApplicationContext(), null);
startActivityForResult(postProperty, HomeActivity.REQUEST_FRAGMENT);
}
setResult(HomeActivity.REQUEST_LOGIN);
finish();
}
@Override
public void signOutSuccessfull() {
Log.d(TAG, "Logout successfull");
}
});
setContentView(R.layout.activity_login);
LoginButton loginButton = (LoginButton) findViewById(R.id.authButton);
mUserSessionManager.registerFacebookLoginCallback(loginButton);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
mUserSessionManager.setGoogleSignInButtonScopes(signInButton);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(this);
signInButton.setOnClickListener(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override
protected void onStart() {
super.onStart();
//mUserSessionManager.onStartUpInitialization();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mUserSessionManager.callFacebookOnActivityResult(requestCode, resultCode, data);
Log.i(TAG, "OnActivityResult...");
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
mUserSessionManager.handleSignInResult(result);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mUserSessionManager.getGoogleApiClient());
startActivityForResult(signInIntent, RC_SIGN_IN);
}
}
| mit |
Mediv85/jwtExample | server/spring/src/main/java/it/mediv/controller/AuthenticationController.java | 2137 | package it.mediv.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import it.mediv.controller.adapter.AuthReq;
import it.mediv.controller.adapter.AuthResp;
import it.mediv.persistence.Users;
import it.mediv.repository.UsersRepository;
import it.mediv.security.TokenUtils;
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
@Autowired
private UsersRepository ur;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenUtils tokenUtils;
@Autowired
private UserDetailsService userDetailsService;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public AuthResp authenticate(@RequestBody AuthReq ar) throws AuthenticationException {
// Perform the authentication
Authentication authentication = this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(ar.getUsername(), ar.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
// Reload password post-authentication so we can generate token
UserDetails userDetails = this.userDetailsService.loadUserByUsername(ar.getUsername());
String token = this.tokenUtils.generateToken(userDetails);
// Return the token
return new AuthResp(true, token, ar.getUsername());
}
}
| mit |
ITB15-S4-GroupD/Planchester | src/Application/DTO/MusicalWorkDTO.java | 1493 | package Application.DTO;
import Domain.Interfaces.IInstrumentation;
import Domain.Interfaces.IMusicalWork;
/**
* Created by timor on 27.04.2017.
*/
public class MusicalWorkDTO implements IMusicalWork {
private int instrumentationId;
private int id;
private String name;
private String composer;
private IInstrumentation instrumentation;
private IInstrumentation alternativeInstrumentation;
public int getInstrumentationId() {
return instrumentationId;
}
public void setInstrumentationId(int instrumentationId) {
this.instrumentationId = instrumentationId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComposer() {
return composer;
}
public void setComposer(String composer) {
this.composer = composer;
}
public IInstrumentation getInstrumentation() {
return instrumentation;
}
public void setInstrumentation(IInstrumentation instrumentation) {
this.instrumentation = instrumentation;
}
public IInstrumentation getAlternativeInstrumentation() {
return alternativeInstrumentation;
}
public void setAlternativeInstrumentation(IInstrumentation instrumentation) {
this.alternativeInstrumentation = instrumentation;
}
} | mit |
trarck/unluac | src/unluac/decompile/condition/OrCondition.java | 1111 | package unluac.decompile.condition;
import unluac.decompile.Registers;
import unluac.decompile.expression.BinaryExpression;
import unluac.decompile.expression.Expression;
public class OrCondition implements Condition {
private Condition left;
private Condition right;
public OrCondition(Condition left, Condition right) {
this.left = left;
this.right = right;
}
@Override
public Condition inverse() {
if(invertible()) {
return new AndCondition(left.inverse(), right.inverse());
} else {
return new NotCondition(this);
}
}
@Override
public boolean invertible() {
return right.invertible();
}
@Override
public int register() {
return right.register();
}
@Override
public boolean isRegisterTest() {
return false;
}
@Override
public Expression asExpression(Registers r) {
return new BinaryExpression("or", left.asExpression(r), right.asExpression(r), Expression.PRECEDENCE_OR, Expression.ASSOCIATIVITY_NONE);
}
@Override
public String toString() {
return "(" + left + " or " + right + ")";
}
}
| mit |
vrabievictor/proiectCondr | Web/src/model/BarcodeScanner.java | 2252 | package model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class BarcodeScanner {
private String path;
private String result;
public BarcodeScanner(String path2) {
this.path = path2;
String charset = "UTF-8"; // or "ISO-8859-1"
Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
result = readQRCode(this.path,charset,hintMap);
System.out.println(result);
}
public String readQRCode(String filePath, String charset, Map hintMap)
{
BinaryBitmap binaryBitmap = null;
try {
binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(new FileInputStream(filePath)))));
} catch (IOException e) {
e.printStackTrace();
System.out.println("File not found");
}
Result qrCodeResult = null;
try {
qrCodeResult = new MultiFormatReader().decode(binaryBitmap,
hintMap);
} catch (NotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Barcode not found");
}
return qrCodeResult.getText();
}
public static Map<EncodeHintType, ErrorCorrectionLevel> getMap()
{
Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
return hintMap;
}
public void setPath(String path)
{
this.path = path;
}
public String getResult()
{
return this.result;
}
} | mit |
dsaved/africhat-platform-0.1 | actor-apps/app-android/src/main/java/im/AfriChat/messenger/app/util/images/sources/UriSource.java | 4657 | package im.AfriChat.messenger.app.util.images.sources;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import im.AfriChat.messenger.app.util.images.common.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by ex3ndr on 20.09.14.
*/
public class UriSource extends ImageSource {
private Uri uri;
private Context context;
public UriSource(Uri uri, Context context) {
this.uri = uri;
this.context = context;
}
@Override
protected ImageMetadata loadMetadata() throws ImageLoadException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inTempStorage = WorkCache.BITMAP_TMP.get();
InputStream is = null;
try {
is = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(is, null, o);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ImageLoadException("Unable to load image from stream");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (o.outWidth == 0 || o.outHeight == 0) {
throw new ImageLoadException("BitmapFactory.decodeFile: unable to load file");
}
ImageFormat format = ImageFormat.UNKNOWN;
if ("image/jpeg".equals(o.outMimeType) || "image/jpg".equals(o.outMimeType)) {
format = ImageFormat.JPEG;
} else if ("image/gif".equals(o.outMimeType)) {
format = ImageFormat.GIF;
} else if ("image/bmp".equals(o.outMimeType)) {
format = ImageFormat.BMP;
} else if ("image/webp".equals(o.outMimeType)) {
format = ImageFormat.WEBP;
}
int w = o.outWidth;
int h = o.outHeight;
return new ImageMetadata(w, h, 0, format);
}
@Override
public Bitmap loadBitmap() throws ImageLoadException {
return loadBitmap(1);
}
@Override
public Bitmap loadBitmap(int scale) throws ImageLoadException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
o.inTempStorage = WorkCache.BITMAP_TMP.get();
o.inSampleSize = scale;
o.inPreferredConfig = Bitmap.Config.ARGB_8888;
if (Build.VERSION.SDK_INT >= 10) {
o.inPreferQualityOverSpeed = true;
}
if (Build.VERSION.SDK_INT >= 11) {
o.inMutable = true;
}
InputStream is = null;
Bitmap res;
try {
is = context.getContentResolver().openInputStream(uri);
res = BitmapFactory.decodeStream(is, null, o);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ImageLoadException("Unable to load image from stream");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (res == null) {
throw new ImageLoadException("BitmapFactory.decodeFile return null");
}
return res;
}
@Override
public ReuseResult loadBitmap(Bitmap reuse) throws ImageLoadException {
if (Build.VERSION.SDK_INT < 11) {
throw new ImageLoadException("Bitmap reuse not available before HONEYCOMB");
}
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
o.inTempStorage = WorkCache.BITMAP_TMP.get();
o.inPreferQualityOverSpeed = true;
o.inBitmap = reuse;
o.inMutable = true;
o.inPreferredConfig = Bitmap.Config.ARGB_8888;
o.inSampleSize = 1;
InputStream is = null;
Bitmap res;
try {
is = context.getContentResolver().openInputStream(uri);
res = BitmapFactory.decodeStream(is, null, o);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ImageLoadException("Unable to load image from stream");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (res == null) {
throw new ImageLoadException("BitmapFactory.decodeFile return null");
}
return new ReuseResult(res, true);
}
}
| mit |
woojung3/RewardScheme | RewardScheme/lib/jpbc-2.0.0/jpbc-test/src/test/java/it/unisa/dia/gas/plaf/jpbc/pairing/PBCCurveGeneratorPairingTest.java | 1193 | package it.unisa.dia.gas.plaf.jpbc.pairing;
import it.unisa.dia.gas.jpbc.PairingParametersGenerator;
import it.unisa.dia.gas.plaf.jpbc.pbc.curve.*;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assume.assumeTrue;
/**
* @author Angelo De Caro (jpbclib@gmail.com)
*/
public class PBCCurveGeneratorPairingTest extends CurveGeneratorPairingTest {
@Parameterized.Parameters
public static Collection parameters() {
Object[][] data = {
{new PBCTypeACurveGenerator(181, 603)},
{new PBCTypeA1CurveGenerator()},
{new PBCTypeDCurveGenerator(9563)},
{new PBCTypeECurveGenerator(160, 1024)},
{new PBCTypeFCurveGenerator(160)},
{new PBCTypeGCurveGenerator(35707)},
};
return Arrays.asList(data);
}
public PBCCurveGeneratorPairingTest(PairingParametersGenerator parametersGenerator) {
super(false, parametersGenerator);
}
@Override
public void before() throws Exception {
assumeTrue(PairingFactory.getInstance().isPBCAvailable());
super.before();
}
} | mit |
AaronFriesen/Trydent | src/test/java/edu/gatech/cs2340/trydent/test/TimingTest.java | 2924 | package edu.gatech.cs2340.trydent.test;
import static edu.gatech.cs2340.trydent.test.TestUtil.objectEquals;
import org.junit.Test;
import edu.gatech.cs2340.trydent.math.curve.IndexWrapMode;
import edu.gatech.cs2340.trydent.math.curve.TimeWrapMode;
public class TimingTest {
@Test
public void testIndexClamp() {
IndexWrapMode m = IndexWrapMode.CLAMP;
objectEquals(3, m.handle(3, 5));
objectEquals(2, m.handle(3, 3));
objectEquals(0, m.handle(-1, 5));
objectEquals(5, m.handle(1000, 6));
}
@Test
public void testIndexWrap() {
IndexWrapMode m = IndexWrapMode.WRAP;
objectEquals(3, m.handle(3, 5));
objectEquals(0, m.handle(3, 3));
objectEquals(4, m.handle(-1, 5));
objectEquals(4, m.handle(10, 6));
}
@Test
public void testIndexReflect() {
IndexWrapMode m = IndexWrapMode.REFLECT;
objectEquals(3, m.handle(3, 5));
objectEquals(2, m.handle(3, 3));
objectEquals(1, m.handle(-1, 5));
objectEquals(3, m.handle(8, 6));
}
@Test
public void testTimeClamp() {
TimeWrapMode m = TimeWrapMode.CLAMP;
objectEquals(3.0, m.handle(3.0, 10.0));
objectEquals(0.0, m.handle(0.0, 10.0));
objectEquals(10.0, m.handle(10.0, 10.0));
objectEquals(0.0, m.handle(-0.1, 10.0));
objectEquals(0.0, m.handle(-7.0, 10.0));
objectEquals(10.0, m.handle(10.1, 10.0));
objectEquals(10.0, m.handle(17.0, 10.0));
objectEquals(0.0, m.handle(-0.25 - 10.0*12.0, 10.0));
objectEquals(10.0, m.handle(17.0 + 10.0*12.0, 10.0));
}
@Test
public void testTimeWrap() {
TimeWrapMode m = TimeWrapMode.WRAP;
objectEquals(3.0, m.handle(3.0, 10.0));
objectEquals(0.0, m.handle(0.0, 10.0));
objectEquals(9.9999, m.handle(9.9999, 10.0));
objectEquals(9.9, m.handle(-0.1, 10.0));
objectEquals(3.0, m.handle(-7.0, 10.0));
objectEquals(0.25, m.handle(10.25, 10.0));
objectEquals(7.0, m.handle(17.0, 10.0));
objectEquals(9.75, m.handle(-0.25 - 10.0*12.0, 10.0));
objectEquals(7.0, m.handle(17.0 + 10.0*12.0, 10.0));
}
@Test
public void testTimeReflect() {
TimeWrapMode m = TimeWrapMode.REFLECT;
objectEquals(3.0, m.handle(3.0, 10.0));
objectEquals(0.0, m.handle(0.0, 10.0));
objectEquals(9.9999, m.handle(9.9999, 10.0));
objectEquals(0.25, m.handle(-0.25, 10.0));
objectEquals(7.0, m.handle(-7.0, 10.0));
objectEquals(9.75, m.handle(10.25, 10.0));
objectEquals(3.0, m.handle(17.0, 10.0));
objectEquals(0.25, m.handle(-0.25 - 10.0*12.0, 10.0));
objectEquals(3.0, m.handle(17.0 + 10.0*12.0, 10.0));
objectEquals(9.75, m.handle(-0.25 - 10.0*11.0, 10.0));
objectEquals(7.0, m.handle(17.0 + 10.0*11.0, 10.0));
}
}
| mit |
absentm/Demo | SpringMVC-demo/base-demo/demo/src/main/java/com/absentm/demo/beans/FileModel.java | 314 | package com.absentm.demo.beans;
import org.springframework.web.multipart.MultipartFile;
/**
* FileModel
*
* @author AbsentM
*
*/
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
| mit |
seantitus/WaterReporting | app/src/main/java/com/zoinks/waterreporting/model/Facade.java | 9500 | package com.zoinks.waterreporting.model;
import android.util.Log;
import com.github.mikephil.charting.data.Entry;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* Facade for the model for users and water reports
*
* Created by Nancy on 03/24/2017.
*/
public class Facade {
public final static String USER_JSON = "users.json";
public final static String REPORT_JSON = "reports.json";
// required model classes
private UserSvcProvider usp;
private WaterReportSvcProvider wrsp;
// singleton
private static Facade instance = new Facade();
private Facade() {
usp = new UserSvcProvider();
wrsp = new WaterReportSvcProvider();
}
/**
* Accessor for singleton instance of Facade
*
* @return Facade singleton instance
*/
public static Facade getInstance() {
return instance;
}
/**
* Loads data from saved json
*
* @param userFile the file from which to load the user json
* @param reportsFile the file from which to load the reports json
* @return true if successful
*/
public boolean loadData(File userFile, File reportsFile) {
try { // first load up the users
BufferedReader input = new BufferedReader(new FileReader(userFile));
// Since we saved the json as a string, we just read in the string normally
String inString = input.readLine();
Log.d("DEBUG", "JSON: " + inString);
// use the Gson library to recreate the object references and links
Gson gson = new Gson();
usp = gson.fromJson(inString, UserSvcProvider.class);
input.close();
} catch (IOException e) {
Log.e("Facade", "Failed to open/read the buffered reader for user json");
return false;
}
try { // next load up the water reports
BufferedReader input = new BufferedReader(new FileReader(reportsFile));
// Since we saved the json as a string, we just read in the string normally
String inString = input.readLine();
Log.d("DEBUG", "JSON: " + inString);
// use the Gson library to recreate the object references and links
Gson gson = new Gson();
wrsp = gson.fromJson(inString, WaterReportSvcProvider.class);
input.close();
} catch (IOException e) {
Log.e("Facade", "Failed to open/read the buffered reader for reports json");
return false;
}
return true;
}
/**
* Saves data to json
*
* @param userFile the json file to which to save the user
* @param reportsFile the json file to which to save the reports
* @return true if successful
*/
public boolean saveData(File userFile, File reportsFile) {
try {
PrintWriter writer = new PrintWriter(userFile);
Gson gson = new Gson();
// convert our objects to a string for output
String outString = gson.toJson(usp);
Log.d("DEBUG", "JSON Saved: " + outString);
// then just write the string
writer.println(outString);
writer.close();
} catch (FileNotFoundException e) {
Log.e("Facade", "Failed to open json file for output");
return false;
}
try {
PrintWriter writer = new PrintWriter(reportsFile);
Gson gson = new Gson();
// convert our objects to a string for output
String outString = gson.toJson(wrsp);
Log.d("DEBUG", "JSON Saved: " + outString);
// then just write the string
writer.println(outString);
writer.close();
} catch (FileNotFoundException e) {
Log.e("Facade", "Failed to open json file for output");
return false;
}
return true;
}
/**
* Returns the currently logged in user, if any
*
* @return the currently logged in user, if any
*/
public User getCurrentUser() {
return usp.getCurrentUser();
}
/**
* Gets all of the users currently registered
* @return a List of all of the Users currently registered
*/
public List<User> getAllUsers() {
return usp.getAllUsers();
}
/**
* Attempts to register a new user
*
* @param firstName first name of the new user
* @param lastName last name of the new user
* @param username username of the new user
* @param password un-hashed password of new user
* @param privilege type of new user, used for privilege
* @return True if the new user was registered, False if the user was not registered (ie username taken)
*/
public boolean registerUser(String firstName, String lastName, String username, String password,
UserType privilege) {
return usp.register(firstName, lastName, username, password, privilege);
}
/**
* Delete user's account
*
* @param username username of the user to delete
*/
public void deleteUser(String username) {
usp.deleteUser(username);
}
/**
* Gets the User by username
* @param username of User to get
* @return User with associated username
*/
public User getUserByUsername(String username) {
return usp.getUserByUsername(username);
}
/**
* Updates attributes passed in to update profile of current user
*
* @param oldUsername username from current user
* @param newUsername username from edit text
* @param firstName new or old firstName
* @param lastName new or old lastName
* @param password "" if password was unchanged, otherwise old hashed password
* @return boolean true if profile was updated
*/
public boolean updateUser(String oldUsername, String newUsername, String firstName,
String lastName, String password, String email, String address,
String phone) {
return usp.update(oldUsername, newUsername, firstName, lastName, password, email, address,
phone);
}
/**
* Attempts login
*
* @param username username of profile trying to login as
* @param password to be checked for a match
* @return True only if user exists and password matches
* False if password incorrect, user does not exist, or user blocked
*/
public boolean login(String username, String password) {
return usp.login(username, password);
}
/**
* Logs user out of application and resets current user
*/
public void logout() {
usp.logout();
}
/**
* Get the list of water reports
*
* @return the list of water reports
*/
public List<WaterReport> getReports() {
return wrsp.getReports();
}
/**
* Get the list of water source reports
*
* @return the list of water source reports
*/
public List<WaterReport> getSourceReports() {
return wrsp.getSourceReports();
}
/**
* Get the list of water quality reports for managers to view
*
* @return the list of water quality reports
*/
public List<WaterReport> getQualityReports() {
return wrsp.getQualityReports();
}
/**
* Adds a water source report where time is current time and author is current user
*
* @param latitude latitude of the water report
* @param longitude longitude of the water report
* @param type type of water at the water source
* @param condition condition of water at the water source
*/
public void addSourceReport(double latitude, double longitude, WaterSourceType type,
WaterSourceCondition condition) {
wrsp.addSourceReport(latitude, longitude, type, condition, usp.getCurrentUser());
}
/**
* Adds a water quality report where time is current time and author is current user
*
* @param latitude latitude of the water report
* @param longitude longitude of the water report
* @param condition condition of water at the water source
* @param virusPPM virus concentration measured in PPM at the water source
* @param contaminantPPM contaminant concentration measured in PPM at the water source
*/
public void addQualityReport(double latitude, double longitude, WaterQualityCondition condition,
double virusPPM, double contaminantPPM) {
wrsp.addQualityReport(latitude, longitude, condition, virusPPM, contaminantPPM, usp.getCurrentUser());
}
/**
* Returns the data for the year requested, 12 points, one for each month for the location requested
*
* @param year the year from which data is requested
* @param latitude the latitude of the reports to get
* @param longitude the longitude of the reports to get
* @param virus true if the manager wishes to graph virus PPM, false to graph contaminant PPM
*/
public List<Entry> getYearsData(int year, double latitude, double longitude, boolean virus) {
return wrsp.getYearsData(year, latitude, longitude, virus);
}
}
| mit |
unisar/CIFARClassification | dl4j/AllConvolutionDL4J.java | 9129 | import org.apache.commons.math3.optim.nonlinear.vector.Weight;
import org.datavec.api.records.reader.RecordReader;
import org.datavec.api.records.reader.impl.ComposableRecordReader;
import org.datavec.api.records.reader.impl.csv.CSVRecordReader;
import org.datavec.api.split.CollectionInputSplit;
import org.datavec.api.split.FileSplit;
import org.datavec.api.split.InputSplit;
import org.datavec.image.recordreader.ImageRecordReader;
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.*;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.api.IterationListener;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.ui.weights.HistogramIterationListener;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.convolution.Convolution;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.SplitTestAndTrain;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static java.lang.System.exit;
/**
* Created by unisar
*/
public class AllConvolutionDL4J {
private static final Logger log = LoggerFactory.getLogger(AllConvolutionDL4J.class);
private static String X_Train;
private static String Y_Train;
private static String X_Test;
private static String Image_Path;
public static void main(String[] args) throws Exception {
if (args.length < 4)
{
System.out.println("Usage: X_Train Y_Train X_Test IMAGE_FOLDER");
exit(1);
}
X_Train = args[0];
Y_Train = args[1];
X_Test = args[2];
Image_Path = args[3];
int nChannels = 3;
int outputNum = 10;
int batchSize = 100;
int nEpochs = 50;
int iterations = 1;
int seed = 123;
Nd4j.ENFORCE_NUMERICAL_STABILITY = true;
RecordReader recordReader = loadTrainingData();
log.info("Load data....");
DataSetIterator dataSetIterator = new RecordReaderDataSetIterator(recordReader, batchSize, 1, 10);
// DataSetIterator testSetIterator = new RecordReaderDataSetIterator(loadTestingData(), 1);
log.info("Build model....");
MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder()
.seed(seed).miniBatch(true)
.iterations(iterations)
.regularization(true).l2(0.0005)
.learningRate(0.1) //.biasLearningRate(0.2)
.learningRateDecayPolicy(LearningRatePolicy.Step).lrPolicyDecayRate(0.1).lrPolicySteps(45000/batchSize * 50)
.weightInit(WeightInit.XAVIER)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(Updater.NESTEROVS).momentum(0.9)
.list()
.layer(0, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 })
.nOut(96)
.activation("relu")
.build())
.layer(1, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 })
.nOut(96)
.activation("relu")
.build())
.layer(2, new ConvolutionLayer.Builder().kernelSize(new int[] {2, 2}).stride(new int[] {2, 2})
.nOut(96).activation("relu")
.dropOut(0.5)
.build())
.layer(3, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 })
.nOut(192)
.activation("relu")
.build())
.layer(4, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 })
.nOut(192)
.activation("relu")
.build())
.layer(5, new ConvolutionLayer.Builder().kernelSize(new int[] {2, 2}).stride(new int[] {2, 2})
.nOut(192).activation("relu")
.dropOut(0.5)
.build())
.layer(6, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 })
.nOut(192)
.activation("relu")
.build())
.layer(7, new ConvolutionLayer.Builder().kernelSize(new int[] {1,1}).stride(new int[] { 1, 1 })
.nOut(192)
.activation("relu")
.build())
.layer(8, new ConvolutionLayer.Builder().kernelSize(new int[] {1,1}).stride(new int[] { 1, 1 })
.nOut(10)
.activation("relu")
.build())
.layer(9, new SubsamplingLayer.Builder().kernelSize(new int[] {8, 8}).stride(new int[] { 1, 1 }).build())
.layer(10, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(outputNum)
.activation("softmax")
.build()).setInputType(InputType.convolutionalFlat(32, 32, 3))
.backprop(true)
.pretrain(false);
MultiLayerConfiguration conf = builder.build();
MultiLayerNetwork model = new MultiLayerNetwork(conf);
model.init();
log.info("Train model....");
model.setListeners(new IterationListener[] {new ScoreIterationListener(1), new HistogramIterationListener(1)});
DataSet cifarDataSet;
SplitTestAndTrain trainAndTest;
for( int i=0; i<nEpochs; i++ ) {
dataSetIterator.reset();
List<INDArray> testInput = new ArrayList<>();
List<INDArray> testLabels = new ArrayList<>();
while (dataSetIterator.hasNext())
{
cifarDataSet = dataSetIterator.next();
trainAndTest = cifarDataSet.splitTestAndTrain((int)(batchSize*0.9));
DataSet trainInput = trainAndTest.getTrain();
testInput.add(trainAndTest.getTest().getFeatureMatrix());
testLabels.add(trainAndTest.getTest().getLabels());
model.fit(trainInput);
}
File file = File.createTempFile("Epoch", String.valueOf(i));
ModelSerializer.writeModel(model, file, true );
log.info("*** Completed epoch {} ***", i);
log.info("Evaluate model....");
Evaluation eval = new Evaluation(outputNum);
for (int j = 0; j < testInput.size(); j++) {
INDArray output = model.output(testInput.get(j));
eval.eval(testLabels.get(i), output);
}
log.info(eval.stats());
// testSetIterator.reset();
dataSetIterator.reset();
}
log.info("****************Example finished********************");
}
public static RecordReader loadTestingData() throws Exception {
RecordReader imageReader = new ImageRecordReader(32, 32, 3, 255);
List<URI> images = new ArrayList<>();
for (String number: Files.readAllLines(Paths.get(X_Test), Charset.defaultCharset()))
images.add(URI.create("file:/"+ Image_Path + "/Test/" + number + ".png"));
InputSplit splits = new CollectionInputSplit(images);
imageReader.initialize(splits);
return imageReader;
}
public static RecordReader loadTrainingData() throws Exception {
RecordReader imageReader = new ImageRecordReader(32, 32, 3, 255);
List<URI> images = new ArrayList<>();
for (String number: Files.readAllLines(Paths.get(X_Train), Charset.defaultCharset()))
images.add(URI.create("file:/"+ Image_Path + "/Train/" + number + ".png"));
InputSplit splits = new CollectionInputSplit(images);
imageReader.initialize(splits);
RecordReader labelsReader = new CSVRecordReader();
labelsReader.initialize(new FileSplit(new File(Y_Train)));
return new ComposableRecordReader(imageReader, labelsReader);
}
}
| mit |
chreck/movento-webview | android/src/com/movento/webview/MoventoWebviewAndroidModule.java | 1227 | /**
* This file was auto-generated by the Titanium Module SDK helper for Android
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
*/
package com.movento.webview;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
@Kroll.module(name="MoventoWebviewAndroid", id="com.movento.webview")
public class MoventoWebviewAndroidModule extends KrollModule
{
// Standard Debugging variables
private static final String TAG = "MoventoWebviewAndroidModule";
private static final boolean DBG = TiConfig.LOGD;
// You can define constants with @Kroll.constant, for example:
// @Kroll.constant public static final String EXTERNAL_NAME = value;
public MoventoWebviewAndroidModule()
{
super();
Log.i(TAG, "MoventoWebviewAndroidModule");
}
@Override
public String getApiName()
{
return "com.movento.webview";
}
}
| mit |
sauliusg/jabref | src/main/java/org/jabref/gui/maintable/MainTable.java | 17294 | package org.jabref.gui.maintable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.swing.undo.UndoManager;
import javafx.collections.ListChangeListener;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import org.jabref.gui.DialogService;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.Globals;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.edit.EditAction;
import org.jabref.gui.externalfiles.ImportHandler;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.maintable.columns.MainTableColumn;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.ViewModelTableRowFactory;
import org.jabref.logic.importer.ImportCleanup;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.OS;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.database.event.EntriesAddedEvent;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainTable extends TableView<BibEntryTableViewModel> {
private static final Logger LOGGER = LoggerFactory.getLogger(MainTable.class);
private final LibraryTab libraryTab;
private final DialogService dialogService;
private final BibDatabaseContext database;
private final MainTableDataModel model;
private final ImportHandler importHandler;
private final CustomLocalDragboard localDragboard;
private long lastKeyPressTime;
private String columnSearchTerm;
public MainTable(MainTableDataModel model,
LibraryTab libraryTab,
BibDatabaseContext database,
PreferencesService preferencesService,
DialogService dialogService,
StateManager stateManager,
ExternalFileTypes externalFileTypes,
KeyBindingRepository keyBindingRepository) {
super();
this.libraryTab = libraryTab;
this.dialogService = dialogService;
this.database = Objects.requireNonNull(database);
this.model = model;
UndoManager undoManager = libraryTab.getUndoManager();
MainTablePreferences mainTablePreferences = preferencesService.getMainTablePreferences();
importHandler = new ImportHandler(
database, externalFileTypes,
preferencesService,
Globals.getFileUpdateMonitor(),
undoManager,
stateManager);
localDragboard = stateManager.getLocalDragboard();
this.setOnDragOver(this::handleOnDragOverTableView);
this.setOnDragDropped(this::handleOnDragDroppedTableView);
this.getColumns().addAll(
new MainTableColumnFactory(
database,
preferencesService,
externalFileTypes,
libraryTab.getUndoManager(),
dialogService,
stateManager).createColumns());
new ViewModelTableRowFactory<BibEntryTableViewModel>()
.withOnMouseClickedEvent((entry, event) -> {
if (event.getClickCount() == 2) {
libraryTab.showAndEdit(entry.getEntry());
}
})
.withContextMenu(entry -> RightClickMenu.create(entry,
keyBindingRepository,
libraryTab,
dialogService,
stateManager,
preferencesService,
undoManager,
Globals.getClipboardManager()))
.setOnDragDetected(this::handleOnDragDetected)
.setOnDragDropped(this::handleOnDragDropped)
.setOnDragOver(this::handleOnDragOver)
.setOnDragExited(this::handleOnDragExited)
.setOnMouseDragEntered(this::handleOnDragEntered)
.install(this);
this.getSortOrder().clear();
/* KEEP for debugging purposes
for (var colModel : mainTablePreferences.getColumnPreferences().getColumnSortOrder()) {
for (var col : this.getColumns()) {
var tablecColModel = ((MainTableColumn<?>) col).getModel();
if (tablecColModel.equals(colModel)) {
LOGGER.debug("Adding sort order for col {} ", col);
this.getSortOrder().add(col);
break;
}
}
}
*/
mainTablePreferences.getColumnPreferences().getColumnSortOrder().forEach(columnModel ->
this.getColumns().stream()
.map(column -> (MainTableColumn<?>) column)
.filter(column -> column.getModel().equals(columnModel))
.findFirst()
.ifPresent(column -> this.getSortOrder().add(column)));
if (mainTablePreferences.getResizeColumnsToFit()) {
this.setColumnResizePolicy(new SmartConstrainedResizePolicy());
}
this.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
this.setItems(model.getEntriesFilteredAndSorted());
// Enable sorting
model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty());
this.getStylesheets().add(MainTable.class.getResource("MainTable.css").toExternalForm());
// Store visual state
new PersistenceVisualStateTable(this, preferencesService);
setupKeyBindings(keyBindingRepository);
this.setOnKeyTyped(key -> {
if (this.getSortOrder().isEmpty()) {
return;
}
this.jumpToSearchKey(getSortOrder().get(0), key);
});
database.getDatabase().registerListener(this);
}
/**
* This is called, if a user starts typing some characters into the keyboard with focus on main table. The {@link MainTable} will scroll to the cell with the same starting column value and typed string
*
* @param sortedColumn The sorted column in {@link MainTable}
* @param keyEvent The pressed character
*/
private void jumpToSearchKey(TableColumn<BibEntryTableViewModel, ?> sortedColumn, KeyEvent keyEvent) {
if ((keyEvent.getCharacter() == null) || (sortedColumn == null)) {
return;
}
if ((System.currentTimeMillis() - lastKeyPressTime) < 700) {
columnSearchTerm += keyEvent.getCharacter().toLowerCase();
} else {
columnSearchTerm = keyEvent.getCharacter().toLowerCase();
}
lastKeyPressTime = System.currentTimeMillis();
this.getItems().stream()
.filter(item -> Optional.ofNullable(sortedColumn.getCellObservableValue(item).getValue())
.map(Object::toString)
.orElse("")
.toLowerCase()
.startsWith(columnSearchTerm))
.findFirst()
.ifPresent(item -> {
this.scrollTo(item);
this.clearAndSelect(item.getEntry());
});
}
@Subscribe
public void listen(EntriesAddedEvent event) {
DefaultTaskExecutor.runInJavaFXThread(() -> clearAndSelect(event.getFirstEntry()));
}
public void clearAndSelect(BibEntry bibEntry) {
findEntry(bibEntry).ifPresent(entry -> {
getSelectionModel().clearSelection();
getSelectionModel().select(entry);
scrollTo(entry);
});
}
public void copy() {
List<BibEntry> selectedEntries = getSelectedEntries();
if (!selectedEntries.isEmpty()) {
try {
Globals.getClipboardManager().setContent(selectedEntries);
dialogService.notify(libraryTab.formatOutputMessage(Localization.lang("Copied"), selectedEntries.size()));
} catch (IOException e) {
LOGGER.error("Error while copying selected entries to clipboard", e);
}
}
}
public void cut() {
copy();
libraryTab.delete(true);
}
private void setupKeyBindings(KeyBindingRepository keyBindings) {
this.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ENTER) {
getSelectedEntries().stream()
.findFirst()
.ifPresent(libraryTab::showAndEdit);
event.consume();
return;
}
Optional<KeyBinding> keyBinding = keyBindings.mapToKeyBinding(event);
if (keyBinding.isPresent()) {
switch (keyBinding.get()) {
case SELECT_FIRST_ENTRY:
clearAndSelectFirst();
event.consume();
break;
case SELECT_LAST_ENTRY:
clearAndSelectLast();
event.consume();
break;
case PASTE:
if (!OS.OS_X) {
new EditAction(StandardActions.PASTE, libraryTab.frame(), Globals.stateManager).execute();
}
event.consume();
break;
case COPY:
new EditAction(StandardActions.COPY, libraryTab.frame(), Globals.stateManager).execute();
event.consume();
break;
case CUT:
new EditAction(StandardActions.CUT, libraryTab.frame(), Globals.stateManager).execute();
event.consume();
break;
default:
// Pass other keys to parent
}
}
});
}
public void clearAndSelectFirst() {
getSelectionModel().clearSelection();
getSelectionModel().selectFirst();
scrollTo(0);
}
private void clearAndSelectLast() {
getSelectionModel().clearSelection();
getSelectionModel().selectLast();
scrollTo(getItems().size() - 1);
}
public void paste(BibDatabaseMode bibDatabaseMode) {
// Find entries in clipboard
List<BibEntry> entriesToAdd = Globals.getClipboardManager().extractData();
ImportCleanup cleanup = new ImportCleanup(bibDatabaseMode);
cleanup.doPostCleanup(entriesToAdd);
libraryTab.insertEntries(entriesToAdd);
if (!entriesToAdd.isEmpty()) {
this.requestFocus();
}
}
private void handleOnDragOver(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel item, DragEvent event) {
if (event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.ANY);
ControlHelper.setDroppingPseudoClasses(row, event);
}
event.consume();
}
private void handleOnDragOverTableView(DragEvent event) {
if (event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.ANY);
}
event.consume();
}
private void handleOnDragEntered(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, MouseDragEvent event) {
// Support the following gesture to select entries: click on one row -> hold mouse button -> move over other rows
// We need to select all items between the starting row and the row where the user currently hovers the mouse over
// It is not enough to just select the currently hovered row since then sometimes rows are not marked selected if the user moves to fast
@SuppressWarnings("unchecked")
TableRow<BibEntryTableViewModel> sourceRow = (TableRow<BibEntryTableViewModel>) event.getGestureSource();
getSelectionModel().selectRange(sourceRow.getIndex(), row.getIndex());
}
private void handleOnDragExited(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, DragEvent dragEvent) {
ControlHelper.removeDroppingPseudoClasses(row);
}
private void handleOnDragDetected(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, MouseEvent event) {
// Start drag'n'drop
row.startFullDrag();
List<BibEntry> entries = getSelectionModel().getSelectedItems().stream().map(BibEntryTableViewModel::getEntry).collect(Collectors.toList());
// The following is necesary to initiate the drag and drop in javafx, although we don't need the contents
// It doesn't work without
ClipboardContent content = new ClipboardContent();
Dragboard dragboard = startDragAndDrop(TransferMode.MOVE);
content.put(DragAndDropDataFormats.ENTRIES, "");
dragboard.setContent(content);
if (!entries.isEmpty()) {
localDragboard.putBibEntries(entries);
}
event.consume();
}
private void handleOnDragDropped(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel target, DragEvent event) {
boolean success = false;
if (event.getDragboard().hasFiles()) {
List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList());
// Different actions depending on where the user releases the drop in the target row
// Bottom + top -> import entries
// Center -> link files to entry
// Depending on the pressed modifier, move/copy/link files to drop target
switch (ControlHelper.getDroppingMouseLocation(row, event)) {
case TOP, BOTTOM -> importHandler.importFilesInBackground(files).executeWith(Globals.TASK_EXECUTOR);
case CENTER -> {
BibEntry entry = target.getEntry();
switch (event.getTransferMode()) {
case LINK -> {
LOGGER.debug("Mode LINK"); // shift on win or no modifier
importHandler.getLinker().addFilesToEntry(entry, files);
}
case MOVE -> {
LOGGER.debug("Mode MOVE"); // alt on win
importHandler.getLinker().moveFilesToFileDirAndAddToEntry(entry, files);
}
case COPY -> {
LOGGER.debug("Mode Copy"); // ctrl on win
importHandler.getLinker().copyFilesToFileDirAndAddToEntry(entry, files);
}
}
}
}
success = true;
}
event.setDropCompleted(success);
event.consume();
}
private void handleOnDragDroppedTableView(DragEvent event) {
boolean success = false;
if (event.getDragboard().hasFiles()) {
List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList());
importHandler.importFilesInBackground(files).executeWith(Globals.TASK_EXECUTOR);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
public void addSelectionListener(ListChangeListener<? super BibEntryTableViewModel> listener) {
getSelectionModel().getSelectedItems().addListener(listener);
}
public MainTableDataModel getTableModel() {
return model;
}
public BibEntry getEntryAt(int row) {
return model.getEntriesFilteredAndSorted().get(row).getEntry();
}
public List<BibEntry> getSelectedEntries() {
return getSelectionModel()
.getSelectedItems()
.stream()
.map(BibEntryTableViewModel::getEntry)
.collect(Collectors.toList());
}
private Optional<BibEntryTableViewModel> findEntry(BibEntry entry) {
return model.getEntriesFilteredAndSorted()
.stream()
.filter(viewModel -> viewModel.getEntry().equals(entry))
.findFirst();
}
}
| mit |
backpaper0/spring-boot-sandbox | jpa-example/src/test/java/com/example/many_to_one/ManyToOneTest.java | 1808 | package com.example.many_to_one;
import static org.junit.jupiter.api.Assertions.*;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig
@SpringBootTest
@Transactional
class ManyToOneTest {
@Autowired
private EntityManager em;
private Long author1;
private Long book1;
private Long book2;
private Long book3;
@BeforeEach
void setUp() throws Exception {
final AuthorM2O a = new AuthorM2O();
a.setName("コナン・ドイル");
final BookM2O b1 = new BookM2O();
b1.setTitle("緋色の研究");
final BookM2O b2 = new BookM2O();
b2.setTitle("四つの署名");
final BookM2O b3 = new BookM2O();
b3.setTitle("恐怖の谷");
b3.setAuthor(a);
em.persist(a);
em.persist(b1);
em.persist(b2);
em.persist(b3);
em.flush();
author1 = a.getId();
book1 = b1.getId();
book2 = b2.getId();
book3 = b3.getId();
}
@AfterEach
void tearDown() throws Exception {
em.remove(em.find(AuthorM2O.class, author1));
em.remove(em.find(BookM2O.class, book1));
em.remove(em.find(BookM2O.class, book2));
em.remove(em.find(BookM2O.class, book3));
}
@Test
void getAuthorViaBook() throws Exception {
final BookM2O b = em.find(BookM2O.class, book3);
assertEquals("コナン・ドイル", b.getAuthor().getName());
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/chain/dto/CustomerOrderDTO.java | 16040 | package com.swfarm.biz.chain.dto;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.bo.CustomerOrderItem;
public class CustomerOrderDTO implements Serializable {
private String id;
private String customerOrderId;
private String customerOrderNo;
private Timestamp orderTime;
private Timestamp shippedTime;
private Timestamp paidTime;
private Timestamp allocateTime;
private Timestamp deliverTime;
private Timestamp modifiedTime;
private String customerOrderProcessStep;
private String exceptionalProcessStep;
private String accountNumber;
private String customerName;
private String buyerFullname;
private String buyerPhoneNumber;
private String buyerEmail;
private String buyerAddress1;
private String buyerAddress2;
private String buyerCity;
private String buyerState;
private String buyerZip;
private String buyerCountry;
private String warehouseCode;
private List customerOrderItemDTOs = new ArrayList();
private String saleChannel;
private String saleChannelOrderId;
private String saleRecordNo;
private String shippingForwarderMethod;
private String shippingOrderNo;
private String sfmOrderNo;
private Double totalPrice;
private Double postageFee;
private String stockLocation;
private String buyerCheckoutMessage;
private String shippingServiceSelected;
private String packingMaterialArticleNumber;
private String payPalEmailAddress;
private String payPalTransactionId;
private Double totalAvgPurchasePrice;
private Double totalWeight;
private Double testingShippingCost;
private String customerOrderProcessStepName;
private String allocationProductVoucherNos;
public CustomerOrderDTO() {
}
public CustomerOrderDTO(CustomerOrder customerOrder) {
this.id = customerOrder.getId();
this.customerOrderId = customerOrder.getId();
this.customerOrderNo = customerOrder.getCustomerOrderNo();
this.orderTime = customerOrder.getOrderTime();
this.shippedTime = customerOrder.getShippedTime();
this.paidTime = customerOrder.getPaidTime();
this.allocateTime = customerOrder.getAllocateTime();
this.deliverTime = customerOrder.getDeliverTime();
this.modifiedTime = customerOrder.getModifiedTime();
this.customerOrderProcessStep = customerOrder.getCustomerOrderProcessStep();
this.exceptionalProcessStep = customerOrder.getExceptionalProcessStep();
this.accountNumber = customerOrder.getAccountNumber();
this.customerName = customerOrder.getCustomerName();
this.buyerFullname = customerOrder.getBuyerFullname();
this.buyerPhoneNumber = customerOrder.getBuyerPhoneNumber();
this.buyerEmail = customerOrder.getBuyerEmail();
this.buyerAddress1 = customerOrder.getBuyerAddress1();
this.buyerAddress2 = customerOrder.getBuyerAddress2();
this.buyerCity = customerOrder.getBuyerCity();
this.buyerState = customerOrder.getBuyerState();
this.buyerZip = customerOrder.getBuyerZip();
this.buyerCountry = customerOrder.getBuyerCountry();
this.warehouseCode = customerOrder.getWarehouseCode();
for (Iterator iter = customerOrder.getCustomerOrderItems().iterator(); iter.hasNext();) {
CustomerOrderItem customerOrderItem = (CustomerOrderItem) iter.next();
CustomerOrderItemDTO customerOrderItemDTO = new CustomerOrderItemDTO(customerOrderItem);
this.addCustomerOrderItemDTO(customerOrderItemDTO);
}
this.saleChannel = customerOrder.getSaleChannel();
this.saleChannelOrderId = customerOrder.getSaleChannelOrderId();
this.saleRecordNo = customerOrder.getSaleRecordNo();
this.shippingForwarderMethod = customerOrder.getShippingForwarderMethod();
this.shippingOrderNo = customerOrder.getShippingOrderNo();
this.sfmOrderNo = customerOrder.getSfmOrderNo();
this.totalPrice = customerOrder.getTotalPrice();
this.postageFee = customerOrder.getPostageFee();
this.stockLocation = customerOrder.getStockLocation();
this.buyerCheckoutMessage = customerOrder.getBuyerCheckoutMessage();
this.shippingServiceSelected = customerOrder.getShippingServiceSelected();
this.packingMaterialArticleNumber = customerOrder.getPackingMaterialArticleNumber();
this.payPalEmailAddress = customerOrder.getPayPalEmailAddress();
this.payPalTransactionId = customerOrder.getPayPalTransactionId();
this.totalAvgPurchasePrice = customerOrder.getTotalAvgPurchasePrice();
this.totalWeight = customerOrder.getTotalWeight();
this.testingShippingCost = customerOrder.getTestingShippingCost();
this.customerOrderProcessStepName = customerOrder.getCustomerOrderProcessStepName();
this.allocationProductVoucherNos = customerOrder.getAllocationProductVoucherNos();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCustomerOrderId() {
return customerOrderId;
}
public void setCustomerOrderId(String customerOrderId) {
this.customerOrderId = customerOrderId;
}
public String getCustomerOrderNo() {
return customerOrderNo;
}
public void setCustomerOrderNo(String customerOrderNo) {
this.customerOrderNo = customerOrderNo;
}
public List getCustomerOrderItemDTOs() {
if (customerOrderItemDTOs == null) {
customerOrderItemDTOs = new ArrayList();
}
Collections.sort(customerOrderItemDTOs, new Comparator() {
public int compare(Object obj1, Object obj2) {
CustomerOrderItemDTO coiDTO1 = (CustomerOrderItemDTO) obj1;
CustomerOrderItemDTO coiDTO2 = (CustomerOrderItemDTO) obj2;
int result = 0;
if (StringUtils.isNotEmpty(coiDTO1.getSaleRecordNo())
&& StringUtils.isNotEmpty(coiDTO2.getSaleRecordNo())) {
result = coiDTO1.getSaleRecordNo().compareTo(coiDTO2.getSaleRecordNo());
}
else if (StringUtils.isNotEmpty(coiDTO1.getSaleRecordNo())
&& StringUtils.isEmpty(coiDTO2.getSaleRecordNo())) {
result = -1;
}
else if (StringUtils.isEmpty(coiDTO1.getSaleRecordNo())
&& StringUtils.isNotEmpty(coiDTO2.getSaleRecordNo())) {
result = 1;
}
else {
if (StringUtils.isNotEmpty(coiDTO1.getCustomerOrderItemId())
&& StringUtils.isNotEmpty(coiDTO2.getCustomerOrderItemId())) {
result = coiDTO1.getCustomerOrderItemId().compareTo(coiDTO2.getCustomerOrderItemId());
}
else if (StringUtils.isNotEmpty(coiDTO1.getArticleNumber())
&& StringUtils.isNotEmpty(coiDTO2.getArticleNumber())) {
result = coiDTO1.getArticleNumber().compareTo(coiDTO2.getArticleNumber());
}
else {
result = coiDTO1.toString().compareTo(coiDTO2.toString());
}
}
return result;
}
});
return customerOrderItemDTOs;
}
public void addCustomerOrderItemDTO(CustomerOrderItemDTO coiDTO) {
if (!this.getCustomerOrderItemDTOs().contains(coiDTO)) {
this.customerOrderItemDTOs.add(coiDTO);
coiDTO.setCustomerOrderDTO(this);
}
}
public void setCustomerOrderItemDTOs(List customerOrderItemDTOs) {
this.customerOrderItemDTOs = customerOrderItemDTOs;
}
public Timestamp getOrderTime() {
return orderTime;
}
public void setOrderTime(Timestamp orderTime) {
this.orderTime = orderTime;
}
public String getCustomerOrderProcessStep() {
return customerOrderProcessStep;
}
public void setCustomerOrderProcessStep(String customerOrderProcessStep) {
this.customerOrderProcessStep = customerOrderProcessStep;
}
public String getExceptionalProcessStep() {
return exceptionalProcessStep;
}
public void setExceptionalProcessStep(String exceptionalProcessStep) {
this.exceptionalProcessStep = exceptionalProcessStep;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String ebayUserId) {
this.customerName = ebayUserId;
}
public String getBuyerFullname() {
return buyerFullname;
}
public void setBuyerFullname(String buyerFullname) {
this.buyerFullname = buyerFullname;
}
public String getBuyerPhoneNumber() {
return buyerPhoneNumber;
}
public void setBuyerPhoneNumber(String buyerPhoneNumber) {
this.buyerPhoneNumber = buyerPhoneNumber;
}
public String getBuyerEmail() {
return buyerEmail;
}
public void setBuyerEmail(String buyerEmail) {
this.buyerEmail = buyerEmail;
}
public String getBuyerAddress1() {
return buyerAddress1;
}
public void setBuyerAddress1(String buyerAddress1) {
this.buyerAddress1 = buyerAddress1;
}
public String getBuyerAddress2() {
return buyerAddress2;
}
public void setBuyerAddress2(String buyerAddress2) {
this.buyerAddress2 = buyerAddress2;
}
public String getBuyerCity() {
return buyerCity;
}
public void setBuyerCity(String buyerCity) {
this.buyerCity = buyerCity;
}
public String getBuyerState() {
return buyerState;
}
public void setBuyerState(String buyerState) {
this.buyerState = buyerState;
}
public String getBuyerZip() {
return buyerZip;
}
public void setBuyerZip(String buyerZip) {
this.buyerZip = buyerZip;
}
public String getBuyerCountry() {
return buyerCountry;
}
public void setBuyerCountry(String buyerCountry) {
this.buyerCountry = buyerCountry;
}
public Timestamp getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(Timestamp modifiedTime) {
this.modifiedTime = modifiedTime;
}
public String getWarehouseCode() {
return warehouseCode;
}
public void setWarehouseCode(String warehouseCode) {
this.warehouseCode = warehouseCode;
}
public Timestamp getShippedTime() {
return shippedTime;
}
public void setShippedTime(Timestamp shippedTime) {
this.shippedTime = shippedTime;
}
public Timestamp getPaidTime() {
return paidTime;
}
public void setPaidTime(Timestamp paidTime) {
this.paidTime = paidTime;
}
public String getSaleChannel() {
return saleChannel;
}
public void setSaleChannel(String saleChannel) {
this.saleChannel = saleChannel;
}
public String getSaleChannelOrderId() {
return saleChannelOrderId;
}
public void setSaleChannelOrderId(String saleChannelOrderId) {
this.saleChannelOrderId = saleChannelOrderId;
}
public String getSaleRecordNo() {
return saleRecordNo;
}
public void setSaleRecordNo(String saleRecordNo) {
this.saleRecordNo = saleRecordNo;
}
public String getShippingForwarderMethod() {
return shippingForwarderMethod;
}
public void setShippingForwarderMethod(String shippingForwarderMethod) {
this.shippingForwarderMethod = shippingForwarderMethod;
}
public String getShippingOrderNo() {
return shippingOrderNo;
}
public void setShippingOrderNo(String shippingOrderNo) {
this.shippingOrderNo = shippingOrderNo;
}
public String getSfmOrderNo() {
return sfmOrderNo;
}
public void setSfmOrderNo(String sfmOrderNo) {
this.sfmOrderNo = sfmOrderNo;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Double getPostageFee() {
return postageFee;
}
public void setPostageFee(Double postageFee) {
this.postageFee = postageFee;
}
public String getStockLocation() {
return stockLocation;
}
public void setStockLocation(String stockLocation) {
this.stockLocation = stockLocation;
}
public String getBuyerCheckoutMessage() {
return buyerCheckoutMessage;
}
public void setBuyerCheckoutMessage(String buyerCheckoutMessage) {
this.buyerCheckoutMessage = buyerCheckoutMessage;
}
public String getShippingServiceSelected() {
return shippingServiceSelected;
}
public void setShippingServiceSelected(String shippingServiceSelected) {
this.shippingServiceSelected = shippingServiceSelected;
}
public String getPackingMaterialArticleNumber() {
return packingMaterialArticleNumber;
}
public void setPackingMaterialArticleNumber(String packingMaterialArticleNumber) {
this.packingMaterialArticleNumber = packingMaterialArticleNumber;
}
public String getPayPalEmailAddress() {
return payPalEmailAddress;
}
public void setPayPalEmailAddress(String payPalEmailAddress) {
this.payPalEmailAddress = payPalEmailAddress;
}
public String getPayPalTransactionId() {
return payPalTransactionId;
}
public void setPayPalTransactionId(String payPalTransactionId) {
this.payPalTransactionId = payPalTransactionId;
}
public Double getTotalAvgPurchasePrice() {
return totalAvgPurchasePrice;
}
public void setTotalAvgPurchasePrice(Double totalAvgPurchasePrice) {
this.totalAvgPurchasePrice = totalAvgPurchasePrice;
}
public Double getTotalWeight() {
return totalWeight;
}
public void setTotalWeight(Double totalWeight) {
this.totalWeight = totalWeight;
}
public Double getTestingShippingCost() {
return testingShippingCost;
}
public void setTestingShippingCost(Double testingShippingCost) {
this.testingShippingCost = testingShippingCost;
}
public String getCustomerOrderProcessStepName() {
return customerOrderProcessStepName;
}
public void setCustomerOrderProcessStepName(String customerOrderProcessStepName) {
this.customerOrderProcessStepName = customerOrderProcessStepName;
}
public String getAllocationProductVoucherNos() {
return allocationProductVoucherNos;
}
public void setAllocationProductVoucherNos(String allocationProductVoucherNos) {
this.allocationProductVoucherNos = allocationProductVoucherNos;
}
} | mit |
JEEventStore/JEEventStore | core/src/main/java/org/jeeventstore/store/EventsIterator.java | 2548 | /*
* Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.jeeventstore.store;
import java.io.Serializable;
import java.util.Iterator;
import org.jeeventstore.ChangeSet;
/**
* An iterator that iterates over all events for multiple {@link ChangeSet}s
* in a proper sequence.
*/
public class EventsIterator<T extends ChangeSet> implements Iterator<Serializable> {
private Iterator<T> cit;
private Iterator<Serializable> it = null;
public EventsIterator(Iterator<T> cit) {
this.cit = cit;
advance();
}
private void advance() {
if (it != null && it.hasNext())
return;
// now either it == null or it has no next
do {
// already reached the last change set?
if (!cit.hasNext()) {
it = null;
return;
}
// no, another changeset is available. Grab it.
ChangeSet nextcs = cit.next();
it = nextcs.events();
} while (!it.hasNext()); // protect against ChangeSets w/o events
}
@Override
public boolean hasNext() {
return it != null;
}
@Override
public Serializable next() {
Serializable n = it.next();
advance();
return n;
}
/**
* {@link #remove()} is not supported.
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
| mit |
KartikKapur/DataStructuresAndAlgorithms | Code/Chapter2/OG.java | 352 | package Chapter2;
/**
* Created by kartikkapur on 6/16/17.
*/
public class OG {
int x;
static int y;
public OG(int x, int y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
OG OG1 = new OG(10, 2);
OG OG2 = new OG(0, 1);
OG1.y = OG2.x;
OG1.x = OG2.y;
}
}
| mit |
ritnorthstar/Minimap-Client | Code/Minimap/src/main/java/com/northstar/minimap/Position.java | 738 | //John Paul Mardelli
//Last updated November 2nd, 2013
package com.northstar.minimap;
import android.graphics.Point;
/**
* Class to represent positions on the map.
*/
public class Position {
private double x;
private double y;
public Position(double x, double y){
this.x = x;
this.y = y;
}
public Position(Point p) {
this.x = p.x;
this.y = p.y;
}
public double distance(Position p) {
return Math.sqrt(Math.pow(p.x - x, 2) + Math.pow(p.y - y, 2));
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public Point toPoint() {
return new Point((int) Math.round(x), (int) Math.round(y));
}
}
| mit |
EricHyh/FileDownloader | VideoSample/src/main/java/com/hyh/video/lib/FitXYMeasurer.java | 436 | package com.hyh.video.lib;
/**
* @author Administrator
* @description
* @data 2019/3/8
*/
public class FitXYMeasurer implements ISurfaceMeasurer {
private final int[] mMeasureSize = new int[2];
@Override
public int[] onMeasure(int defaultWidth, int defaultHeight, int videoWidth, int videoHeight) {
mMeasureSize[0] = defaultWidth;
mMeasureSize[1] = defaultHeight;
return mMeasureSize;
}
} | mit |
cscfa/bartleby | library/logBack/logback-1.1.3/logback-core/src/main/java/ch/qos/logback/core/pattern/color/MagentaCompositeConverter.java | 909 | /**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.core.pattern.color;
/**
* Encloses a given set of converter output in magenta using the appropriate ANSI escape codes.
* @param <E>
* @author Ceki Gülcü
* @since 1.0.5
*/
public class MagentaCompositeConverter<E> extends ForegroundCompositeConverterBase<E> {
@Override
protected String getForegroundColorCode(E event) {
return ANSIConstants.MAGENTA_FG;
}
}
| mit |